CombinedText
stringlengths
8
3.42M
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmessageservice.h" #include "qmessageservice_symbian_p.h" #include "qfsengine_symbian_p.h" #include "qmessage_symbian_p.h" #include "messagingutil_p.h" #include "qmessageaccount.h" #include "qmessageaccount_p.h" #include "qmessageaccountfilter.h" #include "qmessageaccountfilter_p.h" #include "qmessagecontentcontainer_symbian_p.h" #include "qmessagefolder.h" #include "qmessagefolder_p.h" #include "qmessagefolderfilter.h" #include "qmessagefolderfilter_p.h" #include "qmessageaccountsortorder_p.h" #include "qmessagestore_symbian_p.h" #include "qmessagefoldersortorder_p.h" #include "qmessagesortorder_p.h" #include <emailinterfacefactory.h> #include <QTextCodec> #include <emailapidefs.h> #include <memailmailbox.h> #include <memailfolder.h> #include <memailmessage.h> #include <memailaddress.h> #include <memailcontent.h> #include <mmessageiterator.h> using namespace EmailInterface; QTM_BEGIN_NAMESPACE using namespace SymbianHelpers; Q_GLOBAL_STATIC(CFSEngine,fsEngine); CFSEngine::CFSEngine() { TRAPD(err, { m_factory = CEmailInterfaceFactory::NewL(); m_ifPtr = m_factory->InterfaceL(KEmailClientApiInterface); }); Q_UNUSED(err); m_clientApi = static_cast<MEmailClientApi*>(m_ifPtr); #ifdef FREESTYLEMAILBOXOBSERVERUSED TRAPD(err2, setPluginObserversL()); Q_UNUSED(err2); #endif } CFSEngine::~CFSEngine() { m_mtmAccountList.clear(); for ( TInt i = 0; i < m_mailboxes.Count(); i++ ) { m_mailboxes[i]->Release(); } m_mailboxes.Reset(); m_clientApi->Release(); delete m_factory; } CFSEngine* CFSEngine::instance() { return fsEngine(); } bool CFSEngine::accountLessThan(const QMessageAccountId accountId1, const QMessageAccountId accountId2) { CFSEngine* freestyleEngine = fsEngine(); return QMessageAccountSortOrderPrivate::lessThan(freestyleEngine->m_currentAccountOrdering, freestyleEngine->account(accountId1), freestyleEngine->account(accountId2)); } void CFSEngine::orderAccounts(QMessageAccountIdList& accountIds, const QMessageAccountSortOrder &sortOrder) const { Q_UNUSED(accountIds); m_currentAccountOrdering = sortOrder; qSort(accountIds.begin(), accountIds.end(), CFSEngine::accountLessThan); } bool CFSEngine::folderLessThan(const QMessageFolderId folderId1, const QMessageFolderId folderId2) { CFSEngine* freestyleEngine = fsEngine(); return QMessageFolderSortOrderPrivate::lessThan(freestyleEngine->m_currentFolderOrdering, freestyleEngine->folder(folderId1), freestyleEngine->folder(folderId2)); } void CFSEngine::orderFolders(QMessageFolderIdList& folderIds, const QMessageFolderSortOrder &sortOrder) const { m_currentFolderOrdering = sortOrder; qSort(folderIds.begin(), folderIds.end(), CFSEngine::folderLessThan); } bool CFSEngine::messageLessThan(const QMessage& message1, const QMessage& message2) { CFSEngine* freestyleEngine = fsEngine(); return QMessageSortOrderPrivate::lessThan(freestyleEngine->m_currentMessageOrdering, message1, message2); } void CFSEngine::orderMessages(QMessageIdList& messageIds, const QMessageSortOrder &sortOrder) const { m_currentMessageOrdering = sortOrder; QList<QMessage> messages; for (int i=0; i < messageIds.count(); i++) { messages.append(message(messageIds[i])); } qSort(messages.begin(), messages.end(), CFSEngine::messageLessThan); messageIds.clear(); for (int i=0; i < messages.count(); i++) { messageIds.append(messages[i].id()); } } void CFSEngine::setMtmAccountIdList(QMessageAccountIdList accountList) { for (TInt i = 0; i < accountList.count(); i++) { m_mtmAccountList.append(stripIdPrefix(accountList[i])); } } QMessageAccountIdList CFSEngine::queryAccounts(const QMessageAccountFilter &filter, const QMessageAccountSortOrder &sortOrder, uint limit, uint offset) const { QMessageAccountIdList accountIds; TRAPD(err, updateEmailAccountsL()); QMessageAccountFilterPrivate* privateMessageAccountFilter = QMessageAccountFilterPrivate::implementation(filter); if (filter.isEmpty()) { if (!privateMessageAccountFilter->_notFilter) { // All accounts are returned for empty filter foreach (QMessageAccount value, m_accounts) { accountIds.append(value.id()); } } } else { if (privateMessageAccountFilter->_valid) { foreach (QMessageAccount value, m_accounts) { if (privateMessageAccountFilter->filter(value)) { accountIds.append(value.id()); } } } else { foreach (QMessageAccount value, m_accounts) { if (privateMessageAccountFilter->filter(value)) { accountIds.append(value.id()); } } } } if (!sortOrder.isEmpty()) { orderAccounts(accountIds, sortOrder); } applyOffsetAndLimitToAccountIds(accountIds, offset, limit); return accountIds; } void CFSEngine::applyOffsetAndLimitToAccountIds(QMessageAccountIdList& idList, int offset, int limit) const { if (offset > 0) { if (offset > idList.count()) { idList.clear(); } else { for (int i = 0; i < offset; i++) { idList.removeFirst(); } } } if (limit > 0) { for (int i = idList.count()-1; i >= limit; i--) { idList.removeAt(i); } } } int CFSEngine::countAccounts(const QMessageAccountFilter &filter) const { return queryAccounts(filter, QMessageAccountSortOrder(), 0, 0).count(); } QMessageAccount CFSEngine::account(const QMessageAccountId &id) const { TRAPD(err, updateEmailAccountsL()); Q_UNUSED(err) return m_accounts[id.toString()]; } QMessageAccountId CFSEngine::defaultAccount(QMessage::Type type) const { // TODO Q_UNUSED(type); return QMessageAccountId(); } QMessageAccountIdList CFSEngine::accountsByType(QMessage::Type type) const { QMessageAccountIdList accountIds = QMessageAccountIdList(); foreach (QMessageAccount value, m_accounts) { if ((value.messageTypes() & type) == (int)type) { accountIds.append(value.id()); } } return accountIds; } void CFSEngine::updateEmailAccountsL() const { QStringList keys = m_accounts.keys(); RMailboxPtrArray mailboxes; CleanupResetAndRelease<MEmailMailbox>::PushL(mailboxes); m_clientApi->GetMailboxesL(mailboxes); for (TInt i = 0; i < mailboxes.Count(); i++) { MEmailMailbox *mailbox = mailboxes[i]; QString idAsString = QString::number(mailbox->MailboxId().iId); QString fsIdAsString = addIdPrefix(idAsString, SymbianHelpers::EngineTypeFreestyle); TBool overlap = false; for (TInt j = 0; j < m_mtmAccountList.count(); j++) { if (idAsString == m_mtmAccountList[j].toString()) overlap = true; } if (!m_accounts.contains(fsIdAsString) && !overlap) { QMessageAccount account = QMessageAccountPrivate::from( QMessageAccountId(fsIdAsString), QString::fromUtf16(mailbox->MailboxName().Ptr(), mailbox->MailboxName().Length()), 0, 0, QMessage::Email); m_accounts.insert(fsIdAsString, account); } else { keys.removeOne(fsIdAsString); } mailbox->Release(); } mailboxes.Reset(); CleanupStack::PopAndDestroy(); for (int i=0; i < keys.count(); i++) { m_accounts.remove(keys[i]); } } #ifdef FREESTYLEMAILBOXOBSERVERUSED void CFSEngine::setPluginObserversL() { m_clientApi->GetMailboxesL(m_mailboxes); for (TInt i = 0; i < m_mailboxes.Count(); i++) { MEmailMailbox *mailbox = m_mailboxes[i]; mailbox->RegisterObserverL(*this); } } void CFSEngine::NewMessageEventL(const TMailboxId& aMailbox, const REmailMessageIdArray aNewMessages, const TFolderId& aParentFolderId) { QMessageManager::NotificationFilterIdSet matchingFilters; QMessageStorePrivate::NotificationType notificationType = QMessageStorePrivate::Added; for (TInt i = 0; i < aNewMessages.Count(); i++) { TMessageId messageId(aNewMessages[i]); notificationL(aMailbox, messageId, aParentFolderId, notificationType); } } void CFSEngine::MessageChangedEventL(const TMailboxId& aMailbox, const REmailMessageIdArray aChangedMessages, const TFolderId& aParentFolderId) { QMessageManager::NotificationFilterIdSet matchingFilters; QMessageStorePrivate::NotificationType notificationType = QMessageStorePrivate::Updated; for (TInt i = 0; i < aChangedMessages.Count(); i++) { TMessageId messageId(aChangedMessages[i]); notificationL(aMailbox, messageId, aParentFolderId, notificationType); } } void CFSEngine::MessageDeletedEventL(const TMailboxId& aMailbox, const REmailMessageIdArray aDeletedMessages, const TFolderId& aParentFolderId) { // TODO: add filter handling QMessageManager::NotificationFilterIdSet matchingFilters; QMap<int, QMessageFilter> filters(m_filters); QMap<int, QMessageFilter>::const_iterator it = filters.begin(), end = filters.end(); QMessageStorePrivate::NotificationType notificationType = QMessageStorePrivate::Removed; MEmailMailbox* mailbox = m_clientApi->MailboxL(aMailbox); MEmailFolder* folder = mailbox->FolderL(aParentFolderId); QString idAsString = QString::number(mailbox->MailboxId().iId); for (TInt j = 0; j < m_mtmAccountList.count(); j++) { if (idAsString == m_mtmAccountList[j].toString()) return; } for (TInt i = 0; i < aDeletedMessages.Count(); i++) { for ( ; it != end; ++it) { // Empty filter matches to all messages matchingFilters.insert(it.key()); } TMessageId messageId(aDeletedMessages[i]); ipMessageStorePrivate->messageNotification(notificationType, QMessageId(addIdPrefix(QString::number(messageId.iId), SymbianHelpers::EngineTypeFreestyle)), matchingFilters); } folder->Release(); mailbox->Release(); } void CFSEngine::notificationL(const TMailboxId& aMailbox, const TMessageId& aMessageId, const TFolderId& aParentFolderId, QMessageStorePrivate::NotificationType aNotificationType) { QMessageManager::NotificationFilterIdSet matchingFilters; // Copy the filter map to protect against modification during traversal QMap<int, QMessageFilter> filters(m_filters); QMap<int, QMessageFilter>::const_iterator it = filters.begin(), end = filters.end(); QMessage message; QMessageId realMessageId = QMessageId(addIdPrefix(QString::number(aMessageId.iId), SymbianHelpers::EngineTypeFreestyle)); bool messageRetrieved = false; MEmailMailbox* mailbox = m_clientApi->MailboxL(aMailbox); CleanupReleasePushL(*mailbox); QString idAsString = QString::number(mailbox->MailboxId().iId); for (TInt j = 0; j < m_mtmAccountList.count(); j++) { if (idAsString == m_mtmAccountList[j].toString()) { CleanupStack::Pop(mailbox); return; } } for ( ; it != end; ++it) { const QMessageFilter &filter(it.value()); if (!messageRetrieved) { MEmailMessage* fsMessage = mailbox->MessageL(aMessageId); CleanupReleasePushL(*fsMessage); if (!fsMessage) { CleanupStack::Pop(fsMessage); CleanupStack::Pop(mailbox); return; } message = CreateQMessageL(fsMessage); messageRetrieved = true; CleanupStack::Pop(fsMessage); } if (filter.isEmpty()) { // Empty filter matches to all messages matchingFilters.insert(it.key()); } else { if (message.type() == QMessage::NoType) { matchingFilters.clear(); continue; } } QMessageFilterPrivate* privateMessageFilter = QMessageFilterPrivate::implementation(filter); if (privateMessageFilter->filter(message)) { matchingFilters.insert(it.key()); } } int c = matchingFilters.count(); QString id = realMessageId.toString(); if (matchingFilters.count() > 0) ipMessageStorePrivate->messageNotification(aNotificationType, realMessageId, matchingFilters); CleanupStack::Pop(mailbox); } #endif MEmailMessage* CFSEngine::createFSMessageL(const QMessage &message, const MEmailMailbox* mailbox) { MEmailMessage* fsMessage = mailbox->CreateDraftMessageL(); CleanupReleasePushL(*fsMessage); switch (message.priority()) { case QMessage::HighPriority: fsMessage->SetFlag(EmailInterface::EFlag_Important); fsMessage->ResetFlag(EmailInterface::EFlag_Low); break; case QMessage::NormalPriority: fsMessage->ResetFlag(EmailInterface::EFlag_Important); fsMessage->ResetFlag(EmailInterface::EFlag_Low); break; case QMessage::LowPriority: fsMessage->SetFlag(EmailInterface::EFlag_Low); fsMessage->ResetFlag(EmailInterface::EFlag_Important); break; } if (message.status() & QMessage::Read) { fsMessage->SetFlag(EmailInterface::EFlag_Read); } else { fsMessage->ResetFlag(EmailInterface::EFlag_Read); } MEmailAddress* sender = mailbox->AddressL(); sender->SetRole(MEmailAddress::ESender); fsMessage->SetReplyToAddressL(*sender); QList<QMessageAddress> toList(message.to()); if (toList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray toAddress; for (int i = 0; i < toList.size(); ++i) { qreceiver = toList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL(); address->SetAddressL(receiver); address->SetDisplayNameL(receiver); address->SetRole(MEmailAddress::ETo); toAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::ETo, toAddress); } QList<QMessageAddress> ccList(message.cc()); if (ccList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray ccAddress; for (int i = 0; i < ccList.size(); ++i) { qreceiver = ccList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL(); address->SetDisplayNameL(receiver); address->SetRole(MEmailAddress::ECc); address->SetAddressL(receiver); ccAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::ECc, ccAddress); } QList<QMessageAddress> bccList(message.bcc()); if (bccList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray bccAddress; for (int i = 0; i < bccList.size(); ++i) { qreceiver = bccList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL(); address->SetDisplayNameL(receiver); address->SetRole(MEmailAddress::EBcc); address->SetAddressL(receiver); bccAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::EBcc, bccAddress); } if (message.bodyId() == QMessageContentContainerPrivate::bodyContentId()) { // Message contains only body (not attachments) QString messageBody = message.textContent(); if (!messageBody.isEmpty()) { QByteArray type = message.contentType(); QByteArray subType = message.contentSubType(); MEmailMessageContent* content = fsMessage->ContentL(); MEmailTextContent* textContent = content->AsTextContentOrNull(); if (textContent) { if (type == "text" && subType == "plain") { textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(message.textContent().utf16()))); } else if (type == "text" && subType == "html") { textContent->SetTextL(MEmailTextContent::EHtmlText, TPtrC(reinterpret_cast<const TUint16*>(message.textContent().utf16()))); } } else fsMessage->SetPlainTextBodyL(TPtrC(reinterpret_cast<const TUint16*>(message.textContent().utf16()))); } } else { // Message contains body and attachments QMessageContentContainerIdList contentIds = message.contentIds(); foreach (QMessageContentContainerId id, contentIds){ QMessageContentContainer container = message.find(id); MEmailMessageContent* content = fsMessage->ContentL(); QMessageContentContainerPrivate* pPrivateContainer = QMessageContentContainerPrivate::implementation(container); if (pPrivateContainer->_id == message.bodyId()) { // ContentContainer is body if (!container.textContent().isEmpty()) { MEmailTextContent* textContent = content->AsTextContentOrNull(); if (textContent) { QByteArray type = container.contentType(); QByteArray subType = container.contentSubType(); if (type == "text" && subType == "plain") { textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16()))); } else if (type == "text" && subType == "html") { textContent->SetTextL(MEmailTextContent::EHtmlText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16()))); } } else fsMessage->SetPlainTextBodyL(TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16()))); } } else { // ContentContainer is attachment QByteArray filePath = QMessageContentContainerPrivate::attachmentFilename(container); // Replace Qt style path separator "/" with Symbian path separator "\" filePath.replace(QByteArray("/"), QByteArray("\\")); QString temp_path = QString(filePath); TPtrC16 attachmentPath(KNullDesC); attachmentPath.Set(reinterpret_cast<const TUint16*>(temp_path.utf16())); fsMessage->AddAttachmentL(attachmentPath); } } } fsMessage->SetSubjectL(TPtrC(reinterpret_cast<const TUint16*>(message.subject().utf16()))); QMessagePrivate* privateMessage = QMessagePrivate::implementation(message); privateMessage->_id = QMessageId(addIdPrefix(QString::number(fsMessage->MessageId().iId),SymbianHelpers::EngineTypeFreestyle)); fsMessage->SaveChangesL(); CleanupStack::Pop(fsMessage); return fsMessage; } bool CFSEngine::addMessage(QMessage* message) { TMailboxId mailboxId(stripIdPrefix(message->parentAccountId().toString()).toInt()); MEmailMailbox* mailbox; TRAPD(mailerr, mailbox = m_clientApi->MailboxL(mailboxId)); if (mailerr != KErrNone) return false; MEmailMessage* fsMessage = NULL; TRAPD(err, fsMessage = createFSMessageL(*message, mailbox)); if (fsMessage) fsMessage->Release(); if (mailbox) mailbox->Release(); if (err != KErrNone) return false; else return true; } bool CFSEngine::updateMessage(QMessage* message) { TRAPD(err, updateMessageL(message)); if (err != KErrNone) return false; else return true; } void CFSEngine::updateMessageL(QMessage* message) { TMailboxId mailboxId(stripIdPrefix(message->parentAccountId().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); CleanupReleasePushL(*mailbox); TMessageId messageId(message->id().toString().toInt(), message->parentFolderId().toString().toInt(), mailboxId); MEmailMessage* fsMessage = mailbox->MessageL(messageId); CleanupReleasePushL(*fsMessage); switch (message->priority()) { case QMessage::HighPriority: fsMessage->SetFlag(EmailInterface::EFlag_Important); fsMessage->ResetFlag(EmailInterface::EFlag_Low); break; case QMessage::NormalPriority: fsMessage->ResetFlag(EmailInterface::EFlag_Important); fsMessage->ResetFlag(EmailInterface::EFlag_Low); break; case QMessage::LowPriority: fsMessage->SetFlag(EmailInterface::EFlag_Low); fsMessage->ResetFlag(EmailInterface::EFlag_Important); break; } if (message->status() & QMessage::Read) { fsMessage->SetFlag(EmailInterface::EFlag_Read); } else { fsMessage->ResetFlag(EmailInterface::EFlag_Read); } MEmailAddress* sender = mailbox->AddressL(); sender->SetRole(MEmailAddress::ESender); fsMessage->SetReplyToAddressL(*sender); QList<QMessageAddress> toList(message->to()); if (toList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray toAddress; for (int i = 0; i < toList.size(); ++i) { qreceiver = toList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL(); address->SetAddressL(receiver); toAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::ETo, toAddress); } QList<QMessageAddress> ccList(message->cc()); if (ccList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray ccAddress; for (int i = 0; i < ccList.size(); ++i) { qreceiver = ccList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL();; address->SetAddressL(receiver); ccAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::ECc, ccAddress); } QList<QMessageAddress> bccList(message->bcc()); if (bccList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray bccAddress; for (int i = 0; i < bccList.size(); ++i) { qreceiver = bccList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL();; address->SetAddressL(receiver); bccAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::EBcc, bccAddress); } if (message->bodyId() == QMessageContentContainerPrivate::bodyContentId()) { // Message contains only body (not attachments) QString messageBody = message->textContent(); if (!messageBody.isEmpty()) { MEmailMessageContent* content = fsMessage->ContentL(); MEmailTextContent* textContent = content->AsTextContentOrNull(); textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(message->textContent().utf16()))); // TODO: } } else { // Message contains body and attachments QMessageContentContainerIdList contentIds = message->contentIds(); foreach (QMessageContentContainerId id, contentIds){ QMessageContentContainer container = message->find(id); QMessageContentContainerPrivate* pPrivateContainer = QMessageContentContainerPrivate::implementation(container); if (pPrivateContainer->_id == message->bodyId()) { // ContentContainer is body if (!container.textContent().isEmpty()) { MEmailMessageContent* content = fsMessage->ContentL(); MEmailTextContent* textContent = content->AsTextContentOrNull(); QByteArray type = container.contentType(); QByteArray subType = container.contentSubType(); if (type == "text" && subType == "plain") { textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16()))); } else if (type == "text" && subType == "html") { textContent->SetTextL(MEmailTextContent::EHtmlText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16()))); } } } else { // ContentContainer is attachment QByteArray filePath = QMessageContentContainerPrivate::attachmentFilename(container); // Replace Qt style path separator "/" with Symbian path separator "\" filePath.replace(QByteArray("/"), QByteArray("\\")); QString temp_path = QString(filePath); TPtrC16 attachmentPath(KNullDesC); attachmentPath.Set(reinterpret_cast<const TUint16*>(temp_path.utf16())); fsMessage->AddAttachmentL(attachmentPath); } } } fsMessage->SetSubjectL(TPtrC(reinterpret_cast<const TUint16*>(message->subject().utf16()))); fsMessage->SaveChangesL(); CleanupStack::PopAndDestroy(fsMessage); CleanupStack::PopAndDestroy(mailbox); } bool CFSEngine::removeMessage(const QMessageId &id, QMessageManager::RemovalOption option) { Q_UNUSED(option); bool retVal = false; foreach (QMessageAccount account, m_accounts) { MEmailMessage* message = NULL; TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); TMessageId messageId( stripIdPrefix(id.toString()).toInt(), 0, mailboxId); TRAPD(err, message = mailbox->MessageL(messageId)); if (err == KErrNone) { TFolderId folderId(message->ParentFolderId()); TRAPD(err2, MEmailFolder* folder = mailbox->FolderL(folderId); REmailMessageIdArray messageIds; messageIds.Append(message->MessageId()); folder->DeleteMessagesL(messageIds); folder->Release(); ); if (err2 == KErrNone) retVal = true; mailbox->Release(); break; // no need to continue } mailbox->Release(); } return retVal; } bool CFSEngine::showMessage(const QMessageId &id) { MEmailMessage* message = NULL; bool retVal = false; foreach (QMessageAccount account, m_accounts) { MEmailMessage* message = NULL; TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); TMessageId messageId( stripIdPrefix(id.toString()).toInt(), 0, mailboxId); TRAPD(err, message = mailbox->MessageL(messageId)); if (err == KErrNone) { TRAPD(err2, message->ShowMessageViewerL()); if (err2 == KErrNone) retVal = true; message->Release(); mailbox->Release(); break; // no need to continue } mailbox->Release(); } return retVal; } bool CFSEngine::composeMessage(const QMessage &message) { bool retVal = false; MEmailMailbox* mailbox; TMailboxId mailboxId(stripIdPrefix(message.parentAccountId().toString()).toInt()); TRAPD(err, mailbox = m_clientApi->MailboxL(mailboxId)); if (err == KErrNone) { TRAPD(err2, mailbox->EditNewMessageL()); if (err2 == KErrNone) retVal = true; mailbox->Release(); } return retVal; } bool CFSEngine::retrieve(const QMessageId &messageId, const QMessageContentContainerId& id) { Q_UNUSED(id); bool retVal = false; foreach (QMessageAccount account, m_accounts) { MEmailMessage* message = NULL; TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); TMessageId mId( stripIdPrefix(messageId.toString()).toInt(), 0, mailboxId); TRAPD(err, message = mailbox->MessageL(mId)); if (err == KErrNone) { MEmailMessageContent* content; TRAPD(contentError, content = message->ContentL()); if (contentError == KErrNone) { MEmailMultipart* mPart = content->AsMultipartOrNull(); for ( int i = 0; i < mPart->PartCountL(); i++) { MEmailAttachment* attContent; TRAPD(attContentErr, attContent = mPart->PartByIndexL(i)->AsAttachmentOrNull()); if (attContent && attContentErr == KErrNone) { TInt availableSize = attContent->AvailableSize(); if (!availableSize) { TRAPD(attErr, attContent->FetchL(*this)); if (attErr == KErrNone) { retVal = true; } } } } } message->Release(); mailbox->Release(); break; // no need to continue } mailbox->Release(); } return retVal; } bool CFSEngine::retrieveBody(const QMessageId& id) { bool retVal = false; foreach (QMessageAccount account, m_accounts) { MEmailMessage* message = NULL; TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); MEmailMailbox* mailbox; TRAPD(mailBoxError, mailbox = m_clientApi->MailboxL(mailboxId)); if (mailBoxError == KErrNone) { TMessageId messageId( stripIdPrefix(id.toString()).toInt(), 0, mailboxId); TRAPD(err, message = mailbox->MessageL(messageId)); if (err == KErrNone) { MEmailMessageContent* content; TRAPD(contentError, content = message->ContentL()); if (contentError == KErrNone) { MEmailTextContent* textContent = content->AsTextContentOrNull(); if (textContent) { TInt availableSize = textContent->AvailableSize(); if (!availableSize) { TRAPD(textErr, textContent->FetchL(*this)); if (textErr == KErrNone) { retVal = true; } } } } message->Release(); mailbox->Release(); break; // no need to continue } mailbox->Release(); } } return retVal; } bool CFSEngine::retrieveHeader(const QMessageId& id) { Q_UNUSED(id); return false; } void CFSEngine::DataFetchedL(const TInt aResult) { Q_UNUSED(aResult); } bool CFSEngine::exportUpdates(const QMessageAccountId &id) { TRAPD(err, exportUpdatesL(id)); if (err != KErrNone) { return false; } else { return true; } } void CFSEngine::exportUpdatesL(const QMessageAccountId &id) { TMailboxId mailboxId(stripIdPrefix(id.toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); mailbox->SynchroniseL(*this); mailbox->Release(); } void CFSEngine::MailboxSynchronisedL(TInt aResult) { Q_UNUSED(aResult); } bool CFSEngine::removeMessages(const QMessageFilter& /*filter*/, QMessageManager::RemovalOption /*option*/) { return false; } void CFSEngine::handleNestedFiltersFromMessageFilter(QMessageFilter &filter) const { QMessageFilterPrivate* pMFFilter = QMessageFilterPrivate::implementation(filter); if (pMFFilter->_filterList.count() > 0) { int filterListCount = pMFFilter->_filterList.count(); for (int i=0; i < filterListCount; i++) { for (int j=0; j < pMFFilter->_filterList[i].count(); j++) { QMessageFilterPrivate* pMFFilter2 = QMessageFilterPrivate::implementation(pMFFilter->_filterList[i][j]); if (pMFFilter2->_field == QMessageFilterPrivate::ParentAccountIdFilter) { QMessageAccountIdList accountIds = queryAccounts(*pMFFilter2->_accountFilter, QMessageAccountSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue)); if (accountIds.count() > 0) { pMFFilter->_filterList[i].removeAt(j); if (cmp == QMessageDataComparator::Includes) { for (int x = 0; x < accountIds.count(); x++) { if (x == 0) { if (x+1 < accountIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[i]); } pMFFilter->_filterList[i].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } else { if (x+1 < accountIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]); pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFilterPrivate::lessThan); } else { pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFilterPrivate::lessThan); } } } } else { // Excludes for (int x = 0; x < accountIds.count(); x++) { pMFFilter->_filterList[i].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::NotEqual)); } qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else { delete pMFFilter2->_accountFilter; pMFFilter2->_accountFilter = 0; pMFFilter2->_field = QMessageFilterPrivate::Id; qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else if (pMFFilter2->_field == QMessageFilterPrivate::ParentFolderIdFilter) { QMessageFolderIdList folderIds = queryFolders(*pMFFilter2->_folderFilter, QMessageFolderSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue)); if (folderIds.count() > 0) { pMFFilter->_filterList[i].removeAt(j); if (cmp == QMessageDataComparator::Includes) { for (int x = 0; x < folderIds.count(); x++) { if (x == 0) { if (x+1 < folderIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[i]); } pMFFilter->_filterList[i].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } else { if (x+1 < folderIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]); pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFilterPrivate::lessThan); } else { pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFilterPrivate::lessThan); } } } } else { // Excludes for (int x = 0; x < folderIds.count(); x++) { pMFFilter->_filterList[i].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::NotEqual)); } qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else { delete pMFFilter2->_folderFilter; pMFFilter2->_folderFilter = 0; pMFFilter2->_field = QMessageFilterPrivate::Id; qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else { break; } } } } else { if (pMFFilter->_field == QMessageFilterPrivate::ParentAccountIdFilter) { QMessageAccountIdList accountIds = queryAccounts(*pMFFilter->_accountFilter, QMessageAccountSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue)); if (accountIds.count() > 0) { for (int i=0; i < accountIds.count(); i++) { if (i == 0) { delete pMFFilter->_accountFilter; pMFFilter->_accountFilter = 0; pMFFilter->_field = QMessageFilterPrivate::ParentAccountId; pMFFilter->_value = accountIds[0].toString(); pMFFilter->_comparatorType = QMessageFilterPrivate::Equality; if (cmp == QMessageDataComparator::Includes) { pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal); } else { // Excludes pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual); } } else { if (cmp == QMessageDataComparator::Includes) { filter |= QMessageFilter::byParentAccountId(accountIds[i],QMessageDataComparator::Equal); } else { // Excludes filter &= QMessageFilter::byParentAccountId(accountIds[i],QMessageDataComparator::NotEqual); } } } } else { delete pMFFilter->_accountFilter; pMFFilter->_accountFilter = 0; pMFFilter->_field = QMessageFilterPrivate::Id; } } else if (pMFFilter->_field == QMessageFilterPrivate::ParentFolderIdFilter) { QMessageFolderIdList folderIds = queryFolders(*pMFFilter->_folderFilter, QMessageFolderSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue)); if (folderIds.count() > 0) { for (int i=0; i < folderIds.count(); i++) { if (i == 0) { delete pMFFilter->_folderFilter; pMFFilter->_folderFilter = 0; pMFFilter->_field = QMessageFilterPrivate::ParentFolderId; pMFFilter->_value = folderIds[0].toString(); pMFFilter->_comparatorType = QMessageFilterPrivate::Equality; if (cmp == QMessageDataComparator::Includes) { pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal); } else { // Excludes pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual); } } else { if (cmp == QMessageDataComparator::Includes) { filter |= QMessageFilter::byParentFolderId(folderIds[i],QMessageDataComparator::Equal); } else { // Excludes filter &= QMessageFilter::byParentFolderId(folderIds[i],QMessageDataComparator::NotEqual); } } } } else { delete pMFFilter->_folderFilter; pMFFilter->_folderFilter = 0; pMFFilter->_field = QMessageFilterPrivate::Id; } } } } bool CFSEngine::queryMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { TRAPD(err, queryMessagesL(privateService, filter, sortOrder, limit, offset)); if (err != KErrNone) { return false; } return true; } void CFSEngine::queryMessagesL(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { FSMessageQueryInfo queryInfo; queryInfo.operationId = ++m_operationIds; if (queryInfo.operationId == 100000) { queryInfo.operationId = 1; } queryInfo.isQuery = true; queryInfo.filter = filter; queryInfo.sortOrder = sortOrder; queryInfo.offset = offset; queryInfo.limit = limit; queryInfo.findOperation = new CFSMessagesFindOperation((CFSEngine&)*this, queryInfo.operationId); queryInfo.privateService = &privateService; queryInfo.currentFilterListIndex = 0; m_messageQueries.append(queryInfo); handleNestedFiltersFromMessageFilter(m_messageQueries[m_messageQueries.count()-1].filter); QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(m_messageQueries[m_messageQueries.count()-1].filter); if (pf->_filterList.count() == 0) { queryInfo.findOperation->filterAndOrderMessages(m_messageQueries[m_messageQueries.count()-1].filter, m_messageQueries[m_messageQueries.count()-1].sortOrder); } else { queryInfo.findOperation->filterAndOrderMessages(pf->_filterList[0], m_messageQueries[m_messageQueries.count()-1].sortOrder); } } bool CFSEngine::queryMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { TRAPD(err, queryMessagesL(privateService, filter, body, matchFlags, sortOrder, limit, offset)); if (err != KErrNone) { return false; } return true; } void CFSEngine::queryMessagesL(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { FSMessageQueryInfo queryInfo; queryInfo.operationId = ++m_operationIds; if (queryInfo.operationId == 100000) { queryInfo.operationId = 1; } queryInfo.isQuery = true; queryInfo.body = body; queryInfo.matchFlags = matchFlags; queryInfo.filter = filter; queryInfo.sortOrder = sortOrder; queryInfo.offset = offset; queryInfo.limit = limit; queryInfo.findOperation = new CFSMessagesFindOperation((CFSEngine&)*this, queryInfo.operationId); queryInfo.privateService = &privateService; queryInfo.currentFilterListIndex = 0; m_messageQueries.append(queryInfo); handleNestedFiltersFromMessageFilter(m_messageQueries[m_messageQueries.count()-1].filter); QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(m_messageQueries[m_messageQueries.count()-1].filter); if (pf->_filterList.count() == 0) { queryInfo.findOperation->filterAndOrderMessages(m_messageQueries[m_messageQueries.count()-1].filter, m_messageQueries[m_messageQueries.count()-1].sortOrder, body, matchFlags); } else { queryInfo.findOperation->filterAndOrderMessages(pf->_filterList[0], m_messageQueries[m_messageQueries.count()-1].sortOrder, body, matchFlags); } } bool CFSEngine::countMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter) { TRAPD(err, countMessagesL(privateService, filter)); if (err != KErrNone) { return false; } return true; } void CFSEngine::countMessagesL(QMessageServicePrivate& privateService, const QMessageFilter &filter) { FSMessageQueryInfo queryInfo; queryInfo.operationId = ++m_operationIds; if (queryInfo.operationId == 100000) { queryInfo.operationId = 1; } queryInfo.isQuery = false; queryInfo.matchFlags = 0; queryInfo.filter = filter; queryInfo.sortOrder = QMessageSortOrder(); queryInfo.offset = 0; queryInfo.limit = 0; queryInfo.findOperation = new CFSMessagesFindOperation((CFSEngine&)*this, queryInfo.operationId); queryInfo.privateService = &privateService; queryInfo.currentFilterListIndex = 0; queryInfo.count = 0; m_messageQueries.append(queryInfo); handleNestedFiltersFromMessageFilter(m_messageQueries[m_messageQueries.count()-1].filter); QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(m_messageQueries[m_messageQueries.count()-1].filter); if (pf->_filterList.count() == 0) { queryInfo.findOperation->filterAndOrderMessages(m_messageQueries[m_messageQueries.count()-1].filter, m_messageQueries[m_messageQueries.count()-1].sortOrder); } else { queryInfo.findOperation->filterAndOrderMessages(pf->_filterList[0], m_messageQueries[m_messageQueries.count()-1].sortOrder); } } void CFSEngine::filterAndOrderMessagesReady(bool success, int operationId, QMessageIdList ids, int numberOfHandledFilters, bool resultSetOrdered) { int index=0; for (; index < m_messageQueries.count(); index++) { if (m_messageQueries[index].operationId == operationId) { break; } } if (success) { // If there are unhandled filters, loop through all filters and do filtering for ids using unhandled filters. QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(m_messageQueries[index].filter); if (pf->_filterList.count() > 0) { if (pf->_filterList[m_messageQueries[index].currentFilterListIndex].count() > numberOfHandledFilters) { for (int i=0; i < ids.count(); i++) { QMessage msg = message(ids[i]); for (int j=numberOfHandledFilters; j < pf->_filterList[m_messageQueries[index].currentFilterListIndex].count(); j++) { QMessageFilterPrivate* pf2 = QMessageFilterPrivate::implementation(pf->_filterList[m_messageQueries[index].currentFilterListIndex][j]); if (!pf2->filter(msg)) { ids.removeAt(i); i--; break; } } } } } if (pf->_filterList.count() > 0) { // Filter contains filterlist (or filterlists), not just one single filter if (m_messageQueries[index].currentFilterListIndex == 0) { m_messageQueries[index].ids << ids; m_messageQueries[index].count = ids.count(); } else { // Append new ids to resultset for (int i=0; i < ids.count(); i++) { if (!m_messageQueries[index].ids.contains(ids[i])) { m_messageQueries[index].ids.append(ids[i]); m_messageQueries[index].count++;; } } } m_messageQueries[index].currentFilterListIndex++; if (m_messageQueries[index].currentFilterListIndex < pf->_filterList.count()) { // There are still unhandled filter lists left m_messageQueries[index].findOperation->filterAndOrderMessages(pf->_filterList[m_messageQueries[index].currentFilterListIndex], m_messageQueries[index].sortOrder, m_messageQueries[index].body, m_messageQueries[index].matchFlags); return; } else { // All filters successfully handled if (m_messageQueries[index].isQuery) { if (!m_messageQueries[index].sortOrder.isEmpty()) { // Make sure that messages are correctly ordered orderMessages(m_messageQueries[index].ids, m_messageQueries[index].sortOrder); } applyOffsetAndLimitToMsgIds(m_messageQueries[index].ids, m_messageQueries[index].offset, m_messageQueries[index].limit); m_messageQueries[index].privateService->messagesFound(m_messageQueries[index].ids, true, true); //emit m_messageQueries[index].privateService->messagesFound(m_messageQueries[index].ids); } else { m_messageQueries[index].privateService->messagesCounted(m_messageQueries[index].count); } } } else { // There was only one single filter to handle if (numberOfHandledFilters == 0) { // The one and only filter was not handled // => Do filtering for all returned messages for (int i=ids.count()-1; i >= 0; i--) { QMessage msg = message(ids[i]); if (!pf->filter(msg)) { ids.removeAt(i); } } } // => All filters successfully handled if (m_messageQueries[index].isQuery) { // Make sure that messages are correctly ordered if (!m_messageQueries[index].sortOrder.isEmpty() && !resultSetOrdered) { orderMessages(ids, m_messageQueries[index].sortOrder); } // Handle offest & limit applyOffsetAndLimitToMsgIds(ids, m_messageQueries[index].offset, m_messageQueries[index].limit); //emit m_messageQueries[index].privateService->messagesFound(ids); m_messageQueries[index].privateService->messagesFound(ids, true, true); } else { m_messageQueries[index].privateService->messagesCounted(ids.count()); } } } else { m_messageQueries[index].privateService->_active = false; if (m_messageQueries[index].privateService->_error == QMessageManager::NoError) { m_messageQueries[index].privateService->_error = QMessageManager::RequestIncomplete; } } delete m_messageQueries[index].findOperation; m_messageQueries.removeAt(index); } void CFSEngine::applyOffsetAndLimitToMsgIds(QMessageIdList& idList, int offset, int limit) const { if (offset > 0) { if (offset > idList.count()) { idList.clear(); } else { for (int i = 0; i < offset; i++) { idList.removeFirst(); } } } if (limit > 0) { for (int i = idList.count()-1; i >= limit; i--) { idList.removeAt(i); } } } QMessageManager::NotificationFilterId CFSEngine::registerNotificationFilter(QMessageStorePrivate& aPrivateStore, const QMessageFilter &filter, QMessageManager::NotificationFilterId aId) { ipMessageStorePrivate = &aPrivateStore; iListenForNotifications = true; int filterId = aId; if (filterId == 0) filterId = ++m_filterId; m_filters.insert(filterId, filter); return filterId; } void CFSEngine::unregisterNotificationFilter(QMessageManager::NotificationFilterId notificationFilterId) { m_filters.remove(notificationFilterId); if (m_filters.count() == 0) { iListenForNotifications = false; } } void CFSEngine::handleNestedFiltersFromFolderFilter(QMessageFolderFilter &filter) const { QMessageFolderFilterPrivate* pMFFilter = QMessageFolderFilterPrivate::implementation(filter); if (pMFFilter->_filterList.count() > 0) { int filterListCount = pMFFilter->_filterList.count(); for (int i=0; i < filterListCount; i++) { for (int j=0; j < pMFFilter->_filterList[i].count(); j++) { QMessageFolderFilterPrivate* pMFFilter2 = QMessageFolderFilterPrivate::implementation(pMFFilter->_filterList[i][j]); if (pMFFilter2->_field == QMessageFolderFilterPrivate::ParentAccountIdFilter) { QMessageAccountIdList accountIds = queryAccounts(*pMFFilter2->_accountFilter, QMessageAccountSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue)); if (accountIds.count() > 0) { pMFFilter->_filterList[i].removeAt(j); if (cmp == QMessageDataComparator::Includes) { for (int x = 0; x < accountIds.count(); x++) { if (x == 0) { if (x+1 < accountIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[i]); } pMFFilter->_filterList[i].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFolderFilterPrivate::lessThan); } else { if (x+1 < accountIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]); pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFolderFilterPrivate::lessThan); } else { pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFolderFilterPrivate::lessThan); } } } } else { // Excludes for (int x = 0; x < accountIds.count(); x++) { pMFFilter->_filterList[i].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::NotEqual)); } qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFolderFilterPrivate::lessThan); } } else { delete pMFFilter2->_accountFilter; pMFFilter2->_accountFilter = 0; pMFFilter2->_field = QMessageFolderFilterPrivate::Id; qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFolderFilterPrivate::lessThan); } } else { break; } } } } else { if (pMFFilter->_field == QMessageFolderFilterPrivate::ParentAccountIdFilter) { QMessageAccountIdList accountIds = queryAccounts(*pMFFilter->_accountFilter, QMessageAccountSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue)); if (accountIds.count() > 0) { for (int i=0; i < accountIds.count(); i++) { if (i == 0) { delete pMFFilter->_accountFilter; pMFFilter->_accountFilter = 0; pMFFilter->_field = QMessageFolderFilterPrivate::ParentAccountId; pMFFilter->_value = accountIds[0].toString(); pMFFilter->_comparatorType = QMessageFolderFilterPrivate::Equality; if (cmp == QMessageDataComparator::Includes) { pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal); } else { // Excludes pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual); } } else { if (cmp == QMessageDataComparator::Includes) { filter |= QMessageFolderFilter::byParentAccountId(accountIds[i],QMessageDataComparator::Equal); } else { // Excludes filter &= QMessageFolderFilter::byParentAccountId(accountIds[i],QMessageDataComparator::NotEqual); } } } } else { delete pMFFilter->_accountFilter; pMFFilter->_accountFilter = 0; pMFFilter->_field = QMessageFolderFilterPrivate::Id; } } } } QMessageFolderIdList CFSEngine::queryFolders(const QMessageFolderFilter &filter, const QMessageFolderSortOrder &sortOrder, uint limit, uint offset) const { QMessageFolderIdList ids; QMessageFolderFilter copyOfFilter = filter; handleNestedFiltersFromFolderFilter(copyOfFilter); QMessageFolderFilterPrivate* pMFFilter = QMessageFolderFilterPrivate::implementation(copyOfFilter); if (pMFFilter->_filterList.count() > 0) { for (int i=0; i < pMFFilter->_filterList.count(); i++) { bool filterHandled; QMessageFolderIdList ids2 = filterMessageFolders(pMFFilter->_filterList[i][0], filterHandled); for (int x=ids2.count()-1; x >= 0; x--) { QMessageFolder mf = folder(ids2[x]); int j = filterHandled ? 1 : 0; for (; j < pMFFilter->_filterList[i].count(); j++) { if (!QMessageFolderFilterPrivate::implementation(pMFFilter->_filterList[i][j])->filter(mf)) { ids2.removeAt(x); break; } } } for (int j=0; j < ids2.count(); j++) { if (!ids.contains(ids2[j])) { ids.append(ids2[j]); } } } } else { bool filterHandled; ids = filterMessageFolders(copyOfFilter, filterHandled); if (!filterHandled) { for (int i=ids.count()-1; i >= 0; i--) { if (!QMessageFolderFilterPrivate::implementation(copyOfFilter)->filter(ids[i])) { ids.removeAt(i); } } } } if (!sortOrder.isEmpty()) { orderFolders(ids, sortOrder); } applyOffsetAndLimitToMsgFolderIds(ids, offset, limit); return ids; } void CFSEngine::applyOffsetAndLimitToMsgFolderIds(QMessageFolderIdList& idList, int offset, int limit) const { if (offset > 0) { if (offset > idList.count()) { idList.clear(); } else { for (int i = 0; i < offset; i++) { idList.removeFirst(); } } } if (limit > 0) { for (int i = idList.count()-1; i >= limit; i--) { idList.removeAt(i); } } } int CFSEngine::countFolders(const QMessageFolderFilter &filter) const { return queryFolders(filter, QMessageFolderSortOrder(), 0, 0).count(); } QMessageFolder CFSEngine::folder(const QMessageFolderId &id) const { //return QMessageFolder(); QMessageFolder folder; TRAPD(err, folder = folderL(id)); Q_UNUSED(err) return folder; } QMessageFolder CFSEngine::folderL(const QMessageFolderId &id) const { QMessageFolder folder; MEmailMailbox* mailbox = NULL; QMessageFolderId parentId; QMessageAccountId accountId; // get account containing folder TRAPD(err, updateEmailAccountsL()); Q_UNUSED(err) foreach (QMessageAccount value, m_accounts) { accountId = value.id(); QMessageFolderIdList ids = folderIdsByAccountIdL(accountId); if (ids.contains(id)) { TMailboxId mailboxId(stripIdPrefix(accountId.toString()).toInt()); mailbox = m_clientApi->MailboxL(mailboxId); CleanupReleasePushL(*mailbox); TFolderId folderId(stripIdPrefix(id.toString()).toInt(), mailbox->MailboxId()); MEmailFolder* emailFolder = mailbox->FolderL(folderId); CleanupReleasePushL(*emailFolder); QString name = QString::fromUtf16(emailFolder->Name().Ptr(), emailFolder->Name().Length()); folder = QMessageFolderPrivate::from(id, accountId, parentId, name, name); CleanupStack::PopAndDestroy(emailFolder); CleanupStack::PopAndDestroy(mailbox); break; } } return folder; } QMessageFolderIdList CFSEngine::filterMessageFolders(const QMessageFolderFilter& filter, bool& filterHandled) const { QMessageFolderIdList ids; TRAPD(err, ids = filterMessageFoldersL(filter, filterHandled)); Q_UNUSED(err) return ids; } QMessageFolderIdList CFSEngine::filterMessageFoldersL(const QMessageFolderFilter& filter, bool& filterHandled) const { filterHandled = false; QMessageFolderIdList ids; if (filter.isEmpty()) { QMessageFolderFilterPrivate* pf = QMessageFolderFilterPrivate::implementation(filter); if (!pf->_notFilter) { ids = allFolders(); } filterHandled = true; } else { QMessageFolderFilterPrivate* pf = QMessageFolderFilterPrivate::implementation(filter); if (!pf->_valid) { return QMessageFolderIdList(); } switch (pf->_field) { case QMessageFolderFilterPrivate::Id: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (pf->_value.toString().length() > QString(SymbianHelpers::mtmPrefix).length()) { bool folderOk = false; MEmailMailbox* mailbox = NULL; MEmailFolder* folder = NULL;; if (fsFolderL(QMessageFolderId(pf->_value.toString()), mailbox, folder)) { folderOk = true; // cleanup folder->Release(); mailbox->Release(); } if (cmp == QMessageDataComparator::Equal) { if (folderOk) { ids.append(QMessageFolderId(pf->_value.toString())); } } else { // NotEqual ids = allFolders(); if (folderOk) { ids.removeOne(QMessageFolderId(pf->_value.toString())); } } } else { if (cmp == QMessageDataComparator::NotEqual) { ids = allFolders(); } } filterHandled = true; } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (pf->_ids.count() > 0) { // QMessageIdList QMessageFolderIdList ids2; for (int i=0; i < pf->_ids.count(); i++) { MEmailMailbox* mailbox = NULL; MEmailFolder* folder = NULL; if (fsFolderL(QMessageFolderId(pf->_ids[i]), mailbox, folder)) { ids2.append(pf->_ids[i]); // cleanup folder->Release(); mailbox->Release(); } } if (cmp == QMessageDataComparator::Includes) { ids << ids2; } else { // Excludes ids = allFolders(); for (int i=0; i < ids2.count(); i++) { ids.removeOne(ids2[i]); } } filterHandled = true; } else { // Empty QMessageIdList as a list if (cmp == QMessageDataComparator::Excludes) { ids = allFolders(); } filterHandled = true; // QMessageFilter /*if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: }*/ } } break; } case QMessageFolderFilterPrivate::Name: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { // TODO: } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes if (pf->_value.toString().isEmpty() || pf->_value.toString().length() == 0) { filterHandled = true; } } } break; } case QMessageFolderFilterPrivate::Path: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { // TODO: } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes if (pf->_value.toString().isEmpty() || pf->_value.toString().length() == 0) { filterHandled = true; } } } break; } case QMessageFolderFilterPrivate::ParentAccountId: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { if (pf->_value.toString().length() > 0) { ids = folderIdsByAccountIdL(QMessageAccountId(pf->_value.toString())); } } else { // NotEqual ids = allFolders(); if (pf->_value.toString().length() > 0) { QMessageFolderIdList ids2 = folderIdsByAccountIdL(QMessageAccountId(pf->_value.toString())); for (int i = 0; i < ids2.count(); i++) { ids.removeOne(ids2[i]); } } } filterHandled = true; } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } break; } case QMessageFolderFilterPrivate::ParentFolderId: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { MEmailMailbox* mailbox = NULL; MEmailFolder* parentFolder = NULL; if (fsFolderL(QMessageFolderId(pf->_value.toString()), mailbox, parentFolder)) { CleanupReleasePushL(*mailbox); CleanupReleasePushL(*parentFolder); RFolderArray subfolders; parentFolder->GetSubfoldersL(subfolders); CleanupClosePushL(subfolders); for(TInt i=0; i < subfolders.Count(); i++) { MEmailFolder *subFolder = subfolders[i]; ids.append(QMessageFolderId(addIdPrefix( QString::number(subFolder->FolderId().iId), SymbianHelpers::EngineTypeFreestyle))); subFolder->Release(); } CleanupStack::PopAndDestroy(&subfolders); CleanupStack::PopAndDestroy(parentFolder); CleanupStack::PopAndDestroy(mailbox); } } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } break; } case QMessageFolderFilterPrivate::AncestorFolderIds: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (!pf->_value.isNull()) { // QMessageFolderId if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } else { // QMessageFolderFilter if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } } break; } case QMessageFolderFilterPrivate::ParentAccountIdFilter: case QMessageFolderFilterPrivate::None: break; } } if (!filterHandled) { ids = allFolders(); } return ids; } QMessageFolderIdList CFSEngine::allFolders() const { QMessageFolderIdList ids; TRAPD(err, updateEmailAccountsL()); Q_UNUSED(err) foreach (QMessageAccount value, m_accounts) { QMessageFolderIdList ids2 = folderIdsByAccountId(value.id()); ids << ids2; } return ids; } QMessageFolderIdList CFSEngine::folderIdsByAccountId(const QMessageAccountId& accountId) const { QMessageFolderIdList idList; TRAPD(err, idList << folderIdsByAccountIdL(accountId)) Q_UNUSED(err); return idList; } QMessageFolderIdList CFSEngine::folderIdsByAccountIdL(const QMessageAccountId& accountId) const { QMessageFolderIdList folderIds; if (idType(accountId) != EngineTypeFreestyle) return QMessageFolderIdList(); QMessageAccount messageAccount = account(accountId); TMailboxId mailboxId(stripIdPrefix(accountId.toString()).toInt()); MEmailMailbox* mailbox = NULL; mailbox = m_clientApi->MailboxL(mailboxId); if (mailbox == NULL) return QMessageFolderIdList(); CleanupReleasePushL(*mailbox); RFolderArray folders; mailbox->GetFoldersL(folders); CleanupClosePushL(folders); for(TInt i=0; i < folders.Count(); i++) { MEmailFolder *mailFolder = folders[i]; QString fsIdAsString = addIdPrefix(QString::number(mailFolder->FolderId().iId), SymbianHelpers::EngineTypeFreestyle); folderIds.append(QMessageFolderId(fsIdAsString)); //TODO: Support for subfolders? mailFolder->Release(); } CleanupStack::PopAndDestroy(&folders); CleanupStack::PopAndDestroy(mailbox); return folderIds; } bool CFSEngine::fsFolderL(const QMessageFolderId& id, MEmailMailbox* mailbox, MEmailFolder* folder) const { MEmailFolder* fsFolder = NULL; foreach (QMessageAccount account, m_accounts) { TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); mailbox = m_clientApi->MailboxL(mailboxId); TFolderId folderId( stripIdPrefix(id.toString()).toInt(), mailboxId); TRAPD(err, folder = mailbox->FolderL(folderId)); if (err == KErrNone) { CleanupReleasePushL(*fsFolder); return true; } mailbox->Release(); } mailbox = NULL; folder = NULL; return false; } QMessage CFSEngine::message(const QMessageId& id) const { QMessage message = QMessage(); TRAPD(err, message = messageL(id)); Q_UNUSED(err); return message; } QMessage CFSEngine::messageL(const QMessageId& id) const { QMessage message = QMessage(); foreach (QMessageAccount account, m_accounts) { TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); CleanupReleasePushL(*mailbox); TMessageId messageId( stripIdPrefix(id.toString()).toInt(), 0, //stripIdPrefix(folderId.toString()).toInt(), mailboxId); MEmailMessage* fsMessage = NULL; TRAPD(err, fsMessage = mailbox->MessageL(messageId)); if (err == KErrNone) { CleanupReleasePushL(*fsMessage); message = CreateQMessageL(fsMessage); QMessagePrivate* privateMessage = QMessagePrivate::implementation(message); privateMessage->_id = id; privateMessage->_modified = false; CleanupStack::PopAndDestroy(fsMessage); CleanupStack::PopAndDestroy(mailbox); return message; } CleanupStack::PopAndDestroy(mailbox); } return message; } bool CFSEngine::sendEmail(QMessage &message) { TMailboxId mailboxId(stripIdPrefix(message.parentAccountId().toString()).toInt()); MEmailMailbox* mailbox; TRAPD(mailerr, mailbox = m_clientApi->MailboxL(mailboxId)); MEmailMessage* fsMessage; TRAPD(err, fsMessage = createFSMessageL(message, mailbox); fsMessage->SaveChangesL(); fsMessage->SendL(); ); if (fsMessage) fsMessage->Release(); if (mailbox) mailbox->Release(); if (err != KErrNone) return false; else return true; } QMessage CFSEngine::CreateQMessageL(MEmailMessage* aMessage) const { QMessage message; int size = 0; message.setType(QMessage::Email); message.setDate(symbianTTimetoQDateTime(aMessage->Date())); message.setReceivedDate(symbianTTimetoQDateTime(aMessage->Date())); const TFolderId& folderId = aMessage->ParentFolderId(); TMailboxId mailboxId = folderId.iMailboxId; const QMessageAccountId accountId = QMessageAccountId(QString::number(mailboxId.iId)); message.setParentAccountId(accountId); QMessagePrivate* privateMessage = QMessagePrivate::implementation(message); privateMessage->_parentFolderId = QMessageFolderId(QString::number(folderId.iId)); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); MEmailFolder* folder = mailbox->FolderL(folderId); QMessagePrivate::setStandardFolder(message, QMessage::InboxFolder); if (folder->FolderType() == EDrafts) { QMessagePrivate::setStandardFolder(message, QMessage::DraftsFolder); } else if (folder->FolderType() == EDeleted) { QMessagePrivate::setStandardFolder(message, QMessage::TrashFolder); } else if (folder->FolderType() == ESent) { QMessagePrivate::setStandardFolder(message, QMessage::SentFolder); } folder->Release(); mailbox->Release(); if (aMessage->Flags() & EFlag_Read) { privateMessage->_status = privateMessage->_status | QMessage::Read; } if (aMessage->Flags() & EFlag_Important) { message.setPriority(QMessage::HighPriority); } else if (aMessage->Flags() & EFlag_Low) { message.setPriority(QMessage::LowPriority); } else { message.setPriority(QMessage::NormalPriority); } // bodytext and attachment(s) MEmailMessageContent* content = aMessage->ContentL(); if (content) { AddContentToMessage(content, &message); } REmailAttachmentArray attachments; CleanupResetAndRelease<MEmailAttachment>::PushL(attachments); TInt count = aMessage->GetAttachmentsL(attachments); if (count > 0) privateMessage->_status = privateMessage->_status | QMessage::HasAttachments; for(TInt i = 0; i < count; i++) { TInt availableSize = attachments[i]->AvailableSize(); QByteArray name = QString::fromUtf16(attachments[i]->FileNameL().Ptr(), attachments[i]->FileNameL().Length()).toLocal8Bit(); QByteArray mimeType; // TODO: atts[i]->ContentType() is empty QByteArray mimeSubType; // TODO; int size = attachments[i]->TotalSize(); QMessageContentContainer attachment = QMessageContentContainerPrivate::from( aMessage->MessageId().iId, attachments[i]->Id().iId, name, mimeType, mimeSubType, size); addAttachmentToMessage(message, attachment); } CleanupStack::PopAndDestroy(); attachments.Close(); //from /* TPtrC from = aMessage->SenderAddressL()->Address(); if (from.Length() > 0) { message.setFrom(QMessageAddress(QMessageAddress::Email, QString::fromUtf16(from.Ptr(), from.Length()))); QMessagePrivate::setSenderName(message, QString::fromUtf16(from.Ptr(), from.Length())); }*/ //to REmailAddressArray toRecipients; CleanupResetAndRelease<MEmailAddress>::PushL(toRecipients); aMessage->GetRecipientsL(MEmailAddress::ETo, toRecipients); QList<QMessageAddress> toList; for(TInt i = 0; i < toRecipients.Count(); i++) { TPtrC to = toRecipients[i]->Address(); toList.append(QMessageAddress(QMessageAddress::Email, QString::fromUtf16(to.Ptr(), to.Length()))); } message.setTo(toList); CleanupStack::PopAndDestroy(&toRecipients); toRecipients.Close(); //cc REmailAddressArray ccRecipients; CleanupResetAndRelease<MEmailAddress>::PushL(ccRecipients); aMessage->GetRecipientsL(MEmailAddress::ECc, ccRecipients); QList<QMessageAddress> ccList; for(TInt i = 0; i < ccRecipients.Count(); i++) { TPtrC cc = ccRecipients[i]->Address(); ccList.append(QMessageAddress(QMessageAddress::Email, QString::fromUtf16(cc.Ptr(), cc.Length()))); } message.setCc(ccList); CleanupStack::PopAndDestroy(&ccRecipients); ccRecipients.Close(); //bcc REmailAddressArray bccRecipients; CleanupResetAndRelease<MEmailAddress>::PushL(bccRecipients); aMessage->GetRecipientsL(MEmailAddress::EBcc, bccRecipients); QList<QMessageAddress> bccList; for(TInt i = 0; i < bccRecipients.Count(); i++) { TPtrC bcc = bccRecipients[i]->Address(); bccList.append(QMessageAddress(QMessageAddress::Email, QString::fromUtf16(bcc.Ptr(), bcc.Length()))); } message.setBcc(bccList); CleanupStack::PopAndDestroy(&bccRecipients); bccRecipients.Close(); // Read message subject TPtrC subject = aMessage->Subject(); if (subject.Length() > 0) { message.setSubject(QString::fromUtf16(subject.Ptr(), subject.Length())); } // TODO: size privateMessage->_size = size; return message; } void CFSEngine::AddContentToMessage(MEmailMessageContent* aContent, QMessage* aMessage) const { MEmailMultipart* mPart = aContent->AsMultipartOrNull(); if (mPart) { TInt partCount = 0; TRAPD(err, partCount = mPart->PartCountL()); if (err == KErrNone) { for (TInt i = 0; i < partCount; i++) { MEmailMessageContent* content = NULL; TRAPD(err2, content = mPart->PartByIndexL(i)); if (err2 == KErrNone) { AddContentToMessage(content, aMessage); content->Release(); } } } return; } MEmailTextContent* textContent = aContent->AsTextContentOrNull(); if (textContent) { QByteArray mimeType; TInt availableSize = textContent->AvailableSize(); TRAPD(err, TPtrC body = textContent->ContentL(); QString text = QString::fromUtf16(body.Ptr(), body.Length()); aMessage->setBody(text, mimeType); ); Q_UNUSED(err); return; } } void CFSEngine::addAttachmentToMessage(QMessage& message, QMessageContentContainer& attachment) const { QMessagePrivate* privateMessage = QMessagePrivate::implementation(message); QMessageContentContainerPrivate* container = QMessagePrivate::containerImplementation(message); if (container->_attachments.isEmpty()) { QMessageContentContainerId existingBodyId(message.bodyId()); if (existingBodyId == QMessageContentContainerPrivate::bodyContentId()) { // The body content is in the message itself - move it to become the first attachment QMessageContentContainer newBody(message); QMessageContentContainerPrivate::implementation(newBody)->setDerivedMessage(0); container->setContentType("multipart", "mixed", ""); privateMessage->_bodyId = container->prependContent(newBody); } else { // This message is now multipart container->setContentType("multipart", "mixed", ""); } container->_available = true; } container->appendContent(attachment); bool haveAttachments = !container->_attachments.isEmpty(); message.setStatus(QMessage::HasAttachments,haveAttachments); privateMessage->_modified = true; } QDateTime CFSEngine::symbianTTimetoQDateTime(const TTime& time) const { TDateTime dateTime = time.DateTime(); QDate qdate = QDate(dateTime.Year(), static_cast<int>(dateTime.Month())+1, dateTime.Day()+1); QTime qtime = QTime(dateTime.Hour(), dateTime.Minute(), dateTime.Second(), dateTime.MicroSecond()/1000 ); return QDateTime(qdate, qtime, Qt::UTC); } TTime CFSEngine::qDateTimeToSymbianTTime(const QDateTime& date) const { TDateTime dateTime; dateTime.SetYear(date.date().year()); dateTime.SetMonth(static_cast<TMonth>(date.date().month()-1)); dateTime.SetDay(date.date().day()-1); dateTime.SetHour(date.time().hour()); dateTime.SetMinute(date.time().minute()); dateTime.SetSecond(date.time().second()); dateTime.SetMicroSecond(date.time().msec()*1000); return TTime(dateTime); } TFolderType CFSEngine::standardFolderId(QMessage::StandardFolder standardFolder) { switch(standardFolder) { case QMessage::InboxFolder: return EInbox; case QMessage::OutboxFolder: return EOutbox; case QMessage::DraftsFolder: return EDrafts; case QMessage::SentFolder: return ESent; case QMessage::TrashFolder: return EDeleted; default: return EOther; } } CFSMessagesFindOperation::CFSMessagesFindOperation(CFSEngine& aOwner, int aOperationId) : m_owner(aOwner), m_operationId(aOperationId), m_resultCorrectlyOrdered(false), m_receiveNewMessages(false), m_activeSearchCount(0), m_searchField(None) { TRAPD(err, m_factory = CEmailInterfaceFactory::NewL(); m_interfacePtr = m_factory->InterfaceL(KEmailClientApiInterface); m_clientApi = static_cast<MEmailClientApi*>(m_interfacePtr); ); } CFSMessagesFindOperation::~CFSMessagesFindOperation() { foreach(FSSearchOperation operation, m_searchOperations) { operation.m_search->Release(); operation.m_mailbox->Release(); } m_receiveNewMessages = false; m_clientApi->Release(); delete m_factory; } void CFSMessagesFindOperation::filterAndOrderMessages(const QMessageFilter &filter, const QMessageSortOrder& sortOrder, QString body, QMessageDataComparator::MatchFlags matchFlags) { m_filterList.clear(); m_filterList.append(filter); filterAndOrderMessages(m_filterList, sortOrder, body, matchFlags); } void CFSMessagesFindOperation::filterAndOrderMessages(const QMessageFilterPrivate::SortedMessageFilterList& filters, const QMessageSortOrder& sortOrder, QString body, QMessageDataComparator::MatchFlags matchFlags) { TRAPD(err, filterAndOrderMessagesL(filters, sortOrder, body, matchFlags)); if (err != KErrNone) { //something has failed -> return empty list m_idList = QMessageIdList(); QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } } void CFSMessagesFindOperation::filterAndOrderMessagesL(const QMessageFilterPrivate::SortedMessageFilterList& filters, const QMessageSortOrder& sortOrder, QString body, QMessageDataComparator::MatchFlags matchFlags) { m_numberOfHandledFilters = 0; TEmailSortCriteria sortCriteria = TEmailSortCriteria(); m_excludeIdList = QMessageIdList(); m_matchFlags = matchFlags; if (filters.count() == 0) { m_idList = QMessageIdList(); QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); return; } QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(filters[m_numberOfHandledFilters]); // Set sortOrder if (!sortOrder.isEmpty() ) { QMessageSortOrderPrivate* privateMessageOrdering = QMessageSortOrderPrivate::implementation(sortOrder); QPair<QMessageSortOrderPrivate::Field, Qt::SortOrder> fieldOrder = privateMessageOrdering->_fieldOrderList.at(0); switch (fieldOrder.first) { case QMessageSortOrderPrivate::Type: break; case QMessageSortOrderPrivate::Sender: sortCriteria.iField = TEmailSortCriteria::EBySender; break; case QMessageSortOrderPrivate::Recipients: sortCriteria.iField = TEmailSortCriteria::EByRecipient; break; case QMessageSortOrderPrivate::Subject: sortCriteria.iField = TEmailSortCriteria::EBySubject; break; case QMessageSortOrderPrivate::TimeStamp: sortCriteria.iField = TEmailSortCriteria::EByDate; break; case QMessageSortOrderPrivate::ReceptionTimeStamp: sortCriteria.iField = TEmailSortCriteria::EBySender; break; case QMessageSortOrderPrivate::Read: sortCriteria.iField = TEmailSortCriteria::EByUnread; break; case QMessageSortOrderPrivate::HasAttachments: sortCriteria.iField = TEmailSortCriteria::EByAttachment; break; case QMessageSortOrderPrivate::Incoming: //TODO: break; case QMessageSortOrderPrivate::Removed: //TODO: break; case QMessageSortOrderPrivate::Priority: sortCriteria.iField = TEmailSortCriteria::EByPriority; break; case QMessageSortOrderPrivate::Size: sortCriteria.iField = TEmailSortCriteria::EBySize; break; } sortCriteria.iAscending = fieldOrder.second == Qt::AscendingOrder?true:false; } if ((filters.count() == 1) && (pf->_field == QMessageFilterPrivate::None) && (pf->_filterList.count() == 0)) { if (pf->_notFilter) { // There is only one filter: empty ~QMessageFilter() // => return empty QMessageIdList m_idList = QMessageIdList(); QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } else { // There is only one filter: empty QMessageFilter() // => return all messages getAllMessagesL(sortCriteria); } m_numberOfHandledFilters++; return; } if (!body.isEmpty()) { m_searchField = Body; m_searchKey = body; } switch (pf->_field) { case QMessageFilterPrivate::ParentFolderId: { if (idType(pf->_value.toString()) != EngineTypeFreestyle) { QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); return; } if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessageFolderId QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { m_numberOfHandledFilters++; QMessageFolder messageFolder = m_owner.folder(QMessageFolderId(pf->_value.toString())); getFolderSpecificMessagesL(messageFolder, sortCriteria); m_resultCorrectlyOrdered = true; QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { // QMessageFolderFilter QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } break; } case QMessageFilterPrivate::Id: { if (idType(pf->_value.toString()) != EngineTypeFreestyle) { QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); return; } m_numberOfHandledFilters++; if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessageId QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (!pf->_value.isNull() && pf->_value.toString().length() > QString(SymbianHelpers::freestylePrefix).length()) { if (cmp == QMessageDataComparator::Equal) { QMessage message = m_owner.message(QMessageId(pf->_value.toString())); m_idList.clear(); m_idList.append(message.id()); m_resultCorrectlyOrdered = true; QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } else { // NotEqual m_excludeIdList.clear(); m_excludeIdList.append(QMessageId(pf->_value.toString())); getAllMessagesL(sortCriteria); } } else { if (cmp == QMessageDataComparator::NotEqual) { getAllMessagesL(sortCriteria); } } } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (pf->_ids.count() > 0) { // QMessageIdList if (cmp == QMessageDataComparator::Includes) { for (int i=0; i < pf->_ids.count(); i++) { QMessage message = m_owner.message(QMessageId(pf->_ids[i].toString())); m_idList.append(message.id()); } QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } else { // Excludes for (int i=0; i < pf->_ids.count(); i++) { m_excludeIdList.clear(); m_excludeIdList.append(QMessageId(pf->_ids[i].toString())); getAllMessagesL(sortCriteria); } getAllMessagesL(sortCriteria); } } else { //ipEntrySelection = new(ELeave)CMsvEntrySelection; if (cmp == QMessageDataComparator::Excludes) { getAllMessagesL(sortCriteria); } /*// QMessageFilter if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: }*/ } } break; } case QMessageFilterPrivate::ParentAccountId: { if (idType(pf->_value.toString()) != EngineTypeFreestyle) { QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); return; } if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessageAccountId m_numberOfHandledFilters++; QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { QMessageAccount messageAccount = m_owner.account(pf->_value.toString()); getAccountSpecificMessagesL(messageAccount, sortCriteria); m_resultCorrectlyOrdered = true; } else { // NotEqual QStringList exludedAccounts; exludedAccounts << pf->_value.toString(); QMessageFilterPrivate* privateFilter = NULL; for (int i=m_numberOfHandledFilters; i < filters.count(); i++) { privateFilter = QMessageFilterPrivate::implementation(filters[i]); if (privateFilter->_field == QMessageFilterPrivate::ParentAccountId && privateFilter->_comparatorType == QMessageFilterPrivate::Equality) { cmp = static_cast<QMessageDataComparator::EqualityComparator>(privateFilter->_comparatorValue); if (cmp == QMessageDataComparator::NotEqual) { exludedAccounts << privateFilter->_value.toString(); m_numberOfHandledFilters++; } else { break; } } else { break; } } privateFilter = NULL; if (filters.count() > m_numberOfHandledFilters) { privateFilter = QMessageFilterPrivate::implementation(filters[m_numberOfHandledFilters]); if (privateFilter->_field == QMessageFilterPrivate::StandardFolder && privateFilter->_comparatorType == QMessageFilterPrivate::Equality) { cmp = static_cast<QMessageDataComparator::EqualityComparator>(privateFilter->_comparatorValue); if (cmp == QMessageDataComparator::Equal) { m_numberOfHandledFilters++; } } else { privateFilter = NULL; } } foreach (QMessageAccount value, m_owner.m_accounts) { if (!exludedAccounts.contains(value.id().toString())) { getAccountSpecificMessagesL(value, sortCriteria); } } } } break; } case QMessageFilterPrivate::AncestorFolderIds: { m_numberOfHandledFilters++; if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (!pf->_value.isNull()) { // QMessageFolderId if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } else { // QMessageFolderFilter if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } } break; } case QMessageFilterPrivate::Type: { m_numberOfHandledFilters++; QMessageFilterPrivate* privateFilter = NULL; // Check if next filter is StandardFolder filter if (filters.count() > m_numberOfHandledFilters) { privateFilter = QMessageFilterPrivate::implementation(filters[m_numberOfHandledFilters]); if (privateFilter->_field != QMessageFilterPrivate::StandardFolder) { privateFilter = NULL; } else { m_numberOfHandledFilters++; } } if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessage::Type QMessage::Type type = static_cast<QMessage::Type>(pf->_value.toInt()); QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { QMessageAccountIdList accountIds = m_owner.accountsByType(type); for (int i = 0; i < accountIds.count(); i++) { QMessageAccount messageAccount = m_owner.account(accountIds[i]); getAccountSpecificMessagesL(messageAccount, sortCriteria); } } else { // NotEqual foreach (QMessageAccount value, m_owner.m_accounts) { if (!(value.messageTypes() & type)) { getAccountSpecificMessagesL(value, sortCriteria); } } } } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { // QMessage::TypeFlags QMessage::TypeFlags typeFlags = static_cast<QMessage::TypeFlags>(pf->_value.toInt()); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { foreach (QMessageAccount value, m_owner.m_accounts) { if (value.messageTypes() | typeFlags) { getAccountSpecificMessagesL(value, sortCriteria); } } } else { // Excludes foreach (QMessageAccount value, m_owner.m_accounts) { if (!(value.messageTypes() & typeFlags)) { getAccountSpecificMessagesL(value, sortCriteria); } } } } break; } case QMessageFilterPrivate::StandardFolder: { m_numberOfHandledFilters++; QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); QMessage::StandardFolder standardFolder = static_cast<QMessage::StandardFolder>(pf->_value.toInt()); TFolderType stdFolder = m_owner.standardFolderId(standardFolder); if (cmp == QMessageDataComparator::Equal) { foreach (QMessageAccount messageAccount, m_owner.m_accounts) { TMailboxId mailboxId(stripIdPrefix(messageAccount.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); CleanupReleasePushL(*mailbox); MEmailFolder* folder = mailbox->FolderByTypeL(stdFolder); CleanupReleasePushL(*folder); QMessageFolder standardFolder = m_owner.folder( QMessageFolderId(QString::number(folder->FolderId().iId))); getFolderSpecificMessagesL(standardFolder, sortCriteria); m_activeSearchCount++; CleanupStack::PopAndDestroy(folder); CleanupStack::PopAndDestroy(mailbox); } m_resultCorrectlyOrdered = true; QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } else { // NotEqual foreach (QMessageAccount messageAccount, m_owner.m_accounts) { TMailboxId mailboxId(stripIdPrefix(messageAccount.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); CleanupReleasePushL(*mailbox); QMessage::StandardFolder i = QMessage::InboxFolder; while (i <= QMessage::TrashFolder) { if (i != standardFolder) { MEmailFolder* folder = mailbox->FolderByTypeL(m_owner.standardFolderId(i)); CleanupReleasePushL(*folder); QMessageFolder standardFolder = m_owner.folder( QMessageFolderId(QString::number(folder->FolderId().iId))); getFolderSpecificMessagesL(standardFolder, sortCriteria); CleanupStack::PopAndDestroy(folder); } i = static_cast<QMessage::StandardFolder>(static_cast<int>(i) + 1); } CleanupStack::PopAndDestroy(mailbox); } QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } break; } case QMessageFilterPrivate::Sender: case QMessageFilterPrivate::Recipients: case QMessageFilterPrivate::Subject: case QMessageFilterPrivate::Status: case QMessageFilterPrivate::Priority: case QMessageFilterPrivate::Size: case QMessageFilterPrivate::ParentAccountIdFilter: case QMessageFilterPrivate::ParentFolderIdFilter: case QMessageFilterPrivate::TimeStamp: case QMessageFilterPrivate::ReceptionTimeStamp: case QMessageFilterPrivate::None: default: break; } if (body.isEmpty()) { if (m_numberOfHandledFilters < filters.count()) { pf = QMessageFilterPrivate::implementation(filters[m_numberOfHandledFilters]); switch (pf->_field) { case QMessageFilterPrivate::Sender: { m_searchField = Sender; if (pf->_comparatorType == QMessageFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { if (pf->_value.toString().length() > 0) { m_searchKey = pf->_value.toString(); m_numberOfHandledFilters++; } } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } break; } case QMessageFilterPrivate::Recipients: { m_searchField = Recipients; if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { if (pf->_value.toString().length() > 0) { m_searchKey = pf->_value.toString(); m_numberOfHandledFilters++; } } else { // Excludes //TODO: } } break; } case QMessageFilterPrivate::Subject: { m_searchField = Subject; if (pf->_comparatorType == QMessageFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { if (pf->_value.toString().length() > 0) { m_searchKey = pf->_value.toString(); m_numberOfHandledFilters++; } } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } break; } case QMessageFilterPrivate::TimeStamp: case QMessageFilterPrivate::ReceptionTimeStamp: case QMessageFilterPrivate::Status: case QMessageFilterPrivate::Priority: case QMessageFilterPrivate::Size: case QMessageFilterPrivate::ParentAccountIdFilter: case QMessageFilterPrivate::ParentFolderIdFilter: case QMessageFilterPrivate::Id: case QMessageFilterPrivate::ParentFolderId: case QMessageFilterPrivate::AncestorFolderIds: case QMessageFilterPrivate::ParentAccountId: case QMessageFilterPrivate::Type: case QMessageFilterPrivate::StandardFolder: case QMessageFilterPrivate::None: default: break; } if (m_activeSearchCount == 0) getAllMessagesL(sortCriteria); } } if (m_activeSearchCount == 0) QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } void CFSMessagesFindOperation::getAllMessagesL(TEmailSortCriteria& sortCriteria) { // Get all messages from every known account foreach (QMessageAccount value, m_owner.m_accounts) { getAccountSpecificMessagesL(value, sortCriteria); } } void CFSMessagesFindOperation::getAccountSpecificMessagesL(QMessageAccount& messageAccount, TEmailSortCriteria& sortCriteria) { TMailboxId mailboxId(stripIdPrefix(messageAccount.id().toString()).toInt()); FSSearchOperation operation; operation.m_mailbox = m_clientApi->MailboxL(mailboxId); operation.m_search = operation.m_mailbox->MessageSearchL(); operation.m_search->AddSearchKeyL(_L("*")); operation.m_search->SetSortCriteriaL( sortCriteria ); operation.m_search->StartSearchL( *this ); // this implements MEmailSearchObserver m_activeSearchCount++; m_searchOperations.append(operation); } void CFSMessagesFindOperation::getFolderSpecificMessagesL(QMessageFolder& messageFolder, TEmailSortCriteria sortCriteria) { m_activeSearchCount++; RSortCriteriaArray sortCriteriaArray; CleanupClosePushL(sortCriteriaArray); TFolderId folderId(stripIdPrefix(messageFolder.id().toString()).toInt(), stripIdPrefix(messageFolder.parentAccountId().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(stripIdPrefix(messageFolder.parentAccountId().toString()).toInt()); CleanupReleasePushL(*mailbox); MEmailFolder *mailFolder = mailbox->FolderL(folderId); CleanupReleasePushL(*mailFolder); sortCriteriaArray.Append(sortCriteria); MMessageIterator* msgIterator = mailFolder->MessagesL(sortCriteriaArray); CleanupReleasePushL(*msgIterator); MEmailMessage* msg = NULL; while ( NULL != (msg = msgIterator->NextL())) { QMessageId messageId(addIdPrefix(QString::number(msg->MessageId().iId), SymbianHelpers::EngineTypeFreestyle)); if (!m_excludeIdList.contains(messageId)) { m_idList.append(messageId); } msg->Release(); } CleanupStack::PopAndDestroy(msgIterator); CleanupStack::PopAndDestroy(mailFolder); CleanupStack::PopAndDestroy(mailbox); CleanupStack::PopAndDestroy(&sortCriteriaArray); } void CFSMessagesFindOperation::HandleResultL(MEmailMessage* aMessage) { QMessageId messageId(addIdPrefix(QString::number(aMessage->MessageId().iId), SymbianHelpers::EngineTypeFreestyle)); if (!m_excludeIdList.contains(messageId)) { m_idList.append(messageId); } aMessage->Release(); } void CFSMessagesFindOperation::SearchCompletedL() { if (m_receiveNewMessages) { m_receiveNewMessages = false; } else { m_activeSearchCount--; if (m_activeSearchCount <= 0) { QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } } } void CFSMessagesFindOperation::SearchCompleted() { if (m_searchField != None) { QMessageIdList idList; foreach (QMessageId messageId, m_idList) { if (fillsSearchKeyCriteria(messageId)) idList.append(messageId); } m_idList = idList; } m_owner.filterAndOrderMessagesReady(true, m_operationId, m_idList, 1, m_resultCorrectlyOrdered); } bool CFSMessagesFindOperation::fillsSearchKeyCriteria(QMessageId& messageId) { QMessage message = m_owner.message(messageId); Qt::CaseSensitivity caseSensitivity = (m_matchFlags & QMessageDataComparator::MatchCaseSensitive) ? Qt::CaseSensitive:Qt::CaseInsensitive; switch (m_searchField) { case Sender: { return message.from().addressee().contains(m_searchKey, caseSensitivity); break; } case Recipients: { foreach (QMessageAddress toRecipient, message.to()) { if (toRecipient.addressee().contains(m_searchKey, caseSensitivity)) return true; } foreach (QMessageAddress ccRecipient, message.cc()) { if (ccRecipient.addressee().contains(m_searchKey, caseSensitivity)) return true; } foreach (QMessageAddress bccRecipient, message.bcc()) { if (bccRecipient.addressee().contains(m_searchKey, caseSensitivity)) return true; } return false; break; } case Subject: { return message.subject().contains(m_searchKey, caseSensitivity); break; } case Body: { if (message.bodyId() == QMessageContentContainerPrivate::bodyContentId()) { // Message contains only body (not attachments) QString messageBody = message.textContent(); return messageBody.contains(m_searchKey, caseSensitivity); } else { // Message contains body and attachments QMessageContentContainerIdList contentIds = message.contentIds(); foreach (QMessageContentContainerId id, contentIds){ QMessageContentContainer container = message.find(id); QMessageContentContainerPrivate* pPrivateContainer = QMessageContentContainerPrivate::implementation(container); if (pPrivateContainer->_id == message.bodyId()) { // ContentContainer is body return container.textContent().contains(m_searchKey, caseSensitivity); } } } break; } default: break; } return false; } #include "..\..\build\Release\QtMessaging\moc\moc_qfsengine_symbian_p.cpp"; QTM_END_NAMESPACE setBody fix /**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmessageservice.h" #include "qmessageservice_symbian_p.h" #include "qfsengine_symbian_p.h" #include "qmessage_symbian_p.h" #include "messagingutil_p.h" #include "qmessageaccount.h" #include "qmessageaccount_p.h" #include "qmessageaccountfilter.h" #include "qmessageaccountfilter_p.h" #include "qmessagecontentcontainer_symbian_p.h" #include "qmessagefolder.h" #include "qmessagefolder_p.h" #include "qmessagefolderfilter.h" #include "qmessagefolderfilter_p.h" #include "qmessageaccountsortorder_p.h" #include "qmessagestore_symbian_p.h" #include "qmessagefoldersortorder_p.h" #include "qmessagesortorder_p.h" #include <emailinterfacefactory.h> #include <QTextCodec> #include <emailapidefs.h> #include <memailmailbox.h> #include <memailfolder.h> #include <memailmessage.h> #include <memailaddress.h> #include <memailcontent.h> #include <mmessageiterator.h> using namespace EmailInterface; QTM_BEGIN_NAMESPACE using namespace SymbianHelpers; Q_GLOBAL_STATIC(CFSEngine,fsEngine); CFSEngine::CFSEngine() { TRAPD(err, { m_factory = CEmailInterfaceFactory::NewL(); m_ifPtr = m_factory->InterfaceL(KEmailClientApiInterface); }); Q_UNUSED(err); m_clientApi = static_cast<MEmailClientApi*>(m_ifPtr); #ifdef FREESTYLEMAILBOXOBSERVERUSED TRAPD(err2, setPluginObserversL()); Q_UNUSED(err2); #endif } CFSEngine::~CFSEngine() { m_mtmAccountList.clear(); for ( TInt i = 0; i < m_mailboxes.Count(); i++ ) { m_mailboxes[i]->Release(); } m_mailboxes.Reset(); m_clientApi->Release(); delete m_factory; } CFSEngine* CFSEngine::instance() { return fsEngine(); } bool CFSEngine::accountLessThan(const QMessageAccountId accountId1, const QMessageAccountId accountId2) { CFSEngine* freestyleEngine = fsEngine(); return QMessageAccountSortOrderPrivate::lessThan(freestyleEngine->m_currentAccountOrdering, freestyleEngine->account(accountId1), freestyleEngine->account(accountId2)); } void CFSEngine::orderAccounts(QMessageAccountIdList& accountIds, const QMessageAccountSortOrder &sortOrder) const { Q_UNUSED(accountIds); m_currentAccountOrdering = sortOrder; qSort(accountIds.begin(), accountIds.end(), CFSEngine::accountLessThan); } bool CFSEngine::folderLessThan(const QMessageFolderId folderId1, const QMessageFolderId folderId2) { CFSEngine* freestyleEngine = fsEngine(); return QMessageFolderSortOrderPrivate::lessThan(freestyleEngine->m_currentFolderOrdering, freestyleEngine->folder(folderId1), freestyleEngine->folder(folderId2)); } void CFSEngine::orderFolders(QMessageFolderIdList& folderIds, const QMessageFolderSortOrder &sortOrder) const { m_currentFolderOrdering = sortOrder; qSort(folderIds.begin(), folderIds.end(), CFSEngine::folderLessThan); } bool CFSEngine::messageLessThan(const QMessage& message1, const QMessage& message2) { CFSEngine* freestyleEngine = fsEngine(); return QMessageSortOrderPrivate::lessThan(freestyleEngine->m_currentMessageOrdering, message1, message2); } void CFSEngine::orderMessages(QMessageIdList& messageIds, const QMessageSortOrder &sortOrder) const { m_currentMessageOrdering = sortOrder; QList<QMessage> messages; for (int i=0; i < messageIds.count(); i++) { messages.append(message(messageIds[i])); } qSort(messages.begin(), messages.end(), CFSEngine::messageLessThan); messageIds.clear(); for (int i=0; i < messages.count(); i++) { messageIds.append(messages[i].id()); } } void CFSEngine::setMtmAccountIdList(QMessageAccountIdList accountList) { for (TInt i = 0; i < accountList.count(); i++) { m_mtmAccountList.append(stripIdPrefix(accountList[i])); } } QMessageAccountIdList CFSEngine::queryAccounts(const QMessageAccountFilter &filter, const QMessageAccountSortOrder &sortOrder, uint limit, uint offset) const { QMessageAccountIdList accountIds; TRAPD(err, updateEmailAccountsL()); QMessageAccountFilterPrivate* privateMessageAccountFilter = QMessageAccountFilterPrivate::implementation(filter); if (filter.isEmpty()) { if (!privateMessageAccountFilter->_notFilter) { // All accounts are returned for empty filter foreach (QMessageAccount value, m_accounts) { accountIds.append(value.id()); } } } else { if (privateMessageAccountFilter->_valid) { foreach (QMessageAccount value, m_accounts) { if (privateMessageAccountFilter->filter(value)) { accountIds.append(value.id()); } } } else { foreach (QMessageAccount value, m_accounts) { if (privateMessageAccountFilter->filter(value)) { accountIds.append(value.id()); } } } } if (!sortOrder.isEmpty()) { orderAccounts(accountIds, sortOrder); } applyOffsetAndLimitToAccountIds(accountIds, offset, limit); return accountIds; } void CFSEngine::applyOffsetAndLimitToAccountIds(QMessageAccountIdList& idList, int offset, int limit) const { if (offset > 0) { if (offset > idList.count()) { idList.clear(); } else { for (int i = 0; i < offset; i++) { idList.removeFirst(); } } } if (limit > 0) { for (int i = idList.count()-1; i >= limit; i--) { idList.removeAt(i); } } } int CFSEngine::countAccounts(const QMessageAccountFilter &filter) const { return queryAccounts(filter, QMessageAccountSortOrder(), 0, 0).count(); } QMessageAccount CFSEngine::account(const QMessageAccountId &id) const { TRAPD(err, updateEmailAccountsL()); Q_UNUSED(err) return m_accounts[id.toString()]; } QMessageAccountId CFSEngine::defaultAccount(QMessage::Type type) const { // TODO Q_UNUSED(type); return QMessageAccountId(); } QMessageAccountIdList CFSEngine::accountsByType(QMessage::Type type) const { QMessageAccountIdList accountIds = QMessageAccountIdList(); foreach (QMessageAccount value, m_accounts) { if ((value.messageTypes() & type) == (int)type) { accountIds.append(value.id()); } } return accountIds; } void CFSEngine::updateEmailAccountsL() const { QStringList keys = m_accounts.keys(); RMailboxPtrArray mailboxes; CleanupResetAndRelease<MEmailMailbox>::PushL(mailboxes); m_clientApi->GetMailboxesL(mailboxes); for (TInt i = 0; i < mailboxes.Count(); i++) { MEmailMailbox *mailbox = mailboxes[i]; QString idAsString = QString::number(mailbox->MailboxId().iId); QString fsIdAsString = addIdPrefix(idAsString, SymbianHelpers::EngineTypeFreestyle); TBool overlap = false; for (TInt j = 0; j < m_mtmAccountList.count(); j++) { if (idAsString == m_mtmAccountList[j].toString()) overlap = true; } if (!m_accounts.contains(fsIdAsString) && !overlap) { QMessageAccount account = QMessageAccountPrivate::from( QMessageAccountId(fsIdAsString), QString::fromUtf16(mailbox->MailboxName().Ptr(), mailbox->MailboxName().Length()), 0, 0, QMessage::Email); m_accounts.insert(fsIdAsString, account); } else { keys.removeOne(fsIdAsString); } mailbox->Release(); } mailboxes.Reset(); CleanupStack::PopAndDestroy(); for (int i=0; i < keys.count(); i++) { m_accounts.remove(keys[i]); } } #ifdef FREESTYLEMAILBOXOBSERVERUSED void CFSEngine::setPluginObserversL() { m_clientApi->GetMailboxesL(m_mailboxes); for (TInt i = 0; i < m_mailboxes.Count(); i++) { MEmailMailbox *mailbox = m_mailboxes[i]; mailbox->RegisterObserverL(*this); } } void CFSEngine::NewMessageEventL(const TMailboxId& aMailbox, const REmailMessageIdArray aNewMessages, const TFolderId& aParentFolderId) { QMessageManager::NotificationFilterIdSet matchingFilters; QMessageStorePrivate::NotificationType notificationType = QMessageStorePrivate::Added; for (TInt i = 0; i < aNewMessages.Count(); i++) { TMessageId messageId(aNewMessages[i]); notificationL(aMailbox, messageId, aParentFolderId, notificationType); } } void CFSEngine::MessageChangedEventL(const TMailboxId& aMailbox, const REmailMessageIdArray aChangedMessages, const TFolderId& aParentFolderId) { QMessageManager::NotificationFilterIdSet matchingFilters; QMessageStorePrivate::NotificationType notificationType = QMessageStorePrivate::Updated; for (TInt i = 0; i < aChangedMessages.Count(); i++) { TMessageId messageId(aChangedMessages[i]); notificationL(aMailbox, messageId, aParentFolderId, notificationType); } } void CFSEngine::MessageDeletedEventL(const TMailboxId& aMailbox, const REmailMessageIdArray aDeletedMessages, const TFolderId& aParentFolderId) { // TODO: add filter handling QMessageManager::NotificationFilterIdSet matchingFilters; QMap<int, QMessageFilter> filters(m_filters); QMap<int, QMessageFilter>::const_iterator it = filters.begin(), end = filters.end(); QMessageStorePrivate::NotificationType notificationType = QMessageStorePrivate::Removed; MEmailMailbox* mailbox = m_clientApi->MailboxL(aMailbox); MEmailFolder* folder = mailbox->FolderL(aParentFolderId); QString idAsString = QString::number(mailbox->MailboxId().iId); for (TInt j = 0; j < m_mtmAccountList.count(); j++) { if (idAsString == m_mtmAccountList[j].toString()) return; } for (TInt i = 0; i < aDeletedMessages.Count(); i++) { for ( ; it != end; ++it) { // Empty filter matches to all messages matchingFilters.insert(it.key()); } TMessageId messageId(aDeletedMessages[i]); ipMessageStorePrivate->messageNotification(notificationType, QMessageId(addIdPrefix(QString::number(messageId.iId), SymbianHelpers::EngineTypeFreestyle)), matchingFilters); } folder->Release(); mailbox->Release(); } void CFSEngine::notificationL(const TMailboxId& aMailbox, const TMessageId& aMessageId, const TFolderId& aParentFolderId, QMessageStorePrivate::NotificationType aNotificationType) { QMessageManager::NotificationFilterIdSet matchingFilters; // Copy the filter map to protect against modification during traversal QMap<int, QMessageFilter> filters(m_filters); QMap<int, QMessageFilter>::const_iterator it = filters.begin(), end = filters.end(); QMessage message; QMessageId realMessageId = QMessageId(addIdPrefix(QString::number(aMessageId.iId), SymbianHelpers::EngineTypeFreestyle)); bool messageRetrieved = false; MEmailMailbox* mailbox = m_clientApi->MailboxL(aMailbox); CleanupReleasePushL(*mailbox); QString idAsString = QString::number(mailbox->MailboxId().iId); for (TInt j = 0; j < m_mtmAccountList.count(); j++) { if (idAsString == m_mtmAccountList[j].toString()) { CleanupStack::Pop(mailbox); return; } } for ( ; it != end; ++it) { const QMessageFilter &filter(it.value()); if (!messageRetrieved) { MEmailMessage* fsMessage = mailbox->MessageL(aMessageId); CleanupReleasePushL(*fsMessage); if (!fsMessage) { CleanupStack::Pop(fsMessage); CleanupStack::Pop(mailbox); return; } message = CreateQMessageL(fsMessage); messageRetrieved = true; CleanupStack::Pop(fsMessage); } if (filter.isEmpty()) { // Empty filter matches to all messages matchingFilters.insert(it.key()); } else { if (message.type() == QMessage::NoType) { matchingFilters.clear(); continue; } } QMessageFilterPrivate* privateMessageFilter = QMessageFilterPrivate::implementation(filter); if (privateMessageFilter->filter(message)) { matchingFilters.insert(it.key()); } } int c = matchingFilters.count(); QString id = realMessageId.toString(); if (matchingFilters.count() > 0) ipMessageStorePrivate->messageNotification(aNotificationType, realMessageId, matchingFilters); CleanupStack::Pop(mailbox); } #endif MEmailMessage* CFSEngine::createFSMessageL(const QMessage &message, const MEmailMailbox* mailbox) { MEmailMessage* fsMessage = mailbox->CreateDraftMessageL(); CleanupReleasePushL(*fsMessage); switch (message.priority()) { case QMessage::HighPriority: fsMessage->SetFlag(EmailInterface::EFlag_Important); fsMessage->ResetFlag(EmailInterface::EFlag_Low); break; case QMessage::NormalPriority: fsMessage->ResetFlag(EmailInterface::EFlag_Important); fsMessage->ResetFlag(EmailInterface::EFlag_Low); break; case QMessage::LowPriority: fsMessage->SetFlag(EmailInterface::EFlag_Low); fsMessage->ResetFlag(EmailInterface::EFlag_Important); break; } if (message.status() & QMessage::Read) { fsMessage->SetFlag(EmailInterface::EFlag_Read); } else { fsMessage->ResetFlag(EmailInterface::EFlag_Read); } MEmailAddress* sender = mailbox->AddressL(); sender->SetRole(MEmailAddress::ESender); fsMessage->SetReplyToAddressL(*sender); QList<QMessageAddress> toList(message.to()); if (toList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray toAddress; for (int i = 0; i < toList.size(); ++i) { qreceiver = toList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL(); address->SetAddressL(receiver); address->SetDisplayNameL(receiver); address->SetRole(MEmailAddress::ETo); toAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::ETo, toAddress); } QList<QMessageAddress> ccList(message.cc()); if (ccList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray ccAddress; for (int i = 0; i < ccList.size(); ++i) { qreceiver = ccList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL(); address->SetDisplayNameL(receiver); address->SetRole(MEmailAddress::ECc); address->SetAddressL(receiver); ccAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::ECc, ccAddress); } QList<QMessageAddress> bccList(message.bcc()); if (bccList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray bccAddress; for (int i = 0; i < bccList.size(); ++i) { qreceiver = bccList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL(); address->SetDisplayNameL(receiver); address->SetRole(MEmailAddress::EBcc); address->SetAddressL(receiver); bccAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::EBcc, bccAddress); } if (message.bodyId() == QMessageContentContainerPrivate::bodyContentId()) { // Message contains only body (not attachments) QString messageBody = message.textContent(); if (!messageBody.isEmpty()) { QByteArray type = message.contentType(); QByteArray subType = message.contentSubType(); MEmailMessageContent* content = fsMessage->ContentL(); MEmailTextContent* textContent = content->AsTextContentOrNull(); if (textContent) { if (type == "text" && subType == "plain") { textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(message.textContent().utf16()))); } else if (type == "text" && subType == "html") { textContent->SetTextL(MEmailTextContent::EHtmlText, TPtrC(reinterpret_cast<const TUint16*>(message.textContent().utf16()))); } } else fsMessage->SetPlainTextBodyL(TPtrC(reinterpret_cast<const TUint16*>(message.textContent().utf16()))); } } else { // Message contains body and attachments QMessageContentContainerIdList contentIds = message.contentIds(); foreach (QMessageContentContainerId id, contentIds){ QMessageContentContainer container = message.find(id); MEmailMessageContent* content = fsMessage->ContentL(); QMessageContentContainerPrivate* pPrivateContainer = QMessageContentContainerPrivate::implementation(container); if (pPrivateContainer->_id == message.bodyId()) { // ContentContainer is body if (!container.textContent().isEmpty()) { MEmailTextContent* textContent = content->AsTextContentOrNull(); if (textContent) { QByteArray type = container.contentType(); QByteArray subType = container.contentSubType(); if (type == "text" && subType == "plain") { textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16()))); } else if (type == "text" && subType == "html") { textContent->SetTextL(MEmailTextContent::EHtmlText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16()))); } } else fsMessage->SetPlainTextBodyL(TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16()))); } } else { // ContentContainer is attachment QByteArray filePath = QMessageContentContainerPrivate::attachmentFilename(container); // Replace Qt style path separator "/" with Symbian path separator "\" filePath.replace(QByteArray("/"), QByteArray("\\")); QString temp_path = QString(filePath); TPtrC16 attachmentPath(KNullDesC); attachmentPath.Set(reinterpret_cast<const TUint16*>(temp_path.utf16())); fsMessage->AddAttachmentL(attachmentPath); } } } fsMessage->SetSubjectL(TPtrC(reinterpret_cast<const TUint16*>(message.subject().utf16()))); QMessagePrivate* privateMessage = QMessagePrivate::implementation(message); privateMessage->_id = QMessageId(addIdPrefix(QString::number(fsMessage->MessageId().iId),SymbianHelpers::EngineTypeFreestyle)); fsMessage->SaveChangesL(); CleanupStack::Pop(fsMessage); return fsMessage; } bool CFSEngine::addMessage(QMessage* message) { TMailboxId mailboxId(stripIdPrefix(message->parentAccountId().toString()).toInt()); MEmailMailbox* mailbox; TRAPD(mailerr, mailbox = m_clientApi->MailboxL(mailboxId)); if (mailerr != KErrNone) return false; MEmailMessage* fsMessage = NULL; TRAPD(err, fsMessage = createFSMessageL(*message, mailbox)); if (fsMessage) fsMessage->Release(); if (mailbox) mailbox->Release(); if (err != KErrNone) return false; else return true; } bool CFSEngine::updateMessage(QMessage* message) { TRAPD(err, updateMessageL(message)); if (err != KErrNone) return false; else return true; } void CFSEngine::updateMessageL(QMessage* message) { TMailboxId mailboxId(stripIdPrefix(message->parentAccountId().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); CleanupReleasePushL(*mailbox); TMessageId messageId(message->id().toString().toInt(), message->parentFolderId().toString().toInt(), mailboxId); MEmailMessage* fsMessage = mailbox->MessageL(messageId); CleanupReleasePushL(*fsMessage); switch (message->priority()) { case QMessage::HighPriority: fsMessage->SetFlag(EmailInterface::EFlag_Important); fsMessage->ResetFlag(EmailInterface::EFlag_Low); break; case QMessage::NormalPriority: fsMessage->ResetFlag(EmailInterface::EFlag_Important); fsMessage->ResetFlag(EmailInterface::EFlag_Low); break; case QMessage::LowPriority: fsMessage->SetFlag(EmailInterface::EFlag_Low); fsMessage->ResetFlag(EmailInterface::EFlag_Important); break; } if (message->status() & QMessage::Read) { fsMessage->SetFlag(EmailInterface::EFlag_Read); } else { fsMessage->ResetFlag(EmailInterface::EFlag_Read); } MEmailAddress* sender = mailbox->AddressL(); sender->SetRole(MEmailAddress::ESender); fsMessage->SetReplyToAddressL(*sender); QList<QMessageAddress> toList(message->to()); if (toList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray toAddress; for (int i = 0; i < toList.size(); ++i) { qreceiver = toList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL(); address->SetAddressL(receiver); toAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::ETo, toAddress); } QList<QMessageAddress> ccList(message->cc()); if (ccList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray ccAddress; for (int i = 0; i < ccList.size(); ++i) { qreceiver = ccList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL();; address->SetAddressL(receiver); ccAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::ECc, ccAddress); } QList<QMessageAddress> bccList(message->bcc()); if (bccList.count() > 0) { TPtrC16 receiver(KNullDesC); QString qreceiver; REmailAddressArray bccAddress; for (int i = 0; i < bccList.size(); ++i) { qreceiver = bccList.at(i).addressee(); receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16())); MEmailAddress* address = mailbox->AddressL();; address->SetAddressL(receiver); bccAddress.Append(address); } fsMessage->SetRecipientsL(MEmailAddress::EBcc, bccAddress); } if (message->bodyId() == QMessageContentContainerPrivate::bodyContentId()) { // Message contains only body (not attachments) QString messageBody = message->textContent(); if (!messageBody.isEmpty()) { MEmailMessageContent* content = fsMessage->ContentL(); MEmailTextContent* textContent = content->AsTextContentOrNull(); textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(message->textContent().utf16()))); // TODO: } } else { // Message contains body and attachments QMessageContentContainerIdList contentIds = message->contentIds(); foreach (QMessageContentContainerId id, contentIds){ QMessageContentContainer container = message->find(id); QMessageContentContainerPrivate* pPrivateContainer = QMessageContentContainerPrivate::implementation(container); if (pPrivateContainer->_id == message->bodyId()) { // ContentContainer is body if (!container.textContent().isEmpty()) { MEmailMessageContent* content = fsMessage->ContentL(); MEmailTextContent* textContent = content->AsTextContentOrNull(); QByteArray type = container.contentType(); QByteArray subType = container.contentSubType(); if (type == "text" && subType == "plain") { textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16()))); } else if (type == "text" && subType == "html") { textContent->SetTextL(MEmailTextContent::EHtmlText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16()))); } } } else { // ContentContainer is attachment QByteArray filePath = QMessageContentContainerPrivate::attachmentFilename(container); // Replace Qt style path separator "/" with Symbian path separator "\" filePath.replace(QByteArray("/"), QByteArray("\\")); QString temp_path = QString(filePath); TPtrC16 attachmentPath(KNullDesC); attachmentPath.Set(reinterpret_cast<const TUint16*>(temp_path.utf16())); fsMessage->AddAttachmentL(attachmentPath); } } } fsMessage->SetSubjectL(TPtrC(reinterpret_cast<const TUint16*>(message->subject().utf16()))); fsMessage->SaveChangesL(); CleanupStack::PopAndDestroy(fsMessage); CleanupStack::PopAndDestroy(mailbox); } bool CFSEngine::removeMessage(const QMessageId &id, QMessageManager::RemovalOption option) { Q_UNUSED(option); bool retVal = false; foreach (QMessageAccount account, m_accounts) { MEmailMessage* message = NULL; TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); TMessageId messageId( stripIdPrefix(id.toString()).toInt(), 0, mailboxId); TRAPD(err, message = mailbox->MessageL(messageId)); if (err == KErrNone) { TFolderId folderId(message->ParentFolderId()); TRAPD(err2, MEmailFolder* folder = mailbox->FolderL(folderId); REmailMessageIdArray messageIds; messageIds.Append(message->MessageId()); folder->DeleteMessagesL(messageIds); folder->Release(); ); if (err2 == KErrNone) retVal = true; mailbox->Release(); break; // no need to continue } mailbox->Release(); } return retVal; } bool CFSEngine::showMessage(const QMessageId &id) { MEmailMessage* message = NULL; bool retVal = false; foreach (QMessageAccount account, m_accounts) { MEmailMessage* message = NULL; TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); TMessageId messageId( stripIdPrefix(id.toString()).toInt(), 0, mailboxId); TRAPD(err, message = mailbox->MessageL(messageId)); if (err == KErrNone) { TRAPD(err2, message->ShowMessageViewerL()); if (err2 == KErrNone) retVal = true; message->Release(); mailbox->Release(); break; // no need to continue } mailbox->Release(); } return retVal; } bool CFSEngine::composeMessage(const QMessage &message) { bool retVal = false; MEmailMailbox* mailbox; TMailboxId mailboxId(stripIdPrefix(message.parentAccountId().toString()).toInt()); TRAPD(err, mailbox = m_clientApi->MailboxL(mailboxId)); if (err == KErrNone) { TRAPD(err2, mailbox->EditNewMessageL()); if (err2 == KErrNone) retVal = true; mailbox->Release(); } return retVal; } bool CFSEngine::retrieve(const QMessageId &messageId, const QMessageContentContainerId& id) { Q_UNUSED(id); bool retVal = false; foreach (QMessageAccount account, m_accounts) { MEmailMessage* message = NULL; TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); TMessageId mId( stripIdPrefix(messageId.toString()).toInt(), 0, mailboxId); TRAPD(err, message = mailbox->MessageL(mId)); if (err == KErrNone) { MEmailMessageContent* content; TRAPD(contentError, content = message->ContentL()); if (contentError == KErrNone) { MEmailMultipart* mPart = content->AsMultipartOrNull(); for ( int i = 0; i < mPart->PartCountL(); i++) { MEmailAttachment* attContent; TRAPD(attContentErr, attContent = mPart->PartByIndexL(i)->AsAttachmentOrNull()); if (attContent && attContentErr == KErrNone) { TInt availableSize = attContent->AvailableSize(); if (!availableSize) { TRAPD(attErr, attContent->FetchL(*this)); if (attErr == KErrNone) { retVal = true; } } } } } message->Release(); mailbox->Release(); break; // no need to continue } mailbox->Release(); } return retVal; } bool CFSEngine::retrieveBody(const QMessageId& id) { bool retVal = false; foreach (QMessageAccount account, m_accounts) { MEmailMessage* message = NULL; TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); MEmailMailbox* mailbox; TRAPD(mailBoxError, mailbox = m_clientApi->MailboxL(mailboxId)); if (mailBoxError == KErrNone) { TMessageId messageId( stripIdPrefix(id.toString()).toInt(), 0, mailboxId); TRAPD(err, message = mailbox->MessageL(messageId)); if (err == KErrNone) { MEmailMessageContent* content; TRAPD(contentError, content = message->ContentL()); if (contentError == KErrNone) { MEmailTextContent* textContent = content->AsTextContentOrNull(); if (textContent) { TInt availableSize = textContent->AvailableSize(); if (!availableSize) { TRAPD(textErr, textContent->FetchL(*this)); if (textErr == KErrNone) { retVal = true; } } } } message->Release(); mailbox->Release(); break; // no need to continue } mailbox->Release(); } } return retVal; } bool CFSEngine::retrieveHeader(const QMessageId& id) { Q_UNUSED(id); return false; } void CFSEngine::DataFetchedL(const TInt aResult) { Q_UNUSED(aResult); } bool CFSEngine::exportUpdates(const QMessageAccountId &id) { TRAPD(err, exportUpdatesL(id)); if (err != KErrNone) { return false; } else { return true; } } void CFSEngine::exportUpdatesL(const QMessageAccountId &id) { TMailboxId mailboxId(stripIdPrefix(id.toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); mailbox->SynchroniseL(*this); mailbox->Release(); } void CFSEngine::MailboxSynchronisedL(TInt aResult) { Q_UNUSED(aResult); } bool CFSEngine::removeMessages(const QMessageFilter& /*filter*/, QMessageManager::RemovalOption /*option*/) { return false; } void CFSEngine::handleNestedFiltersFromMessageFilter(QMessageFilter &filter) const { QMessageFilterPrivate* pMFFilter = QMessageFilterPrivate::implementation(filter); if (pMFFilter->_filterList.count() > 0) { int filterListCount = pMFFilter->_filterList.count(); for (int i=0; i < filterListCount; i++) { for (int j=0; j < pMFFilter->_filterList[i].count(); j++) { QMessageFilterPrivate* pMFFilter2 = QMessageFilterPrivate::implementation(pMFFilter->_filterList[i][j]); if (pMFFilter2->_field == QMessageFilterPrivate::ParentAccountIdFilter) { QMessageAccountIdList accountIds = queryAccounts(*pMFFilter2->_accountFilter, QMessageAccountSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue)); if (accountIds.count() > 0) { pMFFilter->_filterList[i].removeAt(j); if (cmp == QMessageDataComparator::Includes) { for (int x = 0; x < accountIds.count(); x++) { if (x == 0) { if (x+1 < accountIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[i]); } pMFFilter->_filterList[i].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } else { if (x+1 < accountIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]); pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFilterPrivate::lessThan); } else { pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFilterPrivate::lessThan); } } } } else { // Excludes for (int x = 0; x < accountIds.count(); x++) { pMFFilter->_filterList[i].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::NotEqual)); } qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else { delete pMFFilter2->_accountFilter; pMFFilter2->_accountFilter = 0; pMFFilter2->_field = QMessageFilterPrivate::Id; qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else if (pMFFilter2->_field == QMessageFilterPrivate::ParentFolderIdFilter) { QMessageFolderIdList folderIds = queryFolders(*pMFFilter2->_folderFilter, QMessageFolderSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue)); if (folderIds.count() > 0) { pMFFilter->_filterList[i].removeAt(j); if (cmp == QMessageDataComparator::Includes) { for (int x = 0; x < folderIds.count(); x++) { if (x == 0) { if (x+1 < folderIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[i]); } pMFFilter->_filterList[i].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } else { if (x+1 < folderIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]); pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFilterPrivate::lessThan); } else { pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFilterPrivate::lessThan); } } } } else { // Excludes for (int x = 0; x < folderIds.count(); x++) { pMFFilter->_filterList[i].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::NotEqual)); } qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else { delete pMFFilter2->_folderFilter; pMFFilter2->_folderFilter = 0; pMFFilter2->_field = QMessageFilterPrivate::Id; qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else { break; } } } } else { if (pMFFilter->_field == QMessageFilterPrivate::ParentAccountIdFilter) { QMessageAccountIdList accountIds = queryAccounts(*pMFFilter->_accountFilter, QMessageAccountSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue)); if (accountIds.count() > 0) { for (int i=0; i < accountIds.count(); i++) { if (i == 0) { delete pMFFilter->_accountFilter; pMFFilter->_accountFilter = 0; pMFFilter->_field = QMessageFilterPrivate::ParentAccountId; pMFFilter->_value = accountIds[0].toString(); pMFFilter->_comparatorType = QMessageFilterPrivate::Equality; if (cmp == QMessageDataComparator::Includes) { pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal); } else { // Excludes pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual); } } else { if (cmp == QMessageDataComparator::Includes) { filter |= QMessageFilter::byParentAccountId(accountIds[i],QMessageDataComparator::Equal); } else { // Excludes filter &= QMessageFilter::byParentAccountId(accountIds[i],QMessageDataComparator::NotEqual); } } } } else { delete pMFFilter->_accountFilter; pMFFilter->_accountFilter = 0; pMFFilter->_field = QMessageFilterPrivate::Id; } } else if (pMFFilter->_field == QMessageFilterPrivate::ParentFolderIdFilter) { QMessageFolderIdList folderIds = queryFolders(*pMFFilter->_folderFilter, QMessageFolderSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue)); if (folderIds.count() > 0) { for (int i=0; i < folderIds.count(); i++) { if (i == 0) { delete pMFFilter->_folderFilter; pMFFilter->_folderFilter = 0; pMFFilter->_field = QMessageFilterPrivate::ParentFolderId; pMFFilter->_value = folderIds[0].toString(); pMFFilter->_comparatorType = QMessageFilterPrivate::Equality; if (cmp == QMessageDataComparator::Includes) { pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal); } else { // Excludes pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual); } } else { if (cmp == QMessageDataComparator::Includes) { filter |= QMessageFilter::byParentFolderId(folderIds[i],QMessageDataComparator::Equal); } else { // Excludes filter &= QMessageFilter::byParentFolderId(folderIds[i],QMessageDataComparator::NotEqual); } } } } else { delete pMFFilter->_folderFilter; pMFFilter->_folderFilter = 0; pMFFilter->_field = QMessageFilterPrivate::Id; } } } } bool CFSEngine::queryMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { TRAPD(err, queryMessagesL(privateService, filter, sortOrder, limit, offset)); if (err != KErrNone) { return false; } return true; } void CFSEngine::queryMessagesL(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { FSMessageQueryInfo queryInfo; queryInfo.operationId = ++m_operationIds; if (queryInfo.operationId == 100000) { queryInfo.operationId = 1; } queryInfo.isQuery = true; queryInfo.filter = filter; queryInfo.sortOrder = sortOrder; queryInfo.offset = offset; queryInfo.limit = limit; queryInfo.findOperation = new CFSMessagesFindOperation((CFSEngine&)*this, queryInfo.operationId); queryInfo.privateService = &privateService; queryInfo.currentFilterListIndex = 0; m_messageQueries.append(queryInfo); handleNestedFiltersFromMessageFilter(m_messageQueries[m_messageQueries.count()-1].filter); QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(m_messageQueries[m_messageQueries.count()-1].filter); if (pf->_filterList.count() == 0) { queryInfo.findOperation->filterAndOrderMessages(m_messageQueries[m_messageQueries.count()-1].filter, m_messageQueries[m_messageQueries.count()-1].sortOrder); } else { queryInfo.findOperation->filterAndOrderMessages(pf->_filterList[0], m_messageQueries[m_messageQueries.count()-1].sortOrder); } } bool CFSEngine::queryMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { TRAPD(err, queryMessagesL(privateService, filter, body, matchFlags, sortOrder, limit, offset)); if (err != KErrNone) { return false; } return true; } void CFSEngine::queryMessagesL(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { FSMessageQueryInfo queryInfo; queryInfo.operationId = ++m_operationIds; if (queryInfo.operationId == 100000) { queryInfo.operationId = 1; } queryInfo.isQuery = true; queryInfo.body = body; queryInfo.matchFlags = matchFlags; queryInfo.filter = filter; queryInfo.sortOrder = sortOrder; queryInfo.offset = offset; queryInfo.limit = limit; queryInfo.findOperation = new CFSMessagesFindOperation((CFSEngine&)*this, queryInfo.operationId); queryInfo.privateService = &privateService; queryInfo.currentFilterListIndex = 0; m_messageQueries.append(queryInfo); handleNestedFiltersFromMessageFilter(m_messageQueries[m_messageQueries.count()-1].filter); QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(m_messageQueries[m_messageQueries.count()-1].filter); if (pf->_filterList.count() == 0) { queryInfo.findOperation->filterAndOrderMessages(m_messageQueries[m_messageQueries.count()-1].filter, m_messageQueries[m_messageQueries.count()-1].sortOrder, body, matchFlags); } else { queryInfo.findOperation->filterAndOrderMessages(pf->_filterList[0], m_messageQueries[m_messageQueries.count()-1].sortOrder, body, matchFlags); } } bool CFSEngine::countMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter) { TRAPD(err, countMessagesL(privateService, filter)); if (err != KErrNone) { return false; } return true; } void CFSEngine::countMessagesL(QMessageServicePrivate& privateService, const QMessageFilter &filter) { FSMessageQueryInfo queryInfo; queryInfo.operationId = ++m_operationIds; if (queryInfo.operationId == 100000) { queryInfo.operationId = 1; } queryInfo.isQuery = false; queryInfo.matchFlags = 0; queryInfo.filter = filter; queryInfo.sortOrder = QMessageSortOrder(); queryInfo.offset = 0; queryInfo.limit = 0; queryInfo.findOperation = new CFSMessagesFindOperation((CFSEngine&)*this, queryInfo.operationId); queryInfo.privateService = &privateService; queryInfo.currentFilterListIndex = 0; queryInfo.count = 0; m_messageQueries.append(queryInfo); handleNestedFiltersFromMessageFilter(m_messageQueries[m_messageQueries.count()-1].filter); QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(m_messageQueries[m_messageQueries.count()-1].filter); if (pf->_filterList.count() == 0) { queryInfo.findOperation->filterAndOrderMessages(m_messageQueries[m_messageQueries.count()-1].filter, m_messageQueries[m_messageQueries.count()-1].sortOrder); } else { queryInfo.findOperation->filterAndOrderMessages(pf->_filterList[0], m_messageQueries[m_messageQueries.count()-1].sortOrder); } } void CFSEngine::filterAndOrderMessagesReady(bool success, int operationId, QMessageIdList ids, int numberOfHandledFilters, bool resultSetOrdered) { int index=0; for (; index < m_messageQueries.count(); index++) { if (m_messageQueries[index].operationId == operationId) { break; } } if (success) { // If there are unhandled filters, loop through all filters and do filtering for ids using unhandled filters. QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(m_messageQueries[index].filter); if (pf->_filterList.count() > 0) { if (pf->_filterList[m_messageQueries[index].currentFilterListIndex].count() > numberOfHandledFilters) { for (int i=0; i < ids.count(); i++) { QMessage msg = message(ids[i]); for (int j=numberOfHandledFilters; j < pf->_filterList[m_messageQueries[index].currentFilterListIndex].count(); j++) { QMessageFilterPrivate* pf2 = QMessageFilterPrivate::implementation(pf->_filterList[m_messageQueries[index].currentFilterListIndex][j]); if (!pf2->filter(msg)) { ids.removeAt(i); i--; break; } } } } } if (pf->_filterList.count() > 0) { // Filter contains filterlist (or filterlists), not just one single filter if (m_messageQueries[index].currentFilterListIndex == 0) { m_messageQueries[index].ids << ids; m_messageQueries[index].count = ids.count(); } else { // Append new ids to resultset for (int i=0; i < ids.count(); i++) { if (!m_messageQueries[index].ids.contains(ids[i])) { m_messageQueries[index].ids.append(ids[i]); m_messageQueries[index].count++;; } } } m_messageQueries[index].currentFilterListIndex++; if (m_messageQueries[index].currentFilterListIndex < pf->_filterList.count()) { // There are still unhandled filter lists left m_messageQueries[index].findOperation->filterAndOrderMessages(pf->_filterList[m_messageQueries[index].currentFilterListIndex], m_messageQueries[index].sortOrder, m_messageQueries[index].body, m_messageQueries[index].matchFlags); return; } else { // All filters successfully handled if (m_messageQueries[index].isQuery) { if (!m_messageQueries[index].sortOrder.isEmpty()) { // Make sure that messages are correctly ordered orderMessages(m_messageQueries[index].ids, m_messageQueries[index].sortOrder); } applyOffsetAndLimitToMsgIds(m_messageQueries[index].ids, m_messageQueries[index].offset, m_messageQueries[index].limit); m_messageQueries[index].privateService->messagesFound(m_messageQueries[index].ids, true, true); //emit m_messageQueries[index].privateService->messagesFound(m_messageQueries[index].ids); } else { m_messageQueries[index].privateService->messagesCounted(m_messageQueries[index].count); } } } else { // There was only one single filter to handle if (numberOfHandledFilters == 0) { // The one and only filter was not handled // => Do filtering for all returned messages for (int i=ids.count()-1; i >= 0; i--) { QMessage msg = message(ids[i]); if (!pf->filter(msg)) { ids.removeAt(i); } } } // => All filters successfully handled if (m_messageQueries[index].isQuery) { // Make sure that messages are correctly ordered if (!m_messageQueries[index].sortOrder.isEmpty() && !resultSetOrdered) { orderMessages(ids, m_messageQueries[index].sortOrder); } // Handle offest & limit applyOffsetAndLimitToMsgIds(ids, m_messageQueries[index].offset, m_messageQueries[index].limit); //emit m_messageQueries[index].privateService->messagesFound(ids); m_messageQueries[index].privateService->messagesFound(ids, true, true); } else { m_messageQueries[index].privateService->messagesCounted(ids.count()); } } } else { m_messageQueries[index].privateService->_active = false; if (m_messageQueries[index].privateService->_error == QMessageManager::NoError) { m_messageQueries[index].privateService->_error = QMessageManager::RequestIncomplete; } } delete m_messageQueries[index].findOperation; m_messageQueries.removeAt(index); } void CFSEngine::applyOffsetAndLimitToMsgIds(QMessageIdList& idList, int offset, int limit) const { if (offset > 0) { if (offset > idList.count()) { idList.clear(); } else { for (int i = 0; i < offset; i++) { idList.removeFirst(); } } } if (limit > 0) { for (int i = idList.count()-1; i >= limit; i--) { idList.removeAt(i); } } } QMessageManager::NotificationFilterId CFSEngine::registerNotificationFilter(QMessageStorePrivate& aPrivateStore, const QMessageFilter &filter, QMessageManager::NotificationFilterId aId) { ipMessageStorePrivate = &aPrivateStore; iListenForNotifications = true; int filterId = aId; if (filterId == 0) filterId = ++m_filterId; m_filters.insert(filterId, filter); return filterId; } void CFSEngine::unregisterNotificationFilter(QMessageManager::NotificationFilterId notificationFilterId) { m_filters.remove(notificationFilterId); if (m_filters.count() == 0) { iListenForNotifications = false; } } void CFSEngine::handleNestedFiltersFromFolderFilter(QMessageFolderFilter &filter) const { QMessageFolderFilterPrivate* pMFFilter = QMessageFolderFilterPrivate::implementation(filter); if (pMFFilter->_filterList.count() > 0) { int filterListCount = pMFFilter->_filterList.count(); for (int i=0; i < filterListCount; i++) { for (int j=0; j < pMFFilter->_filterList[i].count(); j++) { QMessageFolderFilterPrivate* pMFFilter2 = QMessageFolderFilterPrivate::implementation(pMFFilter->_filterList[i][j]); if (pMFFilter2->_field == QMessageFolderFilterPrivate::ParentAccountIdFilter) { QMessageAccountIdList accountIds = queryAccounts(*pMFFilter2->_accountFilter, QMessageAccountSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue)); if (accountIds.count() > 0) { pMFFilter->_filterList[i].removeAt(j); if (cmp == QMessageDataComparator::Includes) { for (int x = 0; x < accountIds.count(); x++) { if (x == 0) { if (x+1 < accountIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[i]); } pMFFilter->_filterList[i].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFolderFilterPrivate::lessThan); } else { if (x+1 < accountIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]); pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFolderFilterPrivate::lessThan); } else { pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFolderFilterPrivate::lessThan); } } } } else { // Excludes for (int x = 0; x < accountIds.count(); x++) { pMFFilter->_filterList[i].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::NotEqual)); } qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFolderFilterPrivate::lessThan); } } else { delete pMFFilter2->_accountFilter; pMFFilter2->_accountFilter = 0; pMFFilter2->_field = QMessageFolderFilterPrivate::Id; qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFolderFilterPrivate::lessThan); } } else { break; } } } } else { if (pMFFilter->_field == QMessageFolderFilterPrivate::ParentAccountIdFilter) { QMessageAccountIdList accountIds = queryAccounts(*pMFFilter->_accountFilter, QMessageAccountSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue)); if (accountIds.count() > 0) { for (int i=0; i < accountIds.count(); i++) { if (i == 0) { delete pMFFilter->_accountFilter; pMFFilter->_accountFilter = 0; pMFFilter->_field = QMessageFolderFilterPrivate::ParentAccountId; pMFFilter->_value = accountIds[0].toString(); pMFFilter->_comparatorType = QMessageFolderFilterPrivate::Equality; if (cmp == QMessageDataComparator::Includes) { pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal); } else { // Excludes pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual); } } else { if (cmp == QMessageDataComparator::Includes) { filter |= QMessageFolderFilter::byParentAccountId(accountIds[i],QMessageDataComparator::Equal); } else { // Excludes filter &= QMessageFolderFilter::byParentAccountId(accountIds[i],QMessageDataComparator::NotEqual); } } } } else { delete pMFFilter->_accountFilter; pMFFilter->_accountFilter = 0; pMFFilter->_field = QMessageFolderFilterPrivate::Id; } } } } QMessageFolderIdList CFSEngine::queryFolders(const QMessageFolderFilter &filter, const QMessageFolderSortOrder &sortOrder, uint limit, uint offset) const { QMessageFolderIdList ids; QMessageFolderFilter copyOfFilter = filter; handleNestedFiltersFromFolderFilter(copyOfFilter); QMessageFolderFilterPrivate* pMFFilter = QMessageFolderFilterPrivate::implementation(copyOfFilter); if (pMFFilter->_filterList.count() > 0) { for (int i=0; i < pMFFilter->_filterList.count(); i++) { bool filterHandled; QMessageFolderIdList ids2 = filterMessageFolders(pMFFilter->_filterList[i][0], filterHandled); for (int x=ids2.count()-1; x >= 0; x--) { QMessageFolder mf = folder(ids2[x]); int j = filterHandled ? 1 : 0; for (; j < pMFFilter->_filterList[i].count(); j++) { if (!QMessageFolderFilterPrivate::implementation(pMFFilter->_filterList[i][j])->filter(mf)) { ids2.removeAt(x); break; } } } for (int j=0; j < ids2.count(); j++) { if (!ids.contains(ids2[j])) { ids.append(ids2[j]); } } } } else { bool filterHandled; ids = filterMessageFolders(copyOfFilter, filterHandled); if (!filterHandled) { for (int i=ids.count()-1; i >= 0; i--) { if (!QMessageFolderFilterPrivate::implementation(copyOfFilter)->filter(ids[i])) { ids.removeAt(i); } } } } if (!sortOrder.isEmpty()) { orderFolders(ids, sortOrder); } applyOffsetAndLimitToMsgFolderIds(ids, offset, limit); return ids; } void CFSEngine::applyOffsetAndLimitToMsgFolderIds(QMessageFolderIdList& idList, int offset, int limit) const { if (offset > 0) { if (offset > idList.count()) { idList.clear(); } else { for (int i = 0; i < offset; i++) { idList.removeFirst(); } } } if (limit > 0) { for (int i = idList.count()-1; i >= limit; i--) { idList.removeAt(i); } } } int CFSEngine::countFolders(const QMessageFolderFilter &filter) const { return queryFolders(filter, QMessageFolderSortOrder(), 0, 0).count(); } QMessageFolder CFSEngine::folder(const QMessageFolderId &id) const { //return QMessageFolder(); QMessageFolder folder; TRAPD(err, folder = folderL(id)); Q_UNUSED(err) return folder; } QMessageFolder CFSEngine::folderL(const QMessageFolderId &id) const { QMessageFolder folder; MEmailMailbox* mailbox = NULL; QMessageFolderId parentId; QMessageAccountId accountId; // get account containing folder TRAPD(err, updateEmailAccountsL()); Q_UNUSED(err) foreach (QMessageAccount value, m_accounts) { accountId = value.id(); QMessageFolderIdList ids = folderIdsByAccountIdL(accountId); if (ids.contains(id)) { TMailboxId mailboxId(stripIdPrefix(accountId.toString()).toInt()); mailbox = m_clientApi->MailboxL(mailboxId); CleanupReleasePushL(*mailbox); TFolderId folderId(stripIdPrefix(id.toString()).toInt(), mailbox->MailboxId()); MEmailFolder* emailFolder = mailbox->FolderL(folderId); CleanupReleasePushL(*emailFolder); QString name = QString::fromUtf16(emailFolder->Name().Ptr(), emailFolder->Name().Length()); folder = QMessageFolderPrivate::from(id, accountId, parentId, name, name); CleanupStack::PopAndDestroy(emailFolder); CleanupStack::PopAndDestroy(mailbox); break; } } return folder; } QMessageFolderIdList CFSEngine::filterMessageFolders(const QMessageFolderFilter& filter, bool& filterHandled) const { QMessageFolderIdList ids; TRAPD(err, ids = filterMessageFoldersL(filter, filterHandled)); Q_UNUSED(err) return ids; } QMessageFolderIdList CFSEngine::filterMessageFoldersL(const QMessageFolderFilter& filter, bool& filterHandled) const { filterHandled = false; QMessageFolderIdList ids; if (filter.isEmpty()) { QMessageFolderFilterPrivate* pf = QMessageFolderFilterPrivate::implementation(filter); if (!pf->_notFilter) { ids = allFolders(); } filterHandled = true; } else { QMessageFolderFilterPrivate* pf = QMessageFolderFilterPrivate::implementation(filter); if (!pf->_valid) { return QMessageFolderIdList(); } switch (pf->_field) { case QMessageFolderFilterPrivate::Id: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (pf->_value.toString().length() > QString(SymbianHelpers::mtmPrefix).length()) { bool folderOk = false; MEmailMailbox* mailbox = NULL; MEmailFolder* folder = NULL;; if (fsFolderL(QMessageFolderId(pf->_value.toString()), mailbox, folder)) { folderOk = true; // cleanup folder->Release(); mailbox->Release(); } if (cmp == QMessageDataComparator::Equal) { if (folderOk) { ids.append(QMessageFolderId(pf->_value.toString())); } } else { // NotEqual ids = allFolders(); if (folderOk) { ids.removeOne(QMessageFolderId(pf->_value.toString())); } } } else { if (cmp == QMessageDataComparator::NotEqual) { ids = allFolders(); } } filterHandled = true; } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (pf->_ids.count() > 0) { // QMessageIdList QMessageFolderIdList ids2; for (int i=0; i < pf->_ids.count(); i++) { MEmailMailbox* mailbox = NULL; MEmailFolder* folder = NULL; if (fsFolderL(QMessageFolderId(pf->_ids[i]), mailbox, folder)) { ids2.append(pf->_ids[i]); // cleanup folder->Release(); mailbox->Release(); } } if (cmp == QMessageDataComparator::Includes) { ids << ids2; } else { // Excludes ids = allFolders(); for (int i=0; i < ids2.count(); i++) { ids.removeOne(ids2[i]); } } filterHandled = true; } else { // Empty QMessageIdList as a list if (cmp == QMessageDataComparator::Excludes) { ids = allFolders(); } filterHandled = true; // QMessageFilter /*if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: }*/ } } break; } case QMessageFolderFilterPrivate::Name: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { // TODO: } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes if (pf->_value.toString().isEmpty() || pf->_value.toString().length() == 0) { filterHandled = true; } } } break; } case QMessageFolderFilterPrivate::Path: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { // TODO: } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes if (pf->_value.toString().isEmpty() || pf->_value.toString().length() == 0) { filterHandled = true; } } } break; } case QMessageFolderFilterPrivate::ParentAccountId: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { if (pf->_value.toString().length() > 0) { ids = folderIdsByAccountIdL(QMessageAccountId(pf->_value.toString())); } } else { // NotEqual ids = allFolders(); if (pf->_value.toString().length() > 0) { QMessageFolderIdList ids2 = folderIdsByAccountIdL(QMessageAccountId(pf->_value.toString())); for (int i = 0; i < ids2.count(); i++) { ids.removeOne(ids2[i]); } } } filterHandled = true; } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } break; } case QMessageFolderFilterPrivate::ParentFolderId: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { MEmailMailbox* mailbox = NULL; MEmailFolder* parentFolder = NULL; if (fsFolderL(QMessageFolderId(pf->_value.toString()), mailbox, parentFolder)) { CleanupReleasePushL(*mailbox); CleanupReleasePushL(*parentFolder); RFolderArray subfolders; parentFolder->GetSubfoldersL(subfolders); CleanupClosePushL(subfolders); for(TInt i=0; i < subfolders.Count(); i++) { MEmailFolder *subFolder = subfolders[i]; ids.append(QMessageFolderId(addIdPrefix( QString::number(subFolder->FolderId().iId), SymbianHelpers::EngineTypeFreestyle))); subFolder->Release(); } CleanupStack::PopAndDestroy(&subfolders); CleanupStack::PopAndDestroy(parentFolder); CleanupStack::PopAndDestroy(mailbox); } } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } break; } case QMessageFolderFilterPrivate::AncestorFolderIds: { if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (!pf->_value.isNull()) { // QMessageFolderId if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } else { // QMessageFolderFilter if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } } break; } case QMessageFolderFilterPrivate::ParentAccountIdFilter: case QMessageFolderFilterPrivate::None: break; } } if (!filterHandled) { ids = allFolders(); } return ids; } QMessageFolderIdList CFSEngine::allFolders() const { QMessageFolderIdList ids; TRAPD(err, updateEmailAccountsL()); Q_UNUSED(err) foreach (QMessageAccount value, m_accounts) { QMessageFolderIdList ids2 = folderIdsByAccountId(value.id()); ids << ids2; } return ids; } QMessageFolderIdList CFSEngine::folderIdsByAccountId(const QMessageAccountId& accountId) const { QMessageFolderIdList idList; TRAPD(err, idList << folderIdsByAccountIdL(accountId)) Q_UNUSED(err); return idList; } QMessageFolderIdList CFSEngine::folderIdsByAccountIdL(const QMessageAccountId& accountId) const { QMessageFolderIdList folderIds; if (idType(accountId) != EngineTypeFreestyle) return QMessageFolderIdList(); QMessageAccount messageAccount = account(accountId); TMailboxId mailboxId(stripIdPrefix(accountId.toString()).toInt()); MEmailMailbox* mailbox = NULL; mailbox = m_clientApi->MailboxL(mailboxId); if (mailbox == NULL) return QMessageFolderIdList(); CleanupReleasePushL(*mailbox); RFolderArray folders; mailbox->GetFoldersL(folders); CleanupClosePushL(folders); for(TInt i=0; i < folders.Count(); i++) { MEmailFolder *mailFolder = folders[i]; QString fsIdAsString = addIdPrefix(QString::number(mailFolder->FolderId().iId), SymbianHelpers::EngineTypeFreestyle); folderIds.append(QMessageFolderId(fsIdAsString)); //TODO: Support for subfolders? mailFolder->Release(); } CleanupStack::PopAndDestroy(&folders); CleanupStack::PopAndDestroy(mailbox); return folderIds; } bool CFSEngine::fsFolderL(const QMessageFolderId& id, MEmailMailbox* mailbox, MEmailFolder* folder) const { MEmailFolder* fsFolder = NULL; foreach (QMessageAccount account, m_accounts) { TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); mailbox = m_clientApi->MailboxL(mailboxId); TFolderId folderId( stripIdPrefix(id.toString()).toInt(), mailboxId); TRAPD(err, folder = mailbox->FolderL(folderId)); if (err == KErrNone) { CleanupReleasePushL(*fsFolder); return true; } mailbox->Release(); } mailbox = NULL; folder = NULL; return false; } QMessage CFSEngine::message(const QMessageId& id) const { QMessage message = QMessage(); TRAPD(err, message = messageL(id)); Q_UNUSED(err); return message; } QMessage CFSEngine::messageL(const QMessageId& id) const { QMessage message = QMessage(); foreach (QMessageAccount account, m_accounts) { TMailboxId mailboxId(stripIdPrefix(account.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); CleanupReleasePushL(*mailbox); TMessageId messageId( stripIdPrefix(id.toString()).toInt(), 0, //stripIdPrefix(folderId.toString()).toInt(), mailboxId); MEmailMessage* fsMessage = NULL; TRAPD(err, fsMessage = mailbox->MessageL(messageId)); if (err == KErrNone) { CleanupReleasePushL(*fsMessage); message = CreateQMessageL(fsMessage); QMessagePrivate* privateMessage = QMessagePrivate::implementation(message); privateMessage->_id = id; privateMessage->_modified = false; CleanupStack::PopAndDestroy(fsMessage); CleanupStack::PopAndDestroy(mailbox); return message; } CleanupStack::PopAndDestroy(mailbox); } return message; } bool CFSEngine::sendEmail(QMessage &message) { TMailboxId mailboxId(stripIdPrefix(message.parentAccountId().toString()).toInt()); MEmailMailbox* mailbox; TRAPD(mailerr, mailbox = m_clientApi->MailboxL(mailboxId)); MEmailMessage* fsMessage; TRAPD(err, fsMessage = createFSMessageL(message, mailbox); fsMessage->SaveChangesL(); fsMessage->SendL(); ); if (fsMessage) fsMessage->Release(); if (mailbox) mailbox->Release(); if (err != KErrNone) return false; else return true; } QMessage CFSEngine::CreateQMessageL(MEmailMessage* aMessage) const { QMessage message; int size = 0; message.setType(QMessage::Email); message.setDate(symbianTTimetoQDateTime(aMessage->Date())); message.setReceivedDate(symbianTTimetoQDateTime(aMessage->Date())); const TFolderId& folderId = aMessage->ParentFolderId(); TMailboxId mailboxId = folderId.iMailboxId; const QMessageAccountId accountId = QMessageAccountId(QString::number(mailboxId.iId)); message.setParentAccountId(accountId); QMessagePrivate* privateMessage = QMessagePrivate::implementation(message); privateMessage->_parentFolderId = QMessageFolderId(QString::number(folderId.iId)); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); MEmailFolder* folder = mailbox->FolderL(folderId); QMessagePrivate::setStandardFolder(message, QMessage::InboxFolder); if (folder->FolderType() == EDrafts) { QMessagePrivate::setStandardFolder(message, QMessage::DraftsFolder); } else if (folder->FolderType() == EDeleted) { QMessagePrivate::setStandardFolder(message, QMessage::TrashFolder); } else if (folder->FolderType() == ESent) { QMessagePrivate::setStandardFolder(message, QMessage::SentFolder); } folder->Release(); mailbox->Release(); if (aMessage->Flags() & EFlag_Read) { privateMessage->_status = privateMessage->_status | QMessage::Read; } if (aMessage->Flags() & EFlag_Important) { message.setPriority(QMessage::HighPriority); } else if (aMessage->Flags() & EFlag_Low) { message.setPriority(QMessage::LowPriority); } else { message.setPriority(QMessage::NormalPriority); } // bodytext and attachment(s) MEmailMessageContent* content = aMessage->ContentL(); if (content) { AddContentToMessage(content, &message); } REmailAttachmentArray attachments; CleanupResetAndRelease<MEmailAttachment>::PushL(attachments); TInt count = aMessage->GetAttachmentsL(attachments); if (count > 0) privateMessage->_status = privateMessage->_status | QMessage::HasAttachments; for(TInt i = 0; i < count; i++) { TInt availableSize = attachments[i]->AvailableSize(); QByteArray name = QString::fromUtf16(attachments[i]->FileNameL().Ptr(), attachments[i]->FileNameL().Length()).toLocal8Bit(); QByteArray mimeType; // TODO: atts[i]->ContentType() is empty QByteArray mimeSubType; // TODO; int size = attachments[i]->TotalSize(); QMessageContentContainer attachment = QMessageContentContainerPrivate::from( aMessage->MessageId().iId, attachments[i]->Id().iId, name, mimeType, mimeSubType, size); addAttachmentToMessage(message, attachment); } CleanupStack::PopAndDestroy(); attachments.Close(); //from /* TPtrC from = aMessage->SenderAddressL()->Address(); if (from.Length() > 0) { message.setFrom(QMessageAddress(QMessageAddress::Email, QString::fromUtf16(from.Ptr(), from.Length()))); QMessagePrivate::setSenderName(message, QString::fromUtf16(from.Ptr(), from.Length())); }*/ //to REmailAddressArray toRecipients; CleanupResetAndRelease<MEmailAddress>::PushL(toRecipients); aMessage->GetRecipientsL(MEmailAddress::ETo, toRecipients); QList<QMessageAddress> toList; for(TInt i = 0; i < toRecipients.Count(); i++) { TPtrC to = toRecipients[i]->Address(); toList.append(QMessageAddress(QMessageAddress::Email, QString::fromUtf16(to.Ptr(), to.Length()))); } message.setTo(toList); CleanupStack::PopAndDestroy(&toRecipients); toRecipients.Close(); //cc REmailAddressArray ccRecipients; CleanupResetAndRelease<MEmailAddress>::PushL(ccRecipients); aMessage->GetRecipientsL(MEmailAddress::ECc, ccRecipients); QList<QMessageAddress> ccList; for(TInt i = 0; i < ccRecipients.Count(); i++) { TPtrC cc = ccRecipients[i]->Address(); ccList.append(QMessageAddress(QMessageAddress::Email, QString::fromUtf16(cc.Ptr(), cc.Length()))); } message.setCc(ccList); CleanupStack::PopAndDestroy(&ccRecipients); ccRecipients.Close(); //bcc REmailAddressArray bccRecipients; CleanupResetAndRelease<MEmailAddress>::PushL(bccRecipients); aMessage->GetRecipientsL(MEmailAddress::EBcc, bccRecipients); QList<QMessageAddress> bccList; for(TInt i = 0; i < bccRecipients.Count(); i++) { TPtrC bcc = bccRecipients[i]->Address(); bccList.append(QMessageAddress(QMessageAddress::Email, QString::fromUtf16(bcc.Ptr(), bcc.Length()))); } message.setBcc(bccList); CleanupStack::PopAndDestroy(&bccRecipients); bccRecipients.Close(); // Read message subject TPtrC subject = aMessage->Subject(); if (subject.Length() > 0) { message.setSubject(QString::fromUtf16(subject.Ptr(), subject.Length())); } // TODO: size privateMessage->_size = size; return message; } void CFSEngine::AddContentToMessage(MEmailMessageContent* aContent, QMessage* aMessage) const { MEmailMultipart* mPart = aContent->AsMultipartOrNull(); if (mPart) { TInt partCount = 0; TRAPD(err, partCount = mPart->PartCountL()); if (err == KErrNone) { for (TInt i = 0; i < partCount-1; i++) { MEmailMessageContent* content = NULL; TRAPD(err2, content = mPart->PartByIndexL(i)); if (err2 == KErrNone) { AddContentToMessage(content, aMessage); content->Release(); } } } return; } MEmailTextContent* textContent = aContent->AsTextContentOrNull(); if (textContent) { TInt availableSize = textContent->AvailableSize(); TRAPD(err, TPtrC body = textContent->ContentL(); QString text = QString::fromUtf16(body.Ptr(), body.Length()); if (textContent->TextType() == MEmailTextContent::EPlainText) { aMessage->setBody(text, "text/plain"); } else if (textContent->TextType() == MEmailTextContent::EHtmlText) { aMessage->setBody(text, "text/html"); } ); Q_UNUSED(err); return; } } void CFSEngine::addAttachmentToMessage(QMessage& message, QMessageContentContainer& attachment) const { QMessagePrivate* privateMessage = QMessagePrivate::implementation(message); QMessageContentContainerPrivate* container = QMessagePrivate::containerImplementation(message); if (container->_attachments.isEmpty()) { QMessageContentContainerId existingBodyId(message.bodyId()); if (existingBodyId == QMessageContentContainerPrivate::bodyContentId()) { // The body content is in the message itself - move it to become the first attachment QMessageContentContainer newBody(message); QMessageContentContainerPrivate::implementation(newBody)->setDerivedMessage(0); container->setContentType("multipart", "mixed", ""); privateMessage->_bodyId = container->prependContent(newBody); } else { // This message is now multipart container->setContentType("multipart", "mixed", ""); } container->_available = true; } container->appendContent(attachment); bool haveAttachments = !container->_attachments.isEmpty(); message.setStatus(QMessage::HasAttachments,haveAttachments); privateMessage->_modified = true; } QDateTime CFSEngine::symbianTTimetoQDateTime(const TTime& time) const { TDateTime dateTime = time.DateTime(); QDate qdate = QDate(dateTime.Year(), static_cast<int>(dateTime.Month())+1, dateTime.Day()+1); QTime qtime = QTime(dateTime.Hour(), dateTime.Minute(), dateTime.Second(), dateTime.MicroSecond()/1000 ); return QDateTime(qdate, qtime, Qt::UTC); } TTime CFSEngine::qDateTimeToSymbianTTime(const QDateTime& date) const { TDateTime dateTime; dateTime.SetYear(date.date().year()); dateTime.SetMonth(static_cast<TMonth>(date.date().month()-1)); dateTime.SetDay(date.date().day()-1); dateTime.SetHour(date.time().hour()); dateTime.SetMinute(date.time().minute()); dateTime.SetSecond(date.time().second()); dateTime.SetMicroSecond(date.time().msec()*1000); return TTime(dateTime); } TFolderType CFSEngine::standardFolderId(QMessage::StandardFolder standardFolder) { switch(standardFolder) { case QMessage::InboxFolder: return EInbox; case QMessage::OutboxFolder: return EOutbox; case QMessage::DraftsFolder: return EDrafts; case QMessage::SentFolder: return ESent; case QMessage::TrashFolder: return EDeleted; default: return EOther; } } CFSMessagesFindOperation::CFSMessagesFindOperation(CFSEngine& aOwner, int aOperationId) : m_owner(aOwner), m_operationId(aOperationId), m_resultCorrectlyOrdered(false), m_receiveNewMessages(false), m_activeSearchCount(0), m_searchField(None) { TRAPD(err, m_factory = CEmailInterfaceFactory::NewL(); m_interfacePtr = m_factory->InterfaceL(KEmailClientApiInterface); m_clientApi = static_cast<MEmailClientApi*>(m_interfacePtr); ); } CFSMessagesFindOperation::~CFSMessagesFindOperation() { foreach(FSSearchOperation operation, m_searchOperations) { operation.m_search->Release(); operation.m_mailbox->Release(); } m_receiveNewMessages = false; m_clientApi->Release(); delete m_factory; } void CFSMessagesFindOperation::filterAndOrderMessages(const QMessageFilter &filter, const QMessageSortOrder& sortOrder, QString body, QMessageDataComparator::MatchFlags matchFlags) { m_filterList.clear(); m_filterList.append(filter); filterAndOrderMessages(m_filterList, sortOrder, body, matchFlags); } void CFSMessagesFindOperation::filterAndOrderMessages(const QMessageFilterPrivate::SortedMessageFilterList& filters, const QMessageSortOrder& sortOrder, QString body, QMessageDataComparator::MatchFlags matchFlags) { TRAPD(err, filterAndOrderMessagesL(filters, sortOrder, body, matchFlags)); if (err != KErrNone) { //something has failed -> return empty list m_idList = QMessageIdList(); QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } } void CFSMessagesFindOperation::filterAndOrderMessagesL(const QMessageFilterPrivate::SortedMessageFilterList& filters, const QMessageSortOrder& sortOrder, QString body, QMessageDataComparator::MatchFlags matchFlags) { m_numberOfHandledFilters = 0; TEmailSortCriteria sortCriteria = TEmailSortCriteria(); m_excludeIdList = QMessageIdList(); m_matchFlags = matchFlags; if (filters.count() == 0) { m_idList = QMessageIdList(); QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); return; } QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(filters[m_numberOfHandledFilters]); // Set sortOrder if (!sortOrder.isEmpty() ) { QMessageSortOrderPrivate* privateMessageOrdering = QMessageSortOrderPrivate::implementation(sortOrder); QPair<QMessageSortOrderPrivate::Field, Qt::SortOrder> fieldOrder = privateMessageOrdering->_fieldOrderList.at(0); switch (fieldOrder.first) { case QMessageSortOrderPrivate::Type: break; case QMessageSortOrderPrivate::Sender: sortCriteria.iField = TEmailSortCriteria::EBySender; break; case QMessageSortOrderPrivate::Recipients: sortCriteria.iField = TEmailSortCriteria::EByRecipient; break; case QMessageSortOrderPrivate::Subject: sortCriteria.iField = TEmailSortCriteria::EBySubject; break; case QMessageSortOrderPrivate::TimeStamp: sortCriteria.iField = TEmailSortCriteria::EByDate; break; case QMessageSortOrderPrivate::ReceptionTimeStamp: sortCriteria.iField = TEmailSortCriteria::EBySender; break; case QMessageSortOrderPrivate::Read: sortCriteria.iField = TEmailSortCriteria::EByUnread; break; case QMessageSortOrderPrivate::HasAttachments: sortCriteria.iField = TEmailSortCriteria::EByAttachment; break; case QMessageSortOrderPrivate::Incoming: //TODO: break; case QMessageSortOrderPrivate::Removed: //TODO: break; case QMessageSortOrderPrivate::Priority: sortCriteria.iField = TEmailSortCriteria::EByPriority; break; case QMessageSortOrderPrivate::Size: sortCriteria.iField = TEmailSortCriteria::EBySize; break; } sortCriteria.iAscending = fieldOrder.second == Qt::AscendingOrder?true:false; } if ((filters.count() == 1) && (pf->_field == QMessageFilterPrivate::None) && (pf->_filterList.count() == 0)) { if (pf->_notFilter) { // There is only one filter: empty ~QMessageFilter() // => return empty QMessageIdList m_idList = QMessageIdList(); QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } else { // There is only one filter: empty QMessageFilter() // => return all messages getAllMessagesL(sortCriteria); } m_numberOfHandledFilters++; return; } if (!body.isEmpty()) { m_searchField = Body; m_searchKey = body; } switch (pf->_field) { case QMessageFilterPrivate::ParentFolderId: { if (idType(pf->_value.toString()) != EngineTypeFreestyle) { QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); return; } if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessageFolderId QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { m_numberOfHandledFilters++; QMessageFolder messageFolder = m_owner.folder(QMessageFolderId(pf->_value.toString())); getFolderSpecificMessagesL(messageFolder, sortCriteria); m_resultCorrectlyOrdered = true; QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { // QMessageFolderFilter QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } break; } case QMessageFilterPrivate::Id: { if (idType(pf->_value.toString()) != EngineTypeFreestyle) { QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); return; } m_numberOfHandledFilters++; if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessageId QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (!pf->_value.isNull() && pf->_value.toString().length() > QString(SymbianHelpers::freestylePrefix).length()) { if (cmp == QMessageDataComparator::Equal) { QMessage message = m_owner.message(QMessageId(pf->_value.toString())); m_idList.clear(); m_idList.append(message.id()); m_resultCorrectlyOrdered = true; QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } else { // NotEqual m_excludeIdList.clear(); m_excludeIdList.append(QMessageId(pf->_value.toString())); getAllMessagesL(sortCriteria); } } else { if (cmp == QMessageDataComparator::NotEqual) { getAllMessagesL(sortCriteria); } } } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (pf->_ids.count() > 0) { // QMessageIdList if (cmp == QMessageDataComparator::Includes) { for (int i=0; i < pf->_ids.count(); i++) { QMessage message = m_owner.message(QMessageId(pf->_ids[i].toString())); m_idList.append(message.id()); } QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } else { // Excludes for (int i=0; i < pf->_ids.count(); i++) { m_excludeIdList.clear(); m_excludeIdList.append(QMessageId(pf->_ids[i].toString())); getAllMessagesL(sortCriteria); } getAllMessagesL(sortCriteria); } } else { //ipEntrySelection = new(ELeave)CMsvEntrySelection; if (cmp == QMessageDataComparator::Excludes) { getAllMessagesL(sortCriteria); } /*// QMessageFilter if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: }*/ } } break; } case QMessageFilterPrivate::ParentAccountId: { if (idType(pf->_value.toString()) != EngineTypeFreestyle) { QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); return; } if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessageAccountId m_numberOfHandledFilters++; QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { QMessageAccount messageAccount = m_owner.account(pf->_value.toString()); getAccountSpecificMessagesL(messageAccount, sortCriteria); m_resultCorrectlyOrdered = true; } else { // NotEqual QStringList exludedAccounts; exludedAccounts << pf->_value.toString(); QMessageFilterPrivate* privateFilter = NULL; for (int i=m_numberOfHandledFilters; i < filters.count(); i++) { privateFilter = QMessageFilterPrivate::implementation(filters[i]); if (privateFilter->_field == QMessageFilterPrivate::ParentAccountId && privateFilter->_comparatorType == QMessageFilterPrivate::Equality) { cmp = static_cast<QMessageDataComparator::EqualityComparator>(privateFilter->_comparatorValue); if (cmp == QMessageDataComparator::NotEqual) { exludedAccounts << privateFilter->_value.toString(); m_numberOfHandledFilters++; } else { break; } } else { break; } } privateFilter = NULL; if (filters.count() > m_numberOfHandledFilters) { privateFilter = QMessageFilterPrivate::implementation(filters[m_numberOfHandledFilters]); if (privateFilter->_field == QMessageFilterPrivate::StandardFolder && privateFilter->_comparatorType == QMessageFilterPrivate::Equality) { cmp = static_cast<QMessageDataComparator::EqualityComparator>(privateFilter->_comparatorValue); if (cmp == QMessageDataComparator::Equal) { m_numberOfHandledFilters++; } } else { privateFilter = NULL; } } foreach (QMessageAccount value, m_owner.m_accounts) { if (!exludedAccounts.contains(value.id().toString())) { getAccountSpecificMessagesL(value, sortCriteria); } } } } break; } case QMessageFilterPrivate::AncestorFolderIds: { m_numberOfHandledFilters++; if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (!pf->_value.isNull()) { // QMessageFolderId if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } else { // QMessageFolderFilter if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } } break; } case QMessageFilterPrivate::Type: { m_numberOfHandledFilters++; QMessageFilterPrivate* privateFilter = NULL; // Check if next filter is StandardFolder filter if (filters.count() > m_numberOfHandledFilters) { privateFilter = QMessageFilterPrivate::implementation(filters[m_numberOfHandledFilters]); if (privateFilter->_field != QMessageFilterPrivate::StandardFolder) { privateFilter = NULL; } else { m_numberOfHandledFilters++; } } if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessage::Type QMessage::Type type = static_cast<QMessage::Type>(pf->_value.toInt()); QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { QMessageAccountIdList accountIds = m_owner.accountsByType(type); for (int i = 0; i < accountIds.count(); i++) { QMessageAccount messageAccount = m_owner.account(accountIds[i]); getAccountSpecificMessagesL(messageAccount, sortCriteria); } } else { // NotEqual foreach (QMessageAccount value, m_owner.m_accounts) { if (!(value.messageTypes() & type)) { getAccountSpecificMessagesL(value, sortCriteria); } } } } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { // QMessage::TypeFlags QMessage::TypeFlags typeFlags = static_cast<QMessage::TypeFlags>(pf->_value.toInt()); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { foreach (QMessageAccount value, m_owner.m_accounts) { if (value.messageTypes() | typeFlags) { getAccountSpecificMessagesL(value, sortCriteria); } } } else { // Excludes foreach (QMessageAccount value, m_owner.m_accounts) { if (!(value.messageTypes() & typeFlags)) { getAccountSpecificMessagesL(value, sortCriteria); } } } } break; } case QMessageFilterPrivate::StandardFolder: { m_numberOfHandledFilters++; QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); QMessage::StandardFolder standardFolder = static_cast<QMessage::StandardFolder>(pf->_value.toInt()); TFolderType stdFolder = m_owner.standardFolderId(standardFolder); if (cmp == QMessageDataComparator::Equal) { foreach (QMessageAccount messageAccount, m_owner.m_accounts) { TMailboxId mailboxId(stripIdPrefix(messageAccount.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); CleanupReleasePushL(*mailbox); MEmailFolder* folder = mailbox->FolderByTypeL(stdFolder); CleanupReleasePushL(*folder); QMessageFolder standardFolder = m_owner.folder( QMessageFolderId(QString::number(folder->FolderId().iId))); getFolderSpecificMessagesL(standardFolder, sortCriteria); m_activeSearchCount++; CleanupStack::PopAndDestroy(folder); CleanupStack::PopAndDestroy(mailbox); } m_resultCorrectlyOrdered = true; QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } else { // NotEqual foreach (QMessageAccount messageAccount, m_owner.m_accounts) { TMailboxId mailboxId(stripIdPrefix(messageAccount.id().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId); CleanupReleasePushL(*mailbox); QMessage::StandardFolder i = QMessage::InboxFolder; while (i <= QMessage::TrashFolder) { if (i != standardFolder) { MEmailFolder* folder = mailbox->FolderByTypeL(m_owner.standardFolderId(i)); CleanupReleasePushL(*folder); QMessageFolder standardFolder = m_owner.folder( QMessageFolderId(QString::number(folder->FolderId().iId))); getFolderSpecificMessagesL(standardFolder, sortCriteria); CleanupStack::PopAndDestroy(folder); } i = static_cast<QMessage::StandardFolder>(static_cast<int>(i) + 1); } CleanupStack::PopAndDestroy(mailbox); } QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } break; } case QMessageFilterPrivate::Sender: case QMessageFilterPrivate::Recipients: case QMessageFilterPrivate::Subject: case QMessageFilterPrivate::Status: case QMessageFilterPrivate::Priority: case QMessageFilterPrivate::Size: case QMessageFilterPrivate::ParentAccountIdFilter: case QMessageFilterPrivate::ParentFolderIdFilter: case QMessageFilterPrivate::TimeStamp: case QMessageFilterPrivate::ReceptionTimeStamp: case QMessageFilterPrivate::None: default: break; } if (body.isEmpty()) { if (m_numberOfHandledFilters < filters.count()) { pf = QMessageFilterPrivate::implementation(filters[m_numberOfHandledFilters]); switch (pf->_field) { case QMessageFilterPrivate::Sender: { m_searchField = Sender; if (pf->_comparatorType == QMessageFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { if (pf->_value.toString().length() > 0) { m_searchKey = pf->_value.toString(); m_numberOfHandledFilters++; } } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } break; } case QMessageFilterPrivate::Recipients: { m_searchField = Recipients; if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { if (pf->_value.toString().length() > 0) { m_searchKey = pf->_value.toString(); m_numberOfHandledFilters++; } } else { // Excludes //TODO: } } break; } case QMessageFilterPrivate::Subject: { m_searchField = Subject; if (pf->_comparatorType == QMessageFilterPrivate::Equality) { QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Equal) { if (pf->_value.toString().length() > 0) { m_searchKey = pf->_value.toString(); m_numberOfHandledFilters++; } } else { // NotEqual // TODO: } } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue)); if (cmp == QMessageDataComparator::Includes) { // TODO: } else { // Excludes // TODO: } } break; } case QMessageFilterPrivate::TimeStamp: case QMessageFilterPrivate::ReceptionTimeStamp: case QMessageFilterPrivate::Status: case QMessageFilterPrivate::Priority: case QMessageFilterPrivate::Size: case QMessageFilterPrivate::ParentAccountIdFilter: case QMessageFilterPrivate::ParentFolderIdFilter: case QMessageFilterPrivate::Id: case QMessageFilterPrivate::ParentFolderId: case QMessageFilterPrivate::AncestorFolderIds: case QMessageFilterPrivate::ParentAccountId: case QMessageFilterPrivate::Type: case QMessageFilterPrivate::StandardFolder: case QMessageFilterPrivate::None: default: break; } if (m_activeSearchCount == 0) getAllMessagesL(sortCriteria); } } if (m_activeSearchCount == 0) QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } void CFSMessagesFindOperation::getAllMessagesL(TEmailSortCriteria& sortCriteria) { // Get all messages from every known account foreach (QMessageAccount value, m_owner.m_accounts) { getAccountSpecificMessagesL(value, sortCriteria); } } void CFSMessagesFindOperation::getAccountSpecificMessagesL(QMessageAccount& messageAccount, TEmailSortCriteria& sortCriteria) { TMailboxId mailboxId(stripIdPrefix(messageAccount.id().toString()).toInt()); FSSearchOperation operation; operation.m_mailbox = m_clientApi->MailboxL(mailboxId); operation.m_search = operation.m_mailbox->MessageSearchL(); operation.m_search->AddSearchKeyL(_L("*")); operation.m_search->SetSortCriteriaL( sortCriteria ); operation.m_search->StartSearchL( *this ); // this implements MEmailSearchObserver m_activeSearchCount++; m_searchOperations.append(operation); } void CFSMessagesFindOperation::getFolderSpecificMessagesL(QMessageFolder& messageFolder, TEmailSortCriteria sortCriteria) { m_activeSearchCount++; RSortCriteriaArray sortCriteriaArray; CleanupClosePushL(sortCriteriaArray); TFolderId folderId(stripIdPrefix(messageFolder.id().toString()).toInt(), stripIdPrefix(messageFolder.parentAccountId().toString()).toInt()); MEmailMailbox* mailbox = m_clientApi->MailboxL(stripIdPrefix(messageFolder.parentAccountId().toString()).toInt()); CleanupReleasePushL(*mailbox); MEmailFolder *mailFolder = mailbox->FolderL(folderId); CleanupReleasePushL(*mailFolder); sortCriteriaArray.Append(sortCriteria); MMessageIterator* msgIterator = mailFolder->MessagesL(sortCriteriaArray); CleanupReleasePushL(*msgIterator); MEmailMessage* msg = NULL; while ( NULL != (msg = msgIterator->NextL())) { QMessageId messageId(addIdPrefix(QString::number(msg->MessageId().iId), SymbianHelpers::EngineTypeFreestyle)); if (!m_excludeIdList.contains(messageId)) { m_idList.append(messageId); } msg->Release(); } CleanupStack::PopAndDestroy(msgIterator); CleanupStack::PopAndDestroy(mailFolder); CleanupStack::PopAndDestroy(mailbox); CleanupStack::PopAndDestroy(&sortCriteriaArray); } void CFSMessagesFindOperation::HandleResultL(MEmailMessage* aMessage) { QMessageId messageId(addIdPrefix(QString::number(aMessage->MessageId().iId), SymbianHelpers::EngineTypeFreestyle)); if (!m_excludeIdList.contains(messageId)) { m_idList.append(messageId); } aMessage->Release(); } void CFSMessagesFindOperation::SearchCompletedL() { if (m_receiveNewMessages) { m_receiveNewMessages = false; } else { m_activeSearchCount--; if (m_activeSearchCount <= 0) { QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection); } } } void CFSMessagesFindOperation::SearchCompleted() { if (m_searchField != None) { QMessageIdList idList; foreach (QMessageId messageId, m_idList) { if (fillsSearchKeyCriteria(messageId)) idList.append(messageId); } m_idList = idList; } m_owner.filterAndOrderMessagesReady(true, m_operationId, m_idList, 1, m_resultCorrectlyOrdered); } bool CFSMessagesFindOperation::fillsSearchKeyCriteria(QMessageId& messageId) { QMessage message = m_owner.message(messageId); Qt::CaseSensitivity caseSensitivity = (m_matchFlags & QMessageDataComparator::MatchCaseSensitive) ? Qt::CaseSensitive:Qt::CaseInsensitive; switch (m_searchField) { case Sender: { return message.from().addressee().contains(m_searchKey, caseSensitivity); break; } case Recipients: { foreach (QMessageAddress toRecipient, message.to()) { if (toRecipient.addressee().contains(m_searchKey, caseSensitivity)) return true; } foreach (QMessageAddress ccRecipient, message.cc()) { if (ccRecipient.addressee().contains(m_searchKey, caseSensitivity)) return true; } foreach (QMessageAddress bccRecipient, message.bcc()) { if (bccRecipient.addressee().contains(m_searchKey, caseSensitivity)) return true; } return false; break; } case Subject: { return message.subject().contains(m_searchKey, caseSensitivity); break; } case Body: { if (message.bodyId() == QMessageContentContainerPrivate::bodyContentId()) { // Message contains only body (not attachments) QString messageBody = message.textContent(); return messageBody.contains(m_searchKey, caseSensitivity); } else { // Message contains body and attachments QMessageContentContainerIdList contentIds = message.contentIds(); foreach (QMessageContentContainerId id, contentIds){ QMessageContentContainer container = message.find(id); QMessageContentContainerPrivate* pPrivateContainer = QMessageContentContainerPrivate::implementation(container); if (pPrivateContainer->_id == message.bodyId()) { // ContentContainer is body return container.textContent().contains(m_searchKey, caseSensitivity); } } } break; } default: break; } return false; } #include "..\..\build\Release\QtMessaging\moc\moc_qfsengine_symbian_p.cpp"; QTM_END_NAMESPACE
#include "wled.h" /* * Infrared sensor support for generic 24/40/44 key RGB remotes */ #if defined(WLED_DISABLE_INFRARED) void handleIR(){} #else IRrecv* irrecv; //change pin in NpbWrapper.h decode_results results; unsigned long irCheckedTime = 0; uint32_t lastValidCode = 0; byte lastRepeatableAction = ACTION_NONE; uint8_t lastRepeatableValue = 0; uint16_t irTimesRepeated = 0; uint8_t lastIR6ColourIdx = 0; // brightnessSteps: a static array of brightness levels following a geometric // progression. Can be generated from the following Python, adjusting the // arbitrary 4.5 value to taste: // // def values(level): // while level >= 5: // yield int(level) // level -= level / 4.5 // result = [v for v in reversed(list(values(255)))] // print("%d values: %s" % (len(result), result)) // // It would be hard to maintain repeatable steps if calculating this on the fly. const byte brightnessSteps[] = { 5, 7, 9, 12, 16, 20, 26, 34, 43, 56, 72, 93, 119, 154, 198, 255 }; const size_t numBrightnessSteps = sizeof(brightnessSteps) / sizeof(uint8_t); // increment `bri` to the next `brightnessSteps` value void incBrightness() { // dumb incremental search is efficient enough for so few items for (uint8_t index = 0; index < numBrightnessSteps; ++index) { if (brightnessSteps[index] > bri) { bri = brightnessSteps[index]; lastRepeatableAction = ACTION_BRIGHT_UP; break; } } } // decrement `bri` to the next `brightnessSteps` value void decBrightness() { // dumb incremental search is efficient enough for so few items for (int index = numBrightnessSteps - 1; index >= 0; --index) { if (brightnessSteps[index] < bri) { bri = brightnessSteps[index]; lastRepeatableAction = ACTION_BRIGHT_DOWN; break; } } } // apply preset or fallback to a effect and palette if it doesn't exist void presetFallback(uint8_t presetID, uint8_t effectID, uint8_t paletteID) { if (!applyPreset(presetID, CALL_MODE_BUTTON)) { effectCurrent = effectID; effectPalette = paletteID; } } //Add what your custom IR codes should trigger here. Guide: https://github.com/Aircoookie/WLED/wiki/Infrared-Control //IR codes themselves can be defined directly after "case" or in "ir_codes.h" bool decodeIRCustom(uint32_t code) { switch (code) { //just examples, feel free to modify or remove case IRCUSTOM_ONOFF : toggleOnOff(); break; case IRCUSTOM_MACRO1 : applyPreset(1, CALL_MODE_BUTTON); break; default: return false; } if (code != IRCUSTOM_MACRO1) colorUpdated(CALL_MODE_BUTTON); //don't update color again if we apply macro, it already does it return true; } void relativeChange(byte* property, int8_t amount, byte lowerBoundary, byte higherBoundary) { int16_t new_val = (int16_t) *property + amount; if (new_val > higherBoundary) new_val = higherBoundary; else if (new_val < lowerBoundary) new_val = lowerBoundary; *property = (byte)constrain(new_val,0.1,255.1); } void changeEffectSpeed(int8_t amount) { if (effectCurrent != 0) { int16_t new_val = (int16_t) effectSpeed + amount; effectSpeed = (byte)constrain(new_val,0.1,255.1); } else { // if Effect == "solid Color", change the hue of the primary color CRGB fastled_col; fastled_col.red = col[0]; fastled_col.green = col[1]; fastled_col.blue = col[2]; CHSV prim_hsv = rgb2hsv_approximate(fastled_col); int16_t new_val = (int16_t) prim_hsv.h + amount; if (new_val > 255) new_val -= 255; // roll-over if bigger than 255 if (new_val < 0) new_val += 255; // roll-over if smaller than 0 prim_hsv.h = (byte)new_val; hsv2rgb_rainbow(prim_hsv, fastled_col); col[0] = fastled_col.red; col[1] = fastled_col.green; col[2] = fastled_col.blue; } if(amount > 0) lastRepeatableAction = ACTION_SPEED_UP; if(amount < 0) lastRepeatableAction = ACTION_SPEED_DOWN; lastRepeatableValue = amount; } void changeEffectIntensity(int8_t amount) { if (effectCurrent != 0) { int16_t new_val = (int16_t) effectIntensity + amount; effectIntensity = (byte)constrain(new_val,0.1,255.1); } else { // if Effect == "solid Color", change the saturation of the primary color CRGB fastled_col; fastled_col.red = col[0]; fastled_col.green = col[1]; fastled_col.blue = col[2]; CHSV prim_hsv = rgb2hsv_approximate(fastled_col); int16_t new_val = (int16_t) prim_hsv.s + amount; prim_hsv.s = (byte)constrain(new_val,0.1,255.1); // constrain to 0-255 hsv2rgb_rainbow(prim_hsv, fastled_col); col[0] = fastled_col.red; col[1] = fastled_col.green; col[2] = fastled_col.blue; } if(amount > 0) lastRepeatableAction = ACTION_INTENSITY_UP; if(amount < 0) lastRepeatableAction = ACTION_INTENSITY_DOWN; lastRepeatableValue = amount; } void decodeIR(uint32_t code) { if (code == 0xFFFFFFFF) //repeated code, continue brightness up/down { irTimesRepeated++; applyRepeatActions(); return; } lastValidCode = 0; irTimesRepeated = 0; if (decodeIRCustom(code)) return; if (irEnabled == 8) { // any remote configurable with ir.json file decodeIRJson(code); return; } if (code > 0xFFFFFF) return; //invalid code switch (irEnabled) { case 1: if (code > 0xF80000) { decodeIR24OLD(code); // white 24-key remote (old) - it sends 0xFF0000 values } else { decodeIR24(code); // 24-key remote - 0xF70000 to 0xF80000 } break; case 2: decodeIR24CT(code); break; // white 24-key remote with CW, WW, CT+ and CT- keys case 3: decodeIR40(code); break; // blue 40-key remote with 25%, 50%, 75% and 100% keys case 4: decodeIR44(code); break; // white 44-key remote with color-up/down keys and DIY1 to 6 keys case 5: decodeIR21(code); break; // white 21-key remote case 6: decodeIR6(code); break; // black 6-key learning remote defaults: "CH" controls brightness, // "VOL +" controls effect, "VOL -" controls colour/palette, "MUTE" // sets bright plain white case 7: decodeIR9(code); break; //case 8: return; // ir.json file, handled above switch statement default: return; } if (nightlightActive && bri == 0) nightlightActive = false; colorUpdated(CALL_MODE_BUTTON); //for notifier, IR is considered a button input } void applyRepeatActions(){ if (lastRepeatableAction == ACTION_BRIGHT_UP) { incBrightness(); colorUpdated(CALL_MODE_BUTTON); } else if (lastRepeatableAction == ACTION_BRIGHT_DOWN ) { decBrightness(); colorUpdated(CALL_MODE_BUTTON); } if (lastRepeatableAction == ACTION_SPEED_UP) { changeEffectSpeed(lastRepeatableValue); colorUpdated(CALL_MODE_BUTTON); } else if (lastRepeatableAction == ACTION_SPEED_DOWN ) { changeEffectSpeed(lastRepeatableValue); colorUpdated(CALL_MODE_BUTTON); } if (lastRepeatableAction == ACTION_INTENSITY_UP) { changeEffectIntensity(lastRepeatableValue); colorUpdated(CALL_MODE_BUTTON); } else if (lastRepeatableAction == ACTION_INTENSITY_DOWN ) { changeEffectIntensity(lastRepeatableValue); colorUpdated(CALL_MODE_BUTTON); } if (lastValidCode == IR40_WPLUS) { relativeChangeWhite(10); colorUpdated(CALL_MODE_BUTTON); } else if (lastValidCode == IR40_WMINUS) { relativeChangeWhite(-10, 5); colorUpdated(CALL_MODE_BUTTON); } else if ((lastValidCode == IR24_ON || lastValidCode == IR40_ON) && irTimesRepeated > 7 ) { nightlightActive = true; nightlightStartTime = millis(); colorUpdated(CALL_MODE_BUTTON); } else if (irEnabled == 8) { decodeIRJson(lastValidCode); } } void decodeIR24(uint32_t code) { switch (code) { case IR24_BRIGHTER : incBrightness(); break; case IR24_DARKER : decBrightness(); break; case IR24_OFF : if (bri > 0) briLast = bri; bri = 0; break; case IR24_ON : bri = briLast; break; case IR24_RED : colorFromUint32(COLOR_RED); break; case IR24_REDDISH : colorFromUint32(COLOR_REDDISH); break; case IR24_ORANGE : colorFromUint32(COLOR_ORANGE); break; case IR24_YELLOWISH : colorFromUint32(COLOR_YELLOWISH); break; case IR24_YELLOW : colorFromUint32(COLOR_YELLOW); break; case IR24_GREEN : colorFromUint32(COLOR_GREEN); break; case IR24_GREENISH : colorFromUint32(COLOR_GREENISH); break; case IR24_TURQUOISE : colorFromUint32(COLOR_TURQUOISE); break; case IR24_CYAN : colorFromUint32(COLOR_CYAN); break; case IR24_AQUA : colorFromUint32(COLOR_AQUA); break; case IR24_BLUE : colorFromUint32(COLOR_BLUE); break; case IR24_DEEPBLUE : colorFromUint32(COLOR_DEEPBLUE); break; case IR24_PURPLE : colorFromUint32(COLOR_PURPLE); break; case IR24_MAGENTA : colorFromUint32(COLOR_MAGENTA); break; case IR24_PINK : colorFromUint32(COLOR_PINK); break; case IR24_WHITE : colorFromUint32(COLOR_WHITE); effectCurrent = 0; break; case IR24_FLASH : presetFallback(1, FX_MODE_COLORTWINKLE, effectPalette); break; case IR24_STROBE : presetFallback(2, FX_MODE_RAINBOW_CYCLE, effectPalette); break; case IR24_FADE : presetFallback(3, FX_MODE_BREATH, effectPalette); break; case IR24_SMOOTH : presetFallback(4, FX_MODE_RAINBOW, effectPalette); break; default: return; } lastValidCode = code; } void decodeIR24OLD(uint32_t code) { switch (code) { case IR24_OLD_BRIGHTER : incBrightness(); break; case IR24_OLD_DARKER : decBrightness(); break; case IR24_OLD_OFF : if (bri > 0) briLast = bri; bri = 0; break; case IR24_OLD_ON : bri = briLast; break; case IR24_OLD_RED : colorFromUint32(COLOR_RED); break; case IR24_OLD_REDDISH : colorFromUint32(COLOR_REDDISH); break; case IR24_OLD_ORANGE : colorFromUint32(COLOR_ORANGE); break; case IR24_OLD_YELLOWISH : colorFromUint32(COLOR_YELLOWISH); break; case IR24_OLD_YELLOW : colorFromUint32(COLOR_YELLOW); break; case IR24_OLD_GREEN : colorFromUint32(COLOR_GREEN); break; case IR24_OLD_GREENISH : colorFromUint32(COLOR_GREENISH); break; case IR24_OLD_TURQUOISE : colorFromUint32(COLOR_TURQUOISE); break; case IR24_OLD_CYAN : colorFromUint32(COLOR_CYAN); break; case IR24_OLD_AQUA : colorFromUint32(COLOR_AQUA); break; case IR24_OLD_BLUE : colorFromUint32(COLOR_BLUE); break; case IR24_OLD_DEEPBLUE : colorFromUint32(COLOR_DEEPBLUE); break; case IR24_OLD_PURPLE : colorFromUint32(COLOR_PURPLE); break; case IR24_OLD_MAGENTA : colorFromUint32(COLOR_MAGENTA); break; case IR24_OLD_PINK : colorFromUint32(COLOR_PINK); break; case IR24_OLD_WHITE : colorFromUint32(COLOR_WHITE); effectCurrent = 0; break; case IR24_OLD_FLASH : presetFallback(1, FX_MODE_COLORTWINKLE, 0); break; case IR24_OLD_STROBE : presetFallback(2, FX_MODE_RAINBOW_CYCLE, 0); break; case IR24_OLD_FADE : presetFallback(3, FX_MODE_BREATH, 0); break; case IR24_OLD_SMOOTH : presetFallback(4, FX_MODE_RAINBOW, 0); break; default: return; } lastValidCode = code; } void decodeIR24CT(uint32_t code) { switch (code) { case IR24_CT_BRIGHTER : incBrightness(); break; case IR24_CT_DARKER : decBrightness(); break; case IR24_CT_OFF : if (bri > 0) briLast = bri; bri = 0; break; case IR24_CT_ON : bri = briLast; break; case IR24_CT_RED : colorFromUint32(COLOR_RED); break; case IR24_CT_REDDISH : colorFromUint32(COLOR_REDDISH); break; case IR24_CT_ORANGE : colorFromUint32(COLOR_ORANGE); break; case IR24_CT_YELLOWISH : colorFromUint32(COLOR_YELLOWISH); break; case IR24_CT_YELLOW : colorFromUint32(COLOR_YELLOW); break; case IR24_CT_GREEN : colorFromUint32(COLOR_GREEN); break; case IR24_CT_GREENISH : colorFromUint32(COLOR_GREENISH); break; case IR24_CT_TURQUOISE : colorFromUint32(COLOR_TURQUOISE); break; case IR24_CT_CYAN : colorFromUint32(COLOR_CYAN); break; case IR24_CT_AQUA : colorFromUint32(COLOR_AQUA); break; case IR24_CT_BLUE : colorFromUint32(COLOR_BLUE); break; case IR24_CT_DEEPBLUE : colorFromUint32(COLOR_DEEPBLUE); break; case IR24_CT_PURPLE : colorFromUint32(COLOR_PURPLE); break; case IR24_CT_MAGENTA : colorFromUint32(COLOR_MAGENTA); break; case IR24_CT_PINK : colorFromUint32(COLOR_PINK); break; case IR24_CT_COLDWHITE : colorFromUint32(COLOR2_COLDWHITE); effectCurrent = 0; break; case IR24_CT_WARMWHITE : colorFromUint32(COLOR2_WARMWHITE); effectCurrent = 0; break; case IR24_CT_CTPLUS : colorFromUint32(COLOR2_COLDWHITE2); effectCurrent = 0; break; case IR24_CT_CTMINUS : colorFromUint32(COLOR2_WARMWHITE2); effectCurrent = 0; break; case IR24_CT_MEMORY : { if (col[3] > 0) col[3] = 0; else colorFromUint32(COLOR2_NEUTRALWHITE); effectCurrent = 0; } break; default: return; } lastValidCode = code; } void decodeIR40(uint32_t code) { switch (code) { case IR40_BPLUS : incBrightness(); break; case IR40_BMINUS : decBrightness(); break; case IR40_OFF : if (bri > 0) briLast = bri; bri = 0; break; case IR40_ON : bri = briLast; break; case IR40_RED : colorFromUint24(COLOR_RED); break; case IR40_REDDISH : colorFromUint24(COLOR_REDDISH); break; case IR40_ORANGE : colorFromUint24(COLOR_ORANGE); break; case IR40_YELLOWISH : colorFromUint24(COLOR_YELLOWISH); break; case IR40_YELLOW : colorFromUint24(COLOR_YELLOW); break; case IR40_GREEN : colorFromUint24(COLOR_GREEN); break; case IR40_GREENISH : colorFromUint24(COLOR_GREENISH); break; case IR40_TURQUOISE : colorFromUint24(COLOR_TURQUOISE); break; case IR40_CYAN : colorFromUint24(COLOR_CYAN); break; case IR40_AQUA : colorFromUint24(COLOR_AQUA); break; case IR40_BLUE : colorFromUint24(COLOR_BLUE); break; case IR40_DEEPBLUE : colorFromUint24(COLOR_DEEPBLUE); break; case IR40_PURPLE : colorFromUint24(COLOR_PURPLE); break; case IR40_MAGENTA : colorFromUint24(COLOR_MAGENTA); break; case IR40_PINK : colorFromUint24(COLOR_PINK); break; case IR40_WARMWHITE2 : { if (strip.isRgbw) { colorFromUint32(COLOR2_WARMWHITE2); effectCurrent = 0; } else colorFromUint24(COLOR_WARMWHITE2); } break; case IR40_WARMWHITE : { if (strip.isRgbw) { colorFromUint32(COLOR2_WARMWHITE); effectCurrent = 0; } else colorFromUint24(COLOR_WARMWHITE); } break; case IR40_WHITE : { if (strip.isRgbw) { colorFromUint32(COLOR2_NEUTRALWHITE); effectCurrent = 0; } else colorFromUint24(COLOR_NEUTRALWHITE); } break; case IR40_COLDWHITE : { if (strip.isRgbw) { colorFromUint32(COLOR2_COLDWHITE); effectCurrent = 0; } else colorFromUint24(COLOR_COLDWHITE); } break; case IR40_COLDWHITE2 : { if (strip.isRgbw) { colorFromUint32(COLOR2_COLDWHITE2); effectCurrent = 0; } else colorFromUint24(COLOR_COLDWHITE2); } break; case IR40_WPLUS : relativeChangeWhite(10); break; case IR40_WMINUS : relativeChangeWhite(-10, 5); break; case IR40_WOFF : whiteLast = col[3]; col[3] = 0; break; case IR40_WON : col[3] = whiteLast; break; case IR40_W25 : bri = 63; break; case IR40_W50 : bri = 127; break; case IR40_W75 : bri = 191; break; case IR40_W100 : bri = 255; break; case IR40_QUICK : changeEffectSpeed( 16); break; case IR40_SLOW : changeEffectSpeed(-16); break; case IR40_JUMP7 : changeEffectIntensity( 16); break; case IR40_AUTO : changeEffectIntensity(-16); break; case IR40_JUMP3 : presetFallback(1, FX_MODE_STATIC, 0); break; case IR40_FADE3 : presetFallback(2, FX_MODE_BREATH, 0); break; case IR40_FADE7 : presetFallback(3, FX_MODE_FIRE_FLICKER, 0); break; case IR40_FLASH : presetFallback(4, FX_MODE_RAINBOW, 0); break; } lastValidCode = code; } void decodeIR44(uint32_t code) { switch (code) { case IR44_BPLUS : incBrightness(); break; case IR44_BMINUS : decBrightness(); break; case IR44_OFF : if (bri > 0) briLast = bri; bri = 0; break; case IR44_ON : bri = briLast; break; case IR44_RED : colorFromUint24(COLOR_RED); break; case IR44_REDDISH : colorFromUint24(COLOR_REDDISH); break; case IR44_ORANGE : colorFromUint24(COLOR_ORANGE); break; case IR44_YELLOWISH : colorFromUint24(COLOR_YELLOWISH); break; case IR44_YELLOW : colorFromUint24(COLOR_YELLOW); break; case IR44_GREEN : colorFromUint24(COLOR_GREEN); break; case IR44_GREENISH : colorFromUint24(COLOR_GREENISH); break; case IR44_TURQUOISE : colorFromUint24(COLOR_TURQUOISE); break; case IR44_CYAN : colorFromUint24(COLOR_CYAN); break; case IR44_AQUA : colorFromUint24(COLOR_AQUA); break; case IR44_BLUE : colorFromUint24(COLOR_BLUE); break; case IR44_DEEPBLUE : colorFromUint24(COLOR_DEEPBLUE); break; case IR44_PURPLE : colorFromUint24(COLOR_PURPLE); break; case IR44_MAGENTA : colorFromUint24(COLOR_MAGENTA); break; case IR44_PINK : colorFromUint24(COLOR_PINK); break; case IR44_WHITE : { if (strip.isRgbw) { if (col[3] > 0) col[3] = 0; else { colorFromUint32(COLOR2_NEUTRALWHITE); effectCurrent = 0; } } else colorFromUint24(COLOR_NEUTRALWHITE); } break; case IR44_WARMWHITE2 : { if (strip.isRgbw) { colorFromUint32(COLOR2_WARMWHITE2); effectCurrent = 0; } else colorFromUint24(COLOR_WARMWHITE2); } break; case IR44_WARMWHITE : { if (strip.isRgbw) { colorFromUint32(COLOR2_WARMWHITE); effectCurrent = 0; } else colorFromUint24(COLOR_WARMWHITE); } break; case IR44_COLDWHITE : { if (strip.isRgbw) { colorFromUint32(COLOR2_COLDWHITE); effectCurrent = 0; } else colorFromUint24(COLOR_COLDWHITE); } break; case IR44_COLDWHITE2 : { if (strip.isRgbw) { colorFromUint32(COLOR2_COLDWHITE2); effectCurrent = 0; } else colorFromUint24(COLOR_COLDWHITE2); } break; case IR44_REDPLUS : relativeChange(&effectCurrent, 1, 0, MODE_COUNT); break; case IR44_REDMINUS : relativeChange(&effectCurrent, -1, 0); break; case IR44_GREENPLUS : relativeChange(&effectPalette, 1, 0, strip.getPaletteCount() -1); break; case IR44_GREENMINUS : relativeChange(&effectPalette, -1, 0); break; case IR44_BLUEPLUS : changeEffectIntensity( 16); break; case IR44_BLUEMINUS : changeEffectIntensity(-16); break; case IR44_QUICK : changeEffectSpeed( 16); break; case IR44_SLOW : changeEffectSpeed(-16); break; case IR44_DIY1 : presetFallback(1, FX_MODE_STATIC, 0); break; case IR44_DIY2 : presetFallback(2, FX_MODE_BREATH, 0); break; case IR44_DIY3 : presetFallback(3, FX_MODE_FIRE_FLICKER, 0); break; case IR44_DIY4 : presetFallback(4, FX_MODE_RAINBOW, 0); break; case IR44_DIY5 : presetFallback(5, FX_MODE_METEOR_SMOOTH, 0); break; case IR44_DIY6 : presetFallback(6, FX_MODE_RAIN, 0); break; case IR44_AUTO : effectCurrent = FX_MODE_STATIC; break; case IR44_FLASH : effectCurrent = FX_MODE_PALETTE; break; case IR44_JUMP3 : bri = 63; break; case IR44_JUMP7 : bri = 127; break; case IR44_FADE3 : bri = 191; break; case IR44_FADE7 : bri = 255; break; } lastValidCode = code; } void decodeIR21(uint32_t code) { switch (code) { case IR21_BRIGHTER: incBrightness(); break; case IR21_DARKER: decBrightness(); break; case IR21_OFF: if (bri > 0) briLast = bri; bri = 0; break; case IR21_ON: bri = briLast; break; case IR21_RED: colorFromUint32(COLOR_RED); break; case IR21_REDDISH: colorFromUint32(COLOR_REDDISH); break; case IR21_ORANGE: colorFromUint32(COLOR_ORANGE); break; case IR21_YELLOWISH: colorFromUint32(COLOR_YELLOWISH); break; case IR21_GREEN: colorFromUint32(COLOR_GREEN); break; case IR21_GREENISH: colorFromUint32(COLOR_GREENISH); break; case IR21_TURQUOISE: colorFromUint32(COLOR_TURQUOISE); break; case IR21_CYAN: colorFromUint32(COLOR_CYAN); break; case IR21_BLUE: colorFromUint32(COLOR_BLUE); break; case IR21_DEEPBLUE: colorFromUint32(COLOR_DEEPBLUE); break; case IR21_PURPLE: colorFromUint32(COLOR_PURPLE); break; case IR21_PINK: colorFromUint32(COLOR_PINK); break; case IR21_WHITE: colorFromUint32(COLOR_WHITE); effectCurrent = 0; break; case IR21_FLASH: presetFallback(1, FX_MODE_COLORTWINKLE, 0); break; case IR21_STROBE: presetFallback(2, FX_MODE_RAINBOW_CYCLE, 0); break; case IR21_FADE: presetFallback(3, FX_MODE_BREATH, 0); break; case IR21_SMOOTH: presetFallback(4, FX_MODE_RAINBOW, 0); break; default: return; } lastValidCode = code; } void decodeIR6(uint32_t code) { switch (code) { case IR6_POWER: toggleOnOff(); break; case IR6_CHANNEL_UP: incBrightness(); break; case IR6_CHANNEL_DOWN: decBrightness(); break; case IR6_VOLUME_UP: relativeChange(&effectCurrent, 1, 0, MODE_COUNT); break; // next effect case IR6_VOLUME_DOWN: // next palette relativeChange(&effectPalette, 1, 0, strip.getPaletteCount() -1); switch(lastIR6ColourIdx) { case 0: colorFromUint32(COLOR_RED); break; case 1: colorFromUint32(COLOR_REDDISH); break; case 2: colorFromUint32(COLOR_ORANGE); break; case 3: colorFromUint32(COLOR_YELLOWISH); break; case 4: colorFromUint32(COLOR_GREEN); break; case 5: colorFromUint32(COLOR_GREENISH); break; case 6: colorFromUint32(COLOR_TURQUOISE); break; case 7: colorFromUint32(COLOR_CYAN); break; case 8: colorFromUint32(COLOR_BLUE); break; case 9: colorFromUint32(COLOR_DEEPBLUE); break; case 10:colorFromUint32(COLOR_PURPLE); break; case 11:colorFromUint32(COLOR_PINK); break; case 12:colorFromUint32(COLOR_WHITE); break; default: break; } lastIR6ColourIdx++; if(lastIR6ColourIdx > 12) lastIR6ColourIdx = 0; break; case IR6_MUTE: effectCurrent = 0; effectPalette = 0; colorFromUint32(COLOR_WHITE); bri=255; break; } lastValidCode = code; } void decodeIR9(uint32_t code) { switch (code) { case IR9_POWER : toggleOnOff(); break; case IR9_A : presetFallback(1, FX_MODE_COLORTWINKLE, effectPalette); break; case IR9_B : presetFallback(2, FX_MODE_RAINBOW_CYCLE, effectPalette); break; case IR9_C : presetFallback(3, FX_MODE_BREATH, effectPalette); break; case IR9_UP : incBrightness(); break; case IR9_DOWN : decBrightness(); break; //case IR9_UP : changeEffectIntensity(16); break; //case IR9_DOWN : changeEffectIntensity(-16); break; case IR9_LEFT : changeEffectSpeed(-16); break; case IR9_RIGHT : changeEffectSpeed(16); break; case IR9_SELECT : relativeChange(&effectCurrent, 1, 0, MODE_COUNT); break; default: return; } lastValidCode = code; } /* This allows users to customize IR actions without the need to edit C code and compile. From the https://github.com/Aircoookie/WLED/wiki/Infrared-Control page, download the starter ir.json file that corresponds to the number of buttons on your remote. Many of the remotes with the same number of buttons emit the same codes, but will have different labels or colors. Once you edit the ir.json file, upload it to your controller using the /edit page. Each key should be the hex encoded IR code. The "cmd" property should be the HTTP API or JSON API command to execute on button press. If the command contains a relative change (SI=~16), it will register as a repeatable command. If the command doesn't contain a "~" but is repeatable, add "rpt" property set to true. Other properties are ignored but having labels and positions can assist with editing the json file. Sample: { "0xFF629D": {"cmd": "T=2", "rpt": true, "label": "Toggle on/off"}, // HTTP command "0xFF9867": {"cmd": "A=~16", "label": "Inc brightness"}, // HTTP command with incrementing "0xFF38C7": {"cmd": {"bri": 10}, "label": "Dim to 10"}, // JSON command "0xFF22DD": {"cmd": "!presetFallback", "PL": 1, "FX": 16, "FP": 6, // Custom command "label": "Preset 1, fallback to Saw - Party if not found"}, } */ void decodeIRJson(uint32_t code) { char objKey[10]; const char* cmd; String cmdStr; DynamicJsonDocument irDoc(JSON_BUFFER_SIZE); JsonObject fdo; JsonObject jsonCmdObj; sprintf(objKey, "\"0x%X\":", code); errorFlag = readObjectFromFile("/ir.json", objKey, &irDoc) ? ERR_NONE : ERR_FS_PLOAD; fdo = irDoc.as<JsonObject>(); lastValidCode = 0; if (!errorFlag) { cmd = fdo["cmd"]; cmdStr = String(cmd); jsonCmdObj = fdo["cmd"]; if (!cmdStr.isEmpty()) { if (cmdStr.startsWith("!")) { // call limited set of C functions if (cmdStr.startsWith(F("!incBri"))) { lastValidCode = code; incBrightness(); } else if (cmdStr.startsWith(F("!decBri"))) { lastValidCode = code; decBrightness(); } else if (cmdStr.startsWith(F("!presetF"))) { //!presetFallback uint8_t p1 = fdo["PL"] ? fdo["PL"] : 1; uint8_t p2 = fdo["FX"] ? fdo["FX"] : random8(100); uint8_t p3 = fdo["FP"] ? fdo["FP"] : 0; presetFallback(p1, p2, p3); } } else { // HTTP API command if (cmdStr.indexOf("~") || fdo["rpt"]) { // repeatable action lastValidCode = code; } if (effectCurrent == 0 && cmdStr.indexOf("FP=") > -1) { // setting palette but it wont show because effect is solid effectCurrent = FX_MODE_GRADIENT; } if (!cmdStr.startsWith("win&")) { cmdStr = "win&" + cmdStr; } handleSet(nullptr, cmdStr, false); } } else if (!jsonCmdObj.isNull()) { // command is JSON object //allow applyPreset() to reuse JSON buffer, or it would alloc. a second buffer and run out of mem. fileDoc = &irDoc; deserializeState(jsonCmdObj, CALL_MODE_BUTTON); fileDoc = nullptr; } } } void initIR() { if (irEnabled > 0) { irrecv = new IRrecv(irPin); irrecv->enableIRIn(); } } void handleIR() { if (irEnabled > 0 && millis() - irCheckedTime > 120) { irCheckedTime = millis(); if (irEnabled > 0) { if (irrecv == NULL) { initIR(); return; } if (irrecv->decode(&results)) { if (results.value != 0) // only print results if anything is received ( != 0 ) { Serial.print("IR recv\r\n0x"); Serial.println((uint32_t)results.value, HEX); Serial.println(); } decodeIR(results.value); irrecv->resume(); } } else if (irrecv != NULL) { irrecv->disableIRIn(); delete irrecv; irrecv = NULL; } } } #endif Fix error 12 issues #include "wled.h" /* * Infrared sensor support for generic 24/40/44 key RGB remotes */ #if defined(WLED_DISABLE_INFRARED) void handleIR(){} #else IRrecv* irrecv; //change pin in NpbWrapper.h decode_results results; unsigned long irCheckedTime = 0; uint32_t lastValidCode = 0; byte lastRepeatableAction = ACTION_NONE; uint8_t lastRepeatableValue = 0; uint16_t irTimesRepeated = 0; uint8_t lastIR6ColourIdx = 0; // brightnessSteps: a static array of brightness levels following a geometric // progression. Can be generated from the following Python, adjusting the // arbitrary 4.5 value to taste: // // def values(level): // while level >= 5: // yield int(level) // level -= level / 4.5 // result = [v for v in reversed(list(values(255)))] // print("%d values: %s" % (len(result), result)) // // It would be hard to maintain repeatable steps if calculating this on the fly. const byte brightnessSteps[] = { 5, 7, 9, 12, 16, 20, 26, 34, 43, 56, 72, 93, 119, 154, 198, 255 }; const size_t numBrightnessSteps = sizeof(brightnessSteps) / sizeof(uint8_t); // increment `bri` to the next `brightnessSteps` value void incBrightness() { // dumb incremental search is efficient enough for so few items for (uint8_t index = 0; index < numBrightnessSteps; ++index) { if (brightnessSteps[index] > bri) { bri = brightnessSteps[index]; lastRepeatableAction = ACTION_BRIGHT_UP; break; } } } // decrement `bri` to the next `brightnessSteps` value void decBrightness() { // dumb incremental search is efficient enough for so few items for (int index = numBrightnessSteps - 1; index >= 0; --index) { if (brightnessSteps[index] < bri) { bri = brightnessSteps[index]; lastRepeatableAction = ACTION_BRIGHT_DOWN; break; } } } // apply preset or fallback to a effect and palette if it doesn't exist void presetFallback(uint8_t presetID, uint8_t effectID, uint8_t paletteID) { byte prevError = errorFlag; if (!applyPreset(presetID, CALL_MODE_BUTTON)) { effectCurrent = effectID; effectPalette = paletteID; errorFlag = prevError; //clear error 12 from non-existent preset } } //Add what your custom IR codes should trigger here. Guide: https://github.com/Aircoookie/WLED/wiki/Infrared-Control //IR codes themselves can be defined directly after "case" or in "ir_codes.h" bool decodeIRCustom(uint32_t code) { switch (code) { //just examples, feel free to modify or remove case IRCUSTOM_ONOFF : toggleOnOff(); break; case IRCUSTOM_MACRO1 : applyPreset(1, CALL_MODE_BUTTON); break; default: return false; } if (code != IRCUSTOM_MACRO1) colorUpdated(CALL_MODE_BUTTON); //don't update color again if we apply macro, it already does it return true; } void relativeChange(byte* property, int8_t amount, byte lowerBoundary, byte higherBoundary) { int16_t new_val = (int16_t) *property + amount; if (new_val > higherBoundary) new_val = higherBoundary; else if (new_val < lowerBoundary) new_val = lowerBoundary; *property = (byte)constrain(new_val,0.1,255.1); } void changeEffectSpeed(int8_t amount) { if (effectCurrent != 0) { int16_t new_val = (int16_t) effectSpeed + amount; effectSpeed = (byte)constrain(new_val,0.1,255.1); } else { // if Effect == "solid Color", change the hue of the primary color CRGB fastled_col; fastled_col.red = col[0]; fastled_col.green = col[1]; fastled_col.blue = col[2]; CHSV prim_hsv = rgb2hsv_approximate(fastled_col); int16_t new_val = (int16_t) prim_hsv.h + amount; if (new_val > 255) new_val -= 255; // roll-over if bigger than 255 if (new_val < 0) new_val += 255; // roll-over if smaller than 0 prim_hsv.h = (byte)new_val; hsv2rgb_rainbow(prim_hsv, fastled_col); col[0] = fastled_col.red; col[1] = fastled_col.green; col[2] = fastled_col.blue; } if(amount > 0) lastRepeatableAction = ACTION_SPEED_UP; if(amount < 0) lastRepeatableAction = ACTION_SPEED_DOWN; lastRepeatableValue = amount; } void changeEffectIntensity(int8_t amount) { if (effectCurrent != 0) { int16_t new_val = (int16_t) effectIntensity + amount; effectIntensity = (byte)constrain(new_val,0.1,255.1); } else { // if Effect == "solid Color", change the saturation of the primary color CRGB fastled_col; fastled_col.red = col[0]; fastled_col.green = col[1]; fastled_col.blue = col[2]; CHSV prim_hsv = rgb2hsv_approximate(fastled_col); int16_t new_val = (int16_t) prim_hsv.s + amount; prim_hsv.s = (byte)constrain(new_val,0.1,255.1); // constrain to 0-255 hsv2rgb_rainbow(prim_hsv, fastled_col); col[0] = fastled_col.red; col[1] = fastled_col.green; col[2] = fastled_col.blue; } if(amount > 0) lastRepeatableAction = ACTION_INTENSITY_UP; if(amount < 0) lastRepeatableAction = ACTION_INTENSITY_DOWN; lastRepeatableValue = amount; } void decodeIR(uint32_t code) { if (code == 0xFFFFFFFF) //repeated code, continue brightness up/down { irTimesRepeated++; applyRepeatActions(); return; } lastValidCode = 0; irTimesRepeated = 0; if (decodeIRCustom(code)) return; if (irEnabled == 8) { // any remote configurable with ir.json file decodeIRJson(code); return; } if (code > 0xFFFFFF) return; //invalid code switch (irEnabled) { case 1: if (code > 0xF80000) { decodeIR24OLD(code); // white 24-key remote (old) - it sends 0xFF0000 values } else { decodeIR24(code); // 24-key remote - 0xF70000 to 0xF80000 } break; case 2: decodeIR24CT(code); break; // white 24-key remote with CW, WW, CT+ and CT- keys case 3: decodeIR40(code); break; // blue 40-key remote with 25%, 50%, 75% and 100% keys case 4: decodeIR44(code); break; // white 44-key remote with color-up/down keys and DIY1 to 6 keys case 5: decodeIR21(code); break; // white 21-key remote case 6: decodeIR6(code); break; // black 6-key learning remote defaults: "CH" controls brightness, // "VOL +" controls effect, "VOL -" controls colour/palette, "MUTE" // sets bright plain white case 7: decodeIR9(code); break; //case 8: return; // ir.json file, handled above switch statement default: return; } if (nightlightActive && bri == 0) nightlightActive = false; colorUpdated(CALL_MODE_BUTTON); //for notifier, IR is considered a button input } void applyRepeatActions(){ if (lastRepeatableAction == ACTION_BRIGHT_UP) { incBrightness(); colorUpdated(CALL_MODE_BUTTON); } else if (lastRepeatableAction == ACTION_BRIGHT_DOWN ) { decBrightness(); colorUpdated(CALL_MODE_BUTTON); } if (lastRepeatableAction == ACTION_SPEED_UP) { changeEffectSpeed(lastRepeatableValue); colorUpdated(CALL_MODE_BUTTON); } else if (lastRepeatableAction == ACTION_SPEED_DOWN ) { changeEffectSpeed(lastRepeatableValue); colorUpdated(CALL_MODE_BUTTON); } if (lastRepeatableAction == ACTION_INTENSITY_UP) { changeEffectIntensity(lastRepeatableValue); colorUpdated(CALL_MODE_BUTTON); } else if (lastRepeatableAction == ACTION_INTENSITY_DOWN ) { changeEffectIntensity(lastRepeatableValue); colorUpdated(CALL_MODE_BUTTON); } if (lastValidCode == IR40_WPLUS) { relativeChangeWhite(10); colorUpdated(CALL_MODE_BUTTON); } else if (lastValidCode == IR40_WMINUS) { relativeChangeWhite(-10, 5); colorUpdated(CALL_MODE_BUTTON); } else if ((lastValidCode == IR24_ON || lastValidCode == IR40_ON) && irTimesRepeated > 7 ) { nightlightActive = true; nightlightStartTime = millis(); colorUpdated(CALL_MODE_BUTTON); } else if (irEnabled == 8) { decodeIRJson(lastValidCode); } } void decodeIR24(uint32_t code) { switch (code) { case IR24_BRIGHTER : incBrightness(); break; case IR24_DARKER : decBrightness(); break; case IR24_OFF : if (bri > 0) briLast = bri; bri = 0; break; case IR24_ON : bri = briLast; break; case IR24_RED : colorFromUint32(COLOR_RED); break; case IR24_REDDISH : colorFromUint32(COLOR_REDDISH); break; case IR24_ORANGE : colorFromUint32(COLOR_ORANGE); break; case IR24_YELLOWISH : colorFromUint32(COLOR_YELLOWISH); break; case IR24_YELLOW : colorFromUint32(COLOR_YELLOW); break; case IR24_GREEN : colorFromUint32(COLOR_GREEN); break; case IR24_GREENISH : colorFromUint32(COLOR_GREENISH); break; case IR24_TURQUOISE : colorFromUint32(COLOR_TURQUOISE); break; case IR24_CYAN : colorFromUint32(COLOR_CYAN); break; case IR24_AQUA : colorFromUint32(COLOR_AQUA); break; case IR24_BLUE : colorFromUint32(COLOR_BLUE); break; case IR24_DEEPBLUE : colorFromUint32(COLOR_DEEPBLUE); break; case IR24_PURPLE : colorFromUint32(COLOR_PURPLE); break; case IR24_MAGENTA : colorFromUint32(COLOR_MAGENTA); break; case IR24_PINK : colorFromUint32(COLOR_PINK); break; case IR24_WHITE : colorFromUint32(COLOR_WHITE); effectCurrent = 0; break; case IR24_FLASH : presetFallback(1, FX_MODE_COLORTWINKLE, effectPalette); break; case IR24_STROBE : presetFallback(2, FX_MODE_RAINBOW_CYCLE, effectPalette); break; case IR24_FADE : presetFallback(3, FX_MODE_BREATH, effectPalette); break; case IR24_SMOOTH : presetFallback(4, FX_MODE_RAINBOW, effectPalette); break; default: return; } lastValidCode = code; } void decodeIR24OLD(uint32_t code) { switch (code) { case IR24_OLD_BRIGHTER : incBrightness(); break; case IR24_OLD_DARKER : decBrightness(); break; case IR24_OLD_OFF : if (bri > 0) briLast = bri; bri = 0; break; case IR24_OLD_ON : bri = briLast; break; case IR24_OLD_RED : colorFromUint32(COLOR_RED); break; case IR24_OLD_REDDISH : colorFromUint32(COLOR_REDDISH); break; case IR24_OLD_ORANGE : colorFromUint32(COLOR_ORANGE); break; case IR24_OLD_YELLOWISH : colorFromUint32(COLOR_YELLOWISH); break; case IR24_OLD_YELLOW : colorFromUint32(COLOR_YELLOW); break; case IR24_OLD_GREEN : colorFromUint32(COLOR_GREEN); break; case IR24_OLD_GREENISH : colorFromUint32(COLOR_GREENISH); break; case IR24_OLD_TURQUOISE : colorFromUint32(COLOR_TURQUOISE); break; case IR24_OLD_CYAN : colorFromUint32(COLOR_CYAN); break; case IR24_OLD_AQUA : colorFromUint32(COLOR_AQUA); break; case IR24_OLD_BLUE : colorFromUint32(COLOR_BLUE); break; case IR24_OLD_DEEPBLUE : colorFromUint32(COLOR_DEEPBLUE); break; case IR24_OLD_PURPLE : colorFromUint32(COLOR_PURPLE); break; case IR24_OLD_MAGENTA : colorFromUint32(COLOR_MAGENTA); break; case IR24_OLD_PINK : colorFromUint32(COLOR_PINK); break; case IR24_OLD_WHITE : colorFromUint32(COLOR_WHITE); effectCurrent = 0; break; case IR24_OLD_FLASH : presetFallback(1, FX_MODE_COLORTWINKLE, 0); break; case IR24_OLD_STROBE : presetFallback(2, FX_MODE_RAINBOW_CYCLE, 0); break; case IR24_OLD_FADE : presetFallback(3, FX_MODE_BREATH, 0); break; case IR24_OLD_SMOOTH : presetFallback(4, FX_MODE_RAINBOW, 0); break; default: return; } lastValidCode = code; } void decodeIR24CT(uint32_t code) { switch (code) { case IR24_CT_BRIGHTER : incBrightness(); break; case IR24_CT_DARKER : decBrightness(); break; case IR24_CT_OFF : if (bri > 0) briLast = bri; bri = 0; break; case IR24_CT_ON : bri = briLast; break; case IR24_CT_RED : colorFromUint32(COLOR_RED); break; case IR24_CT_REDDISH : colorFromUint32(COLOR_REDDISH); break; case IR24_CT_ORANGE : colorFromUint32(COLOR_ORANGE); break; case IR24_CT_YELLOWISH : colorFromUint32(COLOR_YELLOWISH); break; case IR24_CT_YELLOW : colorFromUint32(COLOR_YELLOW); break; case IR24_CT_GREEN : colorFromUint32(COLOR_GREEN); break; case IR24_CT_GREENISH : colorFromUint32(COLOR_GREENISH); break; case IR24_CT_TURQUOISE : colorFromUint32(COLOR_TURQUOISE); break; case IR24_CT_CYAN : colorFromUint32(COLOR_CYAN); break; case IR24_CT_AQUA : colorFromUint32(COLOR_AQUA); break; case IR24_CT_BLUE : colorFromUint32(COLOR_BLUE); break; case IR24_CT_DEEPBLUE : colorFromUint32(COLOR_DEEPBLUE); break; case IR24_CT_PURPLE : colorFromUint32(COLOR_PURPLE); break; case IR24_CT_MAGENTA : colorFromUint32(COLOR_MAGENTA); break; case IR24_CT_PINK : colorFromUint32(COLOR_PINK); break; case IR24_CT_COLDWHITE : colorFromUint32(COLOR2_COLDWHITE); effectCurrent = 0; break; case IR24_CT_WARMWHITE : colorFromUint32(COLOR2_WARMWHITE); effectCurrent = 0; break; case IR24_CT_CTPLUS : colorFromUint32(COLOR2_COLDWHITE2); effectCurrent = 0; break; case IR24_CT_CTMINUS : colorFromUint32(COLOR2_WARMWHITE2); effectCurrent = 0; break; case IR24_CT_MEMORY : { if (col[3] > 0) col[3] = 0; else colorFromUint32(COLOR2_NEUTRALWHITE); effectCurrent = 0; } break; default: return; } lastValidCode = code; } void decodeIR40(uint32_t code) { switch (code) { case IR40_BPLUS : incBrightness(); break; case IR40_BMINUS : decBrightness(); break; case IR40_OFF : if (bri > 0) briLast = bri; bri = 0; break; case IR40_ON : bri = briLast; break; case IR40_RED : colorFromUint24(COLOR_RED); break; case IR40_REDDISH : colorFromUint24(COLOR_REDDISH); break; case IR40_ORANGE : colorFromUint24(COLOR_ORANGE); break; case IR40_YELLOWISH : colorFromUint24(COLOR_YELLOWISH); break; case IR40_YELLOW : colorFromUint24(COLOR_YELLOW); break; case IR40_GREEN : colorFromUint24(COLOR_GREEN); break; case IR40_GREENISH : colorFromUint24(COLOR_GREENISH); break; case IR40_TURQUOISE : colorFromUint24(COLOR_TURQUOISE); break; case IR40_CYAN : colorFromUint24(COLOR_CYAN); break; case IR40_AQUA : colorFromUint24(COLOR_AQUA); break; case IR40_BLUE : colorFromUint24(COLOR_BLUE); break; case IR40_DEEPBLUE : colorFromUint24(COLOR_DEEPBLUE); break; case IR40_PURPLE : colorFromUint24(COLOR_PURPLE); break; case IR40_MAGENTA : colorFromUint24(COLOR_MAGENTA); break; case IR40_PINK : colorFromUint24(COLOR_PINK); break; case IR40_WARMWHITE2 : { if (strip.isRgbw) { colorFromUint32(COLOR2_WARMWHITE2); effectCurrent = 0; } else colorFromUint24(COLOR_WARMWHITE2); } break; case IR40_WARMWHITE : { if (strip.isRgbw) { colorFromUint32(COLOR2_WARMWHITE); effectCurrent = 0; } else colorFromUint24(COLOR_WARMWHITE); } break; case IR40_WHITE : { if (strip.isRgbw) { colorFromUint32(COLOR2_NEUTRALWHITE); effectCurrent = 0; } else colorFromUint24(COLOR_NEUTRALWHITE); } break; case IR40_COLDWHITE : { if (strip.isRgbw) { colorFromUint32(COLOR2_COLDWHITE); effectCurrent = 0; } else colorFromUint24(COLOR_COLDWHITE); } break; case IR40_COLDWHITE2 : { if (strip.isRgbw) { colorFromUint32(COLOR2_COLDWHITE2); effectCurrent = 0; } else colorFromUint24(COLOR_COLDWHITE2); } break; case IR40_WPLUS : relativeChangeWhite(10); break; case IR40_WMINUS : relativeChangeWhite(-10, 5); break; case IR40_WOFF : whiteLast = col[3]; col[3] = 0; break; case IR40_WON : col[3] = whiteLast; break; case IR40_W25 : bri = 63; break; case IR40_W50 : bri = 127; break; case IR40_W75 : bri = 191; break; case IR40_W100 : bri = 255; break; case IR40_QUICK : changeEffectSpeed( 16); break; case IR40_SLOW : changeEffectSpeed(-16); break; case IR40_JUMP7 : changeEffectIntensity( 16); break; case IR40_AUTO : changeEffectIntensity(-16); break; case IR40_JUMP3 : presetFallback(1, FX_MODE_STATIC, 0); break; case IR40_FADE3 : presetFallback(2, FX_MODE_BREATH, 0); break; case IR40_FADE7 : presetFallback(3, FX_MODE_FIRE_FLICKER, 0); break; case IR40_FLASH : presetFallback(4, FX_MODE_RAINBOW, 0); break; } lastValidCode = code; } void decodeIR44(uint32_t code) { switch (code) { case IR44_BPLUS : incBrightness(); break; case IR44_BMINUS : decBrightness(); break; case IR44_OFF : if (bri > 0) briLast = bri; bri = 0; break; case IR44_ON : bri = briLast; break; case IR44_RED : colorFromUint24(COLOR_RED); break; case IR44_REDDISH : colorFromUint24(COLOR_REDDISH); break; case IR44_ORANGE : colorFromUint24(COLOR_ORANGE); break; case IR44_YELLOWISH : colorFromUint24(COLOR_YELLOWISH); break; case IR44_YELLOW : colorFromUint24(COLOR_YELLOW); break; case IR44_GREEN : colorFromUint24(COLOR_GREEN); break; case IR44_GREENISH : colorFromUint24(COLOR_GREENISH); break; case IR44_TURQUOISE : colorFromUint24(COLOR_TURQUOISE); break; case IR44_CYAN : colorFromUint24(COLOR_CYAN); break; case IR44_AQUA : colorFromUint24(COLOR_AQUA); break; case IR44_BLUE : colorFromUint24(COLOR_BLUE); break; case IR44_DEEPBLUE : colorFromUint24(COLOR_DEEPBLUE); break; case IR44_PURPLE : colorFromUint24(COLOR_PURPLE); break; case IR44_MAGENTA : colorFromUint24(COLOR_MAGENTA); break; case IR44_PINK : colorFromUint24(COLOR_PINK); break; case IR44_WHITE : { if (strip.isRgbw) { if (col[3] > 0) col[3] = 0; else { colorFromUint32(COLOR2_NEUTRALWHITE); effectCurrent = 0; } } else colorFromUint24(COLOR_NEUTRALWHITE); } break; case IR44_WARMWHITE2 : { if (strip.isRgbw) { colorFromUint32(COLOR2_WARMWHITE2); effectCurrent = 0; } else colorFromUint24(COLOR_WARMWHITE2); } break; case IR44_WARMWHITE : { if (strip.isRgbw) { colorFromUint32(COLOR2_WARMWHITE); effectCurrent = 0; } else colorFromUint24(COLOR_WARMWHITE); } break; case IR44_COLDWHITE : { if (strip.isRgbw) { colorFromUint32(COLOR2_COLDWHITE); effectCurrent = 0; } else colorFromUint24(COLOR_COLDWHITE); } break; case IR44_COLDWHITE2 : { if (strip.isRgbw) { colorFromUint32(COLOR2_COLDWHITE2); effectCurrent = 0; } else colorFromUint24(COLOR_COLDWHITE2); } break; case IR44_REDPLUS : relativeChange(&effectCurrent, 1, 0, MODE_COUNT); break; case IR44_REDMINUS : relativeChange(&effectCurrent, -1, 0); break; case IR44_GREENPLUS : relativeChange(&effectPalette, 1, 0, strip.getPaletteCount() -1); break; case IR44_GREENMINUS : relativeChange(&effectPalette, -1, 0); break; case IR44_BLUEPLUS : changeEffectIntensity( 16); break; case IR44_BLUEMINUS : changeEffectIntensity(-16); break; case IR44_QUICK : changeEffectSpeed( 16); break; case IR44_SLOW : changeEffectSpeed(-16); break; case IR44_DIY1 : presetFallback(1, FX_MODE_STATIC, 0); break; case IR44_DIY2 : presetFallback(2, FX_MODE_BREATH, 0); break; case IR44_DIY3 : presetFallback(3, FX_MODE_FIRE_FLICKER, 0); break; case IR44_DIY4 : presetFallback(4, FX_MODE_RAINBOW, 0); break; case IR44_DIY5 : presetFallback(5, FX_MODE_METEOR_SMOOTH, 0); break; case IR44_DIY6 : presetFallback(6, FX_MODE_RAIN, 0); break; case IR44_AUTO : effectCurrent = FX_MODE_STATIC; break; case IR44_FLASH : effectCurrent = FX_MODE_PALETTE; break; case IR44_JUMP3 : bri = 63; break; case IR44_JUMP7 : bri = 127; break; case IR44_FADE3 : bri = 191; break; case IR44_FADE7 : bri = 255; break; } lastValidCode = code; } void decodeIR21(uint32_t code) { switch (code) { case IR21_BRIGHTER: incBrightness(); break; case IR21_DARKER: decBrightness(); break; case IR21_OFF: if (bri > 0) briLast = bri; bri = 0; break; case IR21_ON: bri = briLast; break; case IR21_RED: colorFromUint32(COLOR_RED); break; case IR21_REDDISH: colorFromUint32(COLOR_REDDISH); break; case IR21_ORANGE: colorFromUint32(COLOR_ORANGE); break; case IR21_YELLOWISH: colorFromUint32(COLOR_YELLOWISH); break; case IR21_GREEN: colorFromUint32(COLOR_GREEN); break; case IR21_GREENISH: colorFromUint32(COLOR_GREENISH); break; case IR21_TURQUOISE: colorFromUint32(COLOR_TURQUOISE); break; case IR21_CYAN: colorFromUint32(COLOR_CYAN); break; case IR21_BLUE: colorFromUint32(COLOR_BLUE); break; case IR21_DEEPBLUE: colorFromUint32(COLOR_DEEPBLUE); break; case IR21_PURPLE: colorFromUint32(COLOR_PURPLE); break; case IR21_PINK: colorFromUint32(COLOR_PINK); break; case IR21_WHITE: colorFromUint32(COLOR_WHITE); effectCurrent = 0; break; case IR21_FLASH: presetFallback(1, FX_MODE_COLORTWINKLE, 0); break; case IR21_STROBE: presetFallback(2, FX_MODE_RAINBOW_CYCLE, 0); break; case IR21_FADE: presetFallback(3, FX_MODE_BREATH, 0); break; case IR21_SMOOTH: presetFallback(4, FX_MODE_RAINBOW, 0); break; default: return; } lastValidCode = code; } void decodeIR6(uint32_t code) { switch (code) { case IR6_POWER: toggleOnOff(); break; case IR6_CHANNEL_UP: incBrightness(); break; case IR6_CHANNEL_DOWN: decBrightness(); break; case IR6_VOLUME_UP: relativeChange(&effectCurrent, 1, 0, MODE_COUNT); break; // next effect case IR6_VOLUME_DOWN: // next palette relativeChange(&effectPalette, 1, 0, strip.getPaletteCount() -1); switch(lastIR6ColourIdx) { case 0: colorFromUint32(COLOR_RED); break; case 1: colorFromUint32(COLOR_REDDISH); break; case 2: colorFromUint32(COLOR_ORANGE); break; case 3: colorFromUint32(COLOR_YELLOWISH); break; case 4: colorFromUint32(COLOR_GREEN); break; case 5: colorFromUint32(COLOR_GREENISH); break; case 6: colorFromUint32(COLOR_TURQUOISE); break; case 7: colorFromUint32(COLOR_CYAN); break; case 8: colorFromUint32(COLOR_BLUE); break; case 9: colorFromUint32(COLOR_DEEPBLUE); break; case 10:colorFromUint32(COLOR_PURPLE); break; case 11:colorFromUint32(COLOR_PINK); break; case 12:colorFromUint32(COLOR_WHITE); break; default: break; } lastIR6ColourIdx++; if(lastIR6ColourIdx > 12) lastIR6ColourIdx = 0; break; case IR6_MUTE: effectCurrent = 0; effectPalette = 0; colorFromUint32(COLOR_WHITE); bri=255; break; } lastValidCode = code; } void decodeIR9(uint32_t code) { switch (code) { case IR9_POWER : toggleOnOff(); break; case IR9_A : presetFallback(1, FX_MODE_COLORTWINKLE, effectPalette); break; case IR9_B : presetFallback(2, FX_MODE_RAINBOW_CYCLE, effectPalette); break; case IR9_C : presetFallback(3, FX_MODE_BREATH, effectPalette); break; case IR9_UP : incBrightness(); break; case IR9_DOWN : decBrightness(); break; //case IR9_UP : changeEffectIntensity(16); break; //case IR9_DOWN : changeEffectIntensity(-16); break; case IR9_LEFT : changeEffectSpeed(-16); break; case IR9_RIGHT : changeEffectSpeed(16); break; case IR9_SELECT : relativeChange(&effectCurrent, 1, 0, MODE_COUNT); break; default: return; } lastValidCode = code; } /* This allows users to customize IR actions without the need to edit C code and compile. From the https://github.com/Aircoookie/WLED/wiki/Infrared-Control page, download the starter ir.json file that corresponds to the number of buttons on your remote. Many of the remotes with the same number of buttons emit the same codes, but will have different labels or colors. Once you edit the ir.json file, upload it to your controller using the /edit page. Each key should be the hex encoded IR code. The "cmd" property should be the HTTP API or JSON API command to execute on button press. If the command contains a relative change (SI=~16), it will register as a repeatable command. If the command doesn't contain a "~" but is repeatable, add "rpt" property set to true. Other properties are ignored but having labels and positions can assist with editing the json file. Sample: { "0xFF629D": {"cmd": "T=2", "rpt": true, "label": "Toggle on/off"}, // HTTP command "0xFF9867": {"cmd": "A=~16", "label": "Inc brightness"}, // HTTP command with incrementing "0xFF38C7": {"cmd": {"bri": 10}, "label": "Dim to 10"}, // JSON command "0xFF22DD": {"cmd": "!presetFallback", "PL": 1, "FX": 16, "FP": 6, // Custom command "label": "Preset 1, fallback to Saw - Party if not found"}, } */ void decodeIRJson(uint32_t code) { char objKey[10]; const char* cmd; String cmdStr; byte irError; DynamicJsonDocument irDoc(JSON_BUFFER_SIZE); JsonObject fdo; JsonObject jsonCmdObj; sprintf(objKey, "\"0x%X\":", code); irError = readObjectFromFile("/ir.json", objKey, &irDoc) ? ERR_NONE : ERR_FS_PLOAD; fdo = irDoc.as<JsonObject>(); lastValidCode = 0; if (!irError) { cmd = fdo["cmd"]; cmdStr = String(cmd); jsonCmdObj = fdo["cmd"]; if (!cmdStr.isEmpty()) { if (cmdStr.startsWith("!")) { // call limited set of C functions if (cmdStr.startsWith(F("!incBri"))) { lastValidCode = code; incBrightness(); } else if (cmdStr.startsWith(F("!decBri"))) { lastValidCode = code; decBrightness(); } else if (cmdStr.startsWith(F("!presetF"))) { //!presetFallback uint8_t p1 = fdo["PL"] ? fdo["PL"] : 1; uint8_t p2 = fdo["FX"] ? fdo["FX"] : random8(100); uint8_t p3 = fdo["FP"] ? fdo["FP"] : 0; presetFallback(p1, p2, p3); } } else { // HTTP API command if (cmdStr.indexOf("~") || fdo["rpt"]) { // repeatable action lastValidCode = code; } if (effectCurrent == 0 && cmdStr.indexOf("FP=") > -1) { // setting palette but it wont show because effect is solid effectCurrent = FX_MODE_GRADIENT; } if (!cmdStr.startsWith("win&")) { cmdStr = "win&" + cmdStr; } handleSet(nullptr, cmdStr, false); } } else if (!jsonCmdObj.isNull()) { // command is JSON object //allow applyPreset() to reuse JSON buffer, or it would alloc. a second buffer and run out of mem. fileDoc = &irDoc; deserializeState(jsonCmdObj, CALL_MODE_BUTTON); fileDoc = nullptr; } } } void initIR() { if (irEnabled > 0) { irrecv = new IRrecv(irPin); irrecv->enableIRIn(); } } void handleIR() { if (irEnabled > 0 && millis() - irCheckedTime > 120) { irCheckedTime = millis(); if (irEnabled > 0) { if (irrecv == NULL) { initIR(); return; } if (irrecv->decode(&results)) { if (results.value != 0) // only print results if anything is received ( != 0 ) { Serial.print("IR recv\r\n0x"); Serial.println((uint32_t)results.value, HEX); Serial.println(); } decodeIR(results.value); irrecv->resume(); } } else if (irrecv != NULL) { irrecv->disableIRIn(); delete irrecv; irrecv = NULL; } } } #endif
/** tabular_dataset.cc -*- C++ -*- Jeremy Barnes, 26 November 2015 Copyright (c) 2015 Datacratic Inc. All rights reserved. This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved. */ #include "tabular_dataset.h" #include "mldb/arch/timers.h" #include "mldb/types/basic_value_descriptions.h" #include "mldb/ml/jml/training_index_entry.h" #include "mldb/jml/utils/smart_ptr_utils.h" #include "mldb/server/bucket.h" #include <mutex> using namespace std; namespace Datacratic { namespace MLDB { static constexpr size_t TABULAR_DATASET_DEFAULT_ROWS_PER_CHUNK=65536; /*****************************************************************************/ /* TABULAR DATA STORE */ /*****************************************************************************/ /** Data store that can record tabular data and act as a matrix and column view to the underlying data. */ struct TabularDataset::TabularDataStore: public ColumnIndex, public MatrixView { TabularDataStore() : rowCount(0), mutableChunksIsEmpty(true) { } struct TabularDataStoreRowStream : public RowStream { TabularDataStoreRowStream(TabularDataStore * store) : store(store) {} virtual std::shared_ptr<RowStream> clone() const{ auto ptr = std::make_shared<TabularDataStoreRowStream>(store); return ptr; } virtual void initAt(size_t start){ size_t sum = 0; chunkiter = store->chunks.begin(); while (chunkiter != store->chunks.end() && start > sum + chunkiter->rowNames.size()) { sum += chunkiter->rowNames.size(); ++chunkiter; } if (chunkiter != store->chunks.end()) { rowiter = chunkiter->rowNames.begin() + (start - sum); } } virtual RowName next() { RowName row = *rowiter; rowiter++; if (rowiter == chunkiter->rowNames.end()) { ++chunkiter; if (chunkiter != store->chunks.end()) { rowiter = chunkiter->rowNames.begin(); ExcAssert(rowiter != chunkiter->rowNames.end()); } } return row; } TabularDataStore* store; std::vector<TabularDatasetChunk>::const_iterator chunkiter; std::vector<RowName>::const_iterator rowiter; }; int64_t rowCount; std::vector<ColumnName> columnNames; std::vector<ColumnHash> columnHashes; ML::Lightweight_Hash<ColumnHash, int> columnIndex; std::vector<TabularDatasetChunk> chunks; std::atomic<bool> mutableChunksIsEmpty; std::vector<TabularDatasetChunk> mutableChunks; /// Index from rowHash to (chunk, indexInChunk) when line number not used for rowName ML::Lightweight_Hash<RowHash, std::pair<int, int> > rowIndex; std::string filename; Date earliestTs, latestTs; std::mutex datasetMutex; // Return the value of the column for all rows virtual MatrixColumn getColumn(const ColumnName & column) const { auto it = columnIndex.find(column); if (it == columnIndex.end()) { throw HttpReturnException(400, "Tabular dataset contains no column with given hash", "columnHash", column, "knownColumns", columnNames); } MatrixColumn result; result.columnHash = result.columnName = column; for (unsigned i = 0; i < chunks.size(); ++i) { chunks[i].addToColumn(it->second, result.rows); } return result; } virtual std::vector<CellValue> getColumnDense(const ColumnName & column) const { auto it = columnIndex.find(column); if (it == columnIndex.end()) { throw HttpReturnException(400, "Tabular dataset contains no column with given name", "columnName", column, "knownColumns", columnNames); } std::vector<CellValue> result; result.reserve(rowCount); for (unsigned i = 0; i < chunks.size(); ++i) { auto onValue = [&] (size_t n, CellValue val) { result.emplace_back(std::move(val)); return true; }; chunks[i].columns[it->second].forEach(onValue); } return result; } virtual std::tuple<BucketList, BucketDescriptions> getColumnBuckets(const ColumnName & column, int maxNumBuckets) const override { auto it = columnIndex.find(column); if (it == columnIndex.end()) { throw HttpReturnException(400, "Tabular dataset contains no column with given name", "columnName", column, "knownColumns", columnNames); } std::unordered_map<CellValue, size_t> values; std::vector<CellValue> valueList; size_t totalRows = 0; for (unsigned i = 0; i < chunks.size(); ++i) { auto onValue = [&] (CellValue val, size_t /* count */) { if (values.insert({val,0}).second) valueList.push_back(std::move(val)); return true; }; chunks[i].columns[it->second].forEachDistinctValue(onValue); totalRows += chunks[i].rowCount(); } BucketDescriptions descriptions; descriptions.initialize(valueList, maxNumBuckets); for (auto & v: values) { v.second = descriptions.getBucket(v.first); } // Finally, perform the bucketed lookup WritableBucketList buckets(totalRows, descriptions.numBuckets()); for (unsigned i = 0; i < chunks.size(); ++i) { auto onValue = [&] (size_t, const CellValue & val) { uint32_t bucket = values[val]; buckets.write(bucket); return true; }; chunks[i].columns[it->second].forEach(onValue); } return std::make_tuple(std::move(buckets), std::move(descriptions)); } virtual uint64_t getColumnRowCount(const ColumnName & column) const { return rowCount; } virtual bool knownColumn(const ColumnName & column) const { return columnIndex.count(column); } virtual std::vector<ColumnName> getColumnNames() const { return columnNames; } // TODO: we know more than this... virtual KnownColumn getKnownColumnInfo(const ColumnName & columnName) const { auto it = columnIndex.find(columnName); if (it == columnIndex.end()) { throw HttpReturnException(400, "Tabular dataset contains no column with given hash", "columnName", columnName, "knownColumns", columnNames); } ColumnTypes types; for (auto & c: chunks) { types.update(c.columns[it->second].columnTypes); } #if 0 using namespace std; cerr << "knownColumnInfo for " << columnName << " is " << jsonEncodeStr(types.getExpressionValueInfo()) << endl; cerr << "hasNulls = " << types.hasNulls << endl; cerr << "hasIntegers = " << types.hasIntegers << endl; cerr << "minNegativeInteger = " << types.minNegativeInteger; cerr << "maxPositiveInteger = " << types.maxPositiveInteger; cerr << "hasReals = " << types.hasReals << endl; cerr << "hasStrings = " << types.hasStrings << endl; cerr << "hasOther = " << types.hasOther << endl; #endif return KnownColumn(columnName, types.getExpressionValueInfo(), COLUMN_IS_DENSE); } virtual std::vector<RowName> getRowNames(ssize_t start = 0, ssize_t limit = -1) const { ExcAssertEqual(start, 0); ExcAssertEqual(limit, -1); std::vector<RowName> result; result.reserve(rowCount); for (auto & c: chunks) { result.insert(result.end(), c.rowNames.begin(), c.rowNames.end()); } std::sort(result.begin(), result.end(), [] (const RowName & n1, const RowName & n2) { return n1.hash() < n2.hash(); }); return result; } virtual std::vector<RowHash> getRowHashes(ssize_t start = 0, ssize_t limit = -1) const { ExcAssertEqual(start, 0); ExcAssertEqual(limit, -1); std::vector<RowHash> result; for (auto & i: rowIndex) { result.emplace_back(i.first); } return result; } std::pair<int, int> tryLookupRow(const RowName & rowName) const { auto it = rowIndex.find(rowName); if (it == rowIndex.end()) return { -1, -1 }; return it->second; } std::pair<int, int> lookupRow(const RowName & rowName) const { auto result = tryLookupRow(rowName); if (result.first == -1) throw HttpReturnException(400, "Row not found in CSV dataset"); return result; } virtual bool knownRow(const RowName & rowName) const { int chunkIndex; int rowIndex; std::tie(chunkIndex, rowIndex) = tryLookupRow(rowName); return chunkIndex >= 0; } virtual MatrixNamedRow getRow(const RowName & rowName) const { //cerr << "getting row " << rowName << endl; MatrixNamedRow result; result.rowHash = rowName; result.rowName = rowName; auto it = rowIndex.find(rowName); if (it == rowIndex.end()) { throw HttpReturnException(400, "Row not found in CSV dataset"); } //cerr << "row is in chunk " << it->second.first << " offset " // << it->second.second << endl; Date ts = chunks.at(it->second.first).timestamps[it->second.second].toTimestamp(); for (unsigned i = 0; i < columnNames.size(); ++i) { result.columns.emplace_back(columnNames[i], chunks.at(it->second.first).columns.at(i)[it->second.second], ts); } return result; } virtual RowName getRowName(const RowHash & rowHash) const { auto it = rowIndex.find(rowHash); if (it == rowIndex.end()) { throw HttpReturnException(400, "Row not found in CSV dataset"); } return RowName(chunks.at(it->second.first).rowNames[it->second.second].toUtf8String()); } virtual ColumnName getColumnName(ColumnHash column) const { auto it = columnIndex.find(column); if (it == columnIndex.end()) throw HttpReturnException(400, "CSV dataset contains no column with given hash", "columnHash", column, "knownColumns", columnNames, "knownColumnHashes", columnHashes); return columnNames[it->second]; } virtual const ColumnStats & getColumnStats(const ColumnName & column, ColumnStats & stats) const { auto it = columnIndex.find(column); if (it == columnIndex.end()) { throw HttpReturnException(400, "CSV dataset contains no column with given hash", "columnHash", column, "knownColumns", columnNames, "knownColumnHashes", columnHashes); } stats = ColumnStats(); bool isNumeric = true; for (auto & c: chunks) { auto onValue = [&] (const CellValue & value, size_t rowCount) { if (!value.isNumber()) isNumeric = false; stats.values[value].rowCount_ += 1; return true; }; c.columns[it->second].forEachDistinctValue(onValue); } stats.isNumeric_ = isNumeric && !chunks.empty(); stats.rowCount_ = rowCount; return stats; } virtual size_t getRowCount() const { return rowCount; } virtual size_t getColumnCount() const { return columnNames.size(); } virtual std::pair<Date, Date> getTimestampRange() const { return { earliestTs, latestTs }; } GenerateRowsWhereFunction generateRowsWhere(const SqlBindingScope & context, const SqlExpression & where, ssize_t offset, ssize_t limit) const { GenerateRowsWhereFunction result; return result; } void finalize( std::vector<TabularDatasetChunk>& inputChunks, uint64_t totalRows) { rowCount = totalRows; chunks = std::move(inputChunks); ML::Timer rowIndexTimer; //cerr << "creating row index" << endl; rowIndex.reserve(4 * totalRows / 3); //cerr << "rowIndex capacity is " << rowIndex.capacity() << endl; for (unsigned i = 0; i < chunks.size(); ++i) { for (unsigned j = 0; j < chunks[i].rowNames.size(); ++j) { if (!rowIndex.insert({ chunks[i].rowNames[j], { i, j } }).second) throw HttpReturnException(400, "Duplicate row name in CSV dataset", "rowName", chunks[i].rowNames[j]); } } //cerr << "done creating row index" << endl; //cerr << "row index took " << rowIndexTimer.elapsed() << endl; } void initialize(const vector<ColumnName>& columnNames, const ML::Lightweight_Hash<ColumnHash, int>& columnIndex) { this->columnNames = columnNames; this->columnIndex = columnIndex; for (const auto& c : this->columnNames) { ColumnHash ch(c); columnHashes.push_back(ch); } } void commit() { std::unique_lock<std::mutex> guard(datasetMutex); if (!mutableChunks.empty()) { mutableChunks[0].freeze(); finalize(mutableChunks, mutableChunks[0].rowCount()); mutableChunks.resize(0); mutableChunksIsEmpty = true; } } void recordRow(const RowName & rowName, const std::vector<std::tuple<ColumnName, CellValue, Date> > & vals) { if (rowCount > 0) HttpReturnException(400, "Tabular dataset has already been committed, cannot add more rows"); if (mutableChunksIsEmpty) { std::unique_lock<std::mutex> guard(datasetMutex); if (mutableChunks.empty()) { //need to create the mutable chunk vector<ColumnName> columnNames; //The first recorded row will determine the columns ML::Lightweight_Hash<ColumnHash, int> inputColumnIndex; for (unsigned i = 0; i < vals.size(); ++i) { const ColumnName & c = std::get<0>(vals[i]); ColumnHash ch(c); if (!inputColumnIndex.insert(make_pair(ch, i)).second) throw HttpReturnException(400, "Duplicate column name in tabular dataset entry", "columnName", c.toString()); columnNames.push_back(c); } initialize(columnNames, inputColumnIndex); mutableChunks.emplace_back(columnNames.size(), TABULAR_DATASET_DEFAULT_ROWS_PER_CHUNK); mutableChunksIsEmpty = false; } } std::vector<CellValue> orderedVals(columnNames.size()); Date ts = Date::negativeInfinity(); for (unsigned i = 0; i < vals.size(); ++i) { const ColumnName & c = std::get<0>(vals[i]); auto iter = columnIndex.find(c); if (iter == columnIndex.end()) throw HttpReturnException(400, "New column name while recording row in tabular dataset", "columnName", c.toString()); orderedVals[iter->second] = std::get<1>(vals[i]); ts = std::max(ts, std::get<2>(vals[i])); } { std::unique_lock<std::mutex> guard(datasetMutex); mutableChunks[0].add(rowName, ts, orderedVals.data()); } } }; TabularDataset:: TabularDataset(MldbServer * owner, PolyConfig config, const std::function<bool (const Json::Value &)> & onProgress) : Dataset(owner) { itl = make_shared<TabularDataStore>(); } void TabularDataset:: initialize(const vector<ColumnName>& columnNames, const ML::Lightweight_Hash<ColumnHash, int>& columnIndex) { itl->initialize(columnNames, columnIndex); } TabularDatasetChunk* TabularDataset:: createNewChunk(size_t rowsPerChunk) { return new TabularDatasetChunk(itl->columnNames.size(), rowsPerChunk); } void TabularDataset:: finalize( std::vector<TabularDatasetChunk>& inputChunks, uint64_t totalRows) { itl->finalize(inputChunks, totalRows); } TabularDataset:: ~TabularDataset() { } Any TabularDataset:: getStatus() const { Json::Value status; status["rowCount"] = itl->rowCount; return status; } std::pair<Date, Date> TabularDataset:: getTimestampRange() const { return itl->getTimestampRange(); } std::shared_ptr<MatrixView> TabularDataset:: getMatrixView() const { return itl; } std::shared_ptr<ColumnIndex> TabularDataset:: getColumnIndex() const { return itl; } std::shared_ptr<RowStream> TabularDataset:: getRowStream() const { return std::make_shared<TabularDataStore::TabularDataStoreRowStream>(itl.get()); } GenerateRowsWhereFunction TabularDataset:: generateRowsWhere(const SqlBindingScope & context, const Utf8String& alias, const SqlExpression & where, ssize_t offset, ssize_t limit) const { GenerateRowsWhereFunction fn = itl->generateRowsWhere(context, where, offset, limit); if (!fn) fn = Dataset::generateRowsWhere(context, alias, where, offset, limit); return fn; } KnownColumn TabularDataset:: getKnownColumnInfo(const ColumnName & columnName) const { return itl->getKnownColumnInfo(columnName); } void TabularDataset:: commit() { return itl->commit(); } void TabularDataset:: recordRowItl(const RowName & rowName, const std::vector<std::tuple<ColumnName, CellValue, Date> > & vals) { validateNames(rowName, vals); return itl->recordRow(rowName, vals); } struct TabularDatasetConfig { }; DECLARE_STRUCTURE_DESCRIPTION(TabularDatasetConfig); DEFINE_STRUCTURE_DESCRIPTION(TabularDatasetConfig); TabularDatasetConfigDescription:: TabularDatasetConfigDescription() { nullAccepted = true; } namespace { RegisterDatasetType<TabularDataset, TabularDatasetConfig> regTabular(builtinPackage(), "tabular", "Dense dataset which can be recorded to", "datasets/TabularDataset.md.html"); } // file scope*/ } // MLDB } // Datacratic dont sort by row hash in tabular dataset::getrownames because its unnecessary. /** tabular_dataset.cc -*- C++ -*- Jeremy Barnes, 26 November 2015 Copyright (c) 2015 Datacratic Inc. All rights reserved. This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved. */ #include "tabular_dataset.h" #include "mldb/arch/timers.h" #include "mldb/types/basic_value_descriptions.h" #include "mldb/ml/jml/training_index_entry.h" #include "mldb/jml/utils/smart_ptr_utils.h" #include "mldb/server/bucket.h" #include "mldb/jml/utils/profile.h" #include <mutex> using namespace std; namespace Datacratic { namespace MLDB { static constexpr size_t TABULAR_DATASET_DEFAULT_ROWS_PER_CHUNK=65536; /*****************************************************************************/ /* TABULAR DATA STORE */ /*****************************************************************************/ /** Data store that can record tabular data and act as a matrix and column view to the underlying data. */ struct TabularDataset::TabularDataStore: public ColumnIndex, public MatrixView { TabularDataStore() : rowCount(0), mutableChunksIsEmpty(true) { } struct TabularDataStoreRowStream : public RowStream { TabularDataStoreRowStream(TabularDataStore * store) : store(store) {} virtual std::shared_ptr<RowStream> clone() const{ auto ptr = std::make_shared<TabularDataStoreRowStream>(store); return ptr; } virtual void initAt(size_t start){ size_t sum = 0; chunkiter = store->chunks.begin(); while (chunkiter != store->chunks.end() && start > sum + chunkiter->rowNames.size()) { sum += chunkiter->rowNames.size(); ++chunkiter; } if (chunkiter != store->chunks.end()) { rowiter = chunkiter->rowNames.begin() + (start - sum); } } virtual RowName next() { RowName row = *rowiter; rowiter++; if (rowiter == chunkiter->rowNames.end()) { ++chunkiter; if (chunkiter != store->chunks.end()) { rowiter = chunkiter->rowNames.begin(); ExcAssert(rowiter != chunkiter->rowNames.end()); } } return row; } TabularDataStore* store; std::vector<TabularDatasetChunk>::const_iterator chunkiter; std::vector<RowName>::const_iterator rowiter; }; int64_t rowCount; std::vector<ColumnName> columnNames; std::vector<ColumnHash> columnHashes; ML::Lightweight_Hash<ColumnHash, int> columnIndex; std::vector<TabularDatasetChunk> chunks; std::atomic<bool> mutableChunksIsEmpty; std::vector<TabularDatasetChunk> mutableChunks; /// Index from rowHash to (chunk, indexInChunk) when line number not used for rowName ML::Lightweight_Hash<RowHash, std::pair<int, int> > rowIndex; std::string filename; Date earliestTs, latestTs; std::mutex datasetMutex; // Return the value of the column for all rows virtual MatrixColumn getColumn(const ColumnName & column) const { auto it = columnIndex.find(column); if (it == columnIndex.end()) { throw HttpReturnException(400, "Tabular dataset contains no column with given hash", "columnHash", column, "knownColumns", columnNames); } MatrixColumn result; result.columnHash = result.columnName = column; for (unsigned i = 0; i < chunks.size(); ++i) { chunks[i].addToColumn(it->second, result.rows); } return result; } virtual std::vector<CellValue> getColumnDense(const ColumnName & column) const { auto it = columnIndex.find(column); if (it == columnIndex.end()) { throw HttpReturnException(400, "Tabular dataset contains no column with given name", "columnName", column, "knownColumns", columnNames); } std::vector<CellValue> result; result.reserve(rowCount); for (unsigned i = 0; i < chunks.size(); ++i) { auto onValue = [&] (size_t n, CellValue val) { result.emplace_back(std::move(val)); return true; }; chunks[i].columns[it->second].forEach(onValue); } return result; } virtual std::tuple<BucketList, BucketDescriptions> getColumnBuckets(const ColumnName & column, int maxNumBuckets) const override { auto it = columnIndex.find(column); if (it == columnIndex.end()) { throw HttpReturnException(400, "Tabular dataset contains no column with given name", "columnName", column, "knownColumns", columnNames); } std::unordered_map<CellValue, size_t> values; std::vector<CellValue> valueList; size_t totalRows = 0; for (unsigned i = 0; i < chunks.size(); ++i) { auto onValue = [&] (CellValue val, size_t /* count */) { if (values.insert({val,0}).second) valueList.push_back(std::move(val)); return true; }; chunks[i].columns[it->second].forEachDistinctValue(onValue); totalRows += chunks[i].rowCount(); } BucketDescriptions descriptions; descriptions.initialize(valueList, maxNumBuckets); for (auto & v: values) { v.second = descriptions.getBucket(v.first); } // Finally, perform the bucketed lookup WritableBucketList buckets(totalRows, descriptions.numBuckets()); for (unsigned i = 0; i < chunks.size(); ++i) { auto onValue = [&] (size_t, const CellValue & val) { uint32_t bucket = values[val]; buckets.write(bucket); return true; }; chunks[i].columns[it->second].forEach(onValue); } return std::make_tuple(std::move(buckets), std::move(descriptions)); } virtual uint64_t getColumnRowCount(const ColumnName & column) const { return rowCount; } virtual bool knownColumn(const ColumnName & column) const { return columnIndex.count(column); } virtual std::vector<ColumnName> getColumnNames() const { return columnNames; } // TODO: we know more than this... virtual KnownColumn getKnownColumnInfo(const ColumnName & columnName) const { auto it = columnIndex.find(columnName); if (it == columnIndex.end()) { throw HttpReturnException(400, "Tabular dataset contains no column with given hash", "columnName", columnName, "knownColumns", columnNames); } ColumnTypes types; for (auto & c: chunks) { types.update(c.columns[it->second].columnTypes); } #if 0 using namespace std; cerr << "knownColumnInfo for " << columnName << " is " << jsonEncodeStr(types.getExpressionValueInfo()) << endl; cerr << "hasNulls = " << types.hasNulls << endl; cerr << "hasIntegers = " << types.hasIntegers << endl; cerr << "minNegativeInteger = " << types.minNegativeInteger; cerr << "maxPositiveInteger = " << types.maxPositiveInteger; cerr << "hasReals = " << types.hasReals << endl; cerr << "hasStrings = " << types.hasStrings << endl; cerr << "hasOther = " << types.hasOther << endl; #endif return KnownColumn(columnName, types.getExpressionValueInfo(), COLUMN_IS_DENSE); } virtual std::vector<RowName> getRowNames(ssize_t start = 0, ssize_t limit = -1) const { ExcAssertEqual(start, 0); ExcAssertEqual(limit, -1); std::vector<RowName> result; result.reserve(rowCount); for (auto & c: chunks) { result.insert(result.end(), c.rowNames.begin(), c.rowNames.end()); } return result; } virtual std::vector<RowHash> getRowHashes(ssize_t start = 0, ssize_t limit = -1) const { ExcAssertEqual(start, 0); ExcAssertEqual(limit, -1); std::vector<RowHash> result; for (auto & i: rowIndex) { result.emplace_back(i.first); } return result; } std::pair<int, int> tryLookupRow(const RowName & rowName) const { auto it = rowIndex.find(rowName); if (it == rowIndex.end()) return { -1, -1 }; return it->second; } std::pair<int, int> lookupRow(const RowName & rowName) const { auto result = tryLookupRow(rowName); if (result.first == -1) throw HttpReturnException(400, "Row not found in CSV dataset"); return result; } virtual bool knownRow(const RowName & rowName) const { int chunkIndex; int rowIndex; std::tie(chunkIndex, rowIndex) = tryLookupRow(rowName); return chunkIndex >= 0; } virtual MatrixNamedRow getRow(const RowName & rowName) const { //cerr << "getting row " << rowName << endl; MatrixNamedRow result; result.rowHash = rowName; result.rowName = rowName; auto it = rowIndex.find(rowName); if (it == rowIndex.end()) { throw HttpReturnException(400, "Row not found in CSV dataset"); } //cerr << "row is in chunk " << it->second.first << " offset " // << it->second.second << endl; Date ts = chunks.at(it->second.first).timestamps[it->second.second].toTimestamp(); for (unsigned i = 0; i < columnNames.size(); ++i) { result.columns.emplace_back(columnNames[i], chunks.at(it->second.first).columns.at(i)[it->second.second], ts); } return result; } virtual RowName getRowName(const RowHash & rowHash) const { auto it = rowIndex.find(rowHash); if (it == rowIndex.end()) { throw HttpReturnException(400, "Row not found in CSV dataset"); } return RowName(chunks.at(it->second.first).rowNames[it->second.second].toUtf8String()); } virtual ColumnName getColumnName(ColumnHash column) const { auto it = columnIndex.find(column); if (it == columnIndex.end()) throw HttpReturnException(400, "CSV dataset contains no column with given hash", "columnHash", column, "knownColumns", columnNames, "knownColumnHashes", columnHashes); return columnNames[it->second]; } virtual const ColumnStats & getColumnStats(const ColumnName & column, ColumnStats & stats) const { auto it = columnIndex.find(column); if (it == columnIndex.end()) { throw HttpReturnException(400, "CSV dataset contains no column with given hash", "columnHash", column, "knownColumns", columnNames, "knownColumnHashes", columnHashes); } stats = ColumnStats(); bool isNumeric = true; for (auto & c: chunks) { auto onValue = [&] (const CellValue & value, size_t rowCount) { if (!value.isNumber()) isNumeric = false; stats.values[value].rowCount_ += 1; return true; }; c.columns[it->second].forEachDistinctValue(onValue); } stats.isNumeric_ = isNumeric && !chunks.empty(); stats.rowCount_ = rowCount; return stats; } virtual size_t getRowCount() const { return rowCount; } virtual size_t getColumnCount() const { return columnNames.size(); } virtual std::pair<Date, Date> getTimestampRange() const { return { earliestTs, latestTs }; } GenerateRowsWhereFunction generateRowsWhere(const SqlBindingScope & context, const SqlExpression & where, ssize_t offset, ssize_t limit) const { GenerateRowsWhereFunction result; return result; } void finalize( std::vector<TabularDatasetChunk>& inputChunks, uint64_t totalRows) { rowCount = totalRows; chunks = std::move(inputChunks); ML::Timer rowIndexTimer; //cerr << "creating row index" << endl; rowIndex.reserve(4 * totalRows / 3); //cerr << "rowIndex capacity is " << rowIndex.capacity() << endl; for (unsigned i = 0; i < chunks.size(); ++i) { for (unsigned j = 0; j < chunks[i].rowNames.size(); ++j) { if (!rowIndex.insert({ chunks[i].rowNames[j], { i, j } }).second) throw HttpReturnException(400, "Duplicate row name in CSV dataset", "rowName", chunks[i].rowNames[j]); } } //cerr << "done creating row index" << endl; //cerr << "row index took " << rowIndexTimer.elapsed() << endl; } void initialize(const vector<ColumnName>& columnNames, const ML::Lightweight_Hash<ColumnHash, int>& columnIndex) { this->columnNames = columnNames; this->columnIndex = columnIndex; for (const auto& c : this->columnNames) { ColumnHash ch(c); columnHashes.push_back(ch); } } void commit() { std::unique_lock<std::mutex> guard(datasetMutex); if (!mutableChunks.empty()) { mutableChunks[0].freeze(); finalize(mutableChunks, mutableChunks[0].rowCount()); mutableChunks.resize(0); mutableChunksIsEmpty = true; } } void recordRow(const RowName & rowName, const std::vector<std::tuple<ColumnName, CellValue, Date> > & vals) { if (rowCount > 0) HttpReturnException(400, "Tabular dataset has already been committed, cannot add more rows"); if (mutableChunksIsEmpty) { std::unique_lock<std::mutex> guard(datasetMutex); if (mutableChunks.empty()) { //need to create the mutable chunk vector<ColumnName> columnNames; //The first recorded row will determine the columns ML::Lightweight_Hash<ColumnHash, int> inputColumnIndex; for (unsigned i = 0; i < vals.size(); ++i) { const ColumnName & c = std::get<0>(vals[i]); ColumnHash ch(c); if (!inputColumnIndex.insert(make_pair(ch, i)).second) throw HttpReturnException(400, "Duplicate column name in tabular dataset entry", "columnName", c.toString()); columnNames.push_back(c); } initialize(columnNames, inputColumnIndex); mutableChunks.emplace_back(columnNames.size(), TABULAR_DATASET_DEFAULT_ROWS_PER_CHUNK); mutableChunksIsEmpty = false; } } std::vector<CellValue> orderedVals(columnNames.size()); Date ts = Date::negativeInfinity(); for (unsigned i = 0; i < vals.size(); ++i) { const ColumnName & c = std::get<0>(vals[i]); auto iter = columnIndex.find(c); if (iter == columnIndex.end()) throw HttpReturnException(400, "New column name while recording row in tabular dataset", "columnName", c.toString()); orderedVals[iter->second] = std::get<1>(vals[i]); ts = std::max(ts, std::get<2>(vals[i])); } { std::unique_lock<std::mutex> guard(datasetMutex); mutableChunks[0].add(rowName, ts, orderedVals.data()); } } }; TabularDataset:: TabularDataset(MldbServer * owner, PolyConfig config, const std::function<bool (const Json::Value &)> & onProgress) : Dataset(owner) { itl = make_shared<TabularDataStore>(); } void TabularDataset:: initialize(const vector<ColumnName>& columnNames, const ML::Lightweight_Hash<ColumnHash, int>& columnIndex) { itl->initialize(columnNames, columnIndex); } TabularDatasetChunk* TabularDataset:: createNewChunk(size_t rowsPerChunk) { return new TabularDatasetChunk(itl->columnNames.size(), rowsPerChunk); } void TabularDataset:: finalize( std::vector<TabularDatasetChunk>& inputChunks, uint64_t totalRows) { itl->finalize(inputChunks, totalRows); } TabularDataset:: ~TabularDataset() { } Any TabularDataset:: getStatus() const { Json::Value status; status["rowCount"] = itl->rowCount; return status; } std::pair<Date, Date> TabularDataset:: getTimestampRange() const { return itl->getTimestampRange(); } std::shared_ptr<MatrixView> TabularDataset:: getMatrixView() const { return itl; } std::shared_ptr<ColumnIndex> TabularDataset:: getColumnIndex() const { return itl; } std::shared_ptr<RowStream> TabularDataset:: getRowStream() const { return std::make_shared<TabularDataStore::TabularDataStoreRowStream>(itl.get()); } GenerateRowsWhereFunction TabularDataset:: generateRowsWhere(const SqlBindingScope & context, const Utf8String& alias, const SqlExpression & where, ssize_t offset, ssize_t limit) const { GenerateRowsWhereFunction fn = itl->generateRowsWhere(context, where, offset, limit); if (!fn) fn = Dataset::generateRowsWhere(context, alias, where, offset, limit); return fn; } KnownColumn TabularDataset:: getKnownColumnInfo(const ColumnName & columnName) const { return itl->getKnownColumnInfo(columnName); } void TabularDataset:: commit() { return itl->commit(); } void TabularDataset:: recordRowItl(const RowName & rowName, const std::vector<std::tuple<ColumnName, CellValue, Date> > & vals) { validateNames(rowName, vals); return itl->recordRow(rowName, vals); } struct TabularDatasetConfig { }; DECLARE_STRUCTURE_DESCRIPTION(TabularDatasetConfig); DEFINE_STRUCTURE_DESCRIPTION(TabularDatasetConfig); TabularDatasetConfigDescription:: TabularDatasetConfigDescription() { nullAccepted = true; } namespace { RegisterDatasetType<TabularDataset, TabularDatasetConfig> regTabular(builtinPackage(), "tabular", "Dense dataset which can be recorded to", "datasets/TabularDataset.md.html"); } // file scope*/ } // MLDB } // Datacratic
/**************************************************************************** * * Copyright (c) 2014-2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /// @file mavlink_ftp.cpp /// @author px4dev, Don Gagne <don@thegagnes.com> #include <crc32.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <errno.h> #include <cstring> #include "mavlink_ftp.h" #include "mavlink_tests/mavlink_ftp_test.h" #ifndef MAVLINK_FTP_UNIT_TEST #include "mavlink_main.h" #else #include <v2.0/standard/mavlink.h> #endif constexpr const char MavlinkFTP::_root_dir[]; MavlinkFTP::MavlinkFTP(Mavlink *mavlink) : _mavlink(mavlink) { // initialize session _session_info.fd = -1; } MavlinkFTP::~MavlinkFTP() { delete[] _work_buffer1; delete[] _work_buffer2; } unsigned MavlinkFTP::get_size() { if (_session_info.stream_download) { return MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL_LEN + MAVLINK_NUM_NON_PAYLOAD_BYTES; } else { return 0; } } #ifdef MAVLINK_FTP_UNIT_TEST void MavlinkFTP::set_unittest_worker(ReceiveMessageFunc_t rcvMsgFunc, void *worker_data) { _utRcvMsgFunc = rcvMsgFunc; _worker_data = worker_data; } #endif uint8_t MavlinkFTP::_getServerSystemId() { #ifdef MAVLINK_FTP_UNIT_TEST // We use fake ids when unit testing return MavlinkFtpTest::serverSystemId; #else // Not unit testing, use the real thing return _mavlink->get_system_id(); #endif } uint8_t MavlinkFTP::_getServerComponentId() { #ifdef MAVLINK_FTP_UNIT_TEST // We use fake ids when unit testing return MavlinkFtpTest::serverComponentId; #else // Not unit testing, use the real thing return _mavlink->get_component_id(); #endif } uint8_t MavlinkFTP::_getServerChannel() { #ifdef MAVLINK_FTP_UNIT_TEST // We use fake ids when unit testing return MavlinkFtpTest::serverChannel; #else // Not unit testing, use the real thing return _mavlink->get_channel(); #endif } void MavlinkFTP::handle_message(const mavlink_message_t *msg) { //warnx("MavlinkFTP::handle_message %d %d", buf_size_1, buf_size_2); if (msg->msgid == MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL) { mavlink_file_transfer_protocol_t ftp_request; mavlink_msg_file_transfer_protocol_decode(msg, &ftp_request); #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: received ftp protocol message target_system: %d target_component: %d", ftp_request.target_system, ftp_request.target_component); #endif if ((ftp_request.target_system == _getServerSystemId() || ftp_request.target_system == 0) && (ftp_request.target_component == _getServerComponentId() || ftp_request.target_component == 0)) { _process_request(&ftp_request, msg->sysid, msg->compid); } } } /// @brief Processes an FTP message void MavlinkFTP::_process_request( mavlink_file_transfer_protocol_t *ftp_req, uint8_t target_system_id, uint8_t target_comp_id) { bool stream_send = false; PayloadHeader *payload = reinterpret_cast<PayloadHeader *>(&ftp_req->payload[0]); ErrorCode errorCode = kErrNone; if (!_ensure_buffers_exist()) { PX4_ERR("Failed to allocate buffers"); errorCode = kErrFailErrno; errno = ENOMEM; goto out; } // basic sanity checks; must validate length before use if (payload->size > kMaxDataLength) { errorCode = kErrInvalidDataSize; goto out; } // check the sequence number: if this is a resent request, resend the last response if (_last_reply_valid) { mavlink_file_transfer_protocol_t *last_reply = reinterpret_cast<mavlink_file_transfer_protocol_t *>(_last_reply); PayloadHeader *last_payload = reinterpret_cast<PayloadHeader *>(&last_reply->payload[0]); if (payload->seq_number + 1 == last_payload->seq_number) { // this is the same request as the one we replied to last. It means the (n)ack got lost, and the GCS // resent the request #ifdef MAVLINK_FTP_UNIT_TEST _utRcvMsgFunc(last_reply, _worker_data); #else mavlink_msg_file_transfer_protocol_send_struct(_mavlink->get_channel(), last_reply); #endif return; } } #ifdef MAVLINK_FTP_DEBUG PX4_INFO("ftp: channel %u opc %u size %u offset %u", _getServerChannel(), payload->opcode, payload->size, payload->offset); #endif switch (payload->opcode) { case kCmdNone: break; case kCmdTerminateSession: errorCode = _workTerminate(payload); break; case kCmdResetSessions: errorCode = _workReset(payload); break; case kCmdListDirectory: errorCode = _workList(payload); break; case kCmdOpenFileRO: errorCode = _workOpen(payload, O_RDONLY); break; case kCmdCreateFile: errorCode = _workOpen(payload, O_CREAT | O_EXCL | O_WRONLY); break; case kCmdOpenFileWO: errorCode = _workOpen(payload, O_CREAT | O_WRONLY); break; case kCmdReadFile: errorCode = _workRead(payload); break; case kCmdBurstReadFile: errorCode = _workBurst(payload, target_system_id, target_comp_id); stream_send = true; break; case kCmdWriteFile: errorCode = _workWrite(payload); break; case kCmdRemoveFile: errorCode = _workRemoveFile(payload); break; case kCmdRename: errorCode = _workRename(payload); break; case kCmdTruncateFile: errorCode = _workTruncateFile(payload); break; case kCmdCreateDirectory: errorCode = _workCreateDirectory(payload); break; case kCmdRemoveDirectory: errorCode = _workRemoveDirectory(payload); break; case kCmdCalcFileCRC32: errorCode = _workCalcFileCRC32(payload); break; default: errorCode = kErrUnknownCommand; break; } out: payload->seq_number++; // handle success vs. error if (errorCode == kErrNone) { payload->req_opcode = payload->opcode; payload->opcode = kRspAck; } else { int r_errno = errno; payload->req_opcode = payload->opcode; payload->opcode = kRspNak; payload->size = 1; if (r_errno == EEXIST) { errorCode = kErrFailFileExists; } else if (r_errno == ENOENT && errorCode == kErrFailErrno) { errorCode = kErrFileNotFound; } payload->data[0] = errorCode; if (errorCode == kErrFailErrno) { payload->size = 2; payload->data[1] = r_errno; } } _last_reply_valid = false; // Stream download replies are sent through mavlink stream mechanism. Unless we need to Nack. if (!stream_send || errorCode != kErrNone) { // respond to the request ftp_req->target_system = target_system_id; ftp_req->target_network = 0; ftp_req->target_component = target_comp_id; _reply(ftp_req); } } bool MavlinkFTP::_ensure_buffers_exist() { _last_work_buffer_access = hrt_absolute_time(); if (!_work_buffer1) { _work_buffer1 = new char[_work_buffer1_len]; } if (!_work_buffer2) { _work_buffer2 = new char[_work_buffer2_len]; } return _work_buffer1 && _work_buffer2; } /// @brief Sends the specified FTP response message out through mavlink void MavlinkFTP::_reply(mavlink_file_transfer_protocol_t *ftp_req) { PayloadHeader *payload = reinterpret_cast<PayloadHeader *>(&ftp_req->payload[0]); // keep a copy of the last sent response ((n)ack), so that if it gets lost and the GCS resends the request, // we can simply resend the response. // we only keep small responses to reduce RAM usage and avoid large memcpy's. The larger responses are all data // retrievals without side-effects, meaning it's ok to reexecute them if a response gets lost if (payload->size <= sizeof(uint32_t)) { _last_reply_valid = true; memcpy(_last_reply, ftp_req, sizeof(_last_reply)); } #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: %s seq_number: %d", payload->opcode == kRspAck ? "Ack" : "Nak", payload->seq_number); #endif #ifdef MAVLINK_FTP_UNIT_TEST // Unit test hook is set, call that instead _utRcvMsgFunc(ftp_req, _worker_data); #else mavlink_msg_file_transfer_protocol_send_struct(_mavlink->get_channel(), ftp_req); #endif } /// @brief Responds to a List command MavlinkFTP::ErrorCode MavlinkFTP::_workList(PayloadHeader *payload) { strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); // ensure termination _work_buffer1[_work_buffer1_len - 1] = '\0'; ErrorCode errorCode = kErrNone; unsigned offset = 0; DIR *dp = opendir(_work_buffer1); if (dp == nullptr) { PX4_WARN("File open failed %s", _work_buffer1); return kErrFileNotFound; } #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: list %s offset %d", _work_buffer1, payload->offset); #endif struct dirent *result = nullptr; // move to the requested offset int requested_offset = payload->offset; while (requested_offset-- > 0 && readdir(dp)) {} for (;;) { errno = 0; result = readdir(dp); // read the directory entry if (result == nullptr) { if (errno) { PX4_WARN("readdir failed"); payload->data[offset++] = kDirentSkip; *((char *)&payload->data[offset]) = '\0'; offset++; payload->size = offset; closedir(dp); return errorCode; } // no more entries? if (payload->offset != 0 && offset == 0) { // User is requesting subsequent dir entries but there were none. This means the user asked // to seek past EOF. errorCode = kErrEOF; } // Otherwise we are just at the last directory entry, so we leave the errorCode at kErrorNone to signal that break; } uint32_t fileSize = 0; char direntType; // Determine the directory entry type switch (result->d_type) { #ifdef __PX4_NUTTX case DTYPE_FILE: { #else case DT_REG: { #endif // For files we get the file size as well direntType = kDirentFile; int ret = snprintf(_work_buffer2, _work_buffer2_len, "%s/%s", _work_buffer1, result->d_name); bool buf_is_ok = ((ret > 0) && (ret < _work_buffer2_len)); if (buf_is_ok) { struct stat st; if (stat(_work_buffer2, &st) == 0) { fileSize = st.st_size; } } break; } #ifdef __PX4_NUTTX case DTYPE_DIRECTORY: #else case DT_DIR: #endif if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0) { // Don't bother sending these back direntType = kDirentSkip; } else { direntType = kDirentDir; } break; default: // We only send back file and diretory entries, skip everything else direntType = kDirentSkip; } if (direntType == kDirentSkip) { // Skip send only dirent identifier _work_buffer2[0] = '\0'; } else if (direntType == kDirentFile) { // Files send filename and file length int ret = snprintf(_work_buffer2, _work_buffer2_len, "%s\t%d", result->d_name, fileSize); bool buf_is_ok = ((ret > 0) && (ret < _work_buffer2_len)); if (!buf_is_ok) { _work_buffer2[_work_buffer2_len - 1] = '\0'; } } else { // Everything else just sends name strncpy(_work_buffer2, result->d_name, _work_buffer2_len); _work_buffer2[_work_buffer2_len - 1] = '\0'; } size_t nameLen = strlen(_work_buffer2); // Do we have room for the name, the one char directory identifier and the null terminator? if ((offset + nameLen + 2) > kMaxDataLength) { break; } // Move the data into the buffer payload->data[offset++] = direntType; strcpy((char *)&payload->data[offset], _work_buffer2); #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: list %s %s", _work_buffer1, (char *)&payload->data[offset - 1]); #endif offset += nameLen + 1; } closedir(dp); payload->size = offset; return errorCode; } /// @brief Responds to an Open command MavlinkFTP::ErrorCode MavlinkFTP::_workOpen(PayloadHeader *payload, int oflag) { if (_session_info.fd >= 0) { PX4_ERR("FTP: Open failed - out of sessions\n"); return kErrNoSessionsAvailable; } strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: open '%s'", _work_buffer1); #endif uint32_t fileSize = 0; struct stat st; if (stat(_work_buffer1, &st) != 0) { // fail only if requested open for read if (oflag & O_RDONLY) { return kErrFailErrno; } else { st.st_size = 0; } } fileSize = st.st_size; // Set mode to 666 incase oflag has O_CREAT int fd = ::open(_work_buffer1, oflag, PX4_O_MODE_666); if (fd < 0) { return kErrFailErrno; } _session_info.fd = fd; _session_info.file_size = fileSize; _session_info.stream_download = false; payload->session = 0; payload->size = sizeof(uint32_t); std::memcpy(payload->data, &fileSize, payload->size); return kErrNone; } /// @brief Responds to a Read command MavlinkFTP::ErrorCode MavlinkFTP::_workRead(PayloadHeader *payload) { if (payload->session != 0 || _session_info.fd < 0) { return kErrInvalidSession; } #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: read offset:%d", payload->offset); #endif // We have to test seek past EOF ourselves, lseek will allow seek past EOF if (payload->offset >= _session_info.file_size) { PX4_ERR("request past EOF"); return kErrEOF; } if (lseek(_session_info.fd, payload->offset, SEEK_SET) < 0) { PX4_ERR("seek fail"); return kErrFailErrno; } int bytes_read = ::read(_session_info.fd, &payload->data[0], kMaxDataLength); if (bytes_read < 0) { // Negative return indicates error other than eof PX4_ERR("read fail %d", bytes_read); return kErrFailErrno; } payload->size = bytes_read; return kErrNone; } /// @brief Responds to a Stream command MavlinkFTP::ErrorCode MavlinkFTP::_workBurst(PayloadHeader *payload, uint8_t target_system_id, uint8_t target_component_id) { if (payload->session != 0 && _session_info.fd < 0) { return kErrInvalidSession; } #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: burst offset:%d", payload->offset); #endif // Setup for streaming sends _session_info.stream_download = true; _session_info.stream_offset = payload->offset; _session_info.stream_chunk_transmitted = 0; _session_info.stream_seq_number = payload->seq_number + 1; _session_info.stream_target_system_id = target_system_id; _session_info.stream_target_component_id = target_component_id; return kErrNone; } /// @brief Responds to a Write command MavlinkFTP::ErrorCode MavlinkFTP::_workWrite(PayloadHeader *payload) { if (payload->session != 0 && _session_info.fd < 0) { return kErrInvalidSession; } if (lseek(_session_info.fd, payload->offset, SEEK_SET) < 0) { // Unable to see to the specified location PX4_ERR("seek fail"); return kErrFailErrno; } int bytes_written = ::write(_session_info.fd, &payload->data[0], payload->size); if (bytes_written < 0) { // Negative return indicates error other than eof PX4_ERR("write fail %d", bytes_written); return kErrFailErrno; } payload->size = sizeof(uint32_t); std::memcpy(payload->data, &bytes_written, payload->size); return kErrNone; } /// @brief Responds to a RemoveFile command MavlinkFTP::ErrorCode MavlinkFTP::_workRemoveFile(PayloadHeader *payload) { strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); // ensure termination _work_buffer1[_work_buffer1_len - 1] = '\0'; if (unlink(_work_buffer1) == 0) { payload->size = 0; return kErrNone; } else { return kErrFailErrno; } } /// @brief Responds to a TruncateFile command MavlinkFTP::ErrorCode MavlinkFTP::_workTruncateFile(PayloadHeader *payload) { strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); // ensure termination _work_buffer1[_work_buffer1_len - 1] = '\0'; payload->size = 0; #ifdef __PX4_NUTTX // emulate truncate(_work_buffer1, payload->offset) by // copying to temp and overwrite with O_TRUNC flag (NuttX does not support truncate()). const char temp_file[] = PX4_STORAGEDIR"/.trunc.tmp"; struct stat st; if (stat(_work_buffer1, &st) != 0) { return kErrFailErrno; } if (!S_ISREG(st.st_mode)) { errno = EISDIR; return kErrFailErrno; } // check perms allow us to write (not romfs) if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH))) { errno = EROFS; return kErrFailErrno; } if (payload->offset == (unsigned)st.st_size) { // nothing to do return kErrNone; } else if (payload->offset == 0) { // 1: truncate all data int fd = ::open(_work_buffer1, O_TRUNC | O_WRONLY); if (fd < 0) { return kErrFailErrno; } ::close(fd); return kErrNone; } else if (payload->offset > (unsigned)st.st_size) { // 2: extend file int fd = ::open(_work_buffer1, O_WRONLY); if (fd < 0) { return kErrFailErrno; } if (lseek(fd, payload->offset - 1, SEEK_SET) < 0) { ::close(fd); return kErrFailErrno; } bool ok = 1 == ::write(fd, "", 1); ::close(fd); return (ok) ? kErrNone : kErrFailErrno; } else { // 3: truncate if (_copy_file(_work_buffer1, temp_file, payload->offset) != 0) { return kErrFailErrno; } if (_copy_file(temp_file, _work_buffer1, payload->offset) != 0) { return kErrFailErrno; } if (::unlink(temp_file) != 0) { return kErrFailErrno; } return kErrNone; } #else int ret = truncate(_work_buffer1, payload->offset); if (ret == 0) { return kErrNone; } return kErrFailErrno; #endif /* __PX4_NUTTX */ } /// @brief Responds to a Terminate command MavlinkFTP::ErrorCode MavlinkFTP::_workTerminate(PayloadHeader *payload) { if (payload->session != 0 || _session_info.fd < 0) { return kErrInvalidSession; } ::close(_session_info.fd); _session_info.fd = -1; _session_info.stream_download = false; payload->size = 0; return kErrNone; } /// @brief Responds to a Reset command MavlinkFTP::ErrorCode MavlinkFTP::_workReset(PayloadHeader *payload) { if (_session_info.fd != -1) { ::close(_session_info.fd); _session_info.fd = -1; _session_info.stream_download = false; } payload->size = 0; return kErrNone; } /// @brief Responds to a Rename command MavlinkFTP::ErrorCode MavlinkFTP::_workRename(PayloadHeader *payload) { char *ptr = _data_as_cstring(payload); size_t oldpath_sz = strlen(ptr); if (oldpath_sz == payload->size) { // no newpath errno = EINVAL; return kErrFailErrno; } strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, ptr, _work_buffer1_len - _root_dir_len); _work_buffer1[_work_buffer1_len - 1] = '\0'; // ensure termination strncpy(_work_buffer2, _root_dir, _work_buffer2_len); strncpy(_work_buffer2 + _root_dir_len, ptr + oldpath_sz + 1, _work_buffer2_len - _root_dir_len); _work_buffer2[_work_buffer2_len - 1] = '\0'; // ensure termination if (rename(_work_buffer1, _work_buffer2) == 0) { payload->size = 0; return kErrNone; } else { return kErrFailErrno; } } /// @brief Responds to a RemoveDirectory command MavlinkFTP::ErrorCode MavlinkFTP::_workRemoveDirectory(PayloadHeader *payload) { strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); // ensure termination _work_buffer1[_work_buffer1_len - 1] = '\0'; if (rmdir(_work_buffer1) == 0) { payload->size = 0; return kErrNone; } else { return kErrFailErrno; } } /// @brief Responds to a CreateDirectory command MavlinkFTP::ErrorCode MavlinkFTP::_workCreateDirectory(PayloadHeader *payload) { strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); // ensure termination _work_buffer1[_work_buffer1_len - 1] = '\0'; if (mkdir(_work_buffer1, S_IRWXU | S_IRWXG | S_IRWXO) == 0) { payload->size = 0; return kErrNone; } else { return kErrFailErrno; } } /// @brief Responds to a CalcFileCRC32 command MavlinkFTP::ErrorCode MavlinkFTP::_workCalcFileCRC32(PayloadHeader *payload) { uint32_t checksum = 0; ssize_t bytes_read; strncpy(_work_buffer2, _root_dir, _work_buffer2_len); strncpy(_work_buffer2 + _root_dir_len, _data_as_cstring(payload), _work_buffer2_len - _root_dir_len); // ensure termination _work_buffer2[_work_buffer2_len - 1] = '\0'; int fd = ::open(_work_buffer2, O_RDONLY); if (fd < 0) { return kErrFailErrno; } do { bytes_read = ::read(fd, _work_buffer2, _work_buffer2_len); if (bytes_read < 0) { int r_errno = errno; ::close(fd); errno = r_errno; return kErrFailErrno; } checksum = crc32part((uint8_t *)_work_buffer2, bytes_read, checksum); } while (bytes_read == _work_buffer2_len); ::close(fd); payload->size = sizeof(uint32_t); std::memcpy(payload->data, &checksum, payload->size); return kErrNone; } /// @brief Guarantees that the payload data is null terminated. /// @return Returns a pointer to the payload data as a char * char * MavlinkFTP::_data_as_cstring(PayloadHeader *payload) { // guarantee nul termination if (payload->size < kMaxDataLength) { payload->data[payload->size] = '\0'; } else { payload->data[kMaxDataLength - 1] = '\0'; } // and return data return (char *) & (payload->data[0]); } /// @brief Copy file (with limited space) int MavlinkFTP::_copy_file(const char *src_path, const char *dst_path, size_t length) { int src_fd = -1, dst_fd = -1; int op_errno = 0; src_fd = ::open(src_path, O_RDONLY); if (src_fd < 0) { return -1; } dst_fd = ::open(dst_path, O_CREAT | O_TRUNC | O_WRONLY // POSIX requires the permissions to be supplied if O_CREAT passed #ifdef __PX4_POSIX , 0666 #endif ); if (dst_fd < 0) { op_errno = errno; ::close(src_fd); errno = op_errno; return -1; } while (length > 0) { ssize_t bytes_read, bytes_written; size_t blen = (length > _work_buffer2_len) ? _work_buffer2_len : length; bytes_read = ::read(src_fd, _work_buffer2, blen); if (bytes_read == 0) { // EOF break; } else if (bytes_read < 0) { PX4_ERR("cp: read"); op_errno = errno; break; } bytes_written = ::write(dst_fd, _work_buffer2, bytes_read); if (bytes_written != bytes_read) { PX4_ERR("cp: short write"); op_errno = errno; break; } length -= bytes_written; } ::close(src_fd); ::close(dst_fd); errno = op_errno; return (length > 0) ? -1 : 0; } void MavlinkFTP::send(const hrt_abstime t) { if (_work_buffer1 || _work_buffer2) { // free the work buffers if they are not used for a while if (hrt_elapsed_time(&_last_work_buffer_access) > 2000000) { if (_work_buffer1) { delete[] _work_buffer1; _work_buffer1 = nullptr; } if (_work_buffer2) { delete[] _work_buffer2; _work_buffer2 = nullptr; } } } // Anything to stream? if (!_session_info.stream_download) { return; } #ifndef MAVLINK_FTP_UNIT_TEST // Skip send if not enough room unsigned max_bytes_to_send = _mavlink->get_free_tx_buf(); #ifdef MAVLINK_FTP_DEBUG PX4_INFO("MavlinkFTP::send max_bytes_to_send(%d) get_free_tx_buf(%d)", max_bytes_to_send, _mavlink->get_free_tx_buf()); #endif if (max_bytes_to_send < get_size()) { return; } #endif // Send stream packets until buffer is full bool more_data; do { more_data = false; ErrorCode error_code = kErrNone; mavlink_file_transfer_protocol_t ftp_msg; PayloadHeader *payload = reinterpret_cast<PayloadHeader *>(&ftp_msg.payload[0]); payload->seq_number = _session_info.stream_seq_number; payload->session = 0; payload->opcode = kRspAck; payload->req_opcode = kCmdBurstReadFile; payload->offset = _session_info.stream_offset; _session_info.stream_seq_number++; #ifdef MAVLINK_FTP_DEBUG PX4_INFO("stream send: offset %d", _session_info.stream_offset); #endif // We have to test seek past EOF ourselves, lseek will allow seek past EOF if (_session_info.stream_offset >= _session_info.file_size) { error_code = kErrEOF; #ifdef MAVLINK_FTP_DEBUG PX4_INFO("stream download: sending Nak EOF"); #endif } if (error_code == kErrNone) { if (lseek(_session_info.fd, payload->offset, SEEK_SET) < 0) { error_code = kErrFailErrno; #ifdef MAVLINK_FTP_DEBUG PX4_WARN("stream download: seek fail"); #endif } } if (error_code == kErrNone) { int bytes_read = ::read(_session_info.fd, &payload->data[0], kMaxDataLength); if (bytes_read < 0) { // Negative return indicates error other than eof error_code = kErrFailErrno; #ifdef MAVLINK_FTP_DEBUG PX4_WARN("stream download: read fail"); #endif } else { payload->size = bytes_read; _session_info.stream_offset += bytes_read; _session_info.stream_chunk_transmitted += bytes_read; } } if (error_code != kErrNone) { payload->opcode = kRspNak; payload->size = 1; uint8_t *pData = &payload->data[0]; *pData = error_code; // Straight reference to data[0] is causing bogus gcc array subscript error if (error_code == kErrFailErrno) { int r_errno = errno; payload->size = 2; payload->data[1] = r_errno; } _session_info.stream_download = false; } else { #ifndef MAVLINK_FTP_UNIT_TEST if (max_bytes_to_send < (get_size() * 2)) { more_data = false; /* perform transfers in 35K chunks - this is determined empirical */ if (_session_info.stream_chunk_transmitted > 35000) { payload->burst_complete = true; _session_info.stream_download = false; _session_info.stream_chunk_transmitted = 0; } } else { #endif more_data = true; payload->burst_complete = false; #ifndef MAVLINK_FTP_UNIT_TEST max_bytes_to_send -= get_size(); } #endif } ftp_msg.target_system = _session_info.stream_target_system_id; ftp_msg.target_network = 0; ftp_msg.target_component = _session_info.stream_target_component_id; _reply(&ftp_msg); } while (more_data); } mavlink_ftp: close session without activity 10s inactivity timeout to close session /**************************************************************************** * * Copyright (c) 2014-2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /// @file mavlink_ftp.cpp /// @author px4dev, Don Gagne <don@thegagnes.com> #include <crc32.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <errno.h> #include <cstring> #include "mavlink_ftp.h" #include "mavlink_tests/mavlink_ftp_test.h" #ifndef MAVLINK_FTP_UNIT_TEST #include "mavlink_main.h" #else #include <v2.0/standard/mavlink.h> #endif using namespace time_literals; constexpr const char MavlinkFTP::_root_dir[]; MavlinkFTP::MavlinkFTP(Mavlink *mavlink) : _mavlink(mavlink) { // initialize session _session_info.fd = -1; } MavlinkFTP::~MavlinkFTP() { delete[] _work_buffer1; delete[] _work_buffer2; } unsigned MavlinkFTP::get_size() { if (_session_info.stream_download) { return MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL_LEN + MAVLINK_NUM_NON_PAYLOAD_BYTES; } else { return 0; } } #ifdef MAVLINK_FTP_UNIT_TEST void MavlinkFTP::set_unittest_worker(ReceiveMessageFunc_t rcvMsgFunc, void *worker_data) { _utRcvMsgFunc = rcvMsgFunc; _worker_data = worker_data; } #endif uint8_t MavlinkFTP::_getServerSystemId() { #ifdef MAVLINK_FTP_UNIT_TEST // We use fake ids when unit testing return MavlinkFtpTest::serverSystemId; #else // Not unit testing, use the real thing return _mavlink->get_system_id(); #endif } uint8_t MavlinkFTP::_getServerComponentId() { #ifdef MAVLINK_FTP_UNIT_TEST // We use fake ids when unit testing return MavlinkFtpTest::serverComponentId; #else // Not unit testing, use the real thing return _mavlink->get_component_id(); #endif } uint8_t MavlinkFTP::_getServerChannel() { #ifdef MAVLINK_FTP_UNIT_TEST // We use fake ids when unit testing return MavlinkFtpTest::serverChannel; #else // Not unit testing, use the real thing return _mavlink->get_channel(); #endif } void MavlinkFTP::handle_message(const mavlink_message_t *msg) { //warnx("MavlinkFTP::handle_message %d %d", buf_size_1, buf_size_2); if (msg->msgid == MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL) { mavlink_file_transfer_protocol_t ftp_request; mavlink_msg_file_transfer_protocol_decode(msg, &ftp_request); #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: received ftp protocol message target_system: %d target_component: %d", ftp_request.target_system, ftp_request.target_component); #endif if ((ftp_request.target_system == _getServerSystemId() || ftp_request.target_system == 0) && (ftp_request.target_component == _getServerComponentId() || ftp_request.target_component == 0)) { _process_request(&ftp_request, msg->sysid, msg->compid); } } } /// @brief Processes an FTP message void MavlinkFTP::_process_request( mavlink_file_transfer_protocol_t *ftp_req, uint8_t target_system_id, uint8_t target_comp_id) { bool stream_send = false; PayloadHeader *payload = reinterpret_cast<PayloadHeader *>(&ftp_req->payload[0]); ErrorCode errorCode = kErrNone; if (!_ensure_buffers_exist()) { PX4_ERR("Failed to allocate buffers"); errorCode = kErrFailErrno; errno = ENOMEM; goto out; } // basic sanity checks; must validate length before use if (payload->size > kMaxDataLength) { errorCode = kErrInvalidDataSize; goto out; } // check the sequence number: if this is a resent request, resend the last response if (_last_reply_valid) { mavlink_file_transfer_protocol_t *last_reply = reinterpret_cast<mavlink_file_transfer_protocol_t *>(_last_reply); PayloadHeader *last_payload = reinterpret_cast<PayloadHeader *>(&last_reply->payload[0]); if (payload->seq_number + 1 == last_payload->seq_number) { // this is the same request as the one we replied to last. It means the (n)ack got lost, and the GCS // resent the request #ifdef MAVLINK_FTP_UNIT_TEST _utRcvMsgFunc(last_reply, _worker_data); #else mavlink_msg_file_transfer_protocol_send_struct(_mavlink->get_channel(), last_reply); #endif return; } } #ifdef MAVLINK_FTP_DEBUG PX4_INFO("ftp: channel %u opc %u size %u offset %u", _getServerChannel(), payload->opcode, payload->size, payload->offset); #endif switch (payload->opcode) { case kCmdNone: break; case kCmdTerminateSession: errorCode = _workTerminate(payload); break; case kCmdResetSessions: errorCode = _workReset(payload); break; case kCmdListDirectory: errorCode = _workList(payload); break; case kCmdOpenFileRO: errorCode = _workOpen(payload, O_RDONLY); break; case kCmdCreateFile: errorCode = _workOpen(payload, O_CREAT | O_EXCL | O_WRONLY); break; case kCmdOpenFileWO: errorCode = _workOpen(payload, O_CREAT | O_WRONLY); break; case kCmdReadFile: errorCode = _workRead(payload); break; case kCmdBurstReadFile: errorCode = _workBurst(payload, target_system_id, target_comp_id); stream_send = true; break; case kCmdWriteFile: errorCode = _workWrite(payload); break; case kCmdRemoveFile: errorCode = _workRemoveFile(payload); break; case kCmdRename: errorCode = _workRename(payload); break; case kCmdTruncateFile: errorCode = _workTruncateFile(payload); break; case kCmdCreateDirectory: errorCode = _workCreateDirectory(payload); break; case kCmdRemoveDirectory: errorCode = _workRemoveDirectory(payload); break; case kCmdCalcFileCRC32: errorCode = _workCalcFileCRC32(payload); break; default: errorCode = kErrUnknownCommand; break; } out: payload->seq_number++; // handle success vs. error if (errorCode == kErrNone) { payload->req_opcode = payload->opcode; payload->opcode = kRspAck; } else { int r_errno = errno; payload->req_opcode = payload->opcode; payload->opcode = kRspNak; payload->size = 1; if (r_errno == EEXIST) { errorCode = kErrFailFileExists; } else if (r_errno == ENOENT && errorCode == kErrFailErrno) { errorCode = kErrFileNotFound; } payload->data[0] = errorCode; if (errorCode == kErrFailErrno) { payload->size = 2; payload->data[1] = r_errno; } } _last_reply_valid = false; // Stream download replies are sent through mavlink stream mechanism. Unless we need to Nack. if (!stream_send || errorCode != kErrNone) { // respond to the request ftp_req->target_system = target_system_id; ftp_req->target_network = 0; ftp_req->target_component = target_comp_id; _reply(ftp_req); } } bool MavlinkFTP::_ensure_buffers_exist() { _last_work_buffer_access = hrt_absolute_time(); if (!_work_buffer1) { _work_buffer1 = new char[_work_buffer1_len]; } if (!_work_buffer2) { _work_buffer2 = new char[_work_buffer2_len]; } return _work_buffer1 && _work_buffer2; } /// @brief Sends the specified FTP response message out through mavlink void MavlinkFTP::_reply(mavlink_file_transfer_protocol_t *ftp_req) { PayloadHeader *payload = reinterpret_cast<PayloadHeader *>(&ftp_req->payload[0]); // keep a copy of the last sent response ((n)ack), so that if it gets lost and the GCS resends the request, // we can simply resend the response. // we only keep small responses to reduce RAM usage and avoid large memcpy's. The larger responses are all data // retrievals without side-effects, meaning it's ok to reexecute them if a response gets lost if (payload->size <= sizeof(uint32_t)) { _last_reply_valid = true; memcpy(_last_reply, ftp_req, sizeof(_last_reply)); } #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: %s seq_number: %d", payload->opcode == kRspAck ? "Ack" : "Nak", payload->seq_number); #endif #ifdef MAVLINK_FTP_UNIT_TEST // Unit test hook is set, call that instead _utRcvMsgFunc(ftp_req, _worker_data); #else mavlink_msg_file_transfer_protocol_send_struct(_mavlink->get_channel(), ftp_req); #endif } /// @brief Responds to a List command MavlinkFTP::ErrorCode MavlinkFTP::_workList(PayloadHeader *payload) { strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); // ensure termination _work_buffer1[_work_buffer1_len - 1] = '\0'; ErrorCode errorCode = kErrNone; unsigned offset = 0; DIR *dp = opendir(_work_buffer1); if (dp == nullptr) { PX4_WARN("File open failed %s", _work_buffer1); return kErrFileNotFound; } #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: list %s offset %d", _work_buffer1, payload->offset); #endif struct dirent *result = nullptr; // move to the requested offset int requested_offset = payload->offset; while (requested_offset-- > 0 && readdir(dp)) {} for (;;) { errno = 0; result = readdir(dp); // read the directory entry if (result == nullptr) { if (errno) { PX4_WARN("readdir failed"); payload->data[offset++] = kDirentSkip; *((char *)&payload->data[offset]) = '\0'; offset++; payload->size = offset; closedir(dp); return errorCode; } // no more entries? if (payload->offset != 0 && offset == 0) { // User is requesting subsequent dir entries but there were none. This means the user asked // to seek past EOF. errorCode = kErrEOF; } // Otherwise we are just at the last directory entry, so we leave the errorCode at kErrorNone to signal that break; } uint32_t fileSize = 0; char direntType; // Determine the directory entry type switch (result->d_type) { #ifdef __PX4_NUTTX case DTYPE_FILE: { #else case DT_REG: { #endif // For files we get the file size as well direntType = kDirentFile; int ret = snprintf(_work_buffer2, _work_buffer2_len, "%s/%s", _work_buffer1, result->d_name); bool buf_is_ok = ((ret > 0) && (ret < _work_buffer2_len)); if (buf_is_ok) { struct stat st; if (stat(_work_buffer2, &st) == 0) { fileSize = st.st_size; } } break; } #ifdef __PX4_NUTTX case DTYPE_DIRECTORY: #else case DT_DIR: #endif if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0) { // Don't bother sending these back direntType = kDirentSkip; } else { direntType = kDirentDir; } break; default: // We only send back file and diretory entries, skip everything else direntType = kDirentSkip; } if (direntType == kDirentSkip) { // Skip send only dirent identifier _work_buffer2[0] = '\0'; } else if (direntType == kDirentFile) { // Files send filename and file length int ret = snprintf(_work_buffer2, _work_buffer2_len, "%s\t%d", result->d_name, fileSize); bool buf_is_ok = ((ret > 0) && (ret < _work_buffer2_len)); if (!buf_is_ok) { _work_buffer2[_work_buffer2_len - 1] = '\0'; } } else { // Everything else just sends name strncpy(_work_buffer2, result->d_name, _work_buffer2_len); _work_buffer2[_work_buffer2_len - 1] = '\0'; } size_t nameLen = strlen(_work_buffer2); // Do we have room for the name, the one char directory identifier and the null terminator? if ((offset + nameLen + 2) > kMaxDataLength) { break; } // Move the data into the buffer payload->data[offset++] = direntType; strcpy((char *)&payload->data[offset], _work_buffer2); #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: list %s %s", _work_buffer1, (char *)&payload->data[offset - 1]); #endif offset += nameLen + 1; } closedir(dp); payload->size = offset; return errorCode; } /// @brief Responds to an Open command MavlinkFTP::ErrorCode MavlinkFTP::_workOpen(PayloadHeader *payload, int oflag) { if (_session_info.fd >= 0) { PX4_ERR("FTP: Open failed - out of sessions\n"); return kErrNoSessionsAvailable; } strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: open '%s'", _work_buffer1); #endif uint32_t fileSize = 0; struct stat st; if (stat(_work_buffer1, &st) != 0) { // fail only if requested open for read if (oflag & O_RDONLY) { return kErrFailErrno; } else { st.st_size = 0; } } fileSize = st.st_size; // Set mode to 666 incase oflag has O_CREAT int fd = ::open(_work_buffer1, oflag, PX4_O_MODE_666); if (fd < 0) { return kErrFailErrno; } _session_info.fd = fd; _session_info.file_size = fileSize; _session_info.stream_download = false; payload->session = 0; payload->size = sizeof(uint32_t); std::memcpy(payload->data, &fileSize, payload->size); return kErrNone; } /// @brief Responds to a Read command MavlinkFTP::ErrorCode MavlinkFTP::_workRead(PayloadHeader *payload) { if (payload->session != 0 || _session_info.fd < 0) { return kErrInvalidSession; } #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: read offset:%d", payload->offset); #endif // We have to test seek past EOF ourselves, lseek will allow seek past EOF if (payload->offset >= _session_info.file_size) { PX4_ERR("request past EOF"); return kErrEOF; } if (lseek(_session_info.fd, payload->offset, SEEK_SET) < 0) { PX4_ERR("seek fail"); return kErrFailErrno; } int bytes_read = ::read(_session_info.fd, &payload->data[0], kMaxDataLength); if (bytes_read < 0) { // Negative return indicates error other than eof PX4_ERR("read fail %d", bytes_read); return kErrFailErrno; } payload->size = bytes_read; return kErrNone; } /// @brief Responds to a Stream command MavlinkFTP::ErrorCode MavlinkFTP::_workBurst(PayloadHeader *payload, uint8_t target_system_id, uint8_t target_component_id) { if (payload->session != 0 && _session_info.fd < 0) { return kErrInvalidSession; } #ifdef MAVLINK_FTP_DEBUG PX4_INFO("FTP: burst offset:%d", payload->offset); #endif // Setup for streaming sends _session_info.stream_download = true; _session_info.stream_offset = payload->offset; _session_info.stream_chunk_transmitted = 0; _session_info.stream_seq_number = payload->seq_number + 1; _session_info.stream_target_system_id = target_system_id; _session_info.stream_target_component_id = target_component_id; return kErrNone; } /// @brief Responds to a Write command MavlinkFTP::ErrorCode MavlinkFTP::_workWrite(PayloadHeader *payload) { if (payload->session != 0 && _session_info.fd < 0) { return kErrInvalidSession; } if (lseek(_session_info.fd, payload->offset, SEEK_SET) < 0) { // Unable to see to the specified location PX4_ERR("seek fail"); return kErrFailErrno; } int bytes_written = ::write(_session_info.fd, &payload->data[0], payload->size); if (bytes_written < 0) { // Negative return indicates error other than eof PX4_ERR("write fail %d", bytes_written); return kErrFailErrno; } payload->size = sizeof(uint32_t); std::memcpy(payload->data, &bytes_written, payload->size); return kErrNone; } /// @brief Responds to a RemoveFile command MavlinkFTP::ErrorCode MavlinkFTP::_workRemoveFile(PayloadHeader *payload) { strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); // ensure termination _work_buffer1[_work_buffer1_len - 1] = '\0'; if (unlink(_work_buffer1) == 0) { payload->size = 0; return kErrNone; } else { return kErrFailErrno; } } /// @brief Responds to a TruncateFile command MavlinkFTP::ErrorCode MavlinkFTP::_workTruncateFile(PayloadHeader *payload) { strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); // ensure termination _work_buffer1[_work_buffer1_len - 1] = '\0'; payload->size = 0; #ifdef __PX4_NUTTX // emulate truncate(_work_buffer1, payload->offset) by // copying to temp and overwrite with O_TRUNC flag (NuttX does not support truncate()). const char temp_file[] = PX4_STORAGEDIR"/.trunc.tmp"; struct stat st; if (stat(_work_buffer1, &st) != 0) { return kErrFailErrno; } if (!S_ISREG(st.st_mode)) { errno = EISDIR; return kErrFailErrno; } // check perms allow us to write (not romfs) if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH))) { errno = EROFS; return kErrFailErrno; } if (payload->offset == (unsigned)st.st_size) { // nothing to do return kErrNone; } else if (payload->offset == 0) { // 1: truncate all data int fd = ::open(_work_buffer1, O_TRUNC | O_WRONLY); if (fd < 0) { return kErrFailErrno; } ::close(fd); return kErrNone; } else if (payload->offset > (unsigned)st.st_size) { // 2: extend file int fd = ::open(_work_buffer1, O_WRONLY); if (fd < 0) { return kErrFailErrno; } if (lseek(fd, payload->offset - 1, SEEK_SET) < 0) { ::close(fd); return kErrFailErrno; } bool ok = 1 == ::write(fd, "", 1); ::close(fd); return (ok) ? kErrNone : kErrFailErrno; } else { // 3: truncate if (_copy_file(_work_buffer1, temp_file, payload->offset) != 0) { return kErrFailErrno; } if (_copy_file(temp_file, _work_buffer1, payload->offset) != 0) { return kErrFailErrno; } if (::unlink(temp_file) != 0) { return kErrFailErrno; } return kErrNone; } #else int ret = truncate(_work_buffer1, payload->offset); if (ret == 0) { return kErrNone; } return kErrFailErrno; #endif /* __PX4_NUTTX */ } /// @brief Responds to a Terminate command MavlinkFTP::ErrorCode MavlinkFTP::_workTerminate(PayloadHeader *payload) { if (payload->session != 0 || _session_info.fd < 0) { return kErrInvalidSession; } ::close(_session_info.fd); _session_info.fd = -1; _session_info.stream_download = false; payload->size = 0; return kErrNone; } /// @brief Responds to a Reset command MavlinkFTP::ErrorCode MavlinkFTP::_workReset(PayloadHeader *payload) { if (_session_info.fd != -1) { ::close(_session_info.fd); _session_info.fd = -1; _session_info.stream_download = false; } payload->size = 0; return kErrNone; } /// @brief Responds to a Rename command MavlinkFTP::ErrorCode MavlinkFTP::_workRename(PayloadHeader *payload) { char *ptr = _data_as_cstring(payload); size_t oldpath_sz = strlen(ptr); if (oldpath_sz == payload->size) { // no newpath errno = EINVAL; return kErrFailErrno; } strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, ptr, _work_buffer1_len - _root_dir_len); _work_buffer1[_work_buffer1_len - 1] = '\0'; // ensure termination strncpy(_work_buffer2, _root_dir, _work_buffer2_len); strncpy(_work_buffer2 + _root_dir_len, ptr + oldpath_sz + 1, _work_buffer2_len - _root_dir_len); _work_buffer2[_work_buffer2_len - 1] = '\0'; // ensure termination if (rename(_work_buffer1, _work_buffer2) == 0) { payload->size = 0; return kErrNone; } else { return kErrFailErrno; } } /// @brief Responds to a RemoveDirectory command MavlinkFTP::ErrorCode MavlinkFTP::_workRemoveDirectory(PayloadHeader *payload) { strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); // ensure termination _work_buffer1[_work_buffer1_len - 1] = '\0'; if (rmdir(_work_buffer1) == 0) { payload->size = 0; return kErrNone; } else { return kErrFailErrno; } } /// @brief Responds to a CreateDirectory command MavlinkFTP::ErrorCode MavlinkFTP::_workCreateDirectory(PayloadHeader *payload) { strncpy(_work_buffer1, _root_dir, _work_buffer1_len); strncpy(_work_buffer1 + _root_dir_len, _data_as_cstring(payload), _work_buffer1_len - _root_dir_len); // ensure termination _work_buffer1[_work_buffer1_len - 1] = '\0'; if (mkdir(_work_buffer1, S_IRWXU | S_IRWXG | S_IRWXO) == 0) { payload->size = 0; return kErrNone; } else { return kErrFailErrno; } } /// @brief Responds to a CalcFileCRC32 command MavlinkFTP::ErrorCode MavlinkFTP::_workCalcFileCRC32(PayloadHeader *payload) { uint32_t checksum = 0; ssize_t bytes_read; strncpy(_work_buffer2, _root_dir, _work_buffer2_len); strncpy(_work_buffer2 + _root_dir_len, _data_as_cstring(payload), _work_buffer2_len - _root_dir_len); // ensure termination _work_buffer2[_work_buffer2_len - 1] = '\0'; int fd = ::open(_work_buffer2, O_RDONLY); if (fd < 0) { return kErrFailErrno; } do { bytes_read = ::read(fd, _work_buffer2, _work_buffer2_len); if (bytes_read < 0) { int r_errno = errno; ::close(fd); errno = r_errno; return kErrFailErrno; } checksum = crc32part((uint8_t *)_work_buffer2, bytes_read, checksum); } while (bytes_read == _work_buffer2_len); ::close(fd); payload->size = sizeof(uint32_t); std::memcpy(payload->data, &checksum, payload->size); return kErrNone; } /// @brief Guarantees that the payload data is null terminated. /// @return Returns a pointer to the payload data as a char * char * MavlinkFTP::_data_as_cstring(PayloadHeader *payload) { // guarantee nul termination if (payload->size < kMaxDataLength) { payload->data[payload->size] = '\0'; } else { payload->data[kMaxDataLength - 1] = '\0'; } // and return data return (char *) & (payload->data[0]); } /// @brief Copy file (with limited space) int MavlinkFTP::_copy_file(const char *src_path, const char *dst_path, size_t length) { int src_fd = -1, dst_fd = -1; int op_errno = 0; src_fd = ::open(src_path, O_RDONLY); if (src_fd < 0) { return -1; } dst_fd = ::open(dst_path, O_CREAT | O_TRUNC | O_WRONLY // POSIX requires the permissions to be supplied if O_CREAT passed #ifdef __PX4_POSIX , 0666 #endif ); if (dst_fd < 0) { op_errno = errno; ::close(src_fd); errno = op_errno; return -1; } while (length > 0) { ssize_t bytes_read, bytes_written; size_t blen = (length > _work_buffer2_len) ? _work_buffer2_len : length; bytes_read = ::read(src_fd, _work_buffer2, blen); if (bytes_read == 0) { // EOF break; } else if (bytes_read < 0) { PX4_ERR("cp: read"); op_errno = errno; break; } bytes_written = ::write(dst_fd, _work_buffer2, bytes_read); if (bytes_written != bytes_read) { PX4_ERR("cp: short write"); op_errno = errno; break; } length -= bytes_written; } ::close(src_fd); ::close(dst_fd); errno = op_errno; return (length > 0) ? -1 : 0; } void MavlinkFTP::send(const hrt_abstime t) { if (_work_buffer1 || _work_buffer2) { // free the work buffers if they are not used for a while if (hrt_elapsed_time(&_last_work_buffer_access) > 2_s) { if (_work_buffer1) { delete[] _work_buffer1; _work_buffer1 = nullptr; } if (_work_buffer2) { delete[] _work_buffer2; _work_buffer2 = nullptr; } } } else if (_session_info.fd != -1) { // close session without activity if (hrt_elapsed_time(&_last_work_buffer_access) > 10_s) { ::close(_session_info.fd); _session_info.fd = -1; _session_info.stream_download = false; _last_reply_valid = false; PX4_WARN("Session was closed without activity"); } } // Anything to stream? if (!_session_info.stream_download) { return; } #ifndef MAVLINK_FTP_UNIT_TEST // Skip send if not enough room unsigned max_bytes_to_send = _mavlink->get_free_tx_buf(); #ifdef MAVLINK_FTP_DEBUG PX4_INFO("MavlinkFTP::send max_bytes_to_send(%d) get_free_tx_buf(%d)", max_bytes_to_send, _mavlink->get_free_tx_buf()); #endif if (max_bytes_to_send < get_size()) { return; } #endif // Send stream packets until buffer is full bool more_data; do { more_data = false; ErrorCode error_code = kErrNone; mavlink_file_transfer_protocol_t ftp_msg; PayloadHeader *payload = reinterpret_cast<PayloadHeader *>(&ftp_msg.payload[0]); payload->seq_number = _session_info.stream_seq_number; payload->session = 0; payload->opcode = kRspAck; payload->req_opcode = kCmdBurstReadFile; payload->offset = _session_info.stream_offset; _session_info.stream_seq_number++; #ifdef MAVLINK_FTP_DEBUG PX4_INFO("stream send: offset %d", _session_info.stream_offset); #endif // We have to test seek past EOF ourselves, lseek will allow seek past EOF if (_session_info.stream_offset >= _session_info.file_size) { error_code = kErrEOF; #ifdef MAVLINK_FTP_DEBUG PX4_INFO("stream download: sending Nak EOF"); #endif } if (error_code == kErrNone) { if (lseek(_session_info.fd, payload->offset, SEEK_SET) < 0) { error_code = kErrFailErrno; #ifdef MAVLINK_FTP_DEBUG PX4_WARN("stream download: seek fail"); #endif } } if (error_code == kErrNone) { int bytes_read = ::read(_session_info.fd, &payload->data[0], kMaxDataLength); if (bytes_read < 0) { // Negative return indicates error other than eof error_code = kErrFailErrno; #ifdef MAVLINK_FTP_DEBUG PX4_WARN("stream download: read fail"); #endif } else { payload->size = bytes_read; _session_info.stream_offset += bytes_read; _session_info.stream_chunk_transmitted += bytes_read; } } if (error_code != kErrNone) { payload->opcode = kRspNak; payload->size = 1; uint8_t *pData = &payload->data[0]; *pData = error_code; // Straight reference to data[0] is causing bogus gcc array subscript error if (error_code == kErrFailErrno) { int r_errno = errno; payload->size = 2; payload->data[1] = r_errno; } _session_info.stream_download = false; } else { #ifndef MAVLINK_FTP_UNIT_TEST if (max_bytes_to_send < (get_size() * 2)) { more_data = false; /* perform transfers in 35K chunks - this is determined empirical */ if (_session_info.stream_chunk_transmitted > 35000) { payload->burst_complete = true; _session_info.stream_download = false; _session_info.stream_chunk_transmitted = 0; } } else { #endif more_data = true; payload->burst_complete = false; #ifndef MAVLINK_FTP_UNIT_TEST max_bytes_to_send -= get_size(); } #endif } ftp_msg.target_system = _session_info.stream_target_system_id; ftp_msg.target_network = 0; ftp_msg.target_component = _session_info.stream_target_component_id; _reply(&ftp_msg); } while (more_data); }
/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #if qPlatform_AIX #include <libperfstat.h> #endif #include "../../../Foundation/Characters/FloatConversion.h" #include "../../../Foundation/Characters/String_Constant.h" #include "../../../Foundation/Characters/String2Int.h" #include "../../../Foundation/Configuration/SystemConfiguration.h" #include "../../../Foundation/Containers/Mapping.h" #include "../../../Foundation/Containers/Sequence.h" #include "../../../Foundation/Containers/Set.h" #include "../../../Foundation/Debug/Assertions.h" #include "../../../Foundation/Debug/AssertExternallySynchronizedLock.h" #include "../../../Foundation/Debug/Trace.h" #include "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h" #include "../../../Foundation/Execution/ErrNoException.h" #include "../../../Foundation/Execution/ProcessRunner.h" #include "../../../Foundation/Execution/Sleep.h" #include "../../../Foundation/IO/FileSystem/FileInputStream.h" #include "../../../Foundation/Streams/InputStream.h" #include "../../../Foundation/Streams/MemoryStream.h" #include "../../../Foundation/Streams/TextReader.h" #include "Memory.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::SystemPerformance; using namespace Stroika::Frameworks::SystemPerformance::Instruments::Memory; using Characters::Character; using Characters::String_Constant; using Containers::Mapping; using Containers::Sequence; using Containers::Set; using IO::FileSystem::FileInputStream; using Time::DurationSecondsType; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #ifndef qUseWMICollectionSupport_ #define qUseWMICollectionSupport_ qPlatform_Windows #endif #if qUseWMICollectionSupport_ #include "../Support/WMICollector.h" using SystemPerformance::Support::WMICollector; #endif #if qUseWMICollectionSupport_ namespace { const String_Constant kInstanceName_ { L"_Total" }; const String_Constant kCommittedBytes_ { L"Committed Bytes" }; const String_Constant kCommitLimit_ { L"Commit Limit" }; const String_Constant kPagesPerSec_ { L"Pages/sec" }; // hard page faults/sec const String_Constant kFreeMem_ { L"Free & Zero Page List Bytes" }; } #endif namespace { struct CapturerWithContext_COMMON_ { Options fOptions_; DurationSecondsType fMinimumAveragingInterval_; DurationSecondsType fPostponeCaptureUntil_ { 0 }; DurationSecondsType fLastCapturedAt_ {}; CapturerWithContext_COMMON_ (const Options& options) : fOptions_ (options) , fMinimumAveragingInterval_ (options.fMinimumAveragingInterval) { } DurationSecondsType GetLastCaptureAt () const { return fLastCapturedAt_; } void NoteCompletedCapture_ () { auto now = Time::GetTickCount (); fPostponeCaptureUntil_ = now + fMinimumAveragingInterval_; fLastCapturedAt_ = now; } }; } #if qPlatform_AIX namespace { struct CapturerWithContext_AIX_ : CapturerWithContext_COMMON_ { Time::DurationSecondsType fSaved_VMPageStats_At {}; uint64_t fSaved_MinorPageFaultsSinceBoot {}; uint64_t fSaved_MajorPageFaultsSinceBoot {}; uint64_t fSaved_PageOutsSinceBoot {}; CapturerWithContext_AIX_ (Options options) : CapturerWithContext_COMMON_ (options) { // for side-effect of updating aved_MajorPageFaultsSinc etc try { capture_ (); } catch (...) { DbgTrace ("bad sign that first pre-catpure failed."); // Dont propagate in case just listing collectors } } CapturerWithContext_AIX_ (const CapturerWithContext_AIX_&) = default; // copy by value fine - no need to re-wait... Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; result = capture_perfstat_ (); NoteCompletedCapture_ (); return result; } Instruments::Memory::Info capture_perfstat_ () { Instruments::Memory::Info result; perfstat_memory_total_t memResults; Execution::ThrowErrNoIfNegative (::perfstat_memory_total (nullptr, &memResults, sizeof (memResults), 1)); // From /usr/include/libperfstat.h: // u_longlong_t real_free; /* free real memory (in 4KB pages) */ result.fFreePhysicalMemory = memResults.real_free * 4 * 1024; // From /usr/include/libperfstat.h: // u_longlong_t virt_total; /* total virtual memory (in 4KB pages) result.fCommitLimit = memResults.virt_total * 4 * 1024; // // WAG /* reserved paging space (in 4KB pages) */ // u_longlong_t real_inuse; /* real memory which is in use (in 4KB pages) */ // From /usr/include/libperfstat.h: u_longlong_t pgsp_total; /* total paging space (in 4KB pages) */ result.fPagefileTotalSize = memResults.pgsp_total * 4 * 1024; #if 0 u_longlong_t real_system; /* number of pages used by system segments. * * This is the sum of all the used pages in segment marked for system usage. * * Since segment classifications are not always guaranteed to be accurate, * * This number is only an approximation. */ u_longlong_t real_user; /* number of pages used by non-system segments. * * This is the sum of all pages used in segments not marked for system usage. * * Since segment classifications are not always guaranteed to be accurate, * * This number is only an approximation. */ u_longlong_t real_process; /* number of pages used by process segments. */ #endif //wag // real_process???? result.fActivePhysicalMemory = memResults.real_pinned * 4 * 1024; result.fInactivePhysicalMemory = (memResults.real_inuse - memResults.real_pinned) * 4 * 1024;; // WAG TMPHACK result.fMemoryAvailable = result.fFreePhysicalMemory + result.fInactivePhysicalMemory; // From /usr/include/libperfstat.h: // u_longlong_t pgsp_total; /* total paging space (in 4KB pages) */ // u_longlong_t real_inuse; /* real memory which is in use (in 4KB pages) */ // u_longlong_t pgsp_free; /* free paging space (in 4KB pages) */ result.fCommittedBytes = (memResults.real_inuse + (memResults.pgsp_total - memResults.pgsp_free)) * 4 * 1024; // @todo review/copy docs here for pgexct result.fMinorPageFaultsSinceBoot = memResults.pgexct; //result.fMajorPageFaultsSinceBoot = memResults.pgins + memResults.pgouts; result.fMajorPageFaultsSinceBoot = memResults.pgins; if (result.fMinorPageFaultsSinceBoot.IsPresent ()) { Time::DurationSecondsType now = Time::GetTickCount (); if (fSaved_VMPageStats_At != 0) { result.fMinorPageFaultsPerSecond = (*result.fMinorPageFaultsSinceBoot - fSaved_MinorPageFaultsSinceBoot) / (now - fSaved_VMPageStats_At); } fSaved_MinorPageFaultsSinceBoot = *result.fMinorPageFaultsSinceBoot; fSaved_VMPageStats_At = now; } { result.fPageOutsSinceBoot = memResults.pgouts; if (fSaved_VMPageStats_At != 0) { updateResult->fPageOutsPerSecond = (memResults.pgouts - fSaved_PageOutsSinceBoot) / (now - fSaved_VMPageStats_At); } fSaved_PageOutsSinceBoot = memResults.pgouts; } if (result.fMajorPageFaultsSinceBoot.IsPresent ()) { Time::DurationSecondsType now = Time::GetTickCount (); if (fSaved_VMPageStats_At != 0) { result.fMajorPageFaultsPerSecond = (*result.fMajorPageFaultsSinceBoot - fSaved_MajorPageFaultsSinceBoot) / (now - fSaved_VMPageStats_At); } fSaved_MajorPageFaultsSinceBoot = *result.fMajorPageFaultsSinceBoot; } fSaved_VMPageStats_At = now; return result; } Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } }; } #endif #if qPlatform_POSIX namespace { struct CapturerWithContext_POSIX_ : CapturerWithContext_COMMON_ { uint64_t fSaved_MajorPageFaultsSinceBoot {}; uint64_t fSaved_PageOutsSinceBoot {}; Time::DurationSecondsType fSaved_VMPageStats_At {}; CapturerWithContext_POSIX_ (Options options) : CapturerWithContext_COMMON_ (options) { // for side-effect of updating aved_MajorPageFaultsSinc etc try { capture_ (); } catch (...) { DbgTrace ("bad sign that first pre-catpure failed."); // Dont propagate in case just listing collectors } } CapturerWithContext_POSIX_ (const CapturerWithContext_POSIX_&) = default; // copy by value fine - no need to re-wait... Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; Read_ProcMemInfo (&result); Read_ProcVMStat_ (&result); NoteCompletedCapture_ (); return result; } void Read_ProcMemInfo (Instruments::Memory::Info* updateResult) { auto ReadMemInfoLine_ = [] (Optional<uint64_t>* result, const String & n, const Sequence<String>& line) { if (line.size () >= 3 and line[0] == n) { String unit = line[2]; double factor = (unit == L"kB") ? 1024 : 1; *result = static_cast<uint64_t> (round (Characters::String2Float<double> (line[1]) * factor)); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } }; static const String_Constant kProcMemInfoFileName_ { L"/proc/meminfo" }; //const String_Constant kProcMemInfoFileName_ { L"c:\\Sandbox\\VMSharedFolder\\meminfo" }; DataExchange::CharacterDelimitedLines::Reader reader {{ ':', ' ', '\t' }}; // Note - /procfs files always unseekable for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (kProcMemInfoFileName_, FileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadMemInfoLine_ (&updateResult->fFreePhysicalMemory, String_Constant (L"MemFree"), line); ReadMemInfoLine_ (&updateResult->fMemoryAvailable, String_Constant (L"MemAvailable"), line); ReadMemInfoLine_ (&updateResult->fActivePhysicalMemory, String_Constant (L"Active"), line); ReadMemInfoLine_ (&updateResult->fInactivePhysicalMemory, String_Constant (L"Inactive"), line); ReadMemInfoLine_ (&updateResult->fCommitLimit, String_Constant (L"CommitLimit"), line); ReadMemInfoLine_ (&updateResult->fCommittedBytes, String_Constant (L"Committed_AS"), line); #if 0 ReadMemInfoLine_ (&updateResult->fLargestAvailableVirtualChunk, String_Constant (L"VmallocChunk"), line); #endif ReadMemInfoLine_ (&updateResult->fPagefileTotalSize, String_Constant (L"SwapTotal"), line); } } void Read_ProcVMStat_ (Instruments::Memory::Info* updateResult) { auto ReadVMStatLine_ = [] (Optional<uint64_t>* result, const String & n, const Sequence<String>& line) { if (line.size () >= 2 and line[0] == n) { *result = Characters::String2Int<uint64_t> (line[1]); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } }; { static const String_Constant kProcVMStatFileName_ { L"/proc/vmstat" }; Optional<uint64_t> pgfault; Optional<uint64_t> pgpgout; // Note - /procfs files always unseekable DataExchange::CharacterDelimitedLines::Reader reader {{ ' ', '\t' }}; for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (kProcVMStatFileName_, FileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadVMStatLine_ (&pgfault, String_Constant (L"pgfault"), line); // Unsure if this should be pgpgout or pgpgout, or none of the above. On a system with no swap, I seem to get both happening, // which makes no sense ReadVMStatLine_ (&pgpgout, String_Constant (L"pgpgout"), line); // tried pgpgout but I dont know what it is but doesnt appear to be pages out - noneof this well documented ReadVMStatLine_ (&updateResult->fMajorPageFaultsSinceBoot, String_Constant (L"pgmajfault"), line); } Time::DurationSecondsType now = Time::GetTickCount (); if (pgpgout) { updateResult->fPageOutsSinceBoot = pgpgout; if (fSaved_VMPageStats_At != 0) { updateResult->fPageOutsPerSecond = (*updateResult->fPageOutsSinceBoot - fSaved_PageOutsSinceBoot) / (now - fSaved_VMPageStats_At); } fSaved_PageOutsSinceBoot = *pgpgout; } if (pgfault and updateResult->fMajorPageFaultsSinceBoot) { updateResult->fMinorPageFaultsSinceBoot = *pgfault - *updateResult->fMajorPageFaultsSinceBoot; } if (updateResult->fMajorPageFaultsSinceBoot) { if (fSaved_VMPageStats_At != 0) { updateResult->fMajorPageFaultsPerSecond = (*updateResult->fMajorPageFaultsSinceBoot - fSaved_MajorPageFaultsSinceBoot) / (now - fSaved_VMPageStats_At); } fSaved_MajorPageFaultsSinceBoot = *updateResult->fMajorPageFaultsSinceBoot; } fSaved_VMPageStats_At = now; } } }; } #endif #if qPlatform_Windows namespace { struct CapturerWithContext_Windows_ : CapturerWithContext_COMMON_ { #if qUseWMICollectionSupport_ WMICollector fMemoryWMICollector_ { String_Constant { L"Memory" }, {kInstanceName_}, {kCommittedBytes_, kCommitLimit_, kPagesPerSec_, kFreeMem_ } }; #endif CapturerWithContext_Windows_ (const Options& options) : CapturerWithContext_COMMON_ (options) { capture_ (); // to pre-seed context #if USE_NOISY_TRACE_IN_THIS_MODULE_ for (String i : fMemoryWMICollector_.GetAvailableCounters ()) { DbgTrace (L"Memory:Countername: %s", i.c_str ()); } #endif } CapturerWithContext_Windows_ (const CapturerWithContext_Windows_& from) : CapturerWithContext_COMMON_ (from) #if qUseWMICollectionSupport_ , fMemoryWMICollector_ (from.fMemoryWMICollector_) #endif { #if qUseWMICollectionSupport_ capture_ (); // to pre-seed context #endif } Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; uint64_t totalRAM {}; Read_GlobalMemoryStatusEx_(&result, &totalRAM); #if qUseWMICollectionSupport_ Read_WMI_ (&result, totalRAM); #endif NoteCompletedCapture_ (); return result; } Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } void Read_GlobalMemoryStatusEx_ (Instruments::Memory::Info* updateResult, uint64_t* totalRAM) { RequireNotNull (totalRAM); MEMORYSTATUSEX statex; memset (&statex, 0, sizeof (statex)); statex.dwLength = sizeof (statex); Verify (::GlobalMemoryStatusEx (&statex) != 0); //updateResult->fFreePhysicalMemory = statex.ullAvailPhys; *totalRAM = statex.ullTotalPhys; /* * dwMemoryLoad * A number between 0 and 100 that specifies the approximate percentage of physical * memory that is in use (0 indicates no memory use and 100 indicates full memory use) */ updateResult->fActivePhysicalMemory = statex.ullTotalPhys * statex.dwMemoryLoad / 100; } #if qUseWMICollectionSupport_ void Read_WMI_ (Instruments::Memory::Info* updateResult, uint64_t totalRAM) { fMemoryWMICollector_.Collect (); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kCommittedBytes_).CopyToIf (&updateResult->fCommittedBytes); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kCommitLimit_).CopyToIf (&updateResult->fCommitLimit); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kPagesPerSec_).CopyToIf (&updateResult->fMajorPageFaultsPerSecond); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kFreeMem_).CopyToIf (&updateResult->fFreePhysicalMemory); if (Optional<double> freeMem = fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kFreeMem_)) { if (updateResult->fActivePhysicalMemory) { // Active + Inactive + Free == TotalRAM updateResult->fInactivePhysicalMemory = totalRAM - *updateResult->fActivePhysicalMemory - static_cast<uint64_t> (*freeMem); } } // WAG TMPHACK - probably should add "hardware in use" memory + private WS of each process + shared memory "WS" - but not easy to compute... updateResult->fMemoryAvailable = updateResult->fFreePhysicalMemory + updateResult->fInactivePhysicalMemory; } #endif }; } #endif namespace { struct CapturerWithContext_ : Debug::AssertExternallySynchronizedLock #if qPlatform_AIX , CapturerWithContext_AIX_ #elif qPlatform_POSIX , CapturerWithContext_POSIX_ #elif qPlatform_Windows , CapturerWithContext_Windows_ #endif { #if qPlatform_AIX using inherited = CapturerWithContext_AIX_; #elif qPlatform_POSIX using inherited = CapturerWithContext_POSIX_; #elif qPlatform_Windows using inherited = CapturerWithContext_Windows_; #endif CapturerWithContext_ (Options options) : inherited (options) { } Instruments::Memory::Info capture () { lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Instruments::Memory::Info capture"); #endif return inherited::capture (); } }; } /* ******************************************************************************** ******************** Instruments::Memory::GetObjectVariantMapper *************** ******************************************************************************** */ ObjectVariantMapper Instruments::Memory::GetObjectVariantMapper () { using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo; static const ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper { ObjectVariantMapper mapper; mapper.AddCommonType<Optional<uint64_t>> (); mapper.AddCommonType<Optional<double>> (); DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 mapper.AddClass<Info> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fFreePhysicalMemory), String_Constant (L"Free-Physical-Memory"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMemoryAvailable), String_Constant (L"Memory-Available"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fActivePhysicalMemory), String_Constant (L"Active-Physical-Memory"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fInactivePhysicalMemory), String_Constant (L"Inactive-Physical-Memory"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fCommitLimit), String_Constant (L"Commit-Limit"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fCommittedBytes), String_Constant (L"Committed-Bytes"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fPagefileTotalSize), String_Constant (L"Pagefile-Total-Size"), StructureFieldInfo::NullFieldHandling::eOmit }, #if 0 { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLargestAvailableVirtualChunk), String_Constant (L"Largest-Available-Virtual-Chunk"), StructureFieldInfo::NullFieldHandling::eOmit }, #endif { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsSinceBoot), String_Constant (L"Major-Page-Faults-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsSinceBoot), String_Constant (L"Minor-Page-Faults-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsPerSecond), String_Constant (L"Major-Page-Faults-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsPerSecond), String_Constant (L"Minor-Page-Faults-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fPageOutsSinceBoot), String_Constant (L"Page-Outs-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fPageOutsPerSecond), String_Constant (L"Page-Outs-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, }); DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\""); DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\""); return mapper; } (); return sMapper_; } namespace { const MeasurementType kMemoryUsageMeasurement_ = MeasurementType (String_Constant (L"Memory-Usage")); } namespace { class MyCapturer_ : public Instrument::ICapturer { CapturerWithContext_ fCaptureContext; public: MyCapturer_ (const CapturerWithContext_& ctx) : fCaptureContext (ctx) { } virtual MeasurementSet Capture () { MeasurementSet results; results.fMeasurements.Add (Measurement { kMemoryUsageMeasurement_, GetObjectVariantMapper ().FromObject (Capture_Raw (&results.fMeasuredAt))}); return results; } nonvirtual Info Capture_Raw (Range<DurationSecondsType>* outMeasuredAt) { DurationSecondsType before = fCaptureContext.GetLastCaptureAt (); Info rawMeasurement = fCaptureContext.capture (); if (outMeasuredAt != nullptr) { *outMeasuredAt = Range<DurationSecondsType> (before, fCaptureContext.GetLastCaptureAt ()); } return rawMeasurement; } virtual unique_ptr<ICapturer> Clone () const override { #if qCompilerAndStdLib_make_unique_Buggy return unique_ptr<ICapturer> (new MyCapturer_ (fCaptureContext)); #else return make_unique<MyCapturer_> (fCaptureContext); #endif } }; } /* ******************************************************************************** ******************* Instruments::Memory::GetInstrument ************************* ******************************************************************************** */ Instrument SystemPerformance::Instruments::Memory::GetInstrument (Options options) { return Instrument ( InstrumentNameType { String_Constant (L"Memory") }, #if qCompilerAndStdLib_make_unique_Buggy Instrument::SharedByValueCaptureRepType (unique_ptr<MyCapturer_> (new MyCapturer_ (CapturerWithContext_ { options }))), #else Instrument::SharedByValueCaptureRepType (make_unique<MyCapturer_> (CapturerWithContext_ { options })), #endif { kMemoryUsageMeasurement_ }, GetObjectVariantMapper () ); } /* ******************************************************************************** ********* SystemPerformance::Instrument::CaptureOneMeasurement ***************** ******************************************************************************** */ template <> Instruments::Memory::Info SystemPerformance::Instrument::CaptureOneMeasurement (Range<DurationSecondsType>* measurementTimeOut) { MyCapturer_* myCap = dynamic_cast<MyCapturer_*> (fCapFun_.get ()); AssertNotNull (myCap); return myCap->Capture_Raw (measurementTimeOut); } SystemPerformance/Instruments/Memory that was marked POSIX is really Linux (so re-marked) /* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #if qPlatform_AIX #include <libperfstat.h> #endif #include "../../../Foundation/Characters/FloatConversion.h" #include "../../../Foundation/Characters/String_Constant.h" #include "../../../Foundation/Characters/String2Int.h" #include "../../../Foundation/Configuration/SystemConfiguration.h" #include "../../../Foundation/Containers/Mapping.h" #include "../../../Foundation/Containers/Sequence.h" #include "../../../Foundation/Containers/Set.h" #include "../../../Foundation/Debug/Assertions.h" #include "../../../Foundation/Debug/AssertExternallySynchronizedLock.h" #include "../../../Foundation/Debug/Trace.h" #include "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h" #include "../../../Foundation/Execution/ErrNoException.h" #include "../../../Foundation/Execution/ProcessRunner.h" #include "../../../Foundation/Execution/Sleep.h" #include "../../../Foundation/IO/FileSystem/FileInputStream.h" #include "../../../Foundation/Streams/InputStream.h" #include "../../../Foundation/Streams/MemoryStream.h" #include "../../../Foundation/Streams/TextReader.h" #include "Memory.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::SystemPerformance; using namespace Stroika::Frameworks::SystemPerformance::Instruments::Memory; using Characters::Character; using Characters::String_Constant; using Containers::Mapping; using Containers::Sequence; using Containers::Set; using IO::FileSystem::FileInputStream; using Time::DurationSecondsType; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #ifndef qUseWMICollectionSupport_ #define qUseWMICollectionSupport_ qPlatform_Windows #endif #if qUseWMICollectionSupport_ #include "../Support/WMICollector.h" using SystemPerformance::Support::WMICollector; #endif #if qUseWMICollectionSupport_ namespace { const String_Constant kInstanceName_ { L"_Total" }; const String_Constant kCommittedBytes_ { L"Committed Bytes" }; const String_Constant kCommitLimit_ { L"Commit Limit" }; const String_Constant kPagesPerSec_ { L"Pages/sec" }; // hard page faults/sec const String_Constant kFreeMem_ { L"Free & Zero Page List Bytes" }; } #endif namespace { struct CapturerWithContext_COMMON_ { Options fOptions_; DurationSecondsType fMinimumAveragingInterval_; DurationSecondsType fPostponeCaptureUntil_ { 0 }; DurationSecondsType fLastCapturedAt_ {}; CapturerWithContext_COMMON_ (const Options& options) : fOptions_ (options) , fMinimumAveragingInterval_ (options.fMinimumAveragingInterval) { } DurationSecondsType GetLastCaptureAt () const { return fLastCapturedAt_; } void NoteCompletedCapture_ () { auto now = Time::GetTickCount (); fPostponeCaptureUntil_ = now + fMinimumAveragingInterval_; fLastCapturedAt_ = now; } }; } #if qPlatform_AIX namespace { struct CapturerWithContext_AIX_ : CapturerWithContext_COMMON_ { Time::DurationSecondsType fSaved_VMPageStats_At {}; uint64_t fSaved_MinorPageFaultsSinceBoot {}; uint64_t fSaved_MajorPageFaultsSinceBoot {}; uint64_t fSaved_PageOutsSinceBoot {}; CapturerWithContext_AIX_ (Options options) : CapturerWithContext_COMMON_ (options) { // for side-effect of updating aved_MajorPageFaultsSinc etc try { capture_ (); } catch (...) { DbgTrace ("bad sign that first pre-catpure failed."); // Dont propagate in case just listing collectors } } CapturerWithContext_AIX_ (const CapturerWithContext_AIX_&) = default; // copy by value fine - no need to re-wait... Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; result = capture_perfstat_ (); NoteCompletedCapture_ (); return result; } Instruments::Memory::Info capture_perfstat_ () { Instruments::Memory::Info result; perfstat_memory_total_t memResults; Execution::ThrowErrNoIfNegative (::perfstat_memory_total (nullptr, &memResults, sizeof (memResults), 1)); // From /usr/include/libperfstat.h: // u_longlong_t real_free; /* free real memory (in 4KB pages) */ result.fFreePhysicalMemory = memResults.real_free * 4 * 1024; // From /usr/include/libperfstat.h: // u_longlong_t virt_total; /* total virtual memory (in 4KB pages) result.fCommitLimit = memResults.virt_total * 4 * 1024; // // WAG /* reserved paging space (in 4KB pages) */ // u_longlong_t real_inuse; /* real memory which is in use (in 4KB pages) */ // From /usr/include/libperfstat.h: u_longlong_t pgsp_total; /* total paging space (in 4KB pages) */ result.fPagefileTotalSize = memResults.pgsp_total * 4 * 1024; #if 0 u_longlong_t real_system; /* number of pages used by system segments. * * This is the sum of all the used pages in segment marked for system usage. * * Since segment classifications are not always guaranteed to be accurate, * * This number is only an approximation. */ u_longlong_t real_user; /* number of pages used by non-system segments. * * This is the sum of all pages used in segments not marked for system usage. * * Since segment classifications are not always guaranteed to be accurate, * * This number is only an approximation. */ u_longlong_t real_process; /* number of pages used by process segments. */ #endif //wag // real_process???? result.fActivePhysicalMemory = memResults.real_pinned * 4 * 1024; result.fInactivePhysicalMemory = (memResults.real_inuse - memResults.real_pinned) * 4 * 1024;; // WAG TMPHACK result.fMemoryAvailable = result.fFreePhysicalMemory + result.fInactivePhysicalMemory; // From /usr/include/libperfstat.h: // u_longlong_t pgsp_total; /* total paging space (in 4KB pages) */ // u_longlong_t real_inuse; /* real memory which is in use (in 4KB pages) */ // u_longlong_t pgsp_free; /* free paging space (in 4KB pages) */ result.fCommittedBytes = (memResults.real_inuse + (memResults.pgsp_total - memResults.pgsp_free)) * 4 * 1024; // @todo review/copy docs here for pgexct result.fMinorPageFaultsSinceBoot = memResults.pgexct; //result.fMajorPageFaultsSinceBoot = memResults.pgins + memResults.pgouts; result.fMajorPageFaultsSinceBoot = memResults.pgins; if (result.fMinorPageFaultsSinceBoot.IsPresent ()) { Time::DurationSecondsType now = Time::GetTickCount (); if (fSaved_VMPageStats_At != 0) { result.fMinorPageFaultsPerSecond = (*result.fMinorPageFaultsSinceBoot - fSaved_MinorPageFaultsSinceBoot) / (now - fSaved_VMPageStats_At); } fSaved_MinorPageFaultsSinceBoot = *result.fMinorPageFaultsSinceBoot; fSaved_VMPageStats_At = now; } { result.fPageOutsSinceBoot = memResults.pgouts; if (fSaved_VMPageStats_At != 0) { updateResult->fPageOutsPerSecond = (memResults.pgouts - fSaved_PageOutsSinceBoot) / (now - fSaved_VMPageStats_At); } fSaved_PageOutsSinceBoot = memResults.pgouts; } if (result.fMajorPageFaultsSinceBoot.IsPresent ()) { Time::DurationSecondsType now = Time::GetTickCount (); if (fSaved_VMPageStats_At != 0) { result.fMajorPageFaultsPerSecond = (*result.fMajorPageFaultsSinceBoot - fSaved_MajorPageFaultsSinceBoot) / (now - fSaved_VMPageStats_At); } fSaved_MajorPageFaultsSinceBoot = *result.fMajorPageFaultsSinceBoot; } fSaved_VMPageStats_At = now; return result; } Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } }; } #endif #if qPlatform_Linux namespace { struct CapturerWithContext_Linux_ : CapturerWithContext_COMMON_ { uint64_t fSaved_MajorPageFaultsSinceBoot {}; uint64_t fSaved_PageOutsSinceBoot {}; Time::DurationSecondsType fSaved_VMPageStats_At {}; CapturerWithContext_Linux_ (Options options) : CapturerWithContext_COMMON_ (options) { // for side-effect of updating aved_MajorPageFaultsSinc etc try { capture_ (); } catch (...) { DbgTrace ("bad sign that first pre-catpure failed."); // Dont propagate in case just listing collectors } } CapturerWithContext_Linux_ (const CapturerWithContext_Linux_&) = default; // copy by value fine - no need to re-wait... Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; Read_ProcMemInfo (&result); Read_ProcVMStat_ (&result); NoteCompletedCapture_ (); return result; } void Read_ProcMemInfo (Instruments::Memory::Info* updateResult) { auto ReadMemInfoLine_ = [] (Optional<uint64_t>* result, const String & n, const Sequence<String>& line) { if (line.size () >= 3 and line[0] == n) { String unit = line[2]; double factor = (unit == L"kB") ? 1024 : 1; *result = static_cast<uint64_t> (round (Characters::String2Float<double> (line[1]) * factor)); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } }; static const String_Constant kProcMemInfoFileName_ { L"/proc/meminfo" }; //const String_Constant kProcMemInfoFileName_ { L"c:\\Sandbox\\VMSharedFolder\\meminfo" }; DataExchange::CharacterDelimitedLines::Reader reader {{ ':', ' ', '\t' }}; // Note - /procfs files always unseekable for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (kProcMemInfoFileName_, FileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadMemInfoLine_ (&updateResult->fFreePhysicalMemory, String_Constant (L"MemFree"), line); ReadMemInfoLine_ (&updateResult->fMemoryAvailable, String_Constant (L"MemAvailable"), line); ReadMemInfoLine_ (&updateResult->fActivePhysicalMemory, String_Constant (L"Active"), line); ReadMemInfoLine_ (&updateResult->fInactivePhysicalMemory, String_Constant (L"Inactive"), line); ReadMemInfoLine_ (&updateResult->fCommitLimit, String_Constant (L"CommitLimit"), line); ReadMemInfoLine_ (&updateResult->fCommittedBytes, String_Constant (L"Committed_AS"), line); #if 0 ReadMemInfoLine_ (&updateResult->fLargestAvailableVirtualChunk, String_Constant (L"VmallocChunk"), line); #endif ReadMemInfoLine_ (&updateResult->fPagefileTotalSize, String_Constant (L"SwapTotal"), line); } } void Read_ProcVMStat_ (Instruments::Memory::Info* updateResult) { auto ReadVMStatLine_ = [] (Optional<uint64_t>* result, const String & n, const Sequence<String>& line) { if (line.size () >= 2 and line[0] == n) { *result = Characters::String2Int<uint64_t> (line[1]); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } }; { static const String_Constant kProcVMStatFileName_ { L"/proc/vmstat" }; Optional<uint64_t> pgfault; Optional<uint64_t> pgpgout; // Note - /procfs files always unseekable DataExchange::CharacterDelimitedLines::Reader reader {{ ' ', '\t' }}; for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (kProcVMStatFileName_, FileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadVMStatLine_ (&pgfault, String_Constant (L"pgfault"), line); // Unsure if this should be pgpgout or pgpgout, or none of the above. On a system with no swap, I seem to get both happening, // which makes no sense ReadVMStatLine_ (&pgpgout, String_Constant (L"pgpgout"), line); // tried pgpgout but I dont know what it is but doesnt appear to be pages out - noneof this well documented ReadVMStatLine_ (&updateResult->fMajorPageFaultsSinceBoot, String_Constant (L"pgmajfault"), line); } Time::DurationSecondsType now = Time::GetTickCount (); if (pgpgout) { updateResult->fPageOutsSinceBoot = pgpgout; if (fSaved_VMPageStats_At != 0) { updateResult->fPageOutsPerSecond = (*updateResult->fPageOutsSinceBoot - fSaved_PageOutsSinceBoot) / (now - fSaved_VMPageStats_At); } fSaved_PageOutsSinceBoot = *pgpgout; } if (pgfault and updateResult->fMajorPageFaultsSinceBoot) { updateResult->fMinorPageFaultsSinceBoot = *pgfault - *updateResult->fMajorPageFaultsSinceBoot; } if (updateResult->fMajorPageFaultsSinceBoot) { if (fSaved_VMPageStats_At != 0) { updateResult->fMajorPageFaultsPerSecond = (*updateResult->fMajorPageFaultsSinceBoot - fSaved_MajorPageFaultsSinceBoot) / (now - fSaved_VMPageStats_At); } fSaved_MajorPageFaultsSinceBoot = *updateResult->fMajorPageFaultsSinceBoot; } fSaved_VMPageStats_At = now; } } }; } #endif #if qPlatform_Windows namespace { struct CapturerWithContext_Windows_ : CapturerWithContext_COMMON_ { #if qUseWMICollectionSupport_ WMICollector fMemoryWMICollector_ { String_Constant { L"Memory" }, {kInstanceName_}, {kCommittedBytes_, kCommitLimit_, kPagesPerSec_, kFreeMem_ } }; #endif CapturerWithContext_Windows_ (const Options& options) : CapturerWithContext_COMMON_ (options) { capture_ (); // to pre-seed context #if USE_NOISY_TRACE_IN_THIS_MODULE_ for (String i : fMemoryWMICollector_.GetAvailableCounters ()) { DbgTrace (L"Memory:Countername: %s", i.c_str ()); } #endif } CapturerWithContext_Windows_ (const CapturerWithContext_Windows_& from) : CapturerWithContext_COMMON_ (from) #if qUseWMICollectionSupport_ , fMemoryWMICollector_ (from.fMemoryWMICollector_) #endif { #if qUseWMICollectionSupport_ capture_ (); // to pre-seed context #endif } Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; uint64_t totalRAM {}; Read_GlobalMemoryStatusEx_(&result, &totalRAM); #if qUseWMICollectionSupport_ Read_WMI_ (&result, totalRAM); #endif NoteCompletedCapture_ (); return result; } Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } void Read_GlobalMemoryStatusEx_ (Instruments::Memory::Info* updateResult, uint64_t* totalRAM) { RequireNotNull (totalRAM); MEMORYSTATUSEX statex; memset (&statex, 0, sizeof (statex)); statex.dwLength = sizeof (statex); Verify (::GlobalMemoryStatusEx (&statex) != 0); //updateResult->fFreePhysicalMemory = statex.ullAvailPhys; *totalRAM = statex.ullTotalPhys; /* * dwMemoryLoad * A number between 0 and 100 that specifies the approximate percentage of physical * memory that is in use (0 indicates no memory use and 100 indicates full memory use) */ updateResult->fActivePhysicalMemory = statex.ullTotalPhys * statex.dwMemoryLoad / 100; } #if qUseWMICollectionSupport_ void Read_WMI_ (Instruments::Memory::Info* updateResult, uint64_t totalRAM) { fMemoryWMICollector_.Collect (); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kCommittedBytes_).CopyToIf (&updateResult->fCommittedBytes); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kCommitLimit_).CopyToIf (&updateResult->fCommitLimit); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kPagesPerSec_).CopyToIf (&updateResult->fMajorPageFaultsPerSecond); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kFreeMem_).CopyToIf (&updateResult->fFreePhysicalMemory); if (Optional<double> freeMem = fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kFreeMem_)) { if (updateResult->fActivePhysicalMemory) { // Active + Inactive + Free == TotalRAM updateResult->fInactivePhysicalMemory = totalRAM - *updateResult->fActivePhysicalMemory - static_cast<uint64_t> (*freeMem); } } // WAG TMPHACK - probably should add "hardware in use" memory + private WS of each process + shared memory "WS" - but not easy to compute... updateResult->fMemoryAvailable = updateResult->fFreePhysicalMemory + updateResult->fInactivePhysicalMemory; } #endif }; } #endif namespace { struct CapturerWithContext_ : Debug::AssertExternallySynchronizedLock #if qPlatform_AIX , CapturerWithContext_AIX_ #elif qPlatform_Linux , CapturerWithContext_Linux_ #elif qPlatform_Windows , CapturerWithContext_Windows_ #endif { #if qPlatform_AIX using inherited = CapturerWithContext_AIX_; #elif qPlatform_Linux using inherited = CapturerWithContext_Linux_; #elif qPlatform_Windows using inherited = CapturerWithContext_Windows_; #endif CapturerWithContext_ (Options options) : inherited (options) { } Instruments::Memory::Info capture () { lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Instruments::Memory::Info capture"); #endif return inherited::capture (); } }; } /* ******************************************************************************** ******************** Instruments::Memory::GetObjectVariantMapper *************** ******************************************************************************** */ ObjectVariantMapper Instruments::Memory::GetObjectVariantMapper () { using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo; static const ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper { ObjectVariantMapper mapper; mapper.AddCommonType<Optional<uint64_t>> (); mapper.AddCommonType<Optional<double>> (); DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 mapper.AddClass<Info> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fFreePhysicalMemory), String_Constant (L"Free-Physical-Memory"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMemoryAvailable), String_Constant (L"Memory-Available"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fActivePhysicalMemory), String_Constant (L"Active-Physical-Memory"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fInactivePhysicalMemory), String_Constant (L"Inactive-Physical-Memory"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fCommitLimit), String_Constant (L"Commit-Limit"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fCommittedBytes), String_Constant (L"Committed-Bytes"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fPagefileTotalSize), String_Constant (L"Pagefile-Total-Size"), StructureFieldInfo::NullFieldHandling::eOmit }, #if 0 { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLargestAvailableVirtualChunk), String_Constant (L"Largest-Available-Virtual-Chunk"), StructureFieldInfo::NullFieldHandling::eOmit }, #endif { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsSinceBoot), String_Constant (L"Major-Page-Faults-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsSinceBoot), String_Constant (L"Minor-Page-Faults-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsPerSecond), String_Constant (L"Major-Page-Faults-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsPerSecond), String_Constant (L"Minor-Page-Faults-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fPageOutsSinceBoot), String_Constant (L"Page-Outs-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fPageOutsPerSecond), String_Constant (L"Page-Outs-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, }); DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\""); DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\""); return mapper; } (); return sMapper_; } namespace { const MeasurementType kMemoryUsageMeasurement_ = MeasurementType (String_Constant (L"Memory-Usage")); } namespace { class MyCapturer_ : public Instrument::ICapturer { CapturerWithContext_ fCaptureContext; public: MyCapturer_ (const CapturerWithContext_& ctx) : fCaptureContext (ctx) { } virtual MeasurementSet Capture () { MeasurementSet results; results.fMeasurements.Add (Measurement { kMemoryUsageMeasurement_, GetObjectVariantMapper ().FromObject (Capture_Raw (&results.fMeasuredAt))}); return results; } nonvirtual Info Capture_Raw (Range<DurationSecondsType>* outMeasuredAt) { DurationSecondsType before = fCaptureContext.GetLastCaptureAt (); Info rawMeasurement = fCaptureContext.capture (); if (outMeasuredAt != nullptr) { *outMeasuredAt = Range<DurationSecondsType> (before, fCaptureContext.GetLastCaptureAt ()); } return rawMeasurement; } virtual unique_ptr<ICapturer> Clone () const override { #if qCompilerAndStdLib_make_unique_Buggy return unique_ptr<ICapturer> (new MyCapturer_ (fCaptureContext)); #else return make_unique<MyCapturer_> (fCaptureContext); #endif } }; } /* ******************************************************************************** ******************* Instruments::Memory::GetInstrument ************************* ******************************************************************************** */ Instrument SystemPerformance::Instruments::Memory::GetInstrument (Options options) { return Instrument ( InstrumentNameType { String_Constant (L"Memory") }, #if qCompilerAndStdLib_make_unique_Buggy Instrument::SharedByValueCaptureRepType (unique_ptr<MyCapturer_> (new MyCapturer_ (CapturerWithContext_ { options }))), #else Instrument::SharedByValueCaptureRepType (make_unique<MyCapturer_> (CapturerWithContext_ { options })), #endif { kMemoryUsageMeasurement_ }, GetObjectVariantMapper () ); } /* ******************************************************************************** ********* SystemPerformance::Instrument::CaptureOneMeasurement ***************** ******************************************************************************** */ template <> Instruments::Memory::Info SystemPerformance::Instrument::CaptureOneMeasurement (Range<DurationSecondsType>* measurementTimeOut) { MyCapturer_* myCap = dynamic_cast<MyCapturer_*> (fCapFun_.get ()); AssertNotNull (myCap); return myCap->Capture_Raw (measurementTimeOut); }
/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #if qPlatform_AIX #include <libperfstat.h> #endif #include "../../../Foundation/Characters/FloatConversion.h" #include "../../../Foundation/Characters/String_Constant.h" #include "../../../Foundation/Characters/String2Int.h" #include "../../../Foundation/Configuration/SystemConfiguration.h" #include "../../../Foundation/Containers/Mapping.h" #include "../../../Foundation/Containers/Sequence.h" #include "../../../Foundation/Containers/Set.h" #include "../../../Foundation/Debug/Assertions.h" #include "../../../Foundation/Debug/AssertExternallySynchronizedLock.h" #include "../../../Foundation/Debug/Trace.h" #include "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h" #include "../../../Foundation/Execution/ErrNoException.h" #include "../../../Foundation/Execution/ProcessRunner.h" #include "../../../Foundation/Execution/Sleep.h" #include "../../../Foundation/IO/FileSystem/FileInputStream.h" #include "../../../Foundation/Streams/InputStream.h" #include "../../../Foundation/Streams/MemoryStream.h" #include "../../../Foundation/Streams/TextReader.h" #include "Memory.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::SystemPerformance; using namespace Stroika::Frameworks::SystemPerformance::Instruments::Memory; using Characters::Character; using Characters::String_Constant; using Containers::Mapping; using Containers::Sequence; using Containers::Set; using IO::FileSystem::FileInputStream; using Time::DurationSecondsType; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #ifndef qUseWMICollectionSupport_ #define qUseWMICollectionSupport_ qPlatform_Windows #endif #if qUseWMICollectionSupport_ #include "../Support/WMICollector.h" using SystemPerformance::Support::WMICollector; #endif #if qUseWMICollectionSupport_ namespace { const String_Constant kInstanceName_ { L"_Total" }; const String_Constant kCommittedBytes_ { L"Committed Bytes" }; const String_Constant kCommitLimit_ { L"Commit Limit" }; const String_Constant kPagesPerSec_ { L"Pages/sec" }; // hard page faults/sec const String_Constant kFreeMem_ { L"Free & Zero Page List Bytes" }; } #endif namespace { struct CapturerWithContext_COMMON_ { Options fOptions_; DurationSecondsType fMinimumAveragingInterval_; DurationSecondsType fPostponeCaptureUntil_ { 0 }; DurationSecondsType fLastCapturedAt_ {}; CapturerWithContext_COMMON_ (const Options& options) : fOptions_ (options) , fMinimumAveragingInterval_ (options.fMinimumAveragingInterval) { } DurationSecondsType GetLastCaptureAt () const { return fLastCapturedAt_; } void NoteCompletedCapture_ () { auto now = Time::GetTickCount (); fPostponeCaptureUntil_ = now + fMinimumAveragingInterval_; fLastCapturedAt_ = now; } }; } #if qPlatform_AIX namespace { struct CapturerWithContext_AIX_ : CapturerWithContext_COMMON_ { Time::DurationSecondsType fSaved_VMPageStats_At {}; uint64_t fSaved_MinorPageFaultsSinceBoot {}; uint64_t fSaved_MajorPageFaultsSinceBoot {}; uint64_t fSaved_PageOutsSinceBoot {}; CapturerWithContext_AIX_ (Options options) : CapturerWithContext_COMMON_ (options) { // for side-effect of updating aved_MajorPageFaultsSinc etc try { capture_ (); } catch (...) { DbgTrace ("bad sign that first pre-catpure failed."); // Dont propagate in case just listing collectors } } CapturerWithContext_AIX_ (const CapturerWithContext_AIX_&) = default; // copy by value fine - no need to re-wait... Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; result = capture_perfstat_ (); NoteCompletedCapture_ (); return result; } Instruments::Memory::Info capture_perfstat_ () { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("capture_perfstat_"); #endif Instruments::Memory::Info result; perfstat_memory_total_t memResults; Execution::ThrowErrNoIfNegative (::perfstat_memory_total (nullptr, &memResults, sizeof (memResults), 1)); /* * From /usr/include/libperfstat.h: * u_longlong_t real_free; /* free real memory (in 4KB pages) * u_longlong_t real_avail - number of pages (in 4KB pages) of memory available without paging out working segments * u_longlong_t real_inuse; * real memory which is in use (in 4KB pages) * u_longlong_t pgsp_total; * total paging space (in 4KB pages) * u_longlong_t pgsp_free; * free paging space (in 4KB pages) * u_longlong_t virt_active; Active virtual pages. Virtual pages are considered active if they have been accessed * u_longlong_t virt_total; * total virtual memory (in 4KB pages) * * u_longlong_t pgins; number of pages paged in * u_longlong_t pgouts; number of pages paged out * u_longlong_t pgspins; number of page ins from paging space * u_longlong_t pgspouts; number of page outs from paging space * * Empirically, and logically from the (vague) definitions (perfstat_memory_total_t), real_total = real_inuse + real_free * * Some assorted unused stats from * /usr/include/libperfstat.h: * * u_longlong_t real_system; number of pages used by system segments. * * This is the sum of all the used pages in segment marked for system usage. * * Since segment classifications are not always guaranteed to be accurate, * * This number is only an approximation. * u_longlong_t real_user; * number of pages used by non-system segments. * * This is the sum of all pages used in segments not marked for system usage. * * Since segment classifications are not always guaranteed to be accurate, * * This number is only an approximation. * u_longlong_t real_process; * number of pages used by process segments. * u_longlong_t scans; * number of page scans by clock * u_longlong_t cycles; * number of page replacement cycles * u_longlong_t pgsteals; * number of page steals * u_longlong_t numperm; * number of frames used for files (in 4KB pages) */ #if USE_NOISY_TRACE_IN_THIS_MODULE_ // [---MAIN---][0000.007] real_total=983040 // [---MAIN---][0000.007] real_free=280802 // [---MAIN---][0000.007] real_inuse=702238 // [---MAIN---][0000.007] real_pinned=237141 *not used* see kIncludeUnPinnedActiveRAMAsAvailable_ // [---MAIN---][0000.007] real_avail=606596 // [---MAIN---][0000.007] real_user=472485 *not used* // [---MAIN---][0000.007] real_system=195546 *not used* // [---MAIN---][0000.007] real_process=148875 *not used* // [---MAIN---][0000.007] virt_active=332889 // [---MAIN---][0000.007] virt_total=1998848 DbgTrace ("real_total=%lld", memResults.real_total); DbgTrace ("real_free=%lld", memResults.real_free); DbgTrace ("real_inuse=%lld", memResults.real_inuse); DbgTrace ("real_pinned=%lld", memResults.real_pinned); DbgTrace ("real_avail=%lld", memResults.real_avail); DbgTrace ("real_user=%lld", memResults.real_user); DbgTrace ("real_system=%lld", memResults.real_system); DbgTrace ("real_process=%lld", memResults.real_process); DbgTrace ("virt_active=%lld", memResults.virt_active); DbgTrace ("virt_total=%lld", memResults.virt_total); #endif result.fPhysicalMemory.fFree = memResults.real_free * 4 * 1024; /* * Pinned pages cannot be paged out. * https://www-01.ibm.com/support/knowledgecenter/ssw_aix_71/com.ibm.aix.performance/support_pinned_mem.htm * "Pinning a memory region prohibits the pager from stealing pages from the pages backing the pinned memory region" * * What we want to call active is really LARGER than this, but this is at least an estimate of actively in use memory. * (FOR NOW IGNORE ABOVE BUT LATER WE MAY WANT TO FACTOR 'pinned' in - maybe assuring activePhysRam at least as much * as pinned?) * * SINCE we know: * real_total = real_inuse + real_free; * since we define RAMTOTAL = INACTIVE + ACTIVE + FREE + OS_RESERVED * setting real_inuse + real_free = INACTIVE + ACTIVE + FREE + OS_RESERVED => * ACTIVE + INACTIVE + OS_RESERVED = real_inuse; * * It APPEARS (empirically looking at results) that * real_avail = real_free + INACTIVE * * SO: * INACIVE = is real_avail - real_free * ACTIVE= (real_inuse - (real_avail-real_free) - OS_RESERVED); */ result.fPhysicalMemory.fOSReserved = static_cast<uint64_t> (0); // since we cannot find - it would be subtracted from active or inactive if we had something here result.fPhysicalMemory.fInactive = (memResults.real_avail - memResults.real_free) * 4 * 1024; result.fPhysicalMemory.fActive = (memResults.real_inuse - memResults.real_avail + memResults.real_free) * 4 * 1024 - *result.fPhysicalMemory.fOSReserved; /* * This is our best estimate of what is available. On LINUX, we can also add in 'SReclaimable' - kernel RAM * we could use if needed. */ result.fPhysicalMemory.fAvailable = memResults.real_avail * 4 * 1024; /* * This makes Sterling's graphs look better, but I think including unpinned active RAM is * not likely correct. Maybe if we included non-dirty RAM? but dirty doesnt appear to * lock. So disable this for now. */ const bool kIncludeUnPinnedActiveRAMAsAvailable_ { false }; if (kIncludeUnPinnedActiveRAMAsAvailable_) { // What we are calling available doesn't count un-pinned uint64_t pinnedRAM = memResults.real_pinned * 4 * 1024; if (result.fPhysicalMemory.fActive > pinnedRAM) { result.fPhysicalMemory.fAvailable += (*result.fPhysicalMemory.fActive - pinnedRAM); } } /* * This number (virt_active) by nmon to summarize virtual memory status. But very little else... * * Tried (memResults.real_inuse + (memResults.pgsp_total - memResults.pgsp_free)) * 4 * 1024; * but that didn't produce a good/representative answer. */ result.fVirtualMemory.fCommittedBytes = (memResults.virt_active) * 4 * 1024; result.fVirtualMemory.fCommitLimit = memResults.virt_total * 4 * 1024; result.fVirtualMemory.fPagefileTotalSize = memResults.pgsp_total * 4 * 1024; result.fPaging.fMajorPageFaultsSinceBoot = memResults.pgspins; result.fPaging.fMinorPageFaultsSinceBoot = memResults.pgins - memResults.pgspins; result.fPaging.fPageOutsSinceBoot = memResults.pgouts; Time::DurationSecondsType now = Time::GetTickCount (); auto doAve_ = [] (Time::DurationSecondsType savedVMPageStatsAt, Time::DurationSecondsType now, uint64_t* savedBaseline, Optional<uint64_t> faultsSinceBoot, Optional<double>* faultsPerSecond) { if (faultsSinceBoot) { if (savedVMPageStatsAt != 0) { *faultsPerSecond = (*faultsSinceBoot - *savedBaseline) / (now - savedVMPageStatsAt); } *savedBaseline = *faultsSinceBoot; } }; doAve_ (fSaved_VMPageStats_At, now, &fSaved_MinorPageFaultsSinceBoot, result.fPaging.fMinorPageFaultsSinceBoot, &result.fPaging.fMinorPageFaultsPerSecond); doAve_ (fSaved_VMPageStats_At, now, &fSaved_MajorPageFaultsSinceBoot, result.fPaging.fMajorPageFaultsSinceBoot, &result.fPaging.fMajorPageFaultsPerSecond); doAve_ (fSaved_VMPageStats_At, now, &fSaved_PageOutsSinceBoot, memResults.pgouts, &result.fPaging.fPageOutsPerSecond); fSaved_VMPageStats_At = now; return result; } Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } }; } #endif #if qPlatform_Linux namespace { struct CapturerWithContext_Linux_ : CapturerWithContext_COMMON_ { uint64_t fSaved_MajorPageFaultsSinceBoot {}; uint64_t fSaved_MinorPageFaultsSinceBoot {}; uint64_t fSaved_PageOutsSinceBoot {}; Time::DurationSecondsType fSaved_VMPageStats_At {}; CapturerWithContext_Linux_ (Options options) : CapturerWithContext_COMMON_ (options) { // for side-effect of updating aved_MajorPageFaultsSinc etc try { capture_ (); } catch (...) { DbgTrace ("bad sign that first pre-catpure failed."); // Dont propagate in case just listing collectors } } CapturerWithContext_Linux_ (const CapturerWithContext_Linux_&) = default; // copy by value fine - no need to re-wait... Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; Read_ProcMemInfo (&result); Read_ProcVMStat_ (&result); NoteCompletedCapture_ (); return result; } void Read_ProcMemInfo (Instruments::Memory::Info* updateResult) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Read_ProcMemInfo"); #endif auto ReadMemInfoLine_ = [] (Optional<uint64_t>* result, const String & n, const Sequence<String>& line) { if (line.size () >= 3 and line[0] == n) { String unit = line[2]; double factor = (unit == L"kB") ? 1024 : 1; *result = static_cast<uint64_t> (round (Characters::String2Float<double> (line[1]) * factor)); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } }; static const String_Constant kProcMemInfoFileName_ { L"/proc/meminfo" }; //const String_Constant kProcMemInfoFileName_ { L"c:\\Sandbox\\VMSharedFolder\\meminfo" }; DataExchange::CharacterDelimitedLines::Reader reader {{ ':', ' ', '\t' }}; // Note - /procfs files always unseekable Optional<uint64_t> memTotal; Optional<uint64_t> slabReclaimable; for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (kProcMemInfoFileName_, FileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadMemInfoLine_ (&memTotal, String_Constant (L"MemTotal"), line); ReadMemInfoLine_ (&updateResult->fPhysicalMemory.fFree, String_Constant (L"MemFree"), line); ReadMemInfoLine_ (&updateResult->fPhysicalMemory.fAvailable, String_Constant (L"MemAvailable"), line); ReadMemInfoLine_ (&updateResult->fPhysicalMemory.fActive, String_Constant (L"Active"), line); ReadMemInfoLine_ (&updateResult->fPhysicalMemory.fInactive, String_Constant (L"Inactive"), line); ReadMemInfoLine_ (&updateResult->fVirtualMemory.fCommitLimit, String_Constant (L"CommitLimit"), line); ReadMemInfoLine_ (&updateResult->fVirtualMemory.fCommittedBytes, String_Constant (L"Committed_AS"), line); ReadMemInfoLine_ (&updateResult->fVirtualMemory.fPagefileTotalSize, String_Constant (L"SwapTotal"), line); ReadMemInfoLine_ (&slabReclaimable, String_Constant (L"SReclaimable"), line); } if (memTotal and updateResult->fPhysicalMemory.fFree and updateResult->fPhysicalMemory.fInactive and updateResult->fPhysicalMemory.fActive) { updateResult->fPhysicalMemory.fOSReserved = *memTotal - *updateResult->fPhysicalMemory.fFree - *updateResult->fPhysicalMemory.fInactive - *updateResult->fPhysicalMemory.fActive; } if (updateResult->fPhysicalMemory.fAvailable.IsMissing () and updateResult->fPhysicalMemory.fFree and updateResult->fPhysicalMemory.fInactive) { updateResult->fPhysicalMemory.fAvailable = *updateResult->fPhysicalMemory.fFree + *updateResult->fPhysicalMemory.fInactive + slabReclaimable.Value (); } } void Read_ProcVMStat_ (Instruments::Memory::Info* updateResult) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Read_ProcVMStat_"); #endif auto ReadVMStatLine_ = [] (Optional<uint64_t>* result, const String & n, const Sequence<String>& line) { if (line.size () >= 2 and line[0] == n) { *result = Characters::String2Int<uint64_t> (line[1]); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } }; { static const String_Constant kProcVMStatFileName_ { L"/proc/vmstat" }; Optional<uint64_t> pgfault; Optional<uint64_t> pgpgout; // Note - /procfs files always unseekable DataExchange::CharacterDelimitedLines::Reader reader {{ ' ', '\t' }}; for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (kProcVMStatFileName_, FileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadVMStatLine_ (&pgfault, String_Constant (L"pgfault"), line); // Unsure if this should be pgpgout or pgpgout, or none of the above. On a system with no swap, I seem to get both happening, // which makes no sense ReadVMStatLine_ (&pgpgout, String_Constant (L"pgpgout"), line); // tried pgpgout but I dont know what it is but doesnt appear to be pages out - noneof this well documented ReadVMStatLine_ (&updateResult->fPaging.fMajorPageFaultsSinceBoot, String_Constant (L"pgmajfault"), line); } Time::DurationSecondsType now = Time::GetTickCount (); updateResult->fPaging.fPageOutsSinceBoot = pgpgout; if (pgfault and updateResult->fPaging.fMajorPageFaultsSinceBoot) { updateResult->fPaging.fMinorPageFaultsSinceBoot = *pgfault - *updateResult->fPaging.fMajorPageFaultsSinceBoot; } auto doAve_ = [] (Time::DurationSecondsType savedVMPageStatsAt, Time::DurationSecondsType now, uint64_t* savedBaseline, Optional<uint64_t> faultsSinceBoot, Optional<double>* faultsPerSecond) { if (faultsSinceBoot) { if (savedVMPageStatsAt != 0) { *faultsPerSecond = (*faultsSinceBoot - *savedBaseline) / (now - savedVMPageStatsAt); } *savedBaseline = *faultsSinceBoot; } }; doAve_ (fSaved_VMPageStats_At, now, &fSaved_MinorPageFaultsSinceBoot, updateResult->fPaging.fMinorPageFaultsSinceBoot, &updateResult->fPaging.fMinorPageFaultsPerSecond); doAve_ (fSaved_VMPageStats_At, now, &fSaved_MajorPageFaultsSinceBoot, updateResult->fPaging.fMajorPageFaultsSinceBoot, &updateResult->fPaging.fMajorPageFaultsPerSecond); doAve_ (fSaved_VMPageStats_At, now, &fSaved_PageOutsSinceBoot, updateResult->fPaging.fPageOutsSinceBoot, &updateResult->fPaging.fPageOutsPerSecond); fSaved_VMPageStats_At = now; } } }; } #endif #if qPlatform_Windows namespace { struct CapturerWithContext_Windows_ : CapturerWithContext_COMMON_ { #if qUseWMICollectionSupport_ WMICollector fMemoryWMICollector_ { String_Constant { L"Memory" }, {kInstanceName_}, {kCommittedBytes_, kCommitLimit_, kPagesPerSec_, kFreeMem_ } }; #endif CapturerWithContext_Windows_ (const Options& options) : CapturerWithContext_COMMON_ (options) { capture_ (); // to pre-seed context #if USE_NOISY_TRACE_IN_THIS_MODULE_ for (String i : fMemoryWMICollector_.GetAvailableCounters ()) { DbgTrace (L"Memory:Countername: %s", i.c_str ()); } #endif } CapturerWithContext_Windows_ (const CapturerWithContext_Windows_& from) : CapturerWithContext_COMMON_ (from) #if qUseWMICollectionSupport_ , fMemoryWMICollector_ (from.fMemoryWMICollector_) #endif { #if qUseWMICollectionSupport_ capture_ (); // to pre-seed context #endif } Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; uint64_t totalRAM {}; Read_GlobalMemoryStatusEx_(&result, &totalRAM); #if qUseWMICollectionSupport_ Read_WMI_ (&result, totalRAM); #endif NoteCompletedCapture_ (); return result; } Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } void Read_GlobalMemoryStatusEx_ (Instruments::Memory::Info* updateResult, uint64_t* totalRAM) { RequireNotNull (totalRAM); MEMORYSTATUSEX statex; memset (&statex, 0, sizeof (statex)); statex.dwLength = sizeof (statex); Verify (::GlobalMemoryStatusEx (&statex) != 0); //updateResult->fPhysicalMemory.fFree = statex.ullAvailPhys; *totalRAM = statex.ullTotalPhys; /* * dwMemoryLoad * A number between 0 and 100 that specifies the approximate percentage of physical * memory that is in use (0 indicates no memory use and 100 indicates full memory use) */ updateResult->fPhysicalMemory.fActive = statex.ullTotalPhys * statex.dwMemoryLoad / 100; } #if qUseWMICollectionSupport_ void Read_WMI_ (Instruments::Memory::Info* updateResult, uint64_t totalRAM) { fMemoryWMICollector_.Collect (); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kCommittedBytes_).CopyToIf (&updateResult->fVirtualMemory.fCommittedBytes); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kCommitLimit_).CopyToIf (&updateResult->fVirtualMemory.fCommitLimit); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kPagesPerSec_).CopyToIf (&updateResult->fPaging.fMajorPageFaultsPerSecond); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kFreeMem_).CopyToIf (&updateResult->fPhysicalMemory.fFree); if (Optional<double> freeMem = fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kFreeMem_)) { if (updateResult->fPhysicalMemory.fActive) { // Active + Inactive + Free == TotalRAM updateResult->fPhysicalMemory.fInactive = totalRAM - *updateResult->fPhysicalMemory.fActive - static_cast<uint64_t> (*freeMem); } } // WAG TMPHACK - probably should add "hardware in use" memory + private WS of each process + shared memory "WS" - but not easy to compute... updateResult->fPhysicalMemory.fAvailable = updateResult->fPhysicalMemory.fFree + updateResult->fPhysicalMemory.fInactive; } #endif }; } #endif namespace { struct CapturerWithContext_ : Debug::AssertExternallySynchronizedLock #if qPlatform_AIX , CapturerWithContext_AIX_ #elif qPlatform_Linux , CapturerWithContext_Linux_ #elif qPlatform_Windows , CapturerWithContext_Windows_ #endif { #if qPlatform_AIX using inherited = CapturerWithContext_AIX_; #elif qPlatform_Linux using inherited = CapturerWithContext_Linux_; #elif qPlatform_Windows using inherited = CapturerWithContext_Windows_; #endif CapturerWithContext_ (Options options) : inherited (options) { } Instruments::Memory::Info capture () { lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Instruments::Memory::Info capture"); #endif return inherited::capture (); } }; } /* ******************************************************************************** ****************** Instruments::Memory::GetObjectVariantMapper ***************** ******************************************************************************** */ ObjectVariantMapper Instruments::Memory::GetObjectVariantMapper () { using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo; static const ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper { ObjectVariantMapper mapper; mapper.AddCommonType<Optional<uint64_t>> (); mapper.AddCommonType<Optional<double>> (); DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 mapper.AddClass<Info::PhysicalRAMDetailsType> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PhysicalRAMDetailsType, fAvailable), String_Constant (L"Available"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PhysicalRAMDetailsType, fActive), String_Constant (L"Active"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PhysicalRAMDetailsType, fInactive), String_Constant (L"Inactive"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PhysicalRAMDetailsType, fFree), String_Constant (L"Free"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PhysicalRAMDetailsType, fOSReserved), String_Constant (L"OS-Reserved"), StructureFieldInfo::NullFieldHandling::eOmit }, }); mapper.AddClass<Info::VirtualMemoryDetailsType> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::VirtualMemoryDetailsType, fCommitLimit), String_Constant (L"Commit-Limit"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::VirtualMemoryDetailsType, fCommittedBytes), String_Constant (L"Committed-Bytes"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::VirtualMemoryDetailsType, fPagefileTotalSize), String_Constant (L"Pagefile-Total-Size"), StructureFieldInfo::NullFieldHandling::eOmit }, }); mapper.AddClass<Info::PagingDetailsType> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fMajorPageFaultsSinceBoot), String_Constant (L"Major-Faults-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fMinorPageFaultsSinceBoot), String_Constant (L"Minor-Faults-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fPageOutsSinceBoot), String_Constant (L"Page-Outs-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fMajorPageFaultsPerSecond), String_Constant (L"Major-Faults-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fMinorPageFaultsPerSecond), String_Constant (L"Minor-Faults-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fPageOutsPerSecond), String_Constant (L"Page-Outs-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, }); mapper.AddClass<Info> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fPhysicalMemory), String_Constant (L"Physical-Memory") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fVirtualMemory), String_Constant (L"Virtual-Memory") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fPaging), String_Constant (L"Paging") }, }); DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\""); DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\""); return mapper; } (); return sMapper_; } namespace { const MeasurementType kMemoryUsageMeasurement_ = MeasurementType (String_Constant (L"Memory-Usage")); } namespace { class MyCapturer_ : public Instrument::ICapturer { CapturerWithContext_ fCaptureContext; public: MyCapturer_ (const CapturerWithContext_& ctx) : fCaptureContext (ctx) { } virtual MeasurementSet Capture () { MeasurementSet results; results.fMeasurements.Add (Measurement { kMemoryUsageMeasurement_, GetObjectVariantMapper ().FromObject (Capture_Raw (&results.fMeasuredAt))}); return results; } nonvirtual Info Capture_Raw (Range<DurationSecondsType>* outMeasuredAt) { DurationSecondsType before = fCaptureContext.GetLastCaptureAt (); Info rawMeasurement = fCaptureContext.capture (); if (outMeasuredAt != nullptr) { *outMeasuredAt = Range<DurationSecondsType> (before, fCaptureContext.GetLastCaptureAt ()); } return rawMeasurement; } virtual unique_ptr<ICapturer> Clone () const override { #if qCompilerAndStdLib_make_unique_Buggy return unique_ptr<ICapturer> (new MyCapturer_ (fCaptureContext)); #else return make_unique<MyCapturer_> (fCaptureContext); #endif } }; } /* ******************************************************************************** ******************* Instruments::Memory::GetInstrument ************************* ******************************************************************************** */ Instrument SystemPerformance::Instruments::Memory::GetInstrument (Options options) { return Instrument ( InstrumentNameType { String_Constant (L"Memory") }, #if qCompilerAndStdLib_make_unique_Buggy Instrument::SharedByValueCaptureRepType (unique_ptr<MyCapturer_> (new MyCapturer_ (CapturerWithContext_ { options }))), #else Instrument::SharedByValueCaptureRepType (make_unique<MyCapturer_> (CapturerWithContext_ { options })), #endif { kMemoryUsageMeasurement_ }, GetObjectVariantMapper () ); } /* ******************************************************************************** ********* SystemPerformance::Instrument::CaptureOneMeasurement ***************** ******************************************************************************** */ template <> Instruments::Memory::Info SystemPerformance::Instrument::CaptureOneMeasurement (Range<DurationSecondsType>* measurementTimeOut) { MyCapturer_* myCap = dynamic_cast<MyCapturer_*> (fCapFun_.get ()); AssertNotNull (myCap); return myCap->Capture_Raw (measurementTimeOut); } comments /* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #if qPlatform_AIX #include <libperfstat.h> #endif #include "../../../Foundation/Characters/FloatConversion.h" #include "../../../Foundation/Characters/String_Constant.h" #include "../../../Foundation/Characters/String2Int.h" #include "../../../Foundation/Configuration/SystemConfiguration.h" #include "../../../Foundation/Containers/Mapping.h" #include "../../../Foundation/Containers/Sequence.h" #include "../../../Foundation/Containers/Set.h" #include "../../../Foundation/Debug/Assertions.h" #include "../../../Foundation/Debug/AssertExternallySynchronizedLock.h" #include "../../../Foundation/Debug/Trace.h" #include "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h" #include "../../../Foundation/Execution/ErrNoException.h" #include "../../../Foundation/Execution/ProcessRunner.h" #include "../../../Foundation/Execution/Sleep.h" #include "../../../Foundation/IO/FileSystem/FileInputStream.h" #include "../../../Foundation/Streams/InputStream.h" #include "../../../Foundation/Streams/MemoryStream.h" #include "../../../Foundation/Streams/TextReader.h" #include "Memory.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::SystemPerformance; using namespace Stroika::Frameworks::SystemPerformance::Instruments::Memory; using Characters::Character; using Characters::String_Constant; using Containers::Mapping; using Containers::Sequence; using Containers::Set; using IO::FileSystem::FileInputStream; using Time::DurationSecondsType; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #ifndef qUseWMICollectionSupport_ #define qUseWMICollectionSupport_ qPlatform_Windows #endif #if qUseWMICollectionSupport_ #include "../Support/WMICollector.h" using SystemPerformance::Support::WMICollector; #endif #if qUseWMICollectionSupport_ namespace { const String_Constant kInstanceName_ { L"_Total" }; const String_Constant kCommittedBytes_ { L"Committed Bytes" }; const String_Constant kCommitLimit_ { L"Commit Limit" }; const String_Constant kPagesPerSec_ { L"Pages/sec" }; // hard page faults/sec const String_Constant kFreeMem_ { L"Free & Zero Page List Bytes" }; } #endif namespace { struct CapturerWithContext_COMMON_ { Options fOptions_; DurationSecondsType fMinimumAveragingInterval_; DurationSecondsType fPostponeCaptureUntil_ { 0 }; DurationSecondsType fLastCapturedAt_ {}; CapturerWithContext_COMMON_ (const Options& options) : fOptions_ (options) , fMinimumAveragingInterval_ (options.fMinimumAveragingInterval) { } DurationSecondsType GetLastCaptureAt () const { return fLastCapturedAt_; } void NoteCompletedCapture_ () { auto now = Time::GetTickCount (); fPostponeCaptureUntil_ = now + fMinimumAveragingInterval_; fLastCapturedAt_ = now; } }; } #if qPlatform_AIX namespace { struct CapturerWithContext_AIX_ : CapturerWithContext_COMMON_ { Time::DurationSecondsType fSaved_VMPageStats_At {}; uint64_t fSaved_MinorPageFaultsSinceBoot {}; uint64_t fSaved_MajorPageFaultsSinceBoot {}; uint64_t fSaved_PageOutsSinceBoot {}; CapturerWithContext_AIX_ (Options options) : CapturerWithContext_COMMON_ (options) { // for side-effect of updating aved_MajorPageFaultsSinc etc try { capture_ (); } catch (...) { DbgTrace ("bad sign that first pre-catpure failed."); // Dont propagate in case just listing collectors } } CapturerWithContext_AIX_ (const CapturerWithContext_AIX_&) = default; // copy by value fine - no need to re-wait... Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; result = capture_perfstat_ (); NoteCompletedCapture_ (); return result; } Instruments::Memory::Info capture_perfstat_ () { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("capture_perfstat_"); #endif Instruments::Memory::Info result; perfstat_memory_total_t memResults; Execution::ThrowErrNoIfNegative (::perfstat_memory_total (nullptr, &memResults, sizeof (memResults), 1)); /* * From /usr/include/libperfstat.h: * u_longlong_t real_free; /* free real memory (in 4KB pages) * u_longlong_t real_avail - number of pages (in 4KB pages) of memory available without paging out working segments * u_longlong_t real_inuse; * real memory which is in use (in 4KB pages) * u_longlong_t pgsp_total; * total paging space (in 4KB pages) * u_longlong_t pgsp_free; * free paging space (in 4KB pages) * u_longlong_t virt_active; Active virtual pages. Virtual pages are considered active if they have been accessed * u_longlong_t virt_total; * total virtual memory (in 4KB pages) * * u_longlong_t pgins; number of pages paged in * u_longlong_t pgouts; number of pages paged out * u_longlong_t pgspins; number of page ins from paging space * u_longlong_t pgspouts; number of page outs from paging space * * Empirically, and logically from the (vague) definitions (perfstat_memory_total_t), real_total = real_inuse + real_free * * Some assorted unused stats from * /usr/include/libperfstat.h: * * u_longlong_t real_system; number of pages used by system segments. * * This is the sum of all the used pages in segment marked for system usage. * * Since segment classifications are not always guaranteed to be accurate, * * This number is only an approximation. * u_longlong_t real_user; * number of pages used by non-system segments. * * This is the sum of all pages used in segments not marked for system usage. * * Since segment classifications are not always guaranteed to be accurate, * * This number is only an approximation. * u_longlong_t real_process; * number of pages used by process segments. * u_longlong_t scans; * number of page scans by clock * u_longlong_t cycles; * number of page replacement cycles * u_longlong_t pgsteals; * number of page steals * u_longlong_t numperm; * number of frames used for files (in 4KB pages) */ #if USE_NOISY_TRACE_IN_THIS_MODULE_ // [---MAIN---][0000.007] real_total=983040 // [---MAIN---][0000.007] real_free=280802 // [---MAIN---][0000.007] real_inuse=702238 // [---MAIN---][0000.007] real_pinned=237141 *not used* see kIncludeUnPinnedActiveRAMAsAvailable_ // [---MAIN---][0000.007] real_avail=606596 // [---MAIN---][0000.007] real_user=472485 *not used* // [---MAIN---][0000.007] real_system=195546 *not used* // [---MAIN---][0000.007] real_process=148875 *not used* // [---MAIN---][0000.007] virt_active=332889 // [---MAIN---][0000.007] virt_total=1998848 DbgTrace ("real_total=%lld", memResults.real_total); DbgTrace ("real_free=%lld", memResults.real_free); DbgTrace ("real_inuse=%lld", memResults.real_inuse); DbgTrace ("real_pinned=%lld", memResults.real_pinned); DbgTrace ("real_avail=%lld", memResults.real_avail); DbgTrace ("real_user=%lld", memResults.real_user); DbgTrace ("real_system=%lld", memResults.real_system); DbgTrace ("real_process=%lld", memResults.real_process); DbgTrace ("virt_active=%lld", memResults.virt_active); DbgTrace ("virt_total=%lld", memResults.virt_total); #endif result.fPhysicalMemory.fFree = memResults.real_free * 4 * 1024; /* * Pinned pages cannot be paged out. * https://www-01.ibm.com/support/knowledgecenter/ssw_aix_71/com.ibm.aix.performance/support_pinned_mem.htm * "Pinning a memory region prohibits the pager from stealing pages from the pages backing the pinned memory region" * * What we want to call active is really LARGER than this, but this is at least an estimate of actively in use memory. * (FOR NOW IGNORE ABOVE BUT LATER WE MAY WANT TO FACTOR 'pinned' in - maybe assuring activePhysRam at least as much * as pinned?) * * SINCE we know: * real_total = real_inuse + real_free; * since we define RAMTOTAL = INACTIVE + ACTIVE + FREE + OS_RESERVED * setting real_inuse + real_free = INACTIVE + ACTIVE + FREE + OS_RESERVED => * ACTIVE + INACTIVE + OS_RESERVED = real_inuse; * * It APPEARS (empirically looking at results) that * real_avail = real_free + INACTIVE * * SO: * INACIVE = is real_avail - real_free * ACTIVE= (real_inuse - (real_avail-real_free) - OS_RESERVED); */ result.fPhysicalMemory.fOSReserved = static_cast<uint64_t> (0); // since we cannot find - it would be subtracted from active or inactive if we had something here result.fPhysicalMemory.fInactive = (memResults.real_avail - memResults.real_free) * 4 * 1024; result.fPhysicalMemory.fActive = (memResults.real_inuse - memResults.real_avail + memResults.real_free) * 4 * 1024 - *result.fPhysicalMemory.fOSReserved; /* * This is our best estimate of what is available. On LINUX, we can also add in 'SReclaimable' - kernel RAM * we could use if needed. */ result.fPhysicalMemory.fAvailable = memResults.real_avail * 4 * 1024; /* * This makes Sterling's graphs look better, but I think including unpinned active RAM is * not likely correct. Maybe if we included non-dirty RAM? but dirty doesnt appear to * lock. So disable this for now. */ const bool kIncludeUnPinnedActiveRAMAsAvailable_ { false }; if (kIncludeUnPinnedActiveRAMAsAvailable_) { // What we are calling available doesn't count un-pinned uint64_t pinnedRAM = memResults.real_pinned * 4 * 1024; if (result.fPhysicalMemory.fActive > pinnedRAM) { result.fPhysicalMemory.fAvailable += (*result.fPhysicalMemory.fActive - pinnedRAM); } } /* * This number (virt_active) by nmon to summarize virtual memory status. But very little else... * * Tried (memResults.real_inuse + (memResults.pgsp_total - memResults.pgsp_free)) * 4 * 1024; * but that didn't produce a good/representative answer. */ result.fVirtualMemory.fCommittedBytes = (memResults.virt_active) * 4 * 1024; result.fVirtualMemory.fCommitLimit = memResults.virt_total * 4 * 1024; result.fVirtualMemory.fPagefileTotalSize = memResults.pgsp_total * 4 * 1024; result.fPaging.fMajorPageFaultsSinceBoot = memResults.pgspins; result.fPaging.fMinorPageFaultsSinceBoot = memResults.pgins - memResults.pgspins; result.fPaging.fPageOutsSinceBoot = memResults.pgouts; Time::DurationSecondsType now = Time::GetTickCount (); auto doAve_ = [] (Time::DurationSecondsType savedVMPageStatsAt, Time::DurationSecondsType now, uint64_t* savedBaseline, Optional<uint64_t> faultsSinceBoot, Optional<double>* faultsPerSecond) { if (faultsSinceBoot) { if (savedVMPageStatsAt != 0) { *faultsPerSecond = (*faultsSinceBoot - *savedBaseline) / (now - savedVMPageStatsAt); } *savedBaseline = *faultsSinceBoot; } }; doAve_ (fSaved_VMPageStats_At, now, &fSaved_MinorPageFaultsSinceBoot, result.fPaging.fMinorPageFaultsSinceBoot, &result.fPaging.fMinorPageFaultsPerSecond); doAve_ (fSaved_VMPageStats_At, now, &fSaved_MajorPageFaultsSinceBoot, result.fPaging.fMajorPageFaultsSinceBoot, &result.fPaging.fMajorPageFaultsPerSecond); doAve_ (fSaved_VMPageStats_At, now, &fSaved_PageOutsSinceBoot, memResults.pgouts, &result.fPaging.fPageOutsPerSecond); fSaved_VMPageStats_At = now; return result; } Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } }; } #endif #if qPlatform_Linux namespace { struct CapturerWithContext_Linux_ : CapturerWithContext_COMMON_ { uint64_t fSaved_MajorPageFaultsSinceBoot {}; uint64_t fSaved_MinorPageFaultsSinceBoot {}; uint64_t fSaved_PageOutsSinceBoot {}; Time::DurationSecondsType fSaved_VMPageStats_At {}; CapturerWithContext_Linux_ (Options options) : CapturerWithContext_COMMON_ (options) { // for side-effect of updating aved_MajorPageFaultsSinc etc try { capture_ (); } catch (...) { DbgTrace ("bad sign that first pre-catpure failed."); // Dont propagate in case just listing collectors } } CapturerWithContext_Linux_ (const CapturerWithContext_Linux_&) = default; // copy by value fine - no need to re-wait... Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; Read_ProcMemInfo (&result); Read_ProcVMStat_ (&result); NoteCompletedCapture_ (); return result; } void Read_ProcMemInfo (Instruments::Memory::Info* updateResult) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Read_ProcMemInfo"); #endif auto ReadMemInfoLine_ = [] (Optional<uint64_t>* result, const String & n, const Sequence<String>& line) { if (line.size () >= 3 and line[0] == n) { String unit = line[2]; double factor = (unit == L"kB") ? 1024 : 1; *result = static_cast<uint64_t> (round (Characters::String2Float<double> (line[1]) * factor)); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } }; static const String_Constant kProcMemInfoFileName_ { L"/proc/meminfo" }; //const String_Constant kProcMemInfoFileName_ { L"c:\\Sandbox\\VMSharedFolder\\meminfo" }; DataExchange::CharacterDelimitedLines::Reader reader {{ ':', ' ', '\t' }}; // Note - /procfs files always unseekable Optional<uint64_t> memTotal; Optional<uint64_t> slabReclaimable; for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (kProcMemInfoFileName_, FileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadMemInfoLine_ (&memTotal, String_Constant (L"MemTotal"), line); ReadMemInfoLine_ (&updateResult->fPhysicalMemory.fFree, String_Constant (L"MemFree"), line); ReadMemInfoLine_ (&updateResult->fPhysicalMemory.fAvailable, String_Constant (L"MemAvailable"), line); ReadMemInfoLine_ (&updateResult->fPhysicalMemory.fActive, String_Constant (L"Active"), line); ReadMemInfoLine_ (&updateResult->fPhysicalMemory.fInactive, String_Constant (L"Inactive"), line); ReadMemInfoLine_ (&updateResult->fVirtualMemory.fCommitLimit, String_Constant (L"CommitLimit"), line); /* * From docs on https://github.com/torvalds/linux/blob/master/Documentation/filesystems/proc.txt about * Commited_AS - its unclear if this is the best measure of commited bytes. */ ReadMemInfoLine_ (&updateResult->fVirtualMemory.fCommittedBytes, String_Constant (L"Committed_AS"), line); ReadMemInfoLine_ (&updateResult->fVirtualMemory.fPagefileTotalSize, String_Constant (L"SwapTotal"), line); ReadMemInfoLine_ (&slabReclaimable, String_Constant (L"SReclaimable"), line); } if (memTotal and updateResult->fPhysicalMemory.fFree and updateResult->fPhysicalMemory.fInactive and updateResult->fPhysicalMemory.fActive) { updateResult->fPhysicalMemory.fOSReserved = *memTotal - *updateResult->fPhysicalMemory.fFree - *updateResult->fPhysicalMemory.fInactive - *updateResult->fPhysicalMemory.fActive; } if (updateResult->fPhysicalMemory.fAvailable.IsMissing () and updateResult->fPhysicalMemory.fFree and updateResult->fPhysicalMemory.fInactive) { updateResult->fPhysicalMemory.fAvailable = *updateResult->fPhysicalMemory.fFree + *updateResult->fPhysicalMemory.fInactive + slabReclaimable.Value (); } } void Read_ProcVMStat_ (Instruments::Memory::Info* updateResult) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Read_ProcVMStat_"); #endif auto ReadVMStatLine_ = [] (Optional<uint64_t>* result, const String & n, const Sequence<String>& line) { if (line.size () >= 2 and line[0] == n) { *result = Characters::String2Int<uint64_t> (line[1]); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } }; { static const String_Constant kProcVMStatFileName_ { L"/proc/vmstat" }; Optional<uint64_t> pgfault; Optional<uint64_t> pgpgout; // Note - /procfs files always unseekable DataExchange::CharacterDelimitedLines::Reader reader {{ ' ', '\t' }}; for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (kProcVMStatFileName_, FileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadVMStatLine_ (&pgfault, String_Constant (L"pgfault"), line); // Unsure if this should be pgpgout or pgpgout, or none of the above. On a system with no swap, I seem to get both happening, // which makes no sense ReadVMStatLine_ (&pgpgout, String_Constant (L"pgpgout"), line); // tried pgpgout but I dont know what it is but doesnt appear to be pages out - noneof this well documented ReadVMStatLine_ (&updateResult->fPaging.fMajorPageFaultsSinceBoot, String_Constant (L"pgmajfault"), line); } Time::DurationSecondsType now = Time::GetTickCount (); updateResult->fPaging.fPageOutsSinceBoot = pgpgout; if (pgfault and updateResult->fPaging.fMajorPageFaultsSinceBoot) { updateResult->fPaging.fMinorPageFaultsSinceBoot = *pgfault - *updateResult->fPaging.fMajorPageFaultsSinceBoot; } auto doAve_ = [] (Time::DurationSecondsType savedVMPageStatsAt, Time::DurationSecondsType now, uint64_t* savedBaseline, Optional<uint64_t> faultsSinceBoot, Optional<double>* faultsPerSecond) { if (faultsSinceBoot) { if (savedVMPageStatsAt != 0) { *faultsPerSecond = (*faultsSinceBoot - *savedBaseline) / (now - savedVMPageStatsAt); } *savedBaseline = *faultsSinceBoot; } }; doAve_ (fSaved_VMPageStats_At, now, &fSaved_MinorPageFaultsSinceBoot, updateResult->fPaging.fMinorPageFaultsSinceBoot, &updateResult->fPaging.fMinorPageFaultsPerSecond); doAve_ (fSaved_VMPageStats_At, now, &fSaved_MajorPageFaultsSinceBoot, updateResult->fPaging.fMajorPageFaultsSinceBoot, &updateResult->fPaging.fMajorPageFaultsPerSecond); doAve_ (fSaved_VMPageStats_At, now, &fSaved_PageOutsSinceBoot, updateResult->fPaging.fPageOutsSinceBoot, &updateResult->fPaging.fPageOutsPerSecond); fSaved_VMPageStats_At = now; } } }; } #endif #if qPlatform_Windows namespace { struct CapturerWithContext_Windows_ : CapturerWithContext_COMMON_ { #if qUseWMICollectionSupport_ WMICollector fMemoryWMICollector_ { String_Constant { L"Memory" }, {kInstanceName_}, {kCommittedBytes_, kCommitLimit_, kPagesPerSec_, kFreeMem_ } }; #endif CapturerWithContext_Windows_ (const Options& options) : CapturerWithContext_COMMON_ (options) { capture_ (); // to pre-seed context #if USE_NOISY_TRACE_IN_THIS_MODULE_ for (String i : fMemoryWMICollector_.GetAvailableCounters ()) { DbgTrace (L"Memory:Countername: %s", i.c_str ()); } #endif } CapturerWithContext_Windows_ (const CapturerWithContext_Windows_& from) : CapturerWithContext_COMMON_ (from) #if qUseWMICollectionSupport_ , fMemoryWMICollector_ (from.fMemoryWMICollector_) #endif { #if qUseWMICollectionSupport_ capture_ (); // to pre-seed context #endif } Instruments::Memory::Info capture_ () { Instruments::Memory::Info result; uint64_t totalRAM {}; Read_GlobalMemoryStatusEx_(&result, &totalRAM); #if qUseWMICollectionSupport_ Read_WMI_ (&result, totalRAM); #endif NoteCompletedCapture_ (); return result; } Instruments::Memory::Info capture () { Execution::SleepUntil (fPostponeCaptureUntil_); return capture_ (); } void Read_GlobalMemoryStatusEx_ (Instruments::Memory::Info* updateResult, uint64_t* totalRAM) { RequireNotNull (totalRAM); MEMORYSTATUSEX statex; memset (&statex, 0, sizeof (statex)); statex.dwLength = sizeof (statex); Verify (::GlobalMemoryStatusEx (&statex) != 0); //updateResult->fPhysicalMemory.fFree = statex.ullAvailPhys; *totalRAM = statex.ullTotalPhys; /* * dwMemoryLoad * A number between 0 and 100 that specifies the approximate percentage of physical * memory that is in use (0 indicates no memory use and 100 indicates full memory use) */ updateResult->fPhysicalMemory.fActive = statex.ullTotalPhys * statex.dwMemoryLoad / 100; } #if qUseWMICollectionSupport_ void Read_WMI_ (Instruments::Memory::Info* updateResult, uint64_t totalRAM) { fMemoryWMICollector_.Collect (); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kCommittedBytes_).CopyToIf (&updateResult->fVirtualMemory.fCommittedBytes); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kCommitLimit_).CopyToIf (&updateResult->fVirtualMemory.fCommitLimit); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kPagesPerSec_).CopyToIf (&updateResult->fPaging.fMajorPageFaultsPerSecond); fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kFreeMem_).CopyToIf (&updateResult->fPhysicalMemory.fFree); if (Optional<double> freeMem = fMemoryWMICollector_.PeekCurrentValue (kInstanceName_, kFreeMem_)) { if (updateResult->fPhysicalMemory.fActive) { // Active + Inactive + Free == TotalRAM updateResult->fPhysicalMemory.fInactive = totalRAM - *updateResult->fPhysicalMemory.fActive - static_cast<uint64_t> (*freeMem); } } // WAG TMPHACK - probably should add "hardware in use" memory + private WS of each process + shared memory "WS" - but not easy to compute... updateResult->fPhysicalMemory.fAvailable = updateResult->fPhysicalMemory.fFree + updateResult->fPhysicalMemory.fInactive; } #endif }; } #endif namespace { struct CapturerWithContext_ : Debug::AssertExternallySynchronizedLock #if qPlatform_AIX , CapturerWithContext_AIX_ #elif qPlatform_Linux , CapturerWithContext_Linux_ #elif qPlatform_Windows , CapturerWithContext_Windows_ #endif { #if qPlatform_AIX using inherited = CapturerWithContext_AIX_; #elif qPlatform_Linux using inherited = CapturerWithContext_Linux_; #elif qPlatform_Windows using inherited = CapturerWithContext_Windows_; #endif CapturerWithContext_ (Options options) : inherited (options) { } Instruments::Memory::Info capture () { lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Instruments::Memory::Info capture"); #endif return inherited::capture (); } }; } /* ******************************************************************************** ****************** Instruments::Memory::GetObjectVariantMapper ***************** ******************************************************************************** */ ObjectVariantMapper Instruments::Memory::GetObjectVariantMapper () { using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo; static const ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper { ObjectVariantMapper mapper; mapper.AddCommonType<Optional<uint64_t>> (); mapper.AddCommonType<Optional<double>> (); DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 mapper.AddClass<Info::PhysicalRAMDetailsType> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PhysicalRAMDetailsType, fAvailable), String_Constant (L"Available"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PhysicalRAMDetailsType, fActive), String_Constant (L"Active"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PhysicalRAMDetailsType, fInactive), String_Constant (L"Inactive"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PhysicalRAMDetailsType, fFree), String_Constant (L"Free"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PhysicalRAMDetailsType, fOSReserved), String_Constant (L"OS-Reserved"), StructureFieldInfo::NullFieldHandling::eOmit }, }); mapper.AddClass<Info::VirtualMemoryDetailsType> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::VirtualMemoryDetailsType, fCommitLimit), String_Constant (L"Commit-Limit"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::VirtualMemoryDetailsType, fCommittedBytes), String_Constant (L"Committed-Bytes"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::VirtualMemoryDetailsType, fPagefileTotalSize), String_Constant (L"Pagefile-Total-Size"), StructureFieldInfo::NullFieldHandling::eOmit }, }); mapper.AddClass<Info::PagingDetailsType> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fMajorPageFaultsSinceBoot), String_Constant (L"Major-Faults-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fMinorPageFaultsSinceBoot), String_Constant (L"Minor-Faults-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fPageOutsSinceBoot), String_Constant (L"Page-Outs-Since-Boot"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fMajorPageFaultsPerSecond), String_Constant (L"Major-Faults-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fMinorPageFaultsPerSecond), String_Constant (L"Minor-Faults-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::PagingDetailsType, fPageOutsPerSecond), String_Constant (L"Page-Outs-Per-Second"), StructureFieldInfo::NullFieldHandling::eOmit }, }); mapper.AddClass<Info> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fPhysicalMemory), String_Constant (L"Physical-Memory") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fVirtualMemory), String_Constant (L"Virtual-Memory") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fPaging), String_Constant (L"Paging") }, }); DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\""); DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\""); return mapper; } (); return sMapper_; } namespace { const MeasurementType kMemoryUsageMeasurement_ = MeasurementType (String_Constant (L"Memory-Usage")); } namespace { class MyCapturer_ : public Instrument::ICapturer { CapturerWithContext_ fCaptureContext; public: MyCapturer_ (const CapturerWithContext_& ctx) : fCaptureContext (ctx) { } virtual MeasurementSet Capture () { MeasurementSet results; results.fMeasurements.Add (Measurement { kMemoryUsageMeasurement_, GetObjectVariantMapper ().FromObject (Capture_Raw (&results.fMeasuredAt))}); return results; } nonvirtual Info Capture_Raw (Range<DurationSecondsType>* outMeasuredAt) { DurationSecondsType before = fCaptureContext.GetLastCaptureAt (); Info rawMeasurement = fCaptureContext.capture (); if (outMeasuredAt != nullptr) { *outMeasuredAt = Range<DurationSecondsType> (before, fCaptureContext.GetLastCaptureAt ()); } return rawMeasurement; } virtual unique_ptr<ICapturer> Clone () const override { #if qCompilerAndStdLib_make_unique_Buggy return unique_ptr<ICapturer> (new MyCapturer_ (fCaptureContext)); #else return make_unique<MyCapturer_> (fCaptureContext); #endif } }; } /* ******************************************************************************** ******************* Instruments::Memory::GetInstrument ************************* ******************************************************************************** */ Instrument SystemPerformance::Instruments::Memory::GetInstrument (Options options) { return Instrument ( InstrumentNameType { String_Constant (L"Memory") }, #if qCompilerAndStdLib_make_unique_Buggy Instrument::SharedByValueCaptureRepType (unique_ptr<MyCapturer_> (new MyCapturer_ (CapturerWithContext_ { options }))), #else Instrument::SharedByValueCaptureRepType (make_unique<MyCapturer_> (CapturerWithContext_ { options })), #endif { kMemoryUsageMeasurement_ }, GetObjectVariantMapper () ); } /* ******************************************************************************** ********* SystemPerformance::Instrument::CaptureOneMeasurement ***************** ******************************************************************************** */ template <> Instruments::Memory::Info SystemPerformance::Instrument::CaptureOneMeasurement (Range<DurationSecondsType>* measurementTimeOut) { MyCapturer_* myCap = dynamic_cast<MyCapturer_*> (fCapFun_.get ()); AssertNotNull (myCap); return myCap->Capture_Raw (measurementTimeOut); }
#pragma once #include <array> #include <tuple> #include <utility> namespace cu { /// Returns the size of a tuple as compile-time constant. template <typename ...Ts> constexpr std::size_t get_tuple_size( const std::tuple<Ts...> & ) { return sizeof...(Ts); } template <typename Tuple> constexpr auto make_index_sequence( const Tuple & t ) { return std::make_index_sequence<get_tuple_size(t)>(); } namespace detail { template <typename Tuple, typename F, std::size_t ...indexes> void for_each_impl( Tuple && tuple, F && f, std::index_sequence<indexes...> ) { const auto _ = {(static_cast<void>(std::forward<F>(f)( std::get<indexes>(std::forward<Tuple>(tuple)) ) ),1)...}; static_cast<void>(_); } template <typename Tuple1, typename Tuple2, typename F, std::size_t ...indexes> void for_each_impl( Tuple1 && tuple1, Tuple2 && tuple2, F && f, std::index_sequence<indexes...> ) { const auto _ = { (static_cast<void>( std::forward<F>(f)( std::get<indexes>(std::forward<Tuple1>(tuple1)), std::get<indexes>(std::forward<Tuple2>(tuple2)) ) ),1)... }; static_cast<void>(_); } } // namespace detail /// Applies a functor to each element of a tuple. /// /// The types of the elements can differ and it still works. template <typename Tuple, typename F> void for_each( Tuple && tuple, F && f ) { detail::for_each_impl( std::forward<Tuple>(tuple), std::forward<F>(f), make_index_sequence(tuple) ); } /// Applies a functor to the elements of two tuples. /// /// In effect, the following is called: /// @code /// f( get< 0 >(std::forward<Tuple1>(tuple1)), /// get< 0 >(std::forward<Tuple2>(tuple2)) ); /// . /// . /// . /// f( get<N-1>(std::forward<Tuple1>(tuple1)), /// get<N-1>(std::forward<Tuple2>(tuple2)) ); /// @endcode /// where @c N ist the size of both tuples. Note also, that proper forwarding /// is applied to the elements of the tuples. template <typename Tuple1, typename Tuple2, typename F> void for_each( Tuple1 && tuple1, Tuple2 && tuple2, F && f ) { static_assert( get_tuple_size(tuple1) == get_tuple_size(tuple2), "Tuples must have the same length." ); detail::for_each_impl( std::forward<Tuple1>(tuple1), std::forward<Tuple2>(tuple2), std::forward<F>(f), make_index_sequence(tuple1) ); } namespace detail { template <typename Tuple, typename F, std::size_t ...indexes> decltype(auto) transform_impl( Tuple && tuple, F && f, std::index_sequence<indexes...> ) { return std::make_tuple( f( std::get<indexes>( std::forward<Tuple>(tuple) ) )... ); } } // namespace detail /// A functor is applied to every element of a tuple and the returned values /// are returned in a tuple. template <typename Tuple, typename F> decltype(auto) transform( Tuple && tuple, F && f ) { return detail::transform_impl( std::forward<Tuple>(tuple), std::forward<F>(f), make_index_sequence(tuple) ); } namespace detail { template <typename T, typename Tuple, std::size_t ...indexes> auto to_array_impl( Tuple && tuple, std::index_sequence<indexes...> ) { return std::array<T,get_tuple_size(tuple)>{ std::get<indexes>( std::forward<Tuple>(tuple))... }; } } /// Turns a tuple into an array. /// /// The element type is not inferred, but must be specified. template <typename T, typename Tuple> auto to_array( Tuple && tuple ) { return detail::to_array_impl<T>( std::forward<Tuple>(tuple), make_index_sequence(tuple) ); } namespace detail { template <typename F> struct ReverseAccumulator { ReverseAccumulator( F && f_ ) : f(std::forward<F>(f_)) {} template <typename ...Ts, typename T> decltype(auto) operator()( T && arg, Ts &&...args ) const { return f( std::move(*this)( std::forward<Ts>(args)... ), std::forward<T>(arg) ); } template <typename T> T && operator()( T && arg ) const { return std::forward<T>(arg); } private: F && f; }; template <typename Tuple, typename F, std::size_t ...indexes> decltype(auto) accumulate_impl( Tuple && tuple, F && f, std::index_sequence<indexes...> ) { // The reverse accumulator is used for left to right associativity. // It must be reverse because elements of an argument pack must be // removed from the front while inferring parameters. In other words, // a template of the form // @code // template <typename ...Ts, typename T> // void f( Ts &&...args, T && arg ); // @endcode // is ill-formed code, while // @code // template <typename ...Ts, typename T> // void f( T && arg, Ts &&...args ); // @endcode // is perfectly valid. return ReverseAccumulator<F>(std::forward<F>(f))( std::get<get_tuple_size(tuple)-indexes-1>(std::forward<Tuple>(tuple))... ); } } // namespace detail /// Accumulates the elements of a tuple given a specific functor. /// /// If the elements of the tuple shall be added together, then the functor /// parameter should be something like this: /// @code /// []( auto && rhs, auto && lhs ) { return rhs + lhs; } /// @endcode /// Note that the operation will be performed left to right associative /// independent of the type of functor used. template <typename Tuple, typename F> decltype(auto) accumulate( Tuple && tuple, F && f ) { return detail::accumulate_impl( std::forward<Tuple>(tuple), std::forward<F>(f), make_index_sequence(tuple) ); } namespace detail { template <typename Tuple, typename F, std::size_t ... indexes> bool any_of_impl( Tuple && tuple, F && f, std::index_sequence<indexes...> ) { const std::array<bool,sizeof...(indexes)> values = { f( std::get<indexes>(tuple) )... }; for ( bool value : values ) if ( value ) return true; return false; } } // namespace detail /// Returns @c true, iff any of the @c tuple elements evaluates to @true. template <typename Tuple, typename F> bool any_of( Tuple && tuple, F && f ) { return detail::any_of_impl( std::forward<Tuple>(tuple), std::forward<F>(f), make_index_sequence(tuple) ); } /// This is a helper class which enables the prioritization of overloads. /// /// If there are two overloads of a function that only differ in one argument /// type, which are @c Rank<N> and @c Rang<M>, and the function is called /// given an argument of type @c Rank<K> where @c K>=N and @K>=M, then /// the overload with the larger @c Rank number will be selected by the /// compiler. /// /// This is helpful, when an overload shall be prioritized over another and /// the prioritized overload may be excluded from overload resolution because /// of SFINAE (Substitution Failure Is Not An Error). template <std::size_t N> class Rank; template <> class Rank<0> {}; template <std::size_t N> class Rank : public Rank<N-1> {}; } // namespace cu Added the macro CU_FWD(). #pragma once #include <array> #include <tuple> #include <utility> #define CU_FWD(arg) ::std::forward<decltype(arg)>(arg) namespace cu { /// Returns the size of a tuple as compile-time constant. template <typename ...Ts> constexpr std::size_t get_tuple_size( const std::tuple<Ts...> & ) { return sizeof...(Ts); } template <typename Tuple> constexpr auto make_index_sequence( const Tuple & t ) { return std::make_index_sequence<get_tuple_size(t)>(); } namespace detail { template <typename Tuple, typename F, std::size_t ...indexes> void for_each_impl( Tuple && tuple, F && f, std::index_sequence<indexes...> ) { const auto _ = {(static_cast<void>(std::forward<F>(f)( std::get<indexes>(std::forward<Tuple>(tuple)) ) ),1)...}; static_cast<void>(_); } template <typename Tuple1, typename Tuple2, typename F, std::size_t ...indexes> void for_each_impl( Tuple1 && tuple1, Tuple2 && tuple2, F && f, std::index_sequence<indexes...> ) { const auto _ = { (static_cast<void>( std::forward<F>(f)( std::get<indexes>(std::forward<Tuple1>(tuple1)), std::get<indexes>(std::forward<Tuple2>(tuple2)) ) ),1)... }; static_cast<void>(_); } } // namespace detail /// Applies a functor to each element of a tuple. /// /// The types of the elements can differ and it still works. template <typename Tuple, typename F> void for_each( Tuple && tuple, F && f ) { detail::for_each_impl( std::forward<Tuple>(tuple), std::forward<F>(f), make_index_sequence(tuple) ); } /// Applies a functor to the elements of two tuples. /// /// In effect, the following is called: /// @code /// f( get< 0 >(std::forward<Tuple1>(tuple1)), /// get< 0 >(std::forward<Tuple2>(tuple2)) ); /// . /// . /// . /// f( get<N-1>(std::forward<Tuple1>(tuple1)), /// get<N-1>(std::forward<Tuple2>(tuple2)) ); /// @endcode /// where @c N ist the size of both tuples. Note also, that proper forwarding /// is applied to the elements of the tuples. template <typename Tuple1, typename Tuple2, typename F> void for_each( Tuple1 && tuple1, Tuple2 && tuple2, F && f ) { static_assert( get_tuple_size(tuple1) == get_tuple_size(tuple2), "Tuples must have the same length." ); detail::for_each_impl( std::forward<Tuple1>(tuple1), std::forward<Tuple2>(tuple2), std::forward<F>(f), make_index_sequence(tuple1) ); } namespace detail { template <typename Tuple, typename F, std::size_t ...indexes> decltype(auto) transform_impl( Tuple && tuple, F && f, std::index_sequence<indexes...> ) { return std::make_tuple( f( std::get<indexes>( std::forward<Tuple>(tuple) ) )... ); } } // namespace detail /// A functor is applied to every element of a tuple and the returned values /// are returned in a tuple. template <typename Tuple, typename F> decltype(auto) transform( Tuple && tuple, F && f ) { return detail::transform_impl( std::forward<Tuple>(tuple), std::forward<F>(f), make_index_sequence(tuple) ); } namespace detail { template <typename T, typename Tuple, std::size_t ...indexes> auto to_array_impl( Tuple && tuple, std::index_sequence<indexes...> ) { return std::array<T,get_tuple_size(tuple)>{ std::get<indexes>( std::forward<Tuple>(tuple))... }; } } /// Turns a tuple into an array. /// /// The element type is not inferred, but must be specified. template <typename T, typename Tuple> auto to_array( Tuple && tuple ) { return detail::to_array_impl<T>( std::forward<Tuple>(tuple), make_index_sequence(tuple) ); } namespace detail { template <typename F> struct ReverseAccumulator { ReverseAccumulator( F && f_ ) : f(std::forward<F>(f_)) {} template <typename ...Ts, typename T> decltype(auto) operator()( T && arg, Ts &&...args ) const { return f( std::move(*this)( std::forward<Ts>(args)... ), std::forward<T>(arg) ); } template <typename T> T && operator()( T && arg ) const { return std::forward<T>(arg); } private: F && f; }; template <typename Tuple, typename F, std::size_t ...indexes> decltype(auto) accumulate_impl( Tuple && tuple, F && f, std::index_sequence<indexes...> ) { // The reverse accumulator is used for left to right associativity. // It must be reverse because elements of an argument pack must be // removed from the front while inferring parameters. In other words, // a template of the form // @code // template <typename ...Ts, typename T> // void f( Ts &&...args, T && arg ); // @endcode // is ill-formed code, while // @code // template <typename ...Ts, typename T> // void f( T && arg, Ts &&...args ); // @endcode // is perfectly valid. return ReverseAccumulator<F>(std::forward<F>(f))( std::get<get_tuple_size(tuple)-indexes-1>(std::forward<Tuple>(tuple))... ); } } // namespace detail /// Accumulates the elements of a tuple given a specific functor. /// /// If the elements of the tuple shall be added together, then the functor /// parameter should be something like this: /// @code /// []( auto && rhs, auto && lhs ) { return rhs + lhs; } /// @endcode /// Note that the operation will be performed left to right associative /// independent of the type of functor used. template <typename Tuple, typename F> decltype(auto) accumulate( Tuple && tuple, F && f ) { return detail::accumulate_impl( std::forward<Tuple>(tuple), std::forward<F>(f), make_index_sequence(tuple) ); } namespace detail { template <typename Tuple, typename F, std::size_t ... indexes> bool any_of_impl( Tuple && tuple, F && f, std::index_sequence<indexes...> ) { const std::array<bool,sizeof...(indexes)> values = { f( std::get<indexes>(tuple) )... }; for ( bool value : values ) if ( value ) return true; return false; } } // namespace detail /// Returns @c true, iff any of the @c tuple elements evaluates to @true. template <typename Tuple, typename F> bool any_of( Tuple && tuple, F && f ) { return detail::any_of_impl( std::forward<Tuple>(tuple), std::forward<F>(f), make_index_sequence(tuple) ); } /// This is a helper class which enables the prioritization of overloads. /// /// If there are two overloads of a function that only differ in one argument /// type, which are @c Rank<N> and @c Rang<M>, and the function is called /// given an argument of type @c Rank<K> where @c K>=N and @K>=M, then /// the overload with the larger @c Rank number will be selected by the /// compiler. /// /// This is helpful, when an overload shall be prioritized over another and /// the prioritized overload may be excluded from overload resolution because /// of SFINAE (Substitution Failure Is Not An Error). template <std::size_t N> class Rank; template <> class Rank<0> {}; template <std::size_t N> class Rank : public Rank<N-1> {}; } // namespace cu
// // ScriptingCore.cpp // MyTest // // Created by Lei.zhang on 16/1/19. // Copyright © 2016 Lei.zhang All rights reserved. // #include "ScriptingCore.h" // Removed in Firefox v27, use 'js/OldDebugAPI.h' instead #include "js/OldDebugAPI.h" // for debug socket #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) #include <io.h> #include <WS2tcpip.h> #else #include <sys/socket.h> #include <unistd.h> #include <netdb.h> #endif #include <thread> #include <iostream> #include <sstream> #include <stdio.h> #include <mutex> #include "crossapp_specifics.hpp" #ifdef ANDROID #define LOG_TAG "ScriptingCore.cpp" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #else #define LOGD(...) js_log(__VA_ARGS__) #endif #if CrossApp_DEBUG #define TRACE_DEBUGGER_SERVER(...) CCLOG(__VA_ARGS__) #else #define TRACE_DEBUGGER_SERVER(...) #endif // #if DEBUG #define BYTE_CODE_FILE_EXT ".jsc" static std::string inData; static std::string outData; static std::vector<std::string> g_queue; static std::mutex g_qMutex; static std::mutex g_rwMutex; static int clientSocket = -1; static uint32_t s_nestedLoopLevel = 0; js_proxy_t *_native_js_global_ht = NULL; js_proxy_t *_js_native_global_ht = NULL; std::unordered_map<std::string, js_type_class_t*> _js_global_type_map; static std::unordered_map<void*, js_proxy_t*> _native_js_global_map; static std::unordered_map<JSObject*, js_proxy_t*> _js_native_global_map; static std::unordered_map<JSObject*, JSObject*> _js_hook_owner_map; static char *_js_log_buf = NULL; static std::vector<sc_register_sth> registrationList; // name ~> JSScript map static std::unordered_map<std::string, JSScript*> filename_script; /* static void cc_closesocket(int fd) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) closesocket(fd); #else close(fd); #endif } */ static ScriptingCore* instance = nullptr; typedef void (*sc_register_sth)(JSContext* cx, JS::HandleObject global); /// The max length of CCLog message. static const int MAX_LOG_LENGTH = 16*1024; void js_log(const char *format, ...) { if (_js_log_buf == NULL) { _js_log_buf = (char *)calloc(sizeof(char), MAX_LOG_LENGTH+1); _js_log_buf[MAX_LOG_LENGTH] = '\0'; } va_list vl; va_start(vl, format); int len = vsnprintf(_js_log_buf, MAX_LOG_LENGTH, format, vl); va_end(vl); if (len > 0) { CCLog("JS: %s", _js_log_buf); } } static void sc_finalize(JSFreeOp *freeOp, JSObject *obj) { // CCLOGINFO("jsbindings: finalizing JS object %p (global class)", obj); } static void ReportException(JSContext *cx) { if (JS_IsExceptionPending(cx)) { if (!JS_ReportPendingException(cx)) { JS_ClearPendingException(cx); } } } static const JSClass global_class = { "global", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, sc_finalize, nullptr, nullptr, nullptr, JS_GlobalObjectTraceHook }; // Just a wrapper around JSPrincipals that allows static construction. class CCJSPrincipals : public JSPrincipals { public: explicit CCJSPrincipals(int rc = 0) : JSPrincipals() { refcount = rc; } }; static CCJSPrincipals shellTrustedPrincipals(1); ScriptingCore::ScriptingCore() :_rt(nullptr) ,_cx(nullptr) ,_jsInited(false) ,_needCleanup(false) ,_global(nullptr) ,_debugGlobal(nullptr) ,_callFromScript(false) { initRegister(); } void ScriptingCore::initRegister(){ this->addRegisterCallback(registerDefaultClasses); this->_runLoop = new (std::nothrow) SimpleRunLoop(); } void ScriptingCore::restartVM() { cleanup(); initRegister(); CCApplication::sharedApplication()->applicationDidFinishLaunching(); } ScriptingCore::~ScriptingCore() { cleanup(); } bool JSBCore_platform(JSContext *cx, uint32_t argc, jsval *vp) { if (argc!=0) { JS_ReportError(cx, "Invalid number of arguments in __getPlatform"); return false; } JS::CallArgs args = JS::CallArgsFromVp(argc, vp); TargetPlatform platform; // config.deviceType: Device Type // 'mobile' for any kind of mobile devices, 'desktop' for PCs, 'browser' for Web Browsers // #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) // platform = JS_InternString(_cx, "desktop"); // #else platform = CCApplication::sharedApplication()->getTargetPlatform(); // #endif args.rval().set(INT_TO_JSVAL((int)platform)); return true; }; bool JSBCore_os(JSContext *cx, uint32_t argc, jsval *vp) { if (argc!=0) { JS_ReportError(cx, "Invalid number of arguments in __getOS"); return false; } JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JSString * os; // osx, ios, android, windows, linux, etc.. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) os = JS_InternString(cx, "iOS"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) os = JS_InternString(cx, "Android"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) os = JS_InternString(cx, "Windows"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE) os = JS_InternString(cx, "Marmalade"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) os = JS_InternString(cx, "Linux"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_BADA) os = JS_InternString(cx, "Bada"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) os = JS_InternString(cx, "Blackberry"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) os = JS_InternString(cx, "OS X"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) os = JS_InternString(cx, "WINRT"); #else os = JS_InternString(cx, "Unknown"); #endif args.rval().set(STRING_TO_JSVAL(os)); return true; }; bool JSBCore_version(JSContext *cx, uint32_t argc, jsval *vp) { if (argc!=0) { JS_ReportError(cx, "Invalid number of arguments in __getVersion"); return false; } JS::CallArgs args = JS::CallArgsFromVp(argc, vp); char version[256]; snprintf(version, sizeof(version)-1, "%s", CrossAppVersion()); JSString * js_version = JS_InternString(cx, version); args.rval().set(STRING_TO_JSVAL(js_version)); return true; }; bool JSB_core_restartVM(JSContext *cx, uint32_t argc, jsval *vp) { JSB_PRECONDITION2(argc==0, cx, false, "Invalid number of arguments in executeScript"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); ScriptingCore::getInstance()->reset(); args.rval().setUndefined(); return true; }; bool JSB_cleanScript(JSContext *cx, uint32_t argc, jsval *vp) { if (argc != 1) { JS_ReportError(cx, "Invalid number of arguments in JSB_cleanScript"); return false; } JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JSString *jsPath = args.get(0).toString(); JSB_PRECONDITION2(jsPath, cx, false, "Error js file in clean script"); JSStringWrapper wrapper(jsPath); ScriptingCore::getInstance()->cleanScript(wrapper.get()); args.rval().setUndefined(); return true; }; void registerDefaultClasses(JSContext* cx, JS::HandleObject global) { // first, try to get the ns JS::RootedValue nsval(cx); JS::RootedObject ns(cx); JS_GetProperty(cx, global, "ca", &nsval); // Not exist, create it if (nsval == JSVAL_VOID) { ns.set(JS_NewObject(cx, NULL, JS::NullPtr(), JS::NullPtr())); nsval = OBJECT_TO_JSVAL(ns); JS_SetProperty(cx, global, "ca", nsval); } else { ns.set(nsval.toObjectOrNull()); } // // Javascript controller (__jsc__) // JS::RootedObject proto(cx); JS::RootedObject parent(cx); JS::RootedObject jsc(cx, JS_NewObject(cx, NULL, proto, parent)); JS::RootedValue jscVal(cx); jscVal = OBJECT_TO_JSVAL(jsc); JS_SetProperty(cx, global, "__jsc__", jscVal); //在引擎中注册基础函数,实现这些就可以同javascript调用这些函数进行测试了 JS_DefineFunction(cx, jsc, "garbageCollect", ScriptingCore::forceGC, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, jsc, "dumpRoot", ScriptingCore::dumpRoot, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, jsc, "addGCRootObject", ScriptingCore::addRootJS, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, jsc, "removeGCRootObject", ScriptingCore::removeRootJS, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, jsc, "executeScript", ScriptingCore::executeScript, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); // register some global functions JS_DefineFunction(cx, global, "require", ScriptingCore::executeScript, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "log", ScriptingCore::log, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "executeScript", ScriptingCore::executeScript, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "forceGC", ScriptingCore::forceGC, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__getPlatform", JSBCore_platform, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__getOS", JSBCore_os, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__getVersion", JSBCore_version, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__restartVM", JSB_core_restartVM, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, global, "__cleanScript", JSB_cleanScript, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__isObjectValid", ScriptingCore::isObjectValid, 1, JSPROP_READONLY | JSPROP_PERMANENT); } ScriptingCore* ScriptingCore::getInstance() { if (!instance) { instance = new ScriptingCore(); } return instance; } void ScriptingCore::releaseThis() { instance = nullptr; CCScriptEngineManager::getScriptEngineManager()->setScriptEngine(nullptr); delete this; } void ScriptingCore::addRegisterCallback(sc_register_sth callback) { registrationList.push_back(callback); } static bool CheckObjectAccess(JSContext *cx) { return true; } static JSSecurityCallbacks securityCallbacks = { CheckObjectAccess, NULL }; void ScriptingCore::createGlobalContext() { // if (_cx && _rt) // { // ScriptingCore::removeAllRoots(_cx); // JS_DestroyContext(_cx); // JS_DestroyRuntime(_rt); // _cx = nullptr; // _rt = nullptr; // } if (!_jsInited && !JS_Init()) { return; } else { _jsInited = true; } _rt = JS_NewRuntime(8L * 1024L * 1024L); JS_SetGCParameter(_rt, JSGC_MAX_BYTES, 0xffffffff); JS_SetTrustedPrincipals(_rt, &shellTrustedPrincipals); JS_SetSecurityCallbacks(_rt, &securityCallbacks); JS_SetNativeStackQuota(_rt, JSB_MAX_STACK_QUOTA); _cx = JS_NewContext(_rt, 8192); JS::RuntimeOptionsRef(_rt).setIon(true); JS::RuntimeOptionsRef(_rt).setBaseline(true); JS_SetErrorReporter(_cx, ScriptingCore::reportError); _global = new (std::nothrow) JS::PersistentRootedObject(_rt, NewGlobalObject(_cx)); JS::RootedObject global(_cx, _global->get()); // Removed in Firefox v34 js::SetDefaultObjectForContext(_cx, global); JSAutoCompartment ac(_cx, _global->get()); runScript("script/jsb_prepare.js"); for (std::vector<sc_register_sth>::iterator it = registrationList.begin(); it != registrationList.end(); it++) { sc_register_sth callback = *it; callback(_cx, *_global); } _needCleanup = true; } bool ScriptingCore::evalString(const char *string,JS::RootedValue *outVal, const char *filename, JSContext *cx, JSObject* global ) { if (cx == NULL) { cx = _cx; } if (global == NULL) { global = _global->get(); } JSAutoCompartment ac(cx,global); JS::RootedObject cc(cx, global); JS::RootedValue rval(cx); bool ok = JS_EvaluateScript(cx, cc, string, strlen(string), "ScriptingCore::evalString", 1,&rval); /* if (ok) { JSString *str = rval.toString(); printf("javascript:-->%s",JS_EncodeString(cx, str)); } */ return ok; } static std::string RemoveFileExt(const std::string& filePath) { size_t pos = filePath.rfind('.'); if (0 < pos) { return filePath.substr(0, pos); } else { return filePath; } } JSScript* ScriptingCore::getScript(const char *path){ // a) check jsc file first std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT; if (filename_script.find(byteCodePath) != filename_script.end()) return filename_script[byteCodePath]; // b) no jsc file, check js file std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); if (filename_script.find(fullPath) != filename_script.end()) return filename_script[fullPath]; return NULL; } void ScriptingCore::compileScript(const char *path, JSObject* global, JSContext* cx ){ if (!path) { return; } if (getScript(path)) { return; } FileUtils * futil = FileUtils::getInstance(); if (global == NULL) { global = *_global; } if (cx == NULL) { cx = _cx; } JSAutoCompartment ac(cx,global); JS::RootedScript script(cx); JS::RootedObject obj(cx,global); // a) check jsc file first std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT ; // Check whether '.jsc' files exist to avoid outputing log which says 'couldn't find .jsc file'. if (futil->isFileExist(byteCodePath)) { unsigned long size = 0; unsigned char* data = futil->getFileData(byteCodePath.c_str(), "rb", &size); if (size > 0) { script = JS_DecodeScript(cx, data, static_cast<uint32_t>(size), nullptr); } } // b) no jsc file, check js file if (!script) { /* Clear any pending exception from previous failed decoding. */ ReportException(cx); std::string fullPath = futil->fullPathForFilename(path); JS::CompileOptions op(cx); op.setUTF8(true); op.setFileAndLine(fullPath.c_str(), 1); bool ok = false; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) std::string jsFileContent = futil->getFileString(fullPath); if (!jsFileContent.empty()) { ok = JS::Compile(cx, obj, op, jsFileContent.c_str(), jsFileContent.size(), &script); } #else ok = JS::Compile(cx, obj, op, fullPath.c_str(), &script); #endif if (ok) { filename_script[fullPath] = script; } } else { filename_script[byteCodePath] = script; } } bool ScriptingCore::runScript(const char *path){ return runScript(path, *_global, _cx); } bool ScriptingCore::runScript(const char *path, JS::HandleObject global, JSContext* cx) { if (cx == NULL) { cx = _cx; } compileScript(path,global,cx); JS::RootedScript script(cx,getScript(path)); bool evaluatedOK = false; if (script) { JS::RootedValue rval(cx); JSAutoCompartment ac(cx, global); evaluatedOK = JS_ExecuteScript(cx, global, script, &rval); if (false == evaluatedOK) { CCLog("Evaluating %s failed (evaluatedOK == JS_FALSE)", path); JS_ReportPendingException(cx); } // else // { // JSString *str = rval.toString(); // printf("Runscript:-->%s",JS_EncodeString(cx, str)); // } } return evaluatedOK; } bool ScriptingCore::requireScript(const char *path, JS::MutableHandleValue jsvalRet) { return requireScript(path, *_global, _cx, jsvalRet); } bool ScriptingCore::requireScript(const char *path, JS::HandleObject global, JSContext* cx, JS::MutableHandleValue jsvalRet) { if(cx == NULL) { cx = _cx; } compileScript(path,global,cx); JS::RootedScript script(cx,getScript(path)); bool evaluateOK = false; if (script) { JSAutoCompartment ac(cx,global); evaluateOK = JS_ExecuteScript(cx, global, script, jsvalRet); if (false == evaluateOK) { CCLog("(evaluatedOK == JS_FALSE)"); JS_ReportPendingException(cx); } } return evaluateOK; } void ScriptingCore::cleanScript(const char *path) { std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT ; auto it = filename_script.find(byteCodePath); if (it != filename_script.end()) { filename_script.erase(it); } std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); it = filename_script.find(fullPath); if (it != filename_script.end()) { filename_script.erase(it); } } std::unordered_map<std::string, JSScript*> &ScriptingCore::getFileScript() { return filename_script; } void ScriptingCore::cleanAllScript() { filename_script.clear(); } void ScriptingCore::start() { // for now just this createGlobalContext(); } void ScriptingCore::cleanup() { if (!_needCleanup) { return; } localStorageFree(); removeAllRoots(_cx); garbageCollect(); if (_cx) { JS_DestroyContext(_cx); _cx = nullptr; } if (_rt) { JS_DestroyRuntime(_rt); _rt = nullptr; } CC_SAFE_DELETE(_global); CC_SAFE_DELETE(_debugGlobal); _global = nullptr; _debugGlobal = nullptr; if (_js_log_buf) { free(_js_log_buf); _js_log_buf = NULL; } for (auto iter = _js_global_type_map.begin(); iter != _js_global_type_map.end(); ++iter) { free(iter->second->jsclass); free(iter->second); } _js_global_type_map.clear(); filename_script.clear(); registrationList.clear(); _needCleanup = false; } void ScriptingCore::reset() { CAApplication::getApplication()->restart(); } void ScriptingCore::reportError(JSContext *cx, const char *message, JSErrorReport *report) { js_log("%s:%u:%s\n", report->filename ? report->filename : "<no filename=\"filename\">", (unsigned int) report->lineno, message); }; void removeJSObject(JSContext* cx, void* nativeObj) { js_proxy_t* nproxy; js_proxy_t* jsproxy; nproxy = jsb_get_native_proxy(nativeObj); if (nproxy) { jsproxy = jsb_get_js_proxy(nproxy->obj); RemoveObjectRoot(cx, &jsproxy->obj); jsb_remove_proxy(nproxy, jsproxy); } } bool ScriptingCore::log(JSContext* cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (argc > 0) { JSString *string = JS::ToString(cx, args.get(0)); if (string) { JSStringWrapper wrapper(string); js_log("%s", wrapper.get()); } } args.rval().setUndefined(); return true; } void ScriptingCore::removeScriptObjectByObject(CAObject* pObj) { js_proxy_t* nproxy; js_proxy_t* jsproxy; void *ptr = (void*)pObj; nproxy = jsb_get_native_proxy(ptr); if (nproxy) { JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); jsproxy = jsb_get_js_proxy(nproxy->obj); RemoveObjectRoot(cx, &jsproxy->obj); jsb_remove_proxy(nproxy, jsproxy); } } bool ScriptingCore::setReservedSpot(uint32_t i, JSObject *obj, jsval value) { JS_SetReservedSlot(obj, i, value); return true; } bool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (argc >= 1) { JSString* str = JS::ToString(cx, JS::RootedValue(cx, args.get(0))); JSStringWrapper path(str); bool res = false; if (argc == 2 && args.get(1).isString()) { JSString* globalName = args.get(1).toString(); JSStringWrapper name(globalName); JS::RootedObject debugObj(cx, ScriptingCore::getInstance()->getDebugGlobal()); if (debugObj) { res = ScriptingCore::getInstance()->runScript(path.get(), debugObj); } else { JS_ReportError(cx, "Invalid global object: %s", name.get()); return false; } } else { JS::RootedObject glob(cx, JS::CurrentGlobalOrNull(cx)); res = ScriptingCore::getInstance()->runScript(path.get(), glob); } return res; } args.rval().setUndefined(); return true; } bool ScriptingCore::forceGC(JSContext *cx, uint32_t argc, jsval *vp) { JSRuntime *rt = JS_GetRuntime(cx); JS_GC(rt); return true; } bool ScriptingCore::dumpRoot(JSContext *cx, uint32_t argc, jsval *vp) { // JS_DumpNamedRoots is only available on DEBUG versions of SpiderMonkey. // Mac and Simulator versions were compiled with DEBUG. #if CrossApp_DEBUG // JSContext *_cx = ScriptingCore::getInstance()->getGlobalContext(); // JSRuntime *rt = JS_GetRuntime(_cx); // JS_DumpNamedRoots(rt, dumpNamedRoot, NULL); // JS_DumpHeap(rt, stdout, NULL, JSTRACE_OBJECT, NULL, 2, NULL); #endif return true; } bool ScriptingCore::addRootJS(JSContext *cx, uint32_t argc, jsval *vp) { if (argc == 1) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Heap<JSObject*> o(args.get(0).toObjectOrNull()); if (AddNamedObjectRoot(cx, &o, "from-js") == false) { LOGD("something went wrong when setting an object to the root"); } return true; } return false; } bool ScriptingCore::removeRootJS(JSContext *cx, uint32_t argc, jsval *vp) { if (argc == 1) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Heap<JSObject*> o(args.get(0).toObjectOrNull()); if (o != nullptr) { RemoveObjectRoot(cx, &o); } return true; } return false; } // ** int ScriptingCore::sendEvent(ScriptEvent* evt) { if (NULL == evt) return 0; // special type, can't use this code after JSAutoCompartment if (evt->type == kRestartGame) { restartVM(); return 0; } JSAutoCompartment ac(_cx, _global->get()); switch (evt->type) { case kNodeEvent: { return handleNodeEvent(evt->data); } break; case kScriptActionEvent: { // return handleActionEvent(evt->data); ** } break; case kMenuClickedEvent: break; case kTouchEvent: { // TouchScriptData* data = (TouchScriptData*)evt->data; // return handleTouchEvent(data->nativeObject, data->actionType, data->touch, data->event); ** } break; case kTouchesEvent: { // TouchesScriptData* data = (TouchesScriptData*)evt->data; //** // return handleTouchesEvent(data->nativeObject, data->actionType, data->touches, data->event); ** } break; case kComponentEvent: { // return handleComponentEvent(evt->data); ** } break; case kViewControllerEvent: { return handleViewControllerEvent(evt->data); } break; default: CCAssert(false, "Invalid script event."); break; } return 0; } bool ScriptingCore::isObjectValid(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (argc == 1) { JS::RootedObject tmpObj(cx, args.get(0).toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(tmpObj); if (proxy && proxy->ptr) { args.rval().set(JSVAL_TRUE); } else { args.rval().set(JSVAL_FALSE); } return true; } else { JS_ReportError(cx, "Invalid number of arguments: %d. Expecting: 1", argc); return false; } } void ScriptingCore::debugProcessInput(const std::string& str) { JSAutoCompartment ac(_cx, *_debugGlobal); JSString* jsstr = JS_NewStringCopyZ(_cx, str.c_str()); jsval argv = STRING_TO_JSVAL(jsstr); JS::RootedValue outval(_cx); JS_CallFunctionName(_cx, JS::RootedObject(_cx, *_debugGlobal), "processInput", JS::HandleValueArray::fromMarkedLocation(1, &argv), &outval); } //#pragma mark - Debugger /* static void _clientSocketWriteAndClearString(std::string& s) { ::send(clientSocket, s.c_str(), s.length(), 0); s.clear(); } */ bool JSBDebug_BufferWrite(JSContext* cx, unsigned argc, jsval* vp) { if (argc == 1) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JSStringWrapper strWrapper(args.get(0)); // this is safe because we're already inside a lock (from clearBuffers) outData.append(strWrapper.get()); //_clientSocketWriteAndClearString(outData); } return true; } static bool NS_ProcessNextEvent() { g_qMutex.lock(); size_t size = g_queue.size(); g_qMutex.unlock(); while (size > 0) { g_qMutex.lock(); auto first = g_queue.begin(); std::string str = *first; g_queue.erase(first); size = g_queue.size(); g_qMutex.unlock(); ScriptingCore::getInstance()->debugProcessInput(str); } // std::this_thread::yield(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); return true; } bool JSBDebug_enterNestedEventLoop(JSContext* cx, unsigned argc, jsval* vp) { enum { NS_OK = 0, NS_ERROR_UNEXPECTED }; #define NS_SUCCEEDED(v) ((v) == NS_OK) int rv = NS_OK; uint32_t nestLevel = ++s_nestedLoopLevel; while (NS_SUCCEEDED(rv) && s_nestedLoopLevel >= nestLevel) { if (!NS_ProcessNextEvent()) rv = NS_ERROR_UNEXPECTED; } CCAssert(s_nestedLoopLevel <= nestLevel, "nested event didn't unwind properly"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); args.rval().set(UINT_TO_JSVAL(s_nestedLoopLevel)); // JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(s_nestedLoopLevel)); return true; } bool JSBDebug_exitNestedEventLoop(JSContext* cx, unsigned argc, jsval* vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (s_nestedLoopLevel > 0) { --s_nestedLoopLevel; } else { args.rval().set(UINT_TO_JSVAL(0)); // JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(0)); return true; } args.rval().setUndefined(); // JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(s_nestedLoopLevel)); return true; } bool JSBDebug_getEventLoopNestLevel(JSContext* cx, unsigned argc, jsval* vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); args.rval().set(UINT_TO_JSVAL(s_nestedLoopLevel)); // JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(s_nestedLoopLevel)); return true; } static void processInput(const std::string& data) { std::lock_guard<std::mutex> lk(g_qMutex); g_queue.push_back(data); } static void clearBuffers() { std::lock_guard<std::mutex> lk(g_rwMutex); // only process input if there's something and we're not locked if (inData.length() > 0) { processInput(inData); inData.clear(); } if (outData.length() > 0) { // _clientSocketWriteAndClearString(outData); } } /* static void serverEntryPoint(unsigned int port) { // start a server, accept the connection and keep reading data from it struct addrinfo hints, *result = nullptr, *rp = nullptr; int s = 0; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; // IPv4 hints.ai_socktype = SOCK_STREAM; // TCP stream sockets hints.ai_flags = AI_PASSIVE; // fill in my IP for me std::stringstream portstr; portstr << port; int err = 0; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) WSADATA wsaData; err = WSAStartup(MAKEWORD(2, 2),&wsaData); #endif if ((err = getaddrinfo(NULL, portstr.str().c_str(), &hints, &result)) != 0) { LOGD("getaddrinfo error : %s\n", gai_strerror(err)); } for (rp = result; rp != NULL; rp = rp->ai_next) { if ((s = socket(rp->ai_family, rp->ai_socktype, 0)) < 0) { continue; } int optval = 1; if ((setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval))) < 0) { cc_closesocket(s); TRACE_DEBUGGER_SERVER("debug server : error setting socket option SO_REUSEADDR"); return; } #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if ((setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval))) < 0) { close(s); TRACE_DEBUGGER_SERVER("debug server : error setting socket option SO_NOSIGPIPE"); return; } #endif //(CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if ((::bind(s, rp->ai_addr, rp->ai_addrlen)) == 0) { break; } cc_closesocket(s); s = -1; } if (s < 0 || rp == NULL) { TRACE_DEBUGGER_SERVER("debug server : error creating/binding socket"); return; } freeaddrinfo(result); listen(s, 1); while (true) { clientSocket = accept(s, NULL, NULL); if (clientSocket < 0) { TRACE_DEBUGGER_SERVER("debug server : error on accept"); return; } else { // read/write data TRACE_DEBUGGER_SERVER("debug server : client connected"); inData = "connected"; // process any input, send any output clearBuffers(); char buf[1024] = {0}; int readBytes = 0; while ((readBytes = (int)::recv(clientSocket, buf, sizeof(buf), 0)) > 0) { buf[readBytes] = '\0'; // TRACE_DEBUGGER_SERVER("debug server : received command >%s", buf); // no other thread is using this inData.append(buf); // process any input, send any output clearBuffers(); } // while(read) cc_closesocket(clientSocket); } } // while(true) } */ void ScriptingCore::enableDebugger(unsigned int port) { if (!_debugGlobal) { JSAutoCompartment ac0(_cx, _global->get()); JS_SetDebugMode(_cx, true); _debugGlobal = new (std::nothrow) JS::PersistentRootedObject(_cx, NewGlobalObject(_cx, true)); // Adds the debugger object to root, otherwise it may be collected by GC. //AddObjectRoot(_cx, &*_debugGlobal); no need, it's persistent rooted now //JS_WrapObject(_cx, &*_debugGlobal); Not really needed, JS_WrapObject makes a cross-compartment wrapper for the given JS object JS::RootedObject rootedDebugObj(_cx, _debugGlobal->get()); JSAutoCompartment ac(_cx, rootedDebugObj); // these are used in the debug program JS_DefineFunction(_cx, rootedDebugObj, "log", ScriptingCore::log, 0, JSPROP_READONLY | JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(_cx, rootedDebugObj, "_bufferWrite", JSBDebug_BufferWrite, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(_cx, rootedDebugObj, "_enterNestedEventLoop", JSBDebug_enterNestedEventLoop, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(_cx, rootedDebugObj, "_exitNestedEventLoop", JSBDebug_exitNestedEventLoop, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(_cx, rootedDebugObj, "_getEventLoopNestLevel", JSBDebug_getEventLoopNestLevel, 0, JSPROP_READONLY | JSPROP_PERMANENT); runScript("script/jsb_debugger.js", rootedDebugObj); JS::RootedObject globalObj(_cx, _global->get()); JS_WrapObject(_cx, &globalObj); // prepare the debugger jsval argv = OBJECT_TO_JSVAL(globalObj); JS::RootedValue outval(_cx); bool ok = JS_CallFunctionName(_cx, rootedDebugObj, "_prepareDebugger", JS::HandleValueArray::fromMarkedLocation(1, &argv), &outval); if (!ok) { JS_ReportPendingException(_cx); } // start bg thread // auto t = std::thread(&serverEntryPoint,port); // t.detach(); CAScheduler::getScheduler()->schedule(schedule_selector(SimpleRunLoop::update), this->_runLoop, 0); } } void ScriptingCore::removeAllRoots(JSContext *cx) { js_proxy_t *current, *tmp; HASH_ITER(hh, _js_native_global_ht, current, tmp) { RemoveObjectRoot(cx, &current->obj); HASH_DEL(_js_native_global_ht, current); free(current); } HASH_ITER(hh, _native_js_global_ht, current, tmp) { HASH_DEL(_native_js_global_ht, current); free(current); } HASH_CLEAR(hh, _js_native_global_ht); HASH_CLEAR(hh, _native_js_global_ht); } JSObject* NewGlobalObject(JSContext* cx, bool debug) { JS::CompartmentOptions options; options.setVersion(JSVERSION_LATEST); JS::RootedObject glob(cx, JS_NewGlobalObject(cx, &global_class, &shellTrustedPrincipals, JS::DontFireOnNewGlobalHook, options)); if (!glob) { return nullptr; } JSAutoCompartment ac(cx, glob); bool ok = true; ok = JS_InitStandardClasses(cx, glob); if (ok) JS_InitReflect(cx, glob); if (ok && debug) ok = JS_DefineDebuggerObject(cx, glob); if (!ok) return nullptr; JS_FireOnNewGlobalObject(cx, glob); return glob; } bool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, uint32_t argc, jsval *vp) { JS::HandleValueArray args = JS::HandleValueArray::fromMarkedLocation(argc, vp); JS::RootedValue rval(_cx); return executeFunctionWithOwner(owner, name, args, &rval); } bool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, uint32_t argc, jsval *vp, JS::MutableHandleValue retVal) { //should not use CallArgs here, use HandleValueArray instead !! //because the "jsval* vp" is not the standard format from JSNative, the array doesn't contain this and retval //JS::CallArgs args = JS::CallArgsFromVp(argc, vp); // CCLog("FunctionName:%s",name); JS::HandleValueArray args = JS::HandleValueArray::fromMarkedLocation(argc, vp); return executeFunctionWithOwner(owner, name, args, retVal); } bool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, const JS::HandleValueArray& args) { JS::RootedValue ret(_cx); return executeFunctionWithOwner(owner, name, args, &ret); } bool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, const JS::HandleValueArray& args, JS::MutableHandleValue retVal) { bool bRet = false; bool hasAction; JSContext* cx = this->_cx; JS::RootedValue temp_retval(cx); JS::RootedObject obj(cx, JS::RootedValue(cx, owner).toObjectOrNull()); do { JSAutoCompartment ac(cx, obj); if (JS_HasProperty(cx, obj, name, &hasAction) && hasAction) { if (!JS_GetProperty(cx, obj, name, &temp_retval)) { break; } if (temp_retval == JSVAL_VOID) { break; } bRet = JS_CallFunctionName(cx, obj, name, args, retVal); } }while(0); return bRet; } static std::string getTouchFuncName(int eventCode) { std::string funcName; switch(eventCode) { case CCTOUCHBEGAN: funcName = "onTouchBegan"; break; case CCTOUCHENDED: funcName = "onTouchEnded"; break; case CCTOUCHMOVED: funcName = "onTouchMoved"; break; case CCTOUCHCANCELLED: funcName = "onTouchCancelled"; break; default: CCAssert(false, "Invalid event code!"); } return funcName; } static std::string getTouchesFuncName(int eventCode) { std::string funcName; switch(eventCode) { case CCTOUCHBEGAN: funcName = "onTouchesBegan"; break; case CCTOUCHENDED: funcName = "onTouchesEnded"; break; case CCTOUCHMOVED: funcName = "onTouchesMoved"; break; case CCTOUCHCANCELLED: funcName = "onTouchesCancelled"; break; default: CCAssert(false, "Invalid event code!"); break; } return funcName; } int ScriptingCore::executeCustomTouchesEvent(int eventType,const std::vector<CATouch*>& touches, JSObject *obj) { std::string funcName = getTouchesFuncName(eventType); JS::RootedObject jsretArr(_cx, JS_NewArrayObject(this->_cx, 0)); // JS_AddNamedObjectRoot(this->_cx, &jsretArr, "touchArray"); int count = 0; for (auto& touch : touches) { jsval jsret = getJSObject(this->_cx, touch); JS::RootedValue jsval(_cx, jsret); if (!JS_SetElement(this->_cx, jsretArr, count, jsval)) { break; } ++count; } jsval jsretArrVal = OBJECT_TO_JSVAL(jsretArr); executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), funcName.c_str(), 1, &jsretArrVal); // JS_RemoveObjectRoot(this->_cx, &jsretArr); for (auto& touch : touches) { removeJSObject(this->_cx, touch); } return 1; } int ScriptingCore::executeCustomKeyBackClicked(JSObject *obj){ executeFunctionWithOwner(OBJECT_TO_JSVAL(obj),"keyBackClicked",0,NULL); return 1; } int ScriptingCore::executeCustomKeyMenuClicked(JSObject *obj){ executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), "keyMenuClicked",0,NULL); return 1; } int ScriptingCore::executeCustomTouchEvent(int eventType,CATouch *pTouch, JSObject *obj) { JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET JS::RootedValue retval(_cx); std::string funcName = getTouchFuncName(eventType); jsval jsTouch = getJSObject(this->_cx, pTouch); executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), funcName.c_str(), 1, &jsTouch, &retval); // Remove touch object from global hash table and unroot it. removeJSObject(this->_cx, pTouch); return 1; } int ScriptingCore::executeCustomTouchEvent(int eventType,CATouch *pTouch, JSObject *obj,JS::MutableHandleValue retval) { JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET std::string funcName = getTouchFuncName(eventType); jsval jsTouch = getJSObject(this->_cx, pTouch); executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), funcName.c_str(), 1, &jsTouch, retval); // Remove touch object from global hash table and unroot it. removeJSObject(this->_cx, pTouch); return 1; } void ScriptingCore::cleanupSchedulesAndActions(js_proxy_t* p) { JS::RootedObject obj(_cx, p->obj.get()); CrossApp::CAVector<CAObject*>* arr = JSScheduleWrapper::getTargetForJSObject(obj); if (arr) { for (auto&& target : *arr) { CAScheduler::getScheduler()->unscheduleAllForTarget(target); } JSScheduleWrapper::removeAllTargetsForJSObject(obj); } } bool ScriptingCore::isFunctionOverridedInJS(JS::HandleObject obj, const std::string& name, JSNative native) { JS::RootedObject jsobj(_cx, obj); JSAutoCompartment ac(_cx, jsobj); JS::RootedValue value(_cx); bool ok = JS_GetProperty(_cx, jsobj, name.c_str(), &value); if (ok && !value.isNullOrUndefined() && !JS_IsNativeFunction(value.toObjectOrNull(), native)) { return true; } return false; } int ScriptingCore::handleNodeEvent(void* data) { if (NULL == data) return 0; BasicScriptData* basicScriptData = static_cast<BasicScriptData*>(data); if (NULL == basicScriptData->nativeObject || NULL == basicScriptData->value) return 0; CAView* node = static_cast<CAView*>(basicScriptData->nativeObject); int action = *((int*)(basicScriptData->value)); js_proxy_t * p = jsb_get_native_proxy(node); if (!p) return 0; JSAutoCompartment ac(_cx, *_global); int ret = 0; JS::RootedValue retval(_cx); jsval dataVal = INT_TO_JSVAL(1); JS::RootedObject jstarget(_cx, p->obj); if (action == script::onEnter) { if (isFunctionOverridedInJS(jstarget, "onEnter", js_crossapp_Node_onEnter)) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onEnter", 1, &dataVal, &retval); } } else if (action == script::onExit) { if (isFunctionOverridedInJS(jstarget, "onExit", js_crossapp_Node_onExit)) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onExit", 1, &dataVal, &retval); } } else if (action == script::onEnterTransitionDidFinish) { if (isFunctionOverridedInJS(jstarget, "onEnterTransitionDidFinish", js_crossapp_Node_onEnterTransitionDidFinish)) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onEnterTransitionDidFinish", 0, &dataVal, &retval); } } else if (action == script::onExitTransitionDidStart) { if (isFunctionOverridedInJS(jstarget, "onExitTransitionDidStart", js_crossapp_Node_onExitTransitionDidStart)) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onExitTransitionDidStart", 0, &dataVal, &retval); } } return ret; } int ScriptingCore::handleViewControllerEvent(void* data) { if (NULL == data) return 0; BasicScriptData* basicScriptData = static_cast<BasicScriptData*>(data); if (NULL == basicScriptData->nativeObject || NULL == basicScriptData->value) return 0; CAViewController* viewController = static_cast<CAViewController*>(basicScriptData->nativeObject); int action = *((int*)(basicScriptData->value)); js_proxy_t * p = jsb_get_native_proxy(viewController); if (!p) return 0; JSAutoCompartment ac(_cx, *_global); int ret = 0; JS::RootedValue retval(_cx); jsval dataVal = INT_TO_JSVAL(1); JS::RootedObject jstarget(_cx, p->obj); if (action == script::viewDidUnload) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "viewDidUnload", 0, &dataVal, &retval); cleanupSchedulesAndActions(p); } else if (action == script::viewDidLoad) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "viewDidLoad", 0, &dataVal, &retval); } else if (action == script::viewSizeDidChanged) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "viewSizeDidChanged", 0, &dataVal, &retval); } return ret; } void ScriptingCore::garbageCollect() { #if CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 auto runtime = JS_GetRuntime(_cx); // twice: yep, call it twice since this is a generational GC // and we want to collect as much as possible when this is being called // from replaceScene(). JS_GC(runtime); JS_GC(runtime); #endif } #pragma mark - Debug void SimpleRunLoop::update(float dt) { g_qMutex.lock(); size_t size = g_queue.size(); g_qMutex.unlock(); while (size > 0) { g_qMutex.lock(); auto first = g_queue.begin(); std::string str = *first; g_queue.erase(first); size = g_queue.size(); g_qMutex.unlock(); ScriptingCore::getInstance()->debugProcessInput(str); } } void ScriptingCore::releaseScriptObject(CrossApp::CAObject* owner, CrossApp::CAObject* target) { JS::RootedObject global(_cx, _global->get()); JS::RootedObject jsbObj(_cx); get_or_create_js_obj(_cx, global, "jsb", &jsbObj); JS::RootedValue jsbVal(_cx, OBJECT_TO_JSVAL(jsbObj)); if (jsbVal.isNullOrUndefined()) { return; } js_proxy_t *pOwner = jsb_get_native_proxy(owner); js_proxy_t *pTarget = jsb_get_native_proxy(target); if (!pOwner || !pTarget) { return; } JS::RootedValue valOwner(_cx, OBJECT_TO_JSVAL(pOwner->obj)); JS::RootedValue valTarget(_cx, OBJECT_TO_JSVAL(pTarget->obj)); if (valTarget.isPrimitive()) { return; } JS::RootedValue retval(_cx); jsval valArr[2]; valArr[0] = valOwner; valArr[1] = valTarget; JS::HandleValueArray args = JS::HandleValueArray::fromMarkedLocation(2, valArr); executeFunctionWithOwner(jsbVal, "unregisterNativeObject", args, &retval); } void ScriptingCore::releaseAllSubviewsRecursive(CrossApp::CAView* view) { const CAVector<CAView*>& subviews = view->getSubviews(); for (auto subview : subviews) { releaseScriptObject(view, subview); releaseAllSubviewsRecursive(subview); } } js_proxy_t* jsb_new_proxy(void* nativeObj, JSObject* jsObj) { js_proxy_t* p = nullptr; JS_NEW_PROXY(p, nativeObj, jsObj); return p; } js_proxy_t* jsb_get_native_proxy(void* nativeObj) { js_proxy_t* p = nullptr; JS_GET_PROXY(p, nativeObj); return p; } js_proxy_t* jsb_get_js_proxy(JSObject* jsObj) { js_proxy_t* p = nullptr; JS_GET_NATIVE_PROXY(p, jsObj); return p; } void jsb_remove_proxy(js_proxy_t* nativeProxy, js_proxy_t* jsProxy) { JS_REMOVE_PROXY(nativeProxy, jsProxy); } void jsb_remove_proxy(js_proxy_t* proxy) { void* nativeKey = proxy->ptr; JSObject* jsKey = proxy->_jsobj; // CC_ASSERT(nativeKey && "Invalid nativeKey"); CC_ASSERT(jsKey && "Invalid JSKey"); // auto it_nat = _native_js_global_map.find(nativeKey); auto it_js = _js_native_global_map.find(jsKey); // #if 0 // XXX FIXME: sanity check. Remove me once it is tested that it works Ok if (it_nat != _native_js_global_map.end() && it_js != _js_native_global_map.end()) { CC_ASSERT(it_nat->second == it_js->second && "BUG. Different enties"); } #endif if (it_nat != _native_js_global_map.end()) { _native_js_global_map.erase(it_nat); } else CCLOG("jsb_remove_proxy: failed. Native key not found"); if (it_js != _js_native_global_map.end()) { // Free it once, since we only have one proxy alloced entry free(it_js->second); _js_native_global_map.erase(it_js); } else CCLOG("jsb_remove_proxy: failed. JS key not found"); } no message // // ScriptingCore.cpp // MyTest // // Created by Lei.zhang on 16/1/19. // Copyright © 2016 Lei.zhang All rights reserved. // #include "ScriptingCore.h" // Removed in Firefox v27, use 'js/OldDebugAPI.h' instead #include "js/OldDebugAPI.h" // for debug socket #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) #include <io.h> #include <WS2tcpip.h> #else #include <sys/socket.h> #include <unistd.h> #include <netdb.h> #endif #include <thread> #include <iostream> #include <sstream> #include <stdio.h> #include <mutex> #include "crossapp_specifics.hpp" #ifdef ANDROID #define LOG_TAG "ScriptingCore.cpp" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #else #define LOGD(...) js_log(__VA_ARGS__) #endif #if CrossApp_DEBUG #define TRACE_DEBUGGER_SERVER(...) CCLOG(__VA_ARGS__) #else #define TRACE_DEBUGGER_SERVER(...) #endif // #if DEBUG #define BYTE_CODE_FILE_EXT ".jsc" static std::string inData; static std::string outData; static std::vector<std::string> g_queue; static std::mutex g_qMutex; static std::mutex g_rwMutex; static int clientSocket = -1; static uint32_t s_nestedLoopLevel = 0; js_proxy_t *_native_js_global_ht = NULL; js_proxy_t *_js_native_global_ht = NULL; std::unordered_map<std::string, js_type_class_t*> _js_global_type_map; static std::unordered_map<void*, js_proxy_t*> _native_js_global_map; static std::unordered_map<JSObject*, js_proxy_t*> _js_native_global_map; static std::unordered_map<JSObject*, JSObject*> _js_hook_owner_map; static char *_js_log_buf = NULL; static std::vector<sc_register_sth> registrationList; // name ~> JSScript map static std::unordered_map<std::string, JSScript*> filename_script; /* static void cc_closesocket(int fd) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) closesocket(fd); #else close(fd); #endif } */ static ScriptingCore* instance = nullptr; typedef void (*sc_register_sth)(JSContext* cx, JS::HandleObject global); /// The max length of CCLog message. static const int MAX_LOG_LENGTH = 16*1024; void js_log(const char *format, ...) { if (_js_log_buf == NULL) { _js_log_buf = (char *)calloc(sizeof(char), MAX_LOG_LENGTH+1); _js_log_buf[MAX_LOG_LENGTH] = '\0'; } va_list vl; va_start(vl, format); int len = vsnprintf(_js_log_buf, MAX_LOG_LENGTH, format, vl); va_end(vl); if (len > 0) { CCLog("JS: %s", _js_log_buf); } } static void sc_finalize(JSFreeOp *freeOp, JSObject *obj) { // CCLOGINFO("jsbindings: finalizing JS object %p (global class)", obj); } static void ReportException(JSContext *cx) { if (JS_IsExceptionPending(cx)) { if (!JS_ReportPendingException(cx)) { JS_ClearPendingException(cx); } } } static const JSClass global_class = { "global", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, sc_finalize, nullptr, nullptr, nullptr, JS_GlobalObjectTraceHook }; // Just a wrapper around JSPrincipals that allows static construction. class CCJSPrincipals : public JSPrincipals { public: explicit CCJSPrincipals(int rc = 0) : JSPrincipals() { refcount = rc; } }; static CCJSPrincipals shellTrustedPrincipals(1); ScriptingCore::ScriptingCore() :_rt(nullptr) ,_cx(nullptr) ,_jsInited(false) ,_needCleanup(false) ,_global(nullptr) ,_debugGlobal(nullptr) ,_callFromScript(false) { initRegister(); } void ScriptingCore::initRegister(){ this->addRegisterCallback(registerDefaultClasses); this->_runLoop = new (std::nothrow) SimpleRunLoop(); } void ScriptingCore::restartVM() { cleanup(); initRegister(); CCApplication::sharedApplication()->applicationDidFinishLaunching(); } ScriptingCore::~ScriptingCore() { cleanup(); } bool JSBCore_platform(JSContext *cx, uint32_t argc, jsval *vp) { if (argc!=0) { JS_ReportError(cx, "Invalid number of arguments in __getPlatform"); return false; } JS::CallArgs args = JS::CallArgsFromVp(argc, vp); TargetPlatform platform; // config.deviceType: Device Type // 'mobile' for any kind of mobile devices, 'desktop' for PCs, 'browser' for Web Browsers // #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) // platform = JS_InternString(_cx, "desktop"); // #else platform = CCApplication::sharedApplication()->getTargetPlatform(); // #endif args.rval().set(INT_TO_JSVAL((int)platform)); return true; }; bool JSBCore_os(JSContext *cx, uint32_t argc, jsval *vp) { if (argc!=0) { JS_ReportError(cx, "Invalid number of arguments in __getOS"); return false; } JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JSString * os; // osx, ios, android, windows, linux, etc.. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) os = JS_InternString(cx, "iOS"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) os = JS_InternString(cx, "Android"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) os = JS_InternString(cx, "Windows"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE) os = JS_InternString(cx, "Marmalade"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) os = JS_InternString(cx, "Linux"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_BADA) os = JS_InternString(cx, "Bada"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) os = JS_InternString(cx, "Blackberry"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) os = JS_InternString(cx, "OS X"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) os = JS_InternString(cx, "WINRT"); #else os = JS_InternString(cx, "Unknown"); #endif args.rval().set(STRING_TO_JSVAL(os)); return true; }; bool JSBCore_version(JSContext *cx, uint32_t argc, jsval *vp) { if (argc!=0) { JS_ReportError(cx, "Invalid number of arguments in __getVersion"); return false; } JS::CallArgs args = JS::CallArgsFromVp(argc, vp); char version[256]; snprintf(version, sizeof(version)-1, "%s", CrossAppVersion()); JSString * js_version = JS_InternString(cx, version); args.rval().set(STRING_TO_JSVAL(js_version)); return true; }; bool JSB_core_restartVM(JSContext *cx, uint32_t argc, jsval *vp) { JSB_PRECONDITION2(argc==0, cx, false, "Invalid number of arguments in executeScript"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); ScriptingCore::getInstance()->reset(); args.rval().setUndefined(); return true; }; bool JSB_cleanScript(JSContext *cx, uint32_t argc, jsval *vp) { if (argc != 1) { JS_ReportError(cx, "Invalid number of arguments in JSB_cleanScript"); return false; } JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JSString *jsPath = args.get(0).toString(); JSB_PRECONDITION2(jsPath, cx, false, "Error js file in clean script"); JSStringWrapper wrapper(jsPath); ScriptingCore::getInstance()->cleanScript(wrapper.get()); args.rval().setUndefined(); return true; }; void registerDefaultClasses(JSContext* cx, JS::HandleObject global) { // first, try to get the ns JS::RootedValue nsval(cx); JS::RootedObject ns(cx); JS_GetProperty(cx, global, "ca", &nsval); // Not exist, create it if (nsval == JSVAL_VOID) { ns.set(JS_NewObject(cx, NULL, JS::NullPtr(), JS::NullPtr())); nsval = OBJECT_TO_JSVAL(ns); JS_SetProperty(cx, global, "ca", nsval); } else { ns.set(nsval.toObjectOrNull()); } // // Javascript controller (__jsc__) // JS::RootedObject proto(cx); JS::RootedObject parent(cx); JS::RootedObject jsc(cx, JS_NewObject(cx, NULL, proto, parent)); JS::RootedValue jscVal(cx); jscVal = OBJECT_TO_JSVAL(jsc); JS_SetProperty(cx, global, "__jsc__", jscVal); //在引擎中注册基础函数,实现这些就可以同javascript调用这些函数进行测试了 JS_DefineFunction(cx, jsc, "garbageCollect", ScriptingCore::forceGC, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, jsc, "dumpRoot", ScriptingCore::dumpRoot, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, jsc, "addGCRootObject", ScriptingCore::addRootJS, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, jsc, "removeGCRootObject", ScriptingCore::removeRootJS, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, jsc, "executeScript", ScriptingCore::executeScript, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); // register some global functions JS_DefineFunction(cx, global, "require", ScriptingCore::executeScript, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "log", ScriptingCore::log, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "executeScript", ScriptingCore::executeScript, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "forceGC", ScriptingCore::forceGC, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__getPlatform", JSBCore_platform, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__getOS", JSBCore_os, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__getVersion", JSBCore_version, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__restartVM", JSB_core_restartVM, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, global, "__cleanScript", JSB_cleanScript, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__isObjectValid", ScriptingCore::isObjectValid, 1, JSPROP_READONLY | JSPROP_PERMANENT); } ScriptingCore* ScriptingCore::getInstance() { if (!instance) { instance = new ScriptingCore(); } return instance; } void ScriptingCore::releaseThis() { instance = nullptr; CAScriptEngineManager::getScriptEngineManager()->setScriptEngine(nullptr); delete this; } void ScriptingCore::addRegisterCallback(sc_register_sth callback) { registrationList.push_back(callback); } static bool CheckObjectAccess(JSContext *cx) { return true; } static JSSecurityCallbacks securityCallbacks = { CheckObjectAccess, NULL }; void ScriptingCore::createGlobalContext() { // if (_cx && _rt) // { // ScriptingCore::removeAllRoots(_cx); // JS_DestroyContext(_cx); // JS_DestroyRuntime(_rt); // _cx = nullptr; // _rt = nullptr; // } if (!_jsInited && !JS_Init()) { return; } else { _jsInited = true; } _rt = JS_NewRuntime(8L * 1024L * 1024L); JS_SetGCParameter(_rt, JSGC_MAX_BYTES, 0xffffffff); JS_SetTrustedPrincipals(_rt, &shellTrustedPrincipals); JS_SetSecurityCallbacks(_rt, &securityCallbacks); JS_SetNativeStackQuota(_rt, JSB_MAX_STACK_QUOTA); _cx = JS_NewContext(_rt, 8192); JS::RuntimeOptionsRef(_rt).setIon(true); JS::RuntimeOptionsRef(_rt).setBaseline(true); JS_SetErrorReporter(_cx, ScriptingCore::reportError); _global = new (std::nothrow) JS::PersistentRootedObject(_rt, NewGlobalObject(_cx)); JS::RootedObject global(_cx, _global->get()); // Removed in Firefox v34 js::SetDefaultObjectForContext(_cx, global); JSAutoCompartment ac(_cx, _global->get()); runScript("script/jsb_prepare.js"); for (std::vector<sc_register_sth>::iterator it = registrationList.begin(); it != registrationList.end(); it++) { sc_register_sth callback = *it; callback(_cx, *_global); } _needCleanup = true; } bool ScriptingCore::evalString(const char *string,JS::RootedValue *outVal, const char *filename, JSContext *cx, JSObject* global ) { if (cx == NULL) { cx = _cx; } if (global == NULL) { global = _global->get(); } JSAutoCompartment ac(cx,global); JS::RootedObject cc(cx, global); JS::RootedValue rval(cx); bool ok = JS_EvaluateScript(cx, cc, string, strlen(string), "ScriptingCore::evalString", 1,&rval); /* if (ok) { JSString *str = rval.toString(); printf("javascript:-->%s",JS_EncodeString(cx, str)); } */ return ok; } static std::string RemoveFileExt(const std::string& filePath) { size_t pos = filePath.rfind('.'); if (0 < pos) { return filePath.substr(0, pos); } else { return filePath; } } JSScript* ScriptingCore::getScript(const char *path){ // a) check jsc file first std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT; if (filename_script.find(byteCodePath) != filename_script.end()) return filename_script[byteCodePath]; // b) no jsc file, check js file std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); if (filename_script.find(fullPath) != filename_script.end()) return filename_script[fullPath]; return NULL; } void ScriptingCore::compileScript(const char *path, JSObject* global, JSContext* cx ){ if (!path) { return; } if (getScript(path)) { return; } FileUtils * futil = FileUtils::getInstance(); if (global == NULL) { global = *_global; } if (cx == NULL) { cx = _cx; } JSAutoCompartment ac(cx,global); JS::RootedScript script(cx); JS::RootedObject obj(cx,global); // a) check jsc file first std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT ; // Check whether '.jsc' files exist to avoid outputing log which says 'couldn't find .jsc file'. if (futil->isFileExist(byteCodePath)) { unsigned long size = 0; unsigned char* data = futil->getFileData(byteCodePath.c_str(), "rb", &size); if (size > 0) { script = JS_DecodeScript(cx, data, static_cast<uint32_t>(size), nullptr); } } // b) no jsc file, check js file if (!script) { /* Clear any pending exception from previous failed decoding. */ ReportException(cx); std::string fullPath = futil->fullPathForFilename(path); JS::CompileOptions op(cx); op.setUTF8(true); op.setFileAndLine(fullPath.c_str(), 1); bool ok = false; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) std::string jsFileContent = futil->getFileString(fullPath); if (!jsFileContent.empty()) { ok = JS::Compile(cx, obj, op, jsFileContent.c_str(), jsFileContent.size(), &script); } #else ok = JS::Compile(cx, obj, op, fullPath.c_str(), &script); #endif if (ok) { filename_script[fullPath] = script; } } else { filename_script[byteCodePath] = script; } } bool ScriptingCore::runScript(const char *path){ return runScript(path, *_global, _cx); } bool ScriptingCore::runScript(const char *path, JS::HandleObject global, JSContext* cx) { if (cx == NULL) { cx = _cx; } compileScript(path,global,cx); JS::RootedScript script(cx,getScript(path)); bool evaluatedOK = false; if (script) { JS::RootedValue rval(cx); JSAutoCompartment ac(cx, global); evaluatedOK = JS_ExecuteScript(cx, global, script, &rval); if (false == evaluatedOK) { CCLog("Evaluating %s failed (evaluatedOK == JS_FALSE)", path); JS_ReportPendingException(cx); } // else // { // JSString *str = rval.toString(); // printf("Runscript:-->%s",JS_EncodeString(cx, str)); // } } return evaluatedOK; } bool ScriptingCore::requireScript(const char *path, JS::MutableHandleValue jsvalRet) { return requireScript(path, *_global, _cx, jsvalRet); } bool ScriptingCore::requireScript(const char *path, JS::HandleObject global, JSContext* cx, JS::MutableHandleValue jsvalRet) { if(cx == NULL) { cx = _cx; } compileScript(path,global,cx); JS::RootedScript script(cx,getScript(path)); bool evaluateOK = false; if (script) { JSAutoCompartment ac(cx,global); evaluateOK = JS_ExecuteScript(cx, global, script, jsvalRet); if (false == evaluateOK) { CCLog("(evaluatedOK == JS_FALSE)"); JS_ReportPendingException(cx); } } return evaluateOK; } void ScriptingCore::cleanScript(const char *path) { std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT ; auto it = filename_script.find(byteCodePath); if (it != filename_script.end()) { filename_script.erase(it); } std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); it = filename_script.find(fullPath); if (it != filename_script.end()) { filename_script.erase(it); } } std::unordered_map<std::string, JSScript*> &ScriptingCore::getFileScript() { return filename_script; } void ScriptingCore::cleanAllScript() { filename_script.clear(); } void ScriptingCore::start() { // for now just this createGlobalContext(); } void ScriptingCore::cleanup() { if (!_needCleanup) { return; } localStorageFree(); removeAllRoots(_cx); garbageCollect(); if (_cx) { JS_DestroyContext(_cx); _cx = nullptr; } if (_rt) { JS_DestroyRuntime(_rt); _rt = nullptr; } CC_SAFE_DELETE(_global); CC_SAFE_DELETE(_debugGlobal); _global = nullptr; _debugGlobal = nullptr; if (_js_log_buf) { free(_js_log_buf); _js_log_buf = NULL; } for (auto iter = _js_global_type_map.begin(); iter != _js_global_type_map.end(); ++iter) { free(iter->second->jsclass); free(iter->second); } _js_global_type_map.clear(); filename_script.clear(); registrationList.clear(); _needCleanup = false; } void ScriptingCore::reset() { CAApplication::getApplication()->restart(); } void ScriptingCore::reportError(JSContext *cx, const char *message, JSErrorReport *report) { js_log("%s:%u:%s\n", report->filename ? report->filename : "<no filename=\"filename\">", (unsigned int) report->lineno, message); }; void removeJSObject(JSContext* cx, void* nativeObj) { js_proxy_t* nproxy; js_proxy_t* jsproxy; nproxy = jsb_get_native_proxy(nativeObj); if (nproxy) { jsproxy = jsb_get_js_proxy(nproxy->obj); RemoveObjectRoot(cx, &jsproxy->obj); jsb_remove_proxy(nproxy, jsproxy); } } bool ScriptingCore::log(JSContext* cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (argc > 0) { JSString *string = JS::ToString(cx, args.get(0)); if (string) { JSStringWrapper wrapper(string); js_log("%s", wrapper.get()); } } args.rval().setUndefined(); return true; } void ScriptingCore::removeScriptObjectByObject(CAObject* pObj) { js_proxy_t* nproxy; js_proxy_t* jsproxy; void *ptr = (void*)pObj; nproxy = jsb_get_native_proxy(ptr); if (nproxy) { JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); jsproxy = jsb_get_js_proxy(nproxy->obj); RemoveObjectRoot(cx, &jsproxy->obj); jsb_remove_proxy(nproxy, jsproxy); } } bool ScriptingCore::setReservedSpot(uint32_t i, JSObject *obj, jsval value) { JS_SetReservedSlot(obj, i, value); return true; } bool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (argc >= 1) { JSString* str = JS::ToString(cx, JS::RootedValue(cx, args.get(0))); JSStringWrapper path(str); bool res = false; if (argc == 2 && args.get(1).isString()) { JSString* globalName = args.get(1).toString(); JSStringWrapper name(globalName); JS::RootedObject debugObj(cx, ScriptingCore::getInstance()->getDebugGlobal()); if (debugObj) { res = ScriptingCore::getInstance()->runScript(path.get(), debugObj); } else { JS_ReportError(cx, "Invalid global object: %s", name.get()); return false; } } else { JS::RootedObject glob(cx, JS::CurrentGlobalOrNull(cx)); res = ScriptingCore::getInstance()->runScript(path.get(), glob); } return res; } args.rval().setUndefined(); return true; } bool ScriptingCore::forceGC(JSContext *cx, uint32_t argc, jsval *vp) { JSRuntime *rt = JS_GetRuntime(cx); JS_GC(rt); return true; } bool ScriptingCore::dumpRoot(JSContext *cx, uint32_t argc, jsval *vp) { // JS_DumpNamedRoots is only available on DEBUG versions of SpiderMonkey. // Mac and Simulator versions were compiled with DEBUG. #if CrossApp_DEBUG // JSContext *_cx = ScriptingCore::getInstance()->getGlobalContext(); // JSRuntime *rt = JS_GetRuntime(_cx); // JS_DumpNamedRoots(rt, dumpNamedRoot, NULL); // JS_DumpHeap(rt, stdout, NULL, JSTRACE_OBJECT, NULL, 2, NULL); #endif return true; } bool ScriptingCore::addRootJS(JSContext *cx, uint32_t argc, jsval *vp) { if (argc == 1) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Heap<JSObject*> o(args.get(0).toObjectOrNull()); if (AddNamedObjectRoot(cx, &o, "from-js") == false) { LOGD("something went wrong when setting an object to the root"); } return true; } return false; } bool ScriptingCore::removeRootJS(JSContext *cx, uint32_t argc, jsval *vp) { if (argc == 1) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Heap<JSObject*> o(args.get(0).toObjectOrNull()); if (o != nullptr) { RemoveObjectRoot(cx, &o); } return true; } return false; } // ** int ScriptingCore::sendEvent(ScriptEvent* evt) { if (NULL == evt) return 0; // special type, can't use this code after JSAutoCompartment if (evt->type == kRestartGame) { restartVM(); return 0; } JSAutoCompartment ac(_cx, _global->get()); switch (evt->type) { case kNodeEvent: { return handleNodeEvent(evt->data); } break; case kScriptActionEvent: { // return handleActionEvent(evt->data); ** } break; case kMenuClickedEvent: break; case kTouchEvent: { // TouchScriptData* data = (TouchScriptData*)evt->data; // return handleTouchEvent(data->nativeObject, data->actionType, data->touch, data->event); ** } break; case kTouchesEvent: { // TouchesScriptData* data = (TouchesScriptData*)evt->data; //** // return handleTouchesEvent(data->nativeObject, data->actionType, data->touches, data->event); ** } break; case kComponentEvent: { // return handleComponentEvent(evt->data); ** } break; case kViewControllerEvent: { return handleViewControllerEvent(evt->data); } break; default: CCAssert(false, "Invalid script event."); break; } return 0; } bool ScriptingCore::isObjectValid(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (argc == 1) { JS::RootedObject tmpObj(cx, args.get(0).toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(tmpObj); if (proxy && proxy->ptr) { args.rval().set(JSVAL_TRUE); } else { args.rval().set(JSVAL_FALSE); } return true; } else { JS_ReportError(cx, "Invalid number of arguments: %d. Expecting: 1", argc); return false; } } void ScriptingCore::debugProcessInput(const std::string& str) { JSAutoCompartment ac(_cx, *_debugGlobal); JSString* jsstr = JS_NewStringCopyZ(_cx, str.c_str()); jsval argv = STRING_TO_JSVAL(jsstr); JS::RootedValue outval(_cx); JS_CallFunctionName(_cx, JS::RootedObject(_cx, *_debugGlobal), "processInput", JS::HandleValueArray::fromMarkedLocation(1, &argv), &outval); } //#pragma mark - Debugger /* static void _clientSocketWriteAndClearString(std::string& s) { ::send(clientSocket, s.c_str(), s.length(), 0); s.clear(); } */ bool JSBDebug_BufferWrite(JSContext* cx, unsigned argc, jsval* vp) { if (argc == 1) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JSStringWrapper strWrapper(args.get(0)); // this is safe because we're already inside a lock (from clearBuffers) outData.append(strWrapper.get()); //_clientSocketWriteAndClearString(outData); } return true; } static bool NS_ProcessNextEvent() { g_qMutex.lock(); size_t size = g_queue.size(); g_qMutex.unlock(); while (size > 0) { g_qMutex.lock(); auto first = g_queue.begin(); std::string str = *first; g_queue.erase(first); size = g_queue.size(); g_qMutex.unlock(); ScriptingCore::getInstance()->debugProcessInput(str); } // std::this_thread::yield(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); return true; } bool JSBDebug_enterNestedEventLoop(JSContext* cx, unsigned argc, jsval* vp) { enum { NS_OK = 0, NS_ERROR_UNEXPECTED }; #define NS_SUCCEEDED(v) ((v) == NS_OK) int rv = NS_OK; uint32_t nestLevel = ++s_nestedLoopLevel; while (NS_SUCCEEDED(rv) && s_nestedLoopLevel >= nestLevel) { if (!NS_ProcessNextEvent()) rv = NS_ERROR_UNEXPECTED; } CCAssert(s_nestedLoopLevel <= nestLevel, "nested event didn't unwind properly"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); args.rval().set(UINT_TO_JSVAL(s_nestedLoopLevel)); // JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(s_nestedLoopLevel)); return true; } bool JSBDebug_exitNestedEventLoop(JSContext* cx, unsigned argc, jsval* vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (s_nestedLoopLevel > 0) { --s_nestedLoopLevel; } else { args.rval().set(UINT_TO_JSVAL(0)); // JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(0)); return true; } args.rval().setUndefined(); // JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(s_nestedLoopLevel)); return true; } bool JSBDebug_getEventLoopNestLevel(JSContext* cx, unsigned argc, jsval* vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); args.rval().set(UINT_TO_JSVAL(s_nestedLoopLevel)); // JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(s_nestedLoopLevel)); return true; } static void processInput(const std::string& data) { std::lock_guard<std::mutex> lk(g_qMutex); g_queue.push_back(data); } static void clearBuffers() { std::lock_guard<std::mutex> lk(g_rwMutex); // only process input if there's something and we're not locked if (inData.length() > 0) { processInput(inData); inData.clear(); } if (outData.length() > 0) { // _clientSocketWriteAndClearString(outData); } } /* static void serverEntryPoint(unsigned int port) { // start a server, accept the connection and keep reading data from it struct addrinfo hints, *result = nullptr, *rp = nullptr; int s = 0; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; // IPv4 hints.ai_socktype = SOCK_STREAM; // TCP stream sockets hints.ai_flags = AI_PASSIVE; // fill in my IP for me std::stringstream portstr; portstr << port; int err = 0; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) WSADATA wsaData; err = WSAStartup(MAKEWORD(2, 2),&wsaData); #endif if ((err = getaddrinfo(NULL, portstr.str().c_str(), &hints, &result)) != 0) { LOGD("getaddrinfo error : %s\n", gai_strerror(err)); } for (rp = result; rp != NULL; rp = rp->ai_next) { if ((s = socket(rp->ai_family, rp->ai_socktype, 0)) < 0) { continue; } int optval = 1; if ((setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval))) < 0) { cc_closesocket(s); TRACE_DEBUGGER_SERVER("debug server : error setting socket option SO_REUSEADDR"); return; } #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if ((setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval))) < 0) { close(s); TRACE_DEBUGGER_SERVER("debug server : error setting socket option SO_NOSIGPIPE"); return; } #endif //(CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if ((::bind(s, rp->ai_addr, rp->ai_addrlen)) == 0) { break; } cc_closesocket(s); s = -1; } if (s < 0 || rp == NULL) { TRACE_DEBUGGER_SERVER("debug server : error creating/binding socket"); return; } freeaddrinfo(result); listen(s, 1); while (true) { clientSocket = accept(s, NULL, NULL); if (clientSocket < 0) { TRACE_DEBUGGER_SERVER("debug server : error on accept"); return; } else { // read/write data TRACE_DEBUGGER_SERVER("debug server : client connected"); inData = "connected"; // process any input, send any output clearBuffers(); char buf[1024] = {0}; int readBytes = 0; while ((readBytes = (int)::recv(clientSocket, buf, sizeof(buf), 0)) > 0) { buf[readBytes] = '\0'; // TRACE_DEBUGGER_SERVER("debug server : received command >%s", buf); // no other thread is using this inData.append(buf); // process any input, send any output clearBuffers(); } // while(read) cc_closesocket(clientSocket); } } // while(true) } */ void ScriptingCore::enableDebugger(unsigned int port) { if (!_debugGlobal) { JSAutoCompartment ac0(_cx, _global->get()); JS_SetDebugMode(_cx, true); _debugGlobal = new (std::nothrow) JS::PersistentRootedObject(_cx, NewGlobalObject(_cx, true)); // Adds the debugger object to root, otherwise it may be collected by GC. //AddObjectRoot(_cx, &*_debugGlobal); no need, it's persistent rooted now //JS_WrapObject(_cx, &*_debugGlobal); Not really needed, JS_WrapObject makes a cross-compartment wrapper for the given JS object JS::RootedObject rootedDebugObj(_cx, _debugGlobal->get()); JSAutoCompartment ac(_cx, rootedDebugObj); // these are used in the debug program JS_DefineFunction(_cx, rootedDebugObj, "log", ScriptingCore::log, 0, JSPROP_READONLY | JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(_cx, rootedDebugObj, "_bufferWrite", JSBDebug_BufferWrite, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(_cx, rootedDebugObj, "_enterNestedEventLoop", JSBDebug_enterNestedEventLoop, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(_cx, rootedDebugObj, "_exitNestedEventLoop", JSBDebug_exitNestedEventLoop, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(_cx, rootedDebugObj, "_getEventLoopNestLevel", JSBDebug_getEventLoopNestLevel, 0, JSPROP_READONLY | JSPROP_PERMANENT); runScript("script/jsb_debugger.js", rootedDebugObj); JS::RootedObject globalObj(_cx, _global->get()); JS_WrapObject(_cx, &globalObj); // prepare the debugger jsval argv = OBJECT_TO_JSVAL(globalObj); JS::RootedValue outval(_cx); bool ok = JS_CallFunctionName(_cx, rootedDebugObj, "_prepareDebugger", JS::HandleValueArray::fromMarkedLocation(1, &argv), &outval); if (!ok) { JS_ReportPendingException(_cx); } // start bg thread // auto t = std::thread(&serverEntryPoint,port); // t.detach(); CAScheduler::getScheduler()->schedule(schedule_selector(SimpleRunLoop::update), this->_runLoop, 0); } } void ScriptingCore::removeAllRoots(JSContext *cx) { js_proxy_t *current, *tmp; HASH_ITER(hh, _js_native_global_ht, current, tmp) { RemoveObjectRoot(cx, &current->obj); HASH_DEL(_js_native_global_ht, current); free(current); } HASH_ITER(hh, _native_js_global_ht, current, tmp) { HASH_DEL(_native_js_global_ht, current); free(current); } HASH_CLEAR(hh, _js_native_global_ht); HASH_CLEAR(hh, _native_js_global_ht); } JSObject* NewGlobalObject(JSContext* cx, bool debug) { JS::CompartmentOptions options; options.setVersion(JSVERSION_LATEST); JS::RootedObject glob(cx, JS_NewGlobalObject(cx, &global_class, &shellTrustedPrincipals, JS::DontFireOnNewGlobalHook, options)); if (!glob) { return nullptr; } JSAutoCompartment ac(cx, glob); bool ok = true; ok = JS_InitStandardClasses(cx, glob); if (ok) JS_InitReflect(cx, glob); if (ok && debug) ok = JS_DefineDebuggerObject(cx, glob); if (!ok) return nullptr; JS_FireOnNewGlobalObject(cx, glob); return glob; } bool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, uint32_t argc, jsval *vp) { JS::HandleValueArray args = JS::HandleValueArray::fromMarkedLocation(argc, vp); JS::RootedValue rval(_cx); return executeFunctionWithOwner(owner, name, args, &rval); } bool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, uint32_t argc, jsval *vp, JS::MutableHandleValue retVal) { //should not use CallArgs here, use HandleValueArray instead !! //because the "jsval* vp" is not the standard format from JSNative, the array doesn't contain this and retval //JS::CallArgs args = JS::CallArgsFromVp(argc, vp); // CCLog("FunctionName:%s",name); JS::HandleValueArray args = JS::HandleValueArray::fromMarkedLocation(argc, vp); return executeFunctionWithOwner(owner, name, args, retVal); } bool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, const JS::HandleValueArray& args) { JS::RootedValue ret(_cx); return executeFunctionWithOwner(owner, name, args, &ret); } bool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, const JS::HandleValueArray& args, JS::MutableHandleValue retVal) { bool bRet = false; bool hasAction; JSContext* cx = this->_cx; JS::RootedValue temp_retval(cx); JS::RootedObject obj(cx, JS::RootedValue(cx, owner).toObjectOrNull()); do { JSAutoCompartment ac(cx, obj); if (JS_HasProperty(cx, obj, name, &hasAction) && hasAction) { if (!JS_GetProperty(cx, obj, name, &temp_retval)) { break; } if (temp_retval == JSVAL_VOID) { break; } bRet = JS_CallFunctionName(cx, obj, name, args, retVal); } }while(0); return bRet; } static std::string getTouchFuncName(int eventCode) { std::string funcName; switch(eventCode) { case CCTOUCHBEGAN: funcName = "onTouchBegan"; break; case CCTOUCHENDED: funcName = "onTouchEnded"; break; case CCTOUCHMOVED: funcName = "onTouchMoved"; break; case CCTOUCHCANCELLED: funcName = "onTouchCancelled"; break; default: CCAssert(false, "Invalid event code!"); } return funcName; } static std::string getTouchesFuncName(int eventCode) { std::string funcName; switch(eventCode) { case CCTOUCHBEGAN: funcName = "onTouchesBegan"; break; case CCTOUCHENDED: funcName = "onTouchesEnded"; break; case CCTOUCHMOVED: funcName = "onTouchesMoved"; break; case CCTOUCHCANCELLED: funcName = "onTouchesCancelled"; break; default: CCAssert(false, "Invalid event code!"); break; } return funcName; } int ScriptingCore::executeCustomTouchesEvent(int eventType,const std::vector<CATouch*>& touches, JSObject *obj) { std::string funcName = getTouchesFuncName(eventType); JS::RootedObject jsretArr(_cx, JS_NewArrayObject(this->_cx, 0)); // JS_AddNamedObjectRoot(this->_cx, &jsretArr, "touchArray"); int count = 0; for (auto& touch : touches) { jsval jsret = getJSObject(this->_cx, touch); JS::RootedValue jsval(_cx, jsret); if (!JS_SetElement(this->_cx, jsretArr, count, jsval)) { break; } ++count; } jsval jsretArrVal = OBJECT_TO_JSVAL(jsretArr); executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), funcName.c_str(), 1, &jsretArrVal); // JS_RemoveObjectRoot(this->_cx, &jsretArr); for (auto& touch : touches) { removeJSObject(this->_cx, touch); } return 1; } int ScriptingCore::executeCustomKeyBackClicked(JSObject *obj){ executeFunctionWithOwner(OBJECT_TO_JSVAL(obj),"keyBackClicked",0,NULL); return 1; } int ScriptingCore::executeCustomKeyMenuClicked(JSObject *obj){ executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), "keyMenuClicked",0,NULL); return 1; } int ScriptingCore::executeCustomTouchEvent(int eventType,CATouch *pTouch, JSObject *obj) { JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET JS::RootedValue retval(_cx); std::string funcName = getTouchFuncName(eventType); jsval jsTouch = getJSObject(this->_cx, pTouch); executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), funcName.c_str(), 1, &jsTouch, &retval); // Remove touch object from global hash table and unroot it. removeJSObject(this->_cx, pTouch); return 1; } int ScriptingCore::executeCustomTouchEvent(int eventType,CATouch *pTouch, JSObject *obj,JS::MutableHandleValue retval) { JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET std::string funcName = getTouchFuncName(eventType); jsval jsTouch = getJSObject(this->_cx, pTouch); executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), funcName.c_str(), 1, &jsTouch, retval); // Remove touch object from global hash table and unroot it. removeJSObject(this->_cx, pTouch); return 1; } void ScriptingCore::cleanupSchedulesAndActions(js_proxy_t* p) { JS::RootedObject obj(_cx, p->obj.get()); CrossApp::CAVector<CAObject*>* arr = JSScheduleWrapper::getTargetForJSObject(obj); if (arr) { for (auto&& target : *arr) { CAScheduler::getScheduler()->unscheduleAllForTarget(target); } JSScheduleWrapper::removeAllTargetsForJSObject(obj); } } bool ScriptingCore::isFunctionOverridedInJS(JS::HandleObject obj, const std::string& name, JSNative native) { JS::RootedObject jsobj(_cx, obj); JSAutoCompartment ac(_cx, jsobj); JS::RootedValue value(_cx); bool ok = JS_GetProperty(_cx, jsobj, name.c_str(), &value); if (ok && !value.isNullOrUndefined() && !JS_IsNativeFunction(value.toObjectOrNull(), native)) { return true; } return false; } int ScriptingCore::handleNodeEvent(void* data) { if (NULL == data) return 0; BasicScriptData* basicScriptData = static_cast<BasicScriptData*>(data); if (NULL == basicScriptData->nativeObject || NULL == basicScriptData->value) return 0; CAView* node = static_cast<CAView*>(basicScriptData->nativeObject); int action = *((int*)(basicScriptData->value)); js_proxy_t * p = jsb_get_native_proxy(node); if (!p) return 0; JSAutoCompartment ac(_cx, *_global); int ret = 0; JS::RootedValue retval(_cx); jsval dataVal = INT_TO_JSVAL(1); JS::RootedObject jstarget(_cx, p->obj); if (action == script::onEnter) { if (isFunctionOverridedInJS(jstarget, "onEnter", js_crossapp_Node_onEnter)) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onEnter", 1, &dataVal, &retval); } } else if (action == script::onExit) { if (isFunctionOverridedInJS(jstarget, "onExit", js_crossapp_Node_onExit)) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onExit", 1, &dataVal, &retval); } } else if (action == script::onEnterTransitionDidFinish) { if (isFunctionOverridedInJS(jstarget, "onEnterTransitionDidFinish", js_crossapp_Node_onEnterTransitionDidFinish)) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onEnterTransitionDidFinish", 0, &dataVal, &retval); } } else if (action == script::onExitTransitionDidStart) { if (isFunctionOverridedInJS(jstarget, "onExitTransitionDidStart", js_crossapp_Node_onExitTransitionDidStart)) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onExitTransitionDidStart", 0, &dataVal, &retval); } } return ret; } int ScriptingCore::handleViewControllerEvent(void* data) { if (NULL == data) return 0; BasicScriptData* basicScriptData = static_cast<BasicScriptData*>(data); if (NULL == basicScriptData->nativeObject || NULL == basicScriptData->value) return 0; CAViewController* viewController = static_cast<CAViewController*>(basicScriptData->nativeObject); int action = *((int*)(basicScriptData->value)); js_proxy_t * p = jsb_get_native_proxy(viewController); if (!p) return 0; JSAutoCompartment ac(_cx, *_global); int ret = 0; JS::RootedValue retval(_cx); jsval dataVal = INT_TO_JSVAL(1); JS::RootedObject jstarget(_cx, p->obj); if (action == script::viewDidUnload) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "viewDidUnload", 0, &dataVal, &retval); cleanupSchedulesAndActions(p); } else if (action == script::viewDidLoad) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "viewDidLoad", 0, &dataVal, &retval); } else if (action == script::viewSizeDidChanged) { ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "viewSizeDidChanged", 0, &dataVal, &retval); } return ret; } void ScriptingCore::garbageCollect() { #if CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 auto runtime = JS_GetRuntime(_cx); // twice: yep, call it twice since this is a generational GC // and we want to collect as much as possible when this is being called // from replaceScene(). JS_GC(runtime); JS_GC(runtime); #endif } #pragma mark - Debug void SimpleRunLoop::update(float dt) { g_qMutex.lock(); size_t size = g_queue.size(); g_qMutex.unlock(); while (size > 0) { g_qMutex.lock(); auto first = g_queue.begin(); std::string str = *first; g_queue.erase(first); size = g_queue.size(); g_qMutex.unlock(); ScriptingCore::getInstance()->debugProcessInput(str); } } void ScriptingCore::releaseScriptObject(CrossApp::CAObject* owner, CrossApp::CAObject* target) { JS::RootedObject global(_cx, _global->get()); JS::RootedObject jsbObj(_cx); get_or_create_js_obj(_cx, global, "jsb", &jsbObj); JS::RootedValue jsbVal(_cx, OBJECT_TO_JSVAL(jsbObj)); if (jsbVal.isNullOrUndefined()) { return; } js_proxy_t *pOwner = jsb_get_native_proxy(owner); js_proxy_t *pTarget = jsb_get_native_proxy(target); if (!pOwner || !pTarget) { return; } JS::RootedValue valOwner(_cx, OBJECT_TO_JSVAL(pOwner->obj)); JS::RootedValue valTarget(_cx, OBJECT_TO_JSVAL(pTarget->obj)); if (valTarget.isPrimitive()) { return; } JS::RootedValue retval(_cx); jsval valArr[2]; valArr[0] = valOwner; valArr[1] = valTarget; JS::HandleValueArray args = JS::HandleValueArray::fromMarkedLocation(2, valArr); executeFunctionWithOwner(jsbVal, "unregisterNativeObject", args, &retval); } void ScriptingCore::releaseAllSubviewsRecursive(CrossApp::CAView* view) { const CAVector<CAView*>& subviews = view->getSubviews(); for (auto subview : subviews) { releaseScriptObject(view, subview); releaseAllSubviewsRecursive(subview); } } js_proxy_t* jsb_new_proxy(void* nativeObj, JSObject* jsObj) { js_proxy_t* p = nullptr; JS_NEW_PROXY(p, nativeObj, jsObj); return p; } js_proxy_t* jsb_get_native_proxy(void* nativeObj) { js_proxy_t* p = nullptr; JS_GET_PROXY(p, nativeObj); return p; } js_proxy_t* jsb_get_js_proxy(JSObject* jsObj) { js_proxy_t* p = nullptr; JS_GET_NATIVE_PROXY(p, jsObj); return p; } void jsb_remove_proxy(js_proxy_t* nativeProxy, js_proxy_t* jsProxy) { JS_REMOVE_PROXY(nativeProxy, jsProxy); } void jsb_remove_proxy(js_proxy_t* proxy) { void* nativeKey = proxy->ptr; JSObject* jsKey = proxy->_jsobj; // CC_ASSERT(nativeKey && "Invalid nativeKey"); CC_ASSERT(jsKey && "Invalid JSKey"); // auto it_nat = _native_js_global_map.find(nativeKey); auto it_js = _js_native_global_map.find(jsKey); // #if 0 // XXX FIXME: sanity check. Remove me once it is tested that it works Ok if (it_nat != _native_js_global_map.end() && it_js != _js_native_global_map.end()) { CC_ASSERT(it_nat->second == it_js->second && "BUG. Different enties"); } #endif if (it_nat != _native_js_global_map.end()) { _native_js_global_map.erase(it_nat); } else CCLOG("jsb_remove_proxy: failed. Native key not found"); if (it_js != _js_native_global_map.end()) { // Free it once, since we only have one proxy alloced entry free(it_js->second); _js_native_global_map.erase(it_js); } else CCLOG("jsb_remove_proxy: failed. JS key not found"); }
#ifdef WIN32 #include <gl/gl.h> #define _USE_MATH_DEFINES #include <cmath> #else #include <OpenGL/gl.h> #endif #include <SDL/SDL.h> #include "Apollo.h" #include "Graphics.h" #include "SpriteSheet.h" #include "TextRenderer.h" #include <map> #include "Starfield.h" #include "Graphics.h" #include "Logging.h" #include "Utilities/Matrix2x3.h" #include "Shaders.h" #define DEG2RAD(x) ((x / 180.0f) * M_PI) #define RAD2DEG(x) ((x / M_PI) * 180.0f) const static float circlePoints[] = { 0.000, 1.000, 0.098, 0.995, 0.195, 0.981, 0.290, 0.957, 0.383, 0.924, 0.471, 0.882, 0.556, 0.831, 0.634, 0.773, 0.707, 0.707, 0.773, 0.634, 0.831, 0.556, 0.882, 0.471, 0.924, 0.383, 0.957, 0.290, 0.981, 0.195, 0.995, 0.098, 1.000, -0.000, 0.995, -0.098, 0.981, -0.195, 0.957, -0.290, 0.924, -0.383, 0.882, -0.471, 0.831, -0.556, 0.773, -0.634, 0.707, -0.707, 0.634, -0.773, 0.556, -0.831, 0.471, -0.882, 0.383, -0.924, 0.290, -0.957, 0.195, -0.981, 0.098, -0.995, -0.000, -1.000, -0.098, -0.995, -0.195, -0.981, -0.290, -0.957, -0.383, -0.924, -0.471, -0.882, -0.556, -0.831, -0.634, -0.773, -0.707, -0.707, -0.773, -0.634, -0.831, -0.556, -0.882, -0.471, -0.924, -0.383, -0.957, -0.290, -0.981, -0.195, -0.995, -0.098, -1.000, 0.000, -0.995, 0.098, -0.981, 0.195, -0.957, 0.290, -0.924, 0.383, -0.882, 0.471, -0.831, 0.556, -0.773, 0.634, -0.707, 0.707, -0.634, 0.773, -0.556, 0.831, -0.471, 0.882, -0.383, 0.924, -0.290, 0.957, -0.195, 0.981, -0.098, 0.995, -0.000, 1.000}; typedef std::map<std::string, Graphics::SpriteSheet*> SheetMap; static SheetMap spriteSheets; namespace Graphics { using namespace Shaders; int scw, sch; /* Other files can use: namespace Matrices { void SetProjectionMatrix ( const matrix2x3& m ); void SetViewMatrix ( const matrix2x3& m ); void SetModelMatrix ( const matrix2x3& m ); const matrix2x3& CurrentMatrix (); const matrix2x3& ProjectionMatrix (); const matrix2x3& ViewMatrix (); const matrix2x3& ModelMatrix (); } */ namespace Matrices { static matrix2x3 projectionMatrix; static matrix2x3 viewMatrix; static matrix2x3 modelMatrix; static matrix2x3 mvpMatrix; static void LoadMatrix ( const matrix2x3& m ) { GLfloat array[16]; m.FillOpenGLMatrix(array); glLoadMatrixf(array); } void SetProjectionMatrix ( const matrix2x3& m ) { projectionMatrix = m; } void SetViewMatrix ( const matrix2x3& m ) { viewMatrix = m; } // the state is only guaranteed after a SetModelMatrix call void SetModelMatrix ( const matrix2x3& m ) { modelMatrix = m; mvpMatrix = modelMatrix * viewMatrix * projectionMatrix; LoadMatrix(mvpMatrix); } const matrix2x3& CurrentMatrix () { return mvpMatrix; } const matrix2x3& ProjectionMatrix () { return projectionMatrix; } const matrix2x3& ViewMatrix () { return viewMatrix; } const matrix2x3& ModelMatrix () { return modelMatrix; } } void Init ( int w, int h, bool fullscreen ) { SDL_InitSubSystem ( SDL_INIT_VIDEO ); SDL_GL_SetAttribute ( SDL_GL_RED_SIZE, 8 ); SDL_GL_SetAttribute ( SDL_GL_BLUE_SIZE, 8 ); SDL_GL_SetAttribute ( SDL_GL_GREEN_SIZE, 8 ); SDL_GL_SetAttribute ( SDL_GL_ALPHA_SIZE, 0 ); SDL_GL_SetAttribute ( SDL_GL_DOUBLEBUFFER, 1 ); SDL_GL_SetAttribute ( SDL_GL_DEPTH_SIZE, 0 ); SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLESAMPLES, 4 ); SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLEBUFFERS, 1 ); SDL_GL_SetAttribute ( SDL_GL_SWAP_CONTROL, 1 ); Uint32 flags = SDL_OPENGL; if (fullscreen) flags |= SDL_FULLSCREEN; if (!SDL_SetVideoMode(w, h, 0, flags)) { SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLESAMPLES, 0 ); SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLEBUFFERS, 0 ); LOG("Graphics", LOG_WARNING, "Card does not support FSAA!"); if (!SDL_SetVideoMode(w, h, 0, flags)) { LOG("Graphics", LOG_WARNING, "Card does not support normal video options!"); SDL_GL_SetAttribute ( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute ( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute ( SDL_GL_BLUE_SIZE, 5 ); if (!SDL_SetVideoMode(w, h, 0, flags)) { LOG("Graphics", LOG_ERROR, "Bad graphics driver."); exit(1); } } } scw = w; sch = h; glClear ( GL_COLOR_BUFFER_BIT ); glEnable ( GL_BLEND ); glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable ( GL_LINE_SMOOTH ); glEnable ( GL_POINT_SMOOTH ); glHint ( GL_LINE_SMOOTH_HINT, GL_NICEST ); glHint ( GL_POINT_SMOOTH_HINT, GL_NICEST ); #ifdef __MACH__ glHint ( GL_TRANSFORM_HINT_APPLE, GL_FASTEST ); #endif glEnableClientState ( GL_VERTEX_ARRAY ); } static bool texturingEnabled = false; static void EnableTexturing () { if (!texturingEnabled) { glEnableClientState ( GL_TEXTURE_COORD_ARRAY ); texturingEnabled = true; } } static void DisableTexturing () { if (texturingEnabled) { glDisableClientState ( GL_TEXTURE_COORD_ARRAY ); texturingEnabled = false; } } static bool blendingEnabled = true; static void EnableBlending () { if (!blendingEnabled) { glEnable(GL_BLEND); blendingEnabled = true; } } static void DisableBlending () { if (blendingEnabled) { glDisable(GL_BLEND); blendingEnabled = false; } } static void SetColour ( const colour& col ) { if (sizeof(col) == sizeof(float) * 4) { glColor4fv((const GLfloat*)&col); } else { glColor4f(col.red(), col.green(), col.blue(), col.alpha()); } } static void ClearColour () { const uint32_t white = 0xFFFFFFFF; glColor4ubv((const GLubyte*)&white); } vec2 SpriteDimensions ( const std::string& sheetname ) { SpriteSheet* sheet; SheetMap::iterator iter = spriteSheets.find(sheetname); if (iter == spriteSheets.end()) { // load it sheet = new SpriteSheet(sheetname); spriteSheets[sheetname] = sheet; } else { sheet = iter->second; } assert(sheet); return vec2(sheet->TileSizeX(), sheet->TileSizeY()); } void DrawSprite ( const std::string& sheetname, int sheet_x, int sheet_y, vec2 location, vec2 size, float rotation ) { SetShader("Sprite"); EnableTexturing(); EnableBlending(); ClearColour(); SpriteSheet* sheet; SheetMap::iterator iter = spriteSheets.find(sheetname); if (iter == spriteSheets.end()) { // load it sheet = new SpriteSheet(sheetname); spriteSheets[sheetname] = sheet; } else { sheet = iter->second; } Matrices::SetViewMatrix(matrix2x3::Translate(location)); Matrices::SetModelMatrix(matrix2x3::Identity()); if (sheet->IsRotational()) { assert(sheet_x == 0); assert(sheet_y == 0); sheet->DrawRotation(size, rotation); } else { glRotatef(RAD2DEG(rotation), 0.0f, 0.0f, 1.0f); sheet->Draw(sheet_x, sheet_y, size); } } void DrawTextSDL ( const std::string& text, const std::string& font, vec2 location, float height, colour col, float rotation ) { SetShader("Sprite"); EnableTexturing(); EnableBlending(); SetColour(col); GLuint texID = TextRenderer::TextObject(font, text); Matrices::SetViewMatrix(matrix2x3::Translate(location)); Matrices::SetModelMatrix(matrix2x3::Rotation(rotation)); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texID); vec2 dims = TextRenderer::TextDimensions(font, text); vec2 halfSize = (dims * (height / dims.Y())) * 0.5f; GLfloat textureArray[] = { 0.0f, 0.0f, dims.X(), 0.0f, dims.X(), dims.Y(), 0.0f, dims.Y() }; GLfloat vertexArray[] = { -halfSize.X(), halfSize.Y(), halfSize.X(), halfSize.Y(), halfSize.X(), -halfSize.Y(), -halfSize.X(), -halfSize.Y() }; glVertexPointer(2, GL_FLOAT, 0, vertexArray); glTexCoordPointer(2, GL_FLOAT, 0, textureArray); glDrawArrays(GL_QUADS, 0, 4); } void DrawLine ( vec2 coordinate1, vec2 coordinate2, float width, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } glLineWidth(width); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); SetColour(col); float vertices[4] = { coordinate1.X(), coordinate1.Y(), coordinate2.X(), coordinate2.Y() }; glVertexPointer ( 2, GL_FLOAT, 0, vertices ); glDrawArrays ( GL_LINES, 0, 2 ); } void DrawBox ( float top, float left, float bottom, float right, float width, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); SetColour(col); if (width != 0) { glLineWidth(width); float vertices[16] = { left, top, right, top, left, top, left, bottom, right, top, right, bottom, left, bottom, right, bottom }; glVertexPointer ( 2, GL_FLOAT, 0, vertices ); glDrawArrays ( GL_LINES, 0, 8 ); } } void DrawCircle ( vec2 centre, float radius, float width, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } glLineWidth(width); Matrices::SetViewMatrix(matrix2x3::Translate(centre)); Matrices::SetModelMatrix(matrix2x3::Scale(radius)); SetColour ( col ); glVertexPointer(2, GL_FLOAT, 0, circlePoints); glDrawArrays(GL_LINE_LOOP, 0, sizeof(circlePoints) / (2 * sizeof(float))); } void DrawParticles ( const vec2* locations, unsigned int count, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); glVertexPointer ( 2, GL_FLOAT, 0, locations ); SetColour(col); glDrawArrays ( GL_POINTS, 0, count ); } static vec2 cameraCorner1; static vec2 cameraCorner2; static float cameraRotation; std::vector<Starfield*> starfields; unsigned starfieldNumber; void DrawStarfield ( float depth ) { if (starfields.size() >= starfieldNumber) { starfields.push_back(new Starfield); } SetShader("Starfield"); EnableTexturing(); DisableBlending(); ClearColour(); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); starfields[starfieldNumber++]->Draw(depth, (cameraCorner1 + cameraCorner2) / 2.0f); } float AspectRatio () { return float(scw) / float(sch); } vec2 MapPoint ( vec2 windowCoords ) { matrix2x3 viewProjection ( Matrices::viewMatrix * Matrices::projectionMatrix ); matrix2x3 vpi = viewProjection.Inverse(); vec2 normalisedCoords = vpi * windowCoords; normalisedCoords += vec2(1.0f, 1.0f); normalisedCoords *= 0.5f; return vec2(normalisedCoords.X() * scw, normalisedCoords.Y() * sch); } bool IsCulled ( vec2 location, float radius ) { if ((location.X() + radius) < cameraCorner1.X()) return true; if ((location.X() - radius) > cameraCorner2.X()) return true; if ((location.Y() + radius) < cameraCorner1.Y()) return true; if ((location.Y() - radius) > cameraCorner2.Y()) return true; return false; } void SetCamera ( vec2 corner1, vec2 corner2, float rotation ) { matrix2x3 projection ( matrix2x3::Ortho(corner1.X(), corner2.X(), corner1.Y(), corner2.Y()) ); if (fabs(rotation) > 0.00004f) projection *= matrix2x3::Rotation(rotation); Matrices::SetProjectionMatrix(projection); cameraCorner1 = corner1; cameraCorner2 = corner2; } void BeginFrame () { glClear(GL_COLOR_BUFFER_BIT); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); starfieldNumber = 0; } void EndFrame () { #ifdef __MACH__ glSwapAPPLE(); #else SDL_GL_SwapBuffers(); #endif TextRenderer::Prune(); } } Main panel features up-and-running, although they display static data. Next commit should have that figured out. Signed-off-by: Adam Hintz <96c833980ca266d81f358ac8bd40898278f74af6@gmail.com> #ifdef WIN32 #include <gl/gl.h> #define _USE_MATH_DEFINES #include <cmath> #else #include <OpenGL/gl.h> #endif #include <SDL/SDL.h> #include "Apollo.h" #include "Graphics.h" #include "SpriteSheet.h" #include "TextRenderer.h" #include <map> #include "Starfield.h" #include "Graphics.h" #include "Logging.h" #include "Utilities/Matrix2x3.h" #include "Shaders.h" #define DEG2RAD(x) ((x / 180.0f) * M_PI) #define RAD2DEG(x) ((x / M_PI) * 180.0f) const static float circlePoints[] = { 0.000, 1.000, 0.098, 0.995, 0.195, 0.981, 0.290, 0.957, 0.383, 0.924, 0.471, 0.882, 0.556, 0.831, 0.634, 0.773, 0.707, 0.707, 0.773, 0.634, 0.831, 0.556, 0.882, 0.471, 0.924, 0.383, 0.957, 0.290, 0.981, 0.195, 0.995, 0.098, 1.000, -0.000, 0.995, -0.098, 0.981, -0.195, 0.957, -0.290, 0.924, -0.383, 0.882, -0.471, 0.831, -0.556, 0.773, -0.634, 0.707, -0.707, 0.634, -0.773, 0.556, -0.831, 0.471, -0.882, 0.383, -0.924, 0.290, -0.957, 0.195, -0.981, 0.098, -0.995, -0.000, -1.000, -0.098, -0.995, -0.195, -0.981, -0.290, -0.957, -0.383, -0.924, -0.471, -0.882, -0.556, -0.831, -0.634, -0.773, -0.707, -0.707, -0.773, -0.634, -0.831, -0.556, -0.882, -0.471, -0.924, -0.383, -0.957, -0.290, -0.981, -0.195, -0.995, -0.098, -1.000, 0.000, -0.995, 0.098, -0.981, 0.195, -0.957, 0.290, -0.924, 0.383, -0.882, 0.471, -0.831, 0.556, -0.773, 0.634, -0.707, 0.707, -0.634, 0.773, -0.556, 0.831, -0.471, 0.882, -0.383, 0.924, -0.290, 0.957, -0.195, 0.981, -0.098, 0.995, -0.000, 1.000}; typedef std::map<std::string, Graphics::SpriteSheet*> SheetMap; static SheetMap spriteSheets; namespace Graphics { using namespace Shaders; int scw, sch; /* Other files can use: namespace Matrices { void SetProjectionMatrix ( const matrix2x3& m ); void SetViewMatrix ( const matrix2x3& m ); void SetModelMatrix ( const matrix2x3& m ); const matrix2x3& CurrentMatrix (); const matrix2x3& ProjectionMatrix (); const matrix2x3& ViewMatrix (); const matrix2x3& ModelMatrix (); } */ namespace Matrices { static matrix2x3 projectionMatrix; static matrix2x3 viewMatrix; static matrix2x3 modelMatrix; static matrix2x3 mvpMatrix; static void LoadMatrix ( const matrix2x3& m ) { GLfloat array[16]; m.FillOpenGLMatrix(array); glLoadMatrixf(array); } void SetProjectionMatrix ( const matrix2x3& m ) { projectionMatrix = m; } void SetViewMatrix ( const matrix2x3& m ) { viewMatrix = m; } // the state is only guaranteed after a SetModelMatrix call void SetModelMatrix ( const matrix2x3& m ) { modelMatrix = m; mvpMatrix = modelMatrix * viewMatrix * projectionMatrix; LoadMatrix(mvpMatrix); } const matrix2x3& CurrentMatrix () { return mvpMatrix; } const matrix2x3& ProjectionMatrix () { return projectionMatrix; } const matrix2x3& ViewMatrix () { return viewMatrix; } const matrix2x3& ModelMatrix () { return modelMatrix; } } void Init ( int w, int h, bool fullscreen ) { SDL_InitSubSystem ( SDL_INIT_VIDEO ); SDL_GL_SetAttribute ( SDL_GL_RED_SIZE, 8 ); SDL_GL_SetAttribute ( SDL_GL_BLUE_SIZE, 8 ); SDL_GL_SetAttribute ( SDL_GL_GREEN_SIZE, 8 ); SDL_GL_SetAttribute ( SDL_GL_ALPHA_SIZE, 0 ); SDL_GL_SetAttribute ( SDL_GL_DOUBLEBUFFER, 1 ); SDL_GL_SetAttribute ( SDL_GL_DEPTH_SIZE, 0 ); SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLESAMPLES, 4 ); SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLEBUFFERS, 1 ); SDL_GL_SetAttribute ( SDL_GL_SWAP_CONTROL, 1 ); Uint32 flags = SDL_OPENGL; if (fullscreen) flags |= SDL_FULLSCREEN; if (!SDL_SetVideoMode(w, h, 0, flags)) { SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLESAMPLES, 0 ); SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLEBUFFERS, 0 ); LOG("Graphics", LOG_WARNING, "Card does not support FSAA!"); if (!SDL_SetVideoMode(w, h, 0, flags)) { LOG("Graphics", LOG_WARNING, "Card does not support normal video options!"); SDL_GL_SetAttribute ( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute ( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute ( SDL_GL_BLUE_SIZE, 5 ); if (!SDL_SetVideoMode(w, h, 0, flags)) { LOG("Graphics", LOG_ERROR, "Bad graphics driver."); exit(1); } } } scw = w; sch = h; glClear ( GL_COLOR_BUFFER_BIT ); glEnable ( GL_BLEND ); glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable ( GL_LINE_SMOOTH ); glEnable ( GL_POINT_SMOOTH ); glHint ( GL_LINE_SMOOTH_HINT, GL_NICEST ); glHint ( GL_POINT_SMOOTH_HINT, GL_NICEST ); #ifdef __MACH__ glHint ( GL_TRANSFORM_HINT_APPLE, GL_FASTEST ); #endif glEnableClientState ( GL_VERTEX_ARRAY ); } static bool texturingEnabled = false; static void EnableTexturing () { if (!texturingEnabled) { glEnableClientState ( GL_TEXTURE_COORD_ARRAY ); texturingEnabled = true; } } static void DisableTexturing () { if (texturingEnabled) { glDisableClientState ( GL_TEXTURE_COORD_ARRAY ); texturingEnabled = false; } } static bool blendingEnabled = true; static void EnableBlending () { if (!blendingEnabled) { glEnable(GL_BLEND); blendingEnabled = true; } } static void DisableBlending () { if (blendingEnabled) { glDisable(GL_BLEND); blendingEnabled = false; } } static void SetColour ( const colour& col ) { if (sizeof(col) == sizeof(float) * 4) { glColor4fv((const GLfloat*)&col); } else { glColor4f(col.red(), col.green(), col.blue(), col.alpha()); } } static void ClearColour () { const uint32_t white = 0xFFFFFFFF; glColor4ubv((const GLubyte*)&white); } vec2 SpriteDimensions ( const std::string& sheetname ) { SpriteSheet* sheet; SheetMap::iterator iter = spriteSheets.find(sheetname); if (iter == spriteSheets.end()) { // load it sheet = new SpriteSheet(sheetname); spriteSheets[sheetname] = sheet; } else { sheet = iter->second; } assert(sheet); return vec2(sheet->TileSizeX(), sheet->TileSizeY()); } void DrawSprite ( const std::string& sheetname, int sheet_x, int sheet_y, vec2 location, vec2 size, float rotation ) { SetShader("Sprite"); EnableTexturing(); EnableBlending(); ClearColour(); SpriteSheet* sheet; SheetMap::iterator iter = spriteSheets.find(sheetname); if (iter == spriteSheets.end()) { // load it sheet = new SpriteSheet(sheetname); spriteSheets[sheetname] = sheet; } else { sheet = iter->second; } Matrices::SetViewMatrix(matrix2x3::Translate(location)); Matrices::SetModelMatrix(matrix2x3::Identity()); if (sheet->IsRotational()) { assert(sheet_x == 0); assert(sheet_y == 0); sheet->DrawRotation(size, rotation); } else { glRotatef(RAD2DEG(rotation), 0.0f, 0.0f, 1.0f); sheet->Draw(sheet_x, sheet_y, size); } } void DrawTextSDL ( const std::string& text, const std::string& font, vec2 location, float height, colour col, float rotation ) { SetShader("Sprite"); EnableTexturing(); EnableBlending(); SetColour(col); GLuint texID = TextRenderer::TextObject(font, text); Matrices::SetViewMatrix(matrix2x3::Translate(location)); Matrices::SetModelMatrix(matrix2x3::Rotation(rotation)); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texID); vec2 dims = TextRenderer::TextDimensions(font, text); vec2 halfSize = (dims * (height / dims.Y())) * 0.5f; GLfloat textureArray[] = { 0.0f, 0.0f, dims.X(), 0.0f, dims.X(), dims.Y(), 0.0f, dims.Y() }; GLfloat vertexArray[] = { -halfSize.X(), halfSize.Y(), halfSize.X(), halfSize.Y(), halfSize.X(), -halfSize.Y(), -halfSize.X(), -halfSize.Y() }; glVertexPointer(2, GL_FLOAT, 0, vertexArray); glTexCoordPointer(2, GL_FLOAT, 0, textureArray); glDrawArrays(GL_QUADS, 0, 4); } void DrawLine ( vec2 coordinate1, vec2 coordinate2, float width, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } glLineWidth(width); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); SetColour(col); float vertices[4] = { coordinate1.X(), coordinate1.Y(), coordinate2.X(), coordinate2.Y() }; glVertexPointer ( 2, GL_FLOAT, 0, vertices ); glDrawArrays ( GL_LINES, 0, 2 ); } void DrawBox ( float top, float left, float bottom, float right, float width, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); SetColour(col); float quad[8] = { left, top, left, bottom, right, bottom, right, top }; glVertexPointer ( 2, GL_FLOAT, 0, quad ); glDrawArrays ( GL_QUADS, 0, 4 ); if (width != 0) { SetColour(col + colour(0.45, 0.45, 0.45, 0.0)); glLineWidth(width); float vertices[16] = { left, top, right, top, left, top, left, bottom, right, top, right, bottom, left, bottom, right, bottom }; glVertexPointer ( 2, GL_FLOAT, 0, vertices ); glDrawArrays ( GL_LINES, 0, 8 ); } } void DrawCircle ( vec2 centre, float radius, float width, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } glLineWidth(width); Matrices::SetViewMatrix(matrix2x3::Translate(centre)); Matrices::SetModelMatrix(matrix2x3::Scale(radius)); SetColour ( col ); glVertexPointer(2, GL_FLOAT, 0, circlePoints); glDrawArrays(GL_LINE_LOOP, 0, sizeof(circlePoints) / (2 * sizeof(float))); } void DrawParticles ( const vec2* locations, unsigned int count, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); glVertexPointer ( 2, GL_FLOAT, 0, locations ); SetColour(col); glDrawArrays ( GL_POINTS, 0, count ); } static vec2 cameraCorner1; static vec2 cameraCorner2; static float cameraRotation; std::vector<Starfield*> starfields; unsigned starfieldNumber; void DrawStarfield ( float depth ) { if (starfields.size() >= starfieldNumber) { starfields.push_back(new Starfield); } SetShader("Starfield"); EnableTexturing(); DisableBlending(); ClearColour(); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); starfields[starfieldNumber++]->Draw(depth, (cameraCorner1 + cameraCorner2) / 2.0f); } float AspectRatio () { return float(scw) / float(sch); } vec2 MapPoint ( vec2 windowCoords ) { matrix2x3 viewProjection ( Matrices::viewMatrix * Matrices::projectionMatrix ); matrix2x3 vpi = viewProjection.Inverse(); vec2 normalisedCoords = vpi * windowCoords; normalisedCoords += vec2(1.0f, 1.0f); normalisedCoords *= 0.5f; return vec2(normalisedCoords.X() * scw, normalisedCoords.Y() * sch); } bool IsCulled ( vec2 location, float radius ) { if ((location.X() + radius) < cameraCorner1.X()) return true; if ((location.X() - radius) > cameraCorner2.X()) return true; if ((location.Y() + radius) < cameraCorner1.Y()) return true; if ((location.Y() - radius) > cameraCorner2.Y()) return true; return false; } void SetCamera ( vec2 corner1, vec2 corner2, float rotation ) { matrix2x3 projection ( matrix2x3::Ortho(corner1.X(), corner2.X(), corner1.Y(), corner2.Y()) ); if (fabs(rotation) > 0.00004f) projection *= matrix2x3::Rotation(rotation); Matrices::SetProjectionMatrix(projection); cameraCorner1 = corner1; cameraCorner2 = corner2; } void BeginFrame () { glClear(GL_COLOR_BUFFER_BIT); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); starfieldNumber = 0; } void EndFrame () { #ifdef __MACH__ glSwapAPPLE(); #else SDL_GL_SwapBuffers(); #endif TextRenderer::Prune(); } }
// Natron // /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012. * contact: immarespond at gmail dot com * */ #include "OfxEffectInstance.h" #include <locale> #include <limits> #include <stdexcept> #include <QtCore/QDebug> #include <QByteArray> #include <QReadWriteLock> #include <QPointF> #include "Global/Macros.h" #include <ofxhPluginCache.h> #include <ofxhPluginAPICache.h> #include <ofxhImageEffect.h> #include <ofxhImageEffectAPI.h> #include <ofxhHost.h> #include <tuttle/ofxReadWrite.h> #include "Engine/AppManager.h" #include "Engine/OfxParamInstance.h" #include "Engine/OfxClipInstance.h" #include "Engine/OfxImageEffectInstance.h" #include "Engine/OfxOverlayInteract.h" #include "Engine/ViewerInstance.h" #include "Engine/TimeLine.h" #include "Engine/Project.h" #include "Engine/KnobFile.h" #include "Engine/KnobTypes.h" #include "Engine/AppInstance.h" #include "Engine/NodeSerialization.h" #include "Engine/Node.h" #include "Engine/Transform.h" using namespace Natron; using std::cout; using std::endl; namespace { /** * @class This class is helpful to set thread-storage data on the clips of an effect * When destroyed, it is removed from the clips, ensuring they are removed. * It is to be instantiated right before calling the action that will need the per thread-storage * This way even if exceptions are thrown, clip thread-storage will be purged. * * All the info set on clip thread-storage are "cached" data that might be needed by a call of the OpenFX API which would * otherwise require a recursive action call, which is forbidden by the specification. * The more you pass parameters, the safer you are that the plug-in will not attempt recursive action calls but the more expensive * it is. **/ class ClipsThreadStorageSetter { public: ClipsThreadStorageSetter(OfxImageEffectInstance* effect, bool skipDiscarding, //< this is in case a recursive action is called bool setView, int view, bool setMipmapLevel, unsigned int mipMapLevel) : effect(effect) , skipDiscarding(skipDiscarding) , viewSet(setView) , mipMapLevelSet(setMipmapLevel) { if (setView) { effect->setClipsView(view); } if (setMipmapLevel) { effect->setClipsMipMapLevel(mipMapLevel); } } ~ClipsThreadStorageSetter() { if (!skipDiscarding) { if (viewSet) { effect->discardClipsView(); } if (mipMapLevelSet) { effect->discardClipsMipMapLevel(); } } } private: OfxImageEffectInstance* effect; bool skipDiscarding; bool viewSet; bool mipMapLevelSet; }; } OfxEffectInstance::OfxEffectInstance(boost::shared_ptr<Natron::Node> node) : AbstractOfxEffectInstance(node) , _effect() , _natronPluginID() , _isOutput(false) , _penDown(false) , _overlayInteract(0) , _overlaySlaves() , _created(false) , _initialized(false) , _renderButton() , _renderSafety(EffectInstance::eRenderSafetyUnsafe) , _wasRenderSafetySet(false) , _renderSafetyLock(new QReadWriteLock) , _context(eContextNone) , _preferencesLock(new QReadWriteLock(QReadWriteLock::Recursive)) #ifdef DEBUG , _canSetValue() #endif { QObject::connect( this, SIGNAL( syncPrivateDataRequested() ), this, SLOT( onSyncPrivateDataRequested() ) ); } void OfxEffectInstance::createOfxImageEffectInstance(OFX::Host::ImageEffect::ImageEffectPlugin* plugin, const std::string & context, const NodeSerialization* serialization, const std::list<boost::shared_ptr<KnobSerialization> >& paramValues, bool allowFileDialogs, bool disableRenderScaleSupport) { /*Replicate of the code in OFX::Host::ImageEffect::ImageEffectPlugin::createInstance. We need to pass more parameters to the constructor . That means we cannot create it in the virtual function newInstance. Thus we create it before instanciating the OfxImageEffect. The problem is that calling OFX::Host::ImageEffect::ImageEffectPlugin::createInstance creates the OfxImageEffect and calls populate(). populate() will actually create all OfxClipInstance and OfxParamInstance. All these subclasses need a valid pointer to an this. Hence we need to set the pointer to this in OfxImageEffect BEFORE calling populate(). */ ///Only called from the main thread. assert( QThread::currentThread() == qApp->thread() ); ContextEnum ctx = mapToContextEnum(context); if (disableRenderScaleSupport || ctx == eContextWriter) { setAsOutputNode(); // Writers don't support render scale (full-resolution images are written to disk) setSupportsRenderScaleMaybe(eSupportsNo); } if (ctx == eContextReader) { // Tuttle readers don't support render scale as of 11/8/2014, but may crash (at least in debug configuration). // TuttleAVReader crashes on an assert in copy_and_convert_pixels( avSrcView, this->_dstView ); std::string prefix("tuttle."); if ( !plugin->getIdentifier().compare(0, prefix.size(), prefix) ) { setSupportsRenderScaleMaybe(eSupportsNo); } } OFX::Host::PluginHandle* ph = plugin->getPluginHandle(); assert( ph->getOfxPlugin() ); assert(ph->getOfxPlugin()->mainEntry); (void)ph; OFX::Host::ImageEffect::Descriptor* desc = NULL; desc = plugin->getContext(context); if (!desc) { throw std::runtime_error(std::string("Failed to get description for OFX plugin in context ") + context); } _context = mapToContextEnum(context); std::string images; try { _effect = new Natron::OfxImageEffectInstance(plugin,*desc,context,false); assert(_effect); _effect->setOfxEffectInstance( dynamic_cast<OfxEffectInstance*>(this) ); _natronPluginID = plugin->getIdentifier(); // _natronPluginID = generateImageEffectClassName( _effect->getPlugin()->getIdentifier(), // _effect->getPlugin()->getVersionMajor(), // _effect->getPlugin()->getVersionMinor(), // _effect->getDescriptor().getShortLabel(), // _effect->getDescriptor().getLabel(), // _effect->getDescriptor().getLongLabel(), // _effect->getDescriptor().getPluginGrouping() ); blockEvaluation(); OfxStatus stat; { SET_CAN_SET_VALUE(true); stat = _effect->populate(); initializeContextDependentParams(); _effect->addParamsToTheirParents(); if (stat != kOfxStatOK) { throw std::runtime_error("Error while populating the Ofx image effect"); } assert( _effect->getPlugin() ); assert( _effect->getPlugin()->getPluginHandle() ); assert( _effect->getPlugin()->getPluginHandle()->getOfxPlugin() ); assert(_effect->getPlugin()->getPluginHandle()->getOfxPlugin()->mainEntry); getNode()->createRotoContextConditionnally(); getNode()->initializeInputs(); getNode()->initializeKnobs( serialization ? *serialization : NodeSerialization( getApp() ), disableRenderScaleSupport ? 1 : 0 ); ///before calling the createInstanceAction, load values if ( serialization && !serialization->isNull() ) { getNode()->loadKnobs(*serialization); } if (!paramValues.empty()) { getNode()->setValuesFromSerialization(paramValues); } ////////////////////////////////////////////////////// ///////For READERS & WRITERS only we open an image file dialog if (allowFileDialogs && isReader() && !(serialization && !serialization->isNull()) && paramValues.empty()) { images = getApp()->openImageFileDialog(); } else if (allowFileDialogs && isWriter() && !(serialization && !serialization->isNull()) && paramValues.empty()) { images = getApp()->saveImageFileDialog(); } if (!images.empty()) { boost::shared_ptr<KnobSerialization> defaultFile = createDefaultValueForParam(kOfxImageEffectFileParamName, images); CreateNodeArgs::DefaultValuesList list; list.push_back(defaultFile); getNode()->setValuesFromSerialization(list); } ////////////////////////////////////////////////////// { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->createInstanceAction(); } _created = true; unblockEvaluation(); } // SET_CAN_SET_VALUE(true); if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { throw std::runtime_error("Could not create effect instance for plugin"); } OfxPointD scaleOne; scaleOne.x = 1.; scaleOne.y = 1.; // Try to set renderscale support at plugin creation. // This is not always possible (e.g. if a param has a wrong value). if (supportsRenderScaleMaybe() == eSupportsMaybe) { // does the effect support renderscale? OfxRangeD range; range.min = 0; OfxStatus tdstat = _effect->getTimeDomainAction(range); if ( (tdstat == kOfxStatOK) || (tdstat == kOfxStatReplyDefault) ) { ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? 0, true, 0); double time = range.min; OfxRectD rod; OfxStatus rodstat = _effect->getRegionOfDefinitionAction(time, scaleOne, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { OfxPointD scale; scale.x = 0.5; scale.y = 0.5; rodstat = _effect->getRegionOfDefinitionAction(time, scale, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { setSupportsRenderScaleMaybe(eSupportsYes); } else { setSupportsRenderScaleMaybe(eSupportsNo); } } } } // Check here that bitdepth and components given by getClipPreferences are supported by the effect. // If we don't, the following assert will crash at the beginning of EffectInstance::renderRoIInternal(): // assert(isSupportedBitDepth(outputDepth) && isSupportedComponent(-1, outputComponents)); // If a component/bitdepth is not supported (this is probably a plugin bug), use the closest one, but don't crash Natron. checkOFXClipPreferences_public(getApp()->getTimeLine()->currentFrame(), scaleOne, kOfxChangeUserEdited,true, false); // check that the plugin supports kOfxImageComponentRGBA for all the clips /*const std::vector<OFX::Host::ImageEffect::ClipDescriptor*> & clips = effectInstance()->getDescriptor().getClipsByOrder(); for (U32 i = 0; i < clips.size(); ++i) { if ( (clips[i]->getProps().findStringPropValueIndex(kOfxImageEffectPropSupportedComponents, kOfxImageComponentRGBA) == -1) && !clips[i]->isOptional() && !clips[i]->isMask() ) { appPTR->writeToOfxLog_mt_safe( QString( plugin->getDescriptor().getLabel().c_str() ) + "RGBA components not supported by OFX plugin in context " + QString( context.c_str() ) ); throw std::runtime_error(std::string("RGBA components not supported by OFX plugin in context ") + context); } }*/ } catch (const std::exception & e) { qDebug() << "Error: Caught exception while creating OfxImageEffectInstance" << ": " << e.what(); throw; } catch (...) { qDebug() << "Error: Caught exception while creating OfxImageEffectInstance"; throw; } _initialized = true; ///Now that the instance is created, make sure instanceChangedActino is called for all extra default values ///that we set for (std::list<boost::shared_ptr<KnobSerialization> >::const_iterator it = paramValues.begin(); it != paramValues.end();++it) { boost::shared_ptr<KnobI> knob = getKnobByName((*it)->getName()); assert(knob); for (int i = 0; i < knob->getDimension(); ++i) { knob->evaluateValueChange(i, Natron::eValueChangedReasonUserEdited, true); } } if (!images.empty()) { boost::shared_ptr<KnobI> fileNameKnob = getKnobByName(kOfxImageEffectFileParamName); if (fileNameKnob) { fileNameKnob->evaluateValueChange(0,Natron::eValueChangedReasonUserEdited, true); } } } // createOfxImageEffectInstance OfxEffectInstance::~OfxEffectInstance() { if (_overlayInteract) { delete _overlayInteract; } delete _effect; delete _renderSafetyLock; delete _preferencesLock; } bool OfxEffectInstance::isEffectCreated() const { return _created; } void OfxEffectInstance::initializeContextDependentParams() { assert(_context != eContextNone); if ( isWriter() ) { _renderButton = Natron::createKnob<Button_Knob>(this, "Render"); _renderButton->setHintToolTip("Starts rendering the specified frame range."); _renderButton->setAsRenderButton(); } } std::string OfxEffectInstance::getDescription() const { assert(_context != eContextNone); if ( effectInstance() ) { return effectInstance()->getProps().getStringProperty(kOfxPropPluginDescription); } else { return ""; } } void OfxEffectInstance::tryInitializeOverlayInteracts() { assert(_context != eContextNone); /*create overlay instance if any*/ OfxPluginEntryPoint *overlayEntryPoint = _effect->getOverlayInteractMainEntry(); if (overlayEntryPoint) { _overlayInteract = new OfxOverlayInteract(*_effect,8,true); RenderScale s; effectInstance()->getRenderScaleRecursive(s.x, s.y); { ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? 0, true, 0); { SET_CAN_SET_VALUE(true); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); _overlayInteract->createInstanceAction(); } } ///Fetch all parameters that are overlay slave std::vector<std::string> slaveParams; _overlayInteract->getSlaveToParam(slaveParams); for (U32 i = 0; i < slaveParams.size(); ++i) { boost::shared_ptr<KnobI> param = getKnobByName(slaveParams[i]); assert(param); _overlaySlaves.push_back((void*)param.get()); } getApp()->redrawAllViewers(); } ///for each param, if it has a valid custom interact, create it const std::list<OFX::Host::Param::Instance*> & params = effectInstance()->getParamList(); for (std::list<OFX::Host::Param::Instance*>::const_iterator it = params.begin(); it != params.end(); ++it) { OfxParamToKnob* paramToKnob = dynamic_cast<OfxParamToKnob*>(*it); assert(paramToKnob); OFX::Host::Interact::Descriptor & interactDesc = paramToKnob->getInteractDesc(); if (interactDesc.getState() == OFX::Host::Interact::eDescribed) { boost::shared_ptr<KnobI> knob = paramToKnob->getKnob(); boost::shared_ptr<OfxParamOverlayInteract> overlay( new OfxParamOverlayInteract( knob.get(),interactDesc, effectInstance()->getHandle() ) ); { SET_CAN_SET_VALUE(true); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); overlay->createInstanceAction(); } knob->setCustomInteract(overlay); } } } bool OfxEffectInstance::isOutput() const { assert(_context != eContextNone); return _isOutput; } bool OfxEffectInstance::isGenerator() const { #if 0 assert( effectInstance() ); const std::set<std::string> & contexts = effectInstance()->getPlugin()->getContexts(); std::set<std::string>::const_iterator foundGenerator = contexts.find(kOfxImageEffectContextGenerator); std::set<std::string>::const_iterator foundReader = contexts.find(kOfxImageEffectContextReader); if ( ( foundGenerator != contexts.end() ) || ( foundReader != contexts.end() ) ) { return true; } return false; #else assert(_context != eContextNone); return _context == eContextGenerator || _context == eContextReader; #endif } bool OfxEffectInstance::isReader() const { #if 0 assert( effectInstance() ); const std::set<std::string> & contexts = effectInstance()->getPlugin()->getContexts(); std::set<std::string>::const_iterator foundReader = contexts.find(kOfxImageEffectContextReader); if ( foundReader != contexts.end() ) { return true; } return false; #else assert(_context != eContextNone); return _context == eContextReader; #endif } bool OfxEffectInstance::isWriter() const { #if 0 assert(_context != eContextNone); assert( effectInstance() ); const std::set<std::string> & contexts = effectInstance()->getPlugin()->getContexts(); std::set<std::string>::const_iterator foundWriter = contexts.find(kOfxImageEffectContextWriter); if ( foundWriter != contexts.end() ) { return true; } return false; #else assert(_context != eContextNone); return _context == eContextWriter; #endif } bool OfxEffectInstance::isGeneratorAndFilter() const { assert(_context != eContextNone); const std::set<std::string> & contexts = effectInstance()->getPlugin()->getContexts(); std::set<std::string>::const_iterator foundGenerator = contexts.find(kOfxImageEffectContextGenerator); std::set<std::string>::const_iterator foundGeneral = contexts.find(kOfxImageEffectContextGeneral); return foundGenerator != contexts.end() && foundGeneral != contexts.end(); } /*group is a string as such: Toto/Superplugins/blabla This functions extracts the all parts of such a grouping, e.g in this case it would return [Toto,Superplugins,blabla].*/ static QStringList ofxExtractAllPartsOfGrouping(const QString & pluginIdentifier, int /*versionMajor*/, int /*versionMinor*/, const QString & /*pluginLabel*/, const QString & str) { QString s(str); s.replace( QChar('\\'),QChar('/') ); QStringList out; if ( pluginIdentifier.startsWith("com.genarts.sapphire.") || s.startsWith("Sapphire ") || str.startsWith(" Sapphire ") ) { out.push_back("Sapphire"); } else if ( pluginIdentifier.startsWith("com.genarts.monsters.") || s.startsWith("Monsters ") || str.startsWith(" Monsters ") ) { out.push_back("Monsters"); } else if (pluginIdentifier == "uk.co.thefoundry.keylight.keylight") { s = PLUGIN_GROUP_KEYER; } else if (pluginIdentifier == "uk.co.thefoundry.noisetools.denoise") { s = PLUGIN_GROUP_FILTER; } else if ( (pluginIdentifier == "tuttle.avreader") || (pluginIdentifier == "tuttle.avwriter") || (pluginIdentifier == "tuttle.dpxwriter") || (pluginIdentifier == "tuttle.exrreader") || (pluginIdentifier == "tuttle.exrwriter") || (pluginIdentifier == "tuttle.imagemagickreader") || (pluginIdentifier == "tuttle.jpeg2000reader") || (pluginIdentifier == "tuttle.jpeg2000writer") || (pluginIdentifier == "tuttle.jpegreader") || (pluginIdentifier == "tuttle.jpegwriter") || (pluginIdentifier == "tuttle.oiioreader") || (pluginIdentifier == "tuttle.oiiowriter") || (pluginIdentifier == "tuttle.pngreader") || (pluginIdentifier == "tuttle.pngwriter") || (pluginIdentifier == "tuttle.rawreader") || (pluginIdentifier == "tuttle.turbojpegreader") || (pluginIdentifier == "tuttle.turbojpegwriter") ) { out.push_back(PLUGIN_GROUP_IMAGE); if ( pluginIdentifier.endsWith("reader") ) { s = PLUGIN_GROUP_IMAGE_READERS; } else { s = PLUGIN_GROUP_IMAGE_WRITERS; } } else if ( (pluginIdentifier == "tuttle.checkerboard") || (pluginIdentifier == "tuttle.colorbars") || (pluginIdentifier == "tuttle.colorcube") || // TuttleColorCube (pluginIdentifier == "tuttle.colorgradient") || (pluginIdentifier == "tuttle.colorwheel") || (pluginIdentifier == "tuttle.constant") || (pluginIdentifier == "tuttle.inputbuffer") || (pluginIdentifier == "tuttle.outputbuffer") || (pluginIdentifier == "tuttle.ramp") || (pluginIdentifier == "tuttle.seexpr") ) { s = PLUGIN_GROUP_IMAGE; } else if ( (pluginIdentifier == "tuttle.bitdepth") || (pluginIdentifier == "tuttle.colorgradation") || (pluginIdentifier == "tuttle.colorspace") || (pluginIdentifier == "tuttle.colorsuppress") || (pluginIdentifier == "tuttle.colortransfer") || (pluginIdentifier == "tuttle.colortransform") || (pluginIdentifier == "tuttle.ctl") || (pluginIdentifier == "tuttle.gamma") || (pluginIdentifier == "tuttle.invert") || (pluginIdentifier == "tuttle.lut") || (pluginIdentifier == "tuttle.normalize") ) { s = PLUGIN_GROUP_COLOR; } else if ( (pluginIdentifier == "tuttle.ocio.colorspace") || (pluginIdentifier == "tuttle.ocio.lut") ) { out.push_back(PLUGIN_GROUP_COLOR); s = "OCIO"; } else if ( (pluginIdentifier == "tuttle.mathoperator") ) { out.push_back(PLUGIN_GROUP_COLOR); s = "Math"; } else if ( (pluginIdentifier == "tuttle.channelshuffle") ) { s = PLUGIN_GROUP_CHANNEL; } else if ( (pluginIdentifier == "tuttle.component") || (pluginIdentifier == "tuttle.fade") || (pluginIdentifier == "tuttle.merge") ) { s = PLUGIN_GROUP_MERGE; } else if ( (pluginIdentifier == "tuttle.anisotropicdiffusion") || (pluginIdentifier == "tuttle.anisotropictensors") || (pluginIdentifier == "tuttle.blur") || (pluginIdentifier == "tuttle.convolution") || (pluginIdentifier == "tuttle.floodfill") || (pluginIdentifier == "tuttle.localmaxima") || (pluginIdentifier == "tuttle.nlmdenoiser") || (pluginIdentifier == "tuttle.sobel") || (pluginIdentifier == "tuttle.thinning") ) { s = PLUGIN_GROUP_FILTER; } else if ( (pluginIdentifier == "tuttle.crop") || (pluginIdentifier == "tuttle.flip") || (pluginIdentifier == "tuttle.lensdistort") || (pluginIdentifier == "tuttle.move2d") || (pluginIdentifier == "tuttle.pinning") || (pluginIdentifier == "tuttle.pushpixel") || (pluginIdentifier == "tuttle.resize") || (pluginIdentifier == "tuttle.swscale") || (pluginIdentifier == "tuttle.warp") ) { s = PLUGIN_GROUP_TRANSFORM; } else if ( (pluginIdentifier == "tuttle.timeshift") ) { s = PLUGIN_GROUP_TIME; } else if ( (pluginIdentifier == "tuttle.text") ) { s = PLUGIN_GROUP_PAINT; } else if ( (pluginIdentifier == "tuttle.basickeyer") || (pluginIdentifier == "tuttle.colorspacekeyer") || (pluginIdentifier == "tuttle.histogramkeyer") || (pluginIdentifier == "tuttle.idkeyer") ) { s = PLUGIN_GROUP_KEYER; } else if ( (pluginIdentifier == "tuttle.colorCube") || // TuttleColorCubeViewer (pluginIdentifier == "tuttle.colorcubeviewer") || (pluginIdentifier == "tuttle.diff") || (pluginIdentifier == "tuttle.dummy") || (pluginIdentifier == "tuttle.histogram") || (pluginIdentifier == "tuttle.imagestatistics") ) { s = PLUGIN_GROUP_OTHER; } else if ( (pluginIdentifier == "tuttle.debugimageeffectapi") ) { out.push_back(PLUGIN_GROUP_OTHER); s = "Test"; } // The following plugins are pretty much useless for use within Natron, keep them in the Tuttle group: /* (pluginIdentifier == "tuttle.print") || (pluginIdentifier == "tuttle.viewer") || */ return out + s.split('/'); } // ofxExtractAllPartsOfGrouping QStringList AbstractOfxEffectInstance::makePluginGrouping(const std::string & pluginIdentifier, int versionMajor, int versionMinor, const std::string & pluginLabel, const std::string & grouping) { //printf("%s,%s\n",pluginLabel.c_str(),grouping.c_str()); return ofxExtractAllPartsOfGrouping( pluginIdentifier.c_str(), versionMajor, versionMinor, pluginLabel.c_str(),grouping.c_str() ); } std::string AbstractOfxEffectInstance::makePluginLabel(const std::string & shortLabel, const std::string & label, const std::string & longLabel) { std::string labelToUse = label; if ( labelToUse.empty() ) { labelToUse = shortLabel; } if ( labelToUse.empty() ) { labelToUse = longLabel; } return labelToUse; } std::string OfxEffectInstance::getPluginID() const { assert(_context != eContextNone); return _natronPluginID; } std::string OfxEffectInstance::getPluginLabel() const { assert(_context != eContextNone); assert(_effect); return makePluginLabel( _effect->getDescriptor().getShortLabel(), _effect->getDescriptor().getLabel(), _effect->getDescriptor().getLongLabel() ); } void OfxEffectInstance::getPluginGrouping(std::list<std::string>* grouping) const { assert(_context != eContextNone); std::string groupStr = effectInstance()->getPluginGrouping(); std::string label = getPluginLabel(); const OFX::Host::ImageEffect::ImageEffectPlugin *p = effectInstance()->getPlugin(); QStringList groups = ofxExtractAllPartsOfGrouping( p->getIdentifier().c_str(), p->getVersionMajor(), p->getVersionMinor(), label.c_str(), groupStr.c_str() ); for (int i = 0; i < groups.size(); ++i) { grouping->push_back( groups[i].toStdString() ); } } std::string OfxEffectInstance::getInputLabel(int inputNb) const { assert(_context != eContextNone); MappedInputV copy = inputClipsCopyWithoutOutput(); if ( inputNb < (int)copy.size() ) { return copy[copy.size() - 1 - inputNb]->getShortLabel(); } else { return EffectInstance::getInputLabel(inputNb); } } OfxEffectInstance::MappedInputV OfxEffectInstance::inputClipsCopyWithoutOutput() const { assert(_context != eContextNone); assert( effectInstance() ); const std::vector<OFX::Host::ImageEffect::ClipDescriptor*> & clips = effectInstance()->getDescriptor().getClipsByOrder(); MappedInputV copy; for (U32 i = 0; i < clips.size(); ++i) { assert(clips[i]); if (clips[i]->getShortLabel() != kOfxImageEffectOutputClipName) { copy.push_back(clips[i]); // cout << "Clip[" << i << "] = " << clips[i]->getShortLabel() << endl; } } return copy; } OfxClipInstance* OfxEffectInstance::getClipCorrespondingToInput(int inputNo) const { assert(_context != eContextNone); OfxEffectInstance::MappedInputV clips = inputClipsCopyWithoutOutput(); assert( inputNo < (int)clips.size() ); OFX::Host::ImageEffect::ClipInstance* clip = _effect->getClip( clips[clips.size() - 1 - inputNo]->getName() ); assert(clip); return dynamic_cast<OfxClipInstance*>(clip); } int OfxEffectInstance::getMaxInputCount() const { assert(_context != eContextNone); const std::string & context = effectInstance()->getContext(); if ( (context == kOfxImageEffectContextReader) || ( context == kOfxImageEffectContextGenerator) ) { return 0; } else { assert( effectInstance() ); int totalClips = effectInstance()->getDescriptor().getClips().size(); return totalClips > 0 ? totalClips - 1 : 0; } } bool OfxEffectInstance::isInputOptional(int inputNb) const { assert(_context != eContextNone); MappedInputV inputs = inputClipsCopyWithoutOutput(); assert( inputNb < (int)inputs.size() ); if ( inputs[inputs.size() - 1 - inputNb]->isOptional() ) { return true; } else { if ( isInputRotoBrush(inputNb) ) { return true; } } return false; } bool OfxEffectInstance::isInputMask(int inputNb) const { assert(_context != eContextNone); MappedInputV inputs = inputClipsCopyWithoutOutput(); assert( inputNb < (int)inputs.size() ); return inputs[inputs.size() - 1 - inputNb]->isMask(); } bool OfxEffectInstance::isInputRotoBrush(int inputNb) const { assert(_context != eContextNone); MappedInputV inputs = inputClipsCopyWithoutOutput(); assert( inputNb < (int)inputs.size() ); ///Maybe too crude ? Not like many plug-ins use the paint context except Natron's roto node. return inputs[inputs.size() - 1 - inputNb]->getName() == "Roto" && getNode()->isRotoNode(); } int OfxEffectInstance::getRotoBrushInputIndex() const { assert(_context != eContextNone); MappedInputV inputs = inputClipsCopyWithoutOutput(); for (U32 i = 0; i < inputs.size(); ++i) { if (inputs[i]->getName() == "Roto") { return inputs.size() - 1 - i; } } return -1; } void OfxEffectInstance::onInputChanged(int inputNo) { if (getApp()->getProject()->isLoadingProject()) { return; } assert(_context != eContextNone); OfxClipInstance* clip = getClipCorrespondingToInput(inputNo); assert(clip); double time = getApp()->getTimeLine()->currentFrame(); RenderScale s; s.x = s.y = 1.; /** * The plug-in might call getImage, set a valid thread storage on the tree. **/ Node::ParallelRenderArgsSetter frameRenderArgs(_node.get(), time, 0 /*view*/, true, false, false, getHash(), true, getApp()->getTimeLine().get()); ///Don't do clip preferences while loading a project, they will be refreshed globally once the project is loaded. ///if all non optional clips are connected, call getClipPrefs ///The clip preferences action is never called until all non optional clips have been attached to the plugin. if (_effect->areAllNonOptionalClipsConnected()) { ///Render scale support might not have been set already because getRegionOfDefinition could have failed until all non optional inputs were connected if (supportsRenderScaleMaybe() == eSupportsMaybe) { OfxRectD rod; OfxPointD scaleOne; scaleOne.x = scaleOne.y = 1.; OfxStatus rodstat = _effect->getRegionOfDefinitionAction(time, scaleOne, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { OfxPointD scale; scale.x = 0.5; scale.y = 0.5; rodstat = _effect->getRegionOfDefinitionAction(time, scale, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { setSupportsRenderScaleMaybe(eSupportsYes); } else { setSupportsRenderScaleMaybe(eSupportsNo); } } } if ( !getApp()->getProject()->isLoadingProject() ) { checkOFXClipPreferences_public(time,s,kOfxChangeUserEdited,true, true); } } { RECURSIVE_ACTION(); SET_CAN_SET_VALUE(true); ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? 0 /*view*/, true, //< setmipmaplevel? 0); _effect->beginInstanceChangedAction(kOfxChangeUserEdited); _effect->clipInstanceChangedAction(clip->getName(), kOfxChangeUserEdited, time, s); _effect->endInstanceChangedAction(kOfxChangeUserEdited); } } /** @brief map a std::string to a context */ OfxEffectInstance::ContextEnum OfxEffectInstance::mapToContextEnum(const std::string &s) { if (s == kOfxImageEffectContextGenerator) { return eContextGenerator; } if (s == kOfxImageEffectContextFilter) { return eContextFilter; } if (s == kOfxImageEffectContextTransition) { return eContextTransition; } if (s == kOfxImageEffectContextPaint) { return eContextPaint; } if (s == kOfxImageEffectContextGeneral) { return eContextGeneral; } if (s == kOfxImageEffectContextRetimer) { return eContextRetimer; } if (s == kOfxImageEffectContextReader) { return eContextReader; } if (s == kOfxImageEffectContextWriter) { return eContextWriter; } qDebug() << "OfxEffectInstance::mapToContextEnum: Unknown image effect context '" << s.c_str() << "'"; throw std::invalid_argument(s); } /** * @brief The purpose of this function is to allow Natron to modify slightly the values returned in the getClipPreferencesAction * by the plugin so that we can minimize the amount of Natron::Image::convertToFormat calls. **/ static void clipPrefsProxy(OfxEffectInstance* self, double time, std::map<OfxClipInstance*,OfxImageEffectInstance::ClipPrefs>& clipPrefs, OfxImageEffectInstance::EffectPrefs& effectPrefs, std::list<OfxClipInstance*>& changedClips) { ///We remap all the input clips components to be the same as the output clip, except for the masks. OfxClipInstance* outputClip = dynamic_cast<OfxClipInstance*>(self->effectInstance()->getClip(kOfxImageEffectOutputClipName)); assert(outputClip); std::map<OfxClipInstance*,OfxImageEffectInstance::ClipPrefs>::iterator foundOutputPrefs = clipPrefs.find(outputClip); assert(foundOutputPrefs != clipPrefs.end()); std::string outputClipDepth = foundOutputPrefs->second.bitdepth; Natron::ImageBitDepthEnum outputClipDepthNatron = OfxClipInstance::ofxDepthToNatronDepth(outputClipDepth); ///Set a warning on the node if the bitdepth conversion from one of the input clip to the output clip is lossy QString bitDepthWarning("This nodes converts higher bit depths images from its inputs to work. As " "a result of this process, the quality of the images is degraded. The following conversions are done: \n"); bool setBitDepthWarning = false; bool outputModified = false; if (!self->isSupportedBitDepth(OfxClipInstance::ofxDepthToNatronDepth(outputClipDepth))) { outputClipDepth = self->effectInstance()->bestSupportedDepth(kOfxBitDepthFloat); outputClipDepthNatron = OfxClipInstance::ofxDepthToNatronDepth(outputClipDepth); foundOutputPrefs->second.bitdepth = outputClipDepth; outputModified = true; } double outputAspectRatio = foundOutputPrefs->second.par; ///output clip doesn't support components just remap it, this is probably a plug-in bug. if (!outputClip->isSupportedComponent(foundOutputPrefs->second.components)) { foundOutputPrefs->second.components = outputClip->findSupportedComp(kOfxImageComponentRGBA); outputModified = true; } ///Adjust output premultiplication if needed if (foundOutputPrefs->second.components == kOfxImageComponentRGB) { effectPrefs.premult = kOfxImageOpaque; } else if (foundOutputPrefs->second.components == kOfxImageComponentAlpha) { effectPrefs.premult = kOfxImagePreMultiplied; } int maxInputs = self->getMaxInputCount(); for (int i = 0; i < maxInputs; ++i) { EffectInstance* inputEffect = self->getInput(i); if (inputEffect) { inputEffect = inputEffect->getNearestNonIdentity(time); } OfxEffectInstance* instance = dynamic_cast<OfxEffectInstance*>(inputEffect); OfxClipInstance* clip = self->getClipCorrespondingToInput(i); if (instance) { std::map<OfxClipInstance*,OfxImageEffectInstance::ClipPrefs>::iterator foundClipPrefs = clipPrefs.find(clip); assert(foundClipPrefs != clipPrefs.end()); bool hasChanged = false; ///This is the output clip of the input node OFX::Host::ImageEffect::ClipInstance* inputOutputClip = instance->effectInstance()->getClip(kOfxImageEffectOutputClipName); ///Set the clip to have the same components as the output components if it is supported if ( clip->isSupportedComponent(foundOutputPrefs->second.components) ) { ///we only take into account non mask clips for the most components if ( !clip->isMask() && (foundClipPrefs->second.components != foundOutputPrefs->second.components) ) { foundClipPrefs->second.components = foundOutputPrefs->second.components; hasChanged = true; } } ///Try to remap the clip's bitdepth to be the same as const std::string & input_outputDepth = inputOutputClip->getPixelDepth(); Natron::ImageBitDepthEnum input_outputNatronDepth = OfxClipInstance::ofxDepthToNatronDepth(input_outputDepth); ///If supported, set the clip's bitdepth to be the same as the output depth of the input node if ( self->isSupportedBitDepth(input_outputNatronDepth) ) { bool depthsDifferent = input_outputNatronDepth != outputClipDepthNatron; if (self->effectInstance()->supportsMultipleClipDepths() && depthsDifferent) { foundClipPrefs->second.bitdepth = input_outputDepth; hasChanged = true; } } ///Otherwise if the bit-depth conversion will be lossy, warn the user else if ( Image::isBitDepthConversionLossy(input_outputNatronDepth, outputClipDepthNatron) ) { bitDepthWarning.append( instance->getName().c_str() ); bitDepthWarning.append(" (" + QString( Image::getDepthString(input_outputNatronDepth).c_str() ) + ")"); bitDepthWarning.append(" ----> "); bitDepthWarning.append( self->getName_mt_safe().c_str() ); bitDepthWarning.append(" (" + QString( Image::getDepthString(outputClipDepthNatron).c_str() ) + ")"); bitDepthWarning.append('\n'); setBitDepthWarning = true; } if (!self->effectInstance()->supportsMultipleClipPARs() && foundClipPrefs->second.par != outputAspectRatio && foundClipPrefs->first->getConnected()) { qDebug() << self->getName_mt_safe().c_str() << ": An input clip ("<< foundClipPrefs->first->getName().c_str() << ") has a pixel aspect ratio (" << foundClipPrefs->second.par << ") different than the output clip (" << outputAspectRatio << ") but it doesn't support multiple clips PAR. " << "This should have been handled earlier before connecting the nodes, @see Node::canConnectInput."; } if (hasChanged) { changedClips.push_back(clip); } } } if (outputModified) { changedClips.push_back(outputClip); } self->getNode()->toggleBitDepthWarning(setBitDepthWarning, bitDepthWarning); } //endCheckOFXClipPreferences void OfxEffectInstance::checkOFXClipPreferences(double time, const RenderScale & scale, const std::string & reason, bool forceGetClipPrefAction) { assert(_context != eContextNone); assert( QThread::currentThread() == qApp->thread() ); //////////////////////////////////////////////////////////////// /////////////////////////////////// //////////////// STEP 1 : Get plug-in render preferences std::map<OfxClipInstance*,OfxImageEffectInstance::ClipPrefs> clipsPrefs; OfxImageEffectInstance::EffectPrefs effectPrefs; { RECURSIVE_ACTION(); SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QWriteLocker preferencesLocker(_preferencesLock); if (forceGetClipPrefAction) { if (!_effect->getClipPreferences_safe(clipsPrefs,effectPrefs)) { return; } } else { if (_effect->areClipPrefsDirty()) { if (!_effect->getClipPreferences_safe(clipsPrefs, effectPrefs)) { return; } } else { return; } } } //////////////////////////////////////////////////////////////// //////////////////////////////// //////////////// STEP 2: Apply a proxy, i.e: modify the preferences so it requires a minimum pixel shuffling std::list<OfxClipInstance*> modifiedClips; clipPrefsProxy(this,time,clipsPrefs,effectPrefs,modifiedClips); //////////////////////////////////////////////////////////////// //////////////////////////////// //////////////// STEP 3: Actually push to the clips the preferences and set the flags on the effect, protected by a write lock. { QWriteLocker l(_preferencesLock); for (std::map<OfxClipInstance*,OfxImageEffectInstance::ClipPrefs>::const_iterator it = clipsPrefs.begin(); it != clipsPrefs.end(); ++it) { it->first->setComponents(it->second.components); it->first->setPixelDepth(it->second.bitdepth); it->first->setAspectRatio(it->second.par); } effectInstance()->updatePreferences_safe(effectPrefs.frameRate, effectPrefs.fielding, effectPrefs.premult, effectPrefs.continuous, effectPrefs.frameVarying); } //////////////////////////////////////////////////////////////// //////////////////////////////// //////////////// STEP 4: If our proxy remapping changed some clips preferences, notifying the plug-in of the clips which changed if (!getApp()->getProject()->isLoadingProject()) { RECURSIVE_ACTION(); SET_CAN_SET_VALUE(true); if (!modifiedClips.empty()) { effectInstance()->beginInstanceChangedAction(reason); } for (std::list<OfxClipInstance*>::iterator it = modifiedClips.begin(); it!=modifiedClips.end();++it) { effectInstance()->clipInstanceChangedAction((*it)->getName(), reason, time, scale); } if (!modifiedClips.empty()) { effectInstance()->endInstanceChangedAction(reason); } } } // checkOFXClipPreferences void OfxEffectInstance::restoreClipPreferences() { assert(_context != eContextNone); double time = getApp()->getTimeLine()->currentFrame(); RenderScale s; s.x = s.y = 1.; ///if all non optional clips are connected, call getClipPrefs ///The clip preferences action is never called until all non optional clips have been attached to the plugin. if ( _effect->areAllNonOptionalClipsConnected() ) { ///Render scale support might not have been set already because getRegionOfDefinition could have failed until all non optional inputs were connected if (supportsRenderScaleMaybe() == eSupportsMaybe) { OfxRectD rod; OfxPointD scaleOne; scaleOne.x = scaleOne.y = 1.; OfxStatus rodstat = _effect->getRegionOfDefinitionAction(time, scaleOne, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { OfxPointD scale; scale.x = 0.5; scale.y = 0.5; rodstat = _effect->getRegionOfDefinitionAction(time, scale, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { setSupportsRenderScaleMaybe(eSupportsYes); } else { setSupportsRenderScaleMaybe(eSupportsNo); } } } checkOFXClipPreferences_public(time,s,kOfxChangeUserEdited,true, false); } } std::vector<std::string> OfxEffectInstance::supportedFileFormats() const { assert(_context != eContextNone); int formatsCount = _effect->getDescriptor().getProps().getDimension(kTuttleOfxImageEffectPropSupportedExtensions); std::vector<std::string> formats(formatsCount); for (int k = 0; k < formatsCount; ++k) { formats[k] = _effect->getDescriptor().getProps().getStringProperty(kTuttleOfxImageEffectPropSupportedExtensions,k); std::transform(formats[k].begin(), formats[k].end(), formats[k].begin(), ::tolower); } return formats; } Natron::StatusEnum OfxEffectInstance::getRegionOfDefinition(U64 hash, SequenceTime time, const RenderScale & scale, int view, RectD* rod) { assert(_context != eContextNone); if (!_initialized) { return Natron::eStatusFailed; } assert(_effect); unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); // getRegionOfDefinition may be the first action with renderscale called on any effect. // it may have to check for render scale support. SupportsEnum supportsRS = supportsRenderScaleMaybe(); bool scaleIsOne = (scale.x == 1. && scale.y == 1.); if ( (supportsRS == eSupportsNo) && !scaleIsOne ) { qDebug() << "getRegionOfDefinition called with render scale != 1, but effect does not support render scale!"; return eStatusFailed; } OfxRectD ofxRod; OfxStatus stat; { bool skipDiscarding = false; if (getRecursionLevel() > 1) { skipDiscarding = true; } ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, //< set mipmaplevel? mipMapLevel); { if (getRecursionLevel() > 1) { stat = _effect->getRegionOfDefinitionAction(time, scale, ofxRod); } else { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->getRegionOfDefinitionAction(time, scale, ofxRod); } } if ( !scaleIsOne && (supportsRS == eSupportsMaybe) ) { if ( (stat == kOfxStatOK) || (stat == kOfxStatReplyDefault) ) { // we got at least one success with RS != 1 setSupportsRenderScaleMaybe(eSupportsYes); } else if (stat == kOfxStatFailed) { // maybe the effect does not support renderscale // try again with scale one OfxPointD scaleOne; scaleOne.x = scaleOne.y = 1.; { SET_CAN_SET_VALUE(false); if (getRecursionLevel() > 1) { stat = _effect->getRegionOfDefinitionAction(time, scaleOne, ofxRod); } else { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->getRegionOfDefinitionAction(time, scaleOne, ofxRod); } } if ( (stat == kOfxStatOK) || (stat == kOfxStatReplyDefault) ) { // we got success with scale = 1, which means it doesn't support renderscale after all setSupportsRenderScaleMaybe(eSupportsNo); } else { // if both actions failed, we can't say anything return eStatusFailed; } if (stat == kOfxStatReplyDefault) { calcDefaultRegionOfDefinition(hash,time,view,scaleOne, rod); return eStatusReplyDefault; } } } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { return eStatusFailed; } if (stat == kOfxStatReplyDefault) { calcDefaultRegionOfDefinition(hash,time,view, scale, rod); return eStatusReplyDefault; } } ///If the rod is 1 pixel, determine if it was because one clip was unconnected or this is really a ///1 pixel large image if ( (ofxRod.x2 == 1.) && (ofxRod.y2 == 1.) && (ofxRod.x1 == 0.) && (ofxRod.y1 == 0.) ) { int maxInputs = getMaxInputCount(); for (int i = 0; i < maxInputs; ++i) { OfxClipInstance* clip = getClipCorrespondingToInput(i); if ( clip && !clip->getConnected() && !clip->isOptional() && !clip->isMask() ) { ///this is a mandatory source clip and it is not connected, return statfailed return eStatusFailed; } } } RectD::ofxRectDToRectD(ofxRod, rod); return eStatusOK; // OFX::Host::ImageEffect::ClipInstance* clip = effectInstance()->getClip(kOfxImageEffectOutputClipName); //assert(clip); //double pa = clip->getAspectRatio(); } // getRegionOfDefinition void OfxEffectInstance::calcDefaultRegionOfDefinition(U64 /*hash*/, SequenceTime time, int view, const RenderScale & scale, RectD *rod) { assert(_context != eContextNone); if (!_initialized) { throw std::runtime_error("OfxEffectInstance not initialized"); } bool skipDiscarding = false; if (getRecursionLevel() > 1) { skipDiscarding = true; } unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); OfxRectD ofxRod; { SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. if (getRecursionLevel() == 0) { ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, //< set mipmaplevel? mipMapLevel); // from http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxImageEffectActionGetRegionOfDefinition // generator context - defaults to the project window, // filter and paint contexts - defaults to the RoD of the 'Source' input clip at the given time, // transition context - defaults to the union of the RoDs of the 'SourceFrom' and 'SourceTo' input clips at the given time, // general context - defaults to the union of the RoDs of all the effect non optional input clips at the given time, if none exist, then it is the project window // retimer context - defaults to the union of the RoD of the 'Source' input clip at the frame directly preceding the value of the 'SourceTime' double parameter and the frame directly after it // the following ofxh function does the job QReadLocker preferencesLocker(_preferencesLock); ofxRod = _effect->calcDefaultRegionOfDefinition(time, (OfxPointD)scale); } else { ofxRod = _effect->calcDefaultRegionOfDefinition(time, (OfxPointD)scale); } } rod->x1 = ofxRod.x1; rod->x2 = ofxRod.x2; rod->y1 = ofxRod.y1; rod->y2 = ofxRod.y2; } static void rectToOfxRectD(const RectD & b, OfxRectD *out) { out->x1 = b.left(); out->x2 = b.right(); out->y1 = b.bottom(); out->y2 = b.top(); } void OfxEffectInstance::getRegionsOfInterest(SequenceTime time, const RenderScale & scale, const RectD & outputRoD, const RectD & renderWindow, //!< the region to be rendered in the output image, in Canonical Coordinates int view, EffectInstance::RoIMap* ret) { assert(_context != eContextNone); std::map<OFX::Host::ImageEffect::ClipInstance*,OfxRectD> inputRois; if (!_initialized) { return; } assert(outputRoD.x2 >= outputRoD.x1 && outputRoD.y2 >= outputRoD.y1); assert(renderWindow.x2 >= renderWindow.x1 && renderWindow.y2 >= renderWindow.y1); { bool scaleIsOne = (scale.x == 1. && scale.y == 1.); assert( !( (supportsRenderScaleMaybe() == eSupportsNo) && !scaleIsOne ) ); } OfxStatus stat; ///before calling getRoIaction set the relevant info on the clips unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); { SET_CAN_SET_VALUE(false); bool skipDiscarding = false; if (getRecursionLevel() > 1) { qDebug() << "getRegionsOfInterest cannot be called recursively as an action. Please check this."; skipDiscarding = true; } ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, mipMapLevel); OfxRectD roi; rectToOfxRectD(renderWindow, &roi); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->getRegionOfInterestAction( (OfxTime)time, scale, roi, inputRois ); } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { appPTR->writeToOfxLog_mt_safe(QString( getNode()->getName_mt_safe().c_str() ) + "Failed to specify the region of interest from inputs."); } if (stat != kOfxStatReplyDefault) { for (std::map<OFX::Host::ImageEffect::ClipInstance*,OfxRectD>::iterator it = inputRois.begin(); it != inputRois.end(); ++it) { OfxClipInstance* clip = dynamic_cast<OfxClipInstance*>(it->first); assert(clip); if (clip) { EffectInstance* inputNode = clip->getAssociatedNode(); RectD inputRoi; // input RoI in canonical coordinates inputRoi.x1 = it->second.x1; inputRoi.x2 = it->second.x2; inputRoi.y1 = it->second.y1; inputRoi.y2 = it->second.y2; ///The RoI might be infinite if the getRoI action of the plug-in doesn't do anything and the input effect has an ///infinite rod. ifInfiniteclipRectToProjectDefault(&inputRoi); ret->insert( std::make_pair(inputNode,inputRoi) ); } } } else if (stat == kOfxStatReplyDefault) { const std::map<std::string,OFX::Host::ImageEffect::ClipInstance*>& clips = effectInstance()->getClips(); for (std::map<std::string,OFX::Host::ImageEffect::ClipInstance*>::const_iterator it = clips.begin(); it!=clips.end(); ++it) { if (!it->second->isOutput()) { OfxClipInstance* natronClip = dynamic_cast<OfxClipInstance*>(it->second); assert(natronClip); EffectInstance* inputNode = natronClip ? natronClip->getAssociatedNode() : 0; if (inputNode) { ret->insert( std::make_pair(inputNode, renderWindow) ); } } } } } // getRegionsOfInterest Natron::EffectInstance::FramesNeededMap OfxEffectInstance::getFramesNeeded(SequenceTime time) { assert(_context != eContextNone); EffectInstance::FramesNeededMap ret; if (!_initialized) { return ret; } OFX::Host::ImageEffect::RangeMap inputRanges; assert(_effect); OfxStatus stat; { SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->getFrameNeededAction( (OfxTime)time, inputRanges ); } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { Natron::errorDialog( getName(), QObject::tr("Failed to specify the frame ranges needed from inputs.").toStdString() ); } else if (stat == kOfxStatOK) { for (OFX::Host::ImageEffect::RangeMap::iterator it = inputRanges.begin(); it != inputRanges.end(); ++it) { OfxClipInstance* clip = dynamic_cast<OfxClipInstance*>(it->first); assert(clip); if (clip) { int inputNb = clip->getInputNb(); if (inputNb != -1) { ret.insert( std::make_pair(inputNb,it->second) ); } } } } else if (stat == kOfxStatReplyDefault) { return Natron::EffectInstance::getFramesNeeded(time); } return ret; } void OfxEffectInstance::getFrameRange(SequenceTime *first, SequenceTime *last) { assert(_context != eContextNone); if (!_initialized) { return; } OfxRangeD range; // getTimeDomain should only be called on the 'general', 'reader' or 'generator' contexts. // see http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxImageEffectActionGetTimeDomain" // Edit: Also add the 'writer' context as we need the getTimeDomain action to be able to find out the frame range to render. OfxStatus st = kOfxStatReplyDefault; if ( (_context == eContextGeneral) || ( _context == eContextReader) || ( _context == eContextWriter) || ( _context == eContextGenerator) ) { SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); st = _effect->getTimeDomainAction(range); } if (st == kOfxStatOK) { *first = (SequenceTime)range.min; *last = (SequenceTime)range.max; } else if (st == kOfxStatReplyDefault) { //The default is... int nthClip = _effect->getNClips(); if (nthClip == 0) { //infinite if there are no non optional input clips. *first = INT_MIN; *last = INT_MAX; } else { //the union of all the frame ranges of the non optional input clips. bool firstValidInput = true; *first = INT_MIN; *last = INT_MAX; int inputsCount = getMaxInputCount(); ///Uncommented the isOptional() introduces a bugs with Genarts Monster plug-ins when 2 generators ///are connected in the pipeline. They must rely on the time domain to maintain an internal state and apparantly ///not taking optional inputs into accounts messes it up. for (int i = 0; i < inputsCount; ++i) { //if (!isInputOptional(i)) { EffectInstance* inputEffect = getInput(i); if (inputEffect) { SequenceTime f,l; inputEffect->getFrameRange_public(inputEffect->getRenderHash(),&f, &l); if (!firstValidInput) { if ( (f < *first) && (f != INT_MIN) ) { *first = f; } if ( (l > *last) && (l != INT_MAX) ) { *last = l; } } else { firstValidInput = false; *first = f; *last = l; } } // } } } } } // getFrameRange bool OfxEffectInstance::isIdentity(SequenceTime time, const RenderScale & scale, const RectD & rod, const double par, int view, SequenceTime* inputTime, int* inputNb) { if (!_created) { *inputNb = -1; *inputTime = 0; return false; } assert(_context != eContextNone); const std::string field = kOfxImageFieldNone; // TODO: support interlaced data std::string inputclip; OfxTime inputTimeOfx = time; // isIdentity may be the first action with renderscale called on any effect. // it may have to check for render scale support. SupportsEnum supportsRS = supportsRenderScaleMaybe(); bool scaleIsOne = (scale.x == 1. && scale.y == 1.); if ( (supportsRS == eSupportsNo) && !scaleIsOne ) { qDebug() << "isIdentity called with render scale != 1, but effect does not support render scale!"; assert(false); throw std::logic_error("isIdentity called with render scale != 1, but effect does not support render scale!"); } unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); OfxStatus stat; { bool skipDiscarding = false; if (getRecursionLevel() > 1) { //#ifdef DEBUG // if (QThread::currentThread() != qApp->thread()) { // qDebug() << "isIdentity cannot be called recursively as an action. Please check this."; // } //#endif skipDiscarding = true; } SET_CAN_SET_VALUE(false); ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, mipMapLevel); // In Natron, we only consider isIdentity for whole images RectI roi; rod.toPixelEnclosing(scale, par, &roi); OfxRectI ofxRoI; ofxRoI.x1 = roi.left(); ofxRoI.x2 = roi.right(); ofxRoI.y1 = roi.bottom(); ofxRoI.y2 = roi.top(); { if (getRecursionLevel() > 1) { stat = _effect->isIdentityAction(inputTimeOfx, field, ofxRoI, scale, inputclip); } else { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->isIdentityAction(inputTimeOfx, field, ofxRoI, scale, inputclip); } } if ( !scaleIsOne && (supportsRS == eSupportsMaybe) ) { if ( (stat == kOfxStatOK) || (stat == kOfxStatReplyDefault) ) { // we got at least one success with RS != 1 setSupportsRenderScaleMaybe(eSupportsYes); } else if (stat == kOfxStatFailed) { // maybe the effect does not support renderscale // try again with scale one OfxPointD scaleOne; scaleOne.x = scaleOne.y = 1.; rod.toPixelEnclosing(scaleOne, par, &roi); ofxRoI.x1 = roi.left(); ofxRoI.x2 = roi.right(); ofxRoI.y1 = roi.bottom(); ofxRoI.y2 = roi.top(); if (getRecursionLevel() > 1) { stat = _effect->isIdentityAction(inputTimeOfx, field, ofxRoI, scaleOne, inputclip); } else { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->isIdentityAction(inputTimeOfx, field, ofxRoI, scaleOne, inputclip); } if ( (stat == kOfxStatOK) || (stat == kOfxStatReplyDefault) ) { // we got success with scale = 1, which means it doesn't support renderscale after all setSupportsRenderScaleMaybe(eSupportsNo); } } } } if (stat == kOfxStatOK) { OFX::Host::ImageEffect::ClipInstance* clip = _effect->getClip(inputclip); if (!clip) { // this is a plugin-side error, don't crash qDebug() << "Error in OfxEffectInstance::render(): kOfxImageEffectActionIsIdentity returned an unknown clip: " << inputclip.c_str(); return false; } OfxClipInstance* natronClip = dynamic_cast<OfxClipInstance*>(clip); assert(natronClip); if (!natronClip) { qDebug() << "Error in OfxEffectInstance::render(): kOfxImageEffectActionIsIdentity returned an unknown clip: " << inputclip.c_str(); return false; } *inputTime = inputTimeOfx; if ( natronClip->isOutput() ) { *inputNb = -2; } else { *inputNb = natronClip->getInputNb(); } return true; } else if (stat == kOfxStatReplyDefault) { return false; } return false; //< may fail if getRegionOfDefinition has failed in the plug-in code //throw std::runtime_error("isIdentity failed"); } // isIdentity Natron::StatusEnum OfxEffectInstance::beginSequenceRender(SequenceTime first, SequenceTime last, SequenceTime step, bool interactive, const RenderScale & scale, bool isSequentialRender, bool isRenderResponseToUserInteraction, int view) { { bool scaleIsOne = (scale.x == 1. && scale.y == 1.); assert( !( (supportsRenderScaleMaybe() == eSupportsNo) && !scaleIsOne ) ); } OfxStatus stat; unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); { bool skipDiscarding = false; if (getRecursionLevel() > 1) { qDebug() << "beginRenderAction cannot be called recursively as an action. Please check this."; skipDiscarding = true; } ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, mipMapLevel); SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = effectInstance()->beginRenderAction(first, last, step, interactive, scale, isSequentialRender, isRenderResponseToUserInteraction, view); } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { return eStatusFailed; } return eStatusOK; } Natron::StatusEnum OfxEffectInstance::endSequenceRender(SequenceTime first, SequenceTime last, SequenceTime step, bool interactive, const RenderScale & scale, bool isSequentialRender, bool isRenderResponseToUserInteraction, int view) { { bool scaleIsOne = (scale.x == 1. && scale.y == 1.); assert( !( (supportsRenderScaleMaybe() == eSupportsNo) && !scaleIsOne ) ); } OfxStatus stat; unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); { bool skipDiscarding = false; if (getRecursionLevel() > 1) { qDebug() << "endRenderAction cannot be called recursively as an action. Please check this."; skipDiscarding = true; } ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, mipMapLevel); SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = effectInstance()->endRenderAction(first, last, step, interactive,scale, isSequentialRender, isRenderResponseToUserInteraction, view); } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { return eStatusFailed; } return eStatusOK; } Natron::StatusEnum OfxEffectInstance::render(SequenceTime time, const RenderScale& originalScale, const RenderScale & mappedScale, const RectI & roi, int view, bool isSequentialRender, bool isRenderResponseToUserInteraction, boost::shared_ptr<Natron::Image> output) { if (!_initialized) { return Natron::eStatusFailed; } OfxRectI ofxRoI; ofxRoI.x1 = roi.left(); ofxRoI.x2 = roi.right(); ofxRoI.y1 = roi.bottom(); ofxRoI.y2 = roi.top(); int viewsCount = getApp()->getProject()->getProjectViewsCount(); OfxStatus stat; const std::string field = kOfxImageFieldNone; // TODO: support interlaced data ///before calling render, set the render scale thread storage for each clip # ifdef DEBUG { // check the dimensions of output images const RectI & dstBounds = output->getBounds(); const RectD & dstRodCanonical = output->getRoD(); RectI dstRod; dstRodCanonical.toPixelEnclosing(mappedScale, output->getPixelAspectRatio(), &dstRod); if ( !supportsTiles() ) { // http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxImageEffectPropSupportsTiles // If a clip or plugin does not support tiled images, then the host should supply full RoD images to the effect whenever it fetches one. assert(dstRod.x1 == dstBounds.x1); assert(dstRod.x2 == dstBounds.x2); assert(dstRod.y1 == dstBounds.y1); assert(dstRod.y2 == dstBounds.y2); } if ( !supportsMultiResolution() ) { // http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxImageEffectPropSupportsMultiResolution // Multiple resolution images mean... // input and output images can be of any size // input and output images can be offset from the origin assert(dstRod.x1 == 0); assert(dstRod.y1 == 0); } } # endif // DEBUG { bool skipDiscarding = false; if (getRecursionLevel() > 1) { qDebug() << "renderAction cannot be called recursively as an action. Please check this."; skipDiscarding = true; } SET_CAN_SET_VALUE(false); ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true,//< set mipmaplevel ? Natron::Image::getLevelFromScale(originalScale.x)); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->renderAction( (OfxTime)time, field, ofxRoI, mappedScale, isSequentialRender, isRenderResponseToUserInteraction, view, viewsCount ); } if (stat != kOfxStatOK) { return eStatusFailed; } else { return eStatusOK; } } // render bool OfxEffectInstance::supportsMultipleClipsPAR() const { return _effect->supportsMultipleClipPARs(); } EffectInstance::RenderSafetyEnum OfxEffectInstance::renderThreadSafety() const { { QReadLocker readL(_renderSafetyLock); if (_wasRenderSafetySet) { return _renderSafety; } } { QWriteLocker writeL(_renderSafetyLock); const std::string & safety = _effect->getRenderThreadSafety(); if (safety == kOfxImageEffectRenderUnsafe) { _renderSafety = EffectInstance::eRenderSafetyUnsafe; } else if (safety == kOfxImageEffectRenderInstanceSafe) { _renderSafety = EffectInstance::eRenderSafetyInstanceSafe; } else if (safety == kOfxImageEffectRenderFullySafe) { if ( _effect->getHostFrameThreading() ) { _renderSafety = EffectInstance::eRenderSafetyFullySafeFrame; } else { _renderSafety = EffectInstance::eRenderSafetyFullySafe; } } else { qDebug() << "Unknown thread safety level: " << safety.c_str(); _renderSafety = EffectInstance::eRenderSafetyUnsafe; } _wasRenderSafetySet = true; return _renderSafety; } } bool OfxEffectInstance::makePreviewByDefault() const { return isGenerator(); } const std::string & OfxEffectInstance::getShortLabel() const { return effectInstance()->getShortLabel(); } void OfxEffectInstance::initializeOverlayInteract() { tryInitializeOverlayInteracts(); } void OfxEffectInstance::drawOverlay(double /*scaleX*/, double /*scaleY*/) { if (!_initialized) { return; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); /* if (getRecursionLevel() == 1) { bool skipDiscarding = false; if (getRecursionLevel() > 1) { ///This happens sometimes because of dialogs popping from the request of a plug-in (inside an action) ///and making the mainwindow loose focus, hence forcing a new paint event //qDebug() << "drawAction cannot be called recursively as an action. Please check this."; skipDiscarding = true; } ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, false, //< setView ? 0, false, 0); _overlayInteract->drawAction(time, rs); } else {*/ SET_CAN_SET_VALUE(false); _overlayInteract->drawAction(time, rs); /*}*/ } } void OfxEffectInstance::setCurrentViewportForOverlays(OverlaySupport* viewport) { if (_overlayInteract) { _overlayInteract->setCallingViewport(viewport); } } bool OfxEffectInstance::onOverlayPenDown(double /*scaleX*/, double /*scaleY*/, const QPointF & viewportPos, const QPointF & pos) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxPointD penPos; penPos.x = pos.x(); penPos.y = pos.y(); OfxPointI penPosViewport; penPosViewport.x = viewportPos.x(); penPosViewport.y = viewportPos.y(); OfxTime time = getApp()->getTimeLine()->currentFrame(); /* ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); */ SET_CAN_SET_VALUE(true); OfxStatus stat = _overlayInteract->penDownAction(time, rs, penPos, penPosViewport, 1.); if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } if (stat == kOfxStatOK) { _penDown = true; return true; } } return false; } bool OfxEffectInstance::onOverlayPenMotion(double /*scaleX*/, double /*scaleY*/, const QPointF & viewportPos, const QPointF & pos) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxPointD penPos; penPos.x = pos.x(); penPos.y = pos.y(); OfxPointI penPosViewport; penPosViewport.x = viewportPos.x(); penPosViewport.y = viewportPos.y(); OfxTime time = getApp()->getTimeLine()->currentFrame(); OfxStatus stat; /* if (getRecursionLevel() == 1) { ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); stat = _overlayInteract->penMotionAction(time, rs, penPos, penPosViewport, 1.); } else {*/ SET_CAN_SET_VALUE(true); stat = _overlayInteract->penMotionAction(time, rs, penPos, penPosViewport, 1.); /*}*/ if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } if (stat == kOfxStatOK) { return true; } } return false; } bool OfxEffectInstance::onOverlayPenUp(double /*scaleX*/, double /*scaleY*/, const QPointF & viewportPos, const QPointF & pos) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxPointD penPos; penPos.x = pos.x(); penPos.y = pos.y(); OfxPointI penPosViewport; penPosViewport.x = viewportPos.x(); penPosViewport.y = viewportPos.y(); OfxTime time = getApp()->getTimeLine()->currentFrame(); /* ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, view, false, 0); */ SET_CAN_SET_VALUE(true); OfxStatus stat = _overlayInteract->penUpAction(time, rs, penPos, penPosViewport, 1.); if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } if (stat == kOfxStatOK) { _penDown = false; return true; } } return false; } bool OfxEffectInstance::onOverlayKeyDown(double /*scaleX*/, double /*scaleY*/, Natron::Key key, Natron::KeyboardModifiers /*modifiers*/) { if (!_initialized) { return false;; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); QByteArray keyStr; /* ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); */ SET_CAN_SET_VALUE(true); OfxStatus stat = _overlayInteract->keyDownAction( time, rs, (int)key, keyStr.data() ); if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } if (stat == kOfxStatOK) { return true; } } return false; } bool OfxEffectInstance::onOverlayKeyUp(double /*scaleX*/, double /*scaleY*/, Natron::Key key, Natron::KeyboardModifiers /* modifiers*/) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); QByteArray keyStr; /* ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); */ SET_CAN_SET_VALUE(true); OfxStatus stat = _overlayInteract->keyUpAction( time, rs, (int)key, keyStr.data() ); if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); if (stat == kOfxStatOK) { return true; } ; } return false; } bool OfxEffectInstance::onOverlayKeyRepeat(double /*scaleX*/, double /*scaleY*/, Natron::Key key, Natron::KeyboardModifiers /*modifiers*/) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); QByteArray keyStr; /* ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); */ SET_CAN_SET_VALUE(true); OfxStatus stat = _overlayInteract->keyRepeatAction( time, rs, (int)key, keyStr.data() ); if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } if (stat == kOfxStatOK) { return true; } } return false; } bool OfxEffectInstance::onOverlayFocusGained(double /*scaleX*/, double /*scaleY*/) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); OfxStatus stat; /* if (getRecursionLevel() == 1) { ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); stat = _overlayInteract->gainFocusAction(time, rs); } else {*/ SET_CAN_SET_VALUE(true); stat = _overlayInteract->gainFocusAction(time, rs); /*}*/ assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); if (stat == kOfxStatOK) { return true; } } return false; } bool OfxEffectInstance::onOverlayFocusLost(double /*scaleX*/, double /*scaleY*/) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); OfxStatus stat; /*if (getRecursionLevel() == 1) { ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); stat = _overlayInteract->loseFocusAction(time, rs); } else {*/ SET_CAN_SET_VALUE(true); stat = _overlayInteract->loseFocusAction(time, rs); /*}*/ assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); if (stat == kOfxStatOK) { return true; } } return false; } bool OfxEffectInstance::hasOverlay() const { return _overlayInteract != NULL; } static std::string natronValueChangedReasonToOfxValueChangedReason(Natron::ValueChangedReasonEnum reason) { switch (reason) { case Natron::eValueChangedReasonUserEdited: case Natron::eValueChangedReasonNatronGuiEdited: return kOfxChangeUserEdited; case Natron::eValueChangedReasonPluginEdited: case Natron::eValueChangedReasonNatronInternalEdited: case Natron::eValueChangedReasonSlaveRefresh: case Natron::eValueChangedReasonRestoreDefault: return kOfxChangePluginEdited; case Natron::eValueChangedReasonTimeChanged: return kOfxChangeTime; default: assert(false); // all Natron reasons should be processed return ""; } } void OfxEffectInstance::knobChanged(KnobI* k, Natron::ValueChangedReasonEnum reason, int view, SequenceTime time, bool originatedFromMainThread) { if (!_initialized) { return; } ///If the param changed is a button and the node is disabled don't do anything which might ///trigger an analysis if ( (reason == eValueChangedReasonUserEdited) && dynamic_cast<Button_Knob*>(k) && _node->isNodeDisabled() ) { return; } if ( _renderButton && ( k == _renderButton.get() ) ) { ///don't do anything since it is handled upstream return; } // OFX::Host::Param::paramSetValue() does it for us when it's edited by the plugin bool canCallInstanceChangedAction = reason != Natron::eValueChangedReasonPluginEdited; std::string ofxReason = natronValueChangedReasonToOfxValueChangedReason(reason); assert( !ofxReason.empty() ); // crashes when resetting to defaults OfxPointD renderScale; renderScale.x = renderScale.y = 1; OfxStatus stat = kOfxStatOK; int recursionLevel = getRecursionLevel(); if (canCallInstanceChangedAction) { if (recursionLevel == 1) { SET_CAN_SET_VALUE(true); ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, true, //< setmipmaplevel? 0); ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. stat = effectInstance()->paramInstanceChangedAction(k->getName(), ofxReason,(OfxTime)time,renderScale); } else { ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. stat = effectInstance()->paramInstanceChangedAction(k->getName(), ofxReason,(OfxTime)time,renderScale); } } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { QString err( QString( getNode()->getName_mt_safe().c_str() ) + ": An error occured while changing parameter " + k->getDescription().c_str() ); appPTR->writeToOfxLog_mt_safe(err); return; } if (QThread::currentThread() == qApp->thread() && originatedFromMainThread) { //< change didnt occur in main-thread in the first, palce don't attempt to draw the overlay ///Run the following only in the main-thread if ( _effect->isClipPreferencesSlaveParam( k->getName() ) ) { RECURSIVE_ACTION(); checkOFXClipPreferences_public(time, renderScale, ofxReason,true, true); } if (_overlayInteract) { if (std::find(_overlaySlaves.begin(), _overlaySlaves.end(), (void*)k) != _overlaySlaves.end()) { incrementRedrawNeededCounter(); } if (recursionLevel == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } } } } // knobChanged void OfxEffectInstance::beginKnobsValuesChanged(Natron::ValueChangedReasonEnum reason) { if (!_initialized) { return; } RECURSIVE_ACTION(); SET_CAN_SET_VALUE(true); ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. (void)effectInstance()->beginInstanceChangedAction(natronValueChangedReasonToOfxValueChangedReason(reason)); } void OfxEffectInstance::endKnobsValuesChanged(Natron::ValueChangedReasonEnum reason) { if (!_initialized) { return; } RECURSIVE_ACTION(); SET_CAN_SET_VALUE(true); ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. (void)effectInstance()->endInstanceChangedAction(natronValueChangedReasonToOfxValueChangedReason(reason)); } void OfxEffectInstance::purgeCaches() { // The kOfxActionPurgeCaches is an action that may be passed to a plug-in instance from time to time in low memory situations. Instances recieving this action should destroy any data structures they may have and release the associated memory, they can later reconstruct this from the effect's parameter set and associated information. http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxActionPurgeCaches OfxStatus stat; { SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->purgeCachesAction(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } // The kOfxActionSyncPrivateData action is called when a plugin should synchronise any private data structures to its parameter set. This generally occurs when an effect is about to be saved or copied, but it could occur in other situations as well. http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxActionSyncPrivateData { RECURSIVE_ACTION(); SET_CAN_SET_VALUE(true); ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. stat = _effect->syncPrivateDataAction(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } } int OfxEffectInstance::getMajorVersion() const { return effectInstance()->getPlugin()->getVersionMajor(); } int OfxEffectInstance::getMinorVersion() const { return effectInstance()->getPlugin()->getVersionMinor(); } bool OfxEffectInstance::supportsTiles() const { OFX::Host::ImageEffect::ClipInstance* outputClip = effectInstance()->getClip(kOfxImageEffectOutputClipName); if (!outputClip) { return false; } return effectInstance()->supportsTiles() && outputClip->supportsTiles(); } bool OfxEffectInstance::supportsMultiResolution() const { return effectInstance()->supportsMultiResolution(); } void OfxEffectInstance::beginEditKnobs() { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); effectInstance()->beginInstanceEditAction(); } void OfxEffectInstance::onSyncPrivateDataRequested() { ///Can only be called in the main thread assert( QThread::currentThread() == qApp->thread() ); RECURSIVE_ACTION(); ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. SET_CAN_SET_VALUE(true); effectInstance()->syncPrivateDataAction(); } void OfxEffectInstance::addAcceptedComponents(int inputNb, std::list<Natron::ImageComponentsEnum>* comps) { if (inputNb >= 0) { OfxClipInstance* clip = getClipCorrespondingToInput(inputNb); assert(clip); const std::vector<std::string> & supportedComps = clip->getSupportedComponents(); for (U32 i = 0; i < supportedComps.size(); ++i) { try { comps->push_back( OfxClipInstance::ofxComponentsToNatronComponents(supportedComps[i]) ); } catch (const std::runtime_error &e) { // ignore unsupported components } } } else { assert(inputNb == -1); OfxClipInstance* clip = dynamic_cast<OfxClipInstance*>( effectInstance()->getClip(kOfxImageEffectOutputClipName) ); assert(clip); const std::vector<std::string> & supportedComps = clip->getSupportedComponents(); for (U32 i = 0; i < supportedComps.size(); ++i) { try { comps->push_back( OfxClipInstance::ofxComponentsToNatronComponents(supportedComps[i]) ); } catch (const std::runtime_error &e) { // ignore unsupported components } } } } void OfxEffectInstance::addSupportedBitDepth(std::list<Natron::ImageBitDepthEnum>* depths) const { const OFX::Host::Property::Set & prop = effectInstance()->getPlugin()->getDescriptor().getParamSetProps(); int dim = prop.getDimension(kOfxImageEffectPropSupportedPixelDepths); for (int i = 0; i < dim; ++i) { const std::string & depth = prop.getStringProperty(kOfxImageEffectPropSupportedPixelDepths,i); try { depths->push_back( OfxClipInstance::ofxDepthToNatronDepth(depth) ); } catch (const std::runtime_error &e) { // ignore unsupported bitdepth } } } void OfxEffectInstance::getPreferredDepthAndComponents(int inputNb, Natron::ImageComponentsEnum* comp, Natron::ImageBitDepthEnum* depth) const { OfxClipInstance* clip; if (inputNb == -1) { clip = dynamic_cast<OfxClipInstance*>( _effect->getClip(kOfxImageEffectOutputClipName) ); } else { clip = getClipCorrespondingToInput(inputNb); } assert(clip); if (getRecursionLevel() > 0) { ///Someone took the read (all actions) or write (getClipPreferences action)lock already *comp = OfxClipInstance::ofxComponentsToNatronComponents( clip->getComponents() ); *depth = OfxClipInstance::ofxDepthToNatronDepth( clip->getPixelDepth() ); } else { ///Take the preferences lock to be sure we're not writing them QReadLocker l(_preferencesLock); *comp = OfxClipInstance::ofxComponentsToNatronComponents( clip->getComponents() ); *depth = OfxClipInstance::ofxDepthToNatronDepth( clip->getPixelDepth() ); } } Natron::SequentialPreferenceEnum OfxEffectInstance::getSequentialPreference() const { int sequential = _effect->getPlugin()->getDescriptor().getProps().getIntProperty(kOfxImageEffectInstancePropSequentialRender); switch (sequential) { case 0: return Natron::eSequentialPreferenceNotSequential; case 1: return Natron::eSequentialPreferenceOnlySequential; case 2: return Natron::eSequentialPreferencePreferSequential; default: return Natron::eSequentialPreferenceNotSequential; break; } } Natron::ImagePremultiplicationEnum OfxEffectInstance::getOutputPremultiplication() const { const std::string & str = ofxGetOutputPremultiplication(); if (str == kOfxImagePreMultiplied) { return Natron::eImagePremultiplicationPremultiplied; } else if (str == kOfxImageUnPreMultiplied) { return Natron::eImagePremultiplicationUnPremultiplied; } else { return Natron::eImagePremultiplicationOpaque; } } const std::string & OfxEffectInstance::ofxGetOutputPremultiplication() const { static const std::string v(kOfxImagePreMultiplied); OFX::Host::ImageEffect::ClipInstance* clip = effectInstance()->getClip(kOfxImageEffectOutputClipName); assert(clip); if (getRecursionLevel() > 0) { const std::string & premult = effectInstance()->getOutputPreMultiplication(); ///if the output has something, use it, otherwise default to premultiplied if ( !premult.empty() ) { return premult; } else { return v; } } else { ///Take the preferences lock to be sure we're not writing them QReadLocker l(_preferencesLock); const std::string & premult = effectInstance()->getOutputPreMultiplication(); ///if the output has something, use it, otherwise default to premultiplied if ( !premult.empty() ) { return premult; } else { return v; } } } double OfxEffectInstance::getPreferredAspectRatio() const { OFX::Host::ImageEffect::ClipInstance* clip = effectInstance()->getClip(kOfxImageEffectOutputClipName); assert(clip); if (getRecursionLevel() > 0) { return clip->getAspectRatio(); } else { ///Take the preferences lock to be sure we're not writing them QReadLocker l(_preferencesLock); return clip->getAspectRatio(); } } double OfxEffectInstance::getPreferredFrameRate() const { OFX::Host::ImageEffect::ClipInstance* clip = effectInstance()->getClip(kOfxImageEffectOutputClipName); assert(clip); if (getRecursionLevel() > 0) { return clip->getFrameRate(); } else { ///Take the preferences lock to be sure we're not writing them QReadLocker l(_preferencesLock); return clip->getFrameRate(); } } bool OfxEffectInstance::getCanTransform() const { //use OFX_EXTENSIONS_NUKE return effectInstance()->canTransform(); } bool OfxEffectInstance::getCanApplyTransform(Natron::EffectInstance** effect) const { OfxClipInstance* transformClip = 0; bool canApply = effectInstance()->getCanApplyTransform(&transformClip); if (!transformClip || !canApply) { return false; } *effect = transformClip->getAssociatedNode(); return true; } Natron::StatusEnum OfxEffectInstance::getTransform(SequenceTime time, const RenderScale& renderScale, //< the plug-in accepted scale int view, Natron::EffectInstance** inputToTransform, Transform::Matrix3x3* transform) { const std::string field = kOfxImageFieldNone; // TODO: support interlaced data std::string clipName; double tmpTransform[9]; OfxStatus stat ; { bool skipDiscarding = false; if (getRecursionLevel() > 1) { qDebug() << "renderAction cannot be called recursively as an action. Please check this."; skipDiscarding = true; } SET_CAN_SET_VALUE(false); ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true,//< set mipmaplevel ? Natron::Image::getLevelFromScale(renderScale.x)); stat = effectInstance()->getTransformAction((OfxTime)time, field, renderScale, view, clipName, tmpTransform); if (stat == kOfxStatReplyDefault) { return Natron::eStatusReplyDefault; } else if (stat == kOfxStatFailed) { return Natron::eStatusFailed; } } assert(stat == kOfxStatOK); transform->a = tmpTransform[0]; transform->b = tmpTransform[1]; transform->c = tmpTransform[2]; transform->d = tmpTransform[3]; transform->e = tmpTransform[4]; transform->f = tmpTransform[5]; transform->g = tmpTransform[6]; transform->h = tmpTransform[7]; transform->i = tmpTransform[8]; OFX::Host::ImageEffect::ClipInstance* clip = effectInstance()->getClip(clipName); assert(clip); OfxClipInstance* natronClip = dynamic_cast<OfxClipInstance*>(clip); if (!natronClip) { return Natron::eStatusFailed; } *inputToTransform = natronClip->getAssociatedNode(); return Natron::eStatusOK; } void OfxEffectInstance::rerouteInputAndSetTransform(int inputNb,Natron::EffectInstance* newInput, int newInputNb,const Transform::Matrix3x3& m) { OfxClipInstance* clip = getClipCorrespondingToInput(inputNb); assert(clip); clip->setTransformAndReRouteInput(m, newInput, newInputNb); } void OfxEffectInstance::clearTransform(int inputNb) { OfxClipInstance* clip = getClipCorrespondingToInput(inputNb); assert(clip); clip->clearTransform(); } bool OfxEffectInstance::isFrameVarying() const { return effectInstance()->isFrameVarying(); } bool OfxEffectInstance::doesTemporalClipAccess() const { return effectInstance()->temporalAccess(); } OfxEffectInstance: tuttlegamma goes to Color/Math // Natron // /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012. * contact: immarespond at gmail dot com * */ #include "OfxEffectInstance.h" #include <locale> #include <limits> #include <stdexcept> #include <QtCore/QDebug> #include <QByteArray> #include <QReadWriteLock> #include <QPointF> #include "Global/Macros.h" #include <ofxhPluginCache.h> #include <ofxhPluginAPICache.h> #include <ofxhImageEffect.h> #include <ofxhImageEffectAPI.h> #include <ofxhHost.h> #include <tuttle/ofxReadWrite.h> #include "Engine/AppManager.h" #include "Engine/OfxParamInstance.h" #include "Engine/OfxClipInstance.h" #include "Engine/OfxImageEffectInstance.h" #include "Engine/OfxOverlayInteract.h" #include "Engine/ViewerInstance.h" #include "Engine/TimeLine.h" #include "Engine/Project.h" #include "Engine/KnobFile.h" #include "Engine/KnobTypes.h" #include "Engine/AppInstance.h" #include "Engine/NodeSerialization.h" #include "Engine/Node.h" #include "Engine/Transform.h" using namespace Natron; using std::cout; using std::endl; namespace { /** * @class This class is helpful to set thread-storage data on the clips of an effect * When destroyed, it is removed from the clips, ensuring they are removed. * It is to be instantiated right before calling the action that will need the per thread-storage * This way even if exceptions are thrown, clip thread-storage will be purged. * * All the info set on clip thread-storage are "cached" data that might be needed by a call of the OpenFX API which would * otherwise require a recursive action call, which is forbidden by the specification. * The more you pass parameters, the safer you are that the plug-in will not attempt recursive action calls but the more expensive * it is. **/ class ClipsThreadStorageSetter { public: ClipsThreadStorageSetter(OfxImageEffectInstance* effect, bool skipDiscarding, //< this is in case a recursive action is called bool setView, int view, bool setMipmapLevel, unsigned int mipMapLevel) : effect(effect) , skipDiscarding(skipDiscarding) , viewSet(setView) , mipMapLevelSet(setMipmapLevel) { if (setView) { effect->setClipsView(view); } if (setMipmapLevel) { effect->setClipsMipMapLevel(mipMapLevel); } } ~ClipsThreadStorageSetter() { if (!skipDiscarding) { if (viewSet) { effect->discardClipsView(); } if (mipMapLevelSet) { effect->discardClipsMipMapLevel(); } } } private: OfxImageEffectInstance* effect; bool skipDiscarding; bool viewSet; bool mipMapLevelSet; }; } OfxEffectInstance::OfxEffectInstance(boost::shared_ptr<Natron::Node> node) : AbstractOfxEffectInstance(node) , _effect() , _natronPluginID() , _isOutput(false) , _penDown(false) , _overlayInteract(0) , _overlaySlaves() , _created(false) , _initialized(false) , _renderButton() , _renderSafety(EffectInstance::eRenderSafetyUnsafe) , _wasRenderSafetySet(false) , _renderSafetyLock(new QReadWriteLock) , _context(eContextNone) , _preferencesLock(new QReadWriteLock(QReadWriteLock::Recursive)) #ifdef DEBUG , _canSetValue() #endif { QObject::connect( this, SIGNAL( syncPrivateDataRequested() ), this, SLOT( onSyncPrivateDataRequested() ) ); } void OfxEffectInstance::createOfxImageEffectInstance(OFX::Host::ImageEffect::ImageEffectPlugin* plugin, const std::string & context, const NodeSerialization* serialization, const std::list<boost::shared_ptr<KnobSerialization> >& paramValues, bool allowFileDialogs, bool disableRenderScaleSupport) { /*Replicate of the code in OFX::Host::ImageEffect::ImageEffectPlugin::createInstance. We need to pass more parameters to the constructor . That means we cannot create it in the virtual function newInstance. Thus we create it before instanciating the OfxImageEffect. The problem is that calling OFX::Host::ImageEffect::ImageEffectPlugin::createInstance creates the OfxImageEffect and calls populate(). populate() will actually create all OfxClipInstance and OfxParamInstance. All these subclasses need a valid pointer to an this. Hence we need to set the pointer to this in OfxImageEffect BEFORE calling populate(). */ ///Only called from the main thread. assert( QThread::currentThread() == qApp->thread() ); ContextEnum ctx = mapToContextEnum(context); if (disableRenderScaleSupport || ctx == eContextWriter) { setAsOutputNode(); // Writers don't support render scale (full-resolution images are written to disk) setSupportsRenderScaleMaybe(eSupportsNo); } if (ctx == eContextReader) { // Tuttle readers don't support render scale as of 11/8/2014, but may crash (at least in debug configuration). // TuttleAVReader crashes on an assert in copy_and_convert_pixels( avSrcView, this->_dstView ); std::string prefix("tuttle."); if ( !plugin->getIdentifier().compare(0, prefix.size(), prefix) ) { setSupportsRenderScaleMaybe(eSupportsNo); } } OFX::Host::PluginHandle* ph = plugin->getPluginHandle(); assert( ph->getOfxPlugin() ); assert(ph->getOfxPlugin()->mainEntry); (void)ph; OFX::Host::ImageEffect::Descriptor* desc = NULL; desc = plugin->getContext(context); if (!desc) { throw std::runtime_error(std::string("Failed to get description for OFX plugin in context ") + context); } _context = mapToContextEnum(context); std::string images; try { _effect = new Natron::OfxImageEffectInstance(plugin,*desc,context,false); assert(_effect); _effect->setOfxEffectInstance( dynamic_cast<OfxEffectInstance*>(this) ); _natronPluginID = plugin->getIdentifier(); // _natronPluginID = generateImageEffectClassName( _effect->getPlugin()->getIdentifier(), // _effect->getPlugin()->getVersionMajor(), // _effect->getPlugin()->getVersionMinor(), // _effect->getDescriptor().getShortLabel(), // _effect->getDescriptor().getLabel(), // _effect->getDescriptor().getLongLabel(), // _effect->getDescriptor().getPluginGrouping() ); blockEvaluation(); OfxStatus stat; { SET_CAN_SET_VALUE(true); stat = _effect->populate(); initializeContextDependentParams(); _effect->addParamsToTheirParents(); if (stat != kOfxStatOK) { throw std::runtime_error("Error while populating the Ofx image effect"); } assert( _effect->getPlugin() ); assert( _effect->getPlugin()->getPluginHandle() ); assert( _effect->getPlugin()->getPluginHandle()->getOfxPlugin() ); assert(_effect->getPlugin()->getPluginHandle()->getOfxPlugin()->mainEntry); getNode()->createRotoContextConditionnally(); getNode()->initializeInputs(); getNode()->initializeKnobs( serialization ? *serialization : NodeSerialization( getApp() ), disableRenderScaleSupport ? 1 : 0 ); ///before calling the createInstanceAction, load values if ( serialization && !serialization->isNull() ) { getNode()->loadKnobs(*serialization); } if (!paramValues.empty()) { getNode()->setValuesFromSerialization(paramValues); } ////////////////////////////////////////////////////// ///////For READERS & WRITERS only we open an image file dialog if (allowFileDialogs && isReader() && !(serialization && !serialization->isNull()) && paramValues.empty()) { images = getApp()->openImageFileDialog(); } else if (allowFileDialogs && isWriter() && !(serialization && !serialization->isNull()) && paramValues.empty()) { images = getApp()->saveImageFileDialog(); } if (!images.empty()) { boost::shared_ptr<KnobSerialization> defaultFile = createDefaultValueForParam(kOfxImageEffectFileParamName, images); CreateNodeArgs::DefaultValuesList list; list.push_back(defaultFile); getNode()->setValuesFromSerialization(list); } ////////////////////////////////////////////////////// { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->createInstanceAction(); } _created = true; unblockEvaluation(); } // SET_CAN_SET_VALUE(true); if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { throw std::runtime_error("Could not create effect instance for plugin"); } OfxPointD scaleOne; scaleOne.x = 1.; scaleOne.y = 1.; // Try to set renderscale support at plugin creation. // This is not always possible (e.g. if a param has a wrong value). if (supportsRenderScaleMaybe() == eSupportsMaybe) { // does the effect support renderscale? OfxRangeD range; range.min = 0; OfxStatus tdstat = _effect->getTimeDomainAction(range); if ( (tdstat == kOfxStatOK) || (tdstat == kOfxStatReplyDefault) ) { ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? 0, true, 0); double time = range.min; OfxRectD rod; OfxStatus rodstat = _effect->getRegionOfDefinitionAction(time, scaleOne, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { OfxPointD scale; scale.x = 0.5; scale.y = 0.5; rodstat = _effect->getRegionOfDefinitionAction(time, scale, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { setSupportsRenderScaleMaybe(eSupportsYes); } else { setSupportsRenderScaleMaybe(eSupportsNo); } } } } // Check here that bitdepth and components given by getClipPreferences are supported by the effect. // If we don't, the following assert will crash at the beginning of EffectInstance::renderRoIInternal(): // assert(isSupportedBitDepth(outputDepth) && isSupportedComponent(-1, outputComponents)); // If a component/bitdepth is not supported (this is probably a plugin bug), use the closest one, but don't crash Natron. checkOFXClipPreferences_public(getApp()->getTimeLine()->currentFrame(), scaleOne, kOfxChangeUserEdited,true, false); // check that the plugin supports kOfxImageComponentRGBA for all the clips /*const std::vector<OFX::Host::ImageEffect::ClipDescriptor*> & clips = effectInstance()->getDescriptor().getClipsByOrder(); for (U32 i = 0; i < clips.size(); ++i) { if ( (clips[i]->getProps().findStringPropValueIndex(kOfxImageEffectPropSupportedComponents, kOfxImageComponentRGBA) == -1) && !clips[i]->isOptional() && !clips[i]->isMask() ) { appPTR->writeToOfxLog_mt_safe( QString( plugin->getDescriptor().getLabel().c_str() ) + "RGBA components not supported by OFX plugin in context " + QString( context.c_str() ) ); throw std::runtime_error(std::string("RGBA components not supported by OFX plugin in context ") + context); } }*/ } catch (const std::exception & e) { qDebug() << "Error: Caught exception while creating OfxImageEffectInstance" << ": " << e.what(); throw; } catch (...) { qDebug() << "Error: Caught exception while creating OfxImageEffectInstance"; throw; } _initialized = true; ///Now that the instance is created, make sure instanceChangedActino is called for all extra default values ///that we set for (std::list<boost::shared_ptr<KnobSerialization> >::const_iterator it = paramValues.begin(); it != paramValues.end();++it) { boost::shared_ptr<KnobI> knob = getKnobByName((*it)->getName()); assert(knob); for (int i = 0; i < knob->getDimension(); ++i) { knob->evaluateValueChange(i, Natron::eValueChangedReasonUserEdited, true); } } if (!images.empty()) { boost::shared_ptr<KnobI> fileNameKnob = getKnobByName(kOfxImageEffectFileParamName); if (fileNameKnob) { fileNameKnob->evaluateValueChange(0,Natron::eValueChangedReasonUserEdited, true); } } } // createOfxImageEffectInstance OfxEffectInstance::~OfxEffectInstance() { if (_overlayInteract) { delete _overlayInteract; } delete _effect; delete _renderSafetyLock; delete _preferencesLock; } bool OfxEffectInstance::isEffectCreated() const { return _created; } void OfxEffectInstance::initializeContextDependentParams() { assert(_context != eContextNone); if ( isWriter() ) { _renderButton = Natron::createKnob<Button_Knob>(this, "Render"); _renderButton->setHintToolTip("Starts rendering the specified frame range."); _renderButton->setAsRenderButton(); } } std::string OfxEffectInstance::getDescription() const { assert(_context != eContextNone); if ( effectInstance() ) { return effectInstance()->getProps().getStringProperty(kOfxPropPluginDescription); } else { return ""; } } void OfxEffectInstance::tryInitializeOverlayInteracts() { assert(_context != eContextNone); /*create overlay instance if any*/ OfxPluginEntryPoint *overlayEntryPoint = _effect->getOverlayInteractMainEntry(); if (overlayEntryPoint) { _overlayInteract = new OfxOverlayInteract(*_effect,8,true); RenderScale s; effectInstance()->getRenderScaleRecursive(s.x, s.y); { ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? 0, true, 0); { SET_CAN_SET_VALUE(true); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); _overlayInteract->createInstanceAction(); } } ///Fetch all parameters that are overlay slave std::vector<std::string> slaveParams; _overlayInteract->getSlaveToParam(slaveParams); for (U32 i = 0; i < slaveParams.size(); ++i) { boost::shared_ptr<KnobI> param = getKnobByName(slaveParams[i]); assert(param); _overlaySlaves.push_back((void*)param.get()); } getApp()->redrawAllViewers(); } ///for each param, if it has a valid custom interact, create it const std::list<OFX::Host::Param::Instance*> & params = effectInstance()->getParamList(); for (std::list<OFX::Host::Param::Instance*>::const_iterator it = params.begin(); it != params.end(); ++it) { OfxParamToKnob* paramToKnob = dynamic_cast<OfxParamToKnob*>(*it); assert(paramToKnob); OFX::Host::Interact::Descriptor & interactDesc = paramToKnob->getInteractDesc(); if (interactDesc.getState() == OFX::Host::Interact::eDescribed) { boost::shared_ptr<KnobI> knob = paramToKnob->getKnob(); boost::shared_ptr<OfxParamOverlayInteract> overlay( new OfxParamOverlayInteract( knob.get(),interactDesc, effectInstance()->getHandle() ) ); { SET_CAN_SET_VALUE(true); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); overlay->createInstanceAction(); } knob->setCustomInteract(overlay); } } } bool OfxEffectInstance::isOutput() const { assert(_context != eContextNone); return _isOutput; } bool OfxEffectInstance::isGenerator() const { #if 0 assert( effectInstance() ); const std::set<std::string> & contexts = effectInstance()->getPlugin()->getContexts(); std::set<std::string>::const_iterator foundGenerator = contexts.find(kOfxImageEffectContextGenerator); std::set<std::string>::const_iterator foundReader = contexts.find(kOfxImageEffectContextReader); if ( ( foundGenerator != contexts.end() ) || ( foundReader != contexts.end() ) ) { return true; } return false; #else assert(_context != eContextNone); return _context == eContextGenerator || _context == eContextReader; #endif } bool OfxEffectInstance::isReader() const { #if 0 assert( effectInstance() ); const std::set<std::string> & contexts = effectInstance()->getPlugin()->getContexts(); std::set<std::string>::const_iterator foundReader = contexts.find(kOfxImageEffectContextReader); if ( foundReader != contexts.end() ) { return true; } return false; #else assert(_context != eContextNone); return _context == eContextReader; #endif } bool OfxEffectInstance::isWriter() const { #if 0 assert(_context != eContextNone); assert( effectInstance() ); const std::set<std::string> & contexts = effectInstance()->getPlugin()->getContexts(); std::set<std::string>::const_iterator foundWriter = contexts.find(kOfxImageEffectContextWriter); if ( foundWriter != contexts.end() ) { return true; } return false; #else assert(_context != eContextNone); return _context == eContextWriter; #endif } bool OfxEffectInstance::isGeneratorAndFilter() const { assert(_context != eContextNone); const std::set<std::string> & contexts = effectInstance()->getPlugin()->getContexts(); std::set<std::string>::const_iterator foundGenerator = contexts.find(kOfxImageEffectContextGenerator); std::set<std::string>::const_iterator foundGeneral = contexts.find(kOfxImageEffectContextGeneral); return foundGenerator != contexts.end() && foundGeneral != contexts.end(); } /*group is a string as such: Toto/Superplugins/blabla This functions extracts the all parts of such a grouping, e.g in this case it would return [Toto,Superplugins,blabla].*/ static QStringList ofxExtractAllPartsOfGrouping(const QString & pluginIdentifier, int /*versionMajor*/, int /*versionMinor*/, const QString & /*pluginLabel*/, const QString & str) { QString s(str); s.replace( QChar('\\'),QChar('/') ); QStringList out; if ( pluginIdentifier.startsWith("com.genarts.sapphire.") || s.startsWith("Sapphire ") || str.startsWith(" Sapphire ") ) { out.push_back("Sapphire"); } else if ( pluginIdentifier.startsWith("com.genarts.monsters.") || s.startsWith("Monsters ") || str.startsWith(" Monsters ") ) { out.push_back("Monsters"); } else if (pluginIdentifier == "uk.co.thefoundry.keylight.keylight") { s = PLUGIN_GROUP_KEYER; } else if (pluginIdentifier == "uk.co.thefoundry.noisetools.denoise") { s = PLUGIN_GROUP_FILTER; } else if ( (pluginIdentifier == "tuttle.avreader") || (pluginIdentifier == "tuttle.avwriter") || (pluginIdentifier == "tuttle.dpxwriter") || (pluginIdentifier == "tuttle.exrreader") || (pluginIdentifier == "tuttle.exrwriter") || (pluginIdentifier == "tuttle.imagemagickreader") || (pluginIdentifier == "tuttle.jpeg2000reader") || (pluginIdentifier == "tuttle.jpeg2000writer") || (pluginIdentifier == "tuttle.jpegreader") || (pluginIdentifier == "tuttle.jpegwriter") || (pluginIdentifier == "tuttle.oiioreader") || (pluginIdentifier == "tuttle.oiiowriter") || (pluginIdentifier == "tuttle.pngreader") || (pluginIdentifier == "tuttle.pngwriter") || (pluginIdentifier == "tuttle.rawreader") || (pluginIdentifier == "tuttle.turbojpegreader") || (pluginIdentifier == "tuttle.turbojpegwriter") ) { out.push_back(PLUGIN_GROUP_IMAGE); if ( pluginIdentifier.endsWith("reader") ) { s = PLUGIN_GROUP_IMAGE_READERS; } else { s = PLUGIN_GROUP_IMAGE_WRITERS; } } else if ( (pluginIdentifier == "tuttle.checkerboard") || (pluginIdentifier == "tuttle.colorbars") || (pluginIdentifier == "tuttle.colorcube") || // TuttleColorCube (pluginIdentifier == "tuttle.colorgradient") || (pluginIdentifier == "tuttle.colorwheel") || (pluginIdentifier == "tuttle.constant") || (pluginIdentifier == "tuttle.inputbuffer") || (pluginIdentifier == "tuttle.outputbuffer") || (pluginIdentifier == "tuttle.ramp") || (pluginIdentifier == "tuttle.seexpr") ) { s = PLUGIN_GROUP_IMAGE; } else if ( (pluginIdentifier == "tuttle.bitdepth") || (pluginIdentifier == "tuttle.colorgradation") || (pluginIdentifier == "tuttle.colorspace") || (pluginIdentifier == "tuttle.colorsuppress") || (pluginIdentifier == "tuttle.colortransfer") || (pluginIdentifier == "tuttle.colortransform") || (pluginIdentifier == "tuttle.ctl") || (pluginIdentifier == "tuttle.invert") || (pluginIdentifier == "tuttle.lut") || (pluginIdentifier == "tuttle.normalize") ) { s = PLUGIN_GROUP_COLOR; } else if ( (pluginIdentifier == "tuttle.ocio.colorspace") || (pluginIdentifier == "tuttle.ocio.lut") ) { out.push_back(PLUGIN_GROUP_COLOR); s = "OCIO"; } else if ( (pluginIdentifier == "tuttle.gamma") || (pluginIdentifier == "tuttle.mathoperator") ) { out.push_back(PLUGIN_GROUP_COLOR); s = "Math"; } else if ( (pluginIdentifier == "tuttle.channelshuffle") ) { s = PLUGIN_GROUP_CHANNEL; } else if ( (pluginIdentifier == "tuttle.component") || (pluginIdentifier == "tuttle.fade") || (pluginIdentifier == "tuttle.merge") ) { s = PLUGIN_GROUP_MERGE; } else if ( (pluginIdentifier == "tuttle.anisotropicdiffusion") || (pluginIdentifier == "tuttle.anisotropictensors") || (pluginIdentifier == "tuttle.blur") || (pluginIdentifier == "tuttle.convolution") || (pluginIdentifier == "tuttle.floodfill") || (pluginIdentifier == "tuttle.localmaxima") || (pluginIdentifier == "tuttle.nlmdenoiser") || (pluginIdentifier == "tuttle.sobel") || (pluginIdentifier == "tuttle.thinning") ) { s = PLUGIN_GROUP_FILTER; } else if ( (pluginIdentifier == "tuttle.crop") || (pluginIdentifier == "tuttle.flip") || (pluginIdentifier == "tuttle.lensdistort") || (pluginIdentifier == "tuttle.move2d") || (pluginIdentifier == "tuttle.pinning") || (pluginIdentifier == "tuttle.pushpixel") || (pluginIdentifier == "tuttle.resize") || (pluginIdentifier == "tuttle.swscale") || (pluginIdentifier == "tuttle.warp") ) { s = PLUGIN_GROUP_TRANSFORM; } else if ( (pluginIdentifier == "tuttle.timeshift") ) { s = PLUGIN_GROUP_TIME; } else if ( (pluginIdentifier == "tuttle.text") ) { s = PLUGIN_GROUP_PAINT; } else if ( (pluginIdentifier == "tuttle.basickeyer") || (pluginIdentifier == "tuttle.colorspacekeyer") || (pluginIdentifier == "tuttle.histogramkeyer") || (pluginIdentifier == "tuttle.idkeyer") ) { s = PLUGIN_GROUP_KEYER; } else if ( (pluginIdentifier == "tuttle.colorCube") || // TuttleColorCubeViewer (pluginIdentifier == "tuttle.colorcubeviewer") || (pluginIdentifier == "tuttle.diff") || (pluginIdentifier == "tuttle.dummy") || (pluginIdentifier == "tuttle.histogram") || (pluginIdentifier == "tuttle.imagestatistics") ) { s = PLUGIN_GROUP_OTHER; } else if ( (pluginIdentifier == "tuttle.debugimageeffectapi") ) { out.push_back(PLUGIN_GROUP_OTHER); s = "Test"; } // The following plugins are pretty much useless for use within Natron, keep them in the Tuttle group: /* (pluginIdentifier == "tuttle.print") || (pluginIdentifier == "tuttle.viewer") || */ return out + s.split('/'); } // ofxExtractAllPartsOfGrouping QStringList AbstractOfxEffectInstance::makePluginGrouping(const std::string & pluginIdentifier, int versionMajor, int versionMinor, const std::string & pluginLabel, const std::string & grouping) { //printf("%s,%s\n",pluginLabel.c_str(),grouping.c_str()); return ofxExtractAllPartsOfGrouping( pluginIdentifier.c_str(), versionMajor, versionMinor, pluginLabel.c_str(),grouping.c_str() ); } std::string AbstractOfxEffectInstance::makePluginLabel(const std::string & shortLabel, const std::string & label, const std::string & longLabel) { std::string labelToUse = label; if ( labelToUse.empty() ) { labelToUse = shortLabel; } if ( labelToUse.empty() ) { labelToUse = longLabel; } return labelToUse; } std::string OfxEffectInstance::getPluginID() const { assert(_context != eContextNone); return _natronPluginID; } std::string OfxEffectInstance::getPluginLabel() const { assert(_context != eContextNone); assert(_effect); return makePluginLabel( _effect->getDescriptor().getShortLabel(), _effect->getDescriptor().getLabel(), _effect->getDescriptor().getLongLabel() ); } void OfxEffectInstance::getPluginGrouping(std::list<std::string>* grouping) const { assert(_context != eContextNone); std::string groupStr = effectInstance()->getPluginGrouping(); std::string label = getPluginLabel(); const OFX::Host::ImageEffect::ImageEffectPlugin *p = effectInstance()->getPlugin(); QStringList groups = ofxExtractAllPartsOfGrouping( p->getIdentifier().c_str(), p->getVersionMajor(), p->getVersionMinor(), label.c_str(), groupStr.c_str() ); for (int i = 0; i < groups.size(); ++i) { grouping->push_back( groups[i].toStdString() ); } } std::string OfxEffectInstance::getInputLabel(int inputNb) const { assert(_context != eContextNone); MappedInputV copy = inputClipsCopyWithoutOutput(); if ( inputNb < (int)copy.size() ) { return copy[copy.size() - 1 - inputNb]->getShortLabel(); } else { return EffectInstance::getInputLabel(inputNb); } } OfxEffectInstance::MappedInputV OfxEffectInstance::inputClipsCopyWithoutOutput() const { assert(_context != eContextNone); assert( effectInstance() ); const std::vector<OFX::Host::ImageEffect::ClipDescriptor*> & clips = effectInstance()->getDescriptor().getClipsByOrder(); MappedInputV copy; for (U32 i = 0; i < clips.size(); ++i) { assert(clips[i]); if (clips[i]->getShortLabel() != kOfxImageEffectOutputClipName) { copy.push_back(clips[i]); // cout << "Clip[" << i << "] = " << clips[i]->getShortLabel() << endl; } } return copy; } OfxClipInstance* OfxEffectInstance::getClipCorrespondingToInput(int inputNo) const { assert(_context != eContextNone); OfxEffectInstance::MappedInputV clips = inputClipsCopyWithoutOutput(); assert( inputNo < (int)clips.size() ); OFX::Host::ImageEffect::ClipInstance* clip = _effect->getClip( clips[clips.size() - 1 - inputNo]->getName() ); assert(clip); return dynamic_cast<OfxClipInstance*>(clip); } int OfxEffectInstance::getMaxInputCount() const { assert(_context != eContextNone); const std::string & context = effectInstance()->getContext(); if ( (context == kOfxImageEffectContextReader) || ( context == kOfxImageEffectContextGenerator) ) { return 0; } else { assert( effectInstance() ); int totalClips = effectInstance()->getDescriptor().getClips().size(); return totalClips > 0 ? totalClips - 1 : 0; } } bool OfxEffectInstance::isInputOptional(int inputNb) const { assert(_context != eContextNone); MappedInputV inputs = inputClipsCopyWithoutOutput(); assert( inputNb < (int)inputs.size() ); if ( inputs[inputs.size() - 1 - inputNb]->isOptional() ) { return true; } else { if ( isInputRotoBrush(inputNb) ) { return true; } } return false; } bool OfxEffectInstance::isInputMask(int inputNb) const { assert(_context != eContextNone); MappedInputV inputs = inputClipsCopyWithoutOutput(); assert( inputNb < (int)inputs.size() ); return inputs[inputs.size() - 1 - inputNb]->isMask(); } bool OfxEffectInstance::isInputRotoBrush(int inputNb) const { assert(_context != eContextNone); MappedInputV inputs = inputClipsCopyWithoutOutput(); assert( inputNb < (int)inputs.size() ); ///Maybe too crude ? Not like many plug-ins use the paint context except Natron's roto node. return inputs[inputs.size() - 1 - inputNb]->getName() == "Roto" && getNode()->isRotoNode(); } int OfxEffectInstance::getRotoBrushInputIndex() const { assert(_context != eContextNone); MappedInputV inputs = inputClipsCopyWithoutOutput(); for (U32 i = 0; i < inputs.size(); ++i) { if (inputs[i]->getName() == "Roto") { return inputs.size() - 1 - i; } } return -1; } void OfxEffectInstance::onInputChanged(int inputNo) { if (getApp()->getProject()->isLoadingProject()) { return; } assert(_context != eContextNone); OfxClipInstance* clip = getClipCorrespondingToInput(inputNo); assert(clip); double time = getApp()->getTimeLine()->currentFrame(); RenderScale s; s.x = s.y = 1.; /** * The plug-in might call getImage, set a valid thread storage on the tree. **/ Node::ParallelRenderArgsSetter frameRenderArgs(_node.get(), time, 0 /*view*/, true, false, false, getHash(), true, getApp()->getTimeLine().get()); ///Don't do clip preferences while loading a project, they will be refreshed globally once the project is loaded. ///if all non optional clips are connected, call getClipPrefs ///The clip preferences action is never called until all non optional clips have been attached to the plugin. if (_effect->areAllNonOptionalClipsConnected()) { ///Render scale support might not have been set already because getRegionOfDefinition could have failed until all non optional inputs were connected if (supportsRenderScaleMaybe() == eSupportsMaybe) { OfxRectD rod; OfxPointD scaleOne; scaleOne.x = scaleOne.y = 1.; OfxStatus rodstat = _effect->getRegionOfDefinitionAction(time, scaleOne, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { OfxPointD scale; scale.x = 0.5; scale.y = 0.5; rodstat = _effect->getRegionOfDefinitionAction(time, scale, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { setSupportsRenderScaleMaybe(eSupportsYes); } else { setSupportsRenderScaleMaybe(eSupportsNo); } } } if ( !getApp()->getProject()->isLoadingProject() ) { checkOFXClipPreferences_public(time,s,kOfxChangeUserEdited,true, true); } } { RECURSIVE_ACTION(); SET_CAN_SET_VALUE(true); ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? 0 /*view*/, true, //< setmipmaplevel? 0); _effect->beginInstanceChangedAction(kOfxChangeUserEdited); _effect->clipInstanceChangedAction(clip->getName(), kOfxChangeUserEdited, time, s); _effect->endInstanceChangedAction(kOfxChangeUserEdited); } } /** @brief map a std::string to a context */ OfxEffectInstance::ContextEnum OfxEffectInstance::mapToContextEnum(const std::string &s) { if (s == kOfxImageEffectContextGenerator) { return eContextGenerator; } if (s == kOfxImageEffectContextFilter) { return eContextFilter; } if (s == kOfxImageEffectContextTransition) { return eContextTransition; } if (s == kOfxImageEffectContextPaint) { return eContextPaint; } if (s == kOfxImageEffectContextGeneral) { return eContextGeneral; } if (s == kOfxImageEffectContextRetimer) { return eContextRetimer; } if (s == kOfxImageEffectContextReader) { return eContextReader; } if (s == kOfxImageEffectContextWriter) { return eContextWriter; } qDebug() << "OfxEffectInstance::mapToContextEnum: Unknown image effect context '" << s.c_str() << "'"; throw std::invalid_argument(s); } /** * @brief The purpose of this function is to allow Natron to modify slightly the values returned in the getClipPreferencesAction * by the plugin so that we can minimize the amount of Natron::Image::convertToFormat calls. **/ static void clipPrefsProxy(OfxEffectInstance* self, double time, std::map<OfxClipInstance*,OfxImageEffectInstance::ClipPrefs>& clipPrefs, OfxImageEffectInstance::EffectPrefs& effectPrefs, std::list<OfxClipInstance*>& changedClips) { ///We remap all the input clips components to be the same as the output clip, except for the masks. OfxClipInstance* outputClip = dynamic_cast<OfxClipInstance*>(self->effectInstance()->getClip(kOfxImageEffectOutputClipName)); assert(outputClip); std::map<OfxClipInstance*,OfxImageEffectInstance::ClipPrefs>::iterator foundOutputPrefs = clipPrefs.find(outputClip); assert(foundOutputPrefs != clipPrefs.end()); std::string outputClipDepth = foundOutputPrefs->second.bitdepth; Natron::ImageBitDepthEnum outputClipDepthNatron = OfxClipInstance::ofxDepthToNatronDepth(outputClipDepth); ///Set a warning on the node if the bitdepth conversion from one of the input clip to the output clip is lossy QString bitDepthWarning("This nodes converts higher bit depths images from its inputs to work. As " "a result of this process, the quality of the images is degraded. The following conversions are done: \n"); bool setBitDepthWarning = false; bool outputModified = false; if (!self->isSupportedBitDepth(OfxClipInstance::ofxDepthToNatronDepth(outputClipDepth))) { outputClipDepth = self->effectInstance()->bestSupportedDepth(kOfxBitDepthFloat); outputClipDepthNatron = OfxClipInstance::ofxDepthToNatronDepth(outputClipDepth); foundOutputPrefs->second.bitdepth = outputClipDepth; outputModified = true; } double outputAspectRatio = foundOutputPrefs->second.par; ///output clip doesn't support components just remap it, this is probably a plug-in bug. if (!outputClip->isSupportedComponent(foundOutputPrefs->second.components)) { foundOutputPrefs->second.components = outputClip->findSupportedComp(kOfxImageComponentRGBA); outputModified = true; } ///Adjust output premultiplication if needed if (foundOutputPrefs->second.components == kOfxImageComponentRGB) { effectPrefs.premult = kOfxImageOpaque; } else if (foundOutputPrefs->second.components == kOfxImageComponentAlpha) { effectPrefs.premult = kOfxImagePreMultiplied; } int maxInputs = self->getMaxInputCount(); for (int i = 0; i < maxInputs; ++i) { EffectInstance* inputEffect = self->getInput(i); if (inputEffect) { inputEffect = inputEffect->getNearestNonIdentity(time); } OfxEffectInstance* instance = dynamic_cast<OfxEffectInstance*>(inputEffect); OfxClipInstance* clip = self->getClipCorrespondingToInput(i); if (instance) { std::map<OfxClipInstance*,OfxImageEffectInstance::ClipPrefs>::iterator foundClipPrefs = clipPrefs.find(clip); assert(foundClipPrefs != clipPrefs.end()); bool hasChanged = false; ///This is the output clip of the input node OFX::Host::ImageEffect::ClipInstance* inputOutputClip = instance->effectInstance()->getClip(kOfxImageEffectOutputClipName); ///Set the clip to have the same components as the output components if it is supported if ( clip->isSupportedComponent(foundOutputPrefs->second.components) ) { ///we only take into account non mask clips for the most components if ( !clip->isMask() && (foundClipPrefs->second.components != foundOutputPrefs->second.components) ) { foundClipPrefs->second.components = foundOutputPrefs->second.components; hasChanged = true; } } ///Try to remap the clip's bitdepth to be the same as const std::string & input_outputDepth = inputOutputClip->getPixelDepth(); Natron::ImageBitDepthEnum input_outputNatronDepth = OfxClipInstance::ofxDepthToNatronDepth(input_outputDepth); ///If supported, set the clip's bitdepth to be the same as the output depth of the input node if ( self->isSupportedBitDepth(input_outputNatronDepth) ) { bool depthsDifferent = input_outputNatronDepth != outputClipDepthNatron; if (self->effectInstance()->supportsMultipleClipDepths() && depthsDifferent) { foundClipPrefs->second.bitdepth = input_outputDepth; hasChanged = true; } } ///Otherwise if the bit-depth conversion will be lossy, warn the user else if ( Image::isBitDepthConversionLossy(input_outputNatronDepth, outputClipDepthNatron) ) { bitDepthWarning.append( instance->getName().c_str() ); bitDepthWarning.append(" (" + QString( Image::getDepthString(input_outputNatronDepth).c_str() ) + ")"); bitDepthWarning.append(" ----> "); bitDepthWarning.append( self->getName_mt_safe().c_str() ); bitDepthWarning.append(" (" + QString( Image::getDepthString(outputClipDepthNatron).c_str() ) + ")"); bitDepthWarning.append('\n'); setBitDepthWarning = true; } if (!self->effectInstance()->supportsMultipleClipPARs() && foundClipPrefs->second.par != outputAspectRatio && foundClipPrefs->first->getConnected()) { qDebug() << self->getName_mt_safe().c_str() << ": An input clip ("<< foundClipPrefs->first->getName().c_str() << ") has a pixel aspect ratio (" << foundClipPrefs->second.par << ") different than the output clip (" << outputAspectRatio << ") but it doesn't support multiple clips PAR. " << "This should have been handled earlier before connecting the nodes, @see Node::canConnectInput."; } if (hasChanged) { changedClips.push_back(clip); } } } if (outputModified) { changedClips.push_back(outputClip); } self->getNode()->toggleBitDepthWarning(setBitDepthWarning, bitDepthWarning); } //endCheckOFXClipPreferences void OfxEffectInstance::checkOFXClipPreferences(double time, const RenderScale & scale, const std::string & reason, bool forceGetClipPrefAction) { assert(_context != eContextNone); assert( QThread::currentThread() == qApp->thread() ); //////////////////////////////////////////////////////////////// /////////////////////////////////// //////////////// STEP 1 : Get plug-in render preferences std::map<OfxClipInstance*,OfxImageEffectInstance::ClipPrefs> clipsPrefs; OfxImageEffectInstance::EffectPrefs effectPrefs; { RECURSIVE_ACTION(); SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QWriteLocker preferencesLocker(_preferencesLock); if (forceGetClipPrefAction) { if (!_effect->getClipPreferences_safe(clipsPrefs,effectPrefs)) { return; } } else { if (_effect->areClipPrefsDirty()) { if (!_effect->getClipPreferences_safe(clipsPrefs, effectPrefs)) { return; } } else { return; } } } //////////////////////////////////////////////////////////////// //////////////////////////////// //////////////// STEP 2: Apply a proxy, i.e: modify the preferences so it requires a minimum pixel shuffling std::list<OfxClipInstance*> modifiedClips; clipPrefsProxy(this,time,clipsPrefs,effectPrefs,modifiedClips); //////////////////////////////////////////////////////////////// //////////////////////////////// //////////////// STEP 3: Actually push to the clips the preferences and set the flags on the effect, protected by a write lock. { QWriteLocker l(_preferencesLock); for (std::map<OfxClipInstance*,OfxImageEffectInstance::ClipPrefs>::const_iterator it = clipsPrefs.begin(); it != clipsPrefs.end(); ++it) { it->first->setComponents(it->second.components); it->first->setPixelDepth(it->second.bitdepth); it->first->setAspectRatio(it->second.par); } effectInstance()->updatePreferences_safe(effectPrefs.frameRate, effectPrefs.fielding, effectPrefs.premult, effectPrefs.continuous, effectPrefs.frameVarying); } //////////////////////////////////////////////////////////////// //////////////////////////////// //////////////// STEP 4: If our proxy remapping changed some clips preferences, notifying the plug-in of the clips which changed if (!getApp()->getProject()->isLoadingProject()) { RECURSIVE_ACTION(); SET_CAN_SET_VALUE(true); if (!modifiedClips.empty()) { effectInstance()->beginInstanceChangedAction(reason); } for (std::list<OfxClipInstance*>::iterator it = modifiedClips.begin(); it!=modifiedClips.end();++it) { effectInstance()->clipInstanceChangedAction((*it)->getName(), reason, time, scale); } if (!modifiedClips.empty()) { effectInstance()->endInstanceChangedAction(reason); } } } // checkOFXClipPreferences void OfxEffectInstance::restoreClipPreferences() { assert(_context != eContextNone); double time = getApp()->getTimeLine()->currentFrame(); RenderScale s; s.x = s.y = 1.; ///if all non optional clips are connected, call getClipPrefs ///The clip preferences action is never called until all non optional clips have been attached to the plugin. if ( _effect->areAllNonOptionalClipsConnected() ) { ///Render scale support might not have been set already because getRegionOfDefinition could have failed until all non optional inputs were connected if (supportsRenderScaleMaybe() == eSupportsMaybe) { OfxRectD rod; OfxPointD scaleOne; scaleOne.x = scaleOne.y = 1.; OfxStatus rodstat = _effect->getRegionOfDefinitionAction(time, scaleOne, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { OfxPointD scale; scale.x = 0.5; scale.y = 0.5; rodstat = _effect->getRegionOfDefinitionAction(time, scale, rod); if ( (rodstat == kOfxStatOK) || (rodstat == kOfxStatReplyDefault) ) { setSupportsRenderScaleMaybe(eSupportsYes); } else { setSupportsRenderScaleMaybe(eSupportsNo); } } } checkOFXClipPreferences_public(time,s,kOfxChangeUserEdited,true, false); } } std::vector<std::string> OfxEffectInstance::supportedFileFormats() const { assert(_context != eContextNone); int formatsCount = _effect->getDescriptor().getProps().getDimension(kTuttleOfxImageEffectPropSupportedExtensions); std::vector<std::string> formats(formatsCount); for (int k = 0; k < formatsCount; ++k) { formats[k] = _effect->getDescriptor().getProps().getStringProperty(kTuttleOfxImageEffectPropSupportedExtensions,k); std::transform(formats[k].begin(), formats[k].end(), formats[k].begin(), ::tolower); } return formats; } Natron::StatusEnum OfxEffectInstance::getRegionOfDefinition(U64 hash, SequenceTime time, const RenderScale & scale, int view, RectD* rod) { assert(_context != eContextNone); if (!_initialized) { return Natron::eStatusFailed; } assert(_effect); unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); // getRegionOfDefinition may be the first action with renderscale called on any effect. // it may have to check for render scale support. SupportsEnum supportsRS = supportsRenderScaleMaybe(); bool scaleIsOne = (scale.x == 1. && scale.y == 1.); if ( (supportsRS == eSupportsNo) && !scaleIsOne ) { qDebug() << "getRegionOfDefinition called with render scale != 1, but effect does not support render scale!"; return eStatusFailed; } OfxRectD ofxRod; OfxStatus stat; { bool skipDiscarding = false; if (getRecursionLevel() > 1) { skipDiscarding = true; } ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, //< set mipmaplevel? mipMapLevel); { if (getRecursionLevel() > 1) { stat = _effect->getRegionOfDefinitionAction(time, scale, ofxRod); } else { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->getRegionOfDefinitionAction(time, scale, ofxRod); } } if ( !scaleIsOne && (supportsRS == eSupportsMaybe) ) { if ( (stat == kOfxStatOK) || (stat == kOfxStatReplyDefault) ) { // we got at least one success with RS != 1 setSupportsRenderScaleMaybe(eSupportsYes); } else if (stat == kOfxStatFailed) { // maybe the effect does not support renderscale // try again with scale one OfxPointD scaleOne; scaleOne.x = scaleOne.y = 1.; { SET_CAN_SET_VALUE(false); if (getRecursionLevel() > 1) { stat = _effect->getRegionOfDefinitionAction(time, scaleOne, ofxRod); } else { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->getRegionOfDefinitionAction(time, scaleOne, ofxRod); } } if ( (stat == kOfxStatOK) || (stat == kOfxStatReplyDefault) ) { // we got success with scale = 1, which means it doesn't support renderscale after all setSupportsRenderScaleMaybe(eSupportsNo); } else { // if both actions failed, we can't say anything return eStatusFailed; } if (stat == kOfxStatReplyDefault) { calcDefaultRegionOfDefinition(hash,time,view,scaleOne, rod); return eStatusReplyDefault; } } } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { return eStatusFailed; } if (stat == kOfxStatReplyDefault) { calcDefaultRegionOfDefinition(hash,time,view, scale, rod); return eStatusReplyDefault; } } ///If the rod is 1 pixel, determine if it was because one clip was unconnected or this is really a ///1 pixel large image if ( (ofxRod.x2 == 1.) && (ofxRod.y2 == 1.) && (ofxRod.x1 == 0.) && (ofxRod.y1 == 0.) ) { int maxInputs = getMaxInputCount(); for (int i = 0; i < maxInputs; ++i) { OfxClipInstance* clip = getClipCorrespondingToInput(i); if ( clip && !clip->getConnected() && !clip->isOptional() && !clip->isMask() ) { ///this is a mandatory source clip and it is not connected, return statfailed return eStatusFailed; } } } RectD::ofxRectDToRectD(ofxRod, rod); return eStatusOK; // OFX::Host::ImageEffect::ClipInstance* clip = effectInstance()->getClip(kOfxImageEffectOutputClipName); //assert(clip); //double pa = clip->getAspectRatio(); } // getRegionOfDefinition void OfxEffectInstance::calcDefaultRegionOfDefinition(U64 /*hash*/, SequenceTime time, int view, const RenderScale & scale, RectD *rod) { assert(_context != eContextNone); if (!_initialized) { throw std::runtime_error("OfxEffectInstance not initialized"); } bool skipDiscarding = false; if (getRecursionLevel() > 1) { skipDiscarding = true; } unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); OfxRectD ofxRod; { SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. if (getRecursionLevel() == 0) { ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, //< set mipmaplevel? mipMapLevel); // from http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxImageEffectActionGetRegionOfDefinition // generator context - defaults to the project window, // filter and paint contexts - defaults to the RoD of the 'Source' input clip at the given time, // transition context - defaults to the union of the RoDs of the 'SourceFrom' and 'SourceTo' input clips at the given time, // general context - defaults to the union of the RoDs of all the effect non optional input clips at the given time, if none exist, then it is the project window // retimer context - defaults to the union of the RoD of the 'Source' input clip at the frame directly preceding the value of the 'SourceTime' double parameter and the frame directly after it // the following ofxh function does the job QReadLocker preferencesLocker(_preferencesLock); ofxRod = _effect->calcDefaultRegionOfDefinition(time, (OfxPointD)scale); } else { ofxRod = _effect->calcDefaultRegionOfDefinition(time, (OfxPointD)scale); } } rod->x1 = ofxRod.x1; rod->x2 = ofxRod.x2; rod->y1 = ofxRod.y1; rod->y2 = ofxRod.y2; } static void rectToOfxRectD(const RectD & b, OfxRectD *out) { out->x1 = b.left(); out->x2 = b.right(); out->y1 = b.bottom(); out->y2 = b.top(); } void OfxEffectInstance::getRegionsOfInterest(SequenceTime time, const RenderScale & scale, const RectD & outputRoD, const RectD & renderWindow, //!< the region to be rendered in the output image, in Canonical Coordinates int view, EffectInstance::RoIMap* ret) { assert(_context != eContextNone); std::map<OFX::Host::ImageEffect::ClipInstance*,OfxRectD> inputRois; if (!_initialized) { return; } assert(outputRoD.x2 >= outputRoD.x1 && outputRoD.y2 >= outputRoD.y1); assert(renderWindow.x2 >= renderWindow.x1 && renderWindow.y2 >= renderWindow.y1); { bool scaleIsOne = (scale.x == 1. && scale.y == 1.); assert( !( (supportsRenderScaleMaybe() == eSupportsNo) && !scaleIsOne ) ); } OfxStatus stat; ///before calling getRoIaction set the relevant info on the clips unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); { SET_CAN_SET_VALUE(false); bool skipDiscarding = false; if (getRecursionLevel() > 1) { qDebug() << "getRegionsOfInterest cannot be called recursively as an action. Please check this."; skipDiscarding = true; } ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, mipMapLevel); OfxRectD roi; rectToOfxRectD(renderWindow, &roi); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->getRegionOfInterestAction( (OfxTime)time, scale, roi, inputRois ); } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { appPTR->writeToOfxLog_mt_safe(QString( getNode()->getName_mt_safe().c_str() ) + "Failed to specify the region of interest from inputs."); } if (stat != kOfxStatReplyDefault) { for (std::map<OFX::Host::ImageEffect::ClipInstance*,OfxRectD>::iterator it = inputRois.begin(); it != inputRois.end(); ++it) { OfxClipInstance* clip = dynamic_cast<OfxClipInstance*>(it->first); assert(clip); if (clip) { EffectInstance* inputNode = clip->getAssociatedNode(); RectD inputRoi; // input RoI in canonical coordinates inputRoi.x1 = it->second.x1; inputRoi.x2 = it->second.x2; inputRoi.y1 = it->second.y1; inputRoi.y2 = it->second.y2; ///The RoI might be infinite if the getRoI action of the plug-in doesn't do anything and the input effect has an ///infinite rod. ifInfiniteclipRectToProjectDefault(&inputRoi); ret->insert( std::make_pair(inputNode,inputRoi) ); } } } else if (stat == kOfxStatReplyDefault) { const std::map<std::string,OFX::Host::ImageEffect::ClipInstance*>& clips = effectInstance()->getClips(); for (std::map<std::string,OFX::Host::ImageEffect::ClipInstance*>::const_iterator it = clips.begin(); it!=clips.end(); ++it) { if (!it->second->isOutput()) { OfxClipInstance* natronClip = dynamic_cast<OfxClipInstance*>(it->second); assert(natronClip); EffectInstance* inputNode = natronClip ? natronClip->getAssociatedNode() : 0; if (inputNode) { ret->insert( std::make_pair(inputNode, renderWindow) ); } } } } } // getRegionsOfInterest Natron::EffectInstance::FramesNeededMap OfxEffectInstance::getFramesNeeded(SequenceTime time) { assert(_context != eContextNone); EffectInstance::FramesNeededMap ret; if (!_initialized) { return ret; } OFX::Host::ImageEffect::RangeMap inputRanges; assert(_effect); OfxStatus stat; { SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->getFrameNeededAction( (OfxTime)time, inputRanges ); } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { Natron::errorDialog( getName(), QObject::tr("Failed to specify the frame ranges needed from inputs.").toStdString() ); } else if (stat == kOfxStatOK) { for (OFX::Host::ImageEffect::RangeMap::iterator it = inputRanges.begin(); it != inputRanges.end(); ++it) { OfxClipInstance* clip = dynamic_cast<OfxClipInstance*>(it->first); assert(clip); if (clip) { int inputNb = clip->getInputNb(); if (inputNb != -1) { ret.insert( std::make_pair(inputNb,it->second) ); } } } } else if (stat == kOfxStatReplyDefault) { return Natron::EffectInstance::getFramesNeeded(time); } return ret; } void OfxEffectInstance::getFrameRange(SequenceTime *first, SequenceTime *last) { assert(_context != eContextNone); if (!_initialized) { return; } OfxRangeD range; // getTimeDomain should only be called on the 'general', 'reader' or 'generator' contexts. // see http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxImageEffectActionGetTimeDomain" // Edit: Also add the 'writer' context as we need the getTimeDomain action to be able to find out the frame range to render. OfxStatus st = kOfxStatReplyDefault; if ( (_context == eContextGeneral) || ( _context == eContextReader) || ( _context == eContextWriter) || ( _context == eContextGenerator) ) { SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); st = _effect->getTimeDomainAction(range); } if (st == kOfxStatOK) { *first = (SequenceTime)range.min; *last = (SequenceTime)range.max; } else if (st == kOfxStatReplyDefault) { //The default is... int nthClip = _effect->getNClips(); if (nthClip == 0) { //infinite if there are no non optional input clips. *first = INT_MIN; *last = INT_MAX; } else { //the union of all the frame ranges of the non optional input clips. bool firstValidInput = true; *first = INT_MIN; *last = INT_MAX; int inputsCount = getMaxInputCount(); ///Uncommented the isOptional() introduces a bugs with Genarts Monster plug-ins when 2 generators ///are connected in the pipeline. They must rely on the time domain to maintain an internal state and apparantly ///not taking optional inputs into accounts messes it up. for (int i = 0; i < inputsCount; ++i) { //if (!isInputOptional(i)) { EffectInstance* inputEffect = getInput(i); if (inputEffect) { SequenceTime f,l; inputEffect->getFrameRange_public(inputEffect->getRenderHash(),&f, &l); if (!firstValidInput) { if ( (f < *first) && (f != INT_MIN) ) { *first = f; } if ( (l > *last) && (l != INT_MAX) ) { *last = l; } } else { firstValidInput = false; *first = f; *last = l; } } // } } } } } // getFrameRange bool OfxEffectInstance::isIdentity(SequenceTime time, const RenderScale & scale, const RectD & rod, const double par, int view, SequenceTime* inputTime, int* inputNb) { if (!_created) { *inputNb = -1; *inputTime = 0; return false; } assert(_context != eContextNone); const std::string field = kOfxImageFieldNone; // TODO: support interlaced data std::string inputclip; OfxTime inputTimeOfx = time; // isIdentity may be the first action with renderscale called on any effect. // it may have to check for render scale support. SupportsEnum supportsRS = supportsRenderScaleMaybe(); bool scaleIsOne = (scale.x == 1. && scale.y == 1.); if ( (supportsRS == eSupportsNo) && !scaleIsOne ) { qDebug() << "isIdentity called with render scale != 1, but effect does not support render scale!"; assert(false); throw std::logic_error("isIdentity called with render scale != 1, but effect does not support render scale!"); } unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); OfxStatus stat; { bool skipDiscarding = false; if (getRecursionLevel() > 1) { //#ifdef DEBUG // if (QThread::currentThread() != qApp->thread()) { // qDebug() << "isIdentity cannot be called recursively as an action. Please check this."; // } //#endif skipDiscarding = true; } SET_CAN_SET_VALUE(false); ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, mipMapLevel); // In Natron, we only consider isIdentity for whole images RectI roi; rod.toPixelEnclosing(scale, par, &roi); OfxRectI ofxRoI; ofxRoI.x1 = roi.left(); ofxRoI.x2 = roi.right(); ofxRoI.y1 = roi.bottom(); ofxRoI.y2 = roi.top(); { if (getRecursionLevel() > 1) { stat = _effect->isIdentityAction(inputTimeOfx, field, ofxRoI, scale, inputclip); } else { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->isIdentityAction(inputTimeOfx, field, ofxRoI, scale, inputclip); } } if ( !scaleIsOne && (supportsRS == eSupportsMaybe) ) { if ( (stat == kOfxStatOK) || (stat == kOfxStatReplyDefault) ) { // we got at least one success with RS != 1 setSupportsRenderScaleMaybe(eSupportsYes); } else if (stat == kOfxStatFailed) { // maybe the effect does not support renderscale // try again with scale one OfxPointD scaleOne; scaleOne.x = scaleOne.y = 1.; rod.toPixelEnclosing(scaleOne, par, &roi); ofxRoI.x1 = roi.left(); ofxRoI.x2 = roi.right(); ofxRoI.y1 = roi.bottom(); ofxRoI.y2 = roi.top(); if (getRecursionLevel() > 1) { stat = _effect->isIdentityAction(inputTimeOfx, field, ofxRoI, scaleOne, inputclip); } else { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->isIdentityAction(inputTimeOfx, field, ofxRoI, scaleOne, inputclip); } if ( (stat == kOfxStatOK) || (stat == kOfxStatReplyDefault) ) { // we got success with scale = 1, which means it doesn't support renderscale after all setSupportsRenderScaleMaybe(eSupportsNo); } } } } if (stat == kOfxStatOK) { OFX::Host::ImageEffect::ClipInstance* clip = _effect->getClip(inputclip); if (!clip) { // this is a plugin-side error, don't crash qDebug() << "Error in OfxEffectInstance::render(): kOfxImageEffectActionIsIdentity returned an unknown clip: " << inputclip.c_str(); return false; } OfxClipInstance* natronClip = dynamic_cast<OfxClipInstance*>(clip); assert(natronClip); if (!natronClip) { qDebug() << "Error in OfxEffectInstance::render(): kOfxImageEffectActionIsIdentity returned an unknown clip: " << inputclip.c_str(); return false; } *inputTime = inputTimeOfx; if ( natronClip->isOutput() ) { *inputNb = -2; } else { *inputNb = natronClip->getInputNb(); } return true; } else if (stat == kOfxStatReplyDefault) { return false; } return false; //< may fail if getRegionOfDefinition has failed in the plug-in code //throw std::runtime_error("isIdentity failed"); } // isIdentity Natron::StatusEnum OfxEffectInstance::beginSequenceRender(SequenceTime first, SequenceTime last, SequenceTime step, bool interactive, const RenderScale & scale, bool isSequentialRender, bool isRenderResponseToUserInteraction, int view) { { bool scaleIsOne = (scale.x == 1. && scale.y == 1.); assert( !( (supportsRenderScaleMaybe() == eSupportsNo) && !scaleIsOne ) ); } OfxStatus stat; unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); { bool skipDiscarding = false; if (getRecursionLevel() > 1) { qDebug() << "beginRenderAction cannot be called recursively as an action. Please check this."; skipDiscarding = true; } ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, mipMapLevel); SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = effectInstance()->beginRenderAction(first, last, step, interactive, scale, isSequentialRender, isRenderResponseToUserInteraction, view); } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { return eStatusFailed; } return eStatusOK; } Natron::StatusEnum OfxEffectInstance::endSequenceRender(SequenceTime first, SequenceTime last, SequenceTime step, bool interactive, const RenderScale & scale, bool isSequentialRender, bool isRenderResponseToUserInteraction, int view) { { bool scaleIsOne = (scale.x == 1. && scale.y == 1.); assert( !( (supportsRenderScaleMaybe() == eSupportsNo) && !scaleIsOne ) ); } OfxStatus stat; unsigned int mipMapLevel = Image::getLevelFromScale(scale.x); { bool skipDiscarding = false; if (getRecursionLevel() > 1) { qDebug() << "endRenderAction cannot be called recursively as an action. Please check this."; skipDiscarding = true; } ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true, mipMapLevel); SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = effectInstance()->endRenderAction(first, last, step, interactive,scale, isSequentialRender, isRenderResponseToUserInteraction, view); } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { return eStatusFailed; } return eStatusOK; } Natron::StatusEnum OfxEffectInstance::render(SequenceTime time, const RenderScale& originalScale, const RenderScale & mappedScale, const RectI & roi, int view, bool isSequentialRender, bool isRenderResponseToUserInteraction, boost::shared_ptr<Natron::Image> output) { if (!_initialized) { return Natron::eStatusFailed; } OfxRectI ofxRoI; ofxRoI.x1 = roi.left(); ofxRoI.x2 = roi.right(); ofxRoI.y1 = roi.bottom(); ofxRoI.y2 = roi.top(); int viewsCount = getApp()->getProject()->getProjectViewsCount(); OfxStatus stat; const std::string field = kOfxImageFieldNone; // TODO: support interlaced data ///before calling render, set the render scale thread storage for each clip # ifdef DEBUG { // check the dimensions of output images const RectI & dstBounds = output->getBounds(); const RectD & dstRodCanonical = output->getRoD(); RectI dstRod; dstRodCanonical.toPixelEnclosing(mappedScale, output->getPixelAspectRatio(), &dstRod); if ( !supportsTiles() ) { // http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxImageEffectPropSupportsTiles // If a clip or plugin does not support tiled images, then the host should supply full RoD images to the effect whenever it fetches one. assert(dstRod.x1 == dstBounds.x1); assert(dstRod.x2 == dstBounds.x2); assert(dstRod.y1 == dstBounds.y1); assert(dstRod.y2 == dstBounds.y2); } if ( !supportsMultiResolution() ) { // http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxImageEffectPropSupportsMultiResolution // Multiple resolution images mean... // input and output images can be of any size // input and output images can be offset from the origin assert(dstRod.x1 == 0); assert(dstRod.y1 == 0); } } # endif // DEBUG { bool skipDiscarding = false; if (getRecursionLevel() > 1) { qDebug() << "renderAction cannot be called recursively as an action. Please check this."; skipDiscarding = true; } SET_CAN_SET_VALUE(false); ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true,//< set mipmaplevel ? Natron::Image::getLevelFromScale(originalScale.x)); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->renderAction( (OfxTime)time, field, ofxRoI, mappedScale, isSequentialRender, isRenderResponseToUserInteraction, view, viewsCount ); } if (stat != kOfxStatOK) { return eStatusFailed; } else { return eStatusOK; } } // render bool OfxEffectInstance::supportsMultipleClipsPAR() const { return _effect->supportsMultipleClipPARs(); } EffectInstance::RenderSafetyEnum OfxEffectInstance::renderThreadSafety() const { { QReadLocker readL(_renderSafetyLock); if (_wasRenderSafetySet) { return _renderSafety; } } { QWriteLocker writeL(_renderSafetyLock); const std::string & safety = _effect->getRenderThreadSafety(); if (safety == kOfxImageEffectRenderUnsafe) { _renderSafety = EffectInstance::eRenderSafetyUnsafe; } else if (safety == kOfxImageEffectRenderInstanceSafe) { _renderSafety = EffectInstance::eRenderSafetyInstanceSafe; } else if (safety == kOfxImageEffectRenderFullySafe) { if ( _effect->getHostFrameThreading() ) { _renderSafety = EffectInstance::eRenderSafetyFullySafeFrame; } else { _renderSafety = EffectInstance::eRenderSafetyFullySafe; } } else { qDebug() << "Unknown thread safety level: " << safety.c_str(); _renderSafety = EffectInstance::eRenderSafetyUnsafe; } _wasRenderSafetySet = true; return _renderSafety; } } bool OfxEffectInstance::makePreviewByDefault() const { return isGenerator(); } const std::string & OfxEffectInstance::getShortLabel() const { return effectInstance()->getShortLabel(); } void OfxEffectInstance::initializeOverlayInteract() { tryInitializeOverlayInteracts(); } void OfxEffectInstance::drawOverlay(double /*scaleX*/, double /*scaleY*/) { if (!_initialized) { return; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); /* if (getRecursionLevel() == 1) { bool skipDiscarding = false; if (getRecursionLevel() > 1) { ///This happens sometimes because of dialogs popping from the request of a plug-in (inside an action) ///and making the mainwindow loose focus, hence forcing a new paint event //qDebug() << "drawAction cannot be called recursively as an action. Please check this."; skipDiscarding = true; } ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, false, //< setView ? 0, false, 0); _overlayInteract->drawAction(time, rs); } else {*/ SET_CAN_SET_VALUE(false); _overlayInteract->drawAction(time, rs); /*}*/ } } void OfxEffectInstance::setCurrentViewportForOverlays(OverlaySupport* viewport) { if (_overlayInteract) { _overlayInteract->setCallingViewport(viewport); } } bool OfxEffectInstance::onOverlayPenDown(double /*scaleX*/, double /*scaleY*/, const QPointF & viewportPos, const QPointF & pos) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxPointD penPos; penPos.x = pos.x(); penPos.y = pos.y(); OfxPointI penPosViewport; penPosViewport.x = viewportPos.x(); penPosViewport.y = viewportPos.y(); OfxTime time = getApp()->getTimeLine()->currentFrame(); /* ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); */ SET_CAN_SET_VALUE(true); OfxStatus stat = _overlayInteract->penDownAction(time, rs, penPos, penPosViewport, 1.); if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } if (stat == kOfxStatOK) { _penDown = true; return true; } } return false; } bool OfxEffectInstance::onOverlayPenMotion(double /*scaleX*/, double /*scaleY*/, const QPointF & viewportPos, const QPointF & pos) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxPointD penPos; penPos.x = pos.x(); penPos.y = pos.y(); OfxPointI penPosViewport; penPosViewport.x = viewportPos.x(); penPosViewport.y = viewportPos.y(); OfxTime time = getApp()->getTimeLine()->currentFrame(); OfxStatus stat; /* if (getRecursionLevel() == 1) { ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); stat = _overlayInteract->penMotionAction(time, rs, penPos, penPosViewport, 1.); } else {*/ SET_CAN_SET_VALUE(true); stat = _overlayInteract->penMotionAction(time, rs, penPos, penPosViewport, 1.); /*}*/ if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } if (stat == kOfxStatOK) { return true; } } return false; } bool OfxEffectInstance::onOverlayPenUp(double /*scaleX*/, double /*scaleY*/, const QPointF & viewportPos, const QPointF & pos) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxPointD penPos; penPos.x = pos.x(); penPos.y = pos.y(); OfxPointI penPosViewport; penPosViewport.x = viewportPos.x(); penPosViewport.y = viewportPos.y(); OfxTime time = getApp()->getTimeLine()->currentFrame(); /* ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, view, false, 0); */ SET_CAN_SET_VALUE(true); OfxStatus stat = _overlayInteract->penUpAction(time, rs, penPos, penPosViewport, 1.); if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } if (stat == kOfxStatOK) { _penDown = false; return true; } } return false; } bool OfxEffectInstance::onOverlayKeyDown(double /*scaleX*/, double /*scaleY*/, Natron::Key key, Natron::KeyboardModifiers /*modifiers*/) { if (!_initialized) { return false;; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); QByteArray keyStr; /* ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); */ SET_CAN_SET_VALUE(true); OfxStatus stat = _overlayInteract->keyDownAction( time, rs, (int)key, keyStr.data() ); if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } if (stat == kOfxStatOK) { return true; } } return false; } bool OfxEffectInstance::onOverlayKeyUp(double /*scaleX*/, double /*scaleY*/, Natron::Key key, Natron::KeyboardModifiers /* modifiers*/) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); QByteArray keyStr; /* ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); */ SET_CAN_SET_VALUE(true); OfxStatus stat = _overlayInteract->keyUpAction( time, rs, (int)key, keyStr.data() ); if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); if (stat == kOfxStatOK) { return true; } ; } return false; } bool OfxEffectInstance::onOverlayKeyRepeat(double /*scaleX*/, double /*scaleY*/, Natron::Key key, Natron::KeyboardModifiers /*modifiers*/) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); QByteArray keyStr; /* ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); */ SET_CAN_SET_VALUE(true); OfxStatus stat = _overlayInteract->keyRepeatAction( time, rs, (int)key, keyStr.data() ); if (getRecursionLevel() == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } if (stat == kOfxStatOK) { return true; } } return false; } bool OfxEffectInstance::onOverlayFocusGained(double /*scaleX*/, double /*scaleY*/) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); OfxStatus stat; /* if (getRecursionLevel() == 1) { ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); stat = _overlayInteract->gainFocusAction(time, rs); } else {*/ SET_CAN_SET_VALUE(true); stat = _overlayInteract->gainFocusAction(time, rs); /*}*/ assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); if (stat == kOfxStatOK) { return true; } } return false; } bool OfxEffectInstance::onOverlayFocusLost(double /*scaleX*/, double /*scaleY*/) { if (!_initialized) { return false; } if (_overlayInteract) { OfxPointD rs; rs.x = 1.; //scaleX; rs.y = 1.; //scaleY; OfxTime time = getApp()->getTimeLine()->currentFrame(); OfxStatus stat; /*if (getRecursionLevel() == 1) { ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, false, 0); stat = _overlayInteract->loseFocusAction(time, rs); } else {*/ SET_CAN_SET_VALUE(true); stat = _overlayInteract->loseFocusAction(time, rs); /*}*/ assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); if (stat == kOfxStatOK) { return true; } } return false; } bool OfxEffectInstance::hasOverlay() const { return _overlayInteract != NULL; } static std::string natronValueChangedReasonToOfxValueChangedReason(Natron::ValueChangedReasonEnum reason) { switch (reason) { case Natron::eValueChangedReasonUserEdited: case Natron::eValueChangedReasonNatronGuiEdited: return kOfxChangeUserEdited; case Natron::eValueChangedReasonPluginEdited: case Natron::eValueChangedReasonNatronInternalEdited: case Natron::eValueChangedReasonSlaveRefresh: case Natron::eValueChangedReasonRestoreDefault: return kOfxChangePluginEdited; case Natron::eValueChangedReasonTimeChanged: return kOfxChangeTime; default: assert(false); // all Natron reasons should be processed return ""; } } void OfxEffectInstance::knobChanged(KnobI* k, Natron::ValueChangedReasonEnum reason, int view, SequenceTime time, bool originatedFromMainThread) { if (!_initialized) { return; } ///If the param changed is a button and the node is disabled don't do anything which might ///trigger an analysis if ( (reason == eValueChangedReasonUserEdited) && dynamic_cast<Button_Knob*>(k) && _node->isNodeDisabled() ) { return; } if ( _renderButton && ( k == _renderButton.get() ) ) { ///don't do anything since it is handled upstream return; } // OFX::Host::Param::paramSetValue() does it for us when it's edited by the plugin bool canCallInstanceChangedAction = reason != Natron::eValueChangedReasonPluginEdited; std::string ofxReason = natronValueChangedReasonToOfxValueChangedReason(reason); assert( !ofxReason.empty() ); // crashes when resetting to defaults OfxPointD renderScale; renderScale.x = renderScale.y = 1; OfxStatus stat = kOfxStatOK; int recursionLevel = getRecursionLevel(); if (canCallInstanceChangedAction) { if (recursionLevel == 1) { SET_CAN_SET_VALUE(true); ClipsThreadStorageSetter clipSetter(effectInstance(), false, true, //< setView ? view, true, //< setmipmaplevel? 0); ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. stat = effectInstance()->paramInstanceChangedAction(k->getName(), ofxReason,(OfxTime)time,renderScale); } else { ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. stat = effectInstance()->paramInstanceChangedAction(k->getName(), ofxReason,(OfxTime)time,renderScale); } } if ( (stat != kOfxStatOK) && (stat != kOfxStatReplyDefault) ) { QString err( QString( getNode()->getName_mt_safe().c_str() ) + ": An error occured while changing parameter " + k->getDescription().c_str() ); appPTR->writeToOfxLog_mt_safe(err); return; } if (QThread::currentThread() == qApp->thread() && originatedFromMainThread) { //< change didnt occur in main-thread in the first, palce don't attempt to draw the overlay ///Run the following only in the main-thread if ( _effect->isClipPreferencesSlaveParam( k->getName() ) ) { RECURSIVE_ACTION(); checkOFXClipPreferences_public(time, renderScale, ofxReason,true, true); } if (_overlayInteract) { if (std::find(_overlaySlaves.begin(), _overlaySlaves.end(), (void*)k) != _overlaySlaves.end()) { incrementRedrawNeededCounter(); } if (recursionLevel == 1 && checkIfOverlayRedrawNeeded()) { stat = _overlayInteract->redraw(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } } } } // knobChanged void OfxEffectInstance::beginKnobsValuesChanged(Natron::ValueChangedReasonEnum reason) { if (!_initialized) { return; } RECURSIVE_ACTION(); SET_CAN_SET_VALUE(true); ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. (void)effectInstance()->beginInstanceChangedAction(natronValueChangedReasonToOfxValueChangedReason(reason)); } void OfxEffectInstance::endKnobsValuesChanged(Natron::ValueChangedReasonEnum reason) { if (!_initialized) { return; } RECURSIVE_ACTION(); SET_CAN_SET_VALUE(true); ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. (void)effectInstance()->endInstanceChangedAction(natronValueChangedReasonToOfxValueChangedReason(reason)); } void OfxEffectInstance::purgeCaches() { // The kOfxActionPurgeCaches is an action that may be passed to a plug-in instance from time to time in low memory situations. Instances recieving this action should destroy any data structures they may have and release the associated memory, they can later reconstruct this from the effect's parameter set and associated information. http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxActionPurgeCaches OfxStatus stat; { SET_CAN_SET_VALUE(false); ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); stat = _effect->purgeCachesAction(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } // The kOfxActionSyncPrivateData action is called when a plugin should synchronise any private data structures to its parameter set. This generally occurs when an effect is about to be saved or copied, but it could occur in other situations as well. http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#kOfxActionSyncPrivateData { RECURSIVE_ACTION(); SET_CAN_SET_VALUE(true); ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. stat = _effect->syncPrivateDataAction(); assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault); } } int OfxEffectInstance::getMajorVersion() const { return effectInstance()->getPlugin()->getVersionMajor(); } int OfxEffectInstance::getMinorVersion() const { return effectInstance()->getPlugin()->getVersionMinor(); } bool OfxEffectInstance::supportsTiles() const { OFX::Host::ImageEffect::ClipInstance* outputClip = effectInstance()->getClip(kOfxImageEffectOutputClipName); if (!outputClip) { return false; } return effectInstance()->supportsTiles() && outputClip->supportsTiles(); } bool OfxEffectInstance::supportsMultiResolution() const { return effectInstance()->supportsMultiResolution(); } void OfxEffectInstance::beginEditKnobs() { ///Take the preferences lock so that it cannot be modified throughout the action. QReadLocker preferencesLocker(_preferencesLock); effectInstance()->beginInstanceEditAction(); } void OfxEffectInstance::onSyncPrivateDataRequested() { ///Can only be called in the main thread assert( QThread::currentThread() == qApp->thread() ); RECURSIVE_ACTION(); ///This action as all the overlay interacts actions can trigger recursive actions, such as ///getClipPreferences() so we don't take the clips preferences lock for read here otherwise we would ///create a deadlock. This code then assumes that the instance changed action of the plug-in doesn't require ///the clip preferences to stay the same throughout the action. SET_CAN_SET_VALUE(true); effectInstance()->syncPrivateDataAction(); } void OfxEffectInstance::addAcceptedComponents(int inputNb, std::list<Natron::ImageComponentsEnum>* comps) { if (inputNb >= 0) { OfxClipInstance* clip = getClipCorrespondingToInput(inputNb); assert(clip); const std::vector<std::string> & supportedComps = clip->getSupportedComponents(); for (U32 i = 0; i < supportedComps.size(); ++i) { try { comps->push_back( OfxClipInstance::ofxComponentsToNatronComponents(supportedComps[i]) ); } catch (const std::runtime_error &e) { // ignore unsupported components } } } else { assert(inputNb == -1); OfxClipInstance* clip = dynamic_cast<OfxClipInstance*>( effectInstance()->getClip(kOfxImageEffectOutputClipName) ); assert(clip); const std::vector<std::string> & supportedComps = clip->getSupportedComponents(); for (U32 i = 0; i < supportedComps.size(); ++i) { try { comps->push_back( OfxClipInstance::ofxComponentsToNatronComponents(supportedComps[i]) ); } catch (const std::runtime_error &e) { // ignore unsupported components } } } } void OfxEffectInstance::addSupportedBitDepth(std::list<Natron::ImageBitDepthEnum>* depths) const { const OFX::Host::Property::Set & prop = effectInstance()->getPlugin()->getDescriptor().getParamSetProps(); int dim = prop.getDimension(kOfxImageEffectPropSupportedPixelDepths); for (int i = 0; i < dim; ++i) { const std::string & depth = prop.getStringProperty(kOfxImageEffectPropSupportedPixelDepths,i); try { depths->push_back( OfxClipInstance::ofxDepthToNatronDepth(depth) ); } catch (const std::runtime_error &e) { // ignore unsupported bitdepth } } } void OfxEffectInstance::getPreferredDepthAndComponents(int inputNb, Natron::ImageComponentsEnum* comp, Natron::ImageBitDepthEnum* depth) const { OfxClipInstance* clip; if (inputNb == -1) { clip = dynamic_cast<OfxClipInstance*>( _effect->getClip(kOfxImageEffectOutputClipName) ); } else { clip = getClipCorrespondingToInput(inputNb); } assert(clip); if (getRecursionLevel() > 0) { ///Someone took the read (all actions) or write (getClipPreferences action)lock already *comp = OfxClipInstance::ofxComponentsToNatronComponents( clip->getComponents() ); *depth = OfxClipInstance::ofxDepthToNatronDepth( clip->getPixelDepth() ); } else { ///Take the preferences lock to be sure we're not writing them QReadLocker l(_preferencesLock); *comp = OfxClipInstance::ofxComponentsToNatronComponents( clip->getComponents() ); *depth = OfxClipInstance::ofxDepthToNatronDepth( clip->getPixelDepth() ); } } Natron::SequentialPreferenceEnum OfxEffectInstance::getSequentialPreference() const { int sequential = _effect->getPlugin()->getDescriptor().getProps().getIntProperty(kOfxImageEffectInstancePropSequentialRender); switch (sequential) { case 0: return Natron::eSequentialPreferenceNotSequential; case 1: return Natron::eSequentialPreferenceOnlySequential; case 2: return Natron::eSequentialPreferencePreferSequential; default: return Natron::eSequentialPreferenceNotSequential; break; } } Natron::ImagePremultiplicationEnum OfxEffectInstance::getOutputPremultiplication() const { const std::string & str = ofxGetOutputPremultiplication(); if (str == kOfxImagePreMultiplied) { return Natron::eImagePremultiplicationPremultiplied; } else if (str == kOfxImageUnPreMultiplied) { return Natron::eImagePremultiplicationUnPremultiplied; } else { return Natron::eImagePremultiplicationOpaque; } } const std::string & OfxEffectInstance::ofxGetOutputPremultiplication() const { static const std::string v(kOfxImagePreMultiplied); OFX::Host::ImageEffect::ClipInstance* clip = effectInstance()->getClip(kOfxImageEffectOutputClipName); assert(clip); if (getRecursionLevel() > 0) { const std::string & premult = effectInstance()->getOutputPreMultiplication(); ///if the output has something, use it, otherwise default to premultiplied if ( !premult.empty() ) { return premult; } else { return v; } } else { ///Take the preferences lock to be sure we're not writing them QReadLocker l(_preferencesLock); const std::string & premult = effectInstance()->getOutputPreMultiplication(); ///if the output has something, use it, otherwise default to premultiplied if ( !premult.empty() ) { return premult; } else { return v; } } } double OfxEffectInstance::getPreferredAspectRatio() const { OFX::Host::ImageEffect::ClipInstance* clip = effectInstance()->getClip(kOfxImageEffectOutputClipName); assert(clip); if (getRecursionLevel() > 0) { return clip->getAspectRatio(); } else { ///Take the preferences lock to be sure we're not writing them QReadLocker l(_preferencesLock); return clip->getAspectRatio(); } } double OfxEffectInstance::getPreferredFrameRate() const { OFX::Host::ImageEffect::ClipInstance* clip = effectInstance()->getClip(kOfxImageEffectOutputClipName); assert(clip); if (getRecursionLevel() > 0) { return clip->getFrameRate(); } else { ///Take the preferences lock to be sure we're not writing them QReadLocker l(_preferencesLock); return clip->getFrameRate(); } } bool OfxEffectInstance::getCanTransform() const { //use OFX_EXTENSIONS_NUKE return effectInstance()->canTransform(); } bool OfxEffectInstance::getCanApplyTransform(Natron::EffectInstance** effect) const { OfxClipInstance* transformClip = 0; bool canApply = effectInstance()->getCanApplyTransform(&transformClip); if (!transformClip || !canApply) { return false; } *effect = transformClip->getAssociatedNode(); return true; } Natron::StatusEnum OfxEffectInstance::getTransform(SequenceTime time, const RenderScale& renderScale, //< the plug-in accepted scale int view, Natron::EffectInstance** inputToTransform, Transform::Matrix3x3* transform) { const std::string field = kOfxImageFieldNone; // TODO: support interlaced data std::string clipName; double tmpTransform[9]; OfxStatus stat ; { bool skipDiscarding = false; if (getRecursionLevel() > 1) { qDebug() << "renderAction cannot be called recursively as an action. Please check this."; skipDiscarding = true; } SET_CAN_SET_VALUE(false); ClipsThreadStorageSetter clipSetter(effectInstance(), skipDiscarding, true, //< setView ? view, true,//< set mipmaplevel ? Natron::Image::getLevelFromScale(renderScale.x)); stat = effectInstance()->getTransformAction((OfxTime)time, field, renderScale, view, clipName, tmpTransform); if (stat == kOfxStatReplyDefault) { return Natron::eStatusReplyDefault; } else if (stat == kOfxStatFailed) { return Natron::eStatusFailed; } } assert(stat == kOfxStatOK); transform->a = tmpTransform[0]; transform->b = tmpTransform[1]; transform->c = tmpTransform[2]; transform->d = tmpTransform[3]; transform->e = tmpTransform[4]; transform->f = tmpTransform[5]; transform->g = tmpTransform[6]; transform->h = tmpTransform[7]; transform->i = tmpTransform[8]; OFX::Host::ImageEffect::ClipInstance* clip = effectInstance()->getClip(clipName); assert(clip); OfxClipInstance* natronClip = dynamic_cast<OfxClipInstance*>(clip); if (!natronClip) { return Natron::eStatusFailed; } *inputToTransform = natronClip->getAssociatedNode(); return Natron::eStatusOK; } void OfxEffectInstance::rerouteInputAndSetTransform(int inputNb,Natron::EffectInstance* newInput, int newInputNb,const Transform::Matrix3x3& m) { OfxClipInstance* clip = getClipCorrespondingToInput(inputNb); assert(clip); clip->setTransformAndReRouteInput(m, newInput, newInputNb); } void OfxEffectInstance::clearTransform(int inputNb) { OfxClipInstance* clip = getClipCorrespondingToInput(inputNb); assert(clip); clip->clearTransform(); } bool OfxEffectInstance::isFrameVarying() const { return effectInstance()->isFrameVarying(); } bool OfxEffectInstance::doesTemporalClipAccess() const { return effectInstance()->temporalAccess(); }
#include <string.h> #include "Apollo.h" #include "Scripting.h" #include "Utilities/ResourceManager.h" #include "Sound/Sound.h" #include "Graphics/Graphics.h" #include "Graphics/TextRenderer.h" #include "Preferences.h" #include "Input.h" #include "Modes/ModeManager.h" #include "TinyXML/tinyxml.h" #include "Net/Net.h" #include "Utilities/GameTime.h" extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } namespace { vec2 luaL_checkvec2(lua_State *L, int narg); void lua_pushvec2(lua_State *L, vec2 val); int VEC_new (lua_State* L) { float x = luaL_checknumber(L, 1); float y = luaL_checknumber(L, 2); vec2 v = vec2(x,y); lua_pushvec2(L, v); return 1; } int VEC_add (lua_State* L) { vec2 left = luaL_checkvec2(L, 1); vec2 right = luaL_checkvec2(L, 2); vec2 result = left + right; lua_pushvec2(L, result); return 1; } int VEC_sub (lua_State* L) { vec2 left = luaL_checkvec2(L, 1); vec2 right = luaL_checkvec2(L, 2); vec2 result = left - right; lua_pushvec2(L, result); return 1; } int VEC_mul (lua_State* L) { vec2 left = luaL_checkvec2(L, 1); if (lua_istable(L, 2)) { vec2 right = luaL_checkvec2(L, 2); float result = left * right; lua_pushnumber(L, result); } else { float right = luaL_checknumber(L, 2); vec2 result = left * right; lua_pushvec2(L, result); } return 1; } int VEC_div (lua_State* L) { vec2 left = luaL_checkvec2(L, 1); float right = luaL_checknumber(L, 2); vec2 result = left / right; lua_pushvec2(L, result); return 1; } int VEC_unm (lua_State* L) { vec2 val = -luaL_checkvec2(L, 1); lua_pushvec2(L, val); return 1; } int VEC_tostring (lua_State* L) { vec2 v = luaL_checkvec2(L, 1); char s[256]; sprintf(s, "%f, %f", v.X(), v.Y()); lua_pushstring(L, s); return 1; } luaL_Reg registryObjectVector[] = { "__add", VEC_add, "__sub", VEC_sub, "__mul", VEC_mul, "__div", VEC_div, "__unm", VEC_unm, "__tostring", VEC_tostring, NULL, NULL }; vec2 luaL_checkvec2(lua_State* L, int narg) { if (!lua_istable(L, narg)) { luaL_argerror(L, narg, "must pass a vector table (not a table)"); } float x, y; lua_getfield(L, narg, "x"); if (!lua_isnumber(L, -1)) { luaL_argerror(L, narg, "must pass a vector table (bad x value)"); } x = lua_tonumber(L, -1); lua_getfield(L, narg, "y"); if (!lua_isnumber(L, -1)) { luaL_argerror(L, narg, "must pass a vector table (bad y value)"); } y = lua_tonumber(L, -1); lua_pop(L, 2); return vec2(x, y); } std::string FloatToString ( float val ) { std::ostringstream o; if (!(o << val)) { printf("BAD CONVERSION?!?!?"); } return o.str(); } unsigned ToInt ( const std::string& value ) { return atoi(value.c_str()); } bool ToBool ( const std::string& value ) { return value == "true"; } vec2 luaL_optvec2(lua_State* L, int narg, vec2 defaultValue) { if (lua_isnoneornil(L, narg)) return defaultValue; return luaL_checkvec2(L, narg); } void lua_pushvec2(lua_State* L, vec2 val) { lua_createtable(L, 0, 2); lua_pushnumber(L, val.X()); lua_setfield(L, -2, "x"); lua_pushnumber(L, val.Y()); lua_setfield(L, -2, "y"); luaL_getmetatable(L, "Apollo.vec2"); lua_setmetatable(L, -2); } int Pref_Get ( lua_State* L ) { const char* arg = luaL_checkstring(L, 1); std::string push = Preferences::Get(arg, "nil"); // [TODO, ADAM] Make this not hardcoded... I think we have to recognize what type "push" is and format it accordingly // lua_pushstring(L, push); if (push == "true") // [HARDCODED] { lua_pushboolean(L, true); } else { lua_pushboolean(L, false); } return 1; } int Pref_Set ( lua_State* L ) { const char* arg = luaL_checkstring(L, 1); const char* set = luaL_checkstring(L, 2); Preferences::Set(arg, set); Preferences::Save(); return 0; } /** * @page lua_preferences The Lua Preferences Registry * This page contains information about the Lua preferences registry. * * This registry currently only contains one function, used for retrieving * preferences. In Lua, it is called called like so: "preferences.get(name)". * * @section pref_get get * Finds and returns a particular preference.\n * Parameters:\n * name - The name of the preference to be fetched.\n * Returns:\n * boolean - The status of the requested preference. (currently, this is hardcoded) * * @todo Make @ref xml_get un-hardcoded. */ luaL_Reg registryPreferences[] = { "get", Pref_Get, "set", Pref_Set, NULL, NULL }; int NetServer_Startup ( lua_State* L ) { unsigned port = luaL_checkinteger(L, 1); luaL_argcheck(L, port < 65536 && port > 0, 1, "Invalid port number"); const char* password = ""; if (lua_gettop(L) > 1) { password = luaL_checkstring(L, 2); } Net::Server::Startup(port, password); return 0; } int NetServer_Shutdown ( lua_State* L ) { Net::Server::Shutdown(); return 0; } int NetServer_Running ( lua_State* L ) { lua_pushboolean(L, Net::Server::IsRunning() ? 1 : 0); return 1; } int NetServer_ClientCount ( lua_State* L ) { lua_pushinteger(L, Net::Server::ClientCount()); return 1; } int NetServer_KillClient ( lua_State* L ) { unsigned clientID = luaL_checkinteger(L, 1); Net::Server::KillClient(clientID); return 0; } int NetServer_Connected ( lua_State* L ) { unsigned clientID = luaL_checkinteger(L, 1); bool isConnected = Net::Server::IsConnected(clientID); lua_pushboolean(L, isConnected ? 1 : 0); return 1; } int NetServer_SendMessage ( lua_State* L ) { int nargs = lua_gettop(L); unsigned clientID = luaL_checkinteger(L, 1); const char* message = luaL_checkstring(L, 2); size_t len = 0; const void* data = NULL; if (nargs > 2) { data = luaL_checklstring(L, 3, &len); } Net::Message messageObject ( message, data, len ); Net::Server::SendMessage ( clientID, messageObject ); return 0; } int NetServer_BroadcastMessage ( lua_State* L ) { int nargs = lua_gettop(L); const char* message = luaL_checkstring(L, 1); size_t len = 0; const void* data = NULL; if (nargs > 1) { data = luaL_checklstring(L, 2, &len); } Net::Message messageObject ( message, data, len ); Net::Server::BroadcastMessage ( messageObject ); return 0; } int NetServer_GetMessage ( lua_State* L ) { Net::Message* msg = Net::Server::GetMessage(); if (msg) { lua_pushlstring(L, msg->message.data(), msg->message.length()); if (msg->data) { lua_pushlstring(L, (const char*)msg->data, msg->dataLength); } else { lua_pushnil(L); } lua_pushinteger(L, msg->clientID); delete msg; } else { lua_pushnil(L); lua_pushnil(L); lua_pushnil(L); } return 3; } /** * @page lua_net_server The Lua Net Server Registry * This page contains information about the Lua net server registry. * * This registry contains functions related to running a multiplayer server. In * Lua, they are all called like so: "net_server.function_name()" (for example: * "startup" becomes "net_server.startup(port, password)"). * * Note: Somebody else will need to complete this registry, I don't know * anything about it right now. * * @section startup * * @section shutdown * * @section running * * @section client_count * * @section kill * * @section net_server_connected connected * * @section net_server_send send * * @section broadcast * * @section net_server_get get * * @todo Complete the @ref lua_net_server registry. * */ luaL_Reg registryNetServer[] = { "startup", NetServer_Startup, "shutdown", NetServer_Shutdown, "running", NetServer_Running, "client_count", NetServer_ClientCount, "kill", NetServer_KillClient, "connected", NetServer_Connected, "send", NetServer_SendMessage, "broadcast", NetServer_BroadcastMessage, "get", NetServer_GetMessage, NULL, NULL }; // XML code based on code from lua-users.org void XML_ParseNode (lua_State* L, TiXmlNode* xmlNode) { if (!xmlNode) return; // resize stack if neccessary luaL_checkstack(L, 5, "XML_ParseNode : recursion too deep"); TiXmlElement* xmlElement = xmlNode->ToElement(); if (xmlElement) { // element name lua_pushstring(L, "name"); lua_pushstring(L, xmlElement->Value()); lua_settable(L, -3); // parse attributes TiXmlAttribute* xmlAttribute = xmlElement->FirstAttribute(); if (xmlAttribute) { lua_pushstring(L, "attr"); lua_newtable(L); for (; xmlAttribute; xmlAttribute = xmlAttribute->Next()) { lua_pushstring(L, xmlAttribute->Name()); lua_pushstring(L, xmlAttribute->Value()); lua_settable(L, -3); } lua_settable(L, -3); } } // children TiXmlNode *child = xmlNode->FirstChild(); if (child) { int childCount = 0; for(; child; child = child->NextSibling()) { switch (child->Type()) { case TiXmlNode::DOCUMENT: break; case TiXmlNode::ELEMENT: // normal element, parse recursive lua_newtable(L); XML_ParseNode(L, child); lua_rawseti(L, -2, ++childCount); break; case TiXmlNode::COMMENT: break; case TiXmlNode::TEXT: // plaintext, push raw lua_pushstring(L, child->Value()); lua_rawseti(L, -2, ++childCount); break; case TiXmlNode::DECLARATION: break; case TiXmlNode::UNKNOWN: break; }; } lua_pushstring(L, "n"); lua_pushnumber(L, childCount); lua_settable(L, -3); } } static int XML_ParseFile (lua_State *L) { const char* fileName = luaL_checkstring(L, 1); SDL_RWops* ops = ResourceManager::OpenFile(fileName); size_t len; void* dataPointer = ResourceManager::ReadFull(&len, ops, 1); char* fullDataPointer = (char*)malloc(len + 1); fullDataPointer[len] = 0; memcpy(fullDataPointer, dataPointer, len); free(dataPointer); TiXmlDocument doc ( fileName ); doc.Parse(fullDataPointer); lua_newtable(L); XML_ParseNode(L, &doc); free((void*)fullDataPointer); return 1; } /** * @page lua_xml The Lua XML Registry * This page contains information about the Lua XML registry. * * This registry currently only contains one function. In Lua, it is called * called like so: "xml.load(file)". * * @section load * Loads and parses an XML file\n * Parameters:\n * name - The name of the mode that the game is currently in.\n * Returns:\n * A table with the contents of the file in it.\n */ luaL_Reg registryXML[] = { "load", XML_ParseFile, NULL, NULL }; int WIND_IsFullscreen ( lua_State* L ) { lua_pushboolean(L, ToBool(Preferences::Get("Screen/Fullscreen"))); return 1; } int WIND_SetFullscreen ( lua_State* L ) { Preferences::Set("Screen/Fullscreen", luaL_checkstring(L, 1) ); Graphics::Init(ToInt(Preferences::Get("Screen/Width")), ToInt(Preferences::Get("Screen/Height")), ToBool(Preferences::Get("Screen/Fullscreen"))); return 0; } int WIND_ToggleFullscreen ( lua_State* L ) { Preferences::Set("Screen/Fullscreen", Preferences::Get("Screen/Fullscreen") == "true" ? "false" : "true"); Graphics::Init(ToInt(Preferences::Get("Screen/Width")), ToInt(Preferences::Get("Screen/Height")), ToBool(Preferences::Get("Screen/Fullscreen"))); return 0; } int WIND_WindowSize ( lua_State* L ) { lua_pushnumber(L, ToInt(Preferences::Get("Screen/Width"))); lua_pushnumber(L, ToInt(Preferences::Get("Screen/Height"))); return 2; } int WIND_SetWindow ( lua_State* L ) { vec2 newSize = luaL_checkvec2(L, 1); std::string width = FloatToString(newSize.X()); std::string height = FloatToString(newSize.Y()); Preferences::Set("Screen/Width", width); Preferences::Set("Screen/Height", height); Graphics::Init(ToInt(Preferences::Get("Screen/Width")), ToInt(Preferences::Get("Screen/Height")), ToBool(Preferences::Get("Screen/Fullscreen"))); return 0; } int WIND_MouseToggle ( lua_State* L ) { if (SDL_ShowCursor(SDL_QUERY) == SDL_ENABLE) SDL_ShowCursor(SDL_DISABLE); else SDL_ShowCursor(SDL_ENABLE); return 0; } /** * @page lua_window The Lua Window Registry * This page contains information about the Lua Window registry. * * This registry contains miscellaneous functions for modifying the SDL window's * properties. * * @section is_fullscreen * Checks the status of the SDL window with regards to fullscreen or windowed * mode.\n * Returns:\n * A boolean value of true or false - true for fullscreen, false for windowed. * * @section set_fullscreen * Sets the fullscreen status of the SDL window based upon the argument given.\n * Parameters:\n * fullscreen - a string equivalent of the boolean value of whether or not the * window should be set to fullscreen.\n * Returns:\n * Initially this function will return nothing, but there are plans to allow for * it to return the SDL status given (in case there's a problem with setting it * to fullscreen). * * @section toggle_fullscreen * Changes the fullscreen status of the SDL window. No parameters or returns.\n * * @section size * Gives the size of the screen in pixels.\n * Returns:\n * size - a vectorized size table containing the dimensions of the window in * pixels. (currently returns two values, I hope to make it a table soon) * * @todo Make @ref size return a vectorized table instead of two values * * @section set * Sets the size of the screen in pixels.\n * Parameters:\n * A table of a coordinate pair, representing the size of the screen (in pixels) * .\n */ luaL_Reg registryWindowManager[] = { "is_fullscreen", WIND_IsFullscreen, "set_fullscreen", WIND_SetFullscreen, "toggle_fullscreen", WIND_ToggleFullscreen, "size", WIND_WindowSize, "set", WIND_SetWindow, "mouse_toggle", WIND_MouseToggle, NULL, NULL }; int MM_Switch ( lua_State* L ) { int nargs = lua_gettop(L); const char* newmode = luaL_checkstring(L, 1); if (nargs > 1) { SwitchMode(std::string(newmode), luaL_ref(L, 2)); } else { SwitchMode(std::string(newmode)); } return 0; } int MM_Time ( lua_State* L ) { lua_pushnumber(L, GameTime()); return 1; } int MM_Query ( lua_State* L ) { lua_pushstring(L, QueryMode()); return 1; } int MM_Release ( lua_State* L ) { #ifdef NDEBUG lua_pushboolean(L, true); return 1; #else lua_pushboolean(L, false); return 1; #endif } /** * @page lua_mode_manager The Lua Mode Manager Registry * This page contains information about the Lua mode manager registry. * * This small registry contains functions for dealing with modes. Modes are the * states in which Lua runs, containing functions triggered by certain states of * Apollo (like mouse movement, keyboard presses, etc). In Lua, they are all * called like so: "mode_manager.function_name()" (for example: "switch" becomes * "mode_manager.switch(mode)"). * * @section switch * Switches the game mode. If the mode cannot be switched to the given name, an * error occurs.\n * Parameters:\n * mode - the name of the mode you want to switch to (without the suffix * ".lua"). For example, to switch to "MainMenu.lua", enter "MainMenu" for the * parameter. * * @section time * Gives the game's time, in seconds, since the game's start. This function has * no parameters.\n * Returns:\n * number - The amount of seconds (accurate to miliseconds) since the game's * start. * * @section query * Returns the game's current mode. This function has no parameters.\n * Returns:\n * string - The name of the mode that the game is currently in. * * @section is_release * Returns the game's current build mode. This function has no parameters.\n * Returns:\n * bool - True if the game's current build is a release build, false if not. */ luaL_Reg registryModeManager[] = { "switch", MM_Switch, "time", MM_Time, "query", MM_Query, "is_release", MM_Release, NULL, NULL }; int RM_Load ( lua_State* L ) { const char* file = luaL_checkstring(L, 1); SDL_RWops* ptr = ResourceManager::OpenFile(file); if (ptr) { size_t len; void* data = ResourceManager::ReadFull(&len, ptr, 1); lua_pushlstring(L, (const char*)data, len); free(data); return 1; } else { lua_pushliteral(L, "file not found"); return lua_error(L); } } int RM_FileExists ( lua_State* L ) { const char* file = luaL_checkstring(L, 1); bool exists = ResourceManager::FileExists(file); lua_pushboolean(L, exists ? 1 : 0); return 1; } int RM_Write ( lua_State* L ) { const char* file = luaL_checkstring(L, 1); size_t len; const char* data = luaL_checklstring(L, 2, &len); ResourceManager::WriteFile(file, (const void*)data, len); return 0; } /** * @page lua_resource_manager The Lua Resource Manager Registry * This page contains information about the Lua resource manager registry. * * This small registry contains a few simple tools for manipulating files. In * Lua, they are all called like so: "resource_manager.function_name()" (for * example: "file_exists" becomes "resource_manager.file_exists(file)"). * * @section file_exists * Ensures that the given file exists, then returns a boolean of whether it does * or not.\n * Parameters:\n * file - The name of the file\n * Returns:\n * Boolean - true if file exists, false if it does not\n * * @section load * Loads a given file. Will return error statement along with error if the file * does not exist or cannot be opened.\n * Parameters:\n * file - The name of the file to be loaded\n * Returns:\n * data - If the load is successful, data will be returned from the file * literal - If the load is unsuccessful, a string will be returned ("file not * found") * * @section write * Writes to a given file. No error checking implemented. * Parameters:\n * file - The name of the file\n * data - The data to be written to the file\n */ luaL_Reg registryResourceManager[] = { "file_exists", RM_FileExists, "load", RM_Load, "write", RM_Write, NULL, NULL }; int GFX_BeginFrame ( lua_State* L ) { Graphics::BeginFrame(); return 0; } int GFX_EndFrame ( lua_State* L ) { Graphics::EndFrame(); return 0; } int GFX_SetCamera ( lua_State* L ) { float ll_x, ll_y, tr_x, tr_y, rot = 0.0f; int nargs = lua_gettop(L); ll_x = luaL_checknumber(L, 1); ll_y = luaL_checknumber(L, 2); tr_x = luaL_checknumber(L, 3); tr_y = luaL_checknumber(L, 4); if (nargs > 4) rot = luaL_checknumber(L, 5); Graphics::SetCamera(vec2(ll_x, ll_y), vec2(tr_x, tr_y), rot); return 0; } static colour LoadColour ( lua_State* L, int index ) { float r = 1.0f, g = 1.0f, b = 1.0f, a = 1.0f; lua_getfield(L, index, "r"); r = luaL_checknumber(L, -1); lua_getfield(L, index, "g"); g = luaL_checknumber(L, -1); lua_getfield(L, index, "b"); b = luaL_checknumber(L, -1); lua_getfield(L, index, "a"); a = luaL_checknumber(L, -1); return colour(r, g, b, a); } int GFX_DrawText ( lua_State* L ) { int nargs = lua_gettop(L); const char* text = luaL_checkstring(L, 1); const char* font = luaL_checkstring(L, 2); const char* justify = luaL_checkstring(L, 3); vec2 location = luaL_checkvec2(L, 4); float height = luaL_checknumber(L, 5); float rotation = 0.0f; if (nargs >= 7) { rotation = luaL_checknumber(L, 7); } if (nargs >= 6) { luaL_argcheck(L, lua_istable(L, 6), 6, "bad colour"); Graphics::DrawTextSDL(text, font, justify, location, height, LoadColour(L, 6), rotation); } else { Graphics::DrawTextSDL(text, font, justify, location, height, colour(1.0f, 1.0f, 1.0f, 1.0f), rotation); } return 0; } int GFX_TextLength (lua_State* L ) { const char* text = luaL_checkstring(L, 1); const char* font = luaL_checkstring(L, 2); float height = luaL_checknumber(L, 3); vec2 dims = Graphics::TextRenderer::TextDimensions(font, text, height); // printf("[%f, %f]\n", dims.X(), dims.Y()); dims = dims * (height / dims.Y()); // printf("[%f, %f]\n", dims.X(), dims.Y()); lua_pushnumber(L, dims.X()); return 1; } int GFX_DrawLine ( lua_State* L ) { int nargs = lua_gettop(L); float width; vec2 point1 = luaL_checkvec2(L, 1); vec2 point2 = luaL_checkvec2(L, 2); width = luaL_checknumber(L, 3); if (nargs > 3) { Graphics::DrawLine(point1, point2, width, LoadColour(L, 4)); } else { Graphics::DrawLine(point1, point2, width, colour(0.0f, 1.0f, 0.0f, 1.0f)); } return 0; } int GFX_DrawLightning ( lua_State* L ) { int nargs = lua_gettop(L); float width, chaos; bool tailed; vec2 point1 = luaL_checkvec2(L, 1); vec2 point2 = luaL_checkvec2(L, 2); width = luaL_checknumber(L, 3); chaos = luaL_checknumber(L, 4); tailed = lua_tonumber(L, 5); if (nargs > 5) { Graphics::DrawLightning(point1, point2, width, chaos, LoadColour(L, 6), tailed); } else { Graphics::DrawLightning(point1, point2, width, chaos, colour(0.93f, 0.88f, 1.0f, 1.0f), tailed); } return 0; } int GFX_DrawBox ( lua_State* L ) { int nargs = lua_gettop(L); float top, left, bottom, right, width; top = luaL_checknumber(L, 1); left = luaL_checknumber(L, 2); bottom = luaL_checknumber(L, 3); right = luaL_checknumber(L, 4); width = luaL_checknumber(L, 5); colour col = colour(0.0f, 1.0f, 0.0f, 1.0f); if (nargs > 5) { col = LoadColour(L, 6); } Graphics::DrawBox(top, left, bottom, right, width, col); return 0; } int GFX_DrawPoint ( lua_State* L ) { int nargs = lua_gettop(L); float size = 1; vec2 location = luaL_checkvec2(L, 1); colour col = colour(0.0f, 1.0f, 0.0f, 1.0f); if (nargs > 1) { size = luaL_checknumber(L, 2); } if (nargs > 2) { col = LoadColour(L, 3); } Graphics::DrawPoint(location, size, col); return 0; } int GFX_DrawRadarTriangle ( lua_State* L ) { int nargs = lua_gettop(L); vec2 coordinates = luaL_checkvec2(L, 1); float varsize = luaL_checknumber(L, 2); if (nargs > 2) { Graphics::DrawTriangle(vec2(coordinates.X(), coordinates.Y() + varsize), vec2(coordinates.X() - varsize, coordinates.Y() - varsize), vec2(coordinates.X() + varsize, coordinates.Y() - varsize), LoadColour(L, 3)); } else { Graphics::DrawTriangle(vec2(coordinates.X(), coordinates.Y() + varsize), vec2(coordinates.X() - varsize, coordinates.Y() - varsize), vec2(coordinates.X() + varsize, coordinates.Y() - varsize), colour(0.0f, 1.0f, 0.0f, 1.0f)); } return 0; } int GFX_DrawRadarPlus ( lua_State* L ) { int nargs = lua_gettop(L); vec2 coordinates = luaL_checkvec2(L, 1); float varsize = luaL_checknumber(L, 2); if (nargs > 2) { Graphics::DrawBox(coordinates.Y() + varsize, coordinates.X() - 0.3 * varsize, coordinates.Y() - varsize, coordinates.X() + 0.3 * varsize, 0, LoadColour(L, 3)); Graphics::DrawBox(coordinates.Y() + 0.3 * varsize, coordinates.X() - varsize, coordinates.Y() - 0.3 * varsize, coordinates.X() + varsize, 0, LoadColour(L, 3)); } else { Graphics::DrawBox(coordinates.Y() + varsize, coordinates.X() - 0.3 * varsize, coordinates.Y() - varsize, coordinates.X() + 0.3 * varsize, 0, colour(0, 1, 0, 1)); Graphics::DrawBox(coordinates.Y() + 0.3 * varsize, coordinates.X() - varsize, coordinates.Y() - 0.3 * varsize, coordinates.X() + varsize, 0, colour(0, 1, 0, 1)); } return 0; } int GFX_DrawRadarBox ( lua_State* L ) { int nargs = lua_gettop(L); vec2 coordinates = luaL_checkvec2(L, 1); float varsize = luaL_checknumber(L, 2); if (nargs > 2) { Graphics::DrawBox(coordinates.Y() + varsize, coordinates.X() - varsize, coordinates.Y() - varsize, coordinates.X() + varsize, 0, LoadColour(L, 3)); } else { Graphics::DrawBox(coordinates.Y() + varsize, coordinates.X() - varsize, coordinates.Y() - varsize, coordinates.X() + varsize, 0, colour(0, 1, 0, 1)); } return 0; } int GFX_DrawRadarDiamond ( lua_State* L ) { int nargs = lua_gettop(L); vec2 coordinates = luaL_checkvec2(L, 1); float varsize = luaL_checknumber(L, 2); if (nargs > 2) { Graphics::DrawDiamond(coordinates.Y() + varsize, coordinates.X() - varsize, coordinates.Y() - varsize, coordinates.X() + varsize, LoadColour(L, 3)); } else { Graphics::DrawDiamond(coordinates.Y() + varsize, coordinates.X() - varsize, coordinates.Y() - varsize, coordinates.X() + varsize, colour(0, 1, 0, 1)); } return 0; } int GFX_DrawObject3DAmbient ( lua_State* L ) { std::string object = luaL_checkstring(L, 1); vec2 location = luaL_checkvec2(L, 2); float scale = luaL_checknumber(L, 3); float angle = luaL_checknumber(L, 4); float bank = luaL_optnumber(L, 5, 0.0); Graphics::DrawObject3DAmbient(object, location, scale, angle, bank); return 0; } int GFX_DrawParticles ( lua_State* L ) { Graphics::DrawParticles(); return 0; } int GFX_ClearParticles ( lua_State* L ) { Graphics::ClearParticles(); } int GFX_AddParticles ( lua_State* L ) { const char* name = luaL_checkstring(L, 1); unsigned long pcount = luaL_checkinteger(L, 2); vec2 location = luaL_checkvec2(L, 3); vec2 velocity = luaL_checkvec2(L, 4); vec2 velocityVar = luaL_checkvec2(L, 5); vec2 acc = luaL_checkvec2(L, 6); float size = luaL_checknumber(L, 7); float lifetime = luaL_checknumber(L, 8); Graphics::AddParticles(name, pcount, location, velocity, velocityVar, acc, size, lifetime); return 0; } int GFX_DrawCircle ( lua_State* L ) { int nargs = lua_gettop(L); float radius, width; vec2 location = luaL_checkvec2(L, 1); radius = luaL_checknumber(L, 2); width = luaL_checknumber(L, 3); if (nargs > 3) { Graphics::DrawCircle(location, radius, width, LoadColour(L, 4)); } else { Graphics::DrawCircle(location, radius, width, colour(0.0f, 1.0f, 0.0f, 1.0f)); } return 0; } int GFX_DrawImage ( lua_State* L ) { const char* imgName; imgName = luaL_checkstring(L, 1); vec2 location = luaL_checkvec2(L, 2); vec2 size = luaL_checkvec2(L, 3); Graphics::DrawImage(imgName, location, size); return 0; } int GFX_SpriteDimensions ( lua_State* L ) { const char* spritesheet; spritesheet = luaL_checkstring(L, 1); vec2 dims = Graphics::SpriteDimensions(spritesheet); lua_pushvec2(L, dims); return 1; } int GFX_DrawSprite ( lua_State* L ) { const char* spritesheet; int nargs = lua_gettop(L); float rot = 0.0f; colour col; spritesheet = luaL_checkstring(L, 1); vec2 location = luaL_checkvec2(L, 2); vec2 size = luaL_checkvec2(L, 3); if (nargs > 3) { rot = luaL_checknumber(L, 4); } if (nargs > 4) { Graphics::DrawSprite(spritesheet, 0, 0, location, size, rot, LoadColour(L, 5)); } else { Graphics::DrawSprite(spritesheet, 0, 0, location, size, rot, colour(1.0f, 1.0f, 1.0f, 1.0f)); } return 0; } int GFX_DrawStarfield ( lua_State* L ) { if (lua_gettop(L) > 0) { float depth = luaL_checknumber(L, 1); Graphics::DrawStarfield(depth); } else { Graphics::DrawStarfield(0.0f); } return 0; } int GFX_IsCulled ( lua_State* L ) { vec2 location = luaL_checkvec2(L, 1); float radius = luaL_optnumber(L, 2, 0.0); bool isCulled = Graphics::IsCulled(location, radius); lua_pushboolean(L, isCulled ? 1 : 0); return 1; } int GFX_DrawSpriteFromSheet ( lua_State* L ) { const char* spritesheet; int nargs = lua_gettop(L); float rot = 0.0f; spritesheet = luaL_checkstring(L, 1); vec2 sheet = luaL_checkvec2(L, 2); vec2 location = luaL_checkvec2(L, 3); vec2 size = luaL_checkvec2(L, 4); if (nargs > 4) { rot = luaL_checknumber(L, 5); } if (nargs > 5) { Graphics::DrawSprite(spritesheet, sheet.X(), sheet.Y(), location, size, rot, LoadColour(L, 6)); } else { Graphics::DrawSprite(spritesheet, sheet.X(), sheet.Y(), location, size, rot, colour(1.0f, 1.0f, 1.0f, 1.0f)); } return 0; } int GFX_DrawSpriteFrame ( lua_State* L ) { const char* spritesheet; int nargs = lua_gettop(L); float rot = 0.0f; spritesheet = luaL_checkstring(L, 1); vec2 location = luaL_checkvec2(L, 2); vec2 size = luaL_checkvec2(L, 3); int index = luaL_checkinteger(L, 4); if (nargs > 4) { rot = luaL_checknumber(L, 5); } if (nargs > 5) { Graphics::DrawSpriteFrame(spritesheet, location, size, index, rot, LoadColour(L, 6)); } else { Graphics::DrawSpriteFrame(spritesheet, location, size, index, rot, colour(1.0f, 1.0f, 1.0f, 1.0f)); } return 0; } int GFX_BeginWarp ( lua_State* L ) { float magnitude = luaL_checknumber(L, 1); float angle = luaL_checknumber(L, 2); float scale = luaL_checknumber(L, 3); Graphics::BeginWarp(magnitude, angle, scale); return 0; } int GFX_EndWarp ( lua_State* L ) { Graphics::EndWarp(); int argCount = lua_gettop(L); if (argCount == 4) { float magnitude = luaL_checknumber(L, 1); float angle = luaL_checknumber(L, 2); float scale = luaL_checknumber(L, 3); vec2 position = luaL_checkvec2(L, 4); Graphics::DrawCircle(position, 45 * scale, 5, colour(1,0,0,1)); Graphics::DrawCircle(position, 45 * scale * magnitude, 5, colour(0,1,0,1)); } return 0; } /** * @page lua_graphics The Lua Graphics Registry * This page contains information about the Lua graphics registry. * * This registry contains all drawing mechanisms for Lua, along with some * drawing manipulation functions. In Lua, they are all called like so: * "graphics.function_name()" (for example: "begin_frame" becomes * "graphics.begin_frame()"). * * @section frame_and_camera Frame and Camera * * @subsection begin_frame * Must be called before any graphics routines are called. It has no parameters. * * @subsection end_frame * Must be called after any graphics routines are called. It has no parameters. * * @subsection set_camera * Sets the bounds of the camera. It requires arguments for the left, bottom, * right, and top of the camera, respectively.\n * Parameters:\n * left - The left, or lower-x bound, of the screen.\n * bottom - The bottom, or lower-y bound, of the screen.\n * right - The right, or upper-x bound, of the screen.\n * top - The top, or upper-y bound, of the screen.\n * * @section sprites Sprites * * @subsection draw_image * Draws an "image", which is functionally different from a sprite. In general, * a sprite has rotational capabilities and / or multiple frames, like most * ships, where an image does not, like panels on the sides of the screen.\n * Parameters:\n * imgname - The name of the image to be drawn\n * loc_x - The x location of where the center of the image should be\n * loc_y - The y location of where the center of the image should be\n * size_x - The x size, in pixels, of the image\n * size_y - The y size, in pixels, of the image - note that size_x and size_y * should be in the same ratio of x:y as the original image, or stretching may * occur.\n * rot - The rotation of the image, in radians. Optional parameter.\n * colour - The colour to be applied to the image, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_sprite * Draws a "sprite", which is functionally different from an image. In general, * a sprite has rotational capabilities and / or multiple frames, like a ship, * where an image does not, like panels on the sides of the screen. * Parameters:\n * spritesheet - The name of the file containing the sprites\n * loc_x - The x location of where the center of the sprite should be\n * loc_y - The y location of where the center of the sprite should be\n * size_x - The x size, in pixels, of the sprite\n * size_y - The y size, in pixels, of the sprite - note that size_x and size_y * should be in the same ratio of x:y as the original image, or stretching may * occur.\n * rot - The rotation of the sprite, in radians. Determines which sprite is * drawn\n * colour - The colour to be applied to the sprite, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_sheet_sprite * Draws a given sprite from within a sprite sheet.\n * Parameters:\n * spritesheet - The name of the sprite sheet to be drawn\n * sheet_x - ?\n * sheet_y - ?\n * loc_x - The x location of where the center of the sprite should be\n * loc_y - The y location of where the center of the sprite should be\n * size_x - The x size, in pixels, of the sprite\n * size_y - The y size, in pixels, of the sprite - note that size_x and size_y * should be in the same ratio of x:y as the original image, or stretching may * occur.\n * rot - The rotation of the sprite, in radians. Determines which sprite is * drawn\n * colour - The colour to be applied to the sprite, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * @todo define sheet_x and sheet_y for @ref draw_sheet_sprite * @todo add in table reading for colours to @ref draw_sheet_sprite * * @subsection sprite_dimensions * Returns the dimensions for a given sprite.\n * Parameters:\n * spritesheet - The sprite sheet to check the dimensions of.\n * Returns:\n * x - The x size of one sprite on the sheet\n * y - The y size of one sprite on the sheet * * @subsection draw_starfield * Draws a starfield at the given depth. Draw multiple starfields at varying * depths to give them a parallax feel. * Parameters:\n * depth - How deep the starfield should appear. Optional parameter (default is * 0). * * @section drawing_text Drawing Text * * @subsection draw_text * Given a position, size, font, and some text, (and optionally a rotation and * some colour) this function will draw text to the screen with those * specifications. If not given rotation or colour, this function will default * to zero degrees rotation and white text.\n * Parameters:\n * text - The text to be displayed on the screen\n * font - The font for the text to be drawn in\n * justify - One of "left", "right", or "center", the justification of the text. * If misspelled or missing, defaults to "center".\n * loc_x - The x coordinate of the text. Justification revolves around the * position of this component.\n * loc_y - The y coordinate of the text.\n * height - The size of the font to be displayed.\n * rotation - Rotation clockwise from the viewer's perspective, in radians.\n * colour - The colour to be applied to the text, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection text_length * Given a size, font, and some text, this function will output how long this * text will be on the screen.\n * Parameters:\n * text - The text to be sized up\n * font - The font being used for the text\n * height - the size of the font * * @section drawing_basic_objects Drawing Basic Objects * * @subsection draw_line * Draws a basic line.\n * Parameters:\n * x1 - The x coordinate of the starting point.\n * y1 - The y coordinate of the starting point.\n * x2 - The x coordinate of the ending point.\n * y2 - The y coordinate of the ending point.\n * width - The thickness of the line in pixels.\n * colour - The colour to be applied to the line, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_point * * @subsection draw_box * Draws a basic box.\n * Parameters:\n * top - The y coordinate of the top of the box.\n * left - The x coordinate of the left of the box.\n * bottom - The y coordinate of the bottom of the box.\n * right - The x coordinate of the right of the box.\n * width - The thickness of the line surrounding the boxin pixels. Use 0 for no * line.\n * colour - The colour to be applied to the box, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_circle * Draws a "circle", which is really just a series of lines approximating a * circle.\n * x - The x coordinate of the center of the circle.\n * y - The y coordinate of the center of the circle.\n * radius - The radius of the circle.\n * width - The width of the lines comprising the circle.\n * colour - The colour to be applied to the circle, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @section drawing_radar_objects Drawing 'Radar' Objects * * @subsection draw_rtri * Draws a triangle - generally used as a placeholder for objects when zoomed * out beyond 1:8 camera ratios. (short for "radar triangle")\n * x - The x coordinate of the center of the triangle.\n * y - The y coordinate of the center of the triangle.\n * varsize - The size of the triangle, according to the object's data.\n * colour - The colour to be applied to the triangle, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_rplus * Draws a plus sign - generally used as a placeholder for objects when zoomed * out beyond 1:8 camera ratios (short for "radar plus").\n * x - The x coordinate of the center of the plus.\n * y - The y coordinate of the center of the plus.\n * varsize - The size of the plus, according to the object's data.\n * colour - The colour to be applied to the plus, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_rbox * Draws a square - generally used as a placeholder for objects when zoomed out * beyond 1:8 camera ratios (short for "radar box").\n * x - The x coordinate of the center of the box.\n * y - The y coordinate of the center of the box.\n * varsize - The size of the box, according to the object's data.\n * colour - The colour to be applied to the box, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_rdia * Draws a diamond - generally used as a placeholder for objects when zoomed out * beyond 1:8 camera ratios (short for "radar diamond").\n * x - The x coordinate of the center of the diamond.\n * y - The y coordinate of the center of the diamond.\n * varsize - The size of the diamond, according to the object's data.\n * colour - The colour to be applied to the diamond, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection is_culled * Checks to see if a particular circle is entirely outside of the vision of the * camera.\n * Parameters:\n * x - The x coordinate of the center of the circle.\n * y - The y coordinate of the center of the circle.\n * radius - The radius of the circle.\n * Returns:\n * isCulled - If the circle is entirely off the screen, true. Otherwise false. * * @section Special Effects * This section contains information about special effects like particles and * lightning. * * @subsection draw_lightning * Draws lightning effects needed for certain weapons.\n * x1 - The x coordinate of the starting point.\n * y1 - The y coordinate of the starting point.\n * x2 - The x coordinate of the ending point.\n * y2 - The y coordinate of the ending point.\n * width - The thickness of the lightning in pixels.\n * chaos - How jagged the lightning appears. 0 gives perfectly straight * lightning.\n * tailed - If tailed is true, the lightning tapers down to the endpoint. If * tailed is false, the lightning does not taper down to the endpoint but * instead ends somewhere around the endpoint.\n * colour - The colour to be applied to the lightning, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * @todo figure out "chaos" and "tailed" properties of @ref draw_lightning * * @subsection add_particles * * @subsection draw_particles * * @subsection clear_particles * * @subsection begin_warp * * @subsection end_warp * * @subsection draw_3d_ambient * * @todo Document @ref add_particles, @ref draw_particles, @ref clear_particles, @ref begin_warp, @ref end_warp, and @ref draw_point * @todo Fix documentation @ref draw_image and @ref draw_sprite to better define sprites/images. */ luaL_Reg registryGraphics[] = { "begin_frame", GFX_BeginFrame, "end_frame", GFX_EndFrame, "set_camera", GFX_SetCamera, "draw_image", GFX_DrawImage, "draw_sprite", GFX_DrawSprite, "draw_sheet_sprite", GFX_DrawSpriteFromSheet, "draw_sprite_frame", GFX_DrawSpriteFrame, "sprite_dimensions", GFX_SpriteDimensions, "draw_starfield", GFX_DrawStarfield, "draw_text", GFX_DrawText, "text_length", GFX_TextLength, "draw_line", GFX_DrawLine, "draw_box", GFX_DrawBox, "draw_point", GFX_DrawPoint, "draw_circle", GFX_DrawCircle, "draw_rtri", GFX_DrawRadarTriangle, "draw_rplus", GFX_DrawRadarPlus, "draw_rbox", GFX_DrawRadarBox, "draw_rdia", GFX_DrawRadarDiamond, "is_culled", GFX_IsCulled, "draw_lightning", GFX_DrawLightning, "add_particles", GFX_AddParticles, "draw_particles", GFX_DrawParticles, "clear_particles", GFX_ClearParticles, "begin_warp", GFX_BeginWarp, "end_warp", GFX_EndWarp, "draw_3d_ambient", GFX_DrawObject3DAmbient, NULL, NULL }; int Sound_Play ( lua_State* L ) { const char* sound; float pan = 0.0f; float volume = 1.0f; int nargs = lua_gettop(L); sound = luaL_checkstring(L, 1); if (nargs > 1) volume = luaL_checknumber(L, 2); Sound::PlaySound (sound, volume); return 0; } int Sound_PlayPositional ( lua_State* L ) { const char* sound = luaL_checkstring(L, 1); vec2 pos = luaL_checkvec2(L, 2); vec2 vel = luaL_checkvec2(L, 3); float volume = luaL_optnumber(L, 4, 1.0); Sound::PlaySoundPositional(sound, pos, vel, volume); return 0; } int Sound_Listener ( lua_State* L ) { vec2 pos = luaL_checkvec2(L, 1); vec2 vel = luaL_checkvec2(L, 2); Sound::SetListener(pos, vel); return 0; } int Sound_Preload ( lua_State* L ) { const char* sound = luaL_checkstring(L, 1); Sound::Preload(sound); return 0; } int Sound_PlayMusic ( lua_State* L ) { const char* mus = luaL_checkstring(L, 1); Sound::PlayMusic(mus); return 0; } int Sound_StopMusic ( lua_State* L ) { Sound::StopMusic(); return 0; } int Sound_CurrentMusic ( lua_State* L ) { std::string name = Sound::MusicName(); lua_pushlstring(L, name.data(), name.length()); return 1; } /** * @page lua_sound The Lua Sound Registry * This page contains information about the Lua sound registry. * * This registry contains all music control mechanisms for Lua, along with a * function for playing sound effects. In Lua, they are all called like so: * "sound.function_name()" (for example: "play" becomes "sound.play(file)"). * * @section sounds Sounds * * @subsection play * Plays the specified sound effect.\n * Parameters:\n * sound - The name of the sound file to be played. * * @subsection preload * Preloads the specified sound effect for quicker access in-game.\n * Parameters:\n * sound - The name of the sound file to be preloaded. * * @section music Music * * @subsection play_music * Plays the given song. Songs can be stopped on command, and their names can be * queried.\n * Parameters:\n * song - the name of the song to be played. * * @subsection stop_music * Stops the current song. This function has no parameters. * * @subsection current_music * Queries the name of the song currently playing. This function has no * parameters.\n * Return:\n * song - the name of the currently playing song. */ luaL_Reg registrySound[] = { "play", Sound_Play, "play_positional", Sound_PlayPositional, "listener", Sound_Listener, "preload", Sound_Preload, "play_music", Sound_PlayMusic, "stop_music", Sound_StopMusic, "current_music", Sound_CurrentMusic, NULL, NULL }; typedef struct Component { LuaScript* script; }; int CPT_Create ( lua_State* L ) { const char* name = luaL_checkstring(L, 1); Component* cpt = (Component*)lua_newuserdata(L, sizeof(Component)); cpt->script = new LuaScript ( std::string("Components/") + name ); cpt->script->InvokeSubroutine("component_init"); luaL_getmetatable(L, "Apollo.Component"); lua_setmetatable(L, -2); return 1; } int CPT_Cleanup ( lua_State* L ) { Component* cpt = (Component*)luaL_checkudata(L, 1, "Apollo.Component"); if (cpt->script) { cpt->script->InvokeSubroutine("component_quit"); delete cpt->script; cpt->script = NULL; } return 0; } int CPT_Invoke ( lua_State* L ) { Component* cpt = (Component*)luaL_checkudata(L, 1, "Apollo.Component"); LuaScript* script = cpt->script; luaL_argcheck(L, script, 1, "Component already freed"); const char* routine = luaL_checkstring(L, 2); lua_State* componentState = script->RawState(); int nargs = lua_gettop(L); int oldBase = lua_gettop(componentState); lua_getglobal(componentState, routine); if (!lua_isfunction(componentState, -1)) { char errorBuffer[512]; sprintf(errorBuffer, "Component has no routine named '%s'", routine); lua_pushstring(L, errorBuffer); return lua_error(L); } if (nargs > 2) { lua_xmove(L, componentState, nargs - 2); } int rc = lua_pcall(componentState, nargs - 2, LUA_MULTRET, 0); if (rc != 0) { lua_xmove(componentState, L, 1); return lua_error(L); } int newBase = lua_gettop(componentState); int nresults = newBase - oldBase; lua_xmove(componentState, L, nresults); lua_settop(componentState, oldBase); return nresults; } luaL_Reg registryComponent[] = { "create", CPT_Create, "invoke", CPT_Invoke, NULL, NULL }; luaL_Reg registryObjectComponent[] = { "invoke", CPT_Invoke, "__gc", CPT_Cleanup, NULL, NULL }; int luaopen_component ( lua_State* L ) { luaL_newmetatable(L, "Apollo.Component"); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_register(L, NULL, registryObjectComponent); luaL_register(L, "component", registryComponent); return 1; } int IN_StillTime ( lua_State* L ) { float stillTime = Input::MouseStillTime(); lua_pushnumber(L, stillTime); return 1; } int IN_Position ( lua_State* L ) { vec2 mouse = Input::MousePosition(); lua_pushvec2(L, mouse); return 1; } luaL_Reg registryInput[] = { "mouse_still_time", IN_StillTime, "mouse_position", IN_Position, NULL, NULL }; int import ( lua_State* L ) { const char* modulename = luaL_checkstring(L, 1); LuaScript::RawImport(L, modulename); return 0; } } /** * @page all_lua_bindings All LuaBind Registries * This page contains information about all Lua registries, along with links to * the pages describing them. * * @ref lua_xml \n * This registry currently only contains one function (load). It is used to load * XML data from files. * * @ref lua_mode_manager \n * This small registry contains functions for dealing with modes. Modes are the * states in which Lua runs, containing functions triggered by certain states of * Apollo (like mouse movement, keyboard presses, etc). * * @ref lua_resource_manager \n * This small registry contains a few simple tools for manipulating files. * * @ref lua_graphics \n * This registry contains all drawing mechanisms for Lua, along with some * drawing manipulation functions. * * @ref lua_sound \n * This registry contains all music control mechanisms for Lua, along with a * function for playing sound effects. * * @ref lua_net_client \n * This registry contains functions related to playing on a multiplayer server. * * @ref lua_net_server \n * This registry contains functions related to hosting a multiplayer server. * * @ref lua_preferences \n * This registry currently only contains one function, used for retrieving * preferences. * * @ref lua_window \n * This registry controls aspects * preferences. */ void __LuaBind ( lua_State* L ) { lua_pushcfunction(L, import); lua_setglobal(L, "import"); lua_pushcfunction(L, VEC_new); lua_setglobal(L, "vec"); lua_cpcall(L, luaopen_component, NULL); luaL_newmetatable(L, "Apollo.vec2"); luaL_register(L, NULL, registryObjectVector); luaL_register(L, "input", registryInput); luaL_register(L, "xml", registryXML); luaL_register(L, "mode_manager", registryModeManager); luaL_register(L, "resource_manager", registryResourceManager); luaL_register(L, "graphics", registryGraphics); luaL_register(L, "sound", registrySound); luaL_register(L, "preferences", registryPreferences); luaL_register(L, "net_server", registryNetServer); luaL_register(L, "window", registryWindowManager); } Added bindings for graphics preloading. Signed-off-by: Alastair Lynn <4665d361aaf271b139147017031ea99df777ca5a@gmail.com> #include <string.h> #include "Apollo.h" #include "Scripting.h" #include "Utilities/ResourceManager.h" #include "Sound/Sound.h" #include "Graphics/Graphics.h" #include "Graphics/TextRenderer.h" #include "Preferences.h" #include "Input.h" #include "Modes/ModeManager.h" #include "TinyXML/tinyxml.h" #include "Net/Net.h" #include "Utilities/GameTime.h" extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } namespace { vec2 luaL_checkvec2(lua_State *L, int narg); void lua_pushvec2(lua_State *L, vec2 val); int VEC_new (lua_State* L) { float x = luaL_checknumber(L, 1); float y = luaL_checknumber(L, 2); vec2 v = vec2(x,y); lua_pushvec2(L, v); return 1; } int VEC_add (lua_State* L) { vec2 left = luaL_checkvec2(L, 1); vec2 right = luaL_checkvec2(L, 2); vec2 result = left + right; lua_pushvec2(L, result); return 1; } int VEC_sub (lua_State* L) { vec2 left = luaL_checkvec2(L, 1); vec2 right = luaL_checkvec2(L, 2); vec2 result = left - right; lua_pushvec2(L, result); return 1; } int VEC_mul (lua_State* L) { vec2 left = luaL_checkvec2(L, 1); if (lua_istable(L, 2)) { vec2 right = luaL_checkvec2(L, 2); float result = left * right; lua_pushnumber(L, result); } else { float right = luaL_checknumber(L, 2); vec2 result = left * right; lua_pushvec2(L, result); } return 1; } int VEC_div (lua_State* L) { vec2 left = luaL_checkvec2(L, 1); float right = luaL_checknumber(L, 2); vec2 result = left / right; lua_pushvec2(L, result); return 1; } int VEC_unm (lua_State* L) { vec2 val = -luaL_checkvec2(L, 1); lua_pushvec2(L, val); return 1; } int VEC_tostring (lua_State* L) { vec2 v = luaL_checkvec2(L, 1); char s[256]; sprintf(s, "%f, %f", v.X(), v.Y()); lua_pushstring(L, s); return 1; } luaL_Reg registryObjectVector[] = { "__add", VEC_add, "__sub", VEC_sub, "__mul", VEC_mul, "__div", VEC_div, "__unm", VEC_unm, "__tostring", VEC_tostring, NULL, NULL }; vec2 luaL_checkvec2(lua_State* L, int narg) { if (!lua_istable(L, narg)) { luaL_argerror(L, narg, "must pass a vector table (not a table)"); } float x, y; lua_getfield(L, narg, "x"); if (!lua_isnumber(L, -1)) { luaL_argerror(L, narg, "must pass a vector table (bad x value)"); } x = lua_tonumber(L, -1); lua_getfield(L, narg, "y"); if (!lua_isnumber(L, -1)) { luaL_argerror(L, narg, "must pass a vector table (bad y value)"); } y = lua_tonumber(L, -1); lua_pop(L, 2); return vec2(x, y); } std::string FloatToString ( float val ) { std::ostringstream o; if (!(o << val)) { printf("BAD CONVERSION?!?!?"); } return o.str(); } unsigned ToInt ( const std::string& value ) { return atoi(value.c_str()); } bool ToBool ( const std::string& value ) { return value == "true"; } vec2 luaL_optvec2(lua_State* L, int narg, vec2 defaultValue) { if (lua_isnoneornil(L, narg)) return defaultValue; return luaL_checkvec2(L, narg); } void lua_pushvec2(lua_State* L, vec2 val) { lua_createtable(L, 0, 2); lua_pushnumber(L, val.X()); lua_setfield(L, -2, "x"); lua_pushnumber(L, val.Y()); lua_setfield(L, -2, "y"); luaL_getmetatable(L, "Apollo.vec2"); lua_setmetatable(L, -2); } int Pref_Get ( lua_State* L ) { const char* arg = luaL_checkstring(L, 1); std::string push = Preferences::Get(arg, "nil"); // [TODO, ADAM] Make this not hardcoded... I think we have to recognize what type "push" is and format it accordingly // lua_pushstring(L, push); if (push == "true") // [HARDCODED] { lua_pushboolean(L, true); } else { lua_pushboolean(L, false); } return 1; } int Pref_Set ( lua_State* L ) { const char* arg = luaL_checkstring(L, 1); const char* set = luaL_checkstring(L, 2); Preferences::Set(arg, set); Preferences::Save(); return 0; } /** * @page lua_preferences The Lua Preferences Registry * This page contains information about the Lua preferences registry. * * This registry currently only contains one function, used for retrieving * preferences. In Lua, it is called called like so: "preferences.get(name)". * * @section pref_get get * Finds and returns a particular preference.\n * Parameters:\n * name - The name of the preference to be fetched.\n * Returns:\n * boolean - The status of the requested preference. (currently, this is hardcoded) * * @todo Make @ref xml_get un-hardcoded. */ luaL_Reg registryPreferences[] = { "get", Pref_Get, "set", Pref_Set, NULL, NULL }; int NetServer_Startup ( lua_State* L ) { unsigned port = luaL_checkinteger(L, 1); luaL_argcheck(L, port < 65536 && port > 0, 1, "Invalid port number"); const char* password = ""; if (lua_gettop(L) > 1) { password = luaL_checkstring(L, 2); } Net::Server::Startup(port, password); return 0; } int NetServer_Shutdown ( lua_State* L ) { Net::Server::Shutdown(); return 0; } int NetServer_Running ( lua_State* L ) { lua_pushboolean(L, Net::Server::IsRunning() ? 1 : 0); return 1; } int NetServer_ClientCount ( lua_State* L ) { lua_pushinteger(L, Net::Server::ClientCount()); return 1; } int NetServer_KillClient ( lua_State* L ) { unsigned clientID = luaL_checkinteger(L, 1); Net::Server::KillClient(clientID); return 0; } int NetServer_Connected ( lua_State* L ) { unsigned clientID = luaL_checkinteger(L, 1); bool isConnected = Net::Server::IsConnected(clientID); lua_pushboolean(L, isConnected ? 1 : 0); return 1; } int NetServer_SendMessage ( lua_State* L ) { int nargs = lua_gettop(L); unsigned clientID = luaL_checkinteger(L, 1); const char* message = luaL_checkstring(L, 2); size_t len = 0; const void* data = NULL; if (nargs > 2) { data = luaL_checklstring(L, 3, &len); } Net::Message messageObject ( message, data, len ); Net::Server::SendMessage ( clientID, messageObject ); return 0; } int NetServer_BroadcastMessage ( lua_State* L ) { int nargs = lua_gettop(L); const char* message = luaL_checkstring(L, 1); size_t len = 0; const void* data = NULL; if (nargs > 1) { data = luaL_checklstring(L, 2, &len); } Net::Message messageObject ( message, data, len ); Net::Server::BroadcastMessage ( messageObject ); return 0; } int NetServer_GetMessage ( lua_State* L ) { Net::Message* msg = Net::Server::GetMessage(); if (msg) { lua_pushlstring(L, msg->message.data(), msg->message.length()); if (msg->data) { lua_pushlstring(L, (const char*)msg->data, msg->dataLength); } else { lua_pushnil(L); } lua_pushinteger(L, msg->clientID); delete msg; } else { lua_pushnil(L); lua_pushnil(L); lua_pushnil(L); } return 3; } /** * @page lua_net_server The Lua Net Server Registry * This page contains information about the Lua net server registry. * * This registry contains functions related to running a multiplayer server. In * Lua, they are all called like so: "net_server.function_name()" (for example: * "startup" becomes "net_server.startup(port, password)"). * * Note: Somebody else will need to complete this registry, I don't know * anything about it right now. * * @section startup * * @section shutdown * * @section running * * @section client_count * * @section kill * * @section net_server_connected connected * * @section net_server_send send * * @section broadcast * * @section net_server_get get * * @todo Complete the @ref lua_net_server registry. * */ luaL_Reg registryNetServer[] = { "startup", NetServer_Startup, "shutdown", NetServer_Shutdown, "running", NetServer_Running, "client_count", NetServer_ClientCount, "kill", NetServer_KillClient, "connected", NetServer_Connected, "send", NetServer_SendMessage, "broadcast", NetServer_BroadcastMessage, "get", NetServer_GetMessage, NULL, NULL }; // XML code based on code from lua-users.org void XML_ParseNode (lua_State* L, TiXmlNode* xmlNode) { if (!xmlNode) return; // resize stack if neccessary luaL_checkstack(L, 5, "XML_ParseNode : recursion too deep"); TiXmlElement* xmlElement = xmlNode->ToElement(); if (xmlElement) { // element name lua_pushstring(L, "name"); lua_pushstring(L, xmlElement->Value()); lua_settable(L, -3); // parse attributes TiXmlAttribute* xmlAttribute = xmlElement->FirstAttribute(); if (xmlAttribute) { lua_pushstring(L, "attr"); lua_newtable(L); for (; xmlAttribute; xmlAttribute = xmlAttribute->Next()) { lua_pushstring(L, xmlAttribute->Name()); lua_pushstring(L, xmlAttribute->Value()); lua_settable(L, -3); } lua_settable(L, -3); } } // children TiXmlNode *child = xmlNode->FirstChild(); if (child) { int childCount = 0; for(; child; child = child->NextSibling()) { switch (child->Type()) { case TiXmlNode::DOCUMENT: break; case TiXmlNode::ELEMENT: // normal element, parse recursive lua_newtable(L); XML_ParseNode(L, child); lua_rawseti(L, -2, ++childCount); break; case TiXmlNode::COMMENT: break; case TiXmlNode::TEXT: // plaintext, push raw lua_pushstring(L, child->Value()); lua_rawseti(L, -2, ++childCount); break; case TiXmlNode::DECLARATION: break; case TiXmlNode::UNKNOWN: break; }; } lua_pushstring(L, "n"); lua_pushnumber(L, childCount); lua_settable(L, -3); } } static int XML_ParseFile (lua_State *L) { const char* fileName = luaL_checkstring(L, 1); SDL_RWops* ops = ResourceManager::OpenFile(fileName); size_t len; void* dataPointer = ResourceManager::ReadFull(&len, ops, 1); char* fullDataPointer = (char*)malloc(len + 1); fullDataPointer[len] = 0; memcpy(fullDataPointer, dataPointer, len); free(dataPointer); TiXmlDocument doc ( fileName ); doc.Parse(fullDataPointer); lua_newtable(L); XML_ParseNode(L, &doc); free((void*)fullDataPointer); return 1; } /** * @page lua_xml The Lua XML Registry * This page contains information about the Lua XML registry. * * This registry currently only contains one function. In Lua, it is called * called like so: "xml.load(file)". * * @section load * Loads and parses an XML file\n * Parameters:\n * name - The name of the mode that the game is currently in.\n * Returns:\n * A table with the contents of the file in it.\n */ luaL_Reg registryXML[] = { "load", XML_ParseFile, NULL, NULL }; int WIND_IsFullscreen ( lua_State* L ) { lua_pushboolean(L, ToBool(Preferences::Get("Screen/Fullscreen"))); return 1; } int WIND_SetFullscreen ( lua_State* L ) { Preferences::Set("Screen/Fullscreen", luaL_checkstring(L, 1) ); Graphics::Init(ToInt(Preferences::Get("Screen/Width")), ToInt(Preferences::Get("Screen/Height")), ToBool(Preferences::Get("Screen/Fullscreen"))); return 0; } int WIND_ToggleFullscreen ( lua_State* L ) { Preferences::Set("Screen/Fullscreen", Preferences::Get("Screen/Fullscreen") == "true" ? "false" : "true"); Graphics::Init(ToInt(Preferences::Get("Screen/Width")), ToInt(Preferences::Get("Screen/Height")), ToBool(Preferences::Get("Screen/Fullscreen"))); return 0; } int WIND_WindowSize ( lua_State* L ) { lua_pushnumber(L, ToInt(Preferences::Get("Screen/Width"))); lua_pushnumber(L, ToInt(Preferences::Get("Screen/Height"))); return 2; } int WIND_SetWindow ( lua_State* L ) { vec2 newSize = luaL_checkvec2(L, 1); std::string width = FloatToString(newSize.X()); std::string height = FloatToString(newSize.Y()); Preferences::Set("Screen/Width", width); Preferences::Set("Screen/Height", height); Graphics::Init(ToInt(Preferences::Get("Screen/Width")), ToInt(Preferences::Get("Screen/Height")), ToBool(Preferences::Get("Screen/Fullscreen"))); return 0; } int WIND_MouseToggle ( lua_State* L ) { if (SDL_ShowCursor(SDL_QUERY) == SDL_ENABLE) SDL_ShowCursor(SDL_DISABLE); else SDL_ShowCursor(SDL_ENABLE); return 0; } /** * @page lua_window The Lua Window Registry * This page contains information about the Lua Window registry. * * This registry contains miscellaneous functions for modifying the SDL window's * properties. * * @section is_fullscreen * Checks the status of the SDL window with regards to fullscreen or windowed * mode.\n * Returns:\n * A boolean value of true or false - true for fullscreen, false for windowed. * * @section set_fullscreen * Sets the fullscreen status of the SDL window based upon the argument given.\n * Parameters:\n * fullscreen - a string equivalent of the boolean value of whether or not the * window should be set to fullscreen.\n * Returns:\n * Initially this function will return nothing, but there are plans to allow for * it to return the SDL status given (in case there's a problem with setting it * to fullscreen). * * @section toggle_fullscreen * Changes the fullscreen status of the SDL window. No parameters or returns.\n * * @section size * Gives the size of the screen in pixels.\n * Returns:\n * size - a vectorized size table containing the dimensions of the window in * pixels. (currently returns two values, I hope to make it a table soon) * * @todo Make @ref size return a vectorized table instead of two values * * @section set * Sets the size of the screen in pixels.\n * Parameters:\n * A table of a coordinate pair, representing the size of the screen (in pixels) * .\n */ luaL_Reg registryWindowManager[] = { "is_fullscreen", WIND_IsFullscreen, "set_fullscreen", WIND_SetFullscreen, "toggle_fullscreen", WIND_ToggleFullscreen, "size", WIND_WindowSize, "set", WIND_SetWindow, "mouse_toggle", WIND_MouseToggle, NULL, NULL }; int MM_Switch ( lua_State* L ) { int nargs = lua_gettop(L); const char* newmode = luaL_checkstring(L, 1); if (nargs > 1) { SwitchMode(std::string(newmode), luaL_ref(L, 2)); } else { SwitchMode(std::string(newmode)); } return 0; } int MM_Time ( lua_State* L ) { lua_pushnumber(L, GameTime()); return 1; } int MM_Query ( lua_State* L ) { lua_pushstring(L, QueryMode()); return 1; } int MM_Release ( lua_State* L ) { #ifdef NDEBUG lua_pushboolean(L, true); return 1; #else lua_pushboolean(L, false); return 1; #endif } /** * @page lua_mode_manager The Lua Mode Manager Registry * This page contains information about the Lua mode manager registry. * * This small registry contains functions for dealing with modes. Modes are the * states in which Lua runs, containing functions triggered by certain states of * Apollo (like mouse movement, keyboard presses, etc). In Lua, they are all * called like so: "mode_manager.function_name()" (for example: "switch" becomes * "mode_manager.switch(mode)"). * * @section switch * Switches the game mode. If the mode cannot be switched to the given name, an * error occurs.\n * Parameters:\n * mode - the name of the mode you want to switch to (without the suffix * ".lua"). For example, to switch to "MainMenu.lua", enter "MainMenu" for the * parameter. * * @section time * Gives the game's time, in seconds, since the game's start. This function has * no parameters.\n * Returns:\n * number - The amount of seconds (accurate to miliseconds) since the game's * start. * * @section query * Returns the game's current mode. This function has no parameters.\n * Returns:\n * string - The name of the mode that the game is currently in. * * @section is_release * Returns the game's current build mode. This function has no parameters.\n * Returns:\n * bool - True if the game's current build is a release build, false if not. */ luaL_Reg registryModeManager[] = { "switch", MM_Switch, "time", MM_Time, "query", MM_Query, "is_release", MM_Release, NULL, NULL }; int RM_Load ( lua_State* L ) { const char* file = luaL_checkstring(L, 1); SDL_RWops* ptr = ResourceManager::OpenFile(file); if (ptr) { size_t len; void* data = ResourceManager::ReadFull(&len, ptr, 1); lua_pushlstring(L, (const char*)data, len); free(data); return 1; } else { lua_pushliteral(L, "file not found"); return lua_error(L); } } int RM_FileExists ( lua_State* L ) { const char* file = luaL_checkstring(L, 1); bool exists = ResourceManager::FileExists(file); lua_pushboolean(L, exists ? 1 : 0); return 1; } int RM_Write ( lua_State* L ) { const char* file = luaL_checkstring(L, 1); size_t len; const char* data = luaL_checklstring(L, 2, &len); ResourceManager::WriteFile(file, (const void*)data, len); return 0; } /** * @page lua_resource_manager The Lua Resource Manager Registry * This page contains information about the Lua resource manager registry. * * This small registry contains a few simple tools for manipulating files. In * Lua, they are all called like so: "resource_manager.function_name()" (for * example: "file_exists" becomes "resource_manager.file_exists(file)"). * * @section file_exists * Ensures that the given file exists, then returns a boolean of whether it does * or not.\n * Parameters:\n * file - The name of the file\n * Returns:\n * Boolean - true if file exists, false if it does not\n * * @section load * Loads a given file. Will return error statement along with error if the file * does not exist or cannot be opened.\n * Parameters:\n * file - The name of the file to be loaded\n * Returns:\n * data - If the load is successful, data will be returned from the file * literal - If the load is unsuccessful, a string will be returned ("file not * found") * * @section write * Writes to a given file. No error checking implemented. * Parameters:\n * file - The name of the file\n * data - The data to be written to the file\n */ luaL_Reg registryResourceManager[] = { "file_exists", RM_FileExists, "load", RM_Load, "write", RM_Write, NULL, NULL }; int GFX_BeginFrame ( lua_State* L ) { Graphics::BeginFrame(); return 0; } int GFX_EndFrame ( lua_State* L ) { Graphics::EndFrame(); return 0; } int GFX_SetCamera ( lua_State* L ) { float ll_x, ll_y, tr_x, tr_y, rot = 0.0f; int nargs = lua_gettop(L); ll_x = luaL_checknumber(L, 1); ll_y = luaL_checknumber(L, 2); tr_x = luaL_checknumber(L, 3); tr_y = luaL_checknumber(L, 4); if (nargs > 4) rot = luaL_checknumber(L, 5); Graphics::SetCamera(vec2(ll_x, ll_y), vec2(tr_x, tr_y), rot); return 0; } static colour LoadColour ( lua_State* L, int index ) { float r = 1.0f, g = 1.0f, b = 1.0f, a = 1.0f; lua_getfield(L, index, "r"); r = luaL_checknumber(L, -1); lua_getfield(L, index, "g"); g = luaL_checknumber(L, -1); lua_getfield(L, index, "b"); b = luaL_checknumber(L, -1); lua_getfield(L, index, "a"); a = luaL_checknumber(L, -1); return colour(r, g, b, a); } int GFX_DrawText ( lua_State* L ) { int nargs = lua_gettop(L); const char* text = luaL_checkstring(L, 1); const char* font = luaL_checkstring(L, 2); const char* justify = luaL_checkstring(L, 3); vec2 location = luaL_checkvec2(L, 4); float height = luaL_checknumber(L, 5); float rotation = 0.0f; if (nargs >= 7) { rotation = luaL_checknumber(L, 7); } if (nargs >= 6) { luaL_argcheck(L, lua_istable(L, 6), 6, "bad colour"); Graphics::DrawTextSDL(text, font, justify, location, height, LoadColour(L, 6), rotation); } else { Graphics::DrawTextSDL(text, font, justify, location, height, colour(1.0f, 1.0f, 1.0f, 1.0f), rotation); } return 0; } int GFX_TextLength (lua_State* L ) { const char* text = luaL_checkstring(L, 1); const char* font = luaL_checkstring(L, 2); float height = luaL_checknumber(L, 3); vec2 dims = Graphics::TextRenderer::TextDimensions(font, text, height); // printf("[%f, %f]\n", dims.X(), dims.Y()); dims = dims * (height / dims.Y()); // printf("[%f, %f]\n", dims.X(), dims.Y()); lua_pushnumber(L, dims.X()); return 1; } int GFX_DrawLine ( lua_State* L ) { int nargs = lua_gettop(L); float width; vec2 point1 = luaL_checkvec2(L, 1); vec2 point2 = luaL_checkvec2(L, 2); width = luaL_checknumber(L, 3); if (nargs > 3) { Graphics::DrawLine(point1, point2, width, LoadColour(L, 4)); } else { Graphics::DrawLine(point1, point2, width, colour(0.0f, 1.0f, 0.0f, 1.0f)); } return 0; } int GFX_DrawLightning ( lua_State* L ) { int nargs = lua_gettop(L); float width, chaos; bool tailed; vec2 point1 = luaL_checkvec2(L, 1); vec2 point2 = luaL_checkvec2(L, 2); width = luaL_checknumber(L, 3); chaos = luaL_checknumber(L, 4); tailed = lua_tonumber(L, 5); if (nargs > 5) { Graphics::DrawLightning(point1, point2, width, chaos, LoadColour(L, 6), tailed); } else { Graphics::DrawLightning(point1, point2, width, chaos, colour(0.93f, 0.88f, 1.0f, 1.0f), tailed); } return 0; } int GFX_DrawBox ( lua_State* L ) { int nargs = lua_gettop(L); float top, left, bottom, right, width; top = luaL_checknumber(L, 1); left = luaL_checknumber(L, 2); bottom = luaL_checknumber(L, 3); right = luaL_checknumber(L, 4); width = luaL_checknumber(L, 5); colour col = colour(0.0f, 1.0f, 0.0f, 1.0f); if (nargs > 5) { col = LoadColour(L, 6); } Graphics::DrawBox(top, left, bottom, right, width, col); return 0; } int GFX_DrawPoint ( lua_State* L ) { int nargs = lua_gettop(L); float size = 1; vec2 location = luaL_checkvec2(L, 1); colour col = colour(0.0f, 1.0f, 0.0f, 1.0f); if (nargs > 1) { size = luaL_checknumber(L, 2); } if (nargs > 2) { col = LoadColour(L, 3); } Graphics::DrawPoint(location, size, col); return 0; } int GFX_DrawRadarTriangle ( lua_State* L ) { int nargs = lua_gettop(L); vec2 coordinates = luaL_checkvec2(L, 1); float varsize = luaL_checknumber(L, 2); if (nargs > 2) { Graphics::DrawTriangle(vec2(coordinates.X(), coordinates.Y() + varsize), vec2(coordinates.X() - varsize, coordinates.Y() - varsize), vec2(coordinates.X() + varsize, coordinates.Y() - varsize), LoadColour(L, 3)); } else { Graphics::DrawTriangle(vec2(coordinates.X(), coordinates.Y() + varsize), vec2(coordinates.X() - varsize, coordinates.Y() - varsize), vec2(coordinates.X() + varsize, coordinates.Y() - varsize), colour(0.0f, 1.0f, 0.0f, 1.0f)); } return 0; } int GFX_DrawRadarPlus ( lua_State* L ) { int nargs = lua_gettop(L); vec2 coordinates = luaL_checkvec2(L, 1); float varsize = luaL_checknumber(L, 2); if (nargs > 2) { Graphics::DrawBox(coordinates.Y() + varsize, coordinates.X() - 0.3 * varsize, coordinates.Y() - varsize, coordinates.X() + 0.3 * varsize, 0, LoadColour(L, 3)); Graphics::DrawBox(coordinates.Y() + 0.3 * varsize, coordinates.X() - varsize, coordinates.Y() - 0.3 * varsize, coordinates.X() + varsize, 0, LoadColour(L, 3)); } else { Graphics::DrawBox(coordinates.Y() + varsize, coordinates.X() - 0.3 * varsize, coordinates.Y() - varsize, coordinates.X() + 0.3 * varsize, 0, colour(0, 1, 0, 1)); Graphics::DrawBox(coordinates.Y() + 0.3 * varsize, coordinates.X() - varsize, coordinates.Y() - 0.3 * varsize, coordinates.X() + varsize, 0, colour(0, 1, 0, 1)); } return 0; } int GFX_DrawRadarBox ( lua_State* L ) { int nargs = lua_gettop(L); vec2 coordinates = luaL_checkvec2(L, 1); float varsize = luaL_checknumber(L, 2); if (nargs > 2) { Graphics::DrawBox(coordinates.Y() + varsize, coordinates.X() - varsize, coordinates.Y() - varsize, coordinates.X() + varsize, 0, LoadColour(L, 3)); } else { Graphics::DrawBox(coordinates.Y() + varsize, coordinates.X() - varsize, coordinates.Y() - varsize, coordinates.X() + varsize, 0, colour(0, 1, 0, 1)); } return 0; } int GFX_DrawRadarDiamond ( lua_State* L ) { int nargs = lua_gettop(L); vec2 coordinates = luaL_checkvec2(L, 1); float varsize = luaL_checknumber(L, 2); if (nargs > 2) { Graphics::DrawDiamond(coordinates.Y() + varsize, coordinates.X() - varsize, coordinates.Y() - varsize, coordinates.X() + varsize, LoadColour(L, 3)); } else { Graphics::DrawDiamond(coordinates.Y() + varsize, coordinates.X() - varsize, coordinates.Y() - varsize, coordinates.X() + varsize, colour(0, 1, 0, 1)); } return 0; } int GFX_DrawObject3DAmbient ( lua_State* L ) { std::string object = luaL_checkstring(L, 1); vec2 location = luaL_checkvec2(L, 2); float scale = luaL_checknumber(L, 3); float angle = luaL_checknumber(L, 4); float bank = luaL_optnumber(L, 5, 0.0); Graphics::DrawObject3DAmbient(object, location, scale, angle, bank); return 0; } int GFX_DrawParticles ( lua_State* L ) { Graphics::DrawParticles(); return 0; } int GFX_ClearParticles ( lua_State* L ) { Graphics::ClearParticles(); } int GFX_AddParticles ( lua_State* L ) { const char* name = luaL_checkstring(L, 1); unsigned long pcount = luaL_checkinteger(L, 2); vec2 location = luaL_checkvec2(L, 3); vec2 velocity = luaL_checkvec2(L, 4); vec2 velocityVar = luaL_checkvec2(L, 5); vec2 acc = luaL_checkvec2(L, 6); float size = luaL_checknumber(L, 7); float lifetime = luaL_checknumber(L, 8); Graphics::AddParticles(name, pcount, location, velocity, velocityVar, acc, size, lifetime); return 0; } int GFX_DrawCircle ( lua_State* L ) { int nargs = lua_gettop(L); float radius, width; vec2 location = luaL_checkvec2(L, 1); radius = luaL_checknumber(L, 2); width = luaL_checknumber(L, 3); if (nargs > 3) { Graphics::DrawCircle(location, radius, width, LoadColour(L, 4)); } else { Graphics::DrawCircle(location, radius, width, colour(0.0f, 1.0f, 0.0f, 1.0f)); } return 0; } int GFX_DrawImage ( lua_State* L ) { const char* imgName; imgName = luaL_checkstring(L, 1); vec2 location = luaL_checkvec2(L, 2); vec2 size = luaL_checkvec2(L, 3); Graphics::DrawImage(imgName, location, size); return 0; } int GFX_SpriteDimensions ( lua_State* L ) { const char* spritesheet; spritesheet = luaL_checkstring(L, 1); vec2 dims = Graphics::SpriteDimensions(spritesheet); lua_pushvec2(L, dims); return 1; } int GFX_DrawSprite ( lua_State* L ) { const char* spritesheet; int nargs = lua_gettop(L); float rot = 0.0f; colour col; spritesheet = luaL_checkstring(L, 1); vec2 location = luaL_checkvec2(L, 2); vec2 size = luaL_checkvec2(L, 3); if (nargs > 3) { rot = luaL_checknumber(L, 4); } if (nargs > 4) { Graphics::DrawSprite(spritesheet, 0, 0, location, size, rot, LoadColour(L, 5)); } else { Graphics::DrawSprite(spritesheet, 0, 0, location, size, rot, colour(1.0f, 1.0f, 1.0f, 1.0f)); } return 0; } int GFX_DrawStarfield ( lua_State* L ) { if (lua_gettop(L) > 0) { float depth = luaL_checknumber(L, 1); Graphics::DrawStarfield(depth); } else { Graphics::DrawStarfield(0.0f); } return 0; } int GFX_IsCulled ( lua_State* L ) { vec2 location = luaL_checkvec2(L, 1); float radius = luaL_optnumber(L, 2, 0.0); bool isCulled = Graphics::IsCulled(location, radius); lua_pushboolean(L, isCulled ? 1 : 0); return 1; } int GFX_DrawSpriteFromSheet ( lua_State* L ) { const char* spritesheet; int nargs = lua_gettop(L); float rot = 0.0f; spritesheet = luaL_checkstring(L, 1); vec2 sheet = luaL_checkvec2(L, 2); vec2 location = luaL_checkvec2(L, 3); vec2 size = luaL_checkvec2(L, 4); if (nargs > 4) { rot = luaL_checknumber(L, 5); } if (nargs > 5) { Graphics::DrawSprite(spritesheet, sheet.X(), sheet.Y(), location, size, rot, LoadColour(L, 6)); } else { Graphics::DrawSprite(spritesheet, sheet.X(), sheet.Y(), location, size, rot, colour(1.0f, 1.0f, 1.0f, 1.0f)); } return 0; } int GFX_DrawSpriteFrame ( lua_State* L ) { const char* spritesheet; int nargs = lua_gettop(L); float rot = 0.0f; spritesheet = luaL_checkstring(L, 1); vec2 location = luaL_checkvec2(L, 2); vec2 size = luaL_checkvec2(L, 3); int index = luaL_checkinteger(L, 4); if (nargs > 4) { rot = luaL_checknumber(L, 5); } if (nargs > 5) { Graphics::DrawSpriteFrame(spritesheet, location, size, index, rot, LoadColour(L, 6)); } else { Graphics::DrawSpriteFrame(spritesheet, location, size, index, rot, colour(1.0f, 1.0f, 1.0f, 1.0f)); } return 0; } int GFX_BeginWarp ( lua_State* L ) { float magnitude = luaL_checknumber(L, 1); float angle = luaL_checknumber(L, 2); float scale = luaL_checknumber(L, 3); Graphics::BeginWarp(magnitude, angle, scale); return 0; } int GFX_EndWarp ( lua_State* L ) { Graphics::EndWarp(); int argCount = lua_gettop(L); if (argCount == 4) { float magnitude = luaL_checknumber(L, 1); float angle = luaL_checknumber(L, 2); float scale = luaL_checknumber(L, 3); vec2 position = luaL_checkvec2(L, 4); Graphics::DrawCircle(position, 45 * scale, 5, colour(1,0,0,1)); Graphics::DrawCircle(position, 45 * scale * magnitude, 5, colour(0,1,0,1)); } return 0; } int GFX_PreloadSpriteSheet ( lua_State* L ) { const char* sheet = luaL_checkstring(L, 1); Graphics::PreloadSpriteSheet(sheet); return 0; } int GFX_PreloadImage ( lua_State* L ) { const char* image = luaL_checkstring(L, 1); Graphics::PreloadImage(image); return 0; } int GFX_PreloadFont ( lua_State* L ) { const char* font = luaL_checkstring(L, 1); Graphics::PreloadFont(font); return 0; } /** * @page lua_graphics The Lua Graphics Registry * This page contains information about the Lua graphics registry. * * This registry contains all drawing mechanisms for Lua, along with some * drawing manipulation functions. In Lua, they are all called like so: * "graphics.function_name()" (for example: "begin_frame" becomes * "graphics.begin_frame()"). * * @section frame_and_camera Frame and Camera * * @subsection begin_frame * Must be called before any graphics routines are called. It has no parameters. * * @subsection end_frame * Must be called after any graphics routines are called. It has no parameters. * * @subsection set_camera * Sets the bounds of the camera. It requires arguments for the left, bottom, * right, and top of the camera, respectively.\n * Parameters:\n * left - The left, or lower-x bound, of the screen.\n * bottom - The bottom, or lower-y bound, of the screen.\n * right - The right, or upper-x bound, of the screen.\n * top - The top, or upper-y bound, of the screen.\n * * @section sprites Sprites * * @subsection draw_image * Draws an "image", which is functionally different from a sprite. In general, * a sprite has rotational capabilities and / or multiple frames, like most * ships, where an image does not, like panels on the sides of the screen.\n * Parameters:\n * imgname - The name of the image to be drawn\n * loc_x - The x location of where the center of the image should be\n * loc_y - The y location of where the center of the image should be\n * size_x - The x size, in pixels, of the image\n * size_y - The y size, in pixels, of the image - note that size_x and size_y * should be in the same ratio of x:y as the original image, or stretching may * occur.\n * rot - The rotation of the image, in radians. Optional parameter.\n * colour - The colour to be applied to the image, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_sprite * Draws a "sprite", which is functionally different from an image. In general, * a sprite has rotational capabilities and / or multiple frames, like a ship, * where an image does not, like panels on the sides of the screen. * Parameters:\n * spritesheet - The name of the file containing the sprites\n * loc_x - The x location of where the center of the sprite should be\n * loc_y - The y location of where the center of the sprite should be\n * size_x - The x size, in pixels, of the sprite\n * size_y - The y size, in pixels, of the sprite - note that size_x and size_y * should be in the same ratio of x:y as the original image, or stretching may * occur.\n * rot - The rotation of the sprite, in radians. Determines which sprite is * drawn\n * colour - The colour to be applied to the sprite, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_sheet_sprite * Draws a given sprite from within a sprite sheet.\n * Parameters:\n * spritesheet - The name of the sprite sheet to be drawn\n * sheet_x - ?\n * sheet_y - ?\n * loc_x - The x location of where the center of the sprite should be\n * loc_y - The y location of where the center of the sprite should be\n * size_x - The x size, in pixels, of the sprite\n * size_y - The y size, in pixels, of the sprite - note that size_x and size_y * should be in the same ratio of x:y as the original image, or stretching may * occur.\n * rot - The rotation of the sprite, in radians. Determines which sprite is * drawn\n * colour - The colour to be applied to the sprite, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * @todo define sheet_x and sheet_y for @ref draw_sheet_sprite * @todo add in table reading for colours to @ref draw_sheet_sprite * * @subsection sprite_dimensions * Returns the dimensions for a given sprite.\n * Parameters:\n * spritesheet - The sprite sheet to check the dimensions of.\n * Returns:\n * x - The x size of one sprite on the sheet\n * y - The y size of one sprite on the sheet * * @subsection draw_starfield * Draws a starfield at the given depth. Draw multiple starfields at varying * depths to give them a parallax feel. * Parameters:\n * depth - How deep the starfield should appear. Optional parameter (default is * 0). * * @section drawing_text Drawing Text * * @subsection draw_text * Given a position, size, font, and some text, (and optionally a rotation and * some colour) this function will draw text to the screen with those * specifications. If not given rotation or colour, this function will default * to zero degrees rotation and white text.\n * Parameters:\n * text - The text to be displayed on the screen\n * font - The font for the text to be drawn in\n * justify - One of "left", "right", or "center", the justification of the text. * If misspelled or missing, defaults to "center".\n * loc_x - The x coordinate of the text. Justification revolves around the * position of this component.\n * loc_y - The y coordinate of the text.\n * height - The size of the font to be displayed.\n * rotation - Rotation clockwise from the viewer's perspective, in radians.\n * colour - The colour to be applied to the text, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection text_length * Given a size, font, and some text, this function will output how long this * text will be on the screen.\n * Parameters:\n * text - The text to be sized up\n * font - The font being used for the text\n * height - the size of the font * * @section drawing_basic_objects Drawing Basic Objects * * @subsection draw_line * Draws a basic line.\n * Parameters:\n * x1 - The x coordinate of the starting point.\n * y1 - The y coordinate of the starting point.\n * x2 - The x coordinate of the ending point.\n * y2 - The y coordinate of the ending point.\n * width - The thickness of the line in pixels.\n * colour - The colour to be applied to the line, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_point * * @subsection draw_box * Draws a basic box.\n * Parameters:\n * top - The y coordinate of the top of the box.\n * left - The x coordinate of the left of the box.\n * bottom - The y coordinate of the bottom of the box.\n * right - The x coordinate of the right of the box.\n * width - The thickness of the line surrounding the boxin pixels. Use 0 for no * line.\n * colour - The colour to be applied to the box, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_circle * Draws a "circle", which is really just a series of lines approximating a * circle.\n * x - The x coordinate of the center of the circle.\n * y - The y coordinate of the center of the circle.\n * radius - The radius of the circle.\n * width - The width of the lines comprising the circle.\n * colour - The colour to be applied to the circle, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @section drawing_radar_objects Drawing 'Radar' Objects * * @subsection draw_rtri * Draws a triangle - generally used as a placeholder for objects when zoomed * out beyond 1:8 camera ratios. (short for "radar triangle")\n * x - The x coordinate of the center of the triangle.\n * y - The y coordinate of the center of the triangle.\n * varsize - The size of the triangle, according to the object's data.\n * colour - The colour to be applied to the triangle, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_rplus * Draws a plus sign - generally used as a placeholder for objects when zoomed * out beyond 1:8 camera ratios (short for "radar plus").\n * x - The x coordinate of the center of the plus.\n * y - The y coordinate of the center of the plus.\n * varsize - The size of the plus, according to the object's data.\n * colour - The colour to be applied to the plus, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_rbox * Draws a square - generally used as a placeholder for objects when zoomed out * beyond 1:8 camera ratios (short for "radar box").\n * x - The x coordinate of the center of the box.\n * y - The y coordinate of the center of the box.\n * varsize - The size of the box, according to the object's data.\n * colour - The colour to be applied to the box, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection draw_rdia * Draws a diamond - generally used as a placeholder for objects when zoomed out * beyond 1:8 camera ratios (short for "radar diamond").\n * x - The x coordinate of the center of the diamond.\n * y - The y coordinate of the center of the diamond.\n * varsize - The size of the diamond, according to the object's data.\n * colour - The colour to be applied to the diamond, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * * @subsection is_culled * Checks to see if a particular circle is entirely outside of the vision of the * camera.\n * Parameters:\n * x - The x coordinate of the center of the circle.\n * y - The y coordinate of the center of the circle.\n * radius - The radius of the circle.\n * Returns:\n * isCulled - If the circle is entirely off the screen, true. Otherwise false. * * @section Special Effects * This section contains information about special effects like particles and * lightning. * * @subsection draw_lightning * Draws lightning effects needed for certain weapons.\n * x1 - The x coordinate of the starting point.\n * y1 - The y coordinate of the starting point.\n * x2 - The x coordinate of the ending point.\n * y2 - The y coordinate of the ending point.\n * width - The thickness of the lightning in pixels.\n * chaos - How jagged the lightning appears. 0 gives perfectly straight * lightning.\n * tailed - If tailed is true, the lightning tapers down to the endpoint. If * tailed is false, the lightning does not taper down to the endpoint but * instead ends somewhere around the endpoint.\n * colour - The colour to be applied to the lightning, in the form of a table:\n * t = { r = red_val, b = blue_val, g = green_val, a = alpha_val }\n * where the colour values are between 0.0 and 1.0. (optional) * @todo figure out "chaos" and "tailed" properties of @ref draw_lightning * * @subsection add_particles * * @subsection draw_particles * * @subsection clear_particles * * @subsection begin_warp * * @subsection end_warp * * @subsection draw_3d_ambient * * @todo Document @ref add_particles, @ref draw_particles, @ref clear_particles, @ref begin_warp, @ref end_warp, and @ref draw_point * @todo Fix documentation @ref draw_image and @ref draw_sprite to better define sprites/images. */ luaL_Reg registryGraphics[] = { "begin_frame", GFX_BeginFrame, "end_frame", GFX_EndFrame, "set_camera", GFX_SetCamera, "draw_image", GFX_DrawImage, "draw_sprite", GFX_DrawSprite, "draw_sheet_sprite", GFX_DrawSpriteFromSheet, "draw_sprite_frame", GFX_DrawSpriteFrame, "sprite_dimensions", GFX_SpriteDimensions, "draw_starfield", GFX_DrawStarfield, "draw_text", GFX_DrawText, "text_length", GFX_TextLength, "draw_line", GFX_DrawLine, "draw_box", GFX_DrawBox, "draw_point", GFX_DrawPoint, "draw_circle", GFX_DrawCircle, "draw_rtri", GFX_DrawRadarTriangle, "draw_rplus", GFX_DrawRadarPlus, "draw_rbox", GFX_DrawRadarBox, "draw_rdia", GFX_DrawRadarDiamond, "is_culled", GFX_IsCulled, "draw_lightning", GFX_DrawLightning, "add_particles", GFX_AddParticles, "draw_particles", GFX_DrawParticles, "clear_particles", GFX_ClearParticles, "begin_warp", GFX_BeginWarp, "end_warp", GFX_EndWarp, "draw_3d_ambient", GFX_DrawObject3DAmbient, NULL, NULL }; int Sound_Play ( lua_State* L ) { const char* sound; float pan = 0.0f; float volume = 1.0f; int nargs = lua_gettop(L); sound = luaL_checkstring(L, 1); if (nargs > 1) volume = luaL_checknumber(L, 2); Sound::PlaySound (sound, volume); return 0; } int Sound_PlayPositional ( lua_State* L ) { const char* sound = luaL_checkstring(L, 1); vec2 pos = luaL_checkvec2(L, 2); vec2 vel = luaL_checkvec2(L, 3); float volume = luaL_optnumber(L, 4, 1.0); Sound::PlaySoundPositional(sound, pos, vel, volume); return 0; } int Sound_Listener ( lua_State* L ) { vec2 pos = luaL_checkvec2(L, 1); vec2 vel = luaL_checkvec2(L, 2); Sound::SetListener(pos, vel); return 0; } int Sound_Preload ( lua_State* L ) { const char* sound = luaL_checkstring(L, 1); Sound::Preload(sound); return 0; } int Sound_PlayMusic ( lua_State* L ) { const char* mus = luaL_checkstring(L, 1); Sound::PlayMusic(mus); return 0; } int Sound_StopMusic ( lua_State* L ) { Sound::StopMusic(); return 0; } int Sound_CurrentMusic ( lua_State* L ) { std::string name = Sound::MusicName(); lua_pushlstring(L, name.data(), name.length()); return 1; } /** * @page lua_sound The Lua Sound Registry * This page contains information about the Lua sound registry. * * This registry contains all music control mechanisms for Lua, along with a * function for playing sound effects. In Lua, they are all called like so: * "sound.function_name()" (for example: "play" becomes "sound.play(file)"). * * @section sounds Sounds * * @subsection play * Plays the specified sound effect.\n * Parameters:\n * sound - The name of the sound file to be played. * * @subsection preload * Preloads the specified sound effect for quicker access in-game.\n * Parameters:\n * sound - The name of the sound file to be preloaded. * * @section music Music * * @subsection play_music * Plays the given song. Songs can be stopped on command, and their names can be * queried.\n * Parameters:\n * song - the name of the song to be played. * * @subsection stop_music * Stops the current song. This function has no parameters. * * @subsection current_music * Queries the name of the song currently playing. This function has no * parameters.\n * Return:\n * song - the name of the currently playing song. */ luaL_Reg registrySound[] = { "play", Sound_Play, "play_positional", Sound_PlayPositional, "listener", Sound_Listener, "preload", Sound_Preload, "play_music", Sound_PlayMusic, "stop_music", Sound_StopMusic, "current_music", Sound_CurrentMusic, NULL, NULL }; typedef struct Component { LuaScript* script; }; int CPT_Create ( lua_State* L ) { const char* name = luaL_checkstring(L, 1); Component* cpt = (Component*)lua_newuserdata(L, sizeof(Component)); cpt->script = new LuaScript ( std::string("Components/") + name ); cpt->script->InvokeSubroutine("component_init"); luaL_getmetatable(L, "Apollo.Component"); lua_setmetatable(L, -2); return 1; } int CPT_Cleanup ( lua_State* L ) { Component* cpt = (Component*)luaL_checkudata(L, 1, "Apollo.Component"); if (cpt->script) { cpt->script->InvokeSubroutine("component_quit"); delete cpt->script; cpt->script = NULL; } return 0; } int CPT_Invoke ( lua_State* L ) { Component* cpt = (Component*)luaL_checkudata(L, 1, "Apollo.Component"); LuaScript* script = cpt->script; luaL_argcheck(L, script, 1, "Component already freed"); const char* routine = luaL_checkstring(L, 2); lua_State* componentState = script->RawState(); int nargs = lua_gettop(L); int oldBase = lua_gettop(componentState); lua_getglobal(componentState, routine); if (!lua_isfunction(componentState, -1)) { char errorBuffer[512]; sprintf(errorBuffer, "Component has no routine named '%s'", routine); lua_pushstring(L, errorBuffer); return lua_error(L); } if (nargs > 2) { lua_xmove(L, componentState, nargs - 2); } int rc = lua_pcall(componentState, nargs - 2, LUA_MULTRET, 0); if (rc != 0) { lua_xmove(componentState, L, 1); return lua_error(L); } int newBase = lua_gettop(componentState); int nresults = newBase - oldBase; lua_xmove(componentState, L, nresults); lua_settop(componentState, oldBase); return nresults; } luaL_Reg registryComponent[] = { "create", CPT_Create, "invoke", CPT_Invoke, NULL, NULL }; luaL_Reg registryObjectComponent[] = { "invoke", CPT_Invoke, "__gc", CPT_Cleanup, NULL, NULL }; int luaopen_component ( lua_State* L ) { luaL_newmetatable(L, "Apollo.Component"); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_register(L, NULL, registryObjectComponent); luaL_register(L, "component", registryComponent); return 1; } int IN_StillTime ( lua_State* L ) { float stillTime = Input::MouseStillTime(); lua_pushnumber(L, stillTime); return 1; } int IN_Position ( lua_State* L ) { vec2 mouse = Input::MousePosition(); lua_pushvec2(L, mouse); return 1; } luaL_Reg registryInput[] = { "mouse_still_time", IN_StillTime, "mouse_position", IN_Position, NULL, NULL }; int import ( lua_State* L ) { const char* modulename = luaL_checkstring(L, 1); LuaScript::RawImport(L, modulename); return 0; } } /** * @page all_lua_bindings All LuaBind Registries * This page contains information about all Lua registries, along with links to * the pages describing them. * * @ref lua_xml \n * This registry currently only contains one function (load). It is used to load * XML data from files. * * @ref lua_mode_manager \n * This small registry contains functions for dealing with modes. Modes are the * states in which Lua runs, containing functions triggered by certain states of * Apollo (like mouse movement, keyboard presses, etc). * * @ref lua_resource_manager \n * This small registry contains a few simple tools for manipulating files. * * @ref lua_graphics \n * This registry contains all drawing mechanisms for Lua, along with some * drawing manipulation functions. * * @ref lua_sound \n * This registry contains all music control mechanisms for Lua, along with a * function for playing sound effects. * * @ref lua_net_client \n * This registry contains functions related to playing on a multiplayer server. * * @ref lua_net_server \n * This registry contains functions related to hosting a multiplayer server. * * @ref lua_preferences \n * This registry currently only contains one function, used for retrieving * preferences. * * @ref lua_window \n * This registry controls aspects * preferences. */ void __LuaBind ( lua_State* L ) { lua_pushcfunction(L, import); lua_setglobal(L, "import"); lua_pushcfunction(L, VEC_new); lua_setglobal(L, "vec"); lua_cpcall(L, luaopen_component, NULL); luaL_newmetatable(L, "Apollo.vec2"); luaL_register(L, NULL, registryObjectVector); luaL_register(L, "input", registryInput); luaL_register(L, "xml", registryXML); luaL_register(L, "mode_manager", registryModeManager); luaL_register(L, "resource_manager", registryResourceManager); luaL_register(L, "graphics", registryGraphics); luaL_register(L, "sound", registrySound); luaL_register(L, "preferences", registryPreferences); luaL_register(L, "net_server", registryNetServer); luaL_register(L, "window", registryWindowManager); }
/* =========================================================================== Daemon BSD Source Code Copyright (c) 2013-2014, Daemon Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Daemon developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAEMON DEVELOPERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================== */ #include "../qcommon/qcommon.h" #include "VirtualMachine.h" #ifdef _WIN32 #include <windows.h> #include <io.h> #undef CopyFile #else #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <sys/wait.h> #ifdef __linux__ #include <sys/prctl.h> #endif #endif // File handle for the root socket #define ROOT_SOCKET_FD 100 // MinGW doesn't define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #ifndef JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 0x2000 #endif // On windows use _snprintf instead of snprintf #ifdef _WIN32 #define snprintf _snprintf #endif namespace VM { // Platform-specific code to load a module static std::pair<Sys::OSHandle, IPC::Socket> InternalLoadModule(std::pair<IPC::Socket, IPC::Socket> pair, const char* const* args, bool reserve_mem, FS::File stderrRedirect = FS::File()) { #ifdef _WIN32 // Inherit the socket in the child process if (!SetHandleInformation(pair.second.GetHandle(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) Sys::Drop("VM: Could not make socket inheritable: %s", Sys::Win32StrError(GetLastError())); // Inherit the stderr redirect in the child process HANDLE stderrRedirectHandle = stderrRedirect ? reinterpret_cast<HANDLE>(_get_osfhandle(fileno(stderrRedirect.GetHandle()))) : NULL; if (stderrRedirect && !SetHandleInformation(stderrRedirectHandle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) Sys::Drop("VM: Could not make stderr redirect inheritable: %s", Sys::Win32StrError(GetLastError())); // Escape command line arguments std::string cmdline; for (int i = 0; args[i]; i++) { if (i != 0) cmdline += " "; // Enclose parameter in quotes cmdline += "\""; int num_slashes = 0; for (int j = 0; true; j++) { char c = args[i][j]; if (c == '\\') num_slashes++; else if (c == '\"' || c == '\0') { // Backlashes before a quote must be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\\\"; num_slashes = 0; if (c == '\"') cmdline += "\\\""; else break; } else { // Backlashes before any other character must not be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\"; num_slashes = 0; cmdline.push_back(c); } } cmdline += "\""; } // Convert command line to UTF-16 and add a NUL terminator std::wstring wcmdline = Str::UTF8To16(cmdline) + L"\0"; // Create a job object to ensure the process is terminated if the parent dies HANDLE job = CreateJobObject(NULL, NULL); if (!job) Sys::Drop("VM: Could not create job object: %s", Sys::Win32StrError(GetLastError())); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli; memset(&jeli, 0, sizeof(jeli)); jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli))) Sys::Drop("VM: Could not set job object information: %s", Sys::Win32StrError(GetLastError())); STARTUPINFOW startupInfo; PROCESS_INFORMATION processInfo; memset(&startupInfo, 0, sizeof(startupInfo)); if (stderrRedirect) { startupInfo.hStdError = stderrRedirectHandle; startupInfo.dwFlags = STARTF_USESTDHANDLES; } startupInfo.cb = sizeof(startupInfo); if (!CreateProcessW(NULL, &wcmdline[0], NULL, NULL, TRUE, CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB | DETACHED_PROCESS, NULL, NULL, &startupInfo, &processInfo)) { CloseHandle(job); Sys::Drop("VM: Could not create child process: %s", Sys::Win32StrError(GetLastError())); } if (!AssignProcessToJobObject(job, processInfo.hProcess)) { TerminateProcess(processInfo.hProcess, 0); CloseHandle(job); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); Sys::Drop("VM: Could not assign process to job object: %s", Sys::Win32StrError(GetLastError())); } #ifndef _WIN64 // Attempt to reserve 1GB of address space for the NaCl sandbox if (reserve_mem) VirtualAllocEx(processInfo.hProcess, NULL, 1 << 30, MEM_RESERVE, PAGE_NOACCESS); #endif ResumeThread(processInfo.hThread); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); return std::make_pair(job, std::move(pair.first)); #else Q_UNUSED(reserve_mem); // Create a pipe to report errors from the child process int pipefds[2]; if (pipe(pipefds) == -1 || fcntl(pipefds[1], F_SETFD, FD_CLOEXEC)) Sys::Drop("VM: Failed to create pipe: %s", strerror(errno)); int pid = vfork(); if (pid == -1) Sys::Drop("VM: Failed to fork process: %s", strerror(errno)); if (pid == 0) { // Close the other end of the pipe close(pipefds[0]); // Explicitly destroy the local socket, since destructors are not called close(pair.first.GetHandle()); // This seems to be required, otherwise killing the child process will // also kill the parent process. setsid(); #ifdef __linux__ // Kill child process if the parent dies. This avoid left-over processes // when using the debug stub. Sadly it is Linux-only. prctl(PR_SET_PDEATHSIG, SIGKILL); #endif // Close standard input/output descriptors close(0); close(1); // If an stderr redirect is provided, set it now if (stderrRedirect) dup2(fileno(stderrRedirect.GetHandle()), 2); // Load the target executable char* env[] = {nullptr}; execve(args[0], const_cast<char* const*>(args), env); // If the exec fails, return errno to the parent through the pipe write(pipefds[1], &errno, sizeof(int)); _exit(-1); } // Try to read from the pipe to see if the child successfully exec'd close(pipefds[1]); ssize_t count; int err; while ((count = read(pipefds[0], &err, sizeof(int))) == -1) { if (errno != EAGAIN && errno != EINTR) break; } close(pipefds[0]); if (count) { waitpid(pid, NULL, 0); Sys::Drop("VM: Failed to exec: %s", strerror(err)); } return std::make_pair(pid, std::move(pair.first)); #endif } std::pair<Sys::OSHandle, IPC::Socket> CreateNaClVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, bool debug, bool extract, int debugLoader) { const std::string& libPath = FS::GetLibPath(); #ifdef NACL_RUNTIME_PATH const char* naclPath = XSTRING(NACL_RUNTIME_PATH); #else const std::string& naclPath = libPath; #endif std::vector<const char*> args; char rootSocketRedir[32]; std::string module, nacl_loader, irt, bootstrap, modulePath, verbosity; FS::File stderrRedirect; bool win32Force64Bit = false; // On Windows, even if we are running a 32-bit engine, we must use the // 64-bit nacl_loader if the host operating system is 64-bit. #if defined(_WIN32) && !defined(_WIN64) SYSTEM_INFO systemInfo; GetNativeSystemInfo(&systemInfo); win32Force64Bit = systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64; #endif // Extract the nexe from the pak so that nacl_loader can load it module = win32Force64Bit ? name + "-x86_64.nexe" : name + "-" ARCH_STRING ".nexe"; if (extract) { try { FS::File out = FS::HomePath::OpenWrite(module); if (const FS::LoadedPakInfo* pak = FS::PakPath::LocateFile(module)) Com_Printf("Extracting VM module %s from %s...\n", module.c_str(), pak->path.c_str()); FS::PakPath::CopyFile(module, out); out.Close(); } catch (std::system_error& err) { Sys::Drop("VM: Failed to extract VM module %s: %s\n", module, err.what()); } modulePath = FS::Path::Build(FS::GetHomePath(), module); } else modulePath = FS::Path::Build(libPath, module); // Generate command line snprintf(rootSocketRedir, sizeof(rootSocketRedir), "%d:%d", ROOT_SOCKET_FD, (int)(intptr_t)pair.second.GetHandle()); irt = FS::Path::Build(naclPath, win32Force64Bit ? "irt_core-x86_64.nexe" : "irt_core-" ARCH_STRING ".nexe"); nacl_loader = FS::Path::Build(naclPath, win32Force64Bit ? "nacl_loader64" EXE_EXT : "nacl_loader" EXE_EXT); #ifdef __linux__ bootstrap = FS::Path::Build(naclPath, "nacl_helper_bootstrap"); args.push_back(bootstrap.c_str()); args.push_back(nacl_loader.c_str()); args.push_back("--r_debug=0xXXXXXXXXXXXXXXXX"); args.push_back("--reserved_at_zero=0xXXXXXXXXXXXXXXXX"); #else Q_UNUSED(bootstrap); args.push_back(nacl_loader.c_str()); #endif if (debug) { args.push_back("-g"); } if (debugLoader) { try { stderrRedirect = FS::HomePath::OpenWrite(name + ".nacl_loader.log"); } catch (std::system_error& err) { Log::Warn("Couldn't open %s: %s", name + ".nacl_loader.log", err.what()); } verbosity = "-"; verbosity.append(debugLoader, 'v'); args.push_back(verbosity.c_str()); } args.push_back("-B"); args.push_back(irt.c_str()); args.push_back("-e"); args.push_back("-i"); args.push_back(rootSocketRedir); args.push_back("--"); args.push_back(modulePath.c_str()); args.push_back(XSTRING(ROOT_SOCKET_FD)); args.push_back(NULL); Com_Printf("Loading VM module %s...\n", module.c_str()); if (debugLoader) { std::string commandLine; for (auto arg : args) { if (arg) { commandLine += " "; commandLine += arg; } } Com_Printf("Using loader args: %s", commandLine.c_str()); } return InternalLoadModule(std::move(pair), args.data(), true, std::move(stderrRedirect)); } std::pair<Sys::OSHandle, IPC::Socket> CreateNativeVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, bool debug) { const std::string& libPath = FS::GetLibPath(); std::vector<const char*> args; std::string handleArg = std::to_string((int)(intptr_t)pair.second.GetHandle()); std::string module = FS::Path::Build(libPath, name + "-native-exe" + EXE_EXT); if (debug) { args.push_back("/usr/bin/gdbserver"); args.push_back("localhost:4014"); } args.push_back(module.c_str()); args.push_back(handleArg.c_str()); args.push_back(NULL); Com_Printf("Loading VM module %s...\n", module.c_str()); return InternalLoadModule(std::move(pair), args.data(), true); } IPC::Socket CreateInProcessNativeVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, VM::VMBase::InProcessInfo& inProcess) { std::string filename = FS::Path::Build(FS::GetLibPath(), name + "-native-dll" + DLL_EXT); Com_Printf("Loading VM module %s...\n", filename.c_str()); std::string errorString; inProcess.sharedLib = Sys::DynamicLib::Open(filename, errorString); if (!inProcess.sharedLib) Sys::Drop("VM: Failed to load shared library VM %s: %s", filename, errorString); auto vmMain = inProcess.sharedLib.LoadSym<void(Sys::OSHandle)>("vmMain", errorString); if (!vmMain) Sys::Drop("VM: Could not find vmMain function in %s: %s", filename, errorString); Sys::OSHandle vmSocketArg = pair.second.ReleaseHandle(); inProcess.running = true; try { inProcess.thread = std::thread([vmMain, vmSocketArg, &inProcess]() { vmMain(vmSocketArg); std::lock_guard<std::mutex> lock(inProcess.mutex); inProcess.running = false; inProcess.condition.notify_one(); }); } catch (std::system_error& err) { // Close vmSocketArg using the Socket destructor IPC::Socket::FromHandle(vmSocketArg); inProcess.running = false; Sys::Drop("VM: Could not create thread for VM: %s", err.what()); } return std::move(pair.first); } uint32_t VMBase::Create() { type = static_cast<vmType_t>(params.vmType.Get()); if (type < 0 || type >= TYPE_END) Sys::Drop("VM: Invalid type %d", type); int loadStartTime = Sys_Milliseconds(); // Free the VM if it exists Free(); // Open the syscall log if (params.logSyscalls.Get()) { std::string filename = name + ".syscallLog"; try { syscallLogFile = FS::RawPath::OpenWrite(filename); } catch (std::system_error& err) { Log::Warn("Couldn't open %s: %s", filename, err.what()); } } // Create the socket pair to get the handle for the root socket std::pair<IPC::Socket, IPC::Socket> pair = IPC::Socket::CreatePair(); IPC::Socket rootSocket; if (type == TYPE_NACL || type == TYPE_NACL_LIBPATH) { std::tie(processHandle, rootSocket) = CreateNaClVM(std::move(pair), name, params.debug.Get(), type == TYPE_NACL, params.debugLoader.Get()); } else if (type == TYPE_NATIVE_EXE) { std::tie(processHandle, rootSocket) = CreateNativeVM(std::move(pair), name, params.debug.Get()); } else { rootSocket = CreateInProcessNativeVM(std::move(pair), name, inProcess); } rootChannel = IPC::Channel(std::move(rootSocket)); if (type != TYPE_NATIVE_DLL && params.debug.Get()) Com_Printf("Waiting for GDB connection on localhost:4014\n"); // Only set a recieve timeout for non-debug configurations, otherwise it // would get triggered by breakpoints. if (type != TYPE_NATIVE_DLL && !params.debug.Get()) rootChannel.SetRecvTimeout(std::chrono::seconds(2)); // Read the ABI version from the root socket. // If this fails, we assume the remote process failed to start Util::Reader reader = rootChannel.RecvMsg(); Com_Printf("Loaded VM module in %d msec\n", Sys_Milliseconds() - loadStartTime); return reader.Read<uint32_t>(); } void VMBase::FreeInProcessVM() { if (inProcess.thread.joinable()) { bool wait = true; if (inProcess.running) { std::unique_lock<std::mutex> lock(inProcess.mutex); auto status = inProcess.condition.wait_for(lock, std::chrono::milliseconds(500)); if (status == std::cv_status::timeout) { wait = false; } } if (wait) { Com_Printf("Waiting for the VM thread...\n"); inProcess.thread.join(); } else { Com_Printf("The VM thread doesn't seem to stop, detaching it (bad things WILL ensue)\n"); inProcess.thread.detach(); } } inProcess.sharedLib.Close(); inProcess.running = false; } void VMBase::LogMessage(bool vmToEngine, bool start, int id) { if (syscallLogFile) { int minor = id & 0xffff; int major = id >> 16; const char* direction = vmToEngine ? "V->E" : "E->V"; const char* extremity = start ? "start" : "end"; uint64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(Sys::SteadyClock::now().time_since_epoch()).count(); try { syscallLogFile.Printf("%s %s %s %s %s\n", direction, extremity, major, minor, ns); } catch (std::system_error& err) { Log::Warn("Error while writing the VM syscall log: %s", err.what()); } } } void VMBase::Free() { if (syscallLogFile) { std::error_code err; syscallLogFile.Close(err); } if (!IsActive()) return; // First send a message signaling an exit to the VM // then delete the socket. This is needed because // recvmsg in NaCl doesn't return when the socket has // been closed. Util::Writer writer; writer.Write<uint32_t>(IPC::ID_EXIT); rootChannel.SendMsg(writer); rootChannel = IPC::Channel(); if (type != TYPE_NATIVE_DLL) { #ifdef _WIN32 // Closing the job object should kill the child process CloseHandle(processHandle); #else int status; if (waitpid(processHandle, &status, WNOHANG) != 0) { if (WIFSIGNALED(status)) Log::Warn("VM exited with signal %d: %s\n", WTERMSIG(status), strsignal(WTERMSIG(status))); else if (WIFEXITED(status)) Log::Warn("VM exited with non-zero exit code %d\n", WEXITSTATUS(status)); } kill(processHandle, SIGKILL); waitpid(processHandle, NULL, 0); #endif processHandle = Sys::INVALID_HANDLE; } else { FreeInProcessVM(); } } } // namespace VM Don't let nacl_loader create a console window /* =========================================================================== Daemon BSD Source Code Copyright (c) 2013-2014, Daemon Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Daemon developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAEMON DEVELOPERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================== */ #include "../qcommon/qcommon.h" #include "VirtualMachine.h" #ifdef _WIN32 #include <windows.h> #include <io.h> #undef CopyFile #else #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <sys/wait.h> #ifdef __linux__ #include <sys/prctl.h> #endif #endif // File handle for the root socket #define ROOT_SOCKET_FD 100 // MinGW doesn't define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #ifndef JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 0x2000 #endif // On windows use _snprintf instead of snprintf #ifdef _WIN32 #define snprintf _snprintf #endif namespace VM { // Platform-specific code to load a module static std::pair<Sys::OSHandle, IPC::Socket> InternalLoadModule(std::pair<IPC::Socket, IPC::Socket> pair, const char* const* args, bool reserve_mem, FS::File stderrRedirect = FS::File()) { #ifdef _WIN32 // Inherit the socket in the child process if (!SetHandleInformation(pair.second.GetHandle(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) Sys::Drop("VM: Could not make socket inheritable: %s", Sys::Win32StrError(GetLastError())); // Inherit the stderr redirect in the child process HANDLE stderrRedirectHandle = stderrRedirect ? reinterpret_cast<HANDLE>(_get_osfhandle(fileno(stderrRedirect.GetHandle()))) : NULL; if (stderrRedirect && !SetHandleInformation(stderrRedirectHandle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) Sys::Drop("VM: Could not make stderr redirect inheritable: %s", Sys::Win32StrError(GetLastError())); // Escape command line arguments std::string cmdline; for (int i = 0; args[i]; i++) { if (i != 0) cmdline += " "; // Enclose parameter in quotes cmdline += "\""; int num_slashes = 0; for (int j = 0; true; j++) { char c = args[i][j]; if (c == '\\') num_slashes++; else if (c == '\"' || c == '\0') { // Backlashes before a quote must be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\\\"; num_slashes = 0; if (c == '\"') cmdline += "\\\""; else break; } else { // Backlashes before any other character must not be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\"; num_slashes = 0; cmdline.push_back(c); } } cmdline += "\""; } // Convert command line to UTF-16 and add a NUL terminator std::wstring wcmdline = Str::UTF8To16(cmdline) + L"\0"; // Create a job object to ensure the process is terminated if the parent dies HANDLE job = CreateJobObject(NULL, NULL); if (!job) Sys::Drop("VM: Could not create job object: %s", Sys::Win32StrError(GetLastError())); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli; memset(&jeli, 0, sizeof(jeli)); jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli))) Sys::Drop("VM: Could not set job object information: %s", Sys::Win32StrError(GetLastError())); STARTUPINFOW startupInfo; PROCESS_INFORMATION processInfo; memset(&startupInfo, 0, sizeof(startupInfo)); if (stderrRedirect) { startupInfo.hStdError = stderrRedirectHandle; startupInfo.dwFlags = STARTF_USESTDHANDLES; } startupInfo.cb = sizeof(startupInfo); if (!CreateProcessW(NULL, &wcmdline[0], NULL, NULL, TRUE, CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB | CREATE_NO_WINDOW, NULL, NULL, &startupInfo, &processInfo)) { CloseHandle(job); Sys::Drop("VM: Could not create child process: %s", Sys::Win32StrError(GetLastError())); } if (!AssignProcessToJobObject(job, processInfo.hProcess)) { TerminateProcess(processInfo.hProcess, 0); CloseHandle(job); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); Sys::Drop("VM: Could not assign process to job object: %s", Sys::Win32StrError(GetLastError())); } #ifndef _WIN64 // Attempt to reserve 1GB of address space for the NaCl sandbox if (reserve_mem) VirtualAllocEx(processInfo.hProcess, NULL, 1 << 30, MEM_RESERVE, PAGE_NOACCESS); #endif ResumeThread(processInfo.hThread); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); return std::make_pair(job, std::move(pair.first)); #else Q_UNUSED(reserve_mem); // Create a pipe to report errors from the child process int pipefds[2]; if (pipe(pipefds) == -1 || fcntl(pipefds[1], F_SETFD, FD_CLOEXEC)) Sys::Drop("VM: Failed to create pipe: %s", strerror(errno)); int pid = vfork(); if (pid == -1) Sys::Drop("VM: Failed to fork process: %s", strerror(errno)); if (pid == 0) { // Close the other end of the pipe close(pipefds[0]); // Explicitly destroy the local socket, since destructors are not called close(pair.first.GetHandle()); // This seems to be required, otherwise killing the child process will // also kill the parent process. setsid(); #ifdef __linux__ // Kill child process if the parent dies. This avoid left-over processes // when using the debug stub. Sadly it is Linux-only. prctl(PR_SET_PDEATHSIG, SIGKILL); #endif // Close standard input/output descriptors close(0); close(1); // If an stderr redirect is provided, set it now if (stderrRedirect) dup2(fileno(stderrRedirect.GetHandle()), 2); // Load the target executable char* env[] = {nullptr}; execve(args[0], const_cast<char* const*>(args), env); // If the exec fails, return errno to the parent through the pipe write(pipefds[1], &errno, sizeof(int)); _exit(-1); } // Try to read from the pipe to see if the child successfully exec'd close(pipefds[1]); ssize_t count; int err; while ((count = read(pipefds[0], &err, sizeof(int))) == -1) { if (errno != EAGAIN && errno != EINTR) break; } close(pipefds[0]); if (count) { waitpid(pid, NULL, 0); Sys::Drop("VM: Failed to exec: %s", strerror(err)); } return std::make_pair(pid, std::move(pair.first)); #endif } std::pair<Sys::OSHandle, IPC::Socket> CreateNaClVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, bool debug, bool extract, int debugLoader) { const std::string& libPath = FS::GetLibPath(); #ifdef NACL_RUNTIME_PATH const char* naclPath = XSTRING(NACL_RUNTIME_PATH); #else const std::string& naclPath = libPath; #endif std::vector<const char*> args; char rootSocketRedir[32]; std::string module, nacl_loader, irt, bootstrap, modulePath, verbosity; FS::File stderrRedirect; bool win32Force64Bit = false; // On Windows, even if we are running a 32-bit engine, we must use the // 64-bit nacl_loader if the host operating system is 64-bit. #if defined(_WIN32) && !defined(_WIN64) SYSTEM_INFO systemInfo; GetNativeSystemInfo(&systemInfo); win32Force64Bit = systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64; #endif // Extract the nexe from the pak so that nacl_loader can load it module = win32Force64Bit ? name + "-x86_64.nexe" : name + "-" ARCH_STRING ".nexe"; if (extract) { try { FS::File out = FS::HomePath::OpenWrite(module); if (const FS::LoadedPakInfo* pak = FS::PakPath::LocateFile(module)) Com_Printf("Extracting VM module %s from %s...\n", module.c_str(), pak->path.c_str()); FS::PakPath::CopyFile(module, out); out.Close(); } catch (std::system_error& err) { Sys::Drop("VM: Failed to extract VM module %s: %s\n", module, err.what()); } modulePath = FS::Path::Build(FS::GetHomePath(), module); } else modulePath = FS::Path::Build(libPath, module); // Generate command line snprintf(rootSocketRedir, sizeof(rootSocketRedir), "%d:%d", ROOT_SOCKET_FD, (int)(intptr_t)pair.second.GetHandle()); irt = FS::Path::Build(naclPath, win32Force64Bit ? "irt_core-x86_64.nexe" : "irt_core-" ARCH_STRING ".nexe"); nacl_loader = FS::Path::Build(naclPath, win32Force64Bit ? "nacl_loader64" EXE_EXT : "nacl_loader" EXE_EXT); #ifdef __linux__ bootstrap = FS::Path::Build(naclPath, "nacl_helper_bootstrap"); args.push_back(bootstrap.c_str()); args.push_back(nacl_loader.c_str()); args.push_back("--r_debug=0xXXXXXXXXXXXXXXXX"); args.push_back("--reserved_at_zero=0xXXXXXXXXXXXXXXXX"); #else Q_UNUSED(bootstrap); args.push_back(nacl_loader.c_str()); #endif if (debug) { args.push_back("-g"); } if (debugLoader) { try { stderrRedirect = FS::HomePath::OpenWrite(name + ".nacl_loader.log"); } catch (std::system_error& err) { Log::Warn("Couldn't open %s: %s", name + ".nacl_loader.log", err.what()); } verbosity = "-"; verbosity.append(debugLoader, 'v'); args.push_back(verbosity.c_str()); } args.push_back("-B"); args.push_back(irt.c_str()); args.push_back("-e"); args.push_back("-i"); args.push_back(rootSocketRedir); args.push_back("--"); args.push_back(modulePath.c_str()); args.push_back(XSTRING(ROOT_SOCKET_FD)); args.push_back(NULL); Com_Printf("Loading VM module %s...\n", module.c_str()); if (debugLoader) { std::string commandLine; for (auto arg : args) { if (arg) { commandLine += " "; commandLine += arg; } } Com_Printf("Using loader args: %s", commandLine.c_str()); } return InternalLoadModule(std::move(pair), args.data(), true, std::move(stderrRedirect)); } std::pair<Sys::OSHandle, IPC::Socket> CreateNativeVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, bool debug) { const std::string& libPath = FS::GetLibPath(); std::vector<const char*> args; std::string handleArg = std::to_string((int)(intptr_t)pair.second.GetHandle()); std::string module = FS::Path::Build(libPath, name + "-native-exe" + EXE_EXT); if (debug) { args.push_back("/usr/bin/gdbserver"); args.push_back("localhost:4014"); } args.push_back(module.c_str()); args.push_back(handleArg.c_str()); args.push_back(NULL); Com_Printf("Loading VM module %s...\n", module.c_str()); return InternalLoadModule(std::move(pair), args.data(), true); } IPC::Socket CreateInProcessNativeVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, VM::VMBase::InProcessInfo& inProcess) { std::string filename = FS::Path::Build(FS::GetLibPath(), name + "-native-dll" + DLL_EXT); Com_Printf("Loading VM module %s...\n", filename.c_str()); std::string errorString; inProcess.sharedLib = Sys::DynamicLib::Open(filename, errorString); if (!inProcess.sharedLib) Sys::Drop("VM: Failed to load shared library VM %s: %s", filename, errorString); auto vmMain = inProcess.sharedLib.LoadSym<void(Sys::OSHandle)>("vmMain", errorString); if (!vmMain) Sys::Drop("VM: Could not find vmMain function in %s: %s", filename, errorString); Sys::OSHandle vmSocketArg = pair.second.ReleaseHandle(); inProcess.running = true; try { inProcess.thread = std::thread([vmMain, vmSocketArg, &inProcess]() { vmMain(vmSocketArg); std::lock_guard<std::mutex> lock(inProcess.mutex); inProcess.running = false; inProcess.condition.notify_one(); }); } catch (std::system_error& err) { // Close vmSocketArg using the Socket destructor IPC::Socket::FromHandle(vmSocketArg); inProcess.running = false; Sys::Drop("VM: Could not create thread for VM: %s", err.what()); } return std::move(pair.first); } uint32_t VMBase::Create() { type = static_cast<vmType_t>(params.vmType.Get()); if (type < 0 || type >= TYPE_END) Sys::Drop("VM: Invalid type %d", type); int loadStartTime = Sys_Milliseconds(); // Free the VM if it exists Free(); // Open the syscall log if (params.logSyscalls.Get()) { std::string filename = name + ".syscallLog"; try { syscallLogFile = FS::RawPath::OpenWrite(filename); } catch (std::system_error& err) { Log::Warn("Couldn't open %s: %s", filename, err.what()); } } // Create the socket pair to get the handle for the root socket std::pair<IPC::Socket, IPC::Socket> pair = IPC::Socket::CreatePair(); IPC::Socket rootSocket; if (type == TYPE_NACL || type == TYPE_NACL_LIBPATH) { std::tie(processHandle, rootSocket) = CreateNaClVM(std::move(pair), name, params.debug.Get(), type == TYPE_NACL, params.debugLoader.Get()); } else if (type == TYPE_NATIVE_EXE) { std::tie(processHandle, rootSocket) = CreateNativeVM(std::move(pair), name, params.debug.Get()); } else { rootSocket = CreateInProcessNativeVM(std::move(pair), name, inProcess); } rootChannel = IPC::Channel(std::move(rootSocket)); if (type != TYPE_NATIVE_DLL && params.debug.Get()) Com_Printf("Waiting for GDB connection on localhost:4014\n"); // Only set a recieve timeout for non-debug configurations, otherwise it // would get triggered by breakpoints. if (type != TYPE_NATIVE_DLL && !params.debug.Get()) rootChannel.SetRecvTimeout(std::chrono::seconds(2)); // Read the ABI version from the root socket. // If this fails, we assume the remote process failed to start Util::Reader reader = rootChannel.RecvMsg(); Com_Printf("Loaded VM module in %d msec\n", Sys_Milliseconds() - loadStartTime); return reader.Read<uint32_t>(); } void VMBase::FreeInProcessVM() { if (inProcess.thread.joinable()) { bool wait = true; if (inProcess.running) { std::unique_lock<std::mutex> lock(inProcess.mutex); auto status = inProcess.condition.wait_for(lock, std::chrono::milliseconds(500)); if (status == std::cv_status::timeout) { wait = false; } } if (wait) { Com_Printf("Waiting for the VM thread...\n"); inProcess.thread.join(); } else { Com_Printf("The VM thread doesn't seem to stop, detaching it (bad things WILL ensue)\n"); inProcess.thread.detach(); } } inProcess.sharedLib.Close(); inProcess.running = false; } void VMBase::LogMessage(bool vmToEngine, bool start, int id) { if (syscallLogFile) { int minor = id & 0xffff; int major = id >> 16; const char* direction = vmToEngine ? "V->E" : "E->V"; const char* extremity = start ? "start" : "end"; uint64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(Sys::SteadyClock::now().time_since_epoch()).count(); try { syscallLogFile.Printf("%s %s %s %s %s\n", direction, extremity, major, minor, ns); } catch (std::system_error& err) { Log::Warn("Error while writing the VM syscall log: %s", err.what()); } } } void VMBase::Free() { if (syscallLogFile) { std::error_code err; syscallLogFile.Close(err); } if (!IsActive()) return; // First send a message signaling an exit to the VM // then delete the socket. This is needed because // recvmsg in NaCl doesn't return when the socket has // been closed. Util::Writer writer; writer.Write<uint32_t>(IPC::ID_EXIT); rootChannel.SendMsg(writer); rootChannel = IPC::Channel(); if (type != TYPE_NATIVE_DLL) { #ifdef _WIN32 // Closing the job object should kill the child process CloseHandle(processHandle); #else int status; if (waitpid(processHandle, &status, WNOHANG) != 0) { if (WIFSIGNALED(status)) Log::Warn("VM exited with signal %d: %s\n", WTERMSIG(status), strsignal(WTERMSIG(status))); else if (WIFEXITED(status)) Log::Warn("VM exited with non-zero exit code %d\n", WEXITSTATUS(status)); } kill(processHandle, SIGKILL); waitpid(processHandle, NULL, 0); #endif processHandle = Sys::INVALID_HANDLE; } else { FreeInProcessVM(); } } } // namespace VM
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames // Copyright (C) 2015 Faust Logic, Inc. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// #include "platform/platform.h" #include "T3D/player.h" #include "platform/profiler.h" #include "math/mMath.h" #include "math/mathIO.h" #include "core/resourceManager.h" #include "core/stringTable.h" #include "core/volume.h" #include "core/stream/bitStream.h" #include "console/consoleTypes.h" #include "console/engineAPI.h" #include "collision/extrudedPolyList.h" #include "collision/clippedPolyList.h" #include "collision/earlyOutPolyList.h" #include "ts/tsShapeInstance.h" #include "sfx/sfxSystem.h" #include "sfx/sfxTrack.h" #include "sfx/sfxSource.h" #include "sfx/sfxTypes.h" #include "scene/sceneManager.h" #include "scene/sceneRenderState.h" #include "T3D/gameBase/gameConnection.h" #include "T3D/trigger.h" #include "T3D/physicalZone.h" #include "T3D/item.h" #include "T3D/missionArea.h" #include "T3D/fx/particleEmitter.h" #include "T3D/fx/cameraFXMgr.h" #include "T3D/fx/splash.h" #include "T3D/tsStatic.h" #include "T3D/physics/physicsPlugin.h" #include "T3D/physics/physicsPlayer.h" #include "T3D/decal/decalManager.h" #include "T3D/decal/decalData.h" #include "materials/baseMatInstance.h" #include "math/mathUtils.h" #include "gfx/sim/debugDraw.h" #ifdef TORQUE_EXTENDED_MOVE #include "T3D/gameBase/extended/extendedMove.h" #endif #ifdef TORQUE_OPENVR #include "platform/input/openVR/openVRProvider.h" #include "platform/input/openVR/openVRTrackedObject.h" #endif // Amount of time if takes to transition to a new action sequence. static F32 sAnimationTransitionTime = 0.25f; static bool sUseAnimationTransitions = true; static F32 sLandReverseScale = 0.25f; static F32 sSlowStandThreshSquared = 1.69f; static S32 sRenderMyPlayer = true; static S32 sRenderMyItems = true; static bool sRenderPlayerCollision = false; // Chooses new action animations every n ticks. static const F32 sNewAnimationTickTime = 4.0f; static const F32 sMountPendingTickWait = 13.0f * F32(TickMs); // Number of ticks before we pick non-contact animations static const S32 sContactTickTime = 10; // Movement constants static F32 sVerticalStepDot = 0.173f; // 80 static F32 sMinFaceDistance = 0.01f; static F32 sTractionDistance = 0.04f; static F32 sNormalElasticity = 0.01f; static U32 sMoveRetryCount = 5; static F32 sMaxImpulseVelocity = 200.0f; // Move triggers static S32 sJumpTrigger = 2; static S32 sCrouchTrigger = 3; static S32 sProneTrigger = 4; static S32 sSprintTrigger = 5; static S32 sImageTrigger0 = 0; static S32 sImageTrigger1 = 1; static S32 sJumpJetTrigger = 1; static S32 sVehicleDismountTrigger = 2; // Client prediction static F32 sMinWarpTicks = 0.5f; // Fraction of tick at which instant warp occurs static S32 sMaxWarpTicks = 3; // Max warp duration in ticks static S32 sMaxPredictionTicks = 30; // Number of ticks to predict S32 Player::smExtendedMoveHeadPosRotIndex = 0; // The ExtendedMove position/rotation index used for head movements // static U32 sCollisionMoveMask = TerrainObjectType | WaterObjectType | PlayerObjectType | StaticShapeObjectType | VehicleObjectType | PhysicalZoneObjectType | // PATHSHAPE PathShapeObjectType; // PATHSHAPE END static U32 sServerCollisionContactMask = sCollisionMoveMask | ItemObjectType | TriggerObjectType | CorpseObjectType; static U32 sClientCollisionContactMask = sCollisionMoveMask | TriggerObjectType; enum PlayerConstants { JumpSkipContactsMax = 8 }; //---------------------------------------------------------------------------- // Player shape animation sequences: // Action Animations: PlayerData::ActionAnimationDef PlayerData::ActionAnimationList[NumTableActionAnims] = { // *** WARNING *** // This array is indexed using the enum values defined in player.h // Root is the default animation { "root" }, // RootAnim, // These are selected in the move state based on velocity { "run", { 0.0f, 1.0f, 0.0f } }, // RunForwardAnim, { "back", { 0.0f,-1.0f, 0.0f } }, // BackBackwardAnim { "side", {-1.0f, 0.0f, 0.0f } }, // SideLeftAnim, { "side_right", { 1.0f, 0.0f, 0.0f } }, // SideRightAnim, { "sprint_root" }, { "sprint_forward", { 0.0f, 1.0f, 0.0f } }, { "sprint_backward", { 0.0f,-1.0f, 0.0f } }, { "sprint_side", {-1.0f, 0.0f, 0.0f } }, { "sprint_right", { 1.0f, 0.0f, 0.0f } }, { "crouch_root" }, { "crouch_forward", { 0.0f, 1.0f, 0.0f } }, { "crouch_backward", { 0.0f,-1.0f, 0.0f } }, { "crouch_side", {-1.0f, 0.0f, 0.0f } }, { "crouch_right", { 1.0f, 0.0f, 0.0f } }, { "prone_root" }, { "prone_forward", { 0.0f, 1.0f, 0.0f } }, { "prone_backward", { 0.0f,-1.0f, 0.0f } }, { "swim_root" }, { "swim_forward", { 0.0f, 1.0f, 0.0f } }, { "swim_backward", { 0.0f,-1.0f, 0.0f } }, { "swim_left", {-1.0f, 0.0f, 0.0f } }, { "swim_right", { 1.0f, 0.0f, 0.0f } }, // These are set explicitly based on player actions { "fall" }, // FallAnim { "jump" }, // JumpAnim { "standjump" }, // StandJumpAnim { "land" }, // LandAnim { "jet" }, // JetAnim }; //---------------------------------------------------------------------------- typedef PlayerData::Sounds playerSoundsEnum; DefineEnumType(playerSoundsEnum); ImplementEnumType(playerSoundsEnum, "enum types.\n" "@ingroup PlayerData\n\n") { playerSoundsEnum::FootSoft, "FootSoft", "..." }, { playerSoundsEnum::FootHard, "FootHard","..." }, { playerSoundsEnum::FootMetal, "FootMetal","..." }, { playerSoundsEnum::FootSnow, "FootSnow","..." }, { playerSoundsEnum::FootShallowSplash, "FootShallowSplash","..." }, { playerSoundsEnum::FootWading, "FootWading","..." }, { playerSoundsEnum::FootUnderWater, "FootUnderWater","..." }, { playerSoundsEnum::FootBubbles, "FootBubbles","..." }, { playerSoundsEnum::MoveBubbles, "MoveBubbles","..." }, { playerSoundsEnum::WaterBreath, "WaterBreath","..." }, { playerSoundsEnum::ImpactSoft, "ImpactSoft","..." }, { playerSoundsEnum::ImpactHard, "ImpactHard","..." }, { playerSoundsEnum::ImpactMetal, "ImpactMetal","..." }, { playerSoundsEnum::ImpactSnow, "ImpactSnow","..." }, { playerSoundsEnum::ImpactWaterEasy, "ImpactWaterEasy","..." }, { playerSoundsEnum::ImpactWaterMedium, "ImpactWaterMedium","..." }, { playerSoundsEnum::ImpactWaterHard, "ImpactWaterHard","..." }, { playerSoundsEnum::ExitWater, "ExitWater","..." }, EndImplementEnumType; //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- IMPLEMENT_CO_DATABLOCK_V1(PlayerData); ConsoleDocClass( PlayerData, "@brief Defines properties for a Player object.\n\n" "@see Player\n" "@ingroup gameObjects\n" ); IMPLEMENT_CALLBACK( PlayerData, onPoseChange, void, ( Player* obj, const char* oldPose, const char* newPose ), ( obj, oldPose, newPose ), "@brief Called when the player changes poses.\n\n" "@param obj The Player object\n" "@param oldPose The pose the player is switching from.\n" "@param newPose The pose the player is switching to.\n"); IMPLEMENT_CALLBACK( PlayerData, onStartSwim, void, ( Player* obj ), ( obj ), "@brief Called when the player starts swimming.\n\n" "@param obj The Player object\n" ); IMPLEMENT_CALLBACK( PlayerData, onStopSwim, void, ( Player* obj ), ( obj ), "@brief Called when the player stops swimming.\n\n" "@param obj The Player object\n" ); IMPLEMENT_CALLBACK( PlayerData, onStartSprintMotion, void, ( Player* obj ), ( obj ), "@brief Called when the player starts moving while in a Sprint pose.\n\n" "@param obj The Player object\n" ); IMPLEMENT_CALLBACK( PlayerData, onStopSprintMotion, void, ( Player* obj ), ( obj ), "@brief Called when the player stops moving while in a Sprint pose.\n\n" "@param obj The Player object\n" ); IMPLEMENT_CALLBACK( PlayerData, doDismount, void, ( Player* obj ), ( obj ), "@brief Called when attempting to dismount the player from a vehicle.\n\n" "It is up to the doDismount() method to actually perform the dismount. Often " "there are some conditions that prevent this, such as the vehicle moving too fast.\n" "@param obj The Player object\n" ); IMPLEMENT_CALLBACK( PlayerData, onEnterLiquid, void, ( Player* obj, F32 coverage, const char* type ), ( obj, coverage, type ), "@brief Called when the player enters a liquid.\n\n" "@param obj The Player object\n" "@param coverage Percentage of the player's bounding box covered by the liquid\n" "@param type The type of liquid the player has entered\n" ); IMPLEMENT_CALLBACK( PlayerData, onLeaveLiquid, void, ( Player* obj, const char* type ), ( obj, type ), "@brief Called when the player leaves a liquid.\n\n" "@param obj The Player object\n" "@param type The type of liquid the player has left\n" ); IMPLEMENT_CALLBACK( PlayerData, animationDone, void, ( Player* obj ), ( obj ), "@brief Called on the server when a scripted animation completes.\n\n" "@param obj The Player object\n" "@see Player::setActionThread() for setting a scripted animation and its 'hold' parameter to " "determine if this callback is used.\n" ); IMPLEMENT_CALLBACK( PlayerData, onEnterMissionArea, void, ( Player* obj ), ( obj ), "@brief Called when the player enters the mission area.\n\n" "@param obj The Player object\n" "@see MissionArea\n" ); IMPLEMENT_CALLBACK( PlayerData, onLeaveMissionArea, void, ( Player* obj ), ( obj ), "@brief Called when the player leaves the mission area.\n" "@param obj The Player object\n" "@see MissionArea\n" ); PlayerData::PlayerData() { shadowEnable = true; shadowSize = 256; shadowProjectionDistance = 14.0f; renderFirstPerson = true; firstPersonShadows = false; // Used for third person image rendering imageAnimPrefix = StringTable->EmptyString(); allowImageStateAnimation = false; // Used for first person image rendering imageAnimPrefixFP = StringTable->EmptyString(); for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { INIT_ASSET_ARRAY(ShapeFP, i); mCRCFP[i] = 0; mValidShapeFP[i] = false; } pickupRadius = 0.0f; minLookAngle = -1.4f; maxLookAngle = 1.4f; maxFreelookAngle = 3.0f; maxTimeScale = 1.5f; mass = 9.0f; // from ShapeBase maxEnergy = 60.0f; // from ShapeBase drag = 0.3f; // from ShapeBase density = 1.1f; // from ShapeBase maxStepHeight = 1.0f; runSurfaceAngle = 80.0f; runSurfaceCos = mCos(mDegToRad(runSurfaceAngle)); fallingSpeedThreshold = -10.0f; recoverDelay = 30; recoverRunForceScale = 1.0f; landSequenceTime = 0.0f; transitionToLand = false; // Running/Walking runForce = 40.0f * 9.0f; runEnergyDrain = 0.0f; minRunEnergy = 0.0f; maxForwardSpeed = 10.0f; maxBackwardSpeed = 10.0f; maxSideSpeed = 10.0f; // Jumping jumpForce = 75.0f; jumpEnergyDrain = 0.0f; minJumpEnergy = 0.0f; jumpSurfaceAngle = 78.0f; jumpSurfaceCos = mCos(mDegToRad(jumpSurfaceAngle)); for (U32 i = 0; i < NumRecoilSequences; i++) recoilSequence[i] = -1; jumpDelay = 30; minJumpSpeed = 500.0f; maxJumpSpeed = 2.0f * minJumpSpeed; // Sprinting sprintForce = 50.0f * 9.0f; sprintEnergyDrain = 0.0f; minSprintEnergy = 0.0f; maxSprintForwardSpeed = 15.0f; maxSprintBackwardSpeed = 10.0f; maxSprintSideSpeed = 10.0f; sprintStrafeScale = 1.0f; sprintYawScale = 1.0f; sprintPitchScale = 1.0f; sprintCanJump = true; // Swimming swimForce = 55.0f * 9.0f; maxUnderwaterForwardSpeed = 6.0f; maxUnderwaterBackwardSpeed = 6.0f; maxUnderwaterSideSpeed = 6.0f; // Crouching crouchForce = 45.0f * 9.0f; maxCrouchForwardSpeed = 4.0f; maxCrouchBackwardSpeed = 4.0f; maxCrouchSideSpeed = 4.0f; // Prone proneForce = 45.0f * 9.0f; maxProneForwardSpeed = 2.0f; maxProneBackwardSpeed = 2.0f; maxProneSideSpeed = 0.0f; // Jetting jetJumpForce = 0; jetJumpEnergyDrain = 0; jetMinJumpEnergy = 0; jetJumpSurfaceAngle = 78; jetMinJumpSpeed = 20; jetMaxJumpSpeed = 100; horizMaxSpeed = 80.0f; horizResistSpeed = 38.0f; horizResistFactor = 1.0f; upMaxSpeed = 80.0f; upResistSpeed = 38.0f; upResistFactor = 1.0f; minImpactSpeed = 25.0f; minLateralImpactSpeed = 25.0f; decalData = NULL; decalID = 0; decalOffset = 0.0f; actionCount = 0; lookAction = 0; dMemset(spineNode, 0, sizeof(spineNode)); pickupDelta = 0.0f; // size of bounding box boxSize.set(1.0f, 1.0f, 2.3f); crouchBoxSize.set(1.0f, 1.0f, 2.0f); proneBoxSize.set(1.0f, 2.3f, 1.0f); swimBoxSize.set(1.0f, 2.3f, 1.0f); // location of head, torso, legs boxHeadPercentage = 0.85f; boxTorsoPercentage = 0.55f; // damage locations boxHeadLeftPercentage = 0; boxHeadRightPercentage = 1; boxHeadBackPercentage = 0; boxHeadFrontPercentage = 1; for (S32 i = 0; i < MaxSounds; i++) INIT_ASSET_ARRAY(PlayerSound, i); footPuffEmitter = NULL; footPuffID = 0; footPuffNumParts = 15; footPuffRadius = .25f; dustEmitter = NULL; dustID = 0; splash = NULL; splashId = 0; splashVelocity = 1.0f; splashAngle = 45.0f; splashFreqMod = 300.0f; splashVelEpsilon = 0.25f; bubbleEmitTime = 0.4f; medSplashSoundVel = 2.0f; hardSplashSoundVel = 3.0f; exitSplashSoundVel = 2.0f; footSplashHeight = 0.1f; dMemset( splashEmitterList, 0, sizeof( splashEmitterList ) ); dMemset( splashEmitterIDList, 0, sizeof( splashEmitterIDList ) ); groundImpactMinSpeed = 10.0f; groundImpactShakeFreq.set( 10.0f, 10.0f, 10.0f ); groundImpactShakeAmp.set( 20.0f, 20.0f, 20.0f ); groundImpactShakeDuration = 1.0f; groundImpactShakeFalloff = 10.0f; // Air control airControl = 0.0f; jumpTowardsNormal = true; physicsPlayerType = StringTable->EmptyString(); dMemset( actionList, 0, sizeof(actionList) ); } bool PlayerData::preload(bool server, String &errorStr) { if(!Parent::preload(server, errorStr)) return false; for (U32 i = 0; i < MaxSounds; ++i) { _setPlayerSound(getPlayerSound(i), i); if (getPlayerSound(i) != StringTable->EmptyString()) { if (!getPlayerSoundProfile(i)) Con::errorf("PlayerData::Preload() - unable to find sfxProfile for asset %d %s", i, mPlayerSoundAssetId[i]); } } // runSurfaceCos = mCos(mDegToRad(runSurfaceAngle)); jumpSurfaceCos = mCos(mDegToRad(jumpSurfaceAngle)); if (minJumpEnergy < jumpEnergyDrain) minJumpEnergy = jumpEnergyDrain; // Jetting if (jetMinJumpEnergy < jetJumpEnergyDrain) jetMinJumpEnergy = jetJumpEnergyDrain; // Validate some of the data if (fallingSpeedThreshold > 0.0f) Con::printf("PlayerData:: Falling speed threshold should be downwards (negative)"); if (recoverDelay > (1 << RecoverDelayBits) - 1) { recoverDelay = (1 << RecoverDelayBits) - 1; Con::printf("PlayerData:: Recover delay exceeds range (0-%d)",recoverDelay); } if (jumpDelay > (1 << JumpDelayBits) - 1) { jumpDelay = (1 << JumpDelayBits) - 1; Con::printf("PlayerData:: Jump delay exceeds range (0-%d)",jumpDelay); } // If we don't have a shape don't crash out trying to // setup animations and sequences. if ( mShape ) { // Go ahead a pre-load the player shape TSShapeInstance* si = new TSShapeInstance(mShape, false); TSThread* thread = si->addThread(); // Extract ground transform velocity from animations // Get the named ones first so they can be indexed directly. ActionAnimation *dp = &actionList[0]; for (S32 i = 0; i < NumTableActionAnims; i++,dp++) { ActionAnimationDef *sp = &ActionAnimationList[i]; dp->name = sp->name; dp->dir.set(sp->dir.x,sp->dir.y,sp->dir.z); dp->sequence = mShape->findSequence(sp->name); // If this is a sprint action and is missing a sequence, attempt to use // the standard run ones. if(dp->sequence == -1 && i >= SprintRootAnim && i <= SprintRightAnim) { S32 offset = i-SprintRootAnim; ActionAnimationDef *standDef = &ActionAnimationList[RootAnim+offset]; dp->sequence = mShape->findSequence(standDef->name); } dp->velocityScale = true; dp->death = false; if (dp->sequence != -1) getGroundInfo(si,thread,dp); } for (S32 b = 0; b < mShape->sequences.size(); b++) { if (!isTableSequence(b)) { dp->sequence = b; dp->name = mShape->getName(mShape->sequences[b].nameIndex); dp->velocityScale = false; getGroundInfo(si,thread,dp++); } } actionCount = dp - actionList; AssertFatal(actionCount <= NumActionAnims, "Too many action animations!"); delete si; // Resolve lookAction index dp = &actionList[0]; String lookName("look"); for (S32 c = 0; c < actionCount; c++,dp++) if( dStricmp( dp->name, lookName ) == 0 ) lookAction = c; // Resolve spine spineNode[0] = mShape->findNode("Bip01 Pelvis"); spineNode[1] = mShape->findNode("Bip01 Spine"); spineNode[2] = mShape->findNode("Bip01 Spine1"); spineNode[3] = mShape->findNode("Bip01 Spine2"); spineNode[4] = mShape->findNode("Bip01 Neck"); spineNode[5] = mShape->findNode("Bip01 Head"); // Recoil animations recoilSequence[0] = mShape->findSequence("light_recoil"); recoilSequence[1] = mShape->findSequence("medium_recoil"); recoilSequence[2] = mShape->findSequence("heavy_recoil"); } // Convert pickupRadius to a delta of boundingBox // // NOTE: it is not really correct to precalculate a pickupRadius based // on boxSize since the actual player's bounds can vary by "pose". // F32 dr = (boxSize.x > boxSize.y)? boxSize.x: boxSize.y; if (pickupRadius < dr) pickupRadius = dr; else if (pickupRadius > 2.0f * dr) pickupRadius = 2.0f * dr; pickupDelta = (S32)(pickupRadius - dr); // Validate jump speed if (maxJumpSpeed <= minJumpSpeed) maxJumpSpeed = minJumpSpeed + 0.1f; // Load up all the emitters if (!footPuffEmitter && footPuffID != 0) if (!Sim::findObject(footPuffID, footPuffEmitter)) Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(footPuffEmitter): 0x%x", footPuffID); if (!decalData && decalID != 0 ) if (!Sim::findObject(decalID, decalData)) Con::errorf(ConsoleLogEntry::General, "PlayerData::preload Invalid packet, bad datablockId(decalData): 0x%x", decalID); if (!dustEmitter && dustID != 0 ) if (!Sim::findObject(dustID, dustEmitter)) Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(dustEmitter): 0x%x", dustID); for (S32 i=0; i<NUM_SPLASH_EMITTERS; i++) if( !splashEmitterList[i] && splashEmitterIDList[i] != 0 ) if( Sim::findObject( splashEmitterIDList[i], splashEmitterList[i] ) == false) Con::errorf(ConsoleLogEntry::General, "PlayerData::onAdd - Invalid packet, bad datablockId(particle emitter): 0x%x", splashEmitterIDList[i]); // First person mounted image shapes. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { bool shapeError = false; if (mShapeFPAssetId[i] != StringTable->EmptyString()) { if (!mShapeFP[i]) { errorStr = String::ToString("PlayerData: Couldn't load mounted image %d shape \"%s\"", i, mShapeFPAssetId[i]); return false; } if (!server && !mShapeFP[i]->preloadMaterialList(mShapeFP[i].getPath()) && NetConnection::filesWereDownloaded()) shapeError = true; if (computeCRC) { Con::printf("Validation required for mounted image %d shape: %s", i, mShapeFPAssetId[i]); Torque::FS::FileNodeRef fileRef = Torque::FS::GetFileNode(mShapeFP[i].getPath()); if (!fileRef) { errorStr = String::ToString("PlayerData: Mounted image %d loading failed, shape \"%s\" is not found.", i, mShapeFP[i].getPath().getFullPath().c_str()); return false; } if (server) mCRCFP[i] = fileRef->getChecksum(); else if (mCRCFP[i] != fileRef->getChecksum()) { errorStr = String::ToString("PlayerData: Mounted image %d shape \"%s\" does not match version on server.", i, mShapeFPAssetId[i]); return false; } } mValidShapeFP[i] = true; } } return true; } void PlayerData::getGroundInfo(TSShapeInstance* si, TSThread* thread,ActionAnimation *dp) { dp->death = !dStrnicmp(dp->name, "death", 5); if (dp->death) { // Death animations use roll frame-to-frame changes in ground transform into position dp->speed = 0.0f; dp->dir.set(0.0f, 0.0f, 0.0f); // Death animations MUST define ground transforms, so add dummy ones if required if (si->getShape()->sequences[dp->sequence].numGroundFrames == 0) si->getShape()->setSequenceGroundSpeed(dp->name, Point3F(0, 0, 0), Point3F(0, 0, 0)); } else { VectorF save = dp->dir; si->setSequence(thread,dp->sequence,0); si->animate(); si->advanceTime(1); si->animateGround(); si->getGroundTransform().getColumn(3,&dp->dir); if ((dp->speed = dp->dir.len()) < 0.01f) { // No ground displacement... In this case we'll use the // default table entry, if there is one. if (save.len() > 0.01f) { dp->dir = save; dp->speed = 1.0f; dp->velocityScale = false; } else dp->speed = 0.0f; } else dp->dir *= 1.0f / dp->speed; } } bool PlayerData::isTableSequence(S32 seq) { // The sequences from the table must already have // been loaded for this to work. for (S32 i = 0; i < NumTableActionAnims; i++) if (actionList[i].sequence == seq) return true; return false; } bool PlayerData::isJumpAction(U32 action) { return (action == JumpAnim || action == StandJumpAnim); } void PlayerData::initPersistFields() { addField( "pickupRadius", TypeF32, Offset(pickupRadius, PlayerData), "@brief Radius around the player to collide with Items in the scene (on server).\n\n" "Internally the pickupRadius is added to the larger side of the initial bounding box " "to determine the actual distance, to a maximum of 2 times the bounding box size. The " "initial bounding box is that used for the root pose, and therefore doesn't take into " "account the change in pose.\n"); addField( "maxTimeScale", TypeF32, Offset(maxTimeScale, PlayerData), "@brief Maximum time scale for action animations.\n\n" "If an action animation has a defined ground frame, it is automatically scaled to match the " "player's ground velocity. This field limits the maximum time scale used even if " "the player's velocity exceeds it." ); addGroup( "Camera" ); addField( "renderFirstPerson", TypeBool, Offset(renderFirstPerson, PlayerData), "@brief Flag controlling whether to render the player shape in first person view.\n\n" ); addField( "firstPersonShadows", TypeBool, Offset(firstPersonShadows, PlayerData), "@brief Forces shadows to be rendered in first person when renderFirstPerson is disabled. Defaults to false.\n\n" ); addField( "minLookAngle", TypeF32, Offset(minLookAngle, PlayerData), "@brief Lowest angle (in radians) the player can look.\n\n" "@note An angle of zero is straight ahead, with positive up and negative down." ); addField( "maxLookAngle", TypeF32, Offset(maxLookAngle, PlayerData), "@brief Highest angle (in radians) the player can look.\n\n" "@note An angle of zero is straight ahead, with positive up and negative down." ); addField( "maxFreelookAngle", TypeF32, Offset(maxFreelookAngle, PlayerData), "@brief Defines the maximum left and right angles (in radians) the player can " "look in freelook mode.\n\n" ); endGroup( "Camera" ); addGroup( "Movement" ); addField( "maxStepHeight", TypeF32, Offset(maxStepHeight, PlayerData), "@brief Maximum height the player can step up.\n\n" "The player will automatically step onto changes in ground height less " "than maxStepHeight. The player will collide with ground height changes " "greater than this." ); addField( "runForce", TypeF32, Offset(runForce, PlayerData), "@brief Force used to accelerate the player when running.\n\n" ); addField( "runEnergyDrain", TypeF32, Offset(runEnergyDrain, PlayerData), "@brief Energy value drained each tick that the player is moving.\n\n" "The player will not be able to move when his energy falls below " "minRunEnergy.\n" "@note Setting this to zero will disable any energy drain.\n" "@see minRunEnergy\n"); addField( "minRunEnergy", TypeF32, Offset(minRunEnergy, PlayerData), "@brief Minimum energy level required to run or swim.\n\n" "@see runEnergyDrain\n"); addField( "maxForwardSpeed", TypeF32, Offset(maxForwardSpeed, PlayerData), "@brief Maximum forward speed when running." ); addField( "maxBackwardSpeed", TypeF32, Offset(maxBackwardSpeed, PlayerData), "@brief Maximum backward speed when running." ); addField( "maxSideSpeed", TypeF32, Offset(maxSideSpeed, PlayerData), "@brief Maximum sideways speed when running." ); addField( "runSurfaceAngle", TypeF32, Offset(runSurfaceAngle, PlayerData), "@brief Maximum angle from vertical (in degrees) the player can run up.\n\n" ); addField( "minImpactSpeed", TypeF32, Offset(minImpactSpeed, PlayerData), "@brief Minimum impact speed to apply falling damage.\n\n" "This field also sets the minimum speed for the onImpact callback " "to be invoked.\n" "@see ShapeBaseData::onImpact()\n"); addField( "minLateralImpactSpeed", TypeF32, Offset(minLateralImpactSpeed, PlayerData), "@brief Minimum impact speed to apply non-falling damage.\n\n" "This field also sets the minimum speed for the onLateralImpact callback " "to be invoked.\n" "@see ShapeBaseData::onLateralImpact()\n"); addField( "horizMaxSpeed", TypeF32, Offset(horizMaxSpeed, PlayerData), "@brief Maximum horizontal speed.\n\n" "@note This limit is only enforced if the player's horizontal speed " "exceeds horizResistSpeed.\n" "@see horizResistSpeed\n" "@see horizResistFactor\n" ); addField( "horizResistSpeed", TypeF32, Offset(horizResistSpeed, PlayerData), "@brief Horizontal speed at which resistence will take place.\n\n" "@see horizMaxSpeed\n" "@see horizResistFactor\n" ); addField( "horizResistFactor", TypeF32, Offset(horizResistFactor, PlayerData), "@brief Factor of resistence once horizResistSpeed has been reached.\n\n" "@see horizMaxSpeed\n" "@see horizResistSpeed\n" ); addField( "upMaxSpeed", TypeF32, Offset(upMaxSpeed, PlayerData), "@brief Maximum upwards speed.\n\n" "@note This limit is only enforced if the player's upward speed exceeds " "upResistSpeed.\n" "@see upResistSpeed\n" "@see upResistFactor\n" ); addField( "upResistSpeed", TypeF32, Offset(upResistSpeed, PlayerData), "@brief Upwards speed at which resistence will take place.\n\n" "@see upMaxSpeed\n" "@see upResistFactor\n" ); addField( "upResistFactor", TypeF32, Offset(upResistFactor, PlayerData), "@brief Factor of resistence once upResistSpeed has been reached.\n\n" "@see upMaxSpeed\n" "@see upResistSpeed\n" ); endGroup( "Movement" ); addGroup( "Movement: Jumping" ); addField( "jumpForce", TypeF32, Offset(jumpForce, PlayerData), "@brief Force used to accelerate the player when a jump is initiated.\n\n" ); addField( "jumpEnergyDrain", TypeF32, Offset(jumpEnergyDrain, PlayerData), "@brief Energy level drained each time the player jumps.\n\n" "@note Setting this to zero will disable any energy drain\n" "@see minJumpEnergy\n"); addField( "minJumpEnergy", TypeF32, Offset(minJumpEnergy, PlayerData), "@brief Minimum energy level required to jump.\n\n" "@see jumpEnergyDrain\n"); addField( "minJumpSpeed", TypeF32, Offset(minJumpSpeed, PlayerData), "@brief Minimum speed needed to jump.\n\n" "If the player's own z velocity is greater than this, then it is used to scale " "the jump speed, up to maxJumpSpeed.\n" "@see maxJumpSpeed\n"); addField( "maxJumpSpeed", TypeF32, Offset(maxJumpSpeed, PlayerData), "@brief Maximum vertical speed before the player can no longer jump.\n\n" ); addField( "jumpSurfaceAngle", TypeF32, Offset(jumpSurfaceAngle, PlayerData), "@brief Angle from vertical (in degrees) where the player can jump.\n\n" ); addField( "jumpDelay", TypeS32, Offset(jumpDelay, PlayerData), "@brief Delay time in number of ticks ticks between jumps.\n\n" ); addField( "airControl", TypeF32, Offset(airControl, PlayerData), "@brief Amount of movement control the player has when in the air.\n\n" "This is applied as a multiplier to the player's x and y motion.\n"); addField( "jumpTowardsNormal", TypeBool, Offset(jumpTowardsNormal, PlayerData), "@brief Controls the direction of the jump impulse.\n" "When false, jumps are always in the vertical (+Z) direction. When true " "jumps are in the direction of the ground normal so long as the player is not " "directly facing the surface. If the player is directly facing the surface, then " "they will jump straight up.\n" ); endGroup( "Movement: Jumping" ); addGroup( "Movement: Sprinting" ); addField( "sprintForce", TypeF32, Offset(sprintForce, PlayerData), "@brief Force used to accelerate the player when sprinting.\n\n" ); addField( "sprintEnergyDrain", TypeF32, Offset(sprintEnergyDrain, PlayerData), "@brief Energy value drained each tick that the player is sprinting.\n\n" "The player will not be able to move when his energy falls below " "sprintEnergyDrain.\n" "@note Setting this to zero will disable any energy drain.\n" "@see minSprintEnergy\n"); addField( "minSprintEnergy", TypeF32, Offset(minSprintEnergy, PlayerData), "@brief Minimum energy level required to sprint.\n\n" "@see sprintEnergyDrain\n"); addField( "maxSprintForwardSpeed", TypeF32, Offset(maxSprintForwardSpeed, PlayerData), "@brief Maximum forward speed when sprinting." ); addField( "maxSprintBackwardSpeed", TypeF32, Offset(maxSprintBackwardSpeed, PlayerData), "@brief Maximum backward speed when sprinting." ); addField( "maxSprintSideSpeed", TypeF32, Offset(maxSprintSideSpeed, PlayerData), "@brief Maximum sideways speed when sprinting." ); addField( "sprintStrafeScale", TypeF32, Offset(sprintStrafeScale, PlayerData), "@brief Amount to scale strafing motion vector while sprinting." ); addField( "sprintYawScale", TypeF32, Offset(sprintYawScale, PlayerData), "@brief Amount to scale yaw motion while sprinting." ); addField( "sprintPitchScale", TypeF32, Offset(sprintPitchScale, PlayerData), "@brief Amount to scale pitch motion while sprinting." ); addField( "sprintCanJump", TypeBool, Offset(sprintCanJump, PlayerData), "@brief Can the player jump while sprinting." ); endGroup( "Movement: Sprinting" ); addGroup( "Movement: Swimming" ); addField( "swimForce", TypeF32, Offset(swimForce, PlayerData), "@brief Force used to accelerate the player when swimming.\n\n" ); addField( "maxUnderwaterForwardSpeed", TypeF32, Offset(maxUnderwaterForwardSpeed, PlayerData), "@brief Maximum forward speed when underwater.\n\n" ); addField( "maxUnderwaterBackwardSpeed", TypeF32, Offset(maxUnderwaterBackwardSpeed, PlayerData), "@brief Maximum backward speed when underwater.\n\n" ); addField( "maxUnderwaterSideSpeed", TypeF32, Offset(maxUnderwaterSideSpeed, PlayerData), "@brief Maximum sideways speed when underwater.\n\n" ); endGroup( "Movement: Swimming" ); addGroup( "Movement: Crouching" ); addField( "crouchForce", TypeF32, Offset(crouchForce, PlayerData), "@brief Force used to accelerate the player when crouching.\n\n" ); addField( "maxCrouchForwardSpeed", TypeF32, Offset(maxCrouchForwardSpeed, PlayerData), "@brief Maximum forward speed when crouching.\n\n" ); addField( "maxCrouchBackwardSpeed", TypeF32, Offset(maxCrouchBackwardSpeed, PlayerData), "@brief Maximum backward speed when crouching.\n\n" ); addField( "maxCrouchSideSpeed", TypeF32, Offset(maxCrouchSideSpeed, PlayerData), "@brief Maximum sideways speed when crouching.\n\n" ); endGroup( "Movement: Crouching" ); addGroup( "Movement: Prone" ); addField( "proneForce", TypeF32, Offset(proneForce, PlayerData), "@brief Force used to accelerate the player when prone (laying down).\n\n" ); addField( "maxProneForwardSpeed", TypeF32, Offset(maxProneForwardSpeed, PlayerData), "@brief Maximum forward speed when prone (laying down).\n\n" ); addField( "maxProneBackwardSpeed", TypeF32, Offset(maxProneBackwardSpeed, PlayerData), "@brief Maximum backward speed when prone (laying down).\n\n" ); addField( "maxProneSideSpeed", TypeF32, Offset(maxProneSideSpeed, PlayerData), "@brief Maximum sideways speed when prone (laying down).\n\n" ); endGroup( "Movement: Prone" ); addGroup( "Movement: Jetting" ); addField( "jetJumpForce", TypeF32, Offset(jetJumpForce, PlayerData), "@brief Force used to accelerate the player when a jet jump is initiated.\n\n" ); addField( "jetJumpEnergyDrain", TypeF32, Offset(jetJumpEnergyDrain, PlayerData), "@brief Energy level drained each time the player jet jumps.\n\n" "@note Setting this to zero will disable any energy drain\n" "@see jetMinJumpEnergy\n"); addField( "jetMinJumpEnergy", TypeF32, Offset(jetMinJumpEnergy, PlayerData), "@brief Minimum energy level required to jet jump.\n\n" "@see jetJumpEnergyDrain\n"); addField( "jetMinJumpSpeed", TypeF32, Offset(jetMinJumpSpeed, PlayerData), "@brief Minimum speed needed to jet jump.\n\n" "If the player's own z velocity is greater than this, then it is used to scale " "the jet jump speed, up to jetMaxJumpSpeed.\n" "@see jetMaxJumpSpeed\n"); addField( "jetMaxJumpSpeed", TypeF32, Offset(jetMaxJumpSpeed, PlayerData), "@brief Maximum vertical speed before the player can no longer jet jump.\n\n" ); addField( "jetJumpSurfaceAngle", TypeF32, Offset(jetJumpSurfaceAngle, PlayerData), "@brief Angle from vertical (in degrees) where the player can jet jump.\n\n" ); endGroup( "Movement: Jetting" ); addGroup( "Falling" ); addField( "fallingSpeedThreshold", TypeF32, Offset(fallingSpeedThreshold, PlayerData), "@brief Downward speed at which we consider the player falling.\n\n" ); addField( "recoverDelay", TypeS32, Offset(recoverDelay, PlayerData), "@brief Number of ticks for the player to recover from falling.\n\n" ); addField( "recoverRunForceScale", TypeF32, Offset(recoverRunForceScale, PlayerData), "@brief Scale factor applied to runForce while in the recover state.\n\n" "This can be used to temporarily slow the player's movement after a fall, or " "prevent the player from moving at all if set to zero.\n" ); addField( "landSequenceTime", TypeF32, Offset(landSequenceTime, PlayerData), "@brief Time of land sequence play back when using new recover system.\n\n" "If greater than 0 then the legacy fall recovery system will be bypassed " "in favour of just playing the player's land sequence. The time to " "recover from a fall then becomes this parameter's time and the land " "sequence's playback will be scaled to match.\n" "@see transitionToLand\n" ); addField( "transitionToLand", TypeBool, Offset(transitionToLand, PlayerData), "@brief When going from a fall to a land, should we transition between the two.\n\n" "@note Only takes affect when landSequenceTime is greater than 0.\n" "@see landSequenceTime\n" ); endGroup( "Falling" ); addGroup( "Collision" ); addField( "boundingBox", TypePoint3F, Offset(boxSize, PlayerData), "@brief Size of the bounding box used by the player for collision.\n\n" "Dimensions are given as \"width depth height\"." ); addField( "crouchBoundingBox", TypePoint3F, Offset(crouchBoxSize, PlayerData), "@brief Collision bounding box used when the player is crouching.\n\n" "@see boundingBox" ); addField( "proneBoundingBox", TypePoint3F, Offset(proneBoxSize, PlayerData), "@brief Collision bounding box used when the player is prone (laying down).\n\n" "@see boundingBox" ); addField( "swimBoundingBox", TypePoint3F, Offset(swimBoxSize, PlayerData), "@brief Collision bounding box used when the player is swimming.\n\n" "@see boundingBox" ); addField( "boxHeadPercentage", TypeF32, Offset(boxHeadPercentage, PlayerData), "@brief Percentage of the player's bounding box height that represents the head.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); addField( "boxTorsoPercentage", TypeF32, Offset(boxTorsoPercentage, PlayerData), "@brief Percentage of the player's bounding box height that represents the torso.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); addField( "boxHeadLeftPercentage", TypeF32, Offset(boxHeadLeftPercentage, PlayerData), "@brief Percentage of the player's bounding box width that represents the left side of the head.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); addField( "boxHeadRightPercentage", TypeF32, Offset(boxHeadRightPercentage, PlayerData), "@brief Percentage of the player's bounding box width that represents the right side of the head.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); addField( "boxHeadBackPercentage", TypeF32, Offset(boxHeadBackPercentage, PlayerData), "@brief Percentage of the player's bounding box depth that represents the back side of the head.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); addField( "boxHeadFrontPercentage", TypeF32, Offset(boxHeadFrontPercentage, PlayerData), "@brief Percentage of the player's bounding box depth that represents the front side of the head.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); endGroup( "Collision" ); addGroup( "Interaction: Footsteps" ); addField( "footPuffEmitter", TYPEID< ParticleEmitterData >(), Offset(footPuffEmitter, PlayerData), "@brief Particle emitter used to generate footpuffs (particles created as the player " "walks along the ground).\n\n" "@note The generation of foot puffs requires the appropriate triggeres to be defined in the " "player's animation sequences. Without these, no foot puffs will be generated.\n"); addField( "footPuffNumParts", TypeS32, Offset(footPuffNumParts, PlayerData), "@brief Number of footpuff particles to generate each step.\n\n" "Each foot puff is randomly placed within the defined foot puff radius. This " "includes having footPuffNumParts set to one.\n" "@see footPuffRadius\n"); addField( "footPuffRadius", TypeF32, Offset(footPuffRadius, PlayerData), "@brief Particle creation radius for footpuff particles.\n\n" "This is applied to each foot puff particle, even if footPuffNumParts is set to one. So " "set this value to zero if you want a single foot puff placed at exactly the same location " "under the player each time.\n"); addField( "dustEmitter", TYPEID< ParticleEmitterData >(), Offset(dustEmitter, PlayerData), "@brief Emitter used to generate dust particles.\n\n" "@note Currently unused." ); addField( "decalData", TYPEID< DecalData >(), Offset(decalData, PlayerData), "@brief Decal to place on the ground for player footsteps.\n\n" ); addField( "decalOffset",TypeF32, Offset(decalOffset, PlayerData), "@brief Distance from the center of the model to the right foot.\n\n" "While this defines the distance to the right foot, it is also used to place " "the left foot decal as well. Just on the opposite side of the player." ); endGroup( "Interaction: Footsteps" ); addGroup( "Interaction: Sounds" ); INITPERSISTFIELD_SOUNDASSET_ENUMED(PlayerSound, playerSoundsEnum, PlayerData::Sounds::MaxSounds, PlayerData, "Sounds related to player interaction."); endGroup( "Interaction: Sounds" ); addGroup( "Interaction: Splashes" ); addField( "splash", TYPEID< SplashData >(), Offset(splash, PlayerData), "@brief SplashData datablock used to create splashes when the player moves " "through water.\n\n" ); addField( "splashVelocity", TypeF32, Offset(splashVelocity, PlayerData), "@brief Minimum velocity when moving through water to generate splashes.\n\n" ); addField( "splashAngle", TypeF32, Offset(splashAngle, PlayerData), "@brief Maximum angle (in degrees) from pure vertical movement in water to " "generate splashes.\n\n" ); addField( "splashFreqMod", TypeF32, Offset(splashFreqMod, PlayerData), "@brief Multipled by speed to determine the number of splash particles to generate.\n\n" ); addField( "splashVelEpsilon", TypeF32, Offset(splashVelEpsilon, PlayerData), "@brief Minimum speed to generate splash particles.\n\n" ); addField( "bubbleEmitTime", TypeF32, Offset(bubbleEmitTime, PlayerData), "@brief Time in seconds to generate bubble particles after entering the water.\n\n" ); addField( "splashEmitter", TYPEID< ParticleEmitterData >(), Offset(splashEmitterList, PlayerData), NUM_SPLASH_EMITTERS, "@brief Particle emitters used to generate splash particles.\n\n" ); addField( "footstepSplashHeight", TypeF32, Offset(footSplashHeight, PlayerData), "@brief Water coverage level to choose between FootShallowSound and FootWadingSound.\n\n" "@see FootShallowSound\n" "@see FootWadingSound\n"); addField( "mediumSplashSoundVelocity", TypeF32, Offset(medSplashSoundVel, PlayerData), "@brief Minimum velocity when entering the water for choosing between the impactWaterEasy and " "impactWaterMedium sounds to play.\n\n" "@see impactWaterEasy\n" "@see impactWaterMedium\n" ); addField( "hardSplashSoundVelocity", TypeF32, Offset(hardSplashSoundVel, PlayerData), "@brief Minimum velocity when entering the water for choosing between the impactWaterMedium and " "impactWaterHard sound to play.\n\n" "@see impactWaterMedium\n" "@see impactWaterHard\n" ); addField( "exitSplashSoundVelocity", TypeF32, Offset(exitSplashSoundVel, PlayerData), "@brief Minimum velocity when leaving the water for the exitingWater sound to " "play.\n\n" "@see exitingWater"); endGroup( "Interaction: Splashes" ); addGroup( "Interaction: Ground Impact" ); addField( "groundImpactMinSpeed", TypeF32, Offset(groundImpactMinSpeed, PlayerData), "@brief Minimum falling impact speed to apply damage and initiate the camera " "shaking effect.\n\n" ); addField( "groundImpactShakeFreq", TypePoint3F, Offset(groundImpactShakeFreq, PlayerData), "@brief Frequency of the camera shake effect after falling.\n\n" "This is how fast to shake the camera.\n"); addField( "groundImpactShakeAmp", TypePoint3F, Offset(groundImpactShakeAmp, PlayerData), "@brief Amplitude of the camera shake effect after falling.\n\n" "This is how much to shake the camera.\n"); addField( "groundImpactShakeDuration", TypeF32, Offset(groundImpactShakeDuration, PlayerData), "@brief Duration (in seconds) of the camera shake effect after falling.\n\n" "This is how long to shake the camera.\n"); addField( "groundImpactShakeFalloff", TypeF32, Offset(groundImpactShakeFalloff, PlayerData), "@brief Falloff factor of the camera shake effect after falling.\n\n" "This is how to fade the camera shake over the duration.\n"); endGroup( "Interaction: Ground Impact" ); addGroup( "Physics" ); // PhysicsPlayer addField( "physicsPlayerType", TypeString, Offset(physicsPlayerType, PlayerData), "@brief Specifies the type of physics used by the player.\n\n" "This depends on the physics module used. An example is 'Capsule'.\n" "@note Not current used.\n"); endGroup( "Physics" ); addGroup( "First Person Arms" ); addField( "imageAnimPrefixFP", TypeCaseString, Offset(imageAnimPrefixFP, PlayerData), "@brief Optional prefix to all mounted image animation sequences in first person.\n\n" "This defines a prefix that will be added when looking up mounted image " "animation sequences while in first person. It allows for the customization " "of a first person image based on the type of player.\n"); // Mounted images arrays addArray( "Mounted Images", ShapeBase::MaxMountedImages ); addProtectedField("shapeNameFP", TypeShapeFilename, Offset(mShapeFPName, PlayerData), &_setShapeFPData, &defaultProtectedGetFn, ShapeBase::MaxMountedImages, "@brief File name of this player's shape that will be used in conjunction with the corresponding mounted image.\n\n" "These optional parameters correspond to each mounted image slot to indicate a shape that is rendered " "in addition to the mounted image shape. Typically these are a player's arms (or arm) that is " "animated along with the mounted image's state animation sequences.\n", AbstractClassRep::FIELD_HideInInspectors); INITPERSISTFIELD_SHAPEASSET_ARRAY(ShapeFP, ShapeBase::MaxMountedImages, PlayerData, "@brief File name of this player's shape that will be used in conjunction with the corresponding mounted image.\n\n" "These optional parameters correspond to each mounted image slot to indicate a shape that is rendered " "in addition to the mounted image shape. Typically these are a player's arms (or arm) that is " "animated along with the mounted image's state animation sequences.\n"); endArray( "Mounted Images" ); endGroup( "First Person Arms" ); addGroup( "Third Person" ); addField( "imageAnimPrefix", TypeCaseString, Offset(imageAnimPrefix, PlayerData), "@brief Optional prefix to all mounted image animation sequences in third person.\n\n" "This defines a prefix that will be added when looking up mounted image " "animation sequences while in third person. It allows for the customization " "of a third person image based on the type of player.\n"); addField( "allowImageStateAnimation", TypeBool, Offset(allowImageStateAnimation, PlayerData), "@brief Allow mounted images to request a sequence be played on the Player.\n\n" "When true a new thread is added to the player to allow for " "mounted images to request a sequence be played on the player " "through the image's state machine. It is only optional so " "that we don't create a TSThread on the player if we don't " "need to.\n"); endGroup( "Third Person" ); Parent::initPersistFields(); } void PlayerData::packData(BitStream* stream) { Parent::packData(stream); stream->writeFlag(renderFirstPerson); stream->writeFlag(firstPersonShadows); stream->write(minLookAngle); stream->write(maxLookAngle); stream->write(maxFreelookAngle); stream->write(maxTimeScale); stream->write(mass); stream->write(maxEnergy); stream->write(drag); stream->write(density); stream->write(maxStepHeight); stream->write(runForce); stream->write(runEnergyDrain); stream->write(minRunEnergy); stream->write(maxForwardSpeed); stream->write(maxBackwardSpeed); stream->write(maxSideSpeed); stream->write(runSurfaceAngle); stream->write(fallingSpeedThreshold); stream->write(recoverDelay); stream->write(recoverRunForceScale); stream->write(landSequenceTime); stream->write(transitionToLand); // Jumping stream->write(jumpForce); stream->write(jumpEnergyDrain); stream->write(minJumpEnergy); stream->write(minJumpSpeed); stream->write(maxJumpSpeed); stream->write(jumpSurfaceAngle); stream->writeInt(jumpDelay,JumpDelayBits); // Sprinting stream->write(sprintForce); stream->write(sprintEnergyDrain); stream->write(minSprintEnergy); stream->write(maxSprintForwardSpeed); stream->write(maxSprintBackwardSpeed); stream->write(maxSprintSideSpeed); stream->write(sprintStrafeScale); stream->write(sprintYawScale); stream->write(sprintPitchScale); stream->writeFlag(sprintCanJump); // Swimming stream->write(swimForce); stream->write(maxUnderwaterForwardSpeed); stream->write(maxUnderwaterBackwardSpeed); stream->write(maxUnderwaterSideSpeed); // Crouching stream->write(crouchForce); stream->write(maxCrouchForwardSpeed); stream->write(maxCrouchBackwardSpeed); stream->write(maxCrouchSideSpeed); // Prone stream->write(proneForce); stream->write(maxProneForwardSpeed); stream->write(maxProneBackwardSpeed); stream->write(maxProneSideSpeed); // Jetting stream->write(jetJumpForce); stream->write(jetJumpEnergyDrain); stream->write(jetMinJumpEnergy); stream->write(jetMinJumpSpeed); stream->write(jetMaxJumpSpeed); stream->write(jetJumpSurfaceAngle); stream->write(horizMaxSpeed); stream->write(horizResistSpeed); stream->write(horizResistFactor); stream->write(upMaxSpeed); stream->write(upResistSpeed); stream->write(upResistFactor); stream->write(splashVelocity); stream->write(splashAngle); stream->write(splashFreqMod); stream->write(splashVelEpsilon); stream->write(bubbleEmitTime); stream->write(medSplashSoundVel); stream->write(hardSplashSoundVel); stream->write(exitSplashSoundVel); stream->write(footSplashHeight); // Don't need damage scale on the client stream->write(minImpactSpeed); stream->write(minLateralImpactSpeed); for (U32 i = 0; i < MaxSounds; i++) PACKDATA_ASSET_ARRAY(PlayerSound, i); mathWrite(*stream, boxSize); mathWrite(*stream, crouchBoxSize); mathWrite(*stream, proneBoxSize); mathWrite(*stream, swimBoxSize); if( stream->writeFlag( footPuffEmitter ) ) { stream->writeRangedU32( footPuffEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast ); } stream->write( footPuffNumParts ); stream->write( footPuffRadius ); if( stream->writeFlag( decalData ) ) { stream->writeRangedU32( decalData->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast ); } stream->write(decalOffset); if( stream->writeFlag( dustEmitter ) ) { stream->writeRangedU32( dustEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast ); } if (stream->writeFlag( splash )) { stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast); } for( U32 i=0; i<NUM_SPLASH_EMITTERS; i++ ) { if( stream->writeFlag( splashEmitterList[i] != NULL ) ) { stream->writeRangedU32( splashEmitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast ); } } stream->write(groundImpactMinSpeed); stream->write(groundImpactShakeFreq.x); stream->write(groundImpactShakeFreq.y); stream->write(groundImpactShakeFreq.z); stream->write(groundImpactShakeAmp.x); stream->write(groundImpactShakeAmp.y); stream->write(groundImpactShakeAmp.z); stream->write(groundImpactShakeDuration); stream->write(groundImpactShakeFalloff); // Air control stream->write(airControl); // Jump off at normal stream->writeFlag(jumpTowardsNormal); stream->writeString(physicsPlayerType); // Third person mounted image shapes stream->writeString(imageAnimPrefix); stream->writeFlag(allowImageStateAnimation); // First person mounted image shapes stream->writeString(imageAnimPrefixFP); for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { PACKDATA_ASSET_ARRAY(ShapeFP, i); // computeCRC is handled in ShapeBaseData if (computeCRC) { stream->write(mCRCFP[i]); } } } void PlayerData::unpackData(BitStream* stream) { Parent::unpackData(stream); renderFirstPerson = stream->readFlag(); firstPersonShadows = stream->readFlag(); stream->read(&minLookAngle); stream->read(&maxLookAngle); stream->read(&maxFreelookAngle); stream->read(&maxTimeScale); stream->read(&mass); stream->read(&maxEnergy); stream->read(&drag); stream->read(&density); stream->read(&maxStepHeight); stream->read(&runForce); stream->read(&runEnergyDrain); stream->read(&minRunEnergy); stream->read(&maxForwardSpeed); stream->read(&maxBackwardSpeed); stream->read(&maxSideSpeed); stream->read(&runSurfaceAngle); stream->read(&fallingSpeedThreshold); stream->read(&recoverDelay); stream->read(&recoverRunForceScale); stream->read(&landSequenceTime); stream->read(&transitionToLand); // Jumping stream->read(&jumpForce); stream->read(&jumpEnergyDrain); stream->read(&minJumpEnergy); stream->read(&minJumpSpeed); stream->read(&maxJumpSpeed); stream->read(&jumpSurfaceAngle); jumpDelay = stream->readInt(JumpDelayBits); // Sprinting stream->read(&sprintForce); stream->read(&sprintEnergyDrain); stream->read(&minSprintEnergy); stream->read(&maxSprintForwardSpeed); stream->read(&maxSprintBackwardSpeed); stream->read(&maxSprintSideSpeed); stream->read(&sprintStrafeScale); stream->read(&sprintYawScale); stream->read(&sprintPitchScale); sprintCanJump = stream->readFlag(); // Swimming stream->read(&swimForce); stream->read(&maxUnderwaterForwardSpeed); stream->read(&maxUnderwaterBackwardSpeed); stream->read(&maxUnderwaterSideSpeed); // Crouching stream->read(&crouchForce); stream->read(&maxCrouchForwardSpeed); stream->read(&maxCrouchBackwardSpeed); stream->read(&maxCrouchSideSpeed); // Prone stream->read(&proneForce); stream->read(&maxProneForwardSpeed); stream->read(&maxProneBackwardSpeed); stream->read(&maxProneSideSpeed); // Jetting stream->read(&jetJumpForce); stream->read(&jetJumpEnergyDrain); stream->read(&jetMinJumpEnergy); stream->read(&jetMinJumpSpeed); stream->read(&jetMaxJumpSpeed); stream->read(&jetJumpSurfaceAngle); stream->read(&horizMaxSpeed); stream->read(&horizResistSpeed); stream->read(&horizResistFactor); stream->read(&upMaxSpeed); stream->read(&upResistSpeed); stream->read(&upResistFactor); stream->read(&splashVelocity); stream->read(&splashAngle); stream->read(&splashFreqMod); stream->read(&splashVelEpsilon); stream->read(&bubbleEmitTime); stream->read(&medSplashSoundVel); stream->read(&hardSplashSoundVel); stream->read(&exitSplashSoundVel); stream->read(&footSplashHeight); stream->read(&minImpactSpeed); stream->read(&minLateralImpactSpeed); for (U32 i = 0; i < MaxSounds; i++) UNPACKDATA_ASSET_ARRAY(PlayerSound, i); mathRead(*stream, &boxSize); mathRead(*stream, &crouchBoxSize); mathRead(*stream, &proneBoxSize); mathRead(*stream, &swimBoxSize); if( stream->readFlag() ) { footPuffID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast); } stream->read(&footPuffNumParts); stream->read(&footPuffRadius); if( stream->readFlag() ) { decalID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast); } stream->read(&decalOffset); if( stream->readFlag() ) { dustID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast); } if (stream->readFlag()) { splashId = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast ); } for( U32 i=0; i<NUM_SPLASH_EMITTERS; i++ ) { if( stream->readFlag() ) { splashEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast ); } } stream->read(&groundImpactMinSpeed); stream->read(&groundImpactShakeFreq.x); stream->read(&groundImpactShakeFreq.y); stream->read(&groundImpactShakeFreq.z); stream->read(&groundImpactShakeAmp.x); stream->read(&groundImpactShakeAmp.y); stream->read(&groundImpactShakeAmp.z); stream->read(&groundImpactShakeDuration); stream->read(&groundImpactShakeFalloff); // Air control stream->read(&airControl); // Jump off at normal jumpTowardsNormal = stream->readFlag(); physicsPlayerType = stream->readSTString(); // Third person mounted image shapes imageAnimPrefix = stream->readSTString(); allowImageStateAnimation = stream->readFlag(); // First person mounted image shapes imageAnimPrefixFP = stream->readSTString(); for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { UNPACKDATA_ASSET_ARRAY(ShapeFP, i); // computeCRC is handled in ShapeBaseData if (computeCRC) { stream->read(&(mCRCFP[i])); } } } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- ImplementEnumType( PlayerPose, "@brief The pose of the Player.\n\n" "@ingroup gameObjects\n\n") { Player::StandPose, "Stand", "Standard movement pose.\n" }, { Player::SprintPose, "Sprint", "Sprinting pose.\n" }, { Player::CrouchPose, "Crouch", "Crouch pose.\n" }, { Player::PronePose, "Prone", "Prone pose.\n" }, { Player::SwimPose, "Swim", "Swimming pose.\n" }, EndImplementEnumType; //---------------------------------------------------------------------------- IMPLEMENT_CO_NETOBJECT_V1(Player); ConsoleDocClass( Player, "@ingroup gameObjects\n" ); //---------------------------------------------------------------------------- Player::Player() { mTypeMask |= PlayerObjectType | DynamicShapeObjectType; mDelta.pos = mAnchorPoint = Point3F(0,0,100); mDelta.rot = mDelta.head = Point3F(0,0,0); mDelta.rotOffset.set(0.0f,0.0f,0.0f); mDelta.warpOffset.set(0.0f,0.0f,0.0f); mDelta.posVec.set(0.0f,0.0f,0.0f); mDelta.rotVec.set(0.0f,0.0f,0.0f); mDelta.headVec.set(0.0f,0.0f,0.0f); mDelta.warpTicks = 0; mDelta.dt = 1.0f; mDelta.move = NullMove; mPredictionCount = sMaxPredictionTicks; mObjToWorld.setColumn(3, mDelta.pos); mRot = mDelta.rot; mHead = mDelta.head; mVelocity.set(0.0f, 0.0f, 0.0f); mDataBlock = 0; mHeadHThread = mHeadVThread = mRecoilThread = mImageStateThread = 0; mArmAnimation.action = PlayerData::NullAnimation; mArmAnimation.thread = 0; mActionAnimation.action = PlayerData::NullAnimation; mActionAnimation.thread = 0; mActionAnimation.delayTicks = 0; mActionAnimation.forward = true; mActionAnimation.firstPerson = false; //mActionAnimation.time = 1.0f; //ActionAnimation::Scale; mActionAnimation.waitForEnd = false; mActionAnimation.holdAtEnd = false; mActionAnimation.animateOnServer = false; mActionAnimation.atEnd = false; mState = MoveState; mJetting = false; mFalling = false; mSwimming = false; mInWater = false; mPose = StandPose; mContactTimer = 0; mJumpDelay = 0; mJumpSurfaceLastContact = 0; mJumpSurfaceNormal.set(0.0f, 0.0f, 1.0f); mControlObject = 0; dMemset( mSplashEmitter, 0, sizeof( mSplashEmitter ) ); mUseHeadZCalc = true; allowAllPoses(); mImpactSound = 0; mRecoverTicks = 0; mReversePending = 0; mLastPos.set( 0.0f, 0.0f, 0.0f ); mMoveBubbleSound = 0; mWaterBreathSound = 0; mConvex.init(this); mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f); mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f); mWeaponBackFraction = 0.0f; mInMissionArea = true; mBubbleEmitterTime = 10.0; mLastWaterPos.set( 0.0, 0.0, 0.0 ); mMountPending = 0; mPhysicsRep = NULL; for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { mShapeFPInstance[i] = 0; mShapeFPAmbientThread[i] = 0; mShapeFPVisThread[i] = 0; mShapeFPAnimThread[i] = 0; mShapeFPFlashThread[i] = 0; mShapeFPSpinThread[i] = 0; } mLastAbsoluteYaw = 0.0f; mLastAbsolutePitch = 0.0f; mLastAbsoluteRoll = 0.0f; afx_init(); } Player::~Player() { for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { delete mShapeFPInstance[i]; mShapeFPInstance[i] = 0; } } //---------------------------------------------------------------------------- bool Player::onAdd() { ActionAnimation serverAnim = mActionAnimation; if(!Parent::onAdd() || !mDataBlock) return false; mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f); mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f); addToScene(); // Make sure any state and animation passed from the server // in the initial update is set correctly. ActionState state = mState; mState = NullState; setState(state); setPose(StandPose); if (serverAnim.action != PlayerData::NullAnimation) { setActionThread(serverAnim.action, true, serverAnim.holdAtEnd, true, false, true); if (serverAnim.atEnd) { mShapeInstance->clearTransition(mActionAnimation.thread); mShapeInstance->setPos(mActionAnimation.thread, mActionAnimation.forward ? 1.0f : 0.0f); if (inDeathAnim()) mDeath.lastPos = 1.0f; } // We have to leave them sitting for a while since mounts don't come through right // away (and sometimes not for a while). Still going to let this time out because // I'm not sure if we're guaranteed another anim will come through and cancel. if (!isServerObject() && inSittingAnim()) mMountPending = (S32) sMountPendingTickWait; else mMountPending = 0; } if (mArmAnimation.action != PlayerData::NullAnimation) setArmThread(mArmAnimation.action); // if (isServerObject()) { scriptOnAdd(); } else { U32 i; for( i=0; i<PlayerData::NUM_SPLASH_EMITTERS; i++ ) { if ( mDataBlock->splashEmitterList[i] ) { mSplashEmitter[i] = new ParticleEmitter; mSplashEmitter[i]->onNewDataBlock( mDataBlock->splashEmitterList[i], false ); if( !mSplashEmitter[i]->registerObject() ) { Con::warnf( ConsoleLogEntry::General, "Could not register splash emitter for class: %s", mDataBlock->getName() ); mSplashEmitter[i].getPointer()->destroySelf(); mSplashEmitter[i] = NULL; } } } mLastWaterPos = getPosition(); // clear out all camera effects gCamFXMgr.clear(); } if ( PHYSICSMGR ) { PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" ); mPhysicsRep = PHYSICSMGR->createPlayer(); mPhysicsRep->init( mDataBlock->physicsPlayerType, mDataBlock->boxSize, mDataBlock->runSurfaceCos, mDataBlock->maxStepHeight, this, world ); mPhysicsRep->setTransform( getTransform() ); } return true; } void Player::onRemove() { setControlObject(0); scriptOnRemove(); removeFromScene(); if ( isGhost() ) { SFX_DELETE( mMoveBubbleSound ); SFX_DELETE( mWaterBreathSound ); } U32 i; for( i=0; i<PlayerData::NUM_SPLASH_EMITTERS; i++ ) { if( mSplashEmitter[i] ) { mSplashEmitter[i]->deleteWhenEmpty(); mSplashEmitter[i] = NULL; } } mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f); mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f); SAFE_DELETE( mPhysicsRep ); Parent::onRemove(); } void Player::onScaleChanged() { const Point3F& scale = getScale(); mScaledBox = mObjBox; mScaledBox.minExtents.convolve( scale ); mScaledBox.maxExtents.convolve( scale ); } //---------------------------------------------------------------------------- bool Player::onNewDataBlock( GameBaseData *dptr, bool reload ) { PlayerData* prevData = mDataBlock; mDataBlock = dynamic_cast<PlayerData*>(dptr); if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) ) return false; // Player requires a shape instance. if ( mShapeInstance == NULL ) return false; // Initialize arm thread, preserve arm sequence from last datablock. // Arm animation can be from last datablock, or sent from the server. U32 prevAction = mArmAnimation.action; mArmAnimation.action = PlayerData::NullAnimation; if (mDataBlock->lookAction) { mArmAnimation.thread = mShapeInstance->addThread(); mShapeInstance->setTimeScale(mArmAnimation.thread,0); if (prevData) { if (prevAction != prevData->lookAction && prevAction != PlayerData::NullAnimation) setArmThread(prevData->actionList[prevAction].name); prevAction = PlayerData::NullAnimation; } if (mArmAnimation.action == PlayerData::NullAnimation) { mArmAnimation.action = (prevAction != PlayerData::NullAnimation)? prevAction: mDataBlock->lookAction; mShapeInstance->setSequence(mArmAnimation.thread, mDataBlock->actionList[mArmAnimation.action].sequence,0); } } else mArmAnimation.thread = 0; // Initialize head look thread TSShape const* shape = mShapeInstance->getShape(); S32 headSeq = shape->findSequence("head"); if (headSeq != -1) { mHeadVThread = mShapeInstance->addThread(); mShapeInstance->setSequence(mHeadVThread,headSeq,0); mShapeInstance->setTimeScale(mHeadVThread,0); } else mHeadVThread = 0; headSeq = shape->findSequence("headside"); if (headSeq != -1) { mHeadHThread = mShapeInstance->addThread(); mShapeInstance->setSequence(mHeadHThread,headSeq,0); mShapeInstance->setTimeScale(mHeadHThread,0); } else mHeadHThread = 0; // Create Recoil thread if any recoil sequences are specified. // Note that the server player does not play this animation. mRecoilThread = 0; if (isGhost()) for (U32 s = 0; s < PlayerData::NumRecoilSequences; s++) if (mDataBlock->recoilSequence[s] != -1) { mRecoilThread = mShapeInstance->addThread(); mShapeInstance->setSequence(mRecoilThread, mDataBlock->recoilSequence[s], 0); mShapeInstance->setTimeScale(mRecoilThread, 0); break; } // Reset the image state driven animation thread. This will be properly built // in onImageStateAnimation() when needed. mImageStateThread = 0; // Initialize the primary thread, the actual sequence is // set later depending on player actions. mActionAnimation.action = PlayerData::NullAnimation; mActionAnimation.thread = mShapeInstance->addThread(); updateAnimationTree(!isGhost()); // First person mounted image shapes. Only on client. if ( isGhost() ) { for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { if (bool(mDataBlock->mShapeFP[i])) { mShapeFPInstance[i] = new TSShapeInstance(mDataBlock->mShapeFP[i], isClientObject()); mShapeFPInstance[i]->cloneMaterialList(); // Ambient animation if (mShapeFPAmbientThread[i]) { S32 seq = mShapeFPInstance[i]->getShape()->findSequence("ambient"); if (seq != -1) { mShapeFPAmbientThread[i] = mShapeFPInstance[i]->addThread(); mShapeFPInstance[i]->setTimeScale(mShapeFPAmbientThread[i], 1); mShapeFPInstance[i]->setSequence(mShapeFPAmbientThread[i], seq, 0); } } // Standard state animation mShapeFPAnimThread[i] = mShapeFPInstance[i]->addThread(); if (mShapeFPAnimThread[i]) { mShapeFPInstance[i]->setTimeScale(mShapeFPAnimThread[i],0); } } } } if ( isGhost() ) { // Create the sounds ahead of time. This reduces runtime // costs and makes the system easier to understand. SFX_DELETE( mMoveBubbleSound ); SFX_DELETE( mWaterBreathSound ); if ( mDataBlock->getPlayerSound(PlayerData::MoveBubbles) ) mMoveBubbleSound = SFX->createSource( mDataBlock->getPlayerSoundProfile(PlayerData::MoveBubbles) ); if ( mDataBlock->getPlayerSound(PlayerData::WaterBreath) ) mWaterBreathSound = SFX->createSource( mDataBlock->getPlayerSoundProfile(PlayerData::WaterBreath) ); } mObjBox.maxExtents.x = mDataBlock->boxSize.x * 0.5f; mObjBox.maxExtents.y = mDataBlock->boxSize.y * 0.5f; mObjBox.maxExtents.z = mDataBlock->boxSize.z; mObjBox.minExtents.x = -mObjBox.maxExtents.x; mObjBox.minExtents.y = -mObjBox.maxExtents.y; mObjBox.minExtents.z = 0.0f; // Setup the box for our convex object... mObjBox.getCenter(&mConvex.mCenter); mConvex.mSize.x = mObjBox.len_x() / 2.0f; mConvex.mSize.y = mObjBox.len_y() / 2.0f; mConvex.mSize.z = mObjBox.len_z() / 2.0f; // Initialize our scaled attributes as well onScaleChanged(); resetWorldBox(); scriptOnNewDataBlock(); return true; } //---------------------------------------------------------------------------- void Player::reSkin() { if ( isGhost() && mShapeInstance && mSkinNameHandle.isValidString() ) { mShapeInstance->resetMaterialList(); Vector<String> skins; String(mSkinNameHandle.getString()).split( ";", skins ); for ( S32 i = 0; i < skins.size(); i++ ) { String oldSkin( mAppliedSkinName.c_str() ); String newSkin( skins[i] ); // Check if the skin handle contains an explicit "old" base string. This // allows all models to support skinning, even if they don't follow the // "base_xxx" material naming convention. S32 split = newSkin.find( '=' ); // "old=new" format skin? if ( split != String::NPos ) { oldSkin = newSkin.substr( 0, split ); newSkin = newSkin.erase( 0, split+1 ); } // Apply skin to both 3rd person and 1st person shape instances mShapeInstance->reSkin( newSkin, oldSkin ); for ( S32 j = 0; j < ShapeBase::MaxMountedImages; j++ ) { if (mShapeFPInstance[j]) mShapeFPInstance[j]->reSkin( newSkin, oldSkin ); } mAppliedSkinName = newSkin; } } } //---------------------------------------------------------------------------- void Player::setControllingClient(GameConnection* client) { Parent::setControllingClient(client); if (mControlObject) mControlObject->setControllingClient(client); } void Player::setControlObject(ShapeBase* obj) { if (mControlObject == obj) return; if (mControlObject) { mControlObject->setControllingObject(0); mControlObject->setControllingClient(0); } if (obj == this || obj == 0) mControlObject = 0; else { if (ShapeBase* coo = obj->getControllingObject()) coo->setControlObject(0); if (GameConnection* con = obj->getControllingClient()) con->setControlObject(0); mControlObject = obj; mControlObject->setControllingObject(this); mControlObject->setControllingClient(getControllingClient()); } } void Player::onCameraScopeQuery(NetConnection *connection, CameraScopeQuery *query) { // First, we are certainly in scope, and whatever we're riding is too... if(mControlObject.isNull() || mControlObject == mMount.object) Parent::onCameraScopeQuery(connection, query); else { connection->objectInScope(this); if (isMounted()) connection->objectInScope(mMount.object); mControlObject->onCameraScopeQuery(connection, query); } } ShapeBase* Player::getControlObject() { return mControlObject; } void Player::processTick(const Move* move) { PROFILE_SCOPE(Player_ProcessTick); bool prevMoveMotion = mMoveMotion; Pose prevPose = getPose(); // If we're not being controlled by a client, let the // AI sub-module get a chance at producing a move. Move aiMove; if (!move && isServerObject() && getAIMove(&aiMove)) move = &aiMove; // Manage the control object and filter moves for the player Move pMove,cMove; if (mControlObject) { if (!move) mControlObject->processTick(0); else { pMove = NullMove; cMove = *move; //if (isMounted()) { // Filter Jump trigger if mounted //pMove.trigger[2] = move->trigger[2]; //cMove.trigger[2] = false; //} if (move->freeLook) { // Filter yaw/picth/roll when freelooking. pMove.yaw = move->yaw; pMove.pitch = move->pitch; pMove.roll = move->roll; pMove.freeLook = true; cMove.freeLook = false; cMove.yaw = cMove.pitch = cMove.roll = 0.0f; } mControlObject->processTick((mDamageState == Enabled)? &cMove: &NullMove); move = &pMove; } } Parent::processTick(move); // Check for state changes in the standard move triggers and // set bits for any triggers that switched on this tick in // the fx_s_triggers mask. Flag any changes to be packed to // clients. if (isServerObject()) { fx_s_triggers = 0; if (move) { U8 on_bits = 0; for (S32 i = 0; i < MaxTriggerKeys; i++) if (move->trigger[i]) on_bits |= BIT(i); if (on_bits != move_trigger_states) { U8 switched_on_bits = (on_bits & ~move_trigger_states); if (switched_on_bits) { fx_s_triggers |= (U32)switched_on_bits; setMaskBits(TriggerMask); } move_trigger_states = on_bits; } } } // Warp to catch up to server if (mDelta.warpTicks > 0) { mDelta.warpTicks--; // Set new pos getTransform().getColumn(3, &mDelta.pos); mDelta.pos += mDelta.warpOffset; mDelta.rot += mDelta.rotOffset; // Wrap yaw to +/-PI if (mDelta.rot.z < - M_PI_F) mDelta.rot.z += M_2PI_F; else if (mDelta.rot.z > M_PI_F) mDelta.rot.z -= M_2PI_F; if (!ignore_updates) { setPosition(mDelta.pos, mDelta.rot); } updateDeathOffsets(); updateLookAnimation(); // Backstepping mDelta.posVec = -mDelta.warpOffset; mDelta.rotVec = -mDelta.rotOffset; } else { // If there is no move, the player is either an // unattached player on the server, or a player's // client ghost. if (!move) { if (isGhost()) { // If we haven't run out of prediction time, // predict using the last known move. if (mPredictionCount-- <= 0) return; move = &mDelta.move; } else move = &NullMove; } if (!isGhost()) updateAnimation(TickSec); PROFILE_START(Player_PhysicsSection); if ( isServerObject() || didRenderLastRender() || getControllingClient() ) { if ( !mPhysicsRep ) { if ( isMounted() ) { // If we're mounted then do not perform any collision checks // and clear our previous working list. mConvex.clearWorkingList(); } else { updateWorkingCollisionSet(); } } updateState(); updateMove(move); updateLookAnimation(); updateDeathOffsets(); updatePos(); } PROFILE_END(); if (!isGhost()) { // Animations are advanced based on frame rate on the // client and must be ticked on the server. updateActionThread(); updateAnimationTree(true); // Check for sprinting motion changes Pose currentPose = getPose(); // Player has just switched into Sprint pose and is moving if (currentPose == SprintPose && prevPose != SprintPose && mMoveMotion) { mDataBlock->onStartSprintMotion_callback( this ); } // Player has just switched out of Sprint pose and is moving, or was just moving else if (currentPose != SprintPose && prevPose == SprintPose && (mMoveMotion || prevMoveMotion)) { mDataBlock->onStopSprintMotion_callback( this ); } // Player is in Sprint pose and has modified their motion else if (currentPose == SprintPose && prevMoveMotion != mMoveMotion) { if (mMoveMotion) { mDataBlock->onStartSprintMotion_callback( this ); } else { mDataBlock->onStopSprintMotion_callback( this ); } } } } // PATHSHAPE if (!isGhost()) updateAttachment(); // PATHSHAPE END } void Player::interpolateTick(F32 dt) { if (mControlObject) mControlObject->interpolateTick(dt); // Client side interpolation Parent::interpolateTick(dt); Point3F pos = mDelta.pos + mDelta.posVec * dt; Point3F rot = mDelta.rot + mDelta.rotVec * dt; if (!ignore_updates) setRenderPosition(pos,rot,dt); /* // apply camera effects - is this the best place? - bramage GameConnection* connection = GameConnection::getConnectionToServer(); if( connection->isFirstPerson() ) { ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject()); if( obj == this ) { MatrixF curTrans = getRenderTransform(); curTrans.mul( gCamFXMgr.getTrans() ); Parent::setRenderTransform( curTrans ); } } */ updateLookAnimation(dt); mDelta.dt = dt; // PATHSHAPE updateRenderChangesByParent(); // PATHSHAPE END } void Player::advanceTime(F32 dt) { // Client side animations Parent::advanceTime(dt); // Increment timer for triggering idle events. if (idle_timer >= 0.0f) idle_timer += dt; updateActionThread(); updateAnimation(dt); updateSplash(); updateFroth(dt); updateWaterSounds(dt); mLastPos = getPosition(); if (mImpactSound) playImpactSound(); // update camera effects. Definitely need to find better place for this - bramage if( isControlObject() ) { if( mDamageState == Disabled || mDamageState == Destroyed ) { // clear out all camera effects being applied to player if dead gCamFXMgr.clear(); } } } bool Player::getAIMove(Move* move) { return false; } void Player::setState(ActionState state, U32 recoverTicks) { if (state != mState) { // Skip initialization if there is no manager, the state // will get reset when the object is added to a manager. if (isProperlyAdded()) { switch (state) { case RecoverState: { if (mDataBlock->landSequenceTime > 0.0f) { // Use the land sequence as the basis for the recovery setActionThread(PlayerData::LandAnim, true, false, true, true); F32 timeScale = mShapeInstance->getDuration(mActionAnimation.thread) / mDataBlock->landSequenceTime; mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale); mRecoverDelay = mDataBlock->landSequenceTime; } else { // Legacy recover system mRecoverTicks = recoverTicks; mReversePending = U32(F32(mRecoverTicks) / sLandReverseScale); setActionThread(PlayerData::LandAnim, true, false, true, true); } break; } default: break; } } mState = state; } } void Player::updateState() { switch (mState) { case RecoverState: if (mDataBlock->landSequenceTime > 0.0f) { // Count down the land time mRecoverDelay -= TickSec; if (mRecoverDelay <= 0.0f) { setState(MoveState); } } else { // Legacy recover system if (mRecoverTicks-- <= 0) { if (mReversePending && mActionAnimation.action != PlayerData::NullAnimation) { // this serves and counter, and direction state mRecoverTicks = mReversePending; mActionAnimation.forward = false; S32 seq = mDataBlock->actionList[mActionAnimation.action].sequence; S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action); if (imageBasedSeq != -1) seq = imageBasedSeq; F32 pos = mShapeInstance->getPos(mActionAnimation.thread); mShapeInstance->setTimeScale(mActionAnimation.thread, -sLandReverseScale); mShapeInstance->transitionToSequence(mActionAnimation.thread, seq, pos, sAnimationTransitionTime, true); mReversePending = 0; } else { setState(MoveState); } } // Stand back up slowly only if not moving much- else if (!mReversePending && mVelocity.lenSquared() > sSlowStandThreshSquared) { mActionAnimation.waitForEnd = false; setState(MoveState); } } break; default: break; } } const char* Player::getStateName() { if (mDamageState != Enabled) return "Dead"; if (isMounted()) return "Mounted"; if (mState == RecoverState) return "Recover"; return "Move"; } void Player::getDamageLocation(const Point3F& in_rPos, const char *&out_rpVert, const char *&out_rpQuad) { // TODO: This will be WRONG when player is prone or swimming! Point3F newPoint; mWorldToObj.mulP(in_rPos, &newPoint); Point3F boxSize = mObjBox.getExtents(); F32 zHeight = boxSize.z; F32 zTorso = mDataBlock->boxTorsoPercentage; F32 zHead = mDataBlock->boxHeadPercentage; zTorso *= zHeight; zHead *= zHeight; if (newPoint.z <= zTorso) out_rpVert = "legs"; else if (newPoint.z <= zHead) out_rpVert = "torso"; else out_rpVert = "head"; if(String::compare(out_rpVert, "head") != 0) { if (newPoint.y >= 0.0f) { if (newPoint.x <= 0.0f) out_rpQuad = "front_left"; else out_rpQuad = "front_right"; } else { if (newPoint.x <= 0.0f) out_rpQuad = "back_left"; else out_rpQuad = "back_right"; } } else { F32 backToFront = boxSize.x; F32 leftToRight = boxSize.y; F32 backPoint = backToFront * mDataBlock->boxHeadBackPercentage; F32 frontPoint = backToFront * mDataBlock->boxHeadFrontPercentage; F32 leftPoint = leftToRight * mDataBlock->boxHeadLeftPercentage; F32 rightPoint = leftToRight * mDataBlock->boxHeadRightPercentage; S32 index = 0; if (newPoint.y < backPoint) index += 0; else if (newPoint.y >= frontPoint) index += 3; else index += 6; if (newPoint.x < leftPoint) index += 0; else if (newPoint.x >= rightPoint) index += 1; else index += 2; switch (index) { case 0: out_rpQuad = "left_back"; break; case 1: out_rpQuad = "middle_back"; break; case 2: out_rpQuad = "right_back"; break; case 3: out_rpQuad = "left_middle"; break; case 4: out_rpQuad = "middle_middle"; break; case 5: out_rpQuad = "right_middle"; break; case 6: out_rpQuad = "left_front"; break; case 7: out_rpQuad = "middle_front"; break; case 8: out_rpQuad = "right_front"; break; default: AssertFatal(0, "Bad non-tant index"); }; } } const char* Player::getPoseName() const { return EngineMarshallData< PlayerPose >(getPose()); } void Player::setPose( Pose pose ) { // Already the set pose, return. if ( pose == mPose ) return; Pose oldPose = mPose; mPose = pose; // Not added yet, just assign the pose and return. if ( !isProperlyAdded() ) return; Point3F boxSize(1,1,1); // Resize the player boxes switch (pose) { case StandPose: case SprintPose: boxSize = mDataBlock->boxSize; break; case CrouchPose: boxSize = mDataBlock->crouchBoxSize; break; case PronePose: boxSize = mDataBlock->proneBoxSize; break; case SwimPose: boxSize = mDataBlock->swimBoxSize; break; } // Object and World Boxes... mObjBox.maxExtents.x = boxSize.x * 0.5f; mObjBox.maxExtents.y = boxSize.y * 0.5f; mObjBox.maxExtents.z = boxSize.z; mObjBox.minExtents.x = -mObjBox.maxExtents.x; mObjBox.minExtents.y = -mObjBox.maxExtents.y; mObjBox.minExtents.z = 0.0f; resetWorldBox(); // Setup the box for our convex object... mObjBox.getCenter(&mConvex.mCenter); mConvex.mSize.x = mObjBox.len_x() / 2.0f; mConvex.mSize.y = mObjBox.len_y() / 2.0f; mConvex.mSize.z = mObjBox.len_z() / 2.0f; // Initialize our scaled attributes as well... onScaleChanged(); // Resize the PhysicsPlayer rep. should we have one if ( mPhysicsRep ) mPhysicsRep->setSpacials( getPosition(), boxSize ); if ( isServerObject() ) mDataBlock->onPoseChange_callback( this, EngineMarshallData< PlayerPose >(oldPose), EngineMarshallData< PlayerPose >(mPose)); } void Player::allowAllPoses() { mAllowJumping = true; mAllowJetJumping = true; mAllowSprinting = true; mAllowCrouching = true; mAllowProne = true; mAllowSwimming = true; } AngAxisF gPlayerMoveRot; void Player::updateMove(const Move* move) { struct Move my_move; if (override_movement && movement_op < 3) { my_move = *move; switch (movement_op) { case 0: // add my_move.x += movement_data.x; my_move.y += movement_data.y; my_move.z += movement_data.z; break; case 1: // mult my_move.x *= movement_data.x; my_move.y *= movement_data.y; my_move.z *= movement_data.z; break; case 2: // replace my_move.x = movement_data.x; my_move.y = movement_data.y; my_move.z = movement_data.z; break; } move = &my_move; } mDelta.move = *move; #ifdef TORQUE_OPENVR if (mControllers[0]) { mControllers[0]->processTick(move); } if (mControllers[1]) { mControllers[1]->processTick(move); } #endif // Is waterCoverage high enough to be 'swimming'? { bool swimming = mWaterCoverage > 0.65f && canSwim(); if ( swimming != mSwimming ) { if ( !isGhost() ) { if ( swimming ) mDataBlock->onStartSwim_callback( this ); else mDataBlock->onStopSwim_callback( this ); } mSwimming = swimming; } } // Trigger images if (mDamageState == Enabled) { setImageTriggerState( 0, move->trigger[sImageTrigger0] ); // If you have a secondary mounted image then // send the second trigger to it. Else give it // to the first image as an alt fire. if ( getMountedImage( 1 ) ) setImageTriggerState( 1, move->trigger[sImageTrigger1] ); else setImageAltTriggerState( 0, move->trigger[sImageTrigger1] ); } // Update current orientation if (mDamageState == Enabled) { F32 prevZRot = mRot.z; mDelta.headVec = mHead; bool doStandardMove = true; bool absoluteDelta = false; GameConnection* con = getControllingClient(); #ifdef TORQUE_EXTENDED_MOVE // Work with an absolute rotation from the ExtendedMove class? if(con && con->getControlSchemeAbsoluteRotation()) { doStandardMove = false; const ExtendedMove* emove = dynamic_cast<const ExtendedMove*>(move); U32 emoveIndex = smExtendedMoveHeadPosRotIndex; if(emoveIndex >= ExtendedMove::MaxPositionsRotations) emoveIndex = 0; if(emove->EulerBasedRotation[emoveIndex]) { // Head pitch mHead.x += (emove->rotX[emoveIndex] - mLastAbsolutePitch); // Do we also include the relative yaw value? if(con->getControlSchemeAddPitchToAbsRot()) { F32 x = move->pitch; if (x > M_PI_F) x -= M_2PI_F; mHead.x += x; } // Constrain the range of mHead.x while (mHead.x < -M_PI_F) mHead.x += M_2PI_F; while (mHead.x > M_PI_F) mHead.x -= M_2PI_F; // Rotate (heading) head or body? if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson()))) { // Rotate head mHead.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw); // Do we also include the relative yaw value? if(con->getControlSchemeAddYawToAbsRot()) { F32 z = move->yaw; if (z > M_PI_F) z -= M_2PI_F; mHead.z += z; } // Constrain the range of mHead.z while (mHead.z < 0.0f) mHead.z += M_2PI_F; while (mHead.z > M_2PI_F) mHead.z -= M_2PI_F; } else { // Rotate body mRot.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw); // Do we also include the relative yaw value? if(con->getControlSchemeAddYawToAbsRot()) { F32 z = move->yaw; if (z > M_PI_F) z -= M_2PI_F; mRot.z += z; } // Constrain the range of mRot.z while (mRot.z < 0.0f) mRot.z += M_2PI_F; while (mRot.z > M_2PI_F) mRot.z -= M_2PI_F; } mLastAbsoluteYaw = emove->rotZ[emoveIndex]; mLastAbsolutePitch = emove->rotX[emoveIndex]; mLastAbsoluteRoll = emove->rotY[emoveIndex]; // Head bank mHead.y = emove->rotY[emoveIndex]; // Constrain the range of mHead.y while (mHead.y > M_PI_F) mHead.y -= M_2PI_F; } else { // Orient the player so we are looking towards the required position, ignoring any banking AngAxisF moveRot(Point3F(emove->rotX[emoveIndex], emove->rotY[emoveIndex], emove->rotZ[emoveIndex]), emove->rotW[emoveIndex]); MatrixF trans(1); moveRot.setMatrix(&trans); trans.inverse(); Point3F vecForward(0, 10, 0); Point3F viewAngle; Point3F orient; EulerF rot; trans.mulV(vecForward); viewAngle = vecForward; vecForward.z = 0; // flatten vecForward.normalizeSafe(); F32 yawAng; F32 pitchAng; MathUtils::getAnglesFromVector(vecForward, yawAng, pitchAng); mRot = EulerF(0); mRot.z = yawAng; mHead = EulerF(0); while (mRot.z < 0.0f) mRot.z += M_2PI_F; while (mRot.z > M_2PI_F) mRot.z -= M_2PI_F; absoluteDelta = true; } } #endif if(doStandardMove) { F32 p = move->pitch * (mPose == SprintPose ? mDataBlock->sprintPitchScale : 1.0f); if (p > M_PI_F) p -= M_2PI_F; mHead.x = mClampF(mHead.x + p,mDataBlock->minLookAngle, mDataBlock->maxLookAngle); F32 y = move->yaw * (mPose == SprintPose ? mDataBlock->sprintYawScale : 1.0f); if (y > M_PI_F) y -= M_2PI_F; if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson()))) { mHead.z = mClampF(mHead.z + y, -mDataBlock->maxFreelookAngle, mDataBlock->maxFreelookAngle); } else { mRot.z += y; // Rotate the head back to the front, center horizontal // as well if we're controlling another object. mHead.z *= 0.5f; if (mControlObject) mHead.x *= 0.5f; } // constrain the range of mRot.z while (mRot.z < 0.0f) mRot.z += M_2PI_F; while (mRot.z > M_2PI_F) mRot.z -= M_2PI_F; } mDelta.rot = mRot; mDelta.rotVec.x = mDelta.rotVec.y = 0.0f; mDelta.rotVec.z = prevZRot - mRot.z; if (mDelta.rotVec.z > M_PI_F) mDelta.rotVec.z -= M_2PI_F; else if (mDelta.rotVec.z < -M_PI_F) mDelta.rotVec.z += M_2PI_F; mDelta.head = mHead; mDelta.headVec -= mHead; if (absoluteDelta) { mDelta.headVec = Point3F(0, 0, 0); mDelta.rotVec = Point3F(0, 0, 0); } for(U32 i=0; i<3; ++i) { if (mDelta.headVec[i] > M_PI_F) mDelta.headVec[i] -= M_2PI_F; else if (mDelta.headVec[i] < -M_PI_F) mDelta.headVec[i] += M_2PI_F; } } MatrixF zRot; zRot.set(EulerF(0.0f, 0.0f, mRot.z)); // Desired move direction & speed VectorF moveVec; F32 moveSpeed; // If BLOCK_USER_CONTROL is set in anim_clip_flags, the user won't be able to // resume control over the player character. This generally happens for // short periods of time synchronized with script driven animation at places // where it makes sense that user motion is prohibited, such as when the // player is lifted off the ground or knocked down. if ((mState == MoveState || (mState == RecoverState && mDataBlock->recoverRunForceScale > 0.0f)) && mDamageState == Enabled && !isAnimationLocked()) { zRot.getColumn(0,&moveVec); moveVec *= (move->x * (mPose == SprintPose ? mDataBlock->sprintStrafeScale : 1.0f)); VectorF tv; zRot.getColumn(1,&tv); moveVec += tv * move->y; // Clamp water movement if (move->y > 0.0f) { if ( mSwimming ) moveSpeed = getMax(mDataBlock->maxUnderwaterForwardSpeed * move->y, mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x)); else if ( mPose == PronePose ) moveSpeed = getMax(mDataBlock->maxProneForwardSpeed * move->y, mDataBlock->maxProneSideSpeed * mFabs(move->x)); else if ( mPose == CrouchPose ) moveSpeed = getMax(mDataBlock->maxCrouchForwardSpeed * move->y, mDataBlock->maxCrouchSideSpeed * mFabs(move->x)); else if ( mPose == SprintPose ) moveSpeed = getMax(mDataBlock->maxSprintForwardSpeed * move->y, mDataBlock->maxSprintSideSpeed * mFabs(move->x)); else // StandPose moveSpeed = getMax(mDataBlock->maxForwardSpeed * move->y, mDataBlock->maxSideSpeed * mFabs(move->x)); } else { if ( mSwimming ) moveSpeed = getMax(mDataBlock->maxUnderwaterBackwardSpeed * mFabs(move->y), mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x)); else if ( mPose == PronePose ) moveSpeed = getMax(mDataBlock->maxProneBackwardSpeed * mFabs(move->y), mDataBlock->maxProneSideSpeed * mFabs(move->x)); else if ( mPose == CrouchPose ) moveSpeed = getMax(mDataBlock->maxCrouchBackwardSpeed * mFabs(move->y), mDataBlock->maxCrouchSideSpeed * mFabs(move->x)); else if ( mPose == SprintPose ) moveSpeed = getMax(mDataBlock->maxSprintBackwardSpeed * mFabs(move->y), mDataBlock->maxSprintSideSpeed * mFabs(move->x)); else // StandPose moveSpeed = getMax(mDataBlock->maxBackwardSpeed * mFabs(move->y), mDataBlock->maxSideSpeed * mFabs(move->x)); } // Cancel any script driven animations if we are going to move. if (moveVec.x + moveVec.y + moveVec.z != 0.0f && (mActionAnimation.action >= PlayerData::NumTableActionAnims || mActionAnimation.action == PlayerData::LandAnim)) mActionAnimation.action = PlayerData::NullAnimation; } else { moveVec.set(0.0f, 0.0f, 0.0f); moveSpeed = 0.0f; } // apply speed bias here. speed_bias = speed_bias + (speed_bias_goal - speed_bias)*0.1f; moveSpeed *= speed_bias; // Acceleration due to gravity VectorF acc(0.0f, 0.0f, mNetGravity/(1.0 - mBuoyancy) * TickSec); if (getParent() !=NULL) acc = VectorF::Zero; // Determine ground contact normal. Only look for contacts if // we can move and aren't mounted. VectorF contactNormal(0,0,0); bool jumpSurface = false, runSurface = false; if ( !isMounted() ) findContact( &runSurface, &jumpSurface, &contactNormal ); if ( jumpSurface ) mJumpSurfaceNormal = contactNormal; // If we don't have a runSurface but we do have a contactNormal, // then we are standing on something that is too steep. // Deflect the force of gravity by the normal so we slide. // We could also try aligning it to the runSurface instead, // but this seems to work well. if ( !runSurface && !contactNormal.isZero() ) acc = ( acc - 2 * contactNormal * mDot( acc, contactNormal ) ); // Acceleration on run surface if (runSurface && !mSwimming) { mContactTimer = 0; // Remove acc into contact surface (should only be gravity) // Clear out floating point acc errors, this will allow // the player to "rest" on the ground. // However, no need to do that if we're using a physics library. // It will take care of itself. if (!mPhysicsRep) { F32 vd = -mDot(acc,contactNormal); if (vd > 0.0f) { VectorF dv = contactNormal * (vd + 0.002f); acc += dv; if (acc.len() < 0.0001f) acc.set(0.0f, 0.0f, 0.0f); } } // Force a 0 move if there is no energy, and only drain // move energy if we're moving. VectorF pv; if (mPose == SprintPose && mEnergy >= mDataBlock->minSprintEnergy) { if (moveSpeed) mEnergy -= mDataBlock->sprintEnergyDrain; pv = moveVec; } else if (mEnergy >= mDataBlock->minRunEnergy) { if (moveSpeed) mEnergy -= mDataBlock->runEnergyDrain; pv = moveVec; } else pv.set(0.0f, 0.0f, 0.0f); // Adjust the player's requested dir. to be parallel // to the contact surface. F32 pvl = pv.len(); if(mJetting) { pvl = moveVec.len(); if (pvl) { VectorF nn; mCross(pv,VectorF(0.0f, 0.0f, 0.0f),&nn); nn *= 1 / pvl; VectorF cv(0.0f, 0.0f, 0.0f); cv -= nn * mDot(nn,cv); pv -= cv * mDot(pv,cv); pvl = pv.len(); } } else if (!mPhysicsRep) { // We only do this if we're not using a physics library. The // library will take care of itself. if (pvl) { VectorF nn; mCross(pv,VectorF(0.0f, 0.0f, 1.0f),&nn); nn *= 1.0f / pvl; VectorF cv = contactNormal; cv -= nn * mDot(nn,cv); pv -= cv * mDot(pv,cv); pvl = pv.len(); } } // Convert to acceleration if ( pvl ) pv *= moveSpeed / pvl; VectorF runAcc = pv - (mVelocity + acc); F32 runSpeed = runAcc.len(); // Clamp acceleration, player also accelerates faster when // in his hard landing recover state. F32 maxAcc; if (mPose == SprintPose) { maxAcc = (mDataBlock->sprintForce / getMass()) * TickSec; } else { maxAcc = (mDataBlock->runForce / getMass()) * TickSec; } if (mState == RecoverState) maxAcc *= mDataBlock->recoverRunForceScale; if (runSpeed > maxAcc) runAcc *= maxAcc / runSpeed; acc += runAcc; // If we are running on the ground, then we're not jumping if (mDataBlock->isJumpAction(mActionAnimation.action)) mActionAnimation.action = PlayerData::NullAnimation; } else if (!mSwimming && mDataBlock->airControl > 0.0f) { VectorF pv; pv = moveVec; F32 pvl = pv.len(); if (pvl) pv *= moveSpeed / pvl; VectorF runAcc = pv - (mVelocity + acc); runAcc.z = 0; runAcc.x = runAcc.x * mDataBlock->airControl; runAcc.y = runAcc.y * mDataBlock->airControl; F32 runSpeed = runAcc.len(); // We don't test for sprinting when performing air control F32 maxAcc = (mDataBlock->runForce / getMass()) * TickSec * 0.3f; if (runSpeed > maxAcc) runAcc *= maxAcc / runSpeed; acc += runAcc; // There are no special air control animations // so... increment this unless you really want to // play the run anims in the air. mContactTimer++; } else if (mSwimming) { // Remove acc into contact surface (should only be gravity) // Clear out floating point acc errors, this will allow // the player to "rest" on the ground. F32 vd = -mDot(acc,contactNormal); if (vd > 0.0f) { VectorF dv = contactNormal * (vd + 0.002f); acc += dv; if (acc.len() < 0.0001f) acc.set(0.0f, 0.0f, 0.0f); } // get the head pitch and add it to the moveVec // This more accurate swim vector calc comes from Matt Fairfax MatrixF xRot; xRot.set(EulerF(mHead.x, 0, 0)); zRot.set(EulerF(0, 0, mRot.z)); MatrixF rot; rot.mul(zRot, xRot); rot.getColumn(0,&moveVec); moveVec *= move->x; VectorF tv; rot.getColumn(1,&tv); moveVec += tv * move->y; rot.getColumn(2,&tv); moveVec += tv * move->z; // Force a 0 move if there is no energy, and only drain // move energy if we're moving. VectorF swimVec; if (mEnergy >= mDataBlock->minRunEnergy) { if (moveSpeed) mEnergy -= mDataBlock->runEnergyDrain; swimVec = moveVec; } else swimVec.set(0.0f, 0.0f, 0.0f); // If we are swimming but close enough to the shore/ground // we can still have a surface-normal. In this case align the // velocity to the normal to make getting out of water easier. moveVec.normalize(); F32 isSwimUp = mDot( moveVec, contactNormal ); if ( !contactNormal.isZero() && isSwimUp < 0.1f ) { F32 pvl = swimVec.len(); if ( true && pvl ) { VectorF nn; mCross(swimVec,VectorF(0.0f, 0.0f, 1.0f),&nn); nn *= 1.0f / pvl; VectorF cv = contactNormal; cv -= nn * mDot(nn,cv); swimVec -= cv * mDot(swimVec,cv); } } F32 swimVecLen = swimVec.len(); // Convert to acceleration. if ( swimVecLen ) swimVec *= moveSpeed / swimVecLen; VectorF swimAcc = swimVec - (mVelocity + acc); F32 swimSpeed = swimAcc.len(); // Clamp acceleration. F32 maxAcc = (mDataBlock->swimForce / getMass()) * TickSec; if ( swimSpeed > maxAcc ) swimAcc *= maxAcc / swimSpeed; acc += swimAcc; mContactTimer++; } else mContactTimer++; // Acceleration from Jumping // While BLOCK_USER_CONTROL is set in anim_clip_flags, the user won't be able to // make the player character jump. if (move->trigger[sJumpTrigger] && canJump() && !isAnimationLocked()) { // Scale the jump impulse base on maxJumpSpeed F32 zSpeedScale = mVelocity.z; if (zSpeedScale <= mDataBlock->maxJumpSpeed) { zSpeedScale = (zSpeedScale <= mDataBlock->minJumpSpeed)? 1: 1 - (zSpeedScale - mDataBlock->minJumpSpeed) / (mDataBlock->maxJumpSpeed - mDataBlock->minJumpSpeed); // Desired jump direction VectorF pv = moveVec; F32 len = pv.len(); if (len > 0) pv *= 1 / len; // We want to scale the jump size by the player size, somewhat // in reduced ratio so a smaller player can jump higher in // proportion to his size, than a larger player. F32 scaleZ = (getScale().z * 0.25) + 0.75; // Calculate our jump impulse F32 impulse = mDataBlock->jumpForce / getMass(); if (mDataBlock->jumpTowardsNormal) { // If we are facing into the surface jump up, otherwise // jump away from surface. F32 dot = mDot(pv,mJumpSurfaceNormal); if (dot <= 0) acc.z += mJumpSurfaceNormal.z * scaleZ * impulse * zSpeedScale; else { acc.x += pv.x * impulse * dot; acc.y += pv.y * impulse * dot; acc.z += mJumpSurfaceNormal.z * scaleZ * impulse * zSpeedScale; } } else acc.z += scaleZ * impulse * zSpeedScale; mJumpDelay = mDataBlock->jumpDelay; mEnergy -= mDataBlock->jumpEnergyDrain; // If we don't have a StandJumpAnim, just play the JumpAnim... S32 seq = (mVelocity.len() < 0.5) ? PlayerData::StandJumpAnim: PlayerData::JumpAnim; if ( mDataBlock->actionList[seq].sequence == -1 ) seq = PlayerData::JumpAnim; setActionThread( seq, true, false, true ); mJumpSurfaceLastContact = JumpSkipContactsMax; // Flag the jump event trigger. fx_s_triggers |= PLAYER_JUMP_S_TRIGGER; setMaskBits(TriggerMask); } } else { if (jumpSurface) { if (mJumpDelay > 0) mJumpDelay--; mJumpSurfaceLastContact = 0; } else mJumpSurfaceLastContact++; } if (move->trigger[sJumpJetTrigger] && !isMounted() && canJetJump()) { mJetting = true; // Scale the jump impulse base on maxJumpSpeed F32 zSpeedScale = mVelocity.z; if (zSpeedScale <= mDataBlock->jetMaxJumpSpeed) { zSpeedScale = (zSpeedScale <= mDataBlock->jetMinJumpSpeed)? 1: 1 - (zSpeedScale - mDataBlock->jetMinJumpSpeed) / (mDataBlock->jetMaxJumpSpeed - mDataBlock->jetMinJumpSpeed); // Desired jump direction VectorF pv = moveVec; F32 len = pv.len(); if (len > 0.0f) pv *= 1 / len; // If we are facing into the surface jump up, otherwise // jump away from surface. F32 dot = mDot(pv,mJumpSurfaceNormal); F32 impulse = mDataBlock->jetJumpForce / getMass(); if (dot <= 0) acc.z += mJumpSurfaceNormal.z * impulse * zSpeedScale; else { acc.x += pv.x * impulse * dot; acc.y += pv.y * impulse * dot; acc.z += mJumpSurfaceNormal.z * impulse * zSpeedScale; } mEnergy -= mDataBlock->jetJumpEnergyDrain; } } else { mJetting = false; } // Add in force from physical zones... acc += (mAppliedForce / getMass()) * TickSec; // Adjust velocity with all the move & gravity acceleration // TG: I forgot why doesn't the TickSec multiply happen here... mVelocity += acc; // apply horizontal air resistance F32 hvel = mSqrt(mVelocity.x * mVelocity.x + mVelocity.y * mVelocity.y); if(hvel > mDataBlock->horizResistSpeed) { F32 speedCap = hvel; if(speedCap > mDataBlock->horizMaxSpeed) speedCap = mDataBlock->horizMaxSpeed; speedCap -= mDataBlock->horizResistFactor * TickSec * (speedCap - mDataBlock->horizResistSpeed); F32 scale = speedCap / hvel; mVelocity.x *= scale; mVelocity.y *= scale; } if(mVelocity.z > mDataBlock->upResistSpeed) { if(mVelocity.z > mDataBlock->upMaxSpeed) mVelocity.z = mDataBlock->upMaxSpeed; mVelocity.z -= mDataBlock->upResistFactor * TickSec * (mVelocity.z - mDataBlock->upResistSpeed); } // Apply drag if ( mSwimming ) mVelocity -= mVelocity * mDrag * TickSec * ( mVelocity.len() / mDataBlock->maxUnderwaterForwardSpeed ); else mVelocity -= mVelocity * mDrag * TickSec; // Clamp very small velocity to zero if ( mVelocity.isZero() ) mVelocity = Point3F::Zero; // If we are not touching anything and have sufficient -z vel, // we are falling. if (runSurface) mFalling = false; else { VectorF vel; mWorldToObj.mulV(mVelocity,&vel); mFalling = vel.z < mDataBlock->fallingSpeedThreshold; } // Vehicle Dismount if ( !isGhost() && move->trigger[sVehicleDismountTrigger] && canJump()) mDataBlock->doDismount_callback( this ); // Enter/Leave Liquid if ( !mInWater && mWaterCoverage > 0.0f ) { mInWater = true; if ( !isGhost() ) mDataBlock->onEnterLiquid_callback( this, mWaterCoverage, mLiquidType.c_str() ); } else if ( mInWater && mWaterCoverage <= 0.0f ) { mInWater = false; if ( !isGhost() ) mDataBlock->onLeaveLiquid_callback( this, mLiquidType.c_str() ); else { // exit-water splash sound happens for client only if ( getSpeed() >= mDataBlock->exitSplashSoundVel && !isMounted() ) SFX->playOnce( mDataBlock->getPlayerSoundProfile(PlayerData::ExitWater), &getTransform() ); } } // Update the PlayerPose Pose desiredPose = mPose; if ( !mIsAiControlled ) { if ( mSwimming ) desiredPose = SwimPose; else if ( runSurface && move->trigger[sCrouchTrigger] && canCrouch() ) desiredPose = CrouchPose; else if ( runSurface && move->trigger[sProneTrigger] && canProne() ) desiredPose = PronePose; else if ( move->trigger[sSprintTrigger] && canSprint() ) desiredPose = SprintPose; else if ( canStand() ) desiredPose = StandPose; setPose( desiredPose ); } } //---------------------------------------------------------------------------- bool Player::checkDismountPosition(const MatrixF& oldMat, const MatrixF& mat) { AssertFatal(getContainer() != NULL, "Error, must have a container!"); AssertFatal(getObjectMount() != NULL, "Error, must be mounted!"); Point3F pos; Point3F oldPos; mat.getColumn(3, &pos); oldMat.getColumn(3, &oldPos); RayInfo info; disableCollision(); getObjectMount()->disableCollision(); if (getContainer()->castRay(oldPos, pos, sCollisionMoveMask, &info)) { enableCollision(); getObjectMount()->enableCollision(); return false; } Box3F wBox = mObjBox; wBox.minExtents += pos; wBox.maxExtents += pos; EarlyOutPolyList polyList; polyList.mNormal.set(0.0f, 0.0f, 0.0f); polyList.mPlaneList.clear(); polyList.mPlaneList.setSize(6); polyList.mPlaneList[0].set(wBox.minExtents,VectorF(-1.0f, 0.0f, 0.0f)); polyList.mPlaneList[1].set(wBox.maxExtents,VectorF(0.0f, 1.0f, 0.0f)); polyList.mPlaneList[2].set(wBox.maxExtents,VectorF(1.0f, 0.0f, 0.0f)); polyList.mPlaneList[3].set(wBox.minExtents,VectorF(0.0f, -1.0f, 0.0f)); polyList.mPlaneList[4].set(wBox.minExtents,VectorF(0.0f, 0.0f, -1.0f)); polyList.mPlaneList[5].set(wBox.maxExtents,VectorF(0.0f, 0.0f, 1.0f)); if (getContainer()->buildPolyList(PLC_Collision, wBox, sCollisionMoveMask, &polyList)) { enableCollision(); getObjectMount()->enableCollision(); return false; } enableCollision(); getObjectMount()->enableCollision(); return true; } //---------------------------------------------------------------------------- bool Player::canJump() { return mAllowJumping && mState == MoveState && mDamageState == Enabled && !isMounted() && !mJumpDelay && mEnergy >= mDataBlock->minJumpEnergy && mJumpSurfaceLastContact < JumpSkipContactsMax && !mSwimming && (mPose != SprintPose || mDataBlock->sprintCanJump); } bool Player::canJetJump() { return mAllowJetJumping && mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->jetMinJumpEnergy && mDataBlock->jetJumpForce != 0.0f; } bool Player::canSwim() { // Not used! //return mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->minSwimEnergy && mWaterCoverage >= 0.8f; return mAllowSwimming; } bool Player::canCrouch() { if (!mAllowCrouching) return false; if ( mState != MoveState || mDamageState != Enabled || isMounted() || mSwimming || mFalling ) return false; // Can't crouch if no crouch animation! if ( mDataBlock->actionList[PlayerData::CrouchRootAnim].sequence == -1 ) return false; // We are already in this pose, so don't test it again... if ( mPose == CrouchPose ) return true; // Do standard Torque physics test here! if ( !mPhysicsRep ) { F32 radius; if ( mPose == PronePose ) radius = mDataBlock->proneBoxSize.z; else return true; // use our X and Y dimentions on our boxsize as the radii for our search, and the difference between a standing position // and the position we currently are in. Point3F extent( mDataBlock->crouchBoxSize.x / 2, mDataBlock->crouchBoxSize.y / 2, mDataBlock->crouchBoxSize.z - radius ); Point3F position = getPosition(); position.z += radius; // Use these radii to create a box that represents the difference between a standing position and the position // we want to move into. Box3F B(position - extent, position + extent, true); EarlyOutPolyList polyList; polyList.mPlaneList.clear(); polyList.mNormal.set( 0,0,0 ); polyList.mPlaneList.setSize( 6 ); polyList.mPlaneList[0].set( B.minExtents, VectorF( -1,0,0 ) ); polyList.mPlaneList[1].set( B.maxExtents, VectorF( 0,1,0 ) ); polyList.mPlaneList[2].set( B.maxExtents, VectorF( 1,0,0 ) ); polyList.mPlaneList[3].set( B.minExtents, VectorF( 0,-1,0 ) ); polyList.mPlaneList[4].set( B.minExtents, VectorF( 0,0,-1 ) ); polyList.mPlaneList[5].set( B.maxExtents, VectorF( 0,0,1 ) ); // If an object exists in this space, we must stay prone. Otherwise we are free to crouch. return !getContainer()->buildPolyList( PLC_Collision, B, StaticShapeObjectType, &polyList ); } return mPhysicsRep->testSpacials( getPosition(), mDataBlock->crouchBoxSize ); } bool Player::canStand() { if ( mState != MoveState || mDamageState != Enabled || isMounted() || mSwimming ) return false; // We are already in this pose, so don't test it again... if ( mPose == StandPose ) return true; // Do standard Torque physics test here! if ( !mPhysicsRep ) { F32 radius; if (mPose == CrouchPose) radius = mDataBlock->crouchBoxSize.z; else if (mPose == PronePose) radius = mDataBlock->proneBoxSize.z; else return true; // use our X and Y dimentions on our boxsize as the radii for our search, and the difference between a standing position // and the position we currently are in. Point3F extent( mDataBlock->boxSize.x / 2, mDataBlock->boxSize.y / 2, mDataBlock->boxSize.z - radius ); Point3F position = getPosition(); position.z += radius; // Use these radii to create a box that represents the difference between a standing position and the position // we want to move into. Box3F B(position - extent, position + extent, true); EarlyOutPolyList polyList; polyList.mPlaneList.clear(); polyList.mNormal.set(0,0,0); polyList.mPlaneList.setSize(6); polyList.mPlaneList[0].set(B.minExtents, VectorF(-1,0,0)); polyList.mPlaneList[1].set(B.maxExtents, VectorF(0,1,0)); polyList.mPlaneList[2].set(B.maxExtents, VectorF(1,0,0)); polyList.mPlaneList[3].set(B.minExtents, VectorF(0,-1,0)); polyList.mPlaneList[4].set(B.minExtents, VectorF(0,0,-1)); polyList.mPlaneList[5].set(B.maxExtents, VectorF(0,0,1)); // If an object exists in this space, we must stay crouched/prone. Otherwise we are free to stand. return !getContainer()->buildPolyList(PLC_Collision, B, StaticShapeObjectType, &polyList); } return mPhysicsRep->testSpacials( getPosition(), mDataBlock->boxSize ); } bool Player::canProne() { if (!mAllowProne) return false; if ( mState != MoveState || mDamageState != Enabled || isMounted() || mSwimming || mFalling ) return false; // Can't go prone if no prone animation! if ( mDataBlock->actionList[PlayerData::ProneRootAnim].sequence == -1 ) return false; // Do standard Torque physics test here! if ( !mPhysicsRep ) return true; // We are already in this pose, so don't test it again... if ( mPose == PronePose ) return true; return mPhysicsRep->testSpacials( getPosition(), mDataBlock->proneBoxSize ); } bool Player::canSprint() { return mAllowSprinting && mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->minSprintEnergy && !mSwimming; } //---------------------------------------------------------------------------- void Player::updateDamageLevel() { if (!isGhost()) setDamageState((mDamage >= mDataBlock->maxDamage)? Disabled: Enabled); if (mDamageThread) mShapeInstance->setPos(mDamageThread, mDamage / mDataBlock->destroyedLevel); } void Player::updateDamageState() { // Become a corpse when we're disabled (dead). if (mDamageState == Enabled) { mTypeMask &= ~CorpseObjectType; mTypeMask |= PlayerObjectType; } else { mTypeMask &= ~PlayerObjectType; mTypeMask |= CorpseObjectType; } Parent::updateDamageState(); } //---------------------------------------------------------------------------- void Player::updateLookAnimation(F32 dt) { // If the preference setting overrideLookAnimation is true, the player's // arm and head no longer animate according to the view direction. They // are instead given fixed positions. if (overrideLookAnimation) { if (mArmAnimation.thread) mShapeInstance->setPos(mArmAnimation.thread, armLookOverridePos); if (mHeadVThread) mShapeInstance->setPos(mHeadVThread, headVLookOverridePos); if (mHeadHThread) mShapeInstance->setPos(mHeadHThread, headHLookOverridePos); return; } // Calculate our interpolated head position. Point3F renderHead = mDelta.head + mDelta.headVec * dt; // Adjust look pos. This assumes that the animations match // the min and max look angles provided in the datablock. if (mArmAnimation.thread) { if(mControlObject) { mShapeInstance->setPos(mArmAnimation.thread,0.5f); } else { F32 d = mDataBlock->maxLookAngle - mDataBlock->minLookAngle; F32 tp = (renderHead.x - mDataBlock->minLookAngle) / d; mShapeInstance->setPos(mArmAnimation.thread,mClampF(tp,0,1)); } } if (mHeadVThread) { F32 d = mDataBlock->maxLookAngle - mDataBlock->minLookAngle; F32 tp = (renderHead.x - mDataBlock->minLookAngle) / d; mShapeInstance->setPos(mHeadVThread,mClampF(tp,0,1)); } if (mHeadHThread) { F32 d = 2 * mDataBlock->maxFreelookAngle; F32 tp = (renderHead.z + mDataBlock->maxFreelookAngle) / d; mShapeInstance->setPos(mHeadHThread,mClampF(tp,0,1)); } } //---------------------------------------------------------------------------- // Methods to get delta (as amount to affect velocity by) bool Player::inDeathAnim() { if ((anim_clip_flags & ANIM_OVERRIDDEN) != 0 && (anim_clip_flags & IS_DEATH_ANIM) == 0) return false; if (mActionAnimation.thread && mActionAnimation.action >= 0) if (mActionAnimation.action < mDataBlock->actionCount) return mDataBlock->actionList[mActionAnimation.action].death; return false; } // Get change from mLastDeathPos - return current pos. Assumes we're in death anim. F32 Player::deathDelta(Point3F & delta) { // Get ground delta from the last time we offset this. MatrixF mat; F32 pos = mShapeInstance->getPos(mActionAnimation.thread); mShapeInstance->deltaGround1(mActionAnimation.thread, mDeath.lastPos, pos, mat); mat.getColumn(3, & delta); return pos; } // Called before updatePos() to prepare it's needed change to velocity, which // must roll over. Should be updated on tick, this is where we remember last // position of animation that was used to roll into velocity. void Player::updateDeathOffsets() { if (inDeathAnim()) // Get ground delta from the last time we offset this. mDeath.lastPos = deathDelta(mDeath.posAdd); else mDeath.clear(); } //---------------------------------------------------------------------------- // PATHSHAPE static const U32 sPlayerConformMask = StaticShapeObjectType | StaticObjectType | TerrainObjectType | PathShapeObjectType; // PATHSHAPE END static void accel(F32& from, F32 to, F32 rate) { if (from < to) from = getMin(from += rate, to); else from = getMax(from -= rate, to); } // if (dt == -1) // normal tick, so we advance. // else // interpolate with dt as % of tick, don't advance // MatrixF * Player::Death::fallToGround(F32 dt, const Point3F& loc, F32 curZ, F32 boxRad) { static const F32 sConformCheckDown = 4.0f; RayInfo coll; bool conformToStairs = false; Point3F pos(loc.x, loc.y, loc.z + 0.1f); Point3F below(pos.x, pos.y, loc.z - sConformCheckDown); MatrixF * retVal = NULL; PROFILE_SCOPE(ConformToGround); if (gClientContainer.castRay(pos, below, sPlayerConformMask, &coll)) { F32 adjust, height = (loc.z - coll.point.z), sink = curSink; VectorF desNormal = coll.normal; VectorF normal = curNormal; // dt >= 0 means we're interpolating and don't accel the numbers if (dt >= 0.0f) adjust = dt * TickSec; else adjust = TickSec; // Try to get them to conform to stairs by doing several LOS calls. We do this if // normal is within about 5 deg. of vertical. if (desNormal.z > 0.995f) { Point3F corners[3], downpts[3]; S32 c; for (c = 0; c < 3; c++) { // Build 3 corners to cast down from- corners[c].set(loc.x - boxRad, loc.y - boxRad, loc.z + 1.0f); if (c) // add (0,boxWidth) and (boxWidth,0) corners[c][c - 1] += (boxRad * 2.0f); downpts[c].set(corners[c].x, corners[c].y, loc.z - sConformCheckDown); } // Do the three casts- for (c = 0; c < 3; c++) if (gClientContainer.castRay(corners[c], downpts[c], sPlayerConformMask, &coll)) downpts[c] = coll.point; else break; // Do the math if everything hit below- if (c == 3) { mCross(downpts[1] - downpts[0], downpts[2] - downpts[1], &desNormal); AssertFatal(desNormal.z > 0, "Abnormality in Player::Death::fallToGround()"); downpts[2] = downpts[2] - downpts[1]; downpts[1] = downpts[1] - downpts[0]; desNormal.normalize(); conformToStairs = true; } } // Move normal in direction we want- F32 * cur = normal, * des = desNormal; for (S32 i = 0; i < 3; i++) accel(*cur++, *des++, adjust * 0.25f); if (mFabs(height) < 2.2f && !normal.isZero() && desNormal.z > 0.01f) { VectorF upY(0.0f, 1.0f, 0.0f), ahead; VectorF sideVec; MatrixF mat(true); normal.normalize(); mat.set(EulerF (0.0f, 0.0f, curZ)); mat.mulV(upY, & ahead); mCross(ahead, normal, &sideVec); sideVec.normalize(); mCross(normal, sideVec, &ahead); static MatrixF resMat(true); resMat.setColumn(0, sideVec); resMat.setColumn(1, ahead); resMat.setColumn(2, normal); // Adjust Z down to account for box offset on slope. Figure out how // much we want to sink, and gradually accel to this amount. Don't do if // we're conforming to stairs though F32 xy = mSqrt(desNormal.x * desNormal.x + desNormal.y * desNormal.y); F32 desiredSink = (boxRad * xy / desNormal.z); if (conformToStairs) desiredSink *= 0.5f; accel(sink, desiredSink, adjust * 0.15f); Point3F position(pos); position.z -= sink; resMat.setColumn(3, position); if (dt < 0.0f) { // we're moving, so update normal and sink amount curNormal = normal; curSink = sink; } retVal = &resMat; } } return retVal; } //------------------------------------------------------------------------------------- // This is called ::onAdd() to see if we're in a sitting animation. These then // can use a longer tick delay for the mount to get across. bool Player::inSittingAnim() { U32 action = mActionAnimation.action; if (mActionAnimation.thread && action < mDataBlock->actionCount) { const char * name = mDataBlock->actionList[action].name; if (!dStricmp(name, "Sitting") || !dStricmp(name, "Scoutroot")) return true; } return false; } //---------------------------------------------------------------------------- const String& Player::getArmThread() const { if (mArmAnimation.thread && mArmAnimation.thread->hasSequence()) { return mArmAnimation.thread->getSequenceName(); } return String::EmptyString; } bool Player::setArmThread(const char* sequence) { // The arm sequence must be in the action list. for (U32 i = 1; i < mDataBlock->actionCount; i++) if (!dStricmp(mDataBlock->actionList[i].name,sequence)) return setArmThread(i); return false; } bool Player::setArmThread(U32 action) { PlayerData::ActionAnimation &anim = mDataBlock->actionList[action]; if (anim.sequence != -1 && anim.sequence != mShapeInstance->getSequence(mArmAnimation.thread)) { mShapeInstance->setSequence(mArmAnimation.thread,anim.sequence,0); mArmAnimation.action = action; setMaskBits(ActionMask); return true; } return false; } //---------------------------------------------------------------------------- bool Player::setActionThread(const char* sequence,bool hold,bool wait,bool fsp) { if (anim_clip_flags & ANIM_OVERRIDDEN) return false; for (U32 i = 1; i < mDataBlock->actionCount; i++) { PlayerData::ActionAnimation &anim = mDataBlock->actionList[i]; if (!dStricmp(anim.name,sequence)) { setActionThread(i,true,hold,wait,fsp); setMaskBits(ActionMask); return true; } } return false; } void Player::setActionThread(U32 action,bool forward,bool hold,bool wait,bool fsp, bool forceSet) { if (!mDataBlock || !mDataBlock->actionCount || (mActionAnimation.action == action && mActionAnimation.forward == forward && !forceSet)) return; if (action >= PlayerData::NumActionAnims) { Con::errorf("Player::setActionThread(%d): Player action out of range", action); return; } if (isClientObject()) { mark_idle = (action == PlayerData::RootAnim); idle_timer = (mark_idle) ? 0.0f : -1.0f; } PlayerData::ActionAnimation &anim = mDataBlock->actionList[action]; if (anim.sequence != -1) { U32 lastAction = mActionAnimation.action; mActionAnimation.action = action; mActionAnimation.forward = forward; mActionAnimation.firstPerson = fsp; mActionAnimation.holdAtEnd = hold; mActionAnimation.waitForEnd = hold? true: wait; mActionAnimation.animateOnServer = fsp; mActionAnimation.atEnd = false; mActionAnimation.delayTicks = (S32)sNewAnimationTickTime; mActionAnimation.atEnd = false; if (sUseAnimationTransitions && (action != PlayerData::LandAnim || !(mDataBlock->landSequenceTime > 0.0f && !mDataBlock->transitionToLand)) && (isGhost()/* || mActionAnimation.animateOnServer*/)) { // The transition code needs the timeScale to be set in the // right direction to know which way to go. F32 transTime = sAnimationTransitionTime; if (mDataBlock && mDataBlock->isJumpAction(action)) transTime = 0.15f; F32 timeScale = mActionAnimation.forward ? 1.0f : -1.0f; if (mDataBlock && mDataBlock->isJumpAction(action)) timeScale *= 1.5f; mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale); S32 seq = anim.sequence; S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action); if (imageBasedSeq != -1) seq = imageBasedSeq; // If we're transitioning into the same sequence (an action may use the // same sequence as a previous action) then we want to start at the same // position. F32 pos = mActionAnimation.forward ? 0.0f : 1.0f; PlayerData::ActionAnimation &lastAnim = mDataBlock->actionList[lastAction]; if (lastAnim.sequence == anim.sequence) { pos = mShapeInstance->getPos(mActionAnimation.thread); } mShapeInstance->transitionToSequence(mActionAnimation.thread,seq, pos, transTime, true); } else { S32 seq = anim.sequence; S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action); if (imageBasedSeq != -1) seq = imageBasedSeq; mShapeInstance->setSequence(mActionAnimation.thread,seq, mActionAnimation.forward ? 0.0f : 1.0f); } } } void Player::updateActionThread() { PROFILE_START(UpdateActionThread); // Select an action animation sequence, this assumes that // this function is called once per tick. if(mActionAnimation.action != PlayerData::NullAnimation) { if (mActionAnimation.forward) mActionAnimation.atEnd = mShapeInstance->getPos(mActionAnimation.thread) == 1; else mActionAnimation.atEnd = mShapeInstance->getPos(mActionAnimation.thread) == 0; } // Only need to deal with triggers on the client if( isGhost() ) { bool triggeredLeft = false; bool triggeredRight = false; F32 offset = 0.0f; if( mShapeInstance->getTriggerState( 1 ) ) { triggeredLeft = true; offset = -mDataBlock->decalOffset * getScale().x; } else if(mShapeInstance->getTriggerState( 2 ) ) { triggeredRight = true; offset = mDataBlock->decalOffset * getScale().x; } process_client_triggers(triggeredLeft, triggeredRight); if ((triggeredLeft || triggeredRight) && !noFootfallFX) { Point3F rot, pos; RayInfo rInfo; MatrixF mat = getRenderTransform(); mat.getColumn( 1, &rot ); mat.mulP( Point3F( offset, 0.0f, 0.0f), &pos ); if( gClientContainer.castRay( Point3F( pos.x, pos.y, pos.z + 0.01f ), Point3F( pos.x, pos.y, pos.z - 2.0f ), STATIC_COLLISION_TYPEMASK | VehicleObjectType, &rInfo ) ) { Material* material = ( rInfo.material ? dynamic_cast< Material* >( rInfo.material->getMaterial() ) : 0 ); // Put footprints on surface, if appropriate for material. if( material && material->mShowFootprints && mDataBlock->decalData && !footfallDecalOverride ) { Point3F normal; Point3F tangent; mObjToWorld.getColumn( 0, &tangent ); mObjToWorld.getColumn( 2, &normal ); gDecalManager->addDecal( rInfo.point, normal, tangent, mDataBlock->decalData, getScale().y ); } // Emit footpuffs. if (!footfallDustOverride && rInfo.t <= 0.5f && mWaterCoverage == 0.0f && material && material->mShowDust ) { // New emitter every time for visibility reasons ParticleEmitter * emitter = new ParticleEmitter; emitter->onNewDataBlock( mDataBlock->footPuffEmitter, false ); LinearColorF colorList[ ParticleData::PDC_NUM_KEYS]; for( U32 x = 0; x < getMin( Material::NUM_EFFECT_COLOR_STAGES, ParticleData::PDC_NUM_KEYS ); ++ x ) colorList[ x ].set( material->mEffectColor[ x ].red, material->mEffectColor[ x ].green, material->mEffectColor[ x ].blue, material->mEffectColor[ x ].alpha ); for( U32 x = Material::NUM_EFFECT_COLOR_STAGES; x < ParticleData::PDC_NUM_KEYS; ++ x ) colorList[ x ].set( 1.0, 1.0, 1.0, 0.0 ); emitter->setColors( colorList ); if( !emitter->registerObject() ) { Con::warnf( ConsoleLogEntry::General, "Could not register emitter for particle of class: %s", mDataBlock->getName() ); delete emitter; emitter = NULL; } else { emitter->emitParticles( pos, Point3F( 0.0, 0.0, 1.0 ), mDataBlock->footPuffRadius, Point3F( 0, 0, 0 ), mDataBlock->footPuffNumParts ); emitter->deleteWhenEmpty(); } } // Play footstep sound. if (footfallSoundOverride <= 0) playFootstepSound( triggeredLeft, material, rInfo.object ); } } } // Mount pending variable puts a hold on the delayTicks below so players don't // inadvertently stand up because their mount has not come over yet. if (mMountPending) mMountPending = (isMounted() ? 0 : (mMountPending - 1)); if ((mActionAnimation.action == PlayerData::NullAnimation) || ((!mActionAnimation.waitForEnd || mActionAnimation.atEnd) && (!mActionAnimation.holdAtEnd && (mActionAnimation.delayTicks -= !mMountPending) <= 0))) { //The scripting language will get a call back when a script animation has finished... // example: When the chat menu animations are done playing... if ( isServerObject() && mActionAnimation.action >= PlayerData::NumTableActionAnims ) mDataBlock->animationDone_callback( this ); pickActionAnimation(); } // prevent scaling of AFX picked actions if ( (mActionAnimation.action != PlayerData::LandAnim) && (mActionAnimation.action != PlayerData::NullAnimation) && !(anim_clip_flags & ANIM_OVERRIDDEN)) { // Update action animation time scale to match ground velocity PlayerData::ActionAnimation &anim = mDataBlock->actionList[mActionAnimation.action]; F32 scale = 1; if (anim.velocityScale && anim.speed) { VectorF vel; mWorldToObj.mulV(mVelocity,&vel); scale = mFabs(mDot(vel, anim.dir) / anim.speed); if (scale > mDataBlock->maxTimeScale) scale = mDataBlock->maxTimeScale; } mShapeInstance->setTimeScale(mActionAnimation.thread, mActionAnimation.forward? scale: -scale); } PROFILE_END(); } void Player::pickBestMoveAction(U32 startAnim, U32 endAnim, U32 * action, bool * forward) const { *action = startAnim; *forward = false; VectorF vel; mWorldToObj.mulV(mVelocity,&vel); if (vel.lenSquared() > 0.01f) { // Bias the velocity towards picking the forward/backward anims over // the sideways ones to prevent oscillation between anims. vel *= VectorF(0.5f, 1.0f, 0.5f); // Pick animation that is the best fit for our current (local) velocity. // Assumes that the root (stationary) animation is at startAnim. F32 curMax = -0.1f; for (U32 i = startAnim+1; i <= endAnim; i++) { const PlayerData::ActionAnimation &anim = mDataBlock->actionList[i]; if (anim.sequence != -1 && anim.speed) { F32 d = mDot(vel, anim.dir); if (d > curMax) { curMax = d; *action = i; *forward = true; } else { // Check if reversing this animation would fit (bias against this // so that when moving right, the real right anim is still chosen, // but if not present, the reversed left anim will be used instead) d *= -0.75f; if (d > curMax) { curMax = d; *action = i; *forward = false; } } } } } } void Player::pickActionAnimation() { // Only select animations in our normal move state. if (mState != MoveState || mDamageState != Enabled) return; if (isMounted() || mMountPending) { // Go into root position unless something was set explicitly // from a script. if (mActionAnimation.action != PlayerData::RootAnim && mActionAnimation.action < PlayerData::NumTableActionAnims) setActionThread(PlayerData::RootAnim,true,false,false); return; } bool forward = true; U32 action = PlayerData::RootAnim; bool fsp = false; // Jetting overrides the fall animation condition if (mJetting) { // Play the jetting animation action = PlayerData::JetAnim; } else if (mFalling) { // Not in contact with any surface and falling action = PlayerData::FallAnim; } else if ( mSwimming ) { pickBestMoveAction(PlayerData::SwimRootAnim, PlayerData::SwimRightAnim, &action, &forward); } else if ( mPose == StandPose ) { if (mContactTimer >= sContactTickTime) { // Nothing under our feet action = PlayerData::RootAnim; } else { // Our feet are on something pickBestMoveAction(PlayerData::RootAnim, PlayerData::SideRightAnim, &action, &forward); } } else if ( mPose == CrouchPose ) { pickBestMoveAction(PlayerData::CrouchRootAnim, PlayerData::CrouchRightAnim, &action, &forward); } else if ( mPose == PronePose ) { pickBestMoveAction(PlayerData::ProneRootAnim, PlayerData::ProneBackwardAnim, &action, &forward); } else if ( mPose == SprintPose ) { pickBestMoveAction(PlayerData::SprintRootAnim, PlayerData::SprintRightAnim, &action, &forward); } setActionThread(action,forward,false,false,fsp); } void Player::onImage(U32 imageSlot, bool unmount) { // Update 3rd person sequences based on images used. Start be getting a // list of all possible image prefix sequences. String prefixPaths[ShapeBase::MaxMountedImages]; buildImagePrefixPaths(prefixPaths); // Clear out any previous image state animation if (mImageStateThread) { mShapeInstance->destroyThread(mImageStateThread); mImageStateThread = 0; } // Attempt to update the action thread U32 action = mActionAnimation.action; if (action != PlayerData::NullAnimation) { String actionSeq = mDataBlock->actionList[action].name; if (actionSeq.isNotEmpty()) { S32 seqIndex = mDataBlock->actionList[action].sequence; S32 prefixIndex = findPrefixSequence(prefixPaths, actionSeq); if (prefixIndex != -1) { seqIndex = prefixIndex; } // Only change the sequence if it isn't already playing. if (seqIndex != mShapeInstance->getSequence(mActionAnimation.thread)) { F32 pos = mShapeInstance->getPos(mActionAnimation.thread); mShapeInstance->setSequence(mActionAnimation.thread, seqIndex, pos); } } } // Attempt to update the arm thread U32 armAction = getArmAction(); if (armAction != PlayerData::NullAnimation) { String armSeq = mDataBlock->actionList[armAction].name; if (armSeq.isNotEmpty()) { S32 seqIndex = mDataBlock->actionList[armAction].sequence; S32 prefixIndex = findPrefixSequence(prefixPaths, armSeq); if (prefixIndex != -1) { seqIndex = prefixIndex; } // Only change the sequence if it isn't already playing. if (seqIndex != mShapeInstance->getSequence(mArmAnimation.thread)) { F32 pos = mShapeInstance->getPos(mArmAnimation.thread); mShapeInstance->setSequence(mArmAnimation.thread, seqIndex, pos); } } } // Attempt to update the head threads if (mHeadVThread) { TSShape const* shape = mShapeInstance->getShape(); S32 seqIndex = shape->findSequence("head"); S32 prefixIndex = findPrefixSequence(prefixPaths, "head"); if (prefixIndex != -1) { seqIndex = prefixIndex; } // Only change the sequence if it isn't already playing. if (seqIndex != mShapeInstance->getSequence(mHeadVThread)) { F32 pos = mShapeInstance->getPos(mHeadVThread); mShapeInstance->setSequence(mHeadVThread, seqIndex, pos); } } if (mHeadHThread) { TSShape const* shape = mShapeInstance->getShape(); S32 seqIndex = shape->findSequence("headside"); S32 prefixIndex = findPrefixSequence(prefixPaths, "headside"); if (prefixIndex != -1) { seqIndex = prefixIndex; } // Only change the sequence if it isn't already playing. if (seqIndex != mShapeInstance->getSequence(mHeadHThread)) { F32 pos = mShapeInstance->getPos(mHeadHThread); mShapeInstance->setSequence(mHeadHThread, seqIndex, pos); } } } void Player::buildImagePrefixPaths(String* prefixPaths) { // We begin obtaining the anim prefix for each image. String prefix[ShapeBase::MaxMountedImages]; for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { MountedImage& image = mMountedImageList[i]; if (image.dataBlock && image.dataBlock->imageAnimPrefix && image.dataBlock->imageAnimPrefix[0]) { prefix[i] = String(image.dataBlock->imageAnimPrefix); } } // Build out the full prefix names we will be searching for. S32 counter = ShapeBase::MaxMountedImages-1; for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { // Only build out the prefix path for images that have a defined prefix. if (prefix[i].isNotEmpty()) { bool start = true; for (U32 j=0; j<=i; ++j) { if (prefix[j].isNotEmpty()) { if (!start) { prefixPaths[counter] += "_"; } else { start = false; } prefixPaths[counter] += prefix[j]; } } } -- counter; } } S32 Player::findPrefixSequence(String* prefixPaths, const String& baseSeq) { // Go through the prefix list. If we find a match then return the sequence // index. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { if (prefixPaths[i].isNotEmpty()) { String seq = prefixPaths[i] + "_" + baseSeq; S32 seqIndex = mShapeInstance->getShape()->findSequence(seq); if (seqIndex != -1) { return seqIndex; } } } return -1; } S32 Player::convertActionToImagePrefix(U32 action) { String prefixPaths[ShapeBase::MaxMountedImages]; buildImagePrefixPaths(prefixPaths); if (action != PlayerData::NullAnimation) { String actionSeq; S32 seq = -1; // We'll first attempt to find the action sequence by name // as defined within the action list. actionSeq = mDataBlock->actionList[action].name; if (actionSeq.isNotEmpty()) { seq = findPrefixSequence(prefixPaths, actionSeq); } if (seq == -1) { // Couldn't find a valid sequence. If this is a sprint action // then we also need to search through the standard movement // sequences. if (action >= PlayerData::SprintRootAnim && action <= PlayerData::SprintRightAnim) { U32 standardAction = action - PlayerData::SprintRootAnim; actionSeq = mDataBlock->actionList[standardAction].name; if (actionSeq.isNotEmpty()) { seq = findPrefixSequence(prefixPaths, actionSeq); } } } return seq; } return -1; } void Player::onImageRecoil( U32, ShapeBaseImageData::StateData::RecoilState state ) { if ( mRecoilThread ) { if ( state != ShapeBaseImageData::StateData::NoRecoil ) { S32 stateIndex = state - ShapeBaseImageData::StateData::LightRecoil; if ( mDataBlock->recoilSequence[stateIndex] != -1 ) { mShapeInstance->setSequence( mRecoilThread, mDataBlock->recoilSequence[stateIndex], 0 ); mShapeInstance->setTimeScale( mRecoilThread, 1 ); } } } } void Player::onImageStateAnimation(U32 imageSlot, const char* seqName, bool direction, bool scaleToState, F32 stateTimeOutValue) { if (mDataBlock->allowImageStateAnimation && isGhost()) { MountedImage& image = mMountedImageList[imageSlot]; // Just as with onImageAnimThreadChange we're going to apply various prefixes to determine the final sequence to use. // Here is the order: // imageBasePrefix_scriptPrefix_baseAnimName // imageBasePrefix_baseAnimName // scriptPrefix_baseAnimName // baseAnimName // Collect the prefixes const char* imageBasePrefix = ""; bool hasImageBasePrefix = image.dataBlock && image.dataBlock->imageAnimPrefix && image.dataBlock->imageAnimPrefix[0]; if (hasImageBasePrefix) imageBasePrefix = image.dataBlock->imageAnimPrefix; const char* scriptPrefix = getImageScriptAnimPrefix(imageSlot).getString(); bool hasScriptPrefix = scriptPrefix && scriptPrefix[0]; S32 seqIndex = mShapeInstance->getShape()->findSequence(seqName); // Find the final sequence based on the prefix combinations if (hasImageBasePrefix || hasScriptPrefix) { bool found = false; String baseSeqName(seqName); if (!found && hasImageBasePrefix && hasScriptPrefix) { String comboSeqName = String(imageBasePrefix) + String("_") + String(scriptPrefix) + String("_") + baseSeqName; S32 index = mShapeInstance->getShape()->findSequence(comboSeqName); if (index != -1) { seqIndex = index; found = true; } } if (!found && hasImageBasePrefix) { String imgSeqName = String(imageBasePrefix) + String("_") + baseSeqName; S32 index = mShapeInstance->getShape()->findSequence(imgSeqName); if (index != -1) { seqIndex = index; found = true; } } if (!found && hasScriptPrefix) { String scriptSeqName = String(scriptPrefix) + String("_") + baseSeqName; S32 index = mShapeInstance->getShape()->findSequence(scriptSeqName); if (index != -1) { seqIndex = index; found = true; } } } if (seqIndex != -1) { if (!mImageStateThread) { mImageStateThread = mShapeInstance->addThread(); } mShapeInstance->setSequence( mImageStateThread, seqIndex, 0 ); F32 timeScale = (scaleToState && stateTimeOutValue) ? mShapeInstance->getDuration(mImageStateThread) / stateTimeOutValue : 1.0f; mShapeInstance->setTimeScale( mImageStateThread, direction ? timeScale : -timeScale ); } } } const char* Player::getImageAnimPrefix(U32 imageSlot, S32 imageShapeIndex) { if (!mDataBlock) return ""; switch (imageShapeIndex) { case ShapeBaseImageData::StandardImageShape: { return mDataBlock->imageAnimPrefix; } case ShapeBaseImageData::FirstPersonImageShape: { return mDataBlock->imageAnimPrefixFP; } default: { return ""; } } } void Player::onImageAnimThreadChange(U32 imageSlot, S32 imageShapeIndex, ShapeBaseImageData::StateData* lastState, const char* anim, F32 pos, F32 timeScale, bool reset) { if (!mShapeFPInstance[imageSlot] || !mShapeFPAnimThread[imageSlot]) return; MountedImage& image = mMountedImageList[imageSlot]; ShapeBaseImageData::StateData& stateData = *image.state; if (reset) { // Reset cyclic sequences back to the first frame to turn it off // (the first key frame should be it's off state). if (mShapeFPAnimThread[imageSlot]->getSequence()->isCyclic() && (stateData.sequenceNeverTransition || !(stateData.sequenceTransitionIn || (lastState && lastState->sequenceTransitionOut))) ) { mShapeFPInstance[imageSlot]->setPos(mShapeFPAnimThread[imageSlot],0); mShapeFPInstance[imageSlot]->setTimeScale(mShapeFPAnimThread[imageSlot],0); } return; } // Just as with ShapeBase::udpateAnimThread we're going to apply various prefixes to determine the final sequence to use. // Here is the order: // imageBasePrefix_scriptPrefix_baseAnimName // imageBasePrefix_baseAnimName // scriptPrefix_baseAnimName // baseAnimName // Collect the prefixes const char* imageBasePrefix = ""; bool hasImageBasePrefix = image.dataBlock && image.dataBlock->imageAnimPrefixFP && image.dataBlock->imageAnimPrefixFP[0]; if (hasImageBasePrefix) imageBasePrefix = image.dataBlock->imageAnimPrefixFP; const char* scriptPrefix = getImageScriptAnimPrefix(imageSlot).getString(); bool hasScriptPrefix = scriptPrefix && scriptPrefix[0]; S32 seqIndex = mShapeFPInstance[imageSlot]->getShape()->findSequence(anim); // Find the final sequence based on the prefix combinations if (hasImageBasePrefix || hasScriptPrefix) { bool found = false; String baseSeqName(anim); if (!found && hasImageBasePrefix && hasScriptPrefix) { String seqName = String(imageBasePrefix) + String("_") + String(scriptPrefix) + String("_") + baseSeqName; S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName); if (index != -1) { seqIndex = index; found = true; } } if (!found && hasImageBasePrefix) { String seqName = String(imageBasePrefix) + String("_") + baseSeqName; S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName); if (index != -1) { seqIndex = index; found = true; } } if (!found && hasScriptPrefix) { String seqName = String(scriptPrefix) + String("_") + baseSeqName; S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName); if (index != -1) { seqIndex = index; found = true; } } } if (seqIndex != -1) { if (!lastState) { // No lastState indicates that we are just switching animation sequences, not states. Transition into this new sequence, but only // if it is different than what we're currently playing. S32 prevSeq = -1; if (mShapeFPAnimThread[imageSlot]->hasSequence()) { prevSeq = mShapeFPInstance[imageSlot]->getSequence(mShapeFPAnimThread[imageSlot]); } if (seqIndex != prevSeq) { mShapeFPInstance[imageSlot]->transitionToSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos, image.dataBlock->scriptAnimTransitionTime, true); } } else if (!stateData.sequenceNeverTransition && stateData.sequenceTransitionTime && (stateData.sequenceTransitionIn || (lastState && lastState->sequenceTransitionOut)) ) { mShapeFPInstance[imageSlot]->transitionToSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos, stateData.sequenceTransitionTime, true); } else { mShapeFPInstance[imageSlot]->setSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos); } mShapeFPInstance[imageSlot]->setTimeScale(mShapeFPAnimThread[imageSlot], timeScale); } } void Player::onImageAnimThreadUpdate(U32 imageSlot, S32 imageShapeIndex, F32 dt) { if (!mShapeFPInstance[imageSlot]) return; if (mShapeFPAmbientThread[imageSlot] && mShapeFPAmbientThread[imageSlot]->hasSequence()) { mShapeFPInstance[imageSlot]->advanceTime(dt,mShapeFPAmbientThread[imageSlot]); } if (mShapeFPAnimThread[imageSlot] && mShapeFPAnimThread[imageSlot]->hasSequence()) { mShapeFPInstance[imageSlot]->advanceTime(dt,mShapeFPAnimThread[imageSlot]); } } void Player::onUnmount( SceneObject *obj, S32 node ) { // Reset back to root position during dismount. setActionThread(PlayerData::RootAnim,true,false,false); // Re-orient the player straight up Point3F pos,vec; getTransform().getColumn(1,&vec); getTransform().getColumn(3,&pos); Point3F rot(0.0f,0.0f,-mAtan2(-vec.x,vec.y)); setPosition(pos,rot); // Parent function will call script Parent::onUnmount( obj, node ); } void Player::unmount() { // Reset back to root position during dismount. This copies what is // done on the server and corrects the fact that the RootAnim change // is not sent across to the client using the standard ActionMask. setActionThread(PlayerData::RootAnim,true,false,false); Parent::unmount(); } //---------------------------------------------------------------------------- void Player::updateAnimation(F32 dt) { // If dead then remove any image animations if ((mDamageState == Disabled || mDamageState == Destroyed) && mImageStateThread) { // Remove the image state animation mShapeInstance->destroyThread(mImageStateThread); mImageStateThread = 0; } if ((isGhost() || mActionAnimation.animateOnServer) && mActionAnimation.thread) mShapeInstance->advanceTime(dt,mActionAnimation.thread); if (mRecoilThread) mShapeInstance->advanceTime(dt,mRecoilThread); if (mImageStateThread) mShapeInstance->advanceTime(dt,mImageStateThread); // update any active blend clips if (isGhost()) for (S32 i = 0; i < blend_clips.size(); i++) mShapeInstance->advanceTime(dt, blend_clips[i].thread); // If we are the client's player on this machine, then we need // to make sure the transforms are up to date as they are used // to setup the camera. if (isGhost()) { if (getControllingClient()) { updateAnimationTree(isFirstPerson()); mShapeInstance->animate(); } else { updateAnimationTree(false); // This addition forces recently visible players to animate their // skeleton now rather than in pre-render so that constrained effects // get up-to-date node transforms. if (didRenderLastRender()) mShapeInstance->animate(); } } } void Player::updateAnimationTree(bool firstPerson) { S32 mode = 0; if (firstPerson) { if (mActionAnimation.firstPerson) mode = 0; // TSShapeInstance::MaskNodeRotation; // TSShapeInstance::MaskNodePosX | // TSShapeInstance::MaskNodePosY; else mode = TSShapeInstance::MaskNodeAllButBlend; } for (U32 i = 0; i < PlayerData::NumSpineNodes; i++) if (mDataBlock->spineNode[i] != -1) mShapeInstance->setNodeAnimationState(mDataBlock->spineNode[i],mode); } //---------------------------------------------------------------------------- bool Player::step(Point3F *pos,F32 *maxStep,F32 time) { const Point3F& scale = getScale(); Box3F box; VectorF offset = mVelocity * time; box.minExtents = mObjBox.minExtents + offset + *pos; box.maxExtents = mObjBox.maxExtents + offset + *pos; box.maxExtents.z += mDataBlock->maxStepHeight * scale.z + sMinFaceDistance; SphereF sphere; sphere.center = (box.minExtents + box.maxExtents) * 0.5f; VectorF bv = box.maxExtents - sphere.center; sphere.radius = bv.len(); ClippedPolyList polyList; polyList.mPlaneList.clear(); polyList.mNormal.set(0.0f, 0.0f, 0.0f); polyList.mPlaneList.setSize(6); polyList.mPlaneList[0].set(box.minExtents,VectorF(-1.0f, 0.0f, 0.0f)); polyList.mPlaneList[1].set(box.maxExtents,VectorF(0.0f, 1.0f, 0.0f)); polyList.mPlaneList[2].set(box.maxExtents,VectorF(1.0f, 0.0f, 0.0f)); polyList.mPlaneList[3].set(box.minExtents,VectorF(0.0f, -1.0f, 0.0f)); polyList.mPlaneList[4].set(box.minExtents,VectorF(0.0f, 0.0f, -1.0f)); polyList.mPlaneList[5].set(box.maxExtents,VectorF(0.0f, 0.0f, 1.0f)); CollisionWorkingList& rList = mConvex.getWorkingList(); CollisionWorkingList* pList = rList.wLink.mNext; while (pList != &rList) { Convex* pConvex = pList->mConvex; // Alright, here's the deal... a polysoup mesh really needs to be // designed with stepping in mind. If there are too many smallish polygons // the stepping system here gets confused and allows you to run up walls // or on the edges/seams of meshes. TSStatic *st = dynamic_cast<TSStatic *> (pConvex->getObject()); bool skip = false; if (st && !st->allowPlayerStep()) skip = true; if ((pConvex->getObject()->getTypeMask() & StaticObjectType) != 0 && !skip) { Box3F convexBox = pConvex->getBoundingBox(); if (box.isOverlapped(convexBox)) pConvex->getPolyList(&polyList); } pList = pList->wLink.mNext; } // Find max step height F32 stepHeight = pos->z - sMinFaceDistance; U32* vp = polyList.mIndexList.begin(); U32* ep = polyList.mIndexList.end(); for (; vp != ep; vp++) { F32 h = polyList.mVertexList[*vp].point.z + sMinFaceDistance; if (h > stepHeight) stepHeight = h; } F32 step = stepHeight - pos->z; if (stepHeight > pos->z && step < *maxStep) { // Go ahead and step pos->z = stepHeight; *maxStep -= step; return true; } return false; } // PATHSHAPE // This Function does a ray cast down to see if a pathshape object is below // If so, it will attempt to attach to it. void Player::updateAttachment(){ Point3F rot, pos; RayInfo rInfo; MatrixF mat = getTransform(); mat.getColumn(3, &pos); if (gServerContainer.castRay(Point3F(pos.x, pos.y, pos.z + 0.1f), Point3F(pos.x, pos.y, pos.z - 1.0f ), PathShapeObjectType, &rInfo)) { if( rInfo.object->getTypeMask() & PathShapeObjectType) //Ramen { if (getParent() == NULL) { // ONLY do this if we are not parented //Con::printf("I'm on a pathshape object. Going to attempt attachment."); ShapeBase* col = static_cast<ShapeBase*>(rInfo.object); if (!isGhost()) { this->attachToParent(col); } } } else { //Con::printf("object %i",rInfo.object->getId()); } } else { if (getParent() !=NULL) { clearProcessAfter(); attachToParent(NULL); } } } // PATHSHAPE END //---------------------------------------------------------------------------- inline Point3F createInterpPos(const Point3F& s, const Point3F& e, const F32 t, const F32 d) { Point3F ret; ret.interpolate(s, e, t/d); return ret; } Point3F Player::_move( const F32 travelTime, Collision *outCol ) { // Try and move to new pos F32 totalMotion = 0.0f; // TODO: not used? //F32 initialSpeed = mVelocity.len(); Point3F start; Point3F initialPosition; getTransform().getColumn(3,&start); initialPosition = start; static CollisionList collisionList; static CollisionList physZoneCollisionList; collisionList.clear(); physZoneCollisionList.clear(); MatrixF collisionMatrix(true); collisionMatrix.setColumn(3, start); VectorF firstNormal(0.0f, 0.0f, 0.0f); F32 maxStep = mDataBlock->maxStepHeight; F32 time = travelTime; U32 count = 0; const Point3F& scale = getScale(); static Polyhedron sBoxPolyhedron; static ExtrudedPolyList sExtrudedPolyList; static ExtrudedPolyList sPhysZonePolyList; for (; count < sMoveRetryCount; count++) { F32 speed = mVelocity.len(); if (!speed && !mDeath.haveVelocity()) break; Point3F end = start + mVelocity * time; if (mDeath.haveVelocity()) { // Add in death movement- VectorF deathVel = mDeath.getPosAdd(); VectorF resVel; getTransform().mulV(deathVel, & resVel); end += resVel; } Point3F distance = end - start; if (mFabs(distance.x) < mScaledBox.len_x() && mFabs(distance.y) < mScaledBox.len_y() && mFabs(distance.z) < mScaledBox.len_z()) { // We can potentially early out of this. If there are no polys in the clipped polylist at our // end position, then we can bail, and just set start = end; Box3F wBox = mScaledBox; wBox.minExtents += end; wBox.maxExtents += end; static EarlyOutPolyList eaPolyList; eaPolyList.clear(); eaPolyList.mNormal.set(0.0f, 0.0f, 0.0f); eaPolyList.mPlaneList.clear(); eaPolyList.mPlaneList.setSize(6); eaPolyList.mPlaneList[0].set(wBox.minExtents,VectorF(-1.0f, 0.0f, 0.0f)); eaPolyList.mPlaneList[1].set(wBox.maxExtents,VectorF(0.0f, 1.0f, 0.0f)); eaPolyList.mPlaneList[2].set(wBox.maxExtents,VectorF(1.0f, 0.0f, 0.0f)); eaPolyList.mPlaneList[3].set(wBox.minExtents,VectorF(0.0f, -1.0f, 0.0f)); eaPolyList.mPlaneList[4].set(wBox.minExtents,VectorF(0.0f, 0.0f, -1.0f)); eaPolyList.mPlaneList[5].set(wBox.maxExtents,VectorF(0.0f, 0.0f, 1.0f)); // Build list from convex states here... CollisionWorkingList& rList = mConvex.getWorkingList(); CollisionWorkingList* pList = rList.wLink.mNext; while (pList != &rList) { Convex* pConvex = pList->mConvex; if (pConvex->getObject()->getTypeMask() & sCollisionMoveMask) { Box3F convexBox = pConvex->getBoundingBox(); if (wBox.isOverlapped(convexBox)) { // No need to separate out the physical zones here, we want those // to cause a fallthrough as well... pConvex->getPolyList(&eaPolyList); } } pList = pList->wLink.mNext; } if (eaPolyList.isEmpty()) { totalMotion += (end - start).len(); start = end; break; } } collisionMatrix.setColumn(3, start); sBoxPolyhedron.buildBox(collisionMatrix, mScaledBox, true); // Setup the bounding box for the extrudedPolyList Box3F plistBox = mScaledBox; collisionMatrix.mul(plistBox); Point3F oldMin = plistBox.minExtents; Point3F oldMax = plistBox.maxExtents; plistBox.minExtents.setMin(oldMin + (mVelocity * time) - Point3F(0.1f, 0.1f, 0.1f)); plistBox.maxExtents.setMax(oldMax + (mVelocity * time) + Point3F(0.1f, 0.1f, 0.1f)); // Build extruded polyList... VectorF vector = end - start; sExtrudedPolyList.extrude(sBoxPolyhedron,vector); sExtrudedPolyList.setVelocity(mVelocity); sExtrudedPolyList.setCollisionList(&collisionList); sPhysZonePolyList.extrude(sBoxPolyhedron,vector); sPhysZonePolyList.setVelocity(mVelocity); sPhysZonePolyList.setCollisionList(&physZoneCollisionList); // Build list from convex states here... CollisionWorkingList& rList = mConvex.getWorkingList(); CollisionWorkingList* pList = rList.wLink.mNext; while (pList != &rList) { Convex* pConvex = pList->mConvex; if (pConvex->getObject()->getTypeMask() & sCollisionMoveMask) { Box3F convexBox = pConvex->getBoundingBox(); if (plistBox.isOverlapped(convexBox)) { if (pConvex->getObject()->getTypeMask() & PhysicalZoneObjectType) pConvex->getPolyList(&sPhysZonePolyList); else pConvex->getPolyList(&sExtrudedPolyList); } } pList = pList->wLink.mNext; } // Take into account any physical zones... for (U32 j = 0; j < physZoneCollisionList.getCount(); j++) { AssertFatal(dynamic_cast<PhysicalZone*>(physZoneCollisionList[j].object), "Bad phys zone!"); const PhysicalZone* pZone = (PhysicalZone*)physZoneCollisionList[j].object; if (pZone->isActive()) mVelocity *= pZone->getVelocityMod(); } if (collisionList.getCount() != 0 && collisionList.getTime() < 1.0f) { // Set to collision point F32 velLen = mVelocity.len(); F32 dt = time * getMin(collisionList.getTime(), 1.0f); start += mVelocity * dt; time -= dt; totalMotion += velLen * dt; bool wasFalling = mFalling; mFalling = false; // Back off... if ( velLen > 0.f ) { F32 newT = getMin(0.01f / velLen, dt); start -= mVelocity * newT; totalMotion -= velLen * newT; } // Try stepping if there is a vertical surface if (collisionList.getMaxHeight() < start.z + mDataBlock->maxStepHeight * scale.z) { bool stepped = false; for (U32 c = 0; c < collisionList.getCount(); c++) { const Collision& cp = collisionList[c]; // if (mFabs(mDot(cp.normal,VectorF(0,0,1))) < sVerticalStepDot) // Dot with (0,0,1) just extracts Z component [lh]- if (mFabs(cp.normal.z) < sVerticalStepDot) { stepped = step(&start,&maxStep,time); break; } } if (stepped) { continue; } } // Pick the surface most parallel to the face that was hit. const Collision *collision = &collisionList[0]; const Collision *cp = collision + 1; const Collision *ep = collision + collisionList.getCount(); for (; cp != ep; cp++) { if (cp->faceDot > collision->faceDot) collision = cp; } F32 bd = _doCollisionImpact( collision, wasFalling ); // Copy this collision out so // we can use it to do impacts // and query collision. *outCol = *collision; if (isServerObject() && bd > 6.8f && collision->normal.z > 0.7f) { fx_s_triggers |= PLAYER_LANDING_S_TRIGGER; setMaskBits(TriggerMask); } // Subtract out velocity VectorF dv = collision->normal * (bd + sNormalElasticity); mVelocity += dv; if (count == 0) { firstNormal = collision->normal; } else { if (count == 1) { // Re-orient velocity along the crease. if (mDot(dv,firstNormal) < 0.0f && mDot(collision->normal,firstNormal) < 0.0f) { VectorF nv; mCross(collision->normal,firstNormal,&nv); F32 nvl = nv.len(); if (nvl) { if (mDot(nv,mVelocity) < 0.0f) nvl = -nvl; nv *= mVelocity.len() / nvl; mVelocity = nv; } } } } } else { totalMotion += (end - start).len(); start = end; break; } } if (count == sMoveRetryCount) { // Failed to move start = initialPosition; mVelocity.set(0.0f, 0.0f, 0.0f); } return start; } F32 Player::_doCollisionImpact( const Collision *collision, bool fallingCollision) { F32 bd = -mDot( mVelocity, collision->normal); // shake camera on ground impact if( bd > mDataBlock->groundImpactMinSpeed && isControlObject() ) { F32 ampScale = (bd - mDataBlock->groundImpactMinSpeed) / mDataBlock->minImpactSpeed; CameraShake *groundImpactShake = new CameraShake; groundImpactShake->setDuration( mDataBlock->groundImpactShakeDuration ); groundImpactShake->setFrequency( mDataBlock->groundImpactShakeFreq ); VectorF shakeAmp = mDataBlock->groundImpactShakeAmp * ampScale; groundImpactShake->setAmplitude( shakeAmp ); groundImpactShake->setFalloff( mDataBlock->groundImpactShakeFalloff ); groundImpactShake->init(); gCamFXMgr.addFX( groundImpactShake ); } if ( ((bd > mDataBlock->minImpactSpeed && fallingCollision) || bd > mDataBlock->minLateralImpactSpeed) && !mMountPending ) { if ( !isGhost() ) onImpact( collision->object, collision->normal * bd ); if (mDamageState == Enabled && mState != RecoverState) { // Scale how long we're down for if (mDataBlock->landSequenceTime > 0.0f) { // Recover time is based on the land sequence setState(RecoverState); } else { // Legacy recover system F32 value = (bd - mDataBlock->minImpactSpeed); F32 range = (mDataBlock->minImpactSpeed * 0.9f); U32 recover = mDataBlock->recoverDelay; if (value < range) recover = 1 + S32(mFloor( F32(recover) * value / range) ); //Con::printf("Used %d recover ticks", recover); //Con::printf(" minImpact = %g, this one = %g", mDataBlock->minImpactSpeed, bd); setState(RecoverState, recover); } } } if ( isServerObject() && (bd > (mDataBlock->minImpactSpeed / 3.0f) || bd > (mDataBlock->minLateralImpactSpeed / 3.0f )) ) { mImpactSound = PlayerData::ImpactNormal; setMaskBits(ImpactMask); } return bd; } void Player::_handleCollision( const Collision &collision ) { // Track collisions if ( !isGhost() && collision.object && collision.object != mContactInfo.contactObject ) queueCollision( collision.object, mVelocity - collision.object->getVelocity() ); } bool Player::updatePos(const F32 travelTime) { PROFILE_SCOPE(Player_UpdatePos); getTransform().getColumn(3,&mDelta.posVec); // When mounted to another object, only Z rotation used. if (isMounted()) { mVelocity = mMount.object->getVelocity(); setPosition(Point3F(0.0f, 0.0f, 0.0f), mRot); setMaskBits(MoveMask); return true; } Point3F newPos; Collision col; dMemset( &col, 0, sizeof( col ) ); // DEBUG: //Point3F savedVelocity = mVelocity; if ( mPhysicsRep ) { static CollisionList collisionList; collisionList.clear(); newPos = mPhysicsRep->move( mVelocity * travelTime, collisionList ); bool haveCollisions = false; bool wasFalling = mFalling; if (collisionList.getCount() > 0) { mFalling = false; haveCollisions = true; } if (haveCollisions) { // Pick the collision that most closely matches our direction VectorF velNormal = mVelocity; velNormal.normalizeSafe(); const Collision *collision = &collisionList[0]; F32 collisionDot = mDot(velNormal, collision->normal); const Collision *cp = collision + 1; const Collision *ep = collision + collisionList.getCount(); for (; cp != ep; cp++) { F32 dp = mDot(velNormal, cp->normal); if (dp < collisionDot) { collisionDot = dp; collision = cp; } } _doCollisionImpact( collision, wasFalling ); // Modify our velocity based on collisions for (U32 i=0; i<collisionList.getCount(); ++i) { F32 bd = -mDot( mVelocity, collisionList[i].normal ); VectorF dv = collisionList[i].normal * (bd + sNormalElasticity); mVelocity += dv; } // Store the last collision for use later on. The handle collision // code only expects a single collision object. if (collisionList.getCount() > 0) col = collisionList[collisionList.getCount() - 1]; // We'll handle any player-to-player collision, and the last collision // with other obejct types. for (U32 i=0; i<collisionList.getCount(); ++i) { Collision& colCheck = collisionList[i]; if (colCheck.object) { SceneObject* obj = static_cast<SceneObject*>(col.object); if (obj->getTypeMask() & PlayerObjectType) { _handleCollision( colCheck ); } else { col = colCheck; } } } _handleCollision( col ); } } else { if ( mVelocity.isZero() ) newPos = mDelta.posVec; else newPos = _move( travelTime, &col ); _handleCollision( col ); } // DEBUG: //if ( isClientObject() ) // Con::printf( "(client) vel: %g %g %g", mVelocity.x, mVelocity.y, mVelocity.z ); //else // Con::printf( "(server) vel: %g %g %g", mVelocity.x, mVelocity.y, mVelocity.z ); // Set new position // If on the client, calc delta for backstepping if (isClientObject()) { mDelta.pos = newPos; mDelta.posVec = mDelta.posVec - mDelta.pos; mDelta.dt = 1.0f; } setPosition( newPos, mRot ); setMaskBits( MoveMask ); updateContainer(); if (!isGhost()) { // Collisions are only queued on the server and can be // generated by either updateMove or updatePos notifyCollision(); // Do mission area callbacks on the server as well checkMissionArea(); } // Check the total distance moved. If it is more than 1000th of the velocity, then // we moved a fair amount... //if (totalMotion >= (0.001f * initialSpeed)) return true; //else //return false; } //---------------------------------------------------------------------------- void Player::_findContact( SceneObject **contactObject, VectorF *contactNormal, Vector<SceneObject*> *outOverlapObjects ) { Point3F pos; getTransform().getColumn(3,&pos); Box3F wBox; Point3F exp(0,0,sTractionDistance); wBox.minExtents = pos + mScaledBox.minExtents - exp; wBox.maxExtents.x = pos.x + mScaledBox.maxExtents.x; wBox.maxExtents.y = pos.y + mScaledBox.maxExtents.y; wBox.maxExtents.z = pos.z + mScaledBox.minExtents.z + sTractionDistance; static ClippedPolyList polyList; polyList.clear(); polyList.doConstruct(); polyList.mNormal.set(0.0f, 0.0f, 0.0f); polyList.setInterestNormal(Point3F(0.0f, 0.0f, -1.0f)); polyList.mPlaneList.setSize(6); polyList.mPlaneList[0].setYZ(wBox.minExtents, -1.0f); polyList.mPlaneList[1].setXZ(wBox.maxExtents, 1.0f); polyList.mPlaneList[2].setYZ(wBox.maxExtents, 1.0f); polyList.mPlaneList[3].setXZ(wBox.minExtents, -1.0f); polyList.mPlaneList[4].setXY(wBox.minExtents, -1.0f); polyList.mPlaneList[5].setXY(wBox.maxExtents, 1.0f); Box3F plistBox = wBox; // Expand build box as it will be used to collide with items. // PickupRadius will be at least the size of the box. F32 pd = (F32)mDataBlock->pickupDelta; wBox.minExtents.x -= pd; wBox.minExtents.y -= pd; wBox.maxExtents.x += pd; wBox.maxExtents.y += pd; wBox.maxExtents.z = pos.z + mScaledBox.maxExtents.z; // Build list from convex states here... CollisionWorkingList& rList = mConvex.getWorkingList(); CollisionWorkingList* pList = rList.wLink.mNext; while (pList != &rList) { Convex* pConvex = pList->mConvex; U32 objectMask = pConvex->getObject()->getTypeMask(); if ( ( objectMask & sCollisionMoveMask ) && !( objectMask & PhysicalZoneObjectType ) ) { Box3F convexBox = pConvex->getBoundingBox(); if (plistBox.isOverlapped(convexBox)) pConvex->getPolyList(&polyList); } else outOverlapObjects->push_back( pConvex->getObject() ); pList = pList->wLink.mNext; } if (!polyList.isEmpty()) { // Pick flattest surface F32 bestVd = -1.0f; ClippedPolyList::Poly* poly = polyList.mPolyList.begin(); ClippedPolyList::Poly* end = polyList.mPolyList.end(); for (; poly != end; poly++) { F32 vd = poly->plane.z; // i.e. mDot(Point3F(0,0,1), poly->plane); if (vd > bestVd) { bestVd = vd; *contactObject = poly->object; *contactNormal = poly->plane; } } } } void Player::findContact( bool *run, bool *jump, VectorF *contactNormal ) { SceneObject *contactObject = NULL; Vector<SceneObject*> overlapObjects; if ( mPhysicsRep ) mPhysicsRep->findContact( &contactObject, contactNormal, &overlapObjects ); else _findContact( &contactObject, contactNormal, &overlapObjects ); // Check for triggers, corpses and items. const U32 filterMask = isGhost() ? sClientCollisionContactMask : sServerCollisionContactMask; for ( U32 i=0; i < overlapObjects.size(); i++ ) { SceneObject *obj = overlapObjects[i]; U32 objectMask = obj->getTypeMask(); if ( !( objectMask & filterMask ) ) continue; // Check: triggers, corpses and items... // if (objectMask & TriggerObjectType) { Trigger* pTrigger = static_cast<Trigger*>( obj ); pTrigger->potentialEnterObject(this); } else if (objectMask & CorpseObjectType) { // If we've overlapped the worldbounding boxes, then that's it... if ( getWorldBox().isOverlapped( obj->getWorldBox() ) ) { ShapeBase* col = static_cast<ShapeBase*>( obj ); queueCollision(col,getVelocity() - col->getVelocity()); } } else if (objectMask & ItemObjectType) { // If we've overlapped the worldbounding boxes, then that's it... Item* item = static_cast<Item*>( obj ); if ( getWorldBox().isOverlapped(item->getWorldBox()) && item->getCollisionObject() != this && !item->isHidden() ) queueCollision(item,getVelocity() - item->getVelocity()); } } F32 vd = (*contactNormal).z; *run = vd > mDataBlock->runSurfaceCos; *jump = vd > mDataBlock->jumpSurfaceCos; mContactInfo.clear(); mContactInfo.contacted = contactObject != NULL; mContactInfo.contactObject = contactObject; if ( mContactInfo.contacted ) mContactInfo.contactNormal = *contactNormal; mContactInfo.run = *run; mContactInfo.jump = *jump; } //---------------------------------------------------------------------------- void Player::checkMissionArea() { // Checks to see if the player is in the Mission Area... Point3F pos; MissionArea * obj = MissionArea::getServerObject(); if(!obj) return; const RectI &area = obj->getArea(); getTransform().getColumn(3, &pos); if ((pos.x < area.point.x || pos.x > area.point.x + area.extent.x || pos.y < area.point.y || pos.y > area.point.y + area.extent.y)) { if(mInMissionArea) { mInMissionArea = false; mDataBlock->onLeaveMissionArea_callback( this ); } } else if(!mInMissionArea) { mInMissionArea = true; mDataBlock->onEnterMissionArea_callback( this ); } } //---------------------------------------------------------------------------- bool Player::isDisplacable() const { return true; } Point3F Player::getMomentum() const { return mVelocity * getMass(); } void Player::setMomentum(const Point3F& newMomentum) { Point3F newVelocity = newMomentum / getMass(); mVelocity = newVelocity; } #define LH_HACK 1 // Hack for short-term soln to Training crash - #if LH_HACK static U32 sBalance; bool Player::displaceObject(const Point3F& displacement) { F32 vellen = mVelocity.len(); if (vellen < 0.001f || sBalance > 16) { mVelocity.set(0.0f, 0.0f, 0.0f); return false; } F32 dt = displacement.len() / vellen; sBalance++; bool result = updatePos(dt); sBalance--; getTransform().getColumn(3, &mDelta.pos); mDelta.posVec.set(0.0f, 0.0f, 0.0f); return result; } #else bool Player::displaceObject(const Point3F& displacement) { F32 vellen = mVelocity.len(); if (vellen < 0.001f) { mVelocity.set(0.0f, 0.0f, 0.0f); return false; } F32 dt = displacement.len() / vellen; bool result = updatePos(dt); mObjToWorld.getColumn(3, &mDelta.pos); mDelta.posVec.set(0.0f, 0.0f, 0.0f); return result; } #endif //---------------------------------------------------------------------------- void Player::setPosition(const Point3F& pos,const Point3F& rot) { MatrixF mat; if (isMounted()) { // Use transform from mounted object //MatrixF nmat,zrot; mMount.object->getMountTransform( mMount.node, mMount.xfm, &mat ); //zrot.set(EulerF(0.0f, 0.0f, rot.z)); //mat.mul(nmat,zrot); } else { mat.set(EulerF(0.0f, 0.0f, rot.z)); mat.setColumn(3,pos); } Parent::setTransform(mat); mRot = rot; if ( mPhysicsRep ) mPhysicsRep->setTransform( mat ); } void Player::setRenderPosition(const Point3F& pos, const Point3F& rot, F32 dt) { MatrixF mat; if (isMounted()) { // Use transform from mounted object //MatrixF nmat,zrot; mMount.object->getRenderMountTransform( dt, mMount.node, mMount.xfm, &mat ); //zrot.set(EulerF(0.0f, 0.0f, rot.z)); //mat.mul(nmat,zrot); } else { EulerF orient(0.0f, 0.0f, rot.z); mat.set(orient); mat.setColumn(3, pos); if (inDeathAnim()) { F32 boxRad = (mDataBlock->boxSize.x * 0.5f); if (MatrixF * fallMat = mDeath.fallToGround(dt, pos, rot.z, boxRad)) mat = * fallMat; } else mDeath.initFall(); } Parent::setRenderTransform(mat); } //---------------------------------------------------------------------------- void Player::setTransform(const MatrixF& mat) { // This method should never be called on the client. // This currently converts all rotation in the mat into // rotations around the z axis. Point3F pos,vec; mat.getColumn(1,&vec); mat.getColumn(3,&pos); Point3F rot(0.0f, 0.0f, -mAtan2(-vec.x,vec.y)); setPosition(pos,rot); setMaskBits(MoveMask | NoWarpMask); } void Player::getEyeTransform(MatrixF* mat) { getEyeBaseTransform(mat, true); // The shape instance is animated in getEyeBaseTransform() so we're // good here when attempting to get the eye node position on the server. S32 imageIndex = -1; S32 shapeIndex = -1; MountedImage* image = NULL; ShapeBaseImageData* data = NULL; for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { image = &(mMountedImageList[i]); if (image->dataBlock) { data = image->dataBlock; shapeIndex = getImageShapeIndex(*image); if ( data->useEyeNode && (data->animateOnServer || isGhost()) && isFirstPerson() && data->eyeMountNode[shapeIndex] != -1 && data->eyeNode[shapeIndex] != -1 ) { imageIndex = i; break; } } } if (imageIndex >= 0) { // Get the image's eye node's position relative to the eye mount node MatrixF mountTransform = image->shapeInstance[shapeIndex]->mNodeTransforms[data->eyeMountNode[shapeIndex]]; Point3F eyeMountNodePos = mountTransform.getPosition(); mountTransform = image->shapeInstance[shapeIndex]->mNodeTransforms[data->eyeNode[shapeIndex]]; Point3F eyeNodePos = mountTransform.getPosition() - eyeMountNodePos; // Now transform to the image's eye node (position only) MatrixF xfm(true); xfm.setPosition(eyeNodePos); mat->mul(xfm); } } void Player::getEyeBaseTransform(MatrixF* mat, bool includeBank) { // Eye transform in world space. We only use the eye position // from the animation and supply our own rotation. MatrixF pmat,xmat,zmat; if(!isGhost()) mShapeInstance->animate(); xmat.set(EulerF(mHead.x, 0.0f, 0.0f)); if (mUseHeadZCalc) zmat.set(EulerF(0.0f, 0.0f, mHead.z)); else zmat.identity(); if(includeBank && mDataBlock->cameraCanBank) { // Take mHead.y into account to bank the camera MatrixF imat; imat.mul(zmat, xmat); MatrixF ymat; ymat.set(EulerF(0.0f, mHead.y, 0.0f)); pmat.mul(imat, ymat); } else { pmat.mul(zmat,xmat); } F32 *dp = pmat; F32* sp; MatrixF eyeMat(true); if (mDataBlock->eyeNode != -1) { sp = mShapeInstance->mNodeTransforms[mDataBlock->eyeNode]; } else { Point3F center; mObjBox.getCenter(&center); eyeMat.setPosition(center); sp = eyeMat; } const Point3F& scale = getScale(); dp[3] = sp[3] * scale.x; dp[7] = sp[7] * scale.y; dp[11] = sp[11] * scale.z; mat->mul(getTransform(),pmat); } void Player::getRenderEyeTransform(MatrixF* mat) { getRenderEyeBaseTransform(mat, true); // Use the first image that is set to use the eye node for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { MountedImage& image = mMountedImageList[i]; if (image.dataBlock) { ShapeBaseImageData& data = *image.dataBlock; U32 shapeIndex = getImageShapeIndex(image); if ( data.useEyeNode && isFirstPerson() && data.eyeMountNode[shapeIndex] != -1 && data.eyeNode[shapeIndex] != -1 ) { // Get the eye node's position relative to the eye mount node MatrixF mountTransform = image.shapeInstance[shapeIndex]->mNodeTransforms[data.eyeMountNode[shapeIndex]]; Point3F eyeMountNodePos = mountTransform.getPosition(); mountTransform = image.shapeInstance[shapeIndex]->mNodeTransforms[data.eyeNode[shapeIndex]]; Point3F eyeNodePos = mountTransform.getPosition() - eyeMountNodePos; // Now transform to the image's eye node (position only) MatrixF xfm(true); xfm.setPosition(eyeNodePos); mat->mul(xfm); return; } } } } void Player::getRenderEyeBaseTransform(MatrixF* mat, bool includeBank) { // Eye transform in world space. We only use the eye position // from the animation and supply our own rotation. MatrixF pmat,xmat,zmat; xmat.set(EulerF(mDelta.head.x + mDelta.headVec.x * mDelta.dt, 0.0f, 0.0f)); if (mUseHeadZCalc) zmat.set(EulerF(0.0f, 0.0f, mDelta.head.z + mDelta.headVec.z * mDelta.dt)); else zmat.identity(); if(includeBank && mDataBlock->cameraCanBank) { // Take mHead.y delta into account to bank the camera MatrixF imat; imat.mul(zmat, xmat); MatrixF ymat; ymat.set(EulerF(0.0f, mDelta.head.y + mDelta.headVec.y * mDelta.dt, 0.0f)); pmat.mul(imat, ymat); } else { pmat.mul(zmat,xmat); } F32 *dp = pmat; F32* sp; MatrixF eyeMat(true); if (mDataBlock->eyeNode != -1) { sp = mShapeInstance->mNodeTransforms[mDataBlock->eyeNode]; } else { // Use the center of the Player's bounding box for the eye position. Point3F center; mObjBox.getCenter(&center); eyeMat.setPosition(center); sp = eyeMat; } // Only use position of eye node, and take Player's scale // into account. const Point3F& scale = getScale(); dp[3] = sp[3] * scale.x; dp[7] = sp[7] * scale.y; dp[11] = sp[11] * scale.z; mat->mul(getRenderTransform(), pmat); } void Player::getMuzzleTransform(U32 imageSlot,MatrixF* mat) { disableHeadZCalc(); MatrixF nmat; Parent::getRetractionTransform(imageSlot,&nmat); MatrixF smat; Parent::getImageTransform(imageSlot,&smat); disableCollision(); // See if we are pushed into a wall... if (getDamageState() == Enabled) { Point3F start, end; smat.getColumn(3, &start); nmat.getColumn(3, &end); RayInfo rinfo; if (getContainer()->castRay(start, end, sCollisionMoveMask, &rinfo)) { Point3F finalPoint; finalPoint.interpolate(start, end, rinfo.t); nmat.setColumn(3, finalPoint); } else Parent::getMuzzleTransform(imageSlot,&nmat); } else Parent::getMuzzleTransform(imageSlot,&nmat); enableCollision(); enableHeadZCalc(); *mat = nmat; } void Player::getRenderMuzzleTransform(U32 imageSlot,MatrixF* mat) { disableHeadZCalc(); MatrixF nmat; Parent::getRenderRetractionTransform(imageSlot,&nmat); MatrixF smat; Parent::getRenderImageTransform(imageSlot,&smat); disableCollision(); // See if we are pushed into a wall... if (getDamageState() == Enabled) { Point3F start, end; smat.getColumn(3, &start); nmat.getColumn(3, &end); RayInfo rinfo; if (getContainer()->castRay(start, end, sCollisionMoveMask, &rinfo)) { Point3F finalPoint; finalPoint.interpolate(start, end, rinfo.t); nmat.setColumn(3, finalPoint); } else { Parent::getRenderMuzzleTransform(imageSlot,&nmat); } } else { Parent::getRenderMuzzleTransform(imageSlot,&nmat); } enableCollision(); enableHeadZCalc(); *mat = nmat; } void Player::getMuzzleVector(U32 imageSlot,VectorF* vec) { MatrixF mat; getMuzzleTransform(imageSlot,&mat); GameConnection * gc = getControllingClient(); if (gc && !gc->isAIControlled()) { MountedImage& image = mMountedImageList[imageSlot]; bool fp = gc->isFirstPerson(); if ((fp && image.dataBlock->correctMuzzleVector) || (!fp && image.dataBlock->correctMuzzleVectorTP)) { disableHeadZCalc(); if (getCorrectedAim(mat, vec)) { enableHeadZCalc(); return; } enableHeadZCalc(); } } mat.getColumn(1,vec); } void Player::renderMountedImage( U32 imageSlot, TSRenderState &rstate, SceneRenderState *state ) { GFX->pushWorldMatrix(); MatrixF world; MountedImage& image = mMountedImageList[imageSlot]; ShapeBaseImageData& data = *image.dataBlock; U32 imageShapeIndex; if ( state->isShadowPass() ) { // Force the standard image shapes for the shadow pass. imageShapeIndex = ShapeBaseImageData::StandardImageShape; } else { imageShapeIndex = getImageShapeIndex(image); } if ( !state->isShadowPass() && isFirstPerson() && (data.useEyeOffset || (data.useEyeNode && data.eyeMountNode[imageShapeIndex] != -1)) ) { if (data.useEyeNode && data.eyeMountNode[imageShapeIndex] != -1) { MatrixF nmat; getRenderEyeBaseTransform(&nmat, mDataBlock->mountedImagesBank); MatrixF offsetMat = image.shapeInstance[imageShapeIndex]->mNodeTransforms[data.eyeMountNode[imageShapeIndex]]; offsetMat.affineInverse(); world.mul(nmat,offsetMat); } else { MatrixF nmat; getRenderEyeBaseTransform(&nmat, mDataBlock->mountedImagesBank); world.mul(nmat,data.eyeOffset); } if ( imageSlot == 0 ) { MatrixF nmat; MatrixF smat; getRenderRetractionTransform(0,&nmat); getRenderImageTransform(0,&smat); // See if we are pushed into a wall... Point3F start, end; smat.getColumn(3, &start); nmat.getColumn(3, &end); Point3F displace = (start - end) * mWeaponBackFraction; world.setPosition( world.getPosition() + displace ); } } else { MatrixF nmat; getRenderMountTransform( 0.0f, data.mountPoint, MatrixF::Identity, &nmat); world.mul(nmat,data.mountTransform[imageShapeIndex]); } GFX->setWorldMatrix( world ); image.shapeInstance[imageShapeIndex]->animate(); image.shapeInstance[imageShapeIndex]->render( rstate ); // Render the first person mount image shape? if (!state->isShadowPass() && imageShapeIndex == ShapeBaseImageData::FirstPersonImageShape && mShapeFPInstance[imageSlot]) { mShapeFPInstance[imageSlot]->animate(); mShapeFPInstance[imageSlot]->render( rstate ); } GFX->popWorldMatrix(); } // Bot aiming code calls this frequently and will work fine without the check // for being pushed into a wall, which shows up on profile at ~ 3% (eight bots) void Player::getMuzzlePointAI(U32 imageSlot, Point3F* point) { MatrixF nmat; Parent::getMuzzleTransform(imageSlot, &nmat); // If we are in one of the standard player animations, adjust the // muzzle to point in the direction we are looking. if (mActionAnimation.action < PlayerData::NumTableActionAnims) { MatrixF xmat; xmat.set(EulerF(mHead.x, 0, 0)); MatrixF result; result.mul(getTransform(), xmat); F32 *sp = nmat, *dp = result; dp[3] = sp[3]; dp[7] = sp[7]; dp[11] = sp[11]; result.getColumn(3, point); } else nmat.getColumn(3, point); } void Player::getCameraParameters(F32 *min,F32* max,Point3F* off,MatrixF* rot) { if (!mControlObject.isNull() && mControlObject == getObjectMount()) { mControlObject->getCameraParameters(min,max,off,rot); return; } const Point3F& scale = getScale(); *min = mDataBlock->cameraMinDist * scale.y; *max = mDataBlock->cameraMaxDist * scale.y; off->set(0.0f, 0.0f, 0.0f); rot->identity(); } //---------------------------------------------------------------------------- Point3F Player::getVelocity() const { return mVelocity; } F32 Player::getSpeed() const { return mVelocity.len(); } void Player::setVelocity(const VectorF& vel) { AssertFatal( !mIsNaN( vel ), "Player::setVelocity() - The velocity is NaN!" ); mVelocity = vel; setMaskBits(MoveMask); } void Player::applyImpulse(const Point3F&,const VectorF& vec) { AssertFatal( !mIsNaN( vec ), "Player::applyImpulse() - The vector is NaN!" ); // Players ignore angular velocity VectorF vel; vel.x = vec.x / getMass(); vel.y = vec.y / getMass(); vel.z = vec.z / getMass(); // Make sure the impulse isn't too big F32 len = vel.magnitudeSafe(); if (len > sMaxImpulseVelocity) { Point3F excess = vel * ( 1.0f - (sMaxImpulseVelocity / len ) ); vel -= excess; } setVelocity(mVelocity + vel); } //---------------------------------------------------------------------------- bool Player::castRay(const Point3F &start, const Point3F &end, RayInfo* info) { // In standard Torque there's a rather brute force culling of all // non-enabled players (corpses) from the ray cast. But, to // demonstrate a resurrection spell, we need corpses to be // selectable, so this code change allows consideration of corpses // in the ray cast if corpsesHiddenFromRayCast is set to false. if (sCorpsesHiddenFromRayCast && getDamageState() != Enabled) return false; // Collide against bounding box. Need at least this for the editor. F32 st,et,fst = 0.0f,fet = 1.0f; F32 *bmin = &mObjBox.minExtents.x; F32 *bmax = &mObjBox.maxExtents.x; F32 const *si = &start.x; F32 const *ei = &end.x; for (S32 i = 0; i < 3; i++) { if (*si < *ei) { if (*si > *bmax || *ei < *bmin) return false; F32 di = *ei - *si; st = (*si < *bmin)? (*bmin - *si) / di: 0.0f; et = (*ei > *bmax)? (*bmax - *si) / di: 1.0f; } else { if (*ei > *bmax || *si < *bmin) return false; F32 di = *ei - *si; st = (*si > *bmax)? (*bmax - *si) / di: 0.0f; et = (*ei < *bmin)? (*bmin - *si) / di: 1.0f; } if (st > fst) fst = st; if (et < fet) fet = et; if (fet < fst) return false; bmin++; bmax++; si++; ei++; } info->normal = start - end; info->normal.normalizeSafe(); getTransform().mulV( info->normal ); info->t = fst; info->object = this; info->point.interpolate(start,end,fst); info->material = 0; return true; } //---------------------------------------------------------------------------- static MatrixF IMat(1); bool Player::buildPolyList(PolyListContext, AbstractPolyList* polyList, const Box3F&, const SphereF&) { // Collision with the player is always against the player's object // space bounding box axis aligned in world space. Point3F pos; getTransform().getColumn(3,&pos); IMat.setColumn(3,pos); polyList->setTransform(&IMat, Point3F(1.0f,1.0f,1.0f)); polyList->setObject(this); polyList->addBox(mObjBox); return true; } void Player::buildConvex(const Box3F& box, Convex* convex) { if (mShapeInstance == NULL) return; // These should really come out of a pool mConvexList->collectGarbage(); Box3F realBox = box; mWorldToObj.mul(realBox); realBox.minExtents.convolveInverse(mObjScale); realBox.maxExtents.convolveInverse(mObjScale); if (realBox.isOverlapped(getObjBox()) == false) return; Convex* cc = 0; CollisionWorkingList& wl = convex->getWorkingList(); for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext) { if (itr->mConvex->getType() == BoxConvexType && itr->mConvex->getObject() == this) { cc = itr->mConvex; break; } } if (cc) return; // Create a new convex. BoxConvex* cp = new OrthoBoxConvex; mConvexList->registerObject(cp); convex->addToWorkingList(cp); cp->init(this); mObjBox.getCenter(&cp->mCenter); cp->mSize.x = mObjBox.len_x() / 2.0f; cp->mSize.y = mObjBox.len_y() / 2.0f; cp->mSize.z = mObjBox.len_z() / 2.0f; } //---------------------------------------------------------------------------- void Player::updateWorkingCollisionSet() { // First, we need to adjust our velocity for possible acceleration. It is assumed // that we will never accelerate more than 20 m/s for gravity, plus 10 m/s for // jetting, and an equivalent 10 m/s for jumping. We also assume that the // working list is updated on a Tick basis, which means we only expand our // box by the possible movement in that tick. Point3F scaledVelocity = mVelocity * TickSec; F32 len = scaledVelocity.len(); F32 newLen = len + (10.0f * TickSec); // Check to see if it is actually necessary to construct the new working list, // or if we can use the cached version from the last query. We use the x // component of the min member of the mWorkingQueryBox, which is lame, but // it works ok. bool updateSet = false; Box3F convexBox = mConvex.getBoundingBox(getTransform(), getScale()); F32 l = (newLen * 1.1f) + 0.1f; // from Convex::updateWorkingList const Point3F lPoint( l, l, l ); convexBox.minExtents -= lPoint; convexBox.maxExtents += lPoint; // Check containment if (mWorkingQueryBox.minExtents.x != -1e9f) { if (mWorkingQueryBox.isContained(convexBox) == false) // Needed region is outside the cached region. Update it. updateSet = true; } else { // Must update updateSet = true; } // Actually perform the query, if necessary if (updateSet == true) { const Point3F twolPoint( 2.0f * l, 2.0f * l, 2.0f * l ); mWorkingQueryBox = convexBox; mWorkingQueryBox.minExtents -= twolPoint; mWorkingQueryBox.maxExtents += twolPoint; disableCollision(); //We temporarily disable the collisions of anything mounted to us so we don't accidentally walk into things we've attached to us for (SceneObject *ptr = mMount.list; ptr; ptr = ptr->getMountLink()) { ptr->disableCollision(); } mConvex.updateWorkingList(mWorkingQueryBox, isGhost() ? sClientCollisionContactMask : sServerCollisionContactMask); //And now re-enable the collisions of the mounted things for (SceneObject *ptr = mMount.list; ptr; ptr = ptr->getMountLink()) { ptr->enableCollision(); } enableCollision(); } } //---------------------------------------------------------------------------- void Player::writePacketData(GameConnection *connection, BitStream *stream) { Parent::writePacketData(connection, stream); stream->writeInt(mState,NumStateBits); if (stream->writeFlag(mState == RecoverState)) stream->writeInt(mRecoverTicks,PlayerData::RecoverDelayBits); if (stream->writeFlag(mJumpDelay > 0)) stream->writeInt(mJumpDelay,PlayerData::JumpDelayBits); Point3F pos; getTransform().getColumn(3,&pos); if (stream->writeFlag(!isMounted())) { // Will get position from mount stream->setCompressionPoint(pos); stream->write(pos.x); stream->write(pos.y); stream->write(pos.z); stream->write(mVelocity.x); stream->write(mVelocity.y); stream->write(mVelocity.z); stream->writeInt(mJumpSurfaceLastContact > 15 ? 15 : mJumpSurfaceLastContact, 4); if (stream->writeFlag(!mAllowSprinting || !mAllowCrouching || !mAllowProne || !mAllowJumping || !mAllowJetJumping || !mAllowSwimming)) { stream->writeFlag(mAllowJumping); stream->writeFlag(mAllowJetJumping); stream->writeFlag(mAllowSprinting); stream->writeFlag(mAllowCrouching); stream->writeFlag(mAllowProne); stream->writeFlag(mAllowSwimming); } } stream->write(mHead.x); if(stream->writeFlag(mDataBlock->cameraCanBank)) { // Include mHead.y to allow for camera banking stream->write(mHead.y); } stream->write(mHead.z); stream->write(mRot.z); if (mControlObject) { S32 gIndex = connection->getGhostIndex(mControlObject); if (stream->writeFlag(gIndex != -1)) { stream->writeInt(gIndex,NetConnection::GhostIdBitSize); mControlObject->writePacketData(connection, stream); } } else stream->writeFlag(false); } void Player::readPacketData(GameConnection *connection, BitStream *stream) { Parent::readPacketData(connection, stream); mState = (ActionState)stream->readInt(NumStateBits); if (stream->readFlag()) mRecoverTicks = stream->readInt(PlayerData::RecoverDelayBits); if (stream->readFlag()) mJumpDelay = stream->readInt(PlayerData::JumpDelayBits); else mJumpDelay = 0; Point3F pos,rot; if (stream->readFlag()) { // Only written if we are not mounted stream->read(&pos.x); stream->read(&pos.y); stream->read(&pos.z); stream->read(&mVelocity.x); stream->read(&mVelocity.y); stream->read(&mVelocity.z); stream->setCompressionPoint(pos); mDelta.pos = pos; mJumpSurfaceLastContact = stream->readInt(4); if (stream->readFlag()) { mAllowJumping = stream->readFlag(); mAllowJetJumping = stream->readFlag(); mAllowSprinting = stream->readFlag(); mAllowCrouching = stream->readFlag(); mAllowProne = stream->readFlag(); mAllowSwimming = stream->readFlag(); } else { mAllowJumping = true; mAllowJetJumping = true; mAllowSprinting = true; mAllowCrouching = true; mAllowProne = true; mAllowSwimming = true; } } else pos = mDelta.pos; stream->read(&mHead.x); if(stream->readFlag()) { // Include mHead.y to allow for camera banking stream->read(&mHead.y); } stream->read(&mHead.z); stream->read(&rot.z); rot.x = rot.y = 0; if (!ignore_updates) setPosition(pos,rot); mDelta.head = mHead; mDelta.rot = rot; if (stream->readFlag()) { S32 gIndex = stream->readInt(NetConnection::GhostIdBitSize); ShapeBase* obj = static_cast<ShapeBase*>(connection->resolveGhost(gIndex)); setControlObject(obj); obj->readPacketData(connection, stream); } else setControlObject(0); } U32 Player::packUpdate(NetConnection *con, U32 mask, BitStream *stream) { U32 retMask = Parent::packUpdate(con, mask, stream); if (stream->writeFlag((mask & ImpactMask) && !(mask & InitialUpdateMask))) stream->writeInt(mImpactSound, PlayerData::ImpactBits); if (stream->writeFlag(mask & ActionMask && mActionAnimation.action != PlayerData::NullAnimation && mActionAnimation.action >= PlayerData::NumTableActionAnims)) { stream->writeInt(mActionAnimation.action,PlayerData::ActionAnimBits); stream->writeFlag(mActionAnimation.holdAtEnd); stream->writeFlag(mActionAnimation.atEnd); stream->writeFlag(mActionAnimation.firstPerson); if (!mActionAnimation.atEnd) { // If somewhere in middle on initial update, must send position- F32 where = mShapeInstance->getPos(mActionAnimation.thread); if (stream->writeFlag((mask & InitialUpdateMask) != 0 && where > 0)) stream->writeSignedFloat(where, 6); } } if (stream->writeFlag(mask & ActionMask && mArmAnimation.action != PlayerData::NullAnimation && (!(mask & InitialUpdateMask) || mArmAnimation.action != mDataBlock->lookAction))) { stream->writeInt(mArmAnimation.action,PlayerData::ActionAnimBits); } retMask = afx_packUpdate(con, mask, stream, retMask); // The rest of the data is part of the control object packet update. // If we're controlled by this client, we don't need to send it. // we only need to send it if this is the initial update - in that case, // the client won't know this is the control object yet. if(stream->writeFlag(getControllingClient() == con && !(mask & InitialUpdateMask))) return(retMask); if (stream->writeFlag(mask & MoveMask)) { stream->writeFlag(mFalling); stream->writeFlag(mSwimming); stream->writeFlag(mJetting); stream->writeInt(mPose, NumPoseBits); stream->writeInt(mState,NumStateBits); if (stream->writeFlag(mState == RecoverState)) stream->writeInt(mRecoverTicks,PlayerData::RecoverDelayBits); Point3F pos; getTransform().getColumn(3,&pos); stream->writeCompressedPoint(pos); F32 len = mVelocity.len(); if(stream->writeFlag(len > 0.02f)) { Point3F outVel = mVelocity; outVel *= 1.0f/len; stream->writeNormalVector(outVel, 10); len *= 32.0f; // 5 bits of fraction if(len > 8191) len = 8191; stream->writeInt((S32)len, 13); // constrain the range of mRot.z while (mRot.z < 0.0f) mRot.z += M_2PI_F; while (mRot.z > M_2PI_F) mRot.z -= M_2PI_F; } stream->writeFloat(mRot.z / M_2PI_F, 7); stream->writeSignedFloat(mHead.x / (mDataBlock->maxLookAngle - mDataBlock->minLookAngle), 6); stream->writeSignedFloat(mHead.z / mDataBlock->maxFreelookAngle, 6); mDelta.move.pack(stream); stream->writeFlag(!(mask & NoWarpMask)); } // Ghost need energy to predict reliably if (mDataBlock->maxEnergy > 0.f) stream->writeFloat(getEnergyLevel() / mDataBlock->maxEnergy, EnergyLevelBits); else stream->writeFloat(0.f, EnergyLevelBits); return retMask; } void Player::unpackUpdate(NetConnection *con, BitStream *stream) { Parent::unpackUpdate(con,stream); if (stream->readFlag()) mImpactSound = stream->readInt(PlayerData::ImpactBits); // Server specified action animation if (stream->readFlag()) { U32 action = stream->readInt(PlayerData::ActionAnimBits); bool hold = stream->readFlag(); bool atEnd = stream->readFlag(); bool fsp = stream->readFlag(); F32 animPos = -1.0f; if (!atEnd && stream->readFlag()) animPos = stream->readSignedFloat(6); if (isProperlyAdded()) { setActionThread(action,true,hold,true,fsp); bool inDeath = inDeathAnim(); if (atEnd) { mShapeInstance->clearTransition(mActionAnimation.thread); mShapeInstance->setPos(mActionAnimation.thread, mActionAnimation.forward? 1: 0); if (inDeath) mDeath.lastPos = 1.0f; } else if (animPos > 0) { mShapeInstance->setPos(mActionAnimation.thread, animPos); if (inDeath) mDeath.lastPos = animPos; } // mMountPending suppresses tickDelay countdown so players will sit until // their mount, or another animation, comes through (or 13 seconds elapses). mMountPending = (S32) (inSittingAnim() ? sMountPendingTickWait : 0); } else { mActionAnimation.action = action; mActionAnimation.holdAtEnd = hold; mActionAnimation.atEnd = atEnd; mActionAnimation.firstPerson = fsp; } } // Server specified arm animation if (stream->readFlag()) { U32 action = stream->readInt(PlayerData::ActionAnimBits); if (isProperlyAdded()) setArmThread(action); else mArmAnimation.action = action; } afx_unpackUpdate(con, stream); // Done if controlled by client ( and not initial update ) if(stream->readFlag()) return; // MoveMask if (stream->readFlag()) { mPredictionCount = sMaxPredictionTicks; mFalling = stream->readFlag(); mSwimming = stream->readFlag(); mJetting = stream->readFlag(); mPose = (Pose)(stream->readInt(NumPoseBits)); ActionState actionState = (ActionState)stream->readInt(NumStateBits); if (stream->readFlag()) { mRecoverTicks = stream->readInt(PlayerData::RecoverDelayBits); setState(actionState, mRecoverTicks); } else setState(actionState); Point3F pos,rot; stream->readCompressedPoint(&pos); F32 speed = mVelocity.len(); if(stream->readFlag()) { stream->readNormalVector(&mVelocity, 10); mVelocity *= stream->readInt(13) / 32.0f; } else { mVelocity.set(0.0f, 0.0f, 0.0f); } rot.y = rot.x = 0.0f; rot.z = stream->readFloat(7) * M_2PI_F; mHead.x = stream->readSignedFloat(6) * (mDataBlock->maxLookAngle - mDataBlock->minLookAngle); mHead.z = stream->readSignedFloat(6) * mDataBlock->maxFreelookAngle; mDelta.move.unpack(stream); mDelta.head = mHead; mDelta.headVec.set(0.0f, 0.0f, 0.0f); if (stream->readFlag() && isProperlyAdded()) { // Determine number of ticks to warp based on the average // of the client and server velocities. mDelta.warpOffset = pos - mDelta.pos; F32 as = (speed + mVelocity.len()) * 0.5f * TickSec; F32 dt = (as > 0.00001f) ? mDelta.warpOffset.len() / as: sMaxWarpTicks; mDelta.warpTicks = (S32)((dt > sMinWarpTicks) ? getMax(mFloor(dt + 0.5f), 1.0f) : 0.0f); if (mDelta.warpTicks) { // Setup the warp to start on the next tick. if (mDelta.warpTicks > sMaxWarpTicks) mDelta.warpTicks = sMaxWarpTicks; mDelta.warpOffset /= (F32)mDelta.warpTicks; mDelta.rotOffset = rot - mDelta.rot; // Ignore small rotation differences if (mFabs(mDelta.rotOffset.z) < 0.001f) mDelta.rotOffset.z = 0; // Wrap rotation to +/-PI if(mDelta.rotOffset.z < - M_PI_F) mDelta.rotOffset.z += M_2PI_F; else if(mDelta.rotOffset.z > M_PI_F) mDelta.rotOffset.z -= M_2PI_F; mDelta.rotOffset /= (F32)mDelta.warpTicks; } else { // Going to skip the warp, server and client are real close. // Adjust the frame interpolation to move smoothly to the // new position within the current tick. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt; if (mDelta.dt == 0) { mDelta.posVec.set(0.0f, 0.0f, 0.0f); mDelta.rotVec.set(0.0f, 0.0f, 0.0f); } else { F32 dti = 1.0f / mDelta.dt; mDelta.posVec = (cp - pos) * dti; mDelta.rotVec.z = mRot.z - rot.z; if(mDelta.rotVec.z > M_PI_F) mDelta.rotVec.z -= M_2PI_F; else if(mDelta.rotVec.z < -M_PI_F) mDelta.rotVec.z += M_2PI_F; mDelta.rotVec.z *= dti; } mDelta.pos = pos; mDelta.rot = rot; if (!ignore_updates) setPosition(pos,rot); } } else { // Set the player to the server position mDelta.pos = pos; mDelta.rot = rot; mDelta.posVec.set(0.0f, 0.0f, 0.0f); mDelta.rotVec.set(0.0f, 0.0f, 0.0f); mDelta.warpTicks = 0; mDelta.dt = 0.0f; if (!ignore_updates) setPosition(pos,rot); } } F32 energy = stream->readFloat(EnergyLevelBits) * mDataBlock->maxEnergy; setEnergyLevel(energy); } //---------------------------------------------------------------------------- DefineEngineMethod( Player, getPose, const char*, (),, "@brief Get the name of the player's current pose.\n\n" "The pose is one of the following:\n\n<ul>" "<li>Stand - Standard movement pose.</li>" "<li>Sprint - Sprinting pose.</li>" "<li>Crouch - Crouch pose.</li>" "<li>Prone - Prone pose.</li>" "<li>Swim - Swimming pose.</li></ul>\n" "@return The current pose; one of: \"Stand\", \"Sprint\", \"Crouch\", \"Prone\", \"Swim\"\n" ) { return object->getPoseName(); } DefineEngineMethod( Player, allowAllPoses, void, (),, "@brief Allow all poses a chance to occur.\n\n" "This method resets any poses that have manually been blocked from occuring. " "This includes the regular pose states such as sprinting, crouch, being prone " "and swimming. It also includes being able to jump and jet jump. While this " "is allowing these poses to occur it doesn't mean that they all can due to other " "conditions. We're just not manually blocking them from being allowed.\n" "@see allowJumping()\n" "@see allowJetJumping()\n" "@see allowSprinting()\n" "@see allowCrouching()\n" "@see allowProne()\n" "@see allowSwimming()\n" ) { object->allowAllPoses(); } DefineEngineMethod( Player, allowJumping, void, (bool state),, "@brief Set if the Player is allowed to jump.\n\n" "The default is to allow jumping unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow jumping " "at any time.\n" "@param state Set to true to allow jumping, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowJumping(state); } DefineEngineMethod( Player, allowJetJumping, void, (bool state),, "@brief Set if the Player is allowed to jet jump.\n\n" "The default is to allow jet jumping unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow jet jumping " "at any time.\n" "@param state Set to true to allow jet jumping, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowJetJumping(state); } DefineEngineMethod( Player, allowSprinting, void, (bool state),, "@brief Set if the Player is allowed to sprint.\n\n" "The default is to allow sprinting unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow sprinting " "at any time.\n" "@param state Set to true to allow sprinting, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowSprinting(state); } DefineEngineMethod( Player, allowCrouching, void, (bool state),, "@brief Set if the Player is allowed to crouch.\n\n" "The default is to allow crouching unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow crouching " "at any time.\n" "@param state Set to true to allow crouching, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowCrouching(state); } DefineEngineMethod( Player, allowProne, void, (bool state),, "@brief Set if the Player is allowed to go prone.\n\n" "The default is to allow being prone unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow going prone " "at any time.\n" "@param state Set to true to allow being prone, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowProne(state); } DefineEngineMethod( Player, allowSwimming, void, (bool state),, "@brief Set if the Player is allowed to swim.\n\n" "The default is to allow swimming unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow swimming " "at any time.\n" "@param state Set to true to allow swimming, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowSwimming(state); } //---------------------------------------------------------------------------- DefineEngineMethod( Player, getState, const char*, (),, "@brief Get the name of the player's current state.\n\n" "The state is one of the following:\n\n<ul>" "<li>Dead - The Player is dead.</li>" "<li>Mounted - The Player is mounted to an object such as a vehicle.</li>" "<li>Move - The Player is free to move. The usual state.</li>" "<li>Recover - The Player is recovering from a fall. See PlayerData::recoverDelay.</li></ul>\n" "@return The current state; one of: \"Dead\", \"Mounted\", \"Move\", \"Recover\"\n" ) { return object->getStateName(); } DefineEngineMethod( Player, getDamageLocation, const char*, ( Point3F pos ),, "@brief Get the named damage location and modifier for a given world position.\n\n" "the Player object can simulate different hit locations based on a pre-defined set " "of PlayerData defined percentages. These hit percentages divide up the Player's " "bounding box into different regions. The diagram below demonstrates how the various " "PlayerData properties split up the bounding volume:\n\n" "<img src=\"images/player_damageloc.png\">\n\n" "While you may pass in any world position and getDamageLocation() will provide a best-fit " "location, you should be aware that this can produce some interesting results. For example, " "any position that is above PlayerData::boxHeadPercentage will be considered a 'head' hit, even " "if the world position is high in the sky. Therefore it may be wise to keep the passed in point " "to somewhere on the surface of, or within, the Player's bounding volume.\n\n" "@note This method will not return an accurate location when the player is " "prone or swimming.\n\n" "@param pos A world position for which to retrieve a body region on this player.\n" "@return a string containing two words (space separated strings), where the " "first is a location and the second is a modifier.\n\n" "Posible locations:<ul>" "<li>head</li>" "<li>torso</li>" "<li>legs</li></ul>\n" "Head modifiers:<ul>" "<li>left_back</li>" "<li>middle_back</li>" "<li>right_back</li>" "<li>left_middle</li>" "<li>middle_middle</li>" "<li>right_middle</li>" "<li>left_front</li>" "<li>middle_front</li>" "<li>right_front</li></ul>\n" "Legs/Torso modifiers:<ul>" "<li>front_left</li>" "<li>front_right</li>" "<li>back_left</li>" "<li>back_right</li></ul>\n" "@see PlayerData::boxHeadPercentage\n" "@see PlayerData::boxHeadFrontPercentage\n" "@see PlayerData::boxHeadBackPercentage\n" "@see PlayerData::boxHeadLeftPercentage\n" "@see PlayerData::boxHeadRightPercentage\n" "@see PlayerData::boxTorsoPercentage\n" ) { const char *buffer1; const char *buffer2; object->getDamageLocation(pos, buffer1, buffer2); static const U32 bufSize = 128; char *buff = Con::getReturnBuffer(bufSize); dSprintf(buff, bufSize, "%s %s", buffer1, buffer2); return buff; } DefineEngineMethod( Player, setArmThread, bool, ( const char* name ),, "@brief Set the sequence that controls the player's arms (dynamically adjusted " "to match look direction).\n\n" "@param name Name of the sequence to play on the player's arms.\n" "@return true if successful, false if failed.\n" "@note By default the 'look' sequence is used, if available.\n") { return object->setArmThread( name ); } DefineEngineMethod( Player, setActionThread, bool, ( const char* name, bool hold, bool fsp ), ( false, true ), "@brief Set the main action sequence to play for this player.\n\n" "@param name Name of the action sequence to set\n" "@param hold Set to false to get a callback on the datablock when the sequence ends (PlayerData::animationDone()). " "When set to true no callback is made.\n" "@param fsp True if first person and none of the spine nodes in the shape should animate. False will allow the shape's " "spine nodes to animate.\n" "@return True if succesful, false if failed\n" "@note The spine nodes for the Player's shape are named as follows:\n\n<ul>" "<li>Bip01 Pelvis</li>" "<li>Bip01 Spine</li>" "<li>Bip01 Spine1</li>" "<li>Bip01 Spine2</li>" "<li>Bip01 Neck</li>" "<li>Bip01 Head</li></ul>\n\n" "You cannot use setActionThread() to have the Player play one of the motion " "determined action animation sequences. These sequences are chosen based on how " "the Player moves and the Player's current pose. The names of these sequences are:\n\n<ul>" "<li>root</li>" "<li>run</li>" "<li>side</li>" "<li>side_right</li>" "<li>crouch_root</li>" "<li>crouch_forward</li>" "<li>crouch_backward</li>" "<li>crouch_side</li>" "<li>crouch_right</li>" "<li>prone_root</li>" "<li>prone_forward</li>" "<li>prone_backward</li>" "<li>swim_root</li>" "<li>swim_forward</li>" "<li>swim_backward</li>" "<li>swim_left</li>" "<li>swim_right</li>" "<li>fall</li>" "<li>jump</li>" "<li>standjump</li>" "<li>land</li>" "<li>jet</li></ul>\n\n" "If the player moves in any direction then the animation sequence set using this " "method will be cancelled and the chosen mation-based sequence will take over. This makes " "great for times when the Player cannot move, such as when mounted, or when it doesn't matter " "if the action sequence changes, such as waving and saluting.\n" "@tsexample\n" "// Place the player in a sitting position after being mounted\n" "%player.setActionThread( \"sitting\", true, true );\n" "@endtsexample\n") { return object->setActionThread( name, hold, true, fsp); } DefineEngineMethod( Player, setControlObject, bool, ( ShapeBase* obj ),, "@brief Set the object to be controlled by this player\n\n" "It is possible to have the moves sent to the Player object from the " "GameConnection to be passed along to another object. This happens, for example " "when a player is mounted to a vehicle. The move commands pass through the Player " "and on to the vehicle (while the player remains stationary within the vehicle). " "With setControlObject() you can have the Player pass along its moves to any object. " "One possible use is for a player to move a remote controlled vehicle. In this case " "the player does not mount the vehicle directly, but still wants to be able to control it.\n" "@param obj Object to control with this player\n" "@return True if the object is valid, false if not\n" "@see getControlObject()\n" "@see clearControlObject()\n" "@see GameConnection::setControlObject()") { if (obj) { object->setControlObject(obj); return true; } else object->setControlObject(0); return false; } DefineEngineMethod( Player, getControlObject, S32, (),, "@brief Get the current object we are controlling.\n\n" "@return ID of the ShapeBase object we control, or 0 if not controlling an " "object.\n" "@see setControlObject()\n" "@see clearControlObject()") { ShapeBase* controlObject = object->getControlObject(); return controlObject ? controlObject->getId(): 0; } DefineEngineMethod( Player, clearControlObject, void, (),, "@brief Clears the player's current control object.\n\n" "Returns control to the player. This internally calls " "Player::setControlObject(0).\n" "@tsexample\n" "%player.clearControlObject();\n" "echo(%player.getControlObject()); //<-- Returns 0, player assumes control\n" "%player.setControlObject(%vehicle);\n" "echo(%player.getControlObject()); //<-- Returns %vehicle, player controls the vehicle now.\n" "@endtsexample\n" "@note If the player does not have a control object, the player will receive all moves " "from its GameConnection. If you're looking to remove control from the player itself " "(i.e. stop sending moves to the player) use GameConnection::setControlObject() to transfer " "control to another object, such as a camera.\n" "@see setControlObject()\n" "@see getControlObject()\n" "@see GameConnection::setControlObject()\n") { object->setControlObject(0); } DefineEngineMethod( Player, checkDismountPoint, bool, ( Point3F oldPos, Point3F pos ),, "@brief Check if it is safe to dismount at this position.\n\n" "Internally this method casts a ray from oldPos to pos to determine if it hits the " "terrain, an interior object, a water object, another player, a static shape, " "a vehicle (exluding the one currently mounted), or physical zone. If this ray " "is in the clear, then the player's bounding box is also checked for a collision at " "the pos position. If this displaced bounding box is also in the clear, then " "checkDismountPoint() returns true.\n" "@param oldPos The player's current position\n" "@param pos The dismount position to check\n" "@return True if the dismount position is clear, false if not\n" "@note The player must be already mounted for this method to not assert.\n") { MatrixF oldPosMat(true); oldPosMat.setColumn(3, oldPos); MatrixF posMat(true); posMat.setColumn(3, pos); return object->checkDismountPosition(oldPosMat, posMat); } DefineEngineMethod( Player, getNumDeathAnimations, S32, ( ),, "@brief Get the number of death animations available to this player.\n\n" "Death animations are assumed to be named death1-N using consecutive indices." ) { S32 count = 0; const PlayerData * db = dynamic_cast<PlayerData*>( object->getDataBlock() ); if ( db ) { for ( S32 i = 0; i < db->actionCount; i++ ) if ( db->actionList[i].death ) count++; } return count; } //---------------------------------------------------------------------------- void Player::consoleInit() { Con::addVariable("$player::renderMyPlayer",TypeBool, &sRenderMyPlayer, "@brief Determines if the player is rendered or not.\n\n" "Used on the client side to disable the rendering of all Player objects. This is " "mainly for the tools or debugging.\n" "@ingroup GameObjects\n"); Con::addVariable("$player::renderMyItems",TypeBool, &sRenderMyItems, "@brief Determines if mounted shapes are rendered or not.\n\n" "Used on the client side to disable the rendering of all Player mounted objects. This is " "mainly used for the tools or debugging.\n" "@ingroup GameObjects\n"); Con::addVariable("$player::renderCollision", TypeBool, &sRenderPlayerCollision, "@brief Determines if the player's collision mesh should be rendered.\n\n" "This is mainly used for the tools and debugging.\n" "@ingroup GameObjects\n"); Con::addVariable("$player::minWarpTicks",TypeF32,&sMinWarpTicks, "@brief Fraction of tick at which instant warp occures on the client.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::maxWarpTicks",TypeS32,&sMaxWarpTicks, "@brief When a warp needs to occur due to the client being too far off from the server, this is the " "maximum number of ticks we'll allow the client to warp to catch up.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::maxPredictionTicks",TypeS32,&sMaxPredictionTicks, "@brief Maximum number of ticks to predict on the client from the last known move obtained from the server.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::maxImpulseVelocity", TypeF32, &sMaxImpulseVelocity, "@brief The maximum velocity allowed due to a single impulse.\n\n" "@ingroup GameObjects\n"); // Move triggers Con::addVariable("$player::jumpTrigger", TypeS32, &sJumpTrigger, "@brief The move trigger index used for player jumping.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::crouchTrigger", TypeS32, &sCrouchTrigger, "@brief The move trigger index used for player crouching.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::proneTrigger", TypeS32, &sProneTrigger, "@brief The move trigger index used for player prone pose.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::sprintTrigger", TypeS32, &sSprintTrigger, "@brief The move trigger index used for player sprinting.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::imageTrigger0", TypeS32, &sImageTrigger0, "@brief The move trigger index used to trigger mounted image 0.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::imageTrigger1", TypeS32, &sImageTrigger1, "@brief The move trigger index used to trigger mounted image 1 or alternate fire " "on mounted image 0.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::jumpJetTrigger", TypeS32, &sJumpJetTrigger, "@brief The move trigger index used for player jump jetting.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::vehicleDismountTrigger", TypeS32, &sVehicleDismountTrigger, "@brief The move trigger index used to dismount player.\n\n" "@ingroup GameObjects\n"); // ExtendedMove support Con::addVariable("$player::extendedMoveHeadPosRotIndex", TypeS32, &smExtendedMoveHeadPosRotIndex, "@brief The ExtendedMove position/rotation index used for head movements.\n\n" "@ingroup GameObjects\n"); afx_consoleInit(); } //-------------------------------------------------------------------------- void Player::calcClassRenderData() { Parent::calcClassRenderData(); // If nothing is mounted do not perform the calculations below. Otherwise, // we'll end up with a bad ray cast as both nmat and smat will be the // Player's transform. MountedImage& image = mMountedImageList[0]; if (!image.dataBlock) { mWeaponBackFraction = 0.0f; return; } disableCollision(); MatrixF nmat; MatrixF smat; Parent::getRetractionTransform(0,&nmat); Parent::getImageTransform(0, &smat); // See if we are pushed into a wall... Point3F start, end; smat.getColumn(3, &start); nmat.getColumn(3, &end); RayInfo rinfo; if (getContainer()->castRay(start, end, sCollisionMoveMask & ~(WaterObjectType|PhysicalZoneObjectType|MarkerObjectType), &rinfo)) { if (rinfo.t < 1.0f) mWeaponBackFraction = 1.0f - rinfo.t; else mWeaponBackFraction = 0.0f; } else { mWeaponBackFraction = 0.0f; } enableCollision(); } //----------------------------------------------------------------------------- void Player::playFootstepSound( bool triggeredLeft, Material* contactMaterial, SceneObject* contactObject ) { if (footfallSoundOverride > 0) return; MatrixF footMat = getTransform(); if( mWaterCoverage > 0.0 ) { // Treading water. if ( mWaterCoverage < mDataBlock->footSplashHeight ) SFX->playOnce( mDataBlock->getPlayerSoundProfile( PlayerData::FootShallowSplash ), &footMat ); else { if ( mWaterCoverage < 1.0 ) SFX->playOnce( mDataBlock->getPlayerSoundProfile( PlayerData::FootWading ), &footMat ); else { if ( triggeredLeft ) { SFX->playOnce( mDataBlock->getPlayerSoundProfile( PlayerData::FootUnderWater ), &footMat ); SFX->playOnce( mDataBlock->getPlayerSoundProfile( PlayerData::FootBubbles ), &footMat ); } } } } else if( contactMaterial && contactMaterial->getCustomFootstepSoundProfile()) { // Footstep sound defined on material. SFX->playOnce( contactMaterial->getCustomFootstepSoundProfile(), &footMat ); } else { // Play default sound. S32 sound = -1; if (contactMaterial && (contactMaterial->mFootstepSoundId > -1 && contactMaterial->mFootstepSoundId < PlayerData::WaterStart)) sound = contactMaterial->mFootstepSoundId; else if( contactObject && contactObject->getTypeMask() & VehicleObjectType ) sound = 2; if (sound>=0) SFX->playOnce(mDataBlock->getPlayerSoundProfile(sound), &footMat); } } void Player:: playImpactSound() { if( mWaterCoverage == 0.0f ) { Point3F pos; RayInfo rInfo; MatrixF mat = getTransform(); mat.mulP(Point3F(mDataBlock->decalOffset,0.0f,0.0f), &pos); if( gClientContainer.castRay( Point3F( pos.x, pos.y, pos.z + 0.01f ), Point3F( pos.x, pos.y, pos.z - 2.0f ), STATIC_COLLISION_TYPEMASK | VehicleObjectType, &rInfo ) ) { Material* material = ( rInfo.material ? dynamic_cast< Material* >( rInfo.material->getMaterial() ) : 0 ); if( material && material->getCustomImpactSoundProfile() ) SFX->playOnce( material->getCustomImpactSoundProfile(), &getTransform() ); else { S32 sound = -1; if (material && (material->mImpactSoundId > -1 && material->mImpactSoundId < PlayerData::WaterStart)) sound = material->mImpactSoundId; else if( rInfo.object->getTypeMask() & VehicleObjectType ) sound = 2; // Play metal; if (sound >= 0) SFX->playOnce(mDataBlock->getPlayerSoundProfile(PlayerData::ImpactSoft + sound), &getTransform()); } } } mImpactSound = 0; } //-------------------------------------------------------------------------- // Update splash //-------------------------------------------------------------------------- void Player::updateSplash() { F32 speed = getVelocity().len(); if( speed < mDataBlock->splashVelocity || isMounted() ) return; Point3F curPos = getPosition(); if ( curPos.equal( mLastPos ) ) return; if (pointInWater( curPos )) { if (!pointInWater( mLastPos )) { Point3F norm = getVelocity(); norm.normalize(); // make sure player is moving vertically at good pace before playing splash F32 splashAng = mDataBlock->splashAngle / 360.0; if( mDot( norm, Point3F(0.0, 0.0, -1.0) ) < splashAng ) return; RayInfo rInfo; if (gClientContainer.castRay(mLastPos, curPos, WaterObjectType, &rInfo)) { createSplash( rInfo.point, speed ); mBubbleEmitterTime = 0.0; } } } } //-------------------------------------------------------------------------- void Player::updateFroth( F32 dt ) { // update bubbles Point3F moveDir = getVelocity(); mBubbleEmitterTime += dt; if (mBubbleEmitterTime < mDataBlock->bubbleEmitTime) { if (mSplashEmitter[PlayerData::BUBBLE_EMITTER]) { Point3F emissionPoint = getRenderPosition(); U32 emitNum = PlayerData::BUBBLE_EMITTER; mSplashEmitter[emitNum]->emitParticles(mLastPos, emissionPoint, Point3F( 0.0, 0.0, 1.0 ), moveDir, (U32)(dt * 1000.0)); } } Point3F contactPoint; if (!collidingWithWater(contactPoint)) { mLastWaterPos = mLastPos; return; } F32 speed = moveDir.len(); if ( speed < mDataBlock->splashVelEpsilon ) speed = 0.0; U32 emitRate = (U32) (speed * mDataBlock->splashFreqMod * dt); // If we're in the water, swimming, but not // moving, then lets emit some particles because // we're treading water. if ( mSwimming && speed == 0.0 ) { emitRate = (U32) (2.0f * mDataBlock->splashFreqMod * dt); } U32 i; for ( i=0; i<PlayerData::BUBBLE_EMITTER; i++ ) { if (mSplashEmitter[i] ) mSplashEmitter[i]->emitParticles( mLastWaterPos, contactPoint, Point3F( 0.0, 0.0, 1.0 ), moveDir, emitRate ); } mLastWaterPos = contactPoint; } void Player::updateWaterSounds(F32 dt) { if ( mWaterCoverage < 1.0f || mDamageState != Enabled ) { // Stop everything if ( mMoveBubbleSound ) mMoveBubbleSound->stop(); if ( mWaterBreathSound ) mWaterBreathSound->stop(); return; } if ( mMoveBubbleSound ) { // We're under water and still alive, so let's play something if ( mVelocity.len() > 1.0f ) { if ( !mMoveBubbleSound->isPlaying() ) mMoveBubbleSound->play(); mMoveBubbleSound->setTransform( getTransform() ); } else mMoveBubbleSound->stop(); } if ( mWaterBreathSound ) { if ( !mWaterBreathSound->isPlaying() ) mWaterBreathSound->play(); mWaterBreathSound->setTransform( getTransform() ); } } //-------------------------------------------------------------------------- // Returns true if player is intersecting a water surface //-------------------------------------------------------------------------- bool Player::collidingWithWater( Point3F &waterHeight ) { if ( !mCurrentWaterObject ) return false; Point3F curPos = getPosition(); if ( mWorldBox.maxExtents.z < mLiquidHeight ) return false; curPos.z = mLiquidHeight; waterHeight = getPosition(); waterHeight.z = mLiquidHeight; return true; } //-------------------------------------------------------------------------- void Player::createSplash( Point3F &pos, F32 speed ) { if ( speed >= mDataBlock->hardSplashSoundVel ) SFX->playOnce( mDataBlock->getPlayerSoundProfile(PlayerData::ImpactWaterHard), &getTransform() ); else if ( speed >= mDataBlock->medSplashSoundVel ) SFX->playOnce( mDataBlock->getPlayerSoundProfile(PlayerData::ImpactWaterMedium), &getTransform() ); else SFX->playOnce( mDataBlock->getPlayerSoundProfile(PlayerData::ImpactWaterEasy), &getTransform() ); if( mDataBlock->splash ) { MatrixF trans = getTransform(); trans.setPosition( pos ); Splash *splash = new Splash; splash->onNewDataBlock( mDataBlock->splash, false ); splash->setTransform( trans ); splash->setInitialState( trans.getPosition(), Point3F( 0.0, 0.0, 1.0 ) ); if (!splash->registerObject()) delete splash; } } bool Player::isControlObject() { GameConnection* connection = GameConnection::getConnectionToServer(); if( !connection ) return false; ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject()); return ( obj == this ); } void Player::prepRenderImage( SceneRenderState* state ) { bool renderPlayer = true; bool renderItems = true; /* if ( mPhysicsRep && Con::getBoolVariable("$PhysicsPlayer::DebugRender",false) ) { ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>(); ri->renderDelegate.bind( mPhysicsRep, &PhysicsPlayer::renderDebug ); ri->objectIndex = -1; ri->type = RenderPassManager::RIT_Editor; state->getRenderPass()->addInst( ri ); } */ // Debug rendering for all convexes in the Players working list. if ( sRenderPlayerCollision ) { ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>(); ri->renderDelegate.bind( this, &Player::renderConvex ); ri->objectIndex = -1; ri->type = RenderPassManager::RIT_Editor; state->getRenderPass()->addInst( ri ); } GameConnection* connection = GameConnection::getConnectionToServer(); if( connection && connection->getControlObject() == this && connection->isFirstPerson() ) { // If we're first person and we are not rendering the player // then disable all shadow rendering... a floating gun shadow sucks. if ( state->isShadowPass() && !mDataBlock->renderFirstPerson && !mDataBlock->firstPersonShadows ) return; renderPlayer = mDataBlock->renderFirstPerson || !state->isDiffusePass(); if( !sRenderMyPlayer ) renderPlayer = false; if( !sRenderMyItems ) renderItems = false; } // Call the protected base class to do the work // now that we know if we're rendering the player // and mounted shapes. return ShapeBase::_prepRenderImage( state, renderPlayer, renderItems ); } void Player::renderConvex( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat ) { GFX->enterDebugEvent( ColorI(255,0,255), "Player_renderConvex" ); mConvex.renderWorkingList(); GFX->leaveDebugEvent(); } // static bool Player::sCorpsesHiddenFromRayCast = true; // this default matches stock Torque behavior. // static void Player::afx_consoleInit() { Con::addVariable("pref::Player::corpsesHiddenFromRayCast", TypeBool, &sCorpsesHiddenFromRayCast); } void Player::afx_init() { overrideLookAnimation = false; armLookOverridePos = 0.5f; headVLookOverridePos = 0.5f; headHLookOverridePos = 0.5f; ignore_updates = false; fx_c_triggers = 0; mark_fx_c_triggers = 0; fx_s_triggers = 0; move_trigger_states = 0; z_velocity = 0.0f; mark_idle = false; idle_timer = 0.0f; mark_s_landing = false; speed_bias = 1.0f; speed_bias_goal = 1.0f; override_movement = 0; movement_data.zero(); movement_op = 1; last_movement_tag = 0; footfallDecalOverride = 0; footfallSoundOverride = 0; footfallDustOverride = 0; noFootfallFX = false; } U32 Player::afx_packUpdate(NetConnection* con, U32 mask, BitStream* stream, U32 retMask) { #if 0 if (stream->writeFlag(mask & LookOverrideMask)) #else if (stream->writeFlag(mask & ActionMask)) #endif stream->writeFlag(overrideLookAnimation); if (stream->writeFlag(mask & TriggerMask)) stream->write(fx_s_triggers); return retMask; } void Player::afx_unpackUpdate(NetConnection* con, BitStream* stream) { if (stream->readFlag()) // LookOverrideMask overrideLookAnimation = stream->readFlag(); if (stream->readFlag()) // TriggerMask { U32 mask; stream->read(&mask); mark_fx_c_triggers = mask; } } // Code for overriding player's animation with sequences selected by the // anim-clip component effect. void Player::restoreAnimation(U32 tag) { // check if this is a blended clip if ((tag & BLENDED_CLIP) != 0) { restoreBlendAnimation(tag); return; } if (tag != 0 && tag == last_anim_tag) { bool is_death_anim = ((anim_clip_flags & IS_DEATH_ANIM) != 0); anim_clip_flags &= ~(ANIM_OVERRIDDEN | IS_DEATH_ANIM); if (isClientObject()) { if (mDamageState != Enabled) { if (!is_death_anim) { // this is a bit hardwired and desperate, // but if he's dead he needs to look like it. setActionThread("death10", false, false, false); } } else if (mState != MoveState) { // not sure what happens here } else { pickActionAnimation(); } } last_anim_tag = 0; last_anim_id = -1; } } U32 Player::getAnimationID(const char* name) { for (U32 i = 0; i < mDataBlock->actionCount; i++) { PlayerData::ActionAnimation &anim = mDataBlock->actionList[i]; if (dStricmp(anim.name, name) == 0) return i; } Con::errorf("Player::getAnimationID() -- Player does not contain a sequence that matches the name, %s.", name); return BAD_ANIM_ID; } U32 Player::playAnimationByID(U32 anim_id, F32 pos, F32 rate, F32 trans, bool hold, bool wait, bool is_death_anim) { if (anim_id == BAD_ANIM_ID) return 0; S32 seq_id = mDataBlock->actionList[anim_id].sequence; if (seq_id == -1) { Con::errorf("Player::playAnimation() problem. BAD_SEQ_ID"); return 0; } if (mShapeInstance->getShape()->sequences[seq_id].isBlend()) return playBlendAnimation(seq_id, pos, rate); if (isClientObject()) { PlayerData::ActionAnimation &anim = mDataBlock->actionList[anim_id]; if (anim.sequence != -1) { mActionAnimation.action = anim_id; mActionAnimation.forward = (rate >= 0); mActionAnimation.firstPerson = false; mActionAnimation.holdAtEnd = hold; mActionAnimation.waitForEnd = hold? true: wait; mActionAnimation.animateOnServer = false; mActionAnimation.atEnd = false; mActionAnimation.delayTicks = (S32)sNewAnimationTickTime; F32 transTime = (trans < 0) ? sAnimationTransitionTime : trans; mShapeInstance->setTimeScale(mActionAnimation.thread, rate); mShapeInstance->transitionToSequence(mActionAnimation.thread,anim.sequence, pos, transTime, true); } } if (is_death_anim) anim_clip_flags |= IS_DEATH_ANIM; else anim_clip_flags &= ~IS_DEATH_ANIM; anim_clip_flags |= ANIM_OVERRIDDEN; last_anim_tag = unique_anim_tag_counter++; last_anim_id = anim_id; return last_anim_tag; } F32 Player::getAnimationDurationByID(U32 anim_id) { if (anim_id == BAD_ANIM_ID) return 0.0f; S32 seq_id = mDataBlock->actionList[anim_id].sequence; if (seq_id >= 0 && seq_id < mDataBlock->mShape->sequences.size()) return mDataBlock->mShape->sequences[seq_id].duration; return 0.0f; } bool Player::isBlendAnimation(const char* name) { U32 anim_id = getAnimationID(name); if (anim_id == BAD_ANIM_ID) return false; S32 seq_id = mDataBlock->actionList[anim_id].sequence; if (seq_id >= 0 && seq_id < mDataBlock->mShape->sequences.size()) return mDataBlock->mShape->sequences[seq_id].isBlend(); return false; } const char* Player::getLastClipName(U32 clip_tag) { if (clip_tag != last_anim_tag || last_anim_id >= PlayerData::NumActionAnims) return ""; return mDataBlock->actionList[last_anim_id].name; } void Player::unlockAnimation(U32 tag, bool force) { if ((tag != 0 && tag == last_anim_lock_tag) || force) anim_clip_flags &= ~BLOCK_USER_CONTROL; } U32 Player::lockAnimation() { anim_clip_flags |= BLOCK_USER_CONTROL; last_anim_lock_tag = unique_anim_tag_counter++; return last_anim_lock_tag; } DefineEngineMethod(Player, isAnimationLocked, bool, (),, "") { return object->isAnimationLocked(); } void Player::setLookAnimationOverride(bool flag) { overrideLookAnimation = flag; #if 0 setMaskBits(LookOverrideMask); #else setMaskBits(ActionMask); #endif } DefineEngineMethod(Player, setLookAnimationOverride, void, (bool flag),, "") { object->setLookAnimationOverride(flag); } DefineEngineMethod(Player, copyHeadRotation, void, (Player* other_player),, "") { if (other_player) object->copyHeadRotation(other_player); } void Player::process_client_triggers(bool triggeredLeft, bool triggeredRight) { bool mark_landing = false; Point3F my_vel = getVelocity(); if (my_vel.z > 5.0f) z_velocity = 1; else if (my_vel.z < -5.0f) z_velocity = -1; else { if (z_velocity < 0) mark_landing = true; z_velocity = 0.0f; } fx_c_triggers = mark_fx_c_triggers; if (triggeredLeft) fx_c_triggers |= PLAYER_LF_FOOT_C_TRIGGER; if (triggeredRight) fx_c_triggers |= PLAYER_RT_FOOT_C_TRIGGER; if (mark_landing) fx_c_triggers |= PLAYER_LANDING_C_TRIGGER; if (idle_timer > 10.0f) { fx_c_triggers |= PLAYER_IDLE_C_TRIGGER; idle_timer = 0.0f; } if (fx_c_triggers & PLAYER_LANDING_S_TRIGGER) { fx_c_triggers &= ~(PLAYER_LANDING_S_TRIGGER); } } U32 Player::unique_movement_tag_counter = 1; void Player::setMovementSpeedBias(F32 bias) { speed_bias_goal = bias; } U32 Player::setMovementOverride(F32 bias, const Point3F* mov, U32 op) { if (mov) { movement_data = *mov; override_movement = true; movement_op = (U8)op; } else override_movement = false; speed_bias_goal = bias; last_movement_tag = unique_movement_tag_counter++; return last_movement_tag; } void Player::restoreMovement(U32 tag) { if (tag != 0 && tag == last_movement_tag) { speed_bias_goal = 1.0; override_movement = false; } } DefineEngineMethod(Player, setMovementSpeedBias, void, (F32 bias),, "setMovementSpeedBias(F32 bias)") { object->setMovementSpeedBias(bias); } void Player::overrideFootfallFX(bool decals, bool sounds, bool dust) { if (decals) footfallDecalOverride++; if (sounds) footfallSoundOverride++; if (dust) footfallDustOverride++; noFootfallFX = (footfallDecalOverride > 0 && footfallSoundOverride > 0 && footfallDustOverride > 0); } void Player::restoreFootfallFX(bool decals, bool sounds, bool dust) { if (decals && footfallDecalOverride) footfallDecalOverride--; if (sounds && footfallSoundOverride) footfallSoundOverride--; if (dust && footfallDustOverride) footfallDustOverride--; noFootfallFX = (footfallDecalOverride > 0 && footfallSoundOverride > 0 && footfallDustOverride > 0); } #ifdef TORQUE_OPENVR void Player::setControllers(Vector<OpenVRTrackedObject*> controllerList) { mControllers[0] = controllerList.size() > 0 ? controllerList[0] : NULL; mControllers[1] = controllerList.size() > 1 ? controllerList[1] : NULL; } DefineEngineMethod(Player, setVRControllers, void, (OpenVRTrackedObject* controllerL, OpenVRTrackedObject* controllerR,, "") { Vector<OpenVRTrackedObject*> list; if (controllerL) { list.push_back(controllerL); } else { list.push_back(NULL); } if (controllerR) { list.push_back(controllerR); } else { list.push_back(NULL); } object->setControllers(list); } #endif constrain player mRot.z reguardless of translation //----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames // Copyright (C) 2015 Faust Logic, Inc. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// #include "platform/platform.h" #include "T3D/player.h" #include "platform/profiler.h" #include "math/mMath.h" #include "math/mathIO.h" #include "core/resourceManager.h" #include "core/stringTable.h" #include "core/volume.h" #include "core/stream/bitStream.h" #include "console/consoleTypes.h" #include "console/engineAPI.h" #include "collision/extrudedPolyList.h" #include "collision/clippedPolyList.h" #include "collision/earlyOutPolyList.h" #include "ts/tsShapeInstance.h" #include "sfx/sfxSystem.h" #include "sfx/sfxTrack.h" #include "sfx/sfxSource.h" #include "sfx/sfxTypes.h" #include "scene/sceneManager.h" #include "scene/sceneRenderState.h" #include "T3D/gameBase/gameConnection.h" #include "T3D/trigger.h" #include "T3D/physicalZone.h" #include "T3D/item.h" #include "T3D/missionArea.h" #include "T3D/fx/particleEmitter.h" #include "T3D/fx/cameraFXMgr.h" #include "T3D/fx/splash.h" #include "T3D/tsStatic.h" #include "T3D/physics/physicsPlugin.h" #include "T3D/physics/physicsPlayer.h" #include "T3D/decal/decalManager.h" #include "T3D/decal/decalData.h" #include "materials/baseMatInstance.h" #include "math/mathUtils.h" #include "gfx/sim/debugDraw.h" #ifdef TORQUE_EXTENDED_MOVE #include "T3D/gameBase/extended/extendedMove.h" #endif #ifdef TORQUE_OPENVR #include "platform/input/openVR/openVRProvider.h" #include "platform/input/openVR/openVRTrackedObject.h" #endif // Amount of time if takes to transition to a new action sequence. static F32 sAnimationTransitionTime = 0.25f; static bool sUseAnimationTransitions = true; static F32 sLandReverseScale = 0.25f; static F32 sSlowStandThreshSquared = 1.69f; static S32 sRenderMyPlayer = true; static S32 sRenderMyItems = true; static bool sRenderPlayerCollision = false; // Chooses new action animations every n ticks. static const F32 sNewAnimationTickTime = 4.0f; static const F32 sMountPendingTickWait = 13.0f * F32(TickMs); // Number of ticks before we pick non-contact animations static const S32 sContactTickTime = 10; // Movement constants static F32 sVerticalStepDot = 0.173f; // 80 static F32 sMinFaceDistance = 0.01f; static F32 sTractionDistance = 0.04f; static F32 sNormalElasticity = 0.01f; static U32 sMoveRetryCount = 5; static F32 sMaxImpulseVelocity = 200.0f; // Move triggers static S32 sJumpTrigger = 2; static S32 sCrouchTrigger = 3; static S32 sProneTrigger = 4; static S32 sSprintTrigger = 5; static S32 sImageTrigger0 = 0; static S32 sImageTrigger1 = 1; static S32 sJumpJetTrigger = 1; static S32 sVehicleDismountTrigger = 2; // Client prediction static F32 sMinWarpTicks = 0.5f; // Fraction of tick at which instant warp occurs static S32 sMaxWarpTicks = 3; // Max warp duration in ticks static S32 sMaxPredictionTicks = 30; // Number of ticks to predict S32 Player::smExtendedMoveHeadPosRotIndex = 0; // The ExtendedMove position/rotation index used for head movements // static U32 sCollisionMoveMask = TerrainObjectType | WaterObjectType | PlayerObjectType | StaticShapeObjectType | VehicleObjectType | PhysicalZoneObjectType | // PATHSHAPE PathShapeObjectType; // PATHSHAPE END static U32 sServerCollisionContactMask = sCollisionMoveMask | ItemObjectType | TriggerObjectType | CorpseObjectType; static U32 sClientCollisionContactMask = sCollisionMoveMask | TriggerObjectType; enum PlayerConstants { JumpSkipContactsMax = 8 }; //---------------------------------------------------------------------------- // Player shape animation sequences: // Action Animations: PlayerData::ActionAnimationDef PlayerData::ActionAnimationList[NumTableActionAnims] = { // *** WARNING *** // This array is indexed using the enum values defined in player.h // Root is the default animation { "root" }, // RootAnim, // These are selected in the move state based on velocity { "run", { 0.0f, 1.0f, 0.0f } }, // RunForwardAnim, { "back", { 0.0f,-1.0f, 0.0f } }, // BackBackwardAnim { "side", {-1.0f, 0.0f, 0.0f } }, // SideLeftAnim, { "side_right", { 1.0f, 0.0f, 0.0f } }, // SideRightAnim, { "sprint_root" }, { "sprint_forward", { 0.0f, 1.0f, 0.0f } }, { "sprint_backward", { 0.0f,-1.0f, 0.0f } }, { "sprint_side", {-1.0f, 0.0f, 0.0f } }, { "sprint_right", { 1.0f, 0.0f, 0.0f } }, { "crouch_root" }, { "crouch_forward", { 0.0f, 1.0f, 0.0f } }, { "crouch_backward", { 0.0f,-1.0f, 0.0f } }, { "crouch_side", {-1.0f, 0.0f, 0.0f } }, { "crouch_right", { 1.0f, 0.0f, 0.0f } }, { "prone_root" }, { "prone_forward", { 0.0f, 1.0f, 0.0f } }, { "prone_backward", { 0.0f,-1.0f, 0.0f } }, { "swim_root" }, { "swim_forward", { 0.0f, 1.0f, 0.0f } }, { "swim_backward", { 0.0f,-1.0f, 0.0f } }, { "swim_left", {-1.0f, 0.0f, 0.0f } }, { "swim_right", { 1.0f, 0.0f, 0.0f } }, // These are set explicitly based on player actions { "fall" }, // FallAnim { "jump" }, // JumpAnim { "standjump" }, // StandJumpAnim { "land" }, // LandAnim { "jet" }, // JetAnim }; //---------------------------------------------------------------------------- typedef PlayerData::Sounds playerSoundsEnum; DefineEnumType(playerSoundsEnum); ImplementEnumType(playerSoundsEnum, "enum types.\n" "@ingroup PlayerData\n\n") { playerSoundsEnum::FootSoft, "FootSoft", "..." }, { playerSoundsEnum::FootHard, "FootHard","..." }, { playerSoundsEnum::FootMetal, "FootMetal","..." }, { playerSoundsEnum::FootSnow, "FootSnow","..." }, { playerSoundsEnum::FootShallowSplash, "FootShallowSplash","..." }, { playerSoundsEnum::FootWading, "FootWading","..." }, { playerSoundsEnum::FootUnderWater, "FootUnderWater","..." }, { playerSoundsEnum::FootBubbles, "FootBubbles","..." }, { playerSoundsEnum::MoveBubbles, "MoveBubbles","..." }, { playerSoundsEnum::WaterBreath, "WaterBreath","..." }, { playerSoundsEnum::ImpactSoft, "ImpactSoft","..." }, { playerSoundsEnum::ImpactHard, "ImpactHard","..." }, { playerSoundsEnum::ImpactMetal, "ImpactMetal","..." }, { playerSoundsEnum::ImpactSnow, "ImpactSnow","..." }, { playerSoundsEnum::ImpactWaterEasy, "ImpactWaterEasy","..." }, { playerSoundsEnum::ImpactWaterMedium, "ImpactWaterMedium","..." }, { playerSoundsEnum::ImpactWaterHard, "ImpactWaterHard","..." }, { playerSoundsEnum::ExitWater, "ExitWater","..." }, EndImplementEnumType; //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- IMPLEMENT_CO_DATABLOCK_V1(PlayerData); ConsoleDocClass( PlayerData, "@brief Defines properties for a Player object.\n\n" "@see Player\n" "@ingroup gameObjects\n" ); IMPLEMENT_CALLBACK( PlayerData, onPoseChange, void, ( Player* obj, const char* oldPose, const char* newPose ), ( obj, oldPose, newPose ), "@brief Called when the player changes poses.\n\n" "@param obj The Player object\n" "@param oldPose The pose the player is switching from.\n" "@param newPose The pose the player is switching to.\n"); IMPLEMENT_CALLBACK( PlayerData, onStartSwim, void, ( Player* obj ), ( obj ), "@brief Called when the player starts swimming.\n\n" "@param obj The Player object\n" ); IMPLEMENT_CALLBACK( PlayerData, onStopSwim, void, ( Player* obj ), ( obj ), "@brief Called when the player stops swimming.\n\n" "@param obj The Player object\n" ); IMPLEMENT_CALLBACK( PlayerData, onStartSprintMotion, void, ( Player* obj ), ( obj ), "@brief Called when the player starts moving while in a Sprint pose.\n\n" "@param obj The Player object\n" ); IMPLEMENT_CALLBACK( PlayerData, onStopSprintMotion, void, ( Player* obj ), ( obj ), "@brief Called when the player stops moving while in a Sprint pose.\n\n" "@param obj The Player object\n" ); IMPLEMENT_CALLBACK( PlayerData, doDismount, void, ( Player* obj ), ( obj ), "@brief Called when attempting to dismount the player from a vehicle.\n\n" "It is up to the doDismount() method to actually perform the dismount. Often " "there are some conditions that prevent this, such as the vehicle moving too fast.\n" "@param obj The Player object\n" ); IMPLEMENT_CALLBACK( PlayerData, onEnterLiquid, void, ( Player* obj, F32 coverage, const char* type ), ( obj, coverage, type ), "@brief Called when the player enters a liquid.\n\n" "@param obj The Player object\n" "@param coverage Percentage of the player's bounding box covered by the liquid\n" "@param type The type of liquid the player has entered\n" ); IMPLEMENT_CALLBACK( PlayerData, onLeaveLiquid, void, ( Player* obj, const char* type ), ( obj, type ), "@brief Called when the player leaves a liquid.\n\n" "@param obj The Player object\n" "@param type The type of liquid the player has left\n" ); IMPLEMENT_CALLBACK( PlayerData, animationDone, void, ( Player* obj ), ( obj ), "@brief Called on the server when a scripted animation completes.\n\n" "@param obj The Player object\n" "@see Player::setActionThread() for setting a scripted animation and its 'hold' parameter to " "determine if this callback is used.\n" ); IMPLEMENT_CALLBACK( PlayerData, onEnterMissionArea, void, ( Player* obj ), ( obj ), "@brief Called when the player enters the mission area.\n\n" "@param obj The Player object\n" "@see MissionArea\n" ); IMPLEMENT_CALLBACK( PlayerData, onLeaveMissionArea, void, ( Player* obj ), ( obj ), "@brief Called when the player leaves the mission area.\n" "@param obj The Player object\n" "@see MissionArea\n" ); PlayerData::PlayerData() { shadowEnable = true; shadowSize = 256; shadowProjectionDistance = 14.0f; renderFirstPerson = true; firstPersonShadows = false; // Used for third person image rendering imageAnimPrefix = StringTable->EmptyString(); allowImageStateAnimation = false; // Used for first person image rendering imageAnimPrefixFP = StringTable->EmptyString(); for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { INIT_ASSET_ARRAY(ShapeFP, i); mCRCFP[i] = 0; mValidShapeFP[i] = false; } pickupRadius = 0.0f; minLookAngle = -1.4f; maxLookAngle = 1.4f; maxFreelookAngle = 3.0f; maxTimeScale = 1.5f; mass = 9.0f; // from ShapeBase maxEnergy = 60.0f; // from ShapeBase drag = 0.3f; // from ShapeBase density = 1.1f; // from ShapeBase maxStepHeight = 1.0f; runSurfaceAngle = 80.0f; runSurfaceCos = mCos(mDegToRad(runSurfaceAngle)); fallingSpeedThreshold = -10.0f; recoverDelay = 30; recoverRunForceScale = 1.0f; landSequenceTime = 0.0f; transitionToLand = false; // Running/Walking runForce = 40.0f * 9.0f; runEnergyDrain = 0.0f; minRunEnergy = 0.0f; maxForwardSpeed = 10.0f; maxBackwardSpeed = 10.0f; maxSideSpeed = 10.0f; // Jumping jumpForce = 75.0f; jumpEnergyDrain = 0.0f; minJumpEnergy = 0.0f; jumpSurfaceAngle = 78.0f; jumpSurfaceCos = mCos(mDegToRad(jumpSurfaceAngle)); for (U32 i = 0; i < NumRecoilSequences; i++) recoilSequence[i] = -1; jumpDelay = 30; minJumpSpeed = 500.0f; maxJumpSpeed = 2.0f * minJumpSpeed; // Sprinting sprintForce = 50.0f * 9.0f; sprintEnergyDrain = 0.0f; minSprintEnergy = 0.0f; maxSprintForwardSpeed = 15.0f; maxSprintBackwardSpeed = 10.0f; maxSprintSideSpeed = 10.0f; sprintStrafeScale = 1.0f; sprintYawScale = 1.0f; sprintPitchScale = 1.0f; sprintCanJump = true; // Swimming swimForce = 55.0f * 9.0f; maxUnderwaterForwardSpeed = 6.0f; maxUnderwaterBackwardSpeed = 6.0f; maxUnderwaterSideSpeed = 6.0f; // Crouching crouchForce = 45.0f * 9.0f; maxCrouchForwardSpeed = 4.0f; maxCrouchBackwardSpeed = 4.0f; maxCrouchSideSpeed = 4.0f; // Prone proneForce = 45.0f * 9.0f; maxProneForwardSpeed = 2.0f; maxProneBackwardSpeed = 2.0f; maxProneSideSpeed = 0.0f; // Jetting jetJumpForce = 0; jetJumpEnergyDrain = 0; jetMinJumpEnergy = 0; jetJumpSurfaceAngle = 78; jetMinJumpSpeed = 20; jetMaxJumpSpeed = 100; horizMaxSpeed = 80.0f; horizResistSpeed = 38.0f; horizResistFactor = 1.0f; upMaxSpeed = 80.0f; upResistSpeed = 38.0f; upResistFactor = 1.0f; minImpactSpeed = 25.0f; minLateralImpactSpeed = 25.0f; decalData = NULL; decalID = 0; decalOffset = 0.0f; actionCount = 0; lookAction = 0; dMemset(spineNode, 0, sizeof(spineNode)); pickupDelta = 0.0f; // size of bounding box boxSize.set(1.0f, 1.0f, 2.3f); crouchBoxSize.set(1.0f, 1.0f, 2.0f); proneBoxSize.set(1.0f, 2.3f, 1.0f); swimBoxSize.set(1.0f, 2.3f, 1.0f); // location of head, torso, legs boxHeadPercentage = 0.85f; boxTorsoPercentage = 0.55f; // damage locations boxHeadLeftPercentage = 0; boxHeadRightPercentage = 1; boxHeadBackPercentage = 0; boxHeadFrontPercentage = 1; for (S32 i = 0; i < MaxSounds; i++) INIT_ASSET_ARRAY(PlayerSound, i); footPuffEmitter = NULL; footPuffID = 0; footPuffNumParts = 15; footPuffRadius = .25f; dustEmitter = NULL; dustID = 0; splash = NULL; splashId = 0; splashVelocity = 1.0f; splashAngle = 45.0f; splashFreqMod = 300.0f; splashVelEpsilon = 0.25f; bubbleEmitTime = 0.4f; medSplashSoundVel = 2.0f; hardSplashSoundVel = 3.0f; exitSplashSoundVel = 2.0f; footSplashHeight = 0.1f; dMemset( splashEmitterList, 0, sizeof( splashEmitterList ) ); dMemset( splashEmitterIDList, 0, sizeof( splashEmitterIDList ) ); groundImpactMinSpeed = 10.0f; groundImpactShakeFreq.set( 10.0f, 10.0f, 10.0f ); groundImpactShakeAmp.set( 20.0f, 20.0f, 20.0f ); groundImpactShakeDuration = 1.0f; groundImpactShakeFalloff = 10.0f; // Air control airControl = 0.0f; jumpTowardsNormal = true; physicsPlayerType = StringTable->EmptyString(); dMemset( actionList, 0, sizeof(actionList) ); } bool PlayerData::preload(bool server, String &errorStr) { if(!Parent::preload(server, errorStr)) return false; for (U32 i = 0; i < MaxSounds; ++i) { _setPlayerSound(getPlayerSound(i), i); if (getPlayerSound(i) != StringTable->EmptyString()) { if (!getPlayerSoundProfile(i)) Con::errorf("PlayerData::Preload() - unable to find sfxProfile for asset %d %s", i, mPlayerSoundAssetId[i]); } } // runSurfaceCos = mCos(mDegToRad(runSurfaceAngle)); jumpSurfaceCos = mCos(mDegToRad(jumpSurfaceAngle)); if (minJumpEnergy < jumpEnergyDrain) minJumpEnergy = jumpEnergyDrain; // Jetting if (jetMinJumpEnergy < jetJumpEnergyDrain) jetMinJumpEnergy = jetJumpEnergyDrain; // Validate some of the data if (fallingSpeedThreshold > 0.0f) Con::printf("PlayerData:: Falling speed threshold should be downwards (negative)"); if (recoverDelay > (1 << RecoverDelayBits) - 1) { recoverDelay = (1 << RecoverDelayBits) - 1; Con::printf("PlayerData:: Recover delay exceeds range (0-%d)",recoverDelay); } if (jumpDelay > (1 << JumpDelayBits) - 1) { jumpDelay = (1 << JumpDelayBits) - 1; Con::printf("PlayerData:: Jump delay exceeds range (0-%d)",jumpDelay); } // If we don't have a shape don't crash out trying to // setup animations and sequences. if ( mShape ) { // Go ahead a pre-load the player shape TSShapeInstance* si = new TSShapeInstance(mShape, false); TSThread* thread = si->addThread(); // Extract ground transform velocity from animations // Get the named ones first so they can be indexed directly. ActionAnimation *dp = &actionList[0]; for (S32 i = 0; i < NumTableActionAnims; i++,dp++) { ActionAnimationDef *sp = &ActionAnimationList[i]; dp->name = sp->name; dp->dir.set(sp->dir.x,sp->dir.y,sp->dir.z); dp->sequence = mShape->findSequence(sp->name); // If this is a sprint action and is missing a sequence, attempt to use // the standard run ones. if(dp->sequence == -1 && i >= SprintRootAnim && i <= SprintRightAnim) { S32 offset = i-SprintRootAnim; ActionAnimationDef *standDef = &ActionAnimationList[RootAnim+offset]; dp->sequence = mShape->findSequence(standDef->name); } dp->velocityScale = true; dp->death = false; if (dp->sequence != -1) getGroundInfo(si,thread,dp); } for (S32 b = 0; b < mShape->sequences.size(); b++) { if (!isTableSequence(b)) { dp->sequence = b; dp->name = mShape->getName(mShape->sequences[b].nameIndex); dp->velocityScale = false; getGroundInfo(si,thread,dp++); } } actionCount = dp - actionList; AssertFatal(actionCount <= NumActionAnims, "Too many action animations!"); delete si; // Resolve lookAction index dp = &actionList[0]; String lookName("look"); for (S32 c = 0; c < actionCount; c++,dp++) if( dStricmp( dp->name, lookName ) == 0 ) lookAction = c; // Resolve spine spineNode[0] = mShape->findNode("Bip01 Pelvis"); spineNode[1] = mShape->findNode("Bip01 Spine"); spineNode[2] = mShape->findNode("Bip01 Spine1"); spineNode[3] = mShape->findNode("Bip01 Spine2"); spineNode[4] = mShape->findNode("Bip01 Neck"); spineNode[5] = mShape->findNode("Bip01 Head"); // Recoil animations recoilSequence[0] = mShape->findSequence("light_recoil"); recoilSequence[1] = mShape->findSequence("medium_recoil"); recoilSequence[2] = mShape->findSequence("heavy_recoil"); } // Convert pickupRadius to a delta of boundingBox // // NOTE: it is not really correct to precalculate a pickupRadius based // on boxSize since the actual player's bounds can vary by "pose". // F32 dr = (boxSize.x > boxSize.y)? boxSize.x: boxSize.y; if (pickupRadius < dr) pickupRadius = dr; else if (pickupRadius > 2.0f * dr) pickupRadius = 2.0f * dr; pickupDelta = (S32)(pickupRadius - dr); // Validate jump speed if (maxJumpSpeed <= minJumpSpeed) maxJumpSpeed = minJumpSpeed + 0.1f; // Load up all the emitters if (!footPuffEmitter && footPuffID != 0) if (!Sim::findObject(footPuffID, footPuffEmitter)) Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(footPuffEmitter): 0x%x", footPuffID); if (!decalData && decalID != 0 ) if (!Sim::findObject(decalID, decalData)) Con::errorf(ConsoleLogEntry::General, "PlayerData::preload Invalid packet, bad datablockId(decalData): 0x%x", decalID); if (!dustEmitter && dustID != 0 ) if (!Sim::findObject(dustID, dustEmitter)) Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(dustEmitter): 0x%x", dustID); for (S32 i=0; i<NUM_SPLASH_EMITTERS; i++) if( !splashEmitterList[i] && splashEmitterIDList[i] != 0 ) if( Sim::findObject( splashEmitterIDList[i], splashEmitterList[i] ) == false) Con::errorf(ConsoleLogEntry::General, "PlayerData::onAdd - Invalid packet, bad datablockId(particle emitter): 0x%x", splashEmitterIDList[i]); // First person mounted image shapes. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { bool shapeError = false; if (mShapeFPAssetId[i] != StringTable->EmptyString()) { if (!mShapeFP[i]) { errorStr = String::ToString("PlayerData: Couldn't load mounted image %d shape \"%s\"", i, mShapeFPAssetId[i]); return false; } if (!server && !mShapeFP[i]->preloadMaterialList(mShapeFP[i].getPath()) && NetConnection::filesWereDownloaded()) shapeError = true; if (computeCRC) { Con::printf("Validation required for mounted image %d shape: %s", i, mShapeFPAssetId[i]); Torque::FS::FileNodeRef fileRef = Torque::FS::GetFileNode(mShapeFP[i].getPath()); if (!fileRef) { errorStr = String::ToString("PlayerData: Mounted image %d loading failed, shape \"%s\" is not found.", i, mShapeFP[i].getPath().getFullPath().c_str()); return false; } if (server) mCRCFP[i] = fileRef->getChecksum(); else if (mCRCFP[i] != fileRef->getChecksum()) { errorStr = String::ToString("PlayerData: Mounted image %d shape \"%s\" does not match version on server.", i, mShapeFPAssetId[i]); return false; } } mValidShapeFP[i] = true; } } return true; } void PlayerData::getGroundInfo(TSShapeInstance* si, TSThread* thread,ActionAnimation *dp) { dp->death = !dStrnicmp(dp->name, "death", 5); if (dp->death) { // Death animations use roll frame-to-frame changes in ground transform into position dp->speed = 0.0f; dp->dir.set(0.0f, 0.0f, 0.0f); // Death animations MUST define ground transforms, so add dummy ones if required if (si->getShape()->sequences[dp->sequence].numGroundFrames == 0) si->getShape()->setSequenceGroundSpeed(dp->name, Point3F(0, 0, 0), Point3F(0, 0, 0)); } else { VectorF save = dp->dir; si->setSequence(thread,dp->sequence,0); si->animate(); si->advanceTime(1); si->animateGround(); si->getGroundTransform().getColumn(3,&dp->dir); if ((dp->speed = dp->dir.len()) < 0.01f) { // No ground displacement... In this case we'll use the // default table entry, if there is one. if (save.len() > 0.01f) { dp->dir = save; dp->speed = 1.0f; dp->velocityScale = false; } else dp->speed = 0.0f; } else dp->dir *= 1.0f / dp->speed; } } bool PlayerData::isTableSequence(S32 seq) { // The sequences from the table must already have // been loaded for this to work. for (S32 i = 0; i < NumTableActionAnims; i++) if (actionList[i].sequence == seq) return true; return false; } bool PlayerData::isJumpAction(U32 action) { return (action == JumpAnim || action == StandJumpAnim); } void PlayerData::initPersistFields() { addField( "pickupRadius", TypeF32, Offset(pickupRadius, PlayerData), "@brief Radius around the player to collide with Items in the scene (on server).\n\n" "Internally the pickupRadius is added to the larger side of the initial bounding box " "to determine the actual distance, to a maximum of 2 times the bounding box size. The " "initial bounding box is that used for the root pose, and therefore doesn't take into " "account the change in pose.\n"); addField( "maxTimeScale", TypeF32, Offset(maxTimeScale, PlayerData), "@brief Maximum time scale for action animations.\n\n" "If an action animation has a defined ground frame, it is automatically scaled to match the " "player's ground velocity. This field limits the maximum time scale used even if " "the player's velocity exceeds it." ); addGroup( "Camera" ); addField( "renderFirstPerson", TypeBool, Offset(renderFirstPerson, PlayerData), "@brief Flag controlling whether to render the player shape in first person view.\n\n" ); addField( "firstPersonShadows", TypeBool, Offset(firstPersonShadows, PlayerData), "@brief Forces shadows to be rendered in first person when renderFirstPerson is disabled. Defaults to false.\n\n" ); addField( "minLookAngle", TypeF32, Offset(minLookAngle, PlayerData), "@brief Lowest angle (in radians) the player can look.\n\n" "@note An angle of zero is straight ahead, with positive up and negative down." ); addField( "maxLookAngle", TypeF32, Offset(maxLookAngle, PlayerData), "@brief Highest angle (in radians) the player can look.\n\n" "@note An angle of zero is straight ahead, with positive up and negative down." ); addField( "maxFreelookAngle", TypeF32, Offset(maxFreelookAngle, PlayerData), "@brief Defines the maximum left and right angles (in radians) the player can " "look in freelook mode.\n\n" ); endGroup( "Camera" ); addGroup( "Movement" ); addField( "maxStepHeight", TypeF32, Offset(maxStepHeight, PlayerData), "@brief Maximum height the player can step up.\n\n" "The player will automatically step onto changes in ground height less " "than maxStepHeight. The player will collide with ground height changes " "greater than this." ); addField( "runForce", TypeF32, Offset(runForce, PlayerData), "@brief Force used to accelerate the player when running.\n\n" ); addField( "runEnergyDrain", TypeF32, Offset(runEnergyDrain, PlayerData), "@brief Energy value drained each tick that the player is moving.\n\n" "The player will not be able to move when his energy falls below " "minRunEnergy.\n" "@note Setting this to zero will disable any energy drain.\n" "@see minRunEnergy\n"); addField( "minRunEnergy", TypeF32, Offset(minRunEnergy, PlayerData), "@brief Minimum energy level required to run or swim.\n\n" "@see runEnergyDrain\n"); addField( "maxForwardSpeed", TypeF32, Offset(maxForwardSpeed, PlayerData), "@brief Maximum forward speed when running." ); addField( "maxBackwardSpeed", TypeF32, Offset(maxBackwardSpeed, PlayerData), "@brief Maximum backward speed when running." ); addField( "maxSideSpeed", TypeF32, Offset(maxSideSpeed, PlayerData), "@brief Maximum sideways speed when running." ); addField( "runSurfaceAngle", TypeF32, Offset(runSurfaceAngle, PlayerData), "@brief Maximum angle from vertical (in degrees) the player can run up.\n\n" ); addField( "minImpactSpeed", TypeF32, Offset(minImpactSpeed, PlayerData), "@brief Minimum impact speed to apply falling damage.\n\n" "This field also sets the minimum speed for the onImpact callback " "to be invoked.\n" "@see ShapeBaseData::onImpact()\n"); addField( "minLateralImpactSpeed", TypeF32, Offset(minLateralImpactSpeed, PlayerData), "@brief Minimum impact speed to apply non-falling damage.\n\n" "This field also sets the minimum speed for the onLateralImpact callback " "to be invoked.\n" "@see ShapeBaseData::onLateralImpact()\n"); addField( "horizMaxSpeed", TypeF32, Offset(horizMaxSpeed, PlayerData), "@brief Maximum horizontal speed.\n\n" "@note This limit is only enforced if the player's horizontal speed " "exceeds horizResistSpeed.\n" "@see horizResistSpeed\n" "@see horizResistFactor\n" ); addField( "horizResistSpeed", TypeF32, Offset(horizResistSpeed, PlayerData), "@brief Horizontal speed at which resistence will take place.\n\n" "@see horizMaxSpeed\n" "@see horizResistFactor\n" ); addField( "horizResistFactor", TypeF32, Offset(horizResistFactor, PlayerData), "@brief Factor of resistence once horizResistSpeed has been reached.\n\n" "@see horizMaxSpeed\n" "@see horizResistSpeed\n" ); addField( "upMaxSpeed", TypeF32, Offset(upMaxSpeed, PlayerData), "@brief Maximum upwards speed.\n\n" "@note This limit is only enforced if the player's upward speed exceeds " "upResistSpeed.\n" "@see upResistSpeed\n" "@see upResistFactor\n" ); addField( "upResistSpeed", TypeF32, Offset(upResistSpeed, PlayerData), "@brief Upwards speed at which resistence will take place.\n\n" "@see upMaxSpeed\n" "@see upResistFactor\n" ); addField( "upResistFactor", TypeF32, Offset(upResistFactor, PlayerData), "@brief Factor of resistence once upResistSpeed has been reached.\n\n" "@see upMaxSpeed\n" "@see upResistSpeed\n" ); endGroup( "Movement" ); addGroup( "Movement: Jumping" ); addField( "jumpForce", TypeF32, Offset(jumpForce, PlayerData), "@brief Force used to accelerate the player when a jump is initiated.\n\n" ); addField( "jumpEnergyDrain", TypeF32, Offset(jumpEnergyDrain, PlayerData), "@brief Energy level drained each time the player jumps.\n\n" "@note Setting this to zero will disable any energy drain\n" "@see minJumpEnergy\n"); addField( "minJumpEnergy", TypeF32, Offset(minJumpEnergy, PlayerData), "@brief Minimum energy level required to jump.\n\n" "@see jumpEnergyDrain\n"); addField( "minJumpSpeed", TypeF32, Offset(minJumpSpeed, PlayerData), "@brief Minimum speed needed to jump.\n\n" "If the player's own z velocity is greater than this, then it is used to scale " "the jump speed, up to maxJumpSpeed.\n" "@see maxJumpSpeed\n"); addField( "maxJumpSpeed", TypeF32, Offset(maxJumpSpeed, PlayerData), "@brief Maximum vertical speed before the player can no longer jump.\n\n" ); addField( "jumpSurfaceAngle", TypeF32, Offset(jumpSurfaceAngle, PlayerData), "@brief Angle from vertical (in degrees) where the player can jump.\n\n" ); addField( "jumpDelay", TypeS32, Offset(jumpDelay, PlayerData), "@brief Delay time in number of ticks ticks between jumps.\n\n" ); addField( "airControl", TypeF32, Offset(airControl, PlayerData), "@brief Amount of movement control the player has when in the air.\n\n" "This is applied as a multiplier to the player's x and y motion.\n"); addField( "jumpTowardsNormal", TypeBool, Offset(jumpTowardsNormal, PlayerData), "@brief Controls the direction of the jump impulse.\n" "When false, jumps are always in the vertical (+Z) direction. When true " "jumps are in the direction of the ground normal so long as the player is not " "directly facing the surface. If the player is directly facing the surface, then " "they will jump straight up.\n" ); endGroup( "Movement: Jumping" ); addGroup( "Movement: Sprinting" ); addField( "sprintForce", TypeF32, Offset(sprintForce, PlayerData), "@brief Force used to accelerate the player when sprinting.\n\n" ); addField( "sprintEnergyDrain", TypeF32, Offset(sprintEnergyDrain, PlayerData), "@brief Energy value drained each tick that the player is sprinting.\n\n" "The player will not be able to move when his energy falls below " "sprintEnergyDrain.\n" "@note Setting this to zero will disable any energy drain.\n" "@see minSprintEnergy\n"); addField( "minSprintEnergy", TypeF32, Offset(minSprintEnergy, PlayerData), "@brief Minimum energy level required to sprint.\n\n" "@see sprintEnergyDrain\n"); addField( "maxSprintForwardSpeed", TypeF32, Offset(maxSprintForwardSpeed, PlayerData), "@brief Maximum forward speed when sprinting." ); addField( "maxSprintBackwardSpeed", TypeF32, Offset(maxSprintBackwardSpeed, PlayerData), "@brief Maximum backward speed when sprinting." ); addField( "maxSprintSideSpeed", TypeF32, Offset(maxSprintSideSpeed, PlayerData), "@brief Maximum sideways speed when sprinting." ); addField( "sprintStrafeScale", TypeF32, Offset(sprintStrafeScale, PlayerData), "@brief Amount to scale strafing motion vector while sprinting." ); addField( "sprintYawScale", TypeF32, Offset(sprintYawScale, PlayerData), "@brief Amount to scale yaw motion while sprinting." ); addField( "sprintPitchScale", TypeF32, Offset(sprintPitchScale, PlayerData), "@brief Amount to scale pitch motion while sprinting." ); addField( "sprintCanJump", TypeBool, Offset(sprintCanJump, PlayerData), "@brief Can the player jump while sprinting." ); endGroup( "Movement: Sprinting" ); addGroup( "Movement: Swimming" ); addField( "swimForce", TypeF32, Offset(swimForce, PlayerData), "@brief Force used to accelerate the player when swimming.\n\n" ); addField( "maxUnderwaterForwardSpeed", TypeF32, Offset(maxUnderwaterForwardSpeed, PlayerData), "@brief Maximum forward speed when underwater.\n\n" ); addField( "maxUnderwaterBackwardSpeed", TypeF32, Offset(maxUnderwaterBackwardSpeed, PlayerData), "@brief Maximum backward speed when underwater.\n\n" ); addField( "maxUnderwaterSideSpeed", TypeF32, Offset(maxUnderwaterSideSpeed, PlayerData), "@brief Maximum sideways speed when underwater.\n\n" ); endGroup( "Movement: Swimming" ); addGroup( "Movement: Crouching" ); addField( "crouchForce", TypeF32, Offset(crouchForce, PlayerData), "@brief Force used to accelerate the player when crouching.\n\n" ); addField( "maxCrouchForwardSpeed", TypeF32, Offset(maxCrouchForwardSpeed, PlayerData), "@brief Maximum forward speed when crouching.\n\n" ); addField( "maxCrouchBackwardSpeed", TypeF32, Offset(maxCrouchBackwardSpeed, PlayerData), "@brief Maximum backward speed when crouching.\n\n" ); addField( "maxCrouchSideSpeed", TypeF32, Offset(maxCrouchSideSpeed, PlayerData), "@brief Maximum sideways speed when crouching.\n\n" ); endGroup( "Movement: Crouching" ); addGroup( "Movement: Prone" ); addField( "proneForce", TypeF32, Offset(proneForce, PlayerData), "@brief Force used to accelerate the player when prone (laying down).\n\n" ); addField( "maxProneForwardSpeed", TypeF32, Offset(maxProneForwardSpeed, PlayerData), "@brief Maximum forward speed when prone (laying down).\n\n" ); addField( "maxProneBackwardSpeed", TypeF32, Offset(maxProneBackwardSpeed, PlayerData), "@brief Maximum backward speed when prone (laying down).\n\n" ); addField( "maxProneSideSpeed", TypeF32, Offset(maxProneSideSpeed, PlayerData), "@brief Maximum sideways speed when prone (laying down).\n\n" ); endGroup( "Movement: Prone" ); addGroup( "Movement: Jetting" ); addField( "jetJumpForce", TypeF32, Offset(jetJumpForce, PlayerData), "@brief Force used to accelerate the player when a jet jump is initiated.\n\n" ); addField( "jetJumpEnergyDrain", TypeF32, Offset(jetJumpEnergyDrain, PlayerData), "@brief Energy level drained each time the player jet jumps.\n\n" "@note Setting this to zero will disable any energy drain\n" "@see jetMinJumpEnergy\n"); addField( "jetMinJumpEnergy", TypeF32, Offset(jetMinJumpEnergy, PlayerData), "@brief Minimum energy level required to jet jump.\n\n" "@see jetJumpEnergyDrain\n"); addField( "jetMinJumpSpeed", TypeF32, Offset(jetMinJumpSpeed, PlayerData), "@brief Minimum speed needed to jet jump.\n\n" "If the player's own z velocity is greater than this, then it is used to scale " "the jet jump speed, up to jetMaxJumpSpeed.\n" "@see jetMaxJumpSpeed\n"); addField( "jetMaxJumpSpeed", TypeF32, Offset(jetMaxJumpSpeed, PlayerData), "@brief Maximum vertical speed before the player can no longer jet jump.\n\n" ); addField( "jetJumpSurfaceAngle", TypeF32, Offset(jetJumpSurfaceAngle, PlayerData), "@brief Angle from vertical (in degrees) where the player can jet jump.\n\n" ); endGroup( "Movement: Jetting" ); addGroup( "Falling" ); addField( "fallingSpeedThreshold", TypeF32, Offset(fallingSpeedThreshold, PlayerData), "@brief Downward speed at which we consider the player falling.\n\n" ); addField( "recoverDelay", TypeS32, Offset(recoverDelay, PlayerData), "@brief Number of ticks for the player to recover from falling.\n\n" ); addField( "recoverRunForceScale", TypeF32, Offset(recoverRunForceScale, PlayerData), "@brief Scale factor applied to runForce while in the recover state.\n\n" "This can be used to temporarily slow the player's movement after a fall, or " "prevent the player from moving at all if set to zero.\n" ); addField( "landSequenceTime", TypeF32, Offset(landSequenceTime, PlayerData), "@brief Time of land sequence play back when using new recover system.\n\n" "If greater than 0 then the legacy fall recovery system will be bypassed " "in favour of just playing the player's land sequence. The time to " "recover from a fall then becomes this parameter's time and the land " "sequence's playback will be scaled to match.\n" "@see transitionToLand\n" ); addField( "transitionToLand", TypeBool, Offset(transitionToLand, PlayerData), "@brief When going from a fall to a land, should we transition between the two.\n\n" "@note Only takes affect when landSequenceTime is greater than 0.\n" "@see landSequenceTime\n" ); endGroup( "Falling" ); addGroup( "Collision" ); addField( "boundingBox", TypePoint3F, Offset(boxSize, PlayerData), "@brief Size of the bounding box used by the player for collision.\n\n" "Dimensions are given as \"width depth height\"." ); addField( "crouchBoundingBox", TypePoint3F, Offset(crouchBoxSize, PlayerData), "@brief Collision bounding box used when the player is crouching.\n\n" "@see boundingBox" ); addField( "proneBoundingBox", TypePoint3F, Offset(proneBoxSize, PlayerData), "@brief Collision bounding box used when the player is prone (laying down).\n\n" "@see boundingBox" ); addField( "swimBoundingBox", TypePoint3F, Offset(swimBoxSize, PlayerData), "@brief Collision bounding box used when the player is swimming.\n\n" "@see boundingBox" ); addField( "boxHeadPercentage", TypeF32, Offset(boxHeadPercentage, PlayerData), "@brief Percentage of the player's bounding box height that represents the head.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); addField( "boxTorsoPercentage", TypeF32, Offset(boxTorsoPercentage, PlayerData), "@brief Percentage of the player's bounding box height that represents the torso.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); addField( "boxHeadLeftPercentage", TypeF32, Offset(boxHeadLeftPercentage, PlayerData), "@brief Percentage of the player's bounding box width that represents the left side of the head.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); addField( "boxHeadRightPercentage", TypeF32, Offset(boxHeadRightPercentage, PlayerData), "@brief Percentage of the player's bounding box width that represents the right side of the head.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); addField( "boxHeadBackPercentage", TypeF32, Offset(boxHeadBackPercentage, PlayerData), "@brief Percentage of the player's bounding box depth that represents the back side of the head.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); addField( "boxHeadFrontPercentage", TypeF32, Offset(boxHeadFrontPercentage, PlayerData), "@brief Percentage of the player's bounding box depth that represents the front side of the head.\n\n" "Used when computing the damage location.\n" "@see Player::getDamageLocation" ); endGroup( "Collision" ); addGroup( "Interaction: Footsteps" ); addField( "footPuffEmitter", TYPEID< ParticleEmitterData >(), Offset(footPuffEmitter, PlayerData), "@brief Particle emitter used to generate footpuffs (particles created as the player " "walks along the ground).\n\n" "@note The generation of foot puffs requires the appropriate triggeres to be defined in the " "player's animation sequences. Without these, no foot puffs will be generated.\n"); addField( "footPuffNumParts", TypeS32, Offset(footPuffNumParts, PlayerData), "@brief Number of footpuff particles to generate each step.\n\n" "Each foot puff is randomly placed within the defined foot puff radius. This " "includes having footPuffNumParts set to one.\n" "@see footPuffRadius\n"); addField( "footPuffRadius", TypeF32, Offset(footPuffRadius, PlayerData), "@brief Particle creation radius for footpuff particles.\n\n" "This is applied to each foot puff particle, even if footPuffNumParts is set to one. So " "set this value to zero if you want a single foot puff placed at exactly the same location " "under the player each time.\n"); addField( "dustEmitter", TYPEID< ParticleEmitterData >(), Offset(dustEmitter, PlayerData), "@brief Emitter used to generate dust particles.\n\n" "@note Currently unused." ); addField( "decalData", TYPEID< DecalData >(), Offset(decalData, PlayerData), "@brief Decal to place on the ground for player footsteps.\n\n" ); addField( "decalOffset",TypeF32, Offset(decalOffset, PlayerData), "@brief Distance from the center of the model to the right foot.\n\n" "While this defines the distance to the right foot, it is also used to place " "the left foot decal as well. Just on the opposite side of the player." ); endGroup( "Interaction: Footsteps" ); addGroup( "Interaction: Sounds" ); INITPERSISTFIELD_SOUNDASSET_ENUMED(PlayerSound, playerSoundsEnum, PlayerData::Sounds::MaxSounds, PlayerData, "Sounds related to player interaction."); endGroup( "Interaction: Sounds" ); addGroup( "Interaction: Splashes" ); addField( "splash", TYPEID< SplashData >(), Offset(splash, PlayerData), "@brief SplashData datablock used to create splashes when the player moves " "through water.\n\n" ); addField( "splashVelocity", TypeF32, Offset(splashVelocity, PlayerData), "@brief Minimum velocity when moving through water to generate splashes.\n\n" ); addField( "splashAngle", TypeF32, Offset(splashAngle, PlayerData), "@brief Maximum angle (in degrees) from pure vertical movement in water to " "generate splashes.\n\n" ); addField( "splashFreqMod", TypeF32, Offset(splashFreqMod, PlayerData), "@brief Multipled by speed to determine the number of splash particles to generate.\n\n" ); addField( "splashVelEpsilon", TypeF32, Offset(splashVelEpsilon, PlayerData), "@brief Minimum speed to generate splash particles.\n\n" ); addField( "bubbleEmitTime", TypeF32, Offset(bubbleEmitTime, PlayerData), "@brief Time in seconds to generate bubble particles after entering the water.\n\n" ); addField( "splashEmitter", TYPEID< ParticleEmitterData >(), Offset(splashEmitterList, PlayerData), NUM_SPLASH_EMITTERS, "@brief Particle emitters used to generate splash particles.\n\n" ); addField( "footstepSplashHeight", TypeF32, Offset(footSplashHeight, PlayerData), "@brief Water coverage level to choose between FootShallowSound and FootWadingSound.\n\n" "@see FootShallowSound\n" "@see FootWadingSound\n"); addField( "mediumSplashSoundVelocity", TypeF32, Offset(medSplashSoundVel, PlayerData), "@brief Minimum velocity when entering the water for choosing between the impactWaterEasy and " "impactWaterMedium sounds to play.\n\n" "@see impactWaterEasy\n" "@see impactWaterMedium\n" ); addField( "hardSplashSoundVelocity", TypeF32, Offset(hardSplashSoundVel, PlayerData), "@brief Minimum velocity when entering the water for choosing between the impactWaterMedium and " "impactWaterHard sound to play.\n\n" "@see impactWaterMedium\n" "@see impactWaterHard\n" ); addField( "exitSplashSoundVelocity", TypeF32, Offset(exitSplashSoundVel, PlayerData), "@brief Minimum velocity when leaving the water for the exitingWater sound to " "play.\n\n" "@see exitingWater"); endGroup( "Interaction: Splashes" ); addGroup( "Interaction: Ground Impact" ); addField( "groundImpactMinSpeed", TypeF32, Offset(groundImpactMinSpeed, PlayerData), "@brief Minimum falling impact speed to apply damage and initiate the camera " "shaking effect.\n\n" ); addField( "groundImpactShakeFreq", TypePoint3F, Offset(groundImpactShakeFreq, PlayerData), "@brief Frequency of the camera shake effect after falling.\n\n" "This is how fast to shake the camera.\n"); addField( "groundImpactShakeAmp", TypePoint3F, Offset(groundImpactShakeAmp, PlayerData), "@brief Amplitude of the camera shake effect after falling.\n\n" "This is how much to shake the camera.\n"); addField( "groundImpactShakeDuration", TypeF32, Offset(groundImpactShakeDuration, PlayerData), "@brief Duration (in seconds) of the camera shake effect after falling.\n\n" "This is how long to shake the camera.\n"); addField( "groundImpactShakeFalloff", TypeF32, Offset(groundImpactShakeFalloff, PlayerData), "@brief Falloff factor of the camera shake effect after falling.\n\n" "This is how to fade the camera shake over the duration.\n"); endGroup( "Interaction: Ground Impact" ); addGroup( "Physics" ); // PhysicsPlayer addField( "physicsPlayerType", TypeString, Offset(physicsPlayerType, PlayerData), "@brief Specifies the type of physics used by the player.\n\n" "This depends on the physics module used. An example is 'Capsule'.\n" "@note Not current used.\n"); endGroup( "Physics" ); addGroup( "First Person Arms" ); addField( "imageAnimPrefixFP", TypeCaseString, Offset(imageAnimPrefixFP, PlayerData), "@brief Optional prefix to all mounted image animation sequences in first person.\n\n" "This defines a prefix that will be added when looking up mounted image " "animation sequences while in first person. It allows for the customization " "of a first person image based on the type of player.\n"); // Mounted images arrays addArray( "Mounted Images", ShapeBase::MaxMountedImages ); addProtectedField("shapeNameFP", TypeShapeFilename, Offset(mShapeFPName, PlayerData), &_setShapeFPData, &defaultProtectedGetFn, ShapeBase::MaxMountedImages, "@brief File name of this player's shape that will be used in conjunction with the corresponding mounted image.\n\n" "These optional parameters correspond to each mounted image slot to indicate a shape that is rendered " "in addition to the mounted image shape. Typically these are a player's arms (or arm) that is " "animated along with the mounted image's state animation sequences.\n", AbstractClassRep::FIELD_HideInInspectors); INITPERSISTFIELD_SHAPEASSET_ARRAY(ShapeFP, ShapeBase::MaxMountedImages, PlayerData, "@brief File name of this player's shape that will be used in conjunction with the corresponding mounted image.\n\n" "These optional parameters correspond to each mounted image slot to indicate a shape that is rendered " "in addition to the mounted image shape. Typically these are a player's arms (or arm) that is " "animated along with the mounted image's state animation sequences.\n"); endArray( "Mounted Images" ); endGroup( "First Person Arms" ); addGroup( "Third Person" ); addField( "imageAnimPrefix", TypeCaseString, Offset(imageAnimPrefix, PlayerData), "@brief Optional prefix to all mounted image animation sequences in third person.\n\n" "This defines a prefix that will be added when looking up mounted image " "animation sequences while in third person. It allows for the customization " "of a third person image based on the type of player.\n"); addField( "allowImageStateAnimation", TypeBool, Offset(allowImageStateAnimation, PlayerData), "@brief Allow mounted images to request a sequence be played on the Player.\n\n" "When true a new thread is added to the player to allow for " "mounted images to request a sequence be played on the player " "through the image's state machine. It is only optional so " "that we don't create a TSThread on the player if we don't " "need to.\n"); endGroup( "Third Person" ); Parent::initPersistFields(); } void PlayerData::packData(BitStream* stream) { Parent::packData(stream); stream->writeFlag(renderFirstPerson); stream->writeFlag(firstPersonShadows); stream->write(minLookAngle); stream->write(maxLookAngle); stream->write(maxFreelookAngle); stream->write(maxTimeScale); stream->write(mass); stream->write(maxEnergy); stream->write(drag); stream->write(density); stream->write(maxStepHeight); stream->write(runForce); stream->write(runEnergyDrain); stream->write(minRunEnergy); stream->write(maxForwardSpeed); stream->write(maxBackwardSpeed); stream->write(maxSideSpeed); stream->write(runSurfaceAngle); stream->write(fallingSpeedThreshold); stream->write(recoverDelay); stream->write(recoverRunForceScale); stream->write(landSequenceTime); stream->write(transitionToLand); // Jumping stream->write(jumpForce); stream->write(jumpEnergyDrain); stream->write(minJumpEnergy); stream->write(minJumpSpeed); stream->write(maxJumpSpeed); stream->write(jumpSurfaceAngle); stream->writeInt(jumpDelay,JumpDelayBits); // Sprinting stream->write(sprintForce); stream->write(sprintEnergyDrain); stream->write(minSprintEnergy); stream->write(maxSprintForwardSpeed); stream->write(maxSprintBackwardSpeed); stream->write(maxSprintSideSpeed); stream->write(sprintStrafeScale); stream->write(sprintYawScale); stream->write(sprintPitchScale); stream->writeFlag(sprintCanJump); // Swimming stream->write(swimForce); stream->write(maxUnderwaterForwardSpeed); stream->write(maxUnderwaterBackwardSpeed); stream->write(maxUnderwaterSideSpeed); // Crouching stream->write(crouchForce); stream->write(maxCrouchForwardSpeed); stream->write(maxCrouchBackwardSpeed); stream->write(maxCrouchSideSpeed); // Prone stream->write(proneForce); stream->write(maxProneForwardSpeed); stream->write(maxProneBackwardSpeed); stream->write(maxProneSideSpeed); // Jetting stream->write(jetJumpForce); stream->write(jetJumpEnergyDrain); stream->write(jetMinJumpEnergy); stream->write(jetMinJumpSpeed); stream->write(jetMaxJumpSpeed); stream->write(jetJumpSurfaceAngle); stream->write(horizMaxSpeed); stream->write(horizResistSpeed); stream->write(horizResistFactor); stream->write(upMaxSpeed); stream->write(upResistSpeed); stream->write(upResistFactor); stream->write(splashVelocity); stream->write(splashAngle); stream->write(splashFreqMod); stream->write(splashVelEpsilon); stream->write(bubbleEmitTime); stream->write(medSplashSoundVel); stream->write(hardSplashSoundVel); stream->write(exitSplashSoundVel); stream->write(footSplashHeight); // Don't need damage scale on the client stream->write(minImpactSpeed); stream->write(minLateralImpactSpeed); for (U32 i = 0; i < MaxSounds; i++) PACKDATA_ASSET_ARRAY(PlayerSound, i); mathWrite(*stream, boxSize); mathWrite(*stream, crouchBoxSize); mathWrite(*stream, proneBoxSize); mathWrite(*stream, swimBoxSize); if( stream->writeFlag( footPuffEmitter ) ) { stream->writeRangedU32( footPuffEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast ); } stream->write( footPuffNumParts ); stream->write( footPuffRadius ); if( stream->writeFlag( decalData ) ) { stream->writeRangedU32( decalData->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast ); } stream->write(decalOffset); if( stream->writeFlag( dustEmitter ) ) { stream->writeRangedU32( dustEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast ); } if (stream->writeFlag( splash )) { stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast); } for( U32 i=0; i<NUM_SPLASH_EMITTERS; i++ ) { if( stream->writeFlag( splashEmitterList[i] != NULL ) ) { stream->writeRangedU32( splashEmitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast ); } } stream->write(groundImpactMinSpeed); stream->write(groundImpactShakeFreq.x); stream->write(groundImpactShakeFreq.y); stream->write(groundImpactShakeFreq.z); stream->write(groundImpactShakeAmp.x); stream->write(groundImpactShakeAmp.y); stream->write(groundImpactShakeAmp.z); stream->write(groundImpactShakeDuration); stream->write(groundImpactShakeFalloff); // Air control stream->write(airControl); // Jump off at normal stream->writeFlag(jumpTowardsNormal); stream->writeString(physicsPlayerType); // Third person mounted image shapes stream->writeString(imageAnimPrefix); stream->writeFlag(allowImageStateAnimation); // First person mounted image shapes stream->writeString(imageAnimPrefixFP); for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { PACKDATA_ASSET_ARRAY(ShapeFP, i); // computeCRC is handled in ShapeBaseData if (computeCRC) { stream->write(mCRCFP[i]); } } } void PlayerData::unpackData(BitStream* stream) { Parent::unpackData(stream); renderFirstPerson = stream->readFlag(); firstPersonShadows = stream->readFlag(); stream->read(&minLookAngle); stream->read(&maxLookAngle); stream->read(&maxFreelookAngle); stream->read(&maxTimeScale); stream->read(&mass); stream->read(&maxEnergy); stream->read(&drag); stream->read(&density); stream->read(&maxStepHeight); stream->read(&runForce); stream->read(&runEnergyDrain); stream->read(&minRunEnergy); stream->read(&maxForwardSpeed); stream->read(&maxBackwardSpeed); stream->read(&maxSideSpeed); stream->read(&runSurfaceAngle); stream->read(&fallingSpeedThreshold); stream->read(&recoverDelay); stream->read(&recoverRunForceScale); stream->read(&landSequenceTime); stream->read(&transitionToLand); // Jumping stream->read(&jumpForce); stream->read(&jumpEnergyDrain); stream->read(&minJumpEnergy); stream->read(&minJumpSpeed); stream->read(&maxJumpSpeed); stream->read(&jumpSurfaceAngle); jumpDelay = stream->readInt(JumpDelayBits); // Sprinting stream->read(&sprintForce); stream->read(&sprintEnergyDrain); stream->read(&minSprintEnergy); stream->read(&maxSprintForwardSpeed); stream->read(&maxSprintBackwardSpeed); stream->read(&maxSprintSideSpeed); stream->read(&sprintStrafeScale); stream->read(&sprintYawScale); stream->read(&sprintPitchScale); sprintCanJump = stream->readFlag(); // Swimming stream->read(&swimForce); stream->read(&maxUnderwaterForwardSpeed); stream->read(&maxUnderwaterBackwardSpeed); stream->read(&maxUnderwaterSideSpeed); // Crouching stream->read(&crouchForce); stream->read(&maxCrouchForwardSpeed); stream->read(&maxCrouchBackwardSpeed); stream->read(&maxCrouchSideSpeed); // Prone stream->read(&proneForce); stream->read(&maxProneForwardSpeed); stream->read(&maxProneBackwardSpeed); stream->read(&maxProneSideSpeed); // Jetting stream->read(&jetJumpForce); stream->read(&jetJumpEnergyDrain); stream->read(&jetMinJumpEnergy); stream->read(&jetMinJumpSpeed); stream->read(&jetMaxJumpSpeed); stream->read(&jetJumpSurfaceAngle); stream->read(&horizMaxSpeed); stream->read(&horizResistSpeed); stream->read(&horizResistFactor); stream->read(&upMaxSpeed); stream->read(&upResistSpeed); stream->read(&upResistFactor); stream->read(&splashVelocity); stream->read(&splashAngle); stream->read(&splashFreqMod); stream->read(&splashVelEpsilon); stream->read(&bubbleEmitTime); stream->read(&medSplashSoundVel); stream->read(&hardSplashSoundVel); stream->read(&exitSplashSoundVel); stream->read(&footSplashHeight); stream->read(&minImpactSpeed); stream->read(&minLateralImpactSpeed); for (U32 i = 0; i < MaxSounds; i++) UNPACKDATA_ASSET_ARRAY(PlayerSound, i); mathRead(*stream, &boxSize); mathRead(*stream, &crouchBoxSize); mathRead(*stream, &proneBoxSize); mathRead(*stream, &swimBoxSize); if( stream->readFlag() ) { footPuffID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast); } stream->read(&footPuffNumParts); stream->read(&footPuffRadius); if( stream->readFlag() ) { decalID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast); } stream->read(&decalOffset); if( stream->readFlag() ) { dustID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast); } if (stream->readFlag()) { splashId = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast ); } for( U32 i=0; i<NUM_SPLASH_EMITTERS; i++ ) { if( stream->readFlag() ) { splashEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast ); } } stream->read(&groundImpactMinSpeed); stream->read(&groundImpactShakeFreq.x); stream->read(&groundImpactShakeFreq.y); stream->read(&groundImpactShakeFreq.z); stream->read(&groundImpactShakeAmp.x); stream->read(&groundImpactShakeAmp.y); stream->read(&groundImpactShakeAmp.z); stream->read(&groundImpactShakeDuration); stream->read(&groundImpactShakeFalloff); // Air control stream->read(&airControl); // Jump off at normal jumpTowardsNormal = stream->readFlag(); physicsPlayerType = stream->readSTString(); // Third person mounted image shapes imageAnimPrefix = stream->readSTString(); allowImageStateAnimation = stream->readFlag(); // First person mounted image shapes imageAnimPrefixFP = stream->readSTString(); for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { UNPACKDATA_ASSET_ARRAY(ShapeFP, i); // computeCRC is handled in ShapeBaseData if (computeCRC) { stream->read(&(mCRCFP[i])); } } } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- ImplementEnumType( PlayerPose, "@brief The pose of the Player.\n\n" "@ingroup gameObjects\n\n") { Player::StandPose, "Stand", "Standard movement pose.\n" }, { Player::SprintPose, "Sprint", "Sprinting pose.\n" }, { Player::CrouchPose, "Crouch", "Crouch pose.\n" }, { Player::PronePose, "Prone", "Prone pose.\n" }, { Player::SwimPose, "Swim", "Swimming pose.\n" }, EndImplementEnumType; //---------------------------------------------------------------------------- IMPLEMENT_CO_NETOBJECT_V1(Player); ConsoleDocClass( Player, "@ingroup gameObjects\n" ); //---------------------------------------------------------------------------- Player::Player() { mTypeMask |= PlayerObjectType | DynamicShapeObjectType; mDelta.pos = mAnchorPoint = Point3F(0,0,100); mDelta.rot = mDelta.head = Point3F(0,0,0); mDelta.rotOffset.set(0.0f,0.0f,0.0f); mDelta.warpOffset.set(0.0f,0.0f,0.0f); mDelta.posVec.set(0.0f,0.0f,0.0f); mDelta.rotVec.set(0.0f,0.0f,0.0f); mDelta.headVec.set(0.0f,0.0f,0.0f); mDelta.warpTicks = 0; mDelta.dt = 1.0f; mDelta.move = NullMove; mPredictionCount = sMaxPredictionTicks; mObjToWorld.setColumn(3, mDelta.pos); mRot = mDelta.rot; mHead = mDelta.head; mVelocity.set(0.0f, 0.0f, 0.0f); mDataBlock = 0; mHeadHThread = mHeadVThread = mRecoilThread = mImageStateThread = 0; mArmAnimation.action = PlayerData::NullAnimation; mArmAnimation.thread = 0; mActionAnimation.action = PlayerData::NullAnimation; mActionAnimation.thread = 0; mActionAnimation.delayTicks = 0; mActionAnimation.forward = true; mActionAnimation.firstPerson = false; //mActionAnimation.time = 1.0f; //ActionAnimation::Scale; mActionAnimation.waitForEnd = false; mActionAnimation.holdAtEnd = false; mActionAnimation.animateOnServer = false; mActionAnimation.atEnd = false; mState = MoveState; mJetting = false; mFalling = false; mSwimming = false; mInWater = false; mPose = StandPose; mContactTimer = 0; mJumpDelay = 0; mJumpSurfaceLastContact = 0; mJumpSurfaceNormal.set(0.0f, 0.0f, 1.0f); mControlObject = 0; dMemset( mSplashEmitter, 0, sizeof( mSplashEmitter ) ); mUseHeadZCalc = true; allowAllPoses(); mImpactSound = 0; mRecoverTicks = 0; mReversePending = 0; mLastPos.set( 0.0f, 0.0f, 0.0f ); mMoveBubbleSound = 0; mWaterBreathSound = 0; mConvex.init(this); mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f); mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f); mWeaponBackFraction = 0.0f; mInMissionArea = true; mBubbleEmitterTime = 10.0; mLastWaterPos.set( 0.0, 0.0, 0.0 ); mMountPending = 0; mPhysicsRep = NULL; for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { mShapeFPInstance[i] = 0; mShapeFPAmbientThread[i] = 0; mShapeFPVisThread[i] = 0; mShapeFPAnimThread[i] = 0; mShapeFPFlashThread[i] = 0; mShapeFPSpinThread[i] = 0; } mLastAbsoluteYaw = 0.0f; mLastAbsolutePitch = 0.0f; mLastAbsoluteRoll = 0.0f; afx_init(); } Player::~Player() { for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { delete mShapeFPInstance[i]; mShapeFPInstance[i] = 0; } } //---------------------------------------------------------------------------- bool Player::onAdd() { ActionAnimation serverAnim = mActionAnimation; if(!Parent::onAdd() || !mDataBlock) return false; mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f); mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f); addToScene(); // Make sure any state and animation passed from the server // in the initial update is set correctly. ActionState state = mState; mState = NullState; setState(state); setPose(StandPose); if (serverAnim.action != PlayerData::NullAnimation) { setActionThread(serverAnim.action, true, serverAnim.holdAtEnd, true, false, true); if (serverAnim.atEnd) { mShapeInstance->clearTransition(mActionAnimation.thread); mShapeInstance->setPos(mActionAnimation.thread, mActionAnimation.forward ? 1.0f : 0.0f); if (inDeathAnim()) mDeath.lastPos = 1.0f; } // We have to leave them sitting for a while since mounts don't come through right // away (and sometimes not for a while). Still going to let this time out because // I'm not sure if we're guaranteed another anim will come through and cancel. if (!isServerObject() && inSittingAnim()) mMountPending = (S32) sMountPendingTickWait; else mMountPending = 0; } if (mArmAnimation.action != PlayerData::NullAnimation) setArmThread(mArmAnimation.action); // if (isServerObject()) { scriptOnAdd(); } else { U32 i; for( i=0; i<PlayerData::NUM_SPLASH_EMITTERS; i++ ) { if ( mDataBlock->splashEmitterList[i] ) { mSplashEmitter[i] = new ParticleEmitter; mSplashEmitter[i]->onNewDataBlock( mDataBlock->splashEmitterList[i], false ); if( !mSplashEmitter[i]->registerObject() ) { Con::warnf( ConsoleLogEntry::General, "Could not register splash emitter for class: %s", mDataBlock->getName() ); mSplashEmitter[i].getPointer()->destroySelf(); mSplashEmitter[i] = NULL; } } } mLastWaterPos = getPosition(); // clear out all camera effects gCamFXMgr.clear(); } if ( PHYSICSMGR ) { PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" ); mPhysicsRep = PHYSICSMGR->createPlayer(); mPhysicsRep->init( mDataBlock->physicsPlayerType, mDataBlock->boxSize, mDataBlock->runSurfaceCos, mDataBlock->maxStepHeight, this, world ); mPhysicsRep->setTransform( getTransform() ); } return true; } void Player::onRemove() { setControlObject(0); scriptOnRemove(); removeFromScene(); if ( isGhost() ) { SFX_DELETE( mMoveBubbleSound ); SFX_DELETE( mWaterBreathSound ); } U32 i; for( i=0; i<PlayerData::NUM_SPLASH_EMITTERS; i++ ) { if( mSplashEmitter[i] ) { mSplashEmitter[i]->deleteWhenEmpty(); mSplashEmitter[i] = NULL; } } mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f); mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f); SAFE_DELETE( mPhysicsRep ); Parent::onRemove(); } void Player::onScaleChanged() { const Point3F& scale = getScale(); mScaledBox = mObjBox; mScaledBox.minExtents.convolve( scale ); mScaledBox.maxExtents.convolve( scale ); } //---------------------------------------------------------------------------- bool Player::onNewDataBlock( GameBaseData *dptr, bool reload ) { PlayerData* prevData = mDataBlock; mDataBlock = dynamic_cast<PlayerData*>(dptr); if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) ) return false; // Player requires a shape instance. if ( mShapeInstance == NULL ) return false; // Initialize arm thread, preserve arm sequence from last datablock. // Arm animation can be from last datablock, or sent from the server. U32 prevAction = mArmAnimation.action; mArmAnimation.action = PlayerData::NullAnimation; if (mDataBlock->lookAction) { mArmAnimation.thread = mShapeInstance->addThread(); mShapeInstance->setTimeScale(mArmAnimation.thread,0); if (prevData) { if (prevAction != prevData->lookAction && prevAction != PlayerData::NullAnimation) setArmThread(prevData->actionList[prevAction].name); prevAction = PlayerData::NullAnimation; } if (mArmAnimation.action == PlayerData::NullAnimation) { mArmAnimation.action = (prevAction != PlayerData::NullAnimation)? prevAction: mDataBlock->lookAction; mShapeInstance->setSequence(mArmAnimation.thread, mDataBlock->actionList[mArmAnimation.action].sequence,0); } } else mArmAnimation.thread = 0; // Initialize head look thread TSShape const* shape = mShapeInstance->getShape(); S32 headSeq = shape->findSequence("head"); if (headSeq != -1) { mHeadVThread = mShapeInstance->addThread(); mShapeInstance->setSequence(mHeadVThread,headSeq,0); mShapeInstance->setTimeScale(mHeadVThread,0); } else mHeadVThread = 0; headSeq = shape->findSequence("headside"); if (headSeq != -1) { mHeadHThread = mShapeInstance->addThread(); mShapeInstance->setSequence(mHeadHThread,headSeq,0); mShapeInstance->setTimeScale(mHeadHThread,0); } else mHeadHThread = 0; // Create Recoil thread if any recoil sequences are specified. // Note that the server player does not play this animation. mRecoilThread = 0; if (isGhost()) for (U32 s = 0; s < PlayerData::NumRecoilSequences; s++) if (mDataBlock->recoilSequence[s] != -1) { mRecoilThread = mShapeInstance->addThread(); mShapeInstance->setSequence(mRecoilThread, mDataBlock->recoilSequence[s], 0); mShapeInstance->setTimeScale(mRecoilThread, 0); break; } // Reset the image state driven animation thread. This will be properly built // in onImageStateAnimation() when needed. mImageStateThread = 0; // Initialize the primary thread, the actual sequence is // set later depending on player actions. mActionAnimation.action = PlayerData::NullAnimation; mActionAnimation.thread = mShapeInstance->addThread(); updateAnimationTree(!isGhost()); // First person mounted image shapes. Only on client. if ( isGhost() ) { for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { if (bool(mDataBlock->mShapeFP[i])) { mShapeFPInstance[i] = new TSShapeInstance(mDataBlock->mShapeFP[i], isClientObject()); mShapeFPInstance[i]->cloneMaterialList(); // Ambient animation if (mShapeFPAmbientThread[i]) { S32 seq = mShapeFPInstance[i]->getShape()->findSequence("ambient"); if (seq != -1) { mShapeFPAmbientThread[i] = mShapeFPInstance[i]->addThread(); mShapeFPInstance[i]->setTimeScale(mShapeFPAmbientThread[i], 1); mShapeFPInstance[i]->setSequence(mShapeFPAmbientThread[i], seq, 0); } } // Standard state animation mShapeFPAnimThread[i] = mShapeFPInstance[i]->addThread(); if (mShapeFPAnimThread[i]) { mShapeFPInstance[i]->setTimeScale(mShapeFPAnimThread[i],0); } } } } if ( isGhost() ) { // Create the sounds ahead of time. This reduces runtime // costs and makes the system easier to understand. SFX_DELETE( mMoveBubbleSound ); SFX_DELETE( mWaterBreathSound ); if ( mDataBlock->getPlayerSound(PlayerData::MoveBubbles) ) mMoveBubbleSound = SFX->createSource( mDataBlock->getPlayerSoundProfile(PlayerData::MoveBubbles) ); if ( mDataBlock->getPlayerSound(PlayerData::WaterBreath) ) mWaterBreathSound = SFX->createSource( mDataBlock->getPlayerSoundProfile(PlayerData::WaterBreath) ); } mObjBox.maxExtents.x = mDataBlock->boxSize.x * 0.5f; mObjBox.maxExtents.y = mDataBlock->boxSize.y * 0.5f; mObjBox.maxExtents.z = mDataBlock->boxSize.z; mObjBox.minExtents.x = -mObjBox.maxExtents.x; mObjBox.minExtents.y = -mObjBox.maxExtents.y; mObjBox.minExtents.z = 0.0f; // Setup the box for our convex object... mObjBox.getCenter(&mConvex.mCenter); mConvex.mSize.x = mObjBox.len_x() / 2.0f; mConvex.mSize.y = mObjBox.len_y() / 2.0f; mConvex.mSize.z = mObjBox.len_z() / 2.0f; // Initialize our scaled attributes as well onScaleChanged(); resetWorldBox(); scriptOnNewDataBlock(); return true; } //---------------------------------------------------------------------------- void Player::reSkin() { if ( isGhost() && mShapeInstance && mSkinNameHandle.isValidString() ) { mShapeInstance->resetMaterialList(); Vector<String> skins; String(mSkinNameHandle.getString()).split( ";", skins ); for ( S32 i = 0; i < skins.size(); i++ ) { String oldSkin( mAppliedSkinName.c_str() ); String newSkin( skins[i] ); // Check if the skin handle contains an explicit "old" base string. This // allows all models to support skinning, even if they don't follow the // "base_xxx" material naming convention. S32 split = newSkin.find( '=' ); // "old=new" format skin? if ( split != String::NPos ) { oldSkin = newSkin.substr( 0, split ); newSkin = newSkin.erase( 0, split+1 ); } // Apply skin to both 3rd person and 1st person shape instances mShapeInstance->reSkin( newSkin, oldSkin ); for ( S32 j = 0; j < ShapeBase::MaxMountedImages; j++ ) { if (mShapeFPInstance[j]) mShapeFPInstance[j]->reSkin( newSkin, oldSkin ); } mAppliedSkinName = newSkin; } } } //---------------------------------------------------------------------------- void Player::setControllingClient(GameConnection* client) { Parent::setControllingClient(client); if (mControlObject) mControlObject->setControllingClient(client); } void Player::setControlObject(ShapeBase* obj) { if (mControlObject == obj) return; if (mControlObject) { mControlObject->setControllingObject(0); mControlObject->setControllingClient(0); } if (obj == this || obj == 0) mControlObject = 0; else { if (ShapeBase* coo = obj->getControllingObject()) coo->setControlObject(0); if (GameConnection* con = obj->getControllingClient()) con->setControlObject(0); mControlObject = obj; mControlObject->setControllingObject(this); mControlObject->setControllingClient(getControllingClient()); } } void Player::onCameraScopeQuery(NetConnection *connection, CameraScopeQuery *query) { // First, we are certainly in scope, and whatever we're riding is too... if(mControlObject.isNull() || mControlObject == mMount.object) Parent::onCameraScopeQuery(connection, query); else { connection->objectInScope(this); if (isMounted()) connection->objectInScope(mMount.object); mControlObject->onCameraScopeQuery(connection, query); } } ShapeBase* Player::getControlObject() { return mControlObject; } void Player::processTick(const Move* move) { PROFILE_SCOPE(Player_ProcessTick); bool prevMoveMotion = mMoveMotion; Pose prevPose = getPose(); // If we're not being controlled by a client, let the // AI sub-module get a chance at producing a move. Move aiMove; if (!move && isServerObject() && getAIMove(&aiMove)) move = &aiMove; // Manage the control object and filter moves for the player Move pMove,cMove; if (mControlObject) { if (!move) mControlObject->processTick(0); else { pMove = NullMove; cMove = *move; //if (isMounted()) { // Filter Jump trigger if mounted //pMove.trigger[2] = move->trigger[2]; //cMove.trigger[2] = false; //} if (move->freeLook) { // Filter yaw/picth/roll when freelooking. pMove.yaw = move->yaw; pMove.pitch = move->pitch; pMove.roll = move->roll; pMove.freeLook = true; cMove.freeLook = false; cMove.yaw = cMove.pitch = cMove.roll = 0.0f; } mControlObject->processTick((mDamageState == Enabled)? &cMove: &NullMove); move = &pMove; } } Parent::processTick(move); // Check for state changes in the standard move triggers and // set bits for any triggers that switched on this tick in // the fx_s_triggers mask. Flag any changes to be packed to // clients. if (isServerObject()) { fx_s_triggers = 0; if (move) { U8 on_bits = 0; for (S32 i = 0; i < MaxTriggerKeys; i++) if (move->trigger[i]) on_bits |= BIT(i); if (on_bits != move_trigger_states) { U8 switched_on_bits = (on_bits & ~move_trigger_states); if (switched_on_bits) { fx_s_triggers |= (U32)switched_on_bits; setMaskBits(TriggerMask); } move_trigger_states = on_bits; } } } // Warp to catch up to server if (mDelta.warpTicks > 0) { mDelta.warpTicks--; // Set new pos getTransform().getColumn(3, &mDelta.pos); mDelta.pos += mDelta.warpOffset; mDelta.rot += mDelta.rotOffset; // Wrap yaw to +/-PI if (mDelta.rot.z < - M_PI_F) mDelta.rot.z += M_2PI_F; else if (mDelta.rot.z > M_PI_F) mDelta.rot.z -= M_2PI_F; if (!ignore_updates) { setPosition(mDelta.pos, mDelta.rot); } updateDeathOffsets(); updateLookAnimation(); // Backstepping mDelta.posVec = -mDelta.warpOffset; mDelta.rotVec = -mDelta.rotOffset; } else { // If there is no move, the player is either an // unattached player on the server, or a player's // client ghost. if (!move) { if (isGhost()) { // If we haven't run out of prediction time, // predict using the last known move. if (mPredictionCount-- <= 0) return; move = &mDelta.move; } else move = &NullMove; } if (!isGhost()) updateAnimation(TickSec); PROFILE_START(Player_PhysicsSection); if ( isServerObject() || didRenderLastRender() || getControllingClient() ) { if ( !mPhysicsRep ) { if ( isMounted() ) { // If we're mounted then do not perform any collision checks // and clear our previous working list. mConvex.clearWorkingList(); } else { updateWorkingCollisionSet(); } } updateState(); updateMove(move); updateLookAnimation(); updateDeathOffsets(); updatePos(); } PROFILE_END(); if (!isGhost()) { // Animations are advanced based on frame rate on the // client and must be ticked on the server. updateActionThread(); updateAnimationTree(true); // Check for sprinting motion changes Pose currentPose = getPose(); // Player has just switched into Sprint pose and is moving if (currentPose == SprintPose && prevPose != SprintPose && mMoveMotion) { mDataBlock->onStartSprintMotion_callback( this ); } // Player has just switched out of Sprint pose and is moving, or was just moving else if (currentPose != SprintPose && prevPose == SprintPose && (mMoveMotion || prevMoveMotion)) { mDataBlock->onStopSprintMotion_callback( this ); } // Player is in Sprint pose and has modified their motion else if (currentPose == SprintPose && prevMoveMotion != mMoveMotion) { if (mMoveMotion) { mDataBlock->onStartSprintMotion_callback( this ); } else { mDataBlock->onStopSprintMotion_callback( this ); } } } } // PATHSHAPE if (!isGhost()) updateAttachment(); // PATHSHAPE END } void Player::interpolateTick(F32 dt) { if (mControlObject) mControlObject->interpolateTick(dt); // Client side interpolation Parent::interpolateTick(dt); Point3F pos = mDelta.pos + mDelta.posVec * dt; Point3F rot = mDelta.rot + mDelta.rotVec * dt; if (!ignore_updates) setRenderPosition(pos,rot,dt); /* // apply camera effects - is this the best place? - bramage GameConnection* connection = GameConnection::getConnectionToServer(); if( connection->isFirstPerson() ) { ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject()); if( obj == this ) { MatrixF curTrans = getRenderTransform(); curTrans.mul( gCamFXMgr.getTrans() ); Parent::setRenderTransform( curTrans ); } } */ updateLookAnimation(dt); mDelta.dt = dt; // PATHSHAPE updateRenderChangesByParent(); // PATHSHAPE END } void Player::advanceTime(F32 dt) { // Client side animations Parent::advanceTime(dt); // Increment timer for triggering idle events. if (idle_timer >= 0.0f) idle_timer += dt; updateActionThread(); updateAnimation(dt); updateSplash(); updateFroth(dt); updateWaterSounds(dt); mLastPos = getPosition(); if (mImpactSound) playImpactSound(); // update camera effects. Definitely need to find better place for this - bramage if( isControlObject() ) { if( mDamageState == Disabled || mDamageState == Destroyed ) { // clear out all camera effects being applied to player if dead gCamFXMgr.clear(); } } } bool Player::getAIMove(Move* move) { return false; } void Player::setState(ActionState state, U32 recoverTicks) { if (state != mState) { // Skip initialization if there is no manager, the state // will get reset when the object is added to a manager. if (isProperlyAdded()) { switch (state) { case RecoverState: { if (mDataBlock->landSequenceTime > 0.0f) { // Use the land sequence as the basis for the recovery setActionThread(PlayerData::LandAnim, true, false, true, true); F32 timeScale = mShapeInstance->getDuration(mActionAnimation.thread) / mDataBlock->landSequenceTime; mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale); mRecoverDelay = mDataBlock->landSequenceTime; } else { // Legacy recover system mRecoverTicks = recoverTicks; mReversePending = U32(F32(mRecoverTicks) / sLandReverseScale); setActionThread(PlayerData::LandAnim, true, false, true, true); } break; } default: break; } } mState = state; } } void Player::updateState() { switch (mState) { case RecoverState: if (mDataBlock->landSequenceTime > 0.0f) { // Count down the land time mRecoverDelay -= TickSec; if (mRecoverDelay <= 0.0f) { setState(MoveState); } } else { // Legacy recover system if (mRecoverTicks-- <= 0) { if (mReversePending && mActionAnimation.action != PlayerData::NullAnimation) { // this serves and counter, and direction state mRecoverTicks = mReversePending; mActionAnimation.forward = false; S32 seq = mDataBlock->actionList[mActionAnimation.action].sequence; S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action); if (imageBasedSeq != -1) seq = imageBasedSeq; F32 pos = mShapeInstance->getPos(mActionAnimation.thread); mShapeInstance->setTimeScale(mActionAnimation.thread, -sLandReverseScale); mShapeInstance->transitionToSequence(mActionAnimation.thread, seq, pos, sAnimationTransitionTime, true); mReversePending = 0; } else { setState(MoveState); } } // Stand back up slowly only if not moving much- else if (!mReversePending && mVelocity.lenSquared() > sSlowStandThreshSquared) { mActionAnimation.waitForEnd = false; setState(MoveState); } } break; default: break; } } const char* Player::getStateName() { if (mDamageState != Enabled) return "Dead"; if (isMounted()) return "Mounted"; if (mState == RecoverState) return "Recover"; return "Move"; } void Player::getDamageLocation(const Point3F& in_rPos, const char *&out_rpVert, const char *&out_rpQuad) { // TODO: This will be WRONG when player is prone or swimming! Point3F newPoint; mWorldToObj.mulP(in_rPos, &newPoint); Point3F boxSize = mObjBox.getExtents(); F32 zHeight = boxSize.z; F32 zTorso = mDataBlock->boxTorsoPercentage; F32 zHead = mDataBlock->boxHeadPercentage; zTorso *= zHeight; zHead *= zHeight; if (newPoint.z <= zTorso) out_rpVert = "legs"; else if (newPoint.z <= zHead) out_rpVert = "torso"; else out_rpVert = "head"; if(String::compare(out_rpVert, "head") != 0) { if (newPoint.y >= 0.0f) { if (newPoint.x <= 0.0f) out_rpQuad = "front_left"; else out_rpQuad = "front_right"; } else { if (newPoint.x <= 0.0f) out_rpQuad = "back_left"; else out_rpQuad = "back_right"; } } else { F32 backToFront = boxSize.x; F32 leftToRight = boxSize.y; F32 backPoint = backToFront * mDataBlock->boxHeadBackPercentage; F32 frontPoint = backToFront * mDataBlock->boxHeadFrontPercentage; F32 leftPoint = leftToRight * mDataBlock->boxHeadLeftPercentage; F32 rightPoint = leftToRight * mDataBlock->boxHeadRightPercentage; S32 index = 0; if (newPoint.y < backPoint) index += 0; else if (newPoint.y >= frontPoint) index += 3; else index += 6; if (newPoint.x < leftPoint) index += 0; else if (newPoint.x >= rightPoint) index += 1; else index += 2; switch (index) { case 0: out_rpQuad = "left_back"; break; case 1: out_rpQuad = "middle_back"; break; case 2: out_rpQuad = "right_back"; break; case 3: out_rpQuad = "left_middle"; break; case 4: out_rpQuad = "middle_middle"; break; case 5: out_rpQuad = "right_middle"; break; case 6: out_rpQuad = "left_front"; break; case 7: out_rpQuad = "middle_front"; break; case 8: out_rpQuad = "right_front"; break; default: AssertFatal(0, "Bad non-tant index"); }; } } const char* Player::getPoseName() const { return EngineMarshallData< PlayerPose >(getPose()); } void Player::setPose( Pose pose ) { // Already the set pose, return. if ( pose == mPose ) return; Pose oldPose = mPose; mPose = pose; // Not added yet, just assign the pose and return. if ( !isProperlyAdded() ) return; Point3F boxSize(1,1,1); // Resize the player boxes switch (pose) { case StandPose: case SprintPose: boxSize = mDataBlock->boxSize; break; case CrouchPose: boxSize = mDataBlock->crouchBoxSize; break; case PronePose: boxSize = mDataBlock->proneBoxSize; break; case SwimPose: boxSize = mDataBlock->swimBoxSize; break; } // Object and World Boxes... mObjBox.maxExtents.x = boxSize.x * 0.5f; mObjBox.maxExtents.y = boxSize.y * 0.5f; mObjBox.maxExtents.z = boxSize.z; mObjBox.minExtents.x = -mObjBox.maxExtents.x; mObjBox.minExtents.y = -mObjBox.maxExtents.y; mObjBox.minExtents.z = 0.0f; resetWorldBox(); // Setup the box for our convex object... mObjBox.getCenter(&mConvex.mCenter); mConvex.mSize.x = mObjBox.len_x() / 2.0f; mConvex.mSize.y = mObjBox.len_y() / 2.0f; mConvex.mSize.z = mObjBox.len_z() / 2.0f; // Initialize our scaled attributes as well... onScaleChanged(); // Resize the PhysicsPlayer rep. should we have one if ( mPhysicsRep ) mPhysicsRep->setSpacials( getPosition(), boxSize ); if ( isServerObject() ) mDataBlock->onPoseChange_callback( this, EngineMarshallData< PlayerPose >(oldPose), EngineMarshallData< PlayerPose >(mPose)); } void Player::allowAllPoses() { mAllowJumping = true; mAllowJetJumping = true; mAllowSprinting = true; mAllowCrouching = true; mAllowProne = true; mAllowSwimming = true; } AngAxisF gPlayerMoveRot; void Player::updateMove(const Move* move) { struct Move my_move; if (override_movement && movement_op < 3) { my_move = *move; switch (movement_op) { case 0: // add my_move.x += movement_data.x; my_move.y += movement_data.y; my_move.z += movement_data.z; break; case 1: // mult my_move.x *= movement_data.x; my_move.y *= movement_data.y; my_move.z *= movement_data.z; break; case 2: // replace my_move.x = movement_data.x; my_move.y = movement_data.y; my_move.z = movement_data.z; break; } move = &my_move; } mDelta.move = *move; #ifdef TORQUE_OPENVR if (mControllers[0]) { mControllers[0]->processTick(move); } if (mControllers[1]) { mControllers[1]->processTick(move); } #endif // Is waterCoverage high enough to be 'swimming'? { bool swimming = mWaterCoverage > 0.65f && canSwim(); if ( swimming != mSwimming ) { if ( !isGhost() ) { if ( swimming ) mDataBlock->onStartSwim_callback( this ); else mDataBlock->onStopSwim_callback( this ); } mSwimming = swimming; } } // Trigger images if (mDamageState == Enabled) { setImageTriggerState( 0, move->trigger[sImageTrigger0] ); // If you have a secondary mounted image then // send the second trigger to it. Else give it // to the first image as an alt fire. if ( getMountedImage( 1 ) ) setImageTriggerState( 1, move->trigger[sImageTrigger1] ); else setImageAltTriggerState( 0, move->trigger[sImageTrigger1] ); } // Update current orientation if (mDamageState == Enabled) { F32 prevZRot = mRot.z; mDelta.headVec = mHead; bool doStandardMove = true; bool absoluteDelta = false; GameConnection* con = getControllingClient(); #ifdef TORQUE_EXTENDED_MOVE // Work with an absolute rotation from the ExtendedMove class? if(con && con->getControlSchemeAbsoluteRotation()) { doStandardMove = false; const ExtendedMove* emove = dynamic_cast<const ExtendedMove*>(move); U32 emoveIndex = smExtendedMoveHeadPosRotIndex; if(emoveIndex >= ExtendedMove::MaxPositionsRotations) emoveIndex = 0; if(emove->EulerBasedRotation[emoveIndex]) { // Head pitch mHead.x += (emove->rotX[emoveIndex] - mLastAbsolutePitch); // Do we also include the relative yaw value? if(con->getControlSchemeAddPitchToAbsRot()) { F32 x = move->pitch; if (x > M_PI_F) x -= M_2PI_F; mHead.x += x; } // Constrain the range of mHead.x while (mHead.x < -M_PI_F) mHead.x += M_2PI_F; while (mHead.x > M_PI_F) mHead.x -= M_2PI_F; // Rotate (heading) head or body? if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson()))) { // Rotate head mHead.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw); // Do we also include the relative yaw value? if(con->getControlSchemeAddYawToAbsRot()) { F32 z = move->yaw; if (z > M_PI_F) z -= M_2PI_F; mHead.z += z; } // Constrain the range of mHead.z while (mHead.z < 0.0f) mHead.z += M_2PI_F; while (mHead.z > M_2PI_F) mHead.z -= M_2PI_F; } else { // Rotate body mRot.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw); // Do we also include the relative yaw value? if(con->getControlSchemeAddYawToAbsRot()) { F32 z = move->yaw; if (z > M_PI_F) z -= M_2PI_F; mRot.z += z; } // Constrain the range of mRot.z while (mRot.z < 0.0f) mRot.z += M_2PI_F; while (mRot.z > M_2PI_F) mRot.z -= M_2PI_F; } mLastAbsoluteYaw = emove->rotZ[emoveIndex]; mLastAbsolutePitch = emove->rotX[emoveIndex]; mLastAbsoluteRoll = emove->rotY[emoveIndex]; // Head bank mHead.y = emove->rotY[emoveIndex]; // Constrain the range of mHead.y while (mHead.y > M_PI_F) mHead.y -= M_2PI_F; } else { // Orient the player so we are looking towards the required position, ignoring any banking AngAxisF moveRot(Point3F(emove->rotX[emoveIndex], emove->rotY[emoveIndex], emove->rotZ[emoveIndex]), emove->rotW[emoveIndex]); MatrixF trans(1); moveRot.setMatrix(&trans); trans.inverse(); Point3F vecForward(0, 10, 0); Point3F viewAngle; Point3F orient; EulerF rot; trans.mulV(vecForward); viewAngle = vecForward; vecForward.z = 0; // flatten vecForward.normalizeSafe(); F32 yawAng; F32 pitchAng; MathUtils::getAnglesFromVector(vecForward, yawAng, pitchAng); mRot = EulerF(0); mRot.z = yawAng; mHead = EulerF(0); while (mRot.z < 0.0f) mRot.z += M_2PI_F; while (mRot.z > M_2PI_F) mRot.z -= M_2PI_F; absoluteDelta = true; } } #endif if(doStandardMove) { F32 p = move->pitch * (mPose == SprintPose ? mDataBlock->sprintPitchScale : 1.0f); if (p > M_PI_F) p -= M_2PI_F; mHead.x = mClampF(mHead.x + p,mDataBlock->minLookAngle, mDataBlock->maxLookAngle); F32 y = move->yaw * (mPose == SprintPose ? mDataBlock->sprintYawScale : 1.0f); if (y > M_PI_F) y -= M_2PI_F; if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson()))) { mHead.z = mClampF(mHead.z + y, -mDataBlock->maxFreelookAngle, mDataBlock->maxFreelookAngle); } else { mRot.z += y; // Rotate the head back to the front, center horizontal // as well if we're controlling another object. mHead.z *= 0.5f; if (mControlObject) mHead.x *= 0.5f; } // constrain the range of mRot.z while (mRot.z < 0.0f) mRot.z += M_2PI_F; while (mRot.z > M_2PI_F) mRot.z -= M_2PI_F; } mDelta.rot = mRot; mDelta.rotVec.x = mDelta.rotVec.y = 0.0f; mDelta.rotVec.z = prevZRot - mRot.z; if (mDelta.rotVec.z > M_PI_F) mDelta.rotVec.z -= M_2PI_F; else if (mDelta.rotVec.z < -M_PI_F) mDelta.rotVec.z += M_2PI_F; mDelta.head = mHead; mDelta.headVec -= mHead; if (absoluteDelta) { mDelta.headVec = Point3F(0, 0, 0); mDelta.rotVec = Point3F(0, 0, 0); } for(U32 i=0; i<3; ++i) { if (mDelta.headVec[i] > M_PI_F) mDelta.headVec[i] -= M_2PI_F; else if (mDelta.headVec[i] < -M_PI_F) mDelta.headVec[i] += M_2PI_F; } } MatrixF zRot; zRot.set(EulerF(0.0f, 0.0f, mRot.z)); // Desired move direction & speed VectorF moveVec; F32 moveSpeed; // If BLOCK_USER_CONTROL is set in anim_clip_flags, the user won't be able to // resume control over the player character. This generally happens for // short periods of time synchronized with script driven animation at places // where it makes sense that user motion is prohibited, such as when the // player is lifted off the ground or knocked down. if ((mState == MoveState || (mState == RecoverState && mDataBlock->recoverRunForceScale > 0.0f)) && mDamageState == Enabled && !isAnimationLocked()) { zRot.getColumn(0,&moveVec); moveVec *= (move->x * (mPose == SprintPose ? mDataBlock->sprintStrafeScale : 1.0f)); VectorF tv; zRot.getColumn(1,&tv); moveVec += tv * move->y; // Clamp water movement if (move->y > 0.0f) { if ( mSwimming ) moveSpeed = getMax(mDataBlock->maxUnderwaterForwardSpeed * move->y, mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x)); else if ( mPose == PronePose ) moveSpeed = getMax(mDataBlock->maxProneForwardSpeed * move->y, mDataBlock->maxProneSideSpeed * mFabs(move->x)); else if ( mPose == CrouchPose ) moveSpeed = getMax(mDataBlock->maxCrouchForwardSpeed * move->y, mDataBlock->maxCrouchSideSpeed * mFabs(move->x)); else if ( mPose == SprintPose ) moveSpeed = getMax(mDataBlock->maxSprintForwardSpeed * move->y, mDataBlock->maxSprintSideSpeed * mFabs(move->x)); else // StandPose moveSpeed = getMax(mDataBlock->maxForwardSpeed * move->y, mDataBlock->maxSideSpeed * mFabs(move->x)); } else { if ( mSwimming ) moveSpeed = getMax(mDataBlock->maxUnderwaterBackwardSpeed * mFabs(move->y), mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x)); else if ( mPose == PronePose ) moveSpeed = getMax(mDataBlock->maxProneBackwardSpeed * mFabs(move->y), mDataBlock->maxProneSideSpeed * mFabs(move->x)); else if ( mPose == CrouchPose ) moveSpeed = getMax(mDataBlock->maxCrouchBackwardSpeed * mFabs(move->y), mDataBlock->maxCrouchSideSpeed * mFabs(move->x)); else if ( mPose == SprintPose ) moveSpeed = getMax(mDataBlock->maxSprintBackwardSpeed * mFabs(move->y), mDataBlock->maxSprintSideSpeed * mFabs(move->x)); else // StandPose moveSpeed = getMax(mDataBlock->maxBackwardSpeed * mFabs(move->y), mDataBlock->maxSideSpeed * mFabs(move->x)); } // Cancel any script driven animations if we are going to move. if (moveVec.x + moveVec.y + moveVec.z != 0.0f && (mActionAnimation.action >= PlayerData::NumTableActionAnims || mActionAnimation.action == PlayerData::LandAnim)) mActionAnimation.action = PlayerData::NullAnimation; } else { moveVec.set(0.0f, 0.0f, 0.0f); moveSpeed = 0.0f; } // apply speed bias here. speed_bias = speed_bias + (speed_bias_goal - speed_bias)*0.1f; moveSpeed *= speed_bias; // Acceleration due to gravity VectorF acc(0.0f, 0.0f, mNetGravity/(1.0 - mBuoyancy) * TickSec); if (getParent() !=NULL) acc = VectorF::Zero; // Determine ground contact normal. Only look for contacts if // we can move and aren't mounted. VectorF contactNormal(0,0,0); bool jumpSurface = false, runSurface = false; if ( !isMounted() ) findContact( &runSurface, &jumpSurface, &contactNormal ); if ( jumpSurface ) mJumpSurfaceNormal = contactNormal; // If we don't have a runSurface but we do have a contactNormal, // then we are standing on something that is too steep. // Deflect the force of gravity by the normal so we slide. // We could also try aligning it to the runSurface instead, // but this seems to work well. if ( !runSurface && !contactNormal.isZero() ) acc = ( acc - 2 * contactNormal * mDot( acc, contactNormal ) ); // Acceleration on run surface if (runSurface && !mSwimming) { mContactTimer = 0; // Remove acc into contact surface (should only be gravity) // Clear out floating point acc errors, this will allow // the player to "rest" on the ground. // However, no need to do that if we're using a physics library. // It will take care of itself. if (!mPhysicsRep) { F32 vd = -mDot(acc,contactNormal); if (vd > 0.0f) { VectorF dv = contactNormal * (vd + 0.002f); acc += dv; if (acc.len() < 0.0001f) acc.set(0.0f, 0.0f, 0.0f); } } // Force a 0 move if there is no energy, and only drain // move energy if we're moving. VectorF pv; if (mPose == SprintPose && mEnergy >= mDataBlock->minSprintEnergy) { if (moveSpeed) mEnergy -= mDataBlock->sprintEnergyDrain; pv = moveVec; } else if (mEnergy >= mDataBlock->minRunEnergy) { if (moveSpeed) mEnergy -= mDataBlock->runEnergyDrain; pv = moveVec; } else pv.set(0.0f, 0.0f, 0.0f); // Adjust the player's requested dir. to be parallel // to the contact surface. F32 pvl = pv.len(); if(mJetting) { pvl = moveVec.len(); if (pvl) { VectorF nn; mCross(pv,VectorF(0.0f, 0.0f, 0.0f),&nn); nn *= 1 / pvl; VectorF cv(0.0f, 0.0f, 0.0f); cv -= nn * mDot(nn,cv); pv -= cv * mDot(pv,cv); pvl = pv.len(); } } else if (!mPhysicsRep) { // We only do this if we're not using a physics library. The // library will take care of itself. if (pvl) { VectorF nn; mCross(pv,VectorF(0.0f, 0.0f, 1.0f),&nn); nn *= 1.0f / pvl; VectorF cv = contactNormal; cv -= nn * mDot(nn,cv); pv -= cv * mDot(pv,cv); pvl = pv.len(); } } // Convert to acceleration if ( pvl ) pv *= moveSpeed / pvl; VectorF runAcc = pv - (mVelocity + acc); F32 runSpeed = runAcc.len(); // Clamp acceleration, player also accelerates faster when // in his hard landing recover state. F32 maxAcc; if (mPose == SprintPose) { maxAcc = (mDataBlock->sprintForce / getMass()) * TickSec; } else { maxAcc = (mDataBlock->runForce / getMass()) * TickSec; } if (mState == RecoverState) maxAcc *= mDataBlock->recoverRunForceScale; if (runSpeed > maxAcc) runAcc *= maxAcc / runSpeed; acc += runAcc; // If we are running on the ground, then we're not jumping if (mDataBlock->isJumpAction(mActionAnimation.action)) mActionAnimation.action = PlayerData::NullAnimation; } else if (!mSwimming && mDataBlock->airControl > 0.0f) { VectorF pv; pv = moveVec; F32 pvl = pv.len(); if (pvl) pv *= moveSpeed / pvl; VectorF runAcc = pv - (mVelocity + acc); runAcc.z = 0; runAcc.x = runAcc.x * mDataBlock->airControl; runAcc.y = runAcc.y * mDataBlock->airControl; F32 runSpeed = runAcc.len(); // We don't test for sprinting when performing air control F32 maxAcc = (mDataBlock->runForce / getMass()) * TickSec * 0.3f; if (runSpeed > maxAcc) runAcc *= maxAcc / runSpeed; acc += runAcc; // There are no special air control animations // so... increment this unless you really want to // play the run anims in the air. mContactTimer++; } else if (mSwimming) { // Remove acc into contact surface (should only be gravity) // Clear out floating point acc errors, this will allow // the player to "rest" on the ground. F32 vd = -mDot(acc,contactNormal); if (vd > 0.0f) { VectorF dv = contactNormal * (vd + 0.002f); acc += dv; if (acc.len() < 0.0001f) acc.set(0.0f, 0.0f, 0.0f); } // get the head pitch and add it to the moveVec // This more accurate swim vector calc comes from Matt Fairfax MatrixF xRot; xRot.set(EulerF(mHead.x, 0, 0)); zRot.set(EulerF(0, 0, mRot.z)); MatrixF rot; rot.mul(zRot, xRot); rot.getColumn(0,&moveVec); moveVec *= move->x; VectorF tv; rot.getColumn(1,&tv); moveVec += tv * move->y; rot.getColumn(2,&tv); moveVec += tv * move->z; // Force a 0 move if there is no energy, and only drain // move energy if we're moving. VectorF swimVec; if (mEnergy >= mDataBlock->minRunEnergy) { if (moveSpeed) mEnergy -= mDataBlock->runEnergyDrain; swimVec = moveVec; } else swimVec.set(0.0f, 0.0f, 0.0f); // If we are swimming but close enough to the shore/ground // we can still have a surface-normal. In this case align the // velocity to the normal to make getting out of water easier. moveVec.normalize(); F32 isSwimUp = mDot( moveVec, contactNormal ); if ( !contactNormal.isZero() && isSwimUp < 0.1f ) { F32 pvl = swimVec.len(); if ( true && pvl ) { VectorF nn; mCross(swimVec,VectorF(0.0f, 0.0f, 1.0f),&nn); nn *= 1.0f / pvl; VectorF cv = contactNormal; cv -= nn * mDot(nn,cv); swimVec -= cv * mDot(swimVec,cv); } } F32 swimVecLen = swimVec.len(); // Convert to acceleration. if ( swimVecLen ) swimVec *= moveSpeed / swimVecLen; VectorF swimAcc = swimVec - (mVelocity + acc); F32 swimSpeed = swimAcc.len(); // Clamp acceleration. F32 maxAcc = (mDataBlock->swimForce / getMass()) * TickSec; if ( swimSpeed > maxAcc ) swimAcc *= maxAcc / swimSpeed; acc += swimAcc; mContactTimer++; } else mContactTimer++; // Acceleration from Jumping // While BLOCK_USER_CONTROL is set in anim_clip_flags, the user won't be able to // make the player character jump. if (move->trigger[sJumpTrigger] && canJump() && !isAnimationLocked()) { // Scale the jump impulse base on maxJumpSpeed F32 zSpeedScale = mVelocity.z; if (zSpeedScale <= mDataBlock->maxJumpSpeed) { zSpeedScale = (zSpeedScale <= mDataBlock->minJumpSpeed)? 1: 1 - (zSpeedScale - mDataBlock->minJumpSpeed) / (mDataBlock->maxJumpSpeed - mDataBlock->minJumpSpeed); // Desired jump direction VectorF pv = moveVec; F32 len = pv.len(); if (len > 0) pv *= 1 / len; // We want to scale the jump size by the player size, somewhat // in reduced ratio so a smaller player can jump higher in // proportion to his size, than a larger player. F32 scaleZ = (getScale().z * 0.25) + 0.75; // Calculate our jump impulse F32 impulse = mDataBlock->jumpForce / getMass(); if (mDataBlock->jumpTowardsNormal) { // If we are facing into the surface jump up, otherwise // jump away from surface. F32 dot = mDot(pv,mJumpSurfaceNormal); if (dot <= 0) acc.z += mJumpSurfaceNormal.z * scaleZ * impulse * zSpeedScale; else { acc.x += pv.x * impulse * dot; acc.y += pv.y * impulse * dot; acc.z += mJumpSurfaceNormal.z * scaleZ * impulse * zSpeedScale; } } else acc.z += scaleZ * impulse * zSpeedScale; mJumpDelay = mDataBlock->jumpDelay; mEnergy -= mDataBlock->jumpEnergyDrain; // If we don't have a StandJumpAnim, just play the JumpAnim... S32 seq = (mVelocity.len() < 0.5) ? PlayerData::StandJumpAnim: PlayerData::JumpAnim; if ( mDataBlock->actionList[seq].sequence == -1 ) seq = PlayerData::JumpAnim; setActionThread( seq, true, false, true ); mJumpSurfaceLastContact = JumpSkipContactsMax; // Flag the jump event trigger. fx_s_triggers |= PLAYER_JUMP_S_TRIGGER; setMaskBits(TriggerMask); } } else { if (jumpSurface) { if (mJumpDelay > 0) mJumpDelay--; mJumpSurfaceLastContact = 0; } else mJumpSurfaceLastContact++; } if (move->trigger[sJumpJetTrigger] && !isMounted() && canJetJump()) { mJetting = true; // Scale the jump impulse base on maxJumpSpeed F32 zSpeedScale = mVelocity.z; if (zSpeedScale <= mDataBlock->jetMaxJumpSpeed) { zSpeedScale = (zSpeedScale <= mDataBlock->jetMinJumpSpeed)? 1: 1 - (zSpeedScale - mDataBlock->jetMinJumpSpeed) / (mDataBlock->jetMaxJumpSpeed - mDataBlock->jetMinJumpSpeed); // Desired jump direction VectorF pv = moveVec; F32 len = pv.len(); if (len > 0.0f) pv *= 1 / len; // If we are facing into the surface jump up, otherwise // jump away from surface. F32 dot = mDot(pv,mJumpSurfaceNormal); F32 impulse = mDataBlock->jetJumpForce / getMass(); if (dot <= 0) acc.z += mJumpSurfaceNormal.z * impulse * zSpeedScale; else { acc.x += pv.x * impulse * dot; acc.y += pv.y * impulse * dot; acc.z += mJumpSurfaceNormal.z * impulse * zSpeedScale; } mEnergy -= mDataBlock->jetJumpEnergyDrain; } } else { mJetting = false; } // Add in force from physical zones... acc += (mAppliedForce / getMass()) * TickSec; // Adjust velocity with all the move & gravity acceleration // TG: I forgot why doesn't the TickSec multiply happen here... mVelocity += acc; // apply horizontal air resistance F32 hvel = mSqrt(mVelocity.x * mVelocity.x + mVelocity.y * mVelocity.y); if(hvel > mDataBlock->horizResistSpeed) { F32 speedCap = hvel; if(speedCap > mDataBlock->horizMaxSpeed) speedCap = mDataBlock->horizMaxSpeed; speedCap -= mDataBlock->horizResistFactor * TickSec * (speedCap - mDataBlock->horizResistSpeed); F32 scale = speedCap / hvel; mVelocity.x *= scale; mVelocity.y *= scale; } if(mVelocity.z > mDataBlock->upResistSpeed) { if(mVelocity.z > mDataBlock->upMaxSpeed) mVelocity.z = mDataBlock->upMaxSpeed; mVelocity.z -= mDataBlock->upResistFactor * TickSec * (mVelocity.z - mDataBlock->upResistSpeed); } // Apply drag if ( mSwimming ) mVelocity -= mVelocity * mDrag * TickSec * ( mVelocity.len() / mDataBlock->maxUnderwaterForwardSpeed ); else mVelocity -= mVelocity * mDrag * TickSec; // Clamp very small velocity to zero if ( mVelocity.isZero() ) mVelocity = Point3F::Zero; // If we are not touching anything and have sufficient -z vel, // we are falling. if (runSurface) mFalling = false; else { VectorF vel; mWorldToObj.mulV(mVelocity,&vel); mFalling = vel.z < mDataBlock->fallingSpeedThreshold; } // Vehicle Dismount if ( !isGhost() && move->trigger[sVehicleDismountTrigger] && canJump()) mDataBlock->doDismount_callback( this ); // Enter/Leave Liquid if ( !mInWater && mWaterCoverage > 0.0f ) { mInWater = true; if ( !isGhost() ) mDataBlock->onEnterLiquid_callback( this, mWaterCoverage, mLiquidType.c_str() ); } else if ( mInWater && mWaterCoverage <= 0.0f ) { mInWater = false; if ( !isGhost() ) mDataBlock->onLeaveLiquid_callback( this, mLiquidType.c_str() ); else { // exit-water splash sound happens for client only if ( getSpeed() >= mDataBlock->exitSplashSoundVel && !isMounted() ) SFX->playOnce( mDataBlock->getPlayerSoundProfile(PlayerData::ExitWater), &getTransform() ); } } // Update the PlayerPose Pose desiredPose = mPose; if ( !mIsAiControlled ) { if ( mSwimming ) desiredPose = SwimPose; else if ( runSurface && move->trigger[sCrouchTrigger] && canCrouch() ) desiredPose = CrouchPose; else if ( runSurface && move->trigger[sProneTrigger] && canProne() ) desiredPose = PronePose; else if ( move->trigger[sSprintTrigger] && canSprint() ) desiredPose = SprintPose; else if ( canStand() ) desiredPose = StandPose; setPose( desiredPose ); } } //---------------------------------------------------------------------------- bool Player::checkDismountPosition(const MatrixF& oldMat, const MatrixF& mat) { AssertFatal(getContainer() != NULL, "Error, must have a container!"); AssertFatal(getObjectMount() != NULL, "Error, must be mounted!"); Point3F pos; Point3F oldPos; mat.getColumn(3, &pos); oldMat.getColumn(3, &oldPos); RayInfo info; disableCollision(); getObjectMount()->disableCollision(); if (getContainer()->castRay(oldPos, pos, sCollisionMoveMask, &info)) { enableCollision(); getObjectMount()->enableCollision(); return false; } Box3F wBox = mObjBox; wBox.minExtents += pos; wBox.maxExtents += pos; EarlyOutPolyList polyList; polyList.mNormal.set(0.0f, 0.0f, 0.0f); polyList.mPlaneList.clear(); polyList.mPlaneList.setSize(6); polyList.mPlaneList[0].set(wBox.minExtents,VectorF(-1.0f, 0.0f, 0.0f)); polyList.mPlaneList[1].set(wBox.maxExtents,VectorF(0.0f, 1.0f, 0.0f)); polyList.mPlaneList[2].set(wBox.maxExtents,VectorF(1.0f, 0.0f, 0.0f)); polyList.mPlaneList[3].set(wBox.minExtents,VectorF(0.0f, -1.0f, 0.0f)); polyList.mPlaneList[4].set(wBox.minExtents,VectorF(0.0f, 0.0f, -1.0f)); polyList.mPlaneList[5].set(wBox.maxExtents,VectorF(0.0f, 0.0f, 1.0f)); if (getContainer()->buildPolyList(PLC_Collision, wBox, sCollisionMoveMask, &polyList)) { enableCollision(); getObjectMount()->enableCollision(); return false; } enableCollision(); getObjectMount()->enableCollision(); return true; } //---------------------------------------------------------------------------- bool Player::canJump() { return mAllowJumping && mState == MoveState && mDamageState == Enabled && !isMounted() && !mJumpDelay && mEnergy >= mDataBlock->minJumpEnergy && mJumpSurfaceLastContact < JumpSkipContactsMax && !mSwimming && (mPose != SprintPose || mDataBlock->sprintCanJump); } bool Player::canJetJump() { return mAllowJetJumping && mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->jetMinJumpEnergy && mDataBlock->jetJumpForce != 0.0f; } bool Player::canSwim() { // Not used! //return mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->minSwimEnergy && mWaterCoverage >= 0.8f; return mAllowSwimming; } bool Player::canCrouch() { if (!mAllowCrouching) return false; if ( mState != MoveState || mDamageState != Enabled || isMounted() || mSwimming || mFalling ) return false; // Can't crouch if no crouch animation! if ( mDataBlock->actionList[PlayerData::CrouchRootAnim].sequence == -1 ) return false; // We are already in this pose, so don't test it again... if ( mPose == CrouchPose ) return true; // Do standard Torque physics test here! if ( !mPhysicsRep ) { F32 radius; if ( mPose == PronePose ) radius = mDataBlock->proneBoxSize.z; else return true; // use our X and Y dimentions on our boxsize as the radii for our search, and the difference between a standing position // and the position we currently are in. Point3F extent( mDataBlock->crouchBoxSize.x / 2, mDataBlock->crouchBoxSize.y / 2, mDataBlock->crouchBoxSize.z - radius ); Point3F position = getPosition(); position.z += radius; // Use these radii to create a box that represents the difference between a standing position and the position // we want to move into. Box3F B(position - extent, position + extent, true); EarlyOutPolyList polyList; polyList.mPlaneList.clear(); polyList.mNormal.set( 0,0,0 ); polyList.mPlaneList.setSize( 6 ); polyList.mPlaneList[0].set( B.minExtents, VectorF( -1,0,0 ) ); polyList.mPlaneList[1].set( B.maxExtents, VectorF( 0,1,0 ) ); polyList.mPlaneList[2].set( B.maxExtents, VectorF( 1,0,0 ) ); polyList.mPlaneList[3].set( B.minExtents, VectorF( 0,-1,0 ) ); polyList.mPlaneList[4].set( B.minExtents, VectorF( 0,0,-1 ) ); polyList.mPlaneList[5].set( B.maxExtents, VectorF( 0,0,1 ) ); // If an object exists in this space, we must stay prone. Otherwise we are free to crouch. return !getContainer()->buildPolyList( PLC_Collision, B, StaticShapeObjectType, &polyList ); } return mPhysicsRep->testSpacials( getPosition(), mDataBlock->crouchBoxSize ); } bool Player::canStand() { if ( mState != MoveState || mDamageState != Enabled || isMounted() || mSwimming ) return false; // We are already in this pose, so don't test it again... if ( mPose == StandPose ) return true; // Do standard Torque physics test here! if ( !mPhysicsRep ) { F32 radius; if (mPose == CrouchPose) radius = mDataBlock->crouchBoxSize.z; else if (mPose == PronePose) radius = mDataBlock->proneBoxSize.z; else return true; // use our X and Y dimentions on our boxsize as the radii for our search, and the difference between a standing position // and the position we currently are in. Point3F extent( mDataBlock->boxSize.x / 2, mDataBlock->boxSize.y / 2, mDataBlock->boxSize.z - radius ); Point3F position = getPosition(); position.z += radius; // Use these radii to create a box that represents the difference between a standing position and the position // we want to move into. Box3F B(position - extent, position + extent, true); EarlyOutPolyList polyList; polyList.mPlaneList.clear(); polyList.mNormal.set(0,0,0); polyList.mPlaneList.setSize(6); polyList.mPlaneList[0].set(B.minExtents, VectorF(-1,0,0)); polyList.mPlaneList[1].set(B.maxExtents, VectorF(0,1,0)); polyList.mPlaneList[2].set(B.maxExtents, VectorF(1,0,0)); polyList.mPlaneList[3].set(B.minExtents, VectorF(0,-1,0)); polyList.mPlaneList[4].set(B.minExtents, VectorF(0,0,-1)); polyList.mPlaneList[5].set(B.maxExtents, VectorF(0,0,1)); // If an object exists in this space, we must stay crouched/prone. Otherwise we are free to stand. return !getContainer()->buildPolyList(PLC_Collision, B, StaticShapeObjectType, &polyList); } return mPhysicsRep->testSpacials( getPosition(), mDataBlock->boxSize ); } bool Player::canProne() { if (!mAllowProne) return false; if ( mState != MoveState || mDamageState != Enabled || isMounted() || mSwimming || mFalling ) return false; // Can't go prone if no prone animation! if ( mDataBlock->actionList[PlayerData::ProneRootAnim].sequence == -1 ) return false; // Do standard Torque physics test here! if ( !mPhysicsRep ) return true; // We are already in this pose, so don't test it again... if ( mPose == PronePose ) return true; return mPhysicsRep->testSpacials( getPosition(), mDataBlock->proneBoxSize ); } bool Player::canSprint() { return mAllowSprinting && mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->minSprintEnergy && !mSwimming; } //---------------------------------------------------------------------------- void Player::updateDamageLevel() { if (!isGhost()) setDamageState((mDamage >= mDataBlock->maxDamage)? Disabled: Enabled); if (mDamageThread) mShapeInstance->setPos(mDamageThread, mDamage / mDataBlock->destroyedLevel); } void Player::updateDamageState() { // Become a corpse when we're disabled (dead). if (mDamageState == Enabled) { mTypeMask &= ~CorpseObjectType; mTypeMask |= PlayerObjectType; } else { mTypeMask &= ~PlayerObjectType; mTypeMask |= CorpseObjectType; } Parent::updateDamageState(); } //---------------------------------------------------------------------------- void Player::updateLookAnimation(F32 dt) { // If the preference setting overrideLookAnimation is true, the player's // arm and head no longer animate according to the view direction. They // are instead given fixed positions. if (overrideLookAnimation) { if (mArmAnimation.thread) mShapeInstance->setPos(mArmAnimation.thread, armLookOverridePos); if (mHeadVThread) mShapeInstance->setPos(mHeadVThread, headVLookOverridePos); if (mHeadHThread) mShapeInstance->setPos(mHeadHThread, headHLookOverridePos); return; } // Calculate our interpolated head position. Point3F renderHead = mDelta.head + mDelta.headVec * dt; // Adjust look pos. This assumes that the animations match // the min and max look angles provided in the datablock. if (mArmAnimation.thread) { if(mControlObject) { mShapeInstance->setPos(mArmAnimation.thread,0.5f); } else { F32 d = mDataBlock->maxLookAngle - mDataBlock->minLookAngle; F32 tp = (renderHead.x - mDataBlock->minLookAngle) / d; mShapeInstance->setPos(mArmAnimation.thread,mClampF(tp,0,1)); } } if (mHeadVThread) { F32 d = mDataBlock->maxLookAngle - mDataBlock->minLookAngle; F32 tp = (renderHead.x - mDataBlock->minLookAngle) / d; mShapeInstance->setPos(mHeadVThread,mClampF(tp,0,1)); } if (mHeadHThread) { F32 d = 2 * mDataBlock->maxFreelookAngle; F32 tp = (renderHead.z + mDataBlock->maxFreelookAngle) / d; mShapeInstance->setPos(mHeadHThread,mClampF(tp,0,1)); } } //---------------------------------------------------------------------------- // Methods to get delta (as amount to affect velocity by) bool Player::inDeathAnim() { if ((anim_clip_flags & ANIM_OVERRIDDEN) != 0 && (anim_clip_flags & IS_DEATH_ANIM) == 0) return false; if (mActionAnimation.thread && mActionAnimation.action >= 0) if (mActionAnimation.action < mDataBlock->actionCount) return mDataBlock->actionList[mActionAnimation.action].death; return false; } // Get change from mLastDeathPos - return current pos. Assumes we're in death anim. F32 Player::deathDelta(Point3F & delta) { // Get ground delta from the last time we offset this. MatrixF mat; F32 pos = mShapeInstance->getPos(mActionAnimation.thread); mShapeInstance->deltaGround1(mActionAnimation.thread, mDeath.lastPos, pos, mat); mat.getColumn(3, & delta); return pos; } // Called before updatePos() to prepare it's needed change to velocity, which // must roll over. Should be updated on tick, this is where we remember last // position of animation that was used to roll into velocity. void Player::updateDeathOffsets() { if (inDeathAnim()) // Get ground delta from the last time we offset this. mDeath.lastPos = deathDelta(mDeath.posAdd); else mDeath.clear(); } //---------------------------------------------------------------------------- // PATHSHAPE static const U32 sPlayerConformMask = StaticShapeObjectType | StaticObjectType | TerrainObjectType | PathShapeObjectType; // PATHSHAPE END static void accel(F32& from, F32 to, F32 rate) { if (from < to) from = getMin(from += rate, to); else from = getMax(from -= rate, to); } // if (dt == -1) // normal tick, so we advance. // else // interpolate with dt as % of tick, don't advance // MatrixF * Player::Death::fallToGround(F32 dt, const Point3F& loc, F32 curZ, F32 boxRad) { static const F32 sConformCheckDown = 4.0f; RayInfo coll; bool conformToStairs = false; Point3F pos(loc.x, loc.y, loc.z + 0.1f); Point3F below(pos.x, pos.y, loc.z - sConformCheckDown); MatrixF * retVal = NULL; PROFILE_SCOPE(ConformToGround); if (gClientContainer.castRay(pos, below, sPlayerConformMask, &coll)) { F32 adjust, height = (loc.z - coll.point.z), sink = curSink; VectorF desNormal = coll.normal; VectorF normal = curNormal; // dt >= 0 means we're interpolating and don't accel the numbers if (dt >= 0.0f) adjust = dt * TickSec; else adjust = TickSec; // Try to get them to conform to stairs by doing several LOS calls. We do this if // normal is within about 5 deg. of vertical. if (desNormal.z > 0.995f) { Point3F corners[3], downpts[3]; S32 c; for (c = 0; c < 3; c++) { // Build 3 corners to cast down from- corners[c].set(loc.x - boxRad, loc.y - boxRad, loc.z + 1.0f); if (c) // add (0,boxWidth) and (boxWidth,0) corners[c][c - 1] += (boxRad * 2.0f); downpts[c].set(corners[c].x, corners[c].y, loc.z - sConformCheckDown); } // Do the three casts- for (c = 0; c < 3; c++) if (gClientContainer.castRay(corners[c], downpts[c], sPlayerConformMask, &coll)) downpts[c] = coll.point; else break; // Do the math if everything hit below- if (c == 3) { mCross(downpts[1] - downpts[0], downpts[2] - downpts[1], &desNormal); AssertFatal(desNormal.z > 0, "Abnormality in Player::Death::fallToGround()"); downpts[2] = downpts[2] - downpts[1]; downpts[1] = downpts[1] - downpts[0]; desNormal.normalize(); conformToStairs = true; } } // Move normal in direction we want- F32 * cur = normal, * des = desNormal; for (S32 i = 0; i < 3; i++) accel(*cur++, *des++, adjust * 0.25f); if (mFabs(height) < 2.2f && !normal.isZero() && desNormal.z > 0.01f) { VectorF upY(0.0f, 1.0f, 0.0f), ahead; VectorF sideVec; MatrixF mat(true); normal.normalize(); mat.set(EulerF (0.0f, 0.0f, curZ)); mat.mulV(upY, & ahead); mCross(ahead, normal, &sideVec); sideVec.normalize(); mCross(normal, sideVec, &ahead); static MatrixF resMat(true); resMat.setColumn(0, sideVec); resMat.setColumn(1, ahead); resMat.setColumn(2, normal); // Adjust Z down to account for box offset on slope. Figure out how // much we want to sink, and gradually accel to this amount. Don't do if // we're conforming to stairs though F32 xy = mSqrt(desNormal.x * desNormal.x + desNormal.y * desNormal.y); F32 desiredSink = (boxRad * xy / desNormal.z); if (conformToStairs) desiredSink *= 0.5f; accel(sink, desiredSink, adjust * 0.15f); Point3F position(pos); position.z -= sink; resMat.setColumn(3, position); if (dt < 0.0f) { // we're moving, so update normal and sink amount curNormal = normal; curSink = sink; } retVal = &resMat; } } return retVal; } //------------------------------------------------------------------------------------- // This is called ::onAdd() to see if we're in a sitting animation. These then // can use a longer tick delay for the mount to get across. bool Player::inSittingAnim() { U32 action = mActionAnimation.action; if (mActionAnimation.thread && action < mDataBlock->actionCount) { const char * name = mDataBlock->actionList[action].name; if (!dStricmp(name, "Sitting") || !dStricmp(name, "Scoutroot")) return true; } return false; } //---------------------------------------------------------------------------- const String& Player::getArmThread() const { if (mArmAnimation.thread && mArmAnimation.thread->hasSequence()) { return mArmAnimation.thread->getSequenceName(); } return String::EmptyString; } bool Player::setArmThread(const char* sequence) { // The arm sequence must be in the action list. for (U32 i = 1; i < mDataBlock->actionCount; i++) if (!dStricmp(mDataBlock->actionList[i].name,sequence)) return setArmThread(i); return false; } bool Player::setArmThread(U32 action) { PlayerData::ActionAnimation &anim = mDataBlock->actionList[action]; if (anim.sequence != -1 && anim.sequence != mShapeInstance->getSequence(mArmAnimation.thread)) { mShapeInstance->setSequence(mArmAnimation.thread,anim.sequence,0); mArmAnimation.action = action; setMaskBits(ActionMask); return true; } return false; } //---------------------------------------------------------------------------- bool Player::setActionThread(const char* sequence,bool hold,bool wait,bool fsp) { if (anim_clip_flags & ANIM_OVERRIDDEN) return false; for (U32 i = 1; i < mDataBlock->actionCount; i++) { PlayerData::ActionAnimation &anim = mDataBlock->actionList[i]; if (!dStricmp(anim.name,sequence)) { setActionThread(i,true,hold,wait,fsp); setMaskBits(ActionMask); return true; } } return false; } void Player::setActionThread(U32 action,bool forward,bool hold,bool wait,bool fsp, bool forceSet) { if (!mDataBlock || !mDataBlock->actionCount || (mActionAnimation.action == action && mActionAnimation.forward == forward && !forceSet)) return; if (action >= PlayerData::NumActionAnims) { Con::errorf("Player::setActionThread(%d): Player action out of range", action); return; } if (isClientObject()) { mark_idle = (action == PlayerData::RootAnim); idle_timer = (mark_idle) ? 0.0f : -1.0f; } PlayerData::ActionAnimation &anim = mDataBlock->actionList[action]; if (anim.sequence != -1) { U32 lastAction = mActionAnimation.action; mActionAnimation.action = action; mActionAnimation.forward = forward; mActionAnimation.firstPerson = fsp; mActionAnimation.holdAtEnd = hold; mActionAnimation.waitForEnd = hold? true: wait; mActionAnimation.animateOnServer = fsp; mActionAnimation.atEnd = false; mActionAnimation.delayTicks = (S32)sNewAnimationTickTime; mActionAnimation.atEnd = false; if (sUseAnimationTransitions && (action != PlayerData::LandAnim || !(mDataBlock->landSequenceTime > 0.0f && !mDataBlock->transitionToLand)) && (isGhost()/* || mActionAnimation.animateOnServer*/)) { // The transition code needs the timeScale to be set in the // right direction to know which way to go. F32 transTime = sAnimationTransitionTime; if (mDataBlock && mDataBlock->isJumpAction(action)) transTime = 0.15f; F32 timeScale = mActionAnimation.forward ? 1.0f : -1.0f; if (mDataBlock && mDataBlock->isJumpAction(action)) timeScale *= 1.5f; mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale); S32 seq = anim.sequence; S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action); if (imageBasedSeq != -1) seq = imageBasedSeq; // If we're transitioning into the same sequence (an action may use the // same sequence as a previous action) then we want to start at the same // position. F32 pos = mActionAnimation.forward ? 0.0f : 1.0f; PlayerData::ActionAnimation &lastAnim = mDataBlock->actionList[lastAction]; if (lastAnim.sequence == anim.sequence) { pos = mShapeInstance->getPos(mActionAnimation.thread); } mShapeInstance->transitionToSequence(mActionAnimation.thread,seq, pos, transTime, true); } else { S32 seq = anim.sequence; S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action); if (imageBasedSeq != -1) seq = imageBasedSeq; mShapeInstance->setSequence(mActionAnimation.thread,seq, mActionAnimation.forward ? 0.0f : 1.0f); } } } void Player::updateActionThread() { PROFILE_START(UpdateActionThread); // Select an action animation sequence, this assumes that // this function is called once per tick. if(mActionAnimation.action != PlayerData::NullAnimation) { if (mActionAnimation.forward) mActionAnimation.atEnd = mShapeInstance->getPos(mActionAnimation.thread) == 1; else mActionAnimation.atEnd = mShapeInstance->getPos(mActionAnimation.thread) == 0; } // Only need to deal with triggers on the client if( isGhost() ) { bool triggeredLeft = false; bool triggeredRight = false; F32 offset = 0.0f; if( mShapeInstance->getTriggerState( 1 ) ) { triggeredLeft = true; offset = -mDataBlock->decalOffset * getScale().x; } else if(mShapeInstance->getTriggerState( 2 ) ) { triggeredRight = true; offset = mDataBlock->decalOffset * getScale().x; } process_client_triggers(triggeredLeft, triggeredRight); if ((triggeredLeft || triggeredRight) && !noFootfallFX) { Point3F rot, pos; RayInfo rInfo; MatrixF mat = getRenderTransform(); mat.getColumn( 1, &rot ); mat.mulP( Point3F( offset, 0.0f, 0.0f), &pos ); if( gClientContainer.castRay( Point3F( pos.x, pos.y, pos.z + 0.01f ), Point3F( pos.x, pos.y, pos.z - 2.0f ), STATIC_COLLISION_TYPEMASK | VehicleObjectType, &rInfo ) ) { Material* material = ( rInfo.material ? dynamic_cast< Material* >( rInfo.material->getMaterial() ) : 0 ); // Put footprints on surface, if appropriate for material. if( material && material->mShowFootprints && mDataBlock->decalData && !footfallDecalOverride ) { Point3F normal; Point3F tangent; mObjToWorld.getColumn( 0, &tangent ); mObjToWorld.getColumn( 2, &normal ); gDecalManager->addDecal( rInfo.point, normal, tangent, mDataBlock->decalData, getScale().y ); } // Emit footpuffs. if (!footfallDustOverride && rInfo.t <= 0.5f && mWaterCoverage == 0.0f && material && material->mShowDust ) { // New emitter every time for visibility reasons ParticleEmitter * emitter = new ParticleEmitter; emitter->onNewDataBlock( mDataBlock->footPuffEmitter, false ); LinearColorF colorList[ ParticleData::PDC_NUM_KEYS]; for( U32 x = 0; x < getMin( Material::NUM_EFFECT_COLOR_STAGES, ParticleData::PDC_NUM_KEYS ); ++ x ) colorList[ x ].set( material->mEffectColor[ x ].red, material->mEffectColor[ x ].green, material->mEffectColor[ x ].blue, material->mEffectColor[ x ].alpha ); for( U32 x = Material::NUM_EFFECT_COLOR_STAGES; x < ParticleData::PDC_NUM_KEYS; ++ x ) colorList[ x ].set( 1.0, 1.0, 1.0, 0.0 ); emitter->setColors( colorList ); if( !emitter->registerObject() ) { Con::warnf( ConsoleLogEntry::General, "Could not register emitter for particle of class: %s", mDataBlock->getName() ); delete emitter; emitter = NULL; } else { emitter->emitParticles( pos, Point3F( 0.0, 0.0, 1.0 ), mDataBlock->footPuffRadius, Point3F( 0, 0, 0 ), mDataBlock->footPuffNumParts ); emitter->deleteWhenEmpty(); } } // Play footstep sound. if (footfallSoundOverride <= 0) playFootstepSound( triggeredLeft, material, rInfo.object ); } } } // Mount pending variable puts a hold on the delayTicks below so players don't // inadvertently stand up because their mount has not come over yet. if (mMountPending) mMountPending = (isMounted() ? 0 : (mMountPending - 1)); if ((mActionAnimation.action == PlayerData::NullAnimation) || ((!mActionAnimation.waitForEnd || mActionAnimation.atEnd) && (!mActionAnimation.holdAtEnd && (mActionAnimation.delayTicks -= !mMountPending) <= 0))) { //The scripting language will get a call back when a script animation has finished... // example: When the chat menu animations are done playing... if ( isServerObject() && mActionAnimation.action >= PlayerData::NumTableActionAnims ) mDataBlock->animationDone_callback( this ); pickActionAnimation(); } // prevent scaling of AFX picked actions if ( (mActionAnimation.action != PlayerData::LandAnim) && (mActionAnimation.action != PlayerData::NullAnimation) && !(anim_clip_flags & ANIM_OVERRIDDEN)) { // Update action animation time scale to match ground velocity PlayerData::ActionAnimation &anim = mDataBlock->actionList[mActionAnimation.action]; F32 scale = 1; if (anim.velocityScale && anim.speed) { VectorF vel; mWorldToObj.mulV(mVelocity,&vel); scale = mFabs(mDot(vel, anim.dir) / anim.speed); if (scale > mDataBlock->maxTimeScale) scale = mDataBlock->maxTimeScale; } mShapeInstance->setTimeScale(mActionAnimation.thread, mActionAnimation.forward? scale: -scale); } PROFILE_END(); } void Player::pickBestMoveAction(U32 startAnim, U32 endAnim, U32 * action, bool * forward) const { *action = startAnim; *forward = false; VectorF vel; mWorldToObj.mulV(mVelocity,&vel); if (vel.lenSquared() > 0.01f) { // Bias the velocity towards picking the forward/backward anims over // the sideways ones to prevent oscillation between anims. vel *= VectorF(0.5f, 1.0f, 0.5f); // Pick animation that is the best fit for our current (local) velocity. // Assumes that the root (stationary) animation is at startAnim. F32 curMax = -0.1f; for (U32 i = startAnim+1; i <= endAnim; i++) { const PlayerData::ActionAnimation &anim = mDataBlock->actionList[i]; if (anim.sequence != -1 && anim.speed) { F32 d = mDot(vel, anim.dir); if (d > curMax) { curMax = d; *action = i; *forward = true; } else { // Check if reversing this animation would fit (bias against this // so that when moving right, the real right anim is still chosen, // but if not present, the reversed left anim will be used instead) d *= -0.75f; if (d > curMax) { curMax = d; *action = i; *forward = false; } } } } } } void Player::pickActionAnimation() { // Only select animations in our normal move state. if (mState != MoveState || mDamageState != Enabled) return; if (isMounted() || mMountPending) { // Go into root position unless something was set explicitly // from a script. if (mActionAnimation.action != PlayerData::RootAnim && mActionAnimation.action < PlayerData::NumTableActionAnims) setActionThread(PlayerData::RootAnim,true,false,false); return; } bool forward = true; U32 action = PlayerData::RootAnim; bool fsp = false; // Jetting overrides the fall animation condition if (mJetting) { // Play the jetting animation action = PlayerData::JetAnim; } else if (mFalling) { // Not in contact with any surface and falling action = PlayerData::FallAnim; } else if ( mSwimming ) { pickBestMoveAction(PlayerData::SwimRootAnim, PlayerData::SwimRightAnim, &action, &forward); } else if ( mPose == StandPose ) { if (mContactTimer >= sContactTickTime) { // Nothing under our feet action = PlayerData::RootAnim; } else { // Our feet are on something pickBestMoveAction(PlayerData::RootAnim, PlayerData::SideRightAnim, &action, &forward); } } else if ( mPose == CrouchPose ) { pickBestMoveAction(PlayerData::CrouchRootAnim, PlayerData::CrouchRightAnim, &action, &forward); } else if ( mPose == PronePose ) { pickBestMoveAction(PlayerData::ProneRootAnim, PlayerData::ProneBackwardAnim, &action, &forward); } else if ( mPose == SprintPose ) { pickBestMoveAction(PlayerData::SprintRootAnim, PlayerData::SprintRightAnim, &action, &forward); } setActionThread(action,forward,false,false,fsp); } void Player::onImage(U32 imageSlot, bool unmount) { // Update 3rd person sequences based on images used. Start be getting a // list of all possible image prefix sequences. String prefixPaths[ShapeBase::MaxMountedImages]; buildImagePrefixPaths(prefixPaths); // Clear out any previous image state animation if (mImageStateThread) { mShapeInstance->destroyThread(mImageStateThread); mImageStateThread = 0; } // Attempt to update the action thread U32 action = mActionAnimation.action; if (action != PlayerData::NullAnimation) { String actionSeq = mDataBlock->actionList[action].name; if (actionSeq.isNotEmpty()) { S32 seqIndex = mDataBlock->actionList[action].sequence; S32 prefixIndex = findPrefixSequence(prefixPaths, actionSeq); if (prefixIndex != -1) { seqIndex = prefixIndex; } // Only change the sequence if it isn't already playing. if (seqIndex != mShapeInstance->getSequence(mActionAnimation.thread)) { F32 pos = mShapeInstance->getPos(mActionAnimation.thread); mShapeInstance->setSequence(mActionAnimation.thread, seqIndex, pos); } } } // Attempt to update the arm thread U32 armAction = getArmAction(); if (armAction != PlayerData::NullAnimation) { String armSeq = mDataBlock->actionList[armAction].name; if (armSeq.isNotEmpty()) { S32 seqIndex = mDataBlock->actionList[armAction].sequence; S32 prefixIndex = findPrefixSequence(prefixPaths, armSeq); if (prefixIndex != -1) { seqIndex = prefixIndex; } // Only change the sequence if it isn't already playing. if (seqIndex != mShapeInstance->getSequence(mArmAnimation.thread)) { F32 pos = mShapeInstance->getPos(mArmAnimation.thread); mShapeInstance->setSequence(mArmAnimation.thread, seqIndex, pos); } } } // Attempt to update the head threads if (mHeadVThread) { TSShape const* shape = mShapeInstance->getShape(); S32 seqIndex = shape->findSequence("head"); S32 prefixIndex = findPrefixSequence(prefixPaths, "head"); if (prefixIndex != -1) { seqIndex = prefixIndex; } // Only change the sequence if it isn't already playing. if (seqIndex != mShapeInstance->getSequence(mHeadVThread)) { F32 pos = mShapeInstance->getPos(mHeadVThread); mShapeInstance->setSequence(mHeadVThread, seqIndex, pos); } } if (mHeadHThread) { TSShape const* shape = mShapeInstance->getShape(); S32 seqIndex = shape->findSequence("headside"); S32 prefixIndex = findPrefixSequence(prefixPaths, "headside"); if (prefixIndex != -1) { seqIndex = prefixIndex; } // Only change the sequence if it isn't already playing. if (seqIndex != mShapeInstance->getSequence(mHeadHThread)) { F32 pos = mShapeInstance->getPos(mHeadHThread); mShapeInstance->setSequence(mHeadHThread, seqIndex, pos); } } } void Player::buildImagePrefixPaths(String* prefixPaths) { // We begin obtaining the anim prefix for each image. String prefix[ShapeBase::MaxMountedImages]; for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { MountedImage& image = mMountedImageList[i]; if (image.dataBlock && image.dataBlock->imageAnimPrefix && image.dataBlock->imageAnimPrefix[0]) { prefix[i] = String(image.dataBlock->imageAnimPrefix); } } // Build out the full prefix names we will be searching for. S32 counter = ShapeBase::MaxMountedImages-1; for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { // Only build out the prefix path for images that have a defined prefix. if (prefix[i].isNotEmpty()) { bool start = true; for (U32 j=0; j<=i; ++j) { if (prefix[j].isNotEmpty()) { if (!start) { prefixPaths[counter] += "_"; } else { start = false; } prefixPaths[counter] += prefix[j]; } } } -- counter; } } S32 Player::findPrefixSequence(String* prefixPaths, const String& baseSeq) { // Go through the prefix list. If we find a match then return the sequence // index. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { if (prefixPaths[i].isNotEmpty()) { String seq = prefixPaths[i] + "_" + baseSeq; S32 seqIndex = mShapeInstance->getShape()->findSequence(seq); if (seqIndex != -1) { return seqIndex; } } } return -1; } S32 Player::convertActionToImagePrefix(U32 action) { String prefixPaths[ShapeBase::MaxMountedImages]; buildImagePrefixPaths(prefixPaths); if (action != PlayerData::NullAnimation) { String actionSeq; S32 seq = -1; // We'll first attempt to find the action sequence by name // as defined within the action list. actionSeq = mDataBlock->actionList[action].name; if (actionSeq.isNotEmpty()) { seq = findPrefixSequence(prefixPaths, actionSeq); } if (seq == -1) { // Couldn't find a valid sequence. If this is a sprint action // then we also need to search through the standard movement // sequences. if (action >= PlayerData::SprintRootAnim && action <= PlayerData::SprintRightAnim) { U32 standardAction = action - PlayerData::SprintRootAnim; actionSeq = mDataBlock->actionList[standardAction].name; if (actionSeq.isNotEmpty()) { seq = findPrefixSequence(prefixPaths, actionSeq); } } } return seq; } return -1; } void Player::onImageRecoil( U32, ShapeBaseImageData::StateData::RecoilState state ) { if ( mRecoilThread ) { if ( state != ShapeBaseImageData::StateData::NoRecoil ) { S32 stateIndex = state - ShapeBaseImageData::StateData::LightRecoil; if ( mDataBlock->recoilSequence[stateIndex] != -1 ) { mShapeInstance->setSequence( mRecoilThread, mDataBlock->recoilSequence[stateIndex], 0 ); mShapeInstance->setTimeScale( mRecoilThread, 1 ); } } } } void Player::onImageStateAnimation(U32 imageSlot, const char* seqName, bool direction, bool scaleToState, F32 stateTimeOutValue) { if (mDataBlock->allowImageStateAnimation && isGhost()) { MountedImage& image = mMountedImageList[imageSlot]; // Just as with onImageAnimThreadChange we're going to apply various prefixes to determine the final sequence to use. // Here is the order: // imageBasePrefix_scriptPrefix_baseAnimName // imageBasePrefix_baseAnimName // scriptPrefix_baseAnimName // baseAnimName // Collect the prefixes const char* imageBasePrefix = ""; bool hasImageBasePrefix = image.dataBlock && image.dataBlock->imageAnimPrefix && image.dataBlock->imageAnimPrefix[0]; if (hasImageBasePrefix) imageBasePrefix = image.dataBlock->imageAnimPrefix; const char* scriptPrefix = getImageScriptAnimPrefix(imageSlot).getString(); bool hasScriptPrefix = scriptPrefix && scriptPrefix[0]; S32 seqIndex = mShapeInstance->getShape()->findSequence(seqName); // Find the final sequence based on the prefix combinations if (hasImageBasePrefix || hasScriptPrefix) { bool found = false; String baseSeqName(seqName); if (!found && hasImageBasePrefix && hasScriptPrefix) { String comboSeqName = String(imageBasePrefix) + String("_") + String(scriptPrefix) + String("_") + baseSeqName; S32 index = mShapeInstance->getShape()->findSequence(comboSeqName); if (index != -1) { seqIndex = index; found = true; } } if (!found && hasImageBasePrefix) { String imgSeqName = String(imageBasePrefix) + String("_") + baseSeqName; S32 index = mShapeInstance->getShape()->findSequence(imgSeqName); if (index != -1) { seqIndex = index; found = true; } } if (!found && hasScriptPrefix) { String scriptSeqName = String(scriptPrefix) + String("_") + baseSeqName; S32 index = mShapeInstance->getShape()->findSequence(scriptSeqName); if (index != -1) { seqIndex = index; found = true; } } } if (seqIndex != -1) { if (!mImageStateThread) { mImageStateThread = mShapeInstance->addThread(); } mShapeInstance->setSequence( mImageStateThread, seqIndex, 0 ); F32 timeScale = (scaleToState && stateTimeOutValue) ? mShapeInstance->getDuration(mImageStateThread) / stateTimeOutValue : 1.0f; mShapeInstance->setTimeScale( mImageStateThread, direction ? timeScale : -timeScale ); } } } const char* Player::getImageAnimPrefix(U32 imageSlot, S32 imageShapeIndex) { if (!mDataBlock) return ""; switch (imageShapeIndex) { case ShapeBaseImageData::StandardImageShape: { return mDataBlock->imageAnimPrefix; } case ShapeBaseImageData::FirstPersonImageShape: { return mDataBlock->imageAnimPrefixFP; } default: { return ""; } } } void Player::onImageAnimThreadChange(U32 imageSlot, S32 imageShapeIndex, ShapeBaseImageData::StateData* lastState, const char* anim, F32 pos, F32 timeScale, bool reset) { if (!mShapeFPInstance[imageSlot] || !mShapeFPAnimThread[imageSlot]) return; MountedImage& image = mMountedImageList[imageSlot]; ShapeBaseImageData::StateData& stateData = *image.state; if (reset) { // Reset cyclic sequences back to the first frame to turn it off // (the first key frame should be it's off state). if (mShapeFPAnimThread[imageSlot]->getSequence()->isCyclic() && (stateData.sequenceNeverTransition || !(stateData.sequenceTransitionIn || (lastState && lastState->sequenceTransitionOut))) ) { mShapeFPInstance[imageSlot]->setPos(mShapeFPAnimThread[imageSlot],0); mShapeFPInstance[imageSlot]->setTimeScale(mShapeFPAnimThread[imageSlot],0); } return; } // Just as with ShapeBase::udpateAnimThread we're going to apply various prefixes to determine the final sequence to use. // Here is the order: // imageBasePrefix_scriptPrefix_baseAnimName // imageBasePrefix_baseAnimName // scriptPrefix_baseAnimName // baseAnimName // Collect the prefixes const char* imageBasePrefix = ""; bool hasImageBasePrefix = image.dataBlock && image.dataBlock->imageAnimPrefixFP && image.dataBlock->imageAnimPrefixFP[0]; if (hasImageBasePrefix) imageBasePrefix = image.dataBlock->imageAnimPrefixFP; const char* scriptPrefix = getImageScriptAnimPrefix(imageSlot).getString(); bool hasScriptPrefix = scriptPrefix && scriptPrefix[0]; S32 seqIndex = mShapeFPInstance[imageSlot]->getShape()->findSequence(anim); // Find the final sequence based on the prefix combinations if (hasImageBasePrefix || hasScriptPrefix) { bool found = false; String baseSeqName(anim); if (!found && hasImageBasePrefix && hasScriptPrefix) { String seqName = String(imageBasePrefix) + String("_") + String(scriptPrefix) + String("_") + baseSeqName; S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName); if (index != -1) { seqIndex = index; found = true; } } if (!found && hasImageBasePrefix) { String seqName = String(imageBasePrefix) + String("_") + baseSeqName; S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName); if (index != -1) { seqIndex = index; found = true; } } if (!found && hasScriptPrefix) { String seqName = String(scriptPrefix) + String("_") + baseSeqName; S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName); if (index != -1) { seqIndex = index; found = true; } } } if (seqIndex != -1) { if (!lastState) { // No lastState indicates that we are just switching animation sequences, not states. Transition into this new sequence, but only // if it is different than what we're currently playing. S32 prevSeq = -1; if (mShapeFPAnimThread[imageSlot]->hasSequence()) { prevSeq = mShapeFPInstance[imageSlot]->getSequence(mShapeFPAnimThread[imageSlot]); } if (seqIndex != prevSeq) { mShapeFPInstance[imageSlot]->transitionToSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos, image.dataBlock->scriptAnimTransitionTime, true); } } else if (!stateData.sequenceNeverTransition && stateData.sequenceTransitionTime && (stateData.sequenceTransitionIn || (lastState && lastState->sequenceTransitionOut)) ) { mShapeFPInstance[imageSlot]->transitionToSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos, stateData.sequenceTransitionTime, true); } else { mShapeFPInstance[imageSlot]->setSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos); } mShapeFPInstance[imageSlot]->setTimeScale(mShapeFPAnimThread[imageSlot], timeScale); } } void Player::onImageAnimThreadUpdate(U32 imageSlot, S32 imageShapeIndex, F32 dt) { if (!mShapeFPInstance[imageSlot]) return; if (mShapeFPAmbientThread[imageSlot] && mShapeFPAmbientThread[imageSlot]->hasSequence()) { mShapeFPInstance[imageSlot]->advanceTime(dt,mShapeFPAmbientThread[imageSlot]); } if (mShapeFPAnimThread[imageSlot] && mShapeFPAnimThread[imageSlot]->hasSequence()) { mShapeFPInstance[imageSlot]->advanceTime(dt,mShapeFPAnimThread[imageSlot]); } } void Player::onUnmount( SceneObject *obj, S32 node ) { // Reset back to root position during dismount. setActionThread(PlayerData::RootAnim,true,false,false); // Re-orient the player straight up Point3F pos,vec; getTransform().getColumn(1,&vec); getTransform().getColumn(3,&pos); Point3F rot(0.0f,0.0f,-mAtan2(-vec.x,vec.y)); setPosition(pos,rot); // Parent function will call script Parent::onUnmount( obj, node ); } void Player::unmount() { // Reset back to root position during dismount. This copies what is // done on the server and corrects the fact that the RootAnim change // is not sent across to the client using the standard ActionMask. setActionThread(PlayerData::RootAnim,true,false,false); Parent::unmount(); } //---------------------------------------------------------------------------- void Player::updateAnimation(F32 dt) { // If dead then remove any image animations if ((mDamageState == Disabled || mDamageState == Destroyed) && mImageStateThread) { // Remove the image state animation mShapeInstance->destroyThread(mImageStateThread); mImageStateThread = 0; } if ((isGhost() || mActionAnimation.animateOnServer) && mActionAnimation.thread) mShapeInstance->advanceTime(dt,mActionAnimation.thread); if (mRecoilThread) mShapeInstance->advanceTime(dt,mRecoilThread); if (mImageStateThread) mShapeInstance->advanceTime(dt,mImageStateThread); // update any active blend clips if (isGhost()) for (S32 i = 0; i < blend_clips.size(); i++) mShapeInstance->advanceTime(dt, blend_clips[i].thread); // If we are the client's player on this machine, then we need // to make sure the transforms are up to date as they are used // to setup the camera. if (isGhost()) { if (getControllingClient()) { updateAnimationTree(isFirstPerson()); mShapeInstance->animate(); } else { updateAnimationTree(false); // This addition forces recently visible players to animate their // skeleton now rather than in pre-render so that constrained effects // get up-to-date node transforms. if (didRenderLastRender()) mShapeInstance->animate(); } } } void Player::updateAnimationTree(bool firstPerson) { S32 mode = 0; if (firstPerson) { if (mActionAnimation.firstPerson) mode = 0; // TSShapeInstance::MaskNodeRotation; // TSShapeInstance::MaskNodePosX | // TSShapeInstance::MaskNodePosY; else mode = TSShapeInstance::MaskNodeAllButBlend; } for (U32 i = 0; i < PlayerData::NumSpineNodes; i++) if (mDataBlock->spineNode[i] != -1) mShapeInstance->setNodeAnimationState(mDataBlock->spineNode[i],mode); } //---------------------------------------------------------------------------- bool Player::step(Point3F *pos,F32 *maxStep,F32 time) { const Point3F& scale = getScale(); Box3F box; VectorF offset = mVelocity * time; box.minExtents = mObjBox.minExtents + offset + *pos; box.maxExtents = mObjBox.maxExtents + offset + *pos; box.maxExtents.z += mDataBlock->maxStepHeight * scale.z + sMinFaceDistance; SphereF sphere; sphere.center = (box.minExtents + box.maxExtents) * 0.5f; VectorF bv = box.maxExtents - sphere.center; sphere.radius = bv.len(); ClippedPolyList polyList; polyList.mPlaneList.clear(); polyList.mNormal.set(0.0f, 0.0f, 0.0f); polyList.mPlaneList.setSize(6); polyList.mPlaneList[0].set(box.minExtents,VectorF(-1.0f, 0.0f, 0.0f)); polyList.mPlaneList[1].set(box.maxExtents,VectorF(0.0f, 1.0f, 0.0f)); polyList.mPlaneList[2].set(box.maxExtents,VectorF(1.0f, 0.0f, 0.0f)); polyList.mPlaneList[3].set(box.minExtents,VectorF(0.0f, -1.0f, 0.0f)); polyList.mPlaneList[4].set(box.minExtents,VectorF(0.0f, 0.0f, -1.0f)); polyList.mPlaneList[5].set(box.maxExtents,VectorF(0.0f, 0.0f, 1.0f)); CollisionWorkingList& rList = mConvex.getWorkingList(); CollisionWorkingList* pList = rList.wLink.mNext; while (pList != &rList) { Convex* pConvex = pList->mConvex; // Alright, here's the deal... a polysoup mesh really needs to be // designed with stepping in mind. If there are too many smallish polygons // the stepping system here gets confused and allows you to run up walls // or on the edges/seams of meshes. TSStatic *st = dynamic_cast<TSStatic *> (pConvex->getObject()); bool skip = false; if (st && !st->allowPlayerStep()) skip = true; if ((pConvex->getObject()->getTypeMask() & StaticObjectType) != 0 && !skip) { Box3F convexBox = pConvex->getBoundingBox(); if (box.isOverlapped(convexBox)) pConvex->getPolyList(&polyList); } pList = pList->wLink.mNext; } // Find max step height F32 stepHeight = pos->z - sMinFaceDistance; U32* vp = polyList.mIndexList.begin(); U32* ep = polyList.mIndexList.end(); for (; vp != ep; vp++) { F32 h = polyList.mVertexList[*vp].point.z + sMinFaceDistance; if (h > stepHeight) stepHeight = h; } F32 step = stepHeight - pos->z; if (stepHeight > pos->z && step < *maxStep) { // Go ahead and step pos->z = stepHeight; *maxStep -= step; return true; } return false; } // PATHSHAPE // This Function does a ray cast down to see if a pathshape object is below // If so, it will attempt to attach to it. void Player::updateAttachment(){ Point3F rot, pos; RayInfo rInfo; MatrixF mat = getTransform(); mat.getColumn(3, &pos); if (gServerContainer.castRay(Point3F(pos.x, pos.y, pos.z + 0.1f), Point3F(pos.x, pos.y, pos.z - 1.0f ), PathShapeObjectType, &rInfo)) { if( rInfo.object->getTypeMask() & PathShapeObjectType) //Ramen { if (getParent() == NULL) { // ONLY do this if we are not parented //Con::printf("I'm on a pathshape object. Going to attempt attachment."); ShapeBase* col = static_cast<ShapeBase*>(rInfo.object); if (!isGhost()) { this->attachToParent(col); } } } else { //Con::printf("object %i",rInfo.object->getId()); } } else { if (getParent() !=NULL) { clearProcessAfter(); attachToParent(NULL); } } } // PATHSHAPE END //---------------------------------------------------------------------------- inline Point3F createInterpPos(const Point3F& s, const Point3F& e, const F32 t, const F32 d) { Point3F ret; ret.interpolate(s, e, t/d); return ret; } Point3F Player::_move( const F32 travelTime, Collision *outCol ) { // Try and move to new pos F32 totalMotion = 0.0f; // TODO: not used? //F32 initialSpeed = mVelocity.len(); Point3F start; Point3F initialPosition; getTransform().getColumn(3,&start); initialPosition = start; static CollisionList collisionList; static CollisionList physZoneCollisionList; collisionList.clear(); physZoneCollisionList.clear(); MatrixF collisionMatrix(true); collisionMatrix.setColumn(3, start); VectorF firstNormal(0.0f, 0.0f, 0.0f); F32 maxStep = mDataBlock->maxStepHeight; F32 time = travelTime; U32 count = 0; const Point3F& scale = getScale(); static Polyhedron sBoxPolyhedron; static ExtrudedPolyList sExtrudedPolyList; static ExtrudedPolyList sPhysZonePolyList; for (; count < sMoveRetryCount; count++) { F32 speed = mVelocity.len(); if (!speed && !mDeath.haveVelocity()) break; Point3F end = start + mVelocity * time; if (mDeath.haveVelocity()) { // Add in death movement- VectorF deathVel = mDeath.getPosAdd(); VectorF resVel; getTransform().mulV(deathVel, & resVel); end += resVel; } Point3F distance = end - start; if (mFabs(distance.x) < mScaledBox.len_x() && mFabs(distance.y) < mScaledBox.len_y() && mFabs(distance.z) < mScaledBox.len_z()) { // We can potentially early out of this. If there are no polys in the clipped polylist at our // end position, then we can bail, and just set start = end; Box3F wBox = mScaledBox; wBox.minExtents += end; wBox.maxExtents += end; static EarlyOutPolyList eaPolyList; eaPolyList.clear(); eaPolyList.mNormal.set(0.0f, 0.0f, 0.0f); eaPolyList.mPlaneList.clear(); eaPolyList.mPlaneList.setSize(6); eaPolyList.mPlaneList[0].set(wBox.minExtents,VectorF(-1.0f, 0.0f, 0.0f)); eaPolyList.mPlaneList[1].set(wBox.maxExtents,VectorF(0.0f, 1.0f, 0.0f)); eaPolyList.mPlaneList[2].set(wBox.maxExtents,VectorF(1.0f, 0.0f, 0.0f)); eaPolyList.mPlaneList[3].set(wBox.minExtents,VectorF(0.0f, -1.0f, 0.0f)); eaPolyList.mPlaneList[4].set(wBox.minExtents,VectorF(0.0f, 0.0f, -1.0f)); eaPolyList.mPlaneList[5].set(wBox.maxExtents,VectorF(0.0f, 0.0f, 1.0f)); // Build list from convex states here... CollisionWorkingList& rList = mConvex.getWorkingList(); CollisionWorkingList* pList = rList.wLink.mNext; while (pList != &rList) { Convex* pConvex = pList->mConvex; if (pConvex->getObject()->getTypeMask() & sCollisionMoveMask) { Box3F convexBox = pConvex->getBoundingBox(); if (wBox.isOverlapped(convexBox)) { // No need to separate out the physical zones here, we want those // to cause a fallthrough as well... pConvex->getPolyList(&eaPolyList); } } pList = pList->wLink.mNext; } if (eaPolyList.isEmpty()) { totalMotion += (end - start).len(); start = end; break; } } collisionMatrix.setColumn(3, start); sBoxPolyhedron.buildBox(collisionMatrix, mScaledBox, true); // Setup the bounding box for the extrudedPolyList Box3F plistBox = mScaledBox; collisionMatrix.mul(plistBox); Point3F oldMin = plistBox.minExtents; Point3F oldMax = plistBox.maxExtents; plistBox.minExtents.setMin(oldMin + (mVelocity * time) - Point3F(0.1f, 0.1f, 0.1f)); plistBox.maxExtents.setMax(oldMax + (mVelocity * time) + Point3F(0.1f, 0.1f, 0.1f)); // Build extruded polyList... VectorF vector = end - start; sExtrudedPolyList.extrude(sBoxPolyhedron,vector); sExtrudedPolyList.setVelocity(mVelocity); sExtrudedPolyList.setCollisionList(&collisionList); sPhysZonePolyList.extrude(sBoxPolyhedron,vector); sPhysZonePolyList.setVelocity(mVelocity); sPhysZonePolyList.setCollisionList(&physZoneCollisionList); // Build list from convex states here... CollisionWorkingList& rList = mConvex.getWorkingList(); CollisionWorkingList* pList = rList.wLink.mNext; while (pList != &rList) { Convex* pConvex = pList->mConvex; if (pConvex->getObject()->getTypeMask() & sCollisionMoveMask) { Box3F convexBox = pConvex->getBoundingBox(); if (plistBox.isOverlapped(convexBox)) { if (pConvex->getObject()->getTypeMask() & PhysicalZoneObjectType) pConvex->getPolyList(&sPhysZonePolyList); else pConvex->getPolyList(&sExtrudedPolyList); } } pList = pList->wLink.mNext; } // Take into account any physical zones... for (U32 j = 0; j < physZoneCollisionList.getCount(); j++) { AssertFatal(dynamic_cast<PhysicalZone*>(physZoneCollisionList[j].object), "Bad phys zone!"); const PhysicalZone* pZone = (PhysicalZone*)physZoneCollisionList[j].object; if (pZone->isActive()) mVelocity *= pZone->getVelocityMod(); } if (collisionList.getCount() != 0 && collisionList.getTime() < 1.0f) { // Set to collision point F32 velLen = mVelocity.len(); F32 dt = time * getMin(collisionList.getTime(), 1.0f); start += mVelocity * dt; time -= dt; totalMotion += velLen * dt; bool wasFalling = mFalling; mFalling = false; // Back off... if ( velLen > 0.f ) { F32 newT = getMin(0.01f / velLen, dt); start -= mVelocity * newT; totalMotion -= velLen * newT; } // Try stepping if there is a vertical surface if (collisionList.getMaxHeight() < start.z + mDataBlock->maxStepHeight * scale.z) { bool stepped = false; for (U32 c = 0; c < collisionList.getCount(); c++) { const Collision& cp = collisionList[c]; // if (mFabs(mDot(cp.normal,VectorF(0,0,1))) < sVerticalStepDot) // Dot with (0,0,1) just extracts Z component [lh]- if (mFabs(cp.normal.z) < sVerticalStepDot) { stepped = step(&start,&maxStep,time); break; } } if (stepped) { continue; } } // Pick the surface most parallel to the face that was hit. const Collision *collision = &collisionList[0]; const Collision *cp = collision + 1; const Collision *ep = collision + collisionList.getCount(); for (; cp != ep; cp++) { if (cp->faceDot > collision->faceDot) collision = cp; } F32 bd = _doCollisionImpact( collision, wasFalling ); // Copy this collision out so // we can use it to do impacts // and query collision. *outCol = *collision; if (isServerObject() && bd > 6.8f && collision->normal.z > 0.7f) { fx_s_triggers |= PLAYER_LANDING_S_TRIGGER; setMaskBits(TriggerMask); } // Subtract out velocity VectorF dv = collision->normal * (bd + sNormalElasticity); mVelocity += dv; if (count == 0) { firstNormal = collision->normal; } else { if (count == 1) { // Re-orient velocity along the crease. if (mDot(dv,firstNormal) < 0.0f && mDot(collision->normal,firstNormal) < 0.0f) { VectorF nv; mCross(collision->normal,firstNormal,&nv); F32 nvl = nv.len(); if (nvl) { if (mDot(nv,mVelocity) < 0.0f) nvl = -nvl; nv *= mVelocity.len() / nvl; mVelocity = nv; } } } } } else { totalMotion += (end - start).len(); start = end; break; } } if (count == sMoveRetryCount) { // Failed to move start = initialPosition; mVelocity.set(0.0f, 0.0f, 0.0f); } return start; } F32 Player::_doCollisionImpact( const Collision *collision, bool fallingCollision) { F32 bd = -mDot( mVelocity, collision->normal); // shake camera on ground impact if( bd > mDataBlock->groundImpactMinSpeed && isControlObject() ) { F32 ampScale = (bd - mDataBlock->groundImpactMinSpeed) / mDataBlock->minImpactSpeed; CameraShake *groundImpactShake = new CameraShake; groundImpactShake->setDuration( mDataBlock->groundImpactShakeDuration ); groundImpactShake->setFrequency( mDataBlock->groundImpactShakeFreq ); VectorF shakeAmp = mDataBlock->groundImpactShakeAmp * ampScale; groundImpactShake->setAmplitude( shakeAmp ); groundImpactShake->setFalloff( mDataBlock->groundImpactShakeFalloff ); groundImpactShake->init(); gCamFXMgr.addFX( groundImpactShake ); } if ( ((bd > mDataBlock->minImpactSpeed && fallingCollision) || bd > mDataBlock->minLateralImpactSpeed) && !mMountPending ) { if ( !isGhost() ) onImpact( collision->object, collision->normal * bd ); if (mDamageState == Enabled && mState != RecoverState) { // Scale how long we're down for if (mDataBlock->landSequenceTime > 0.0f) { // Recover time is based on the land sequence setState(RecoverState); } else { // Legacy recover system F32 value = (bd - mDataBlock->minImpactSpeed); F32 range = (mDataBlock->minImpactSpeed * 0.9f); U32 recover = mDataBlock->recoverDelay; if (value < range) recover = 1 + S32(mFloor( F32(recover) * value / range) ); //Con::printf("Used %d recover ticks", recover); //Con::printf(" minImpact = %g, this one = %g", mDataBlock->minImpactSpeed, bd); setState(RecoverState, recover); } } } if ( isServerObject() && (bd > (mDataBlock->minImpactSpeed / 3.0f) || bd > (mDataBlock->minLateralImpactSpeed / 3.0f )) ) { mImpactSound = PlayerData::ImpactNormal; setMaskBits(ImpactMask); } return bd; } void Player::_handleCollision( const Collision &collision ) { // Track collisions if ( !isGhost() && collision.object && collision.object != mContactInfo.contactObject ) queueCollision( collision.object, mVelocity - collision.object->getVelocity() ); } bool Player::updatePos(const F32 travelTime) { PROFILE_SCOPE(Player_UpdatePos); getTransform().getColumn(3,&mDelta.posVec); // When mounted to another object, only Z rotation used. if (isMounted()) { mVelocity = mMount.object->getVelocity(); setPosition(Point3F(0.0f, 0.0f, 0.0f), mRot); setMaskBits(MoveMask); return true; } Point3F newPos; Collision col; dMemset( &col, 0, sizeof( col ) ); // DEBUG: //Point3F savedVelocity = mVelocity; if ( mPhysicsRep ) { static CollisionList collisionList; collisionList.clear(); newPos = mPhysicsRep->move( mVelocity * travelTime, collisionList ); bool haveCollisions = false; bool wasFalling = mFalling; if (collisionList.getCount() > 0) { mFalling = false; haveCollisions = true; } if (haveCollisions) { // Pick the collision that most closely matches our direction VectorF velNormal = mVelocity; velNormal.normalizeSafe(); const Collision *collision = &collisionList[0]; F32 collisionDot = mDot(velNormal, collision->normal); const Collision *cp = collision + 1; const Collision *ep = collision + collisionList.getCount(); for (; cp != ep; cp++) { F32 dp = mDot(velNormal, cp->normal); if (dp < collisionDot) { collisionDot = dp; collision = cp; } } _doCollisionImpact( collision, wasFalling ); // Modify our velocity based on collisions for (U32 i=0; i<collisionList.getCount(); ++i) { F32 bd = -mDot( mVelocity, collisionList[i].normal ); VectorF dv = collisionList[i].normal * (bd + sNormalElasticity); mVelocity += dv; } // Store the last collision for use later on. The handle collision // code only expects a single collision object. if (collisionList.getCount() > 0) col = collisionList[collisionList.getCount() - 1]; // We'll handle any player-to-player collision, and the last collision // with other obejct types. for (U32 i=0; i<collisionList.getCount(); ++i) { Collision& colCheck = collisionList[i]; if (colCheck.object) { SceneObject* obj = static_cast<SceneObject*>(col.object); if (obj->getTypeMask() & PlayerObjectType) { _handleCollision( colCheck ); } else { col = colCheck; } } } _handleCollision( col ); } } else { if ( mVelocity.isZero() ) newPos = mDelta.posVec; else newPos = _move( travelTime, &col ); _handleCollision( col ); } // DEBUG: //if ( isClientObject() ) // Con::printf( "(client) vel: %g %g %g", mVelocity.x, mVelocity.y, mVelocity.z ); //else // Con::printf( "(server) vel: %g %g %g", mVelocity.x, mVelocity.y, mVelocity.z ); // Set new position // If on the client, calc delta for backstepping if (isClientObject()) { mDelta.pos = newPos; mDelta.posVec = mDelta.posVec - mDelta.pos; mDelta.dt = 1.0f; } setPosition( newPos, mRot ); setMaskBits( MoveMask ); updateContainer(); if (!isGhost()) { // Collisions are only queued on the server and can be // generated by either updateMove or updatePos notifyCollision(); // Do mission area callbacks on the server as well checkMissionArea(); } // Check the total distance moved. If it is more than 1000th of the velocity, then // we moved a fair amount... //if (totalMotion >= (0.001f * initialSpeed)) return true; //else //return false; } //---------------------------------------------------------------------------- void Player::_findContact( SceneObject **contactObject, VectorF *contactNormal, Vector<SceneObject*> *outOverlapObjects ) { Point3F pos; getTransform().getColumn(3,&pos); Box3F wBox; Point3F exp(0,0,sTractionDistance); wBox.minExtents = pos + mScaledBox.minExtents - exp; wBox.maxExtents.x = pos.x + mScaledBox.maxExtents.x; wBox.maxExtents.y = pos.y + mScaledBox.maxExtents.y; wBox.maxExtents.z = pos.z + mScaledBox.minExtents.z + sTractionDistance; static ClippedPolyList polyList; polyList.clear(); polyList.doConstruct(); polyList.mNormal.set(0.0f, 0.0f, 0.0f); polyList.setInterestNormal(Point3F(0.0f, 0.0f, -1.0f)); polyList.mPlaneList.setSize(6); polyList.mPlaneList[0].setYZ(wBox.minExtents, -1.0f); polyList.mPlaneList[1].setXZ(wBox.maxExtents, 1.0f); polyList.mPlaneList[2].setYZ(wBox.maxExtents, 1.0f); polyList.mPlaneList[3].setXZ(wBox.minExtents, -1.0f); polyList.mPlaneList[4].setXY(wBox.minExtents, -1.0f); polyList.mPlaneList[5].setXY(wBox.maxExtents, 1.0f); Box3F plistBox = wBox; // Expand build box as it will be used to collide with items. // PickupRadius will be at least the size of the box. F32 pd = (F32)mDataBlock->pickupDelta; wBox.minExtents.x -= pd; wBox.minExtents.y -= pd; wBox.maxExtents.x += pd; wBox.maxExtents.y += pd; wBox.maxExtents.z = pos.z + mScaledBox.maxExtents.z; // Build list from convex states here... CollisionWorkingList& rList = mConvex.getWorkingList(); CollisionWorkingList* pList = rList.wLink.mNext; while (pList != &rList) { Convex* pConvex = pList->mConvex; U32 objectMask = pConvex->getObject()->getTypeMask(); if ( ( objectMask & sCollisionMoveMask ) && !( objectMask & PhysicalZoneObjectType ) ) { Box3F convexBox = pConvex->getBoundingBox(); if (plistBox.isOverlapped(convexBox)) pConvex->getPolyList(&polyList); } else outOverlapObjects->push_back( pConvex->getObject() ); pList = pList->wLink.mNext; } if (!polyList.isEmpty()) { // Pick flattest surface F32 bestVd = -1.0f; ClippedPolyList::Poly* poly = polyList.mPolyList.begin(); ClippedPolyList::Poly* end = polyList.mPolyList.end(); for (; poly != end; poly++) { F32 vd = poly->plane.z; // i.e. mDot(Point3F(0,0,1), poly->plane); if (vd > bestVd) { bestVd = vd; *contactObject = poly->object; *contactNormal = poly->plane; } } } } void Player::findContact( bool *run, bool *jump, VectorF *contactNormal ) { SceneObject *contactObject = NULL; Vector<SceneObject*> overlapObjects; if ( mPhysicsRep ) mPhysicsRep->findContact( &contactObject, contactNormal, &overlapObjects ); else _findContact( &contactObject, contactNormal, &overlapObjects ); // Check for triggers, corpses and items. const U32 filterMask = isGhost() ? sClientCollisionContactMask : sServerCollisionContactMask; for ( U32 i=0; i < overlapObjects.size(); i++ ) { SceneObject *obj = overlapObjects[i]; U32 objectMask = obj->getTypeMask(); if ( !( objectMask & filterMask ) ) continue; // Check: triggers, corpses and items... // if (objectMask & TriggerObjectType) { Trigger* pTrigger = static_cast<Trigger*>( obj ); pTrigger->potentialEnterObject(this); } else if (objectMask & CorpseObjectType) { // If we've overlapped the worldbounding boxes, then that's it... if ( getWorldBox().isOverlapped( obj->getWorldBox() ) ) { ShapeBase* col = static_cast<ShapeBase*>( obj ); queueCollision(col,getVelocity() - col->getVelocity()); } } else if (objectMask & ItemObjectType) { // If we've overlapped the worldbounding boxes, then that's it... Item* item = static_cast<Item*>( obj ); if ( getWorldBox().isOverlapped(item->getWorldBox()) && item->getCollisionObject() != this && !item->isHidden() ) queueCollision(item,getVelocity() - item->getVelocity()); } } F32 vd = (*contactNormal).z; *run = vd > mDataBlock->runSurfaceCos; *jump = vd > mDataBlock->jumpSurfaceCos; mContactInfo.clear(); mContactInfo.contacted = contactObject != NULL; mContactInfo.contactObject = contactObject; if ( mContactInfo.contacted ) mContactInfo.contactNormal = *contactNormal; mContactInfo.run = *run; mContactInfo.jump = *jump; } //---------------------------------------------------------------------------- void Player::checkMissionArea() { // Checks to see if the player is in the Mission Area... Point3F pos; MissionArea * obj = MissionArea::getServerObject(); if(!obj) return; const RectI &area = obj->getArea(); getTransform().getColumn(3, &pos); if ((pos.x < area.point.x || pos.x > area.point.x + area.extent.x || pos.y < area.point.y || pos.y > area.point.y + area.extent.y)) { if(mInMissionArea) { mInMissionArea = false; mDataBlock->onLeaveMissionArea_callback( this ); } } else if(!mInMissionArea) { mInMissionArea = true; mDataBlock->onEnterMissionArea_callback( this ); } } //---------------------------------------------------------------------------- bool Player::isDisplacable() const { return true; } Point3F Player::getMomentum() const { return mVelocity * getMass(); } void Player::setMomentum(const Point3F& newMomentum) { Point3F newVelocity = newMomentum / getMass(); mVelocity = newVelocity; } #define LH_HACK 1 // Hack for short-term soln to Training crash - #if LH_HACK static U32 sBalance; bool Player::displaceObject(const Point3F& displacement) { F32 vellen = mVelocity.len(); if (vellen < 0.001f || sBalance > 16) { mVelocity.set(0.0f, 0.0f, 0.0f); return false; } F32 dt = displacement.len() / vellen; sBalance++; bool result = updatePos(dt); sBalance--; getTransform().getColumn(3, &mDelta.pos); mDelta.posVec.set(0.0f, 0.0f, 0.0f); return result; } #else bool Player::displaceObject(const Point3F& displacement) { F32 vellen = mVelocity.len(); if (vellen < 0.001f) { mVelocity.set(0.0f, 0.0f, 0.0f); return false; } F32 dt = displacement.len() / vellen; bool result = updatePos(dt); mObjToWorld.getColumn(3, &mDelta.pos); mDelta.posVec.set(0.0f, 0.0f, 0.0f); return result; } #endif //---------------------------------------------------------------------------- void Player::setPosition(const Point3F& pos,const Point3F& rot) { MatrixF mat; if (isMounted()) { // Use transform from mounted object //MatrixF nmat,zrot; mMount.object->getMountTransform( mMount.node, mMount.xfm, &mat ); //zrot.set(EulerF(0.0f, 0.0f, rot.z)); //mat.mul(nmat,zrot); } else { mat.set(EulerF(0.0f, 0.0f, rot.z)); mat.setColumn(3,pos); } Parent::setTransform(mat); mRot = rot; if ( mPhysicsRep ) mPhysicsRep->setTransform( mat ); } void Player::setRenderPosition(const Point3F& pos, const Point3F& rot, F32 dt) { MatrixF mat; if (isMounted()) { // Use transform from mounted object //MatrixF nmat,zrot; mMount.object->getRenderMountTransform( dt, mMount.node, mMount.xfm, &mat ); //zrot.set(EulerF(0.0f, 0.0f, rot.z)); //mat.mul(nmat,zrot); } else { EulerF orient(0.0f, 0.0f, rot.z); mat.set(orient); mat.setColumn(3, pos); if (inDeathAnim()) { F32 boxRad = (mDataBlock->boxSize.x * 0.5f); if (MatrixF * fallMat = mDeath.fallToGround(dt, pos, rot.z, boxRad)) mat = * fallMat; } else mDeath.initFall(); } Parent::setRenderTransform(mat); } //---------------------------------------------------------------------------- void Player::setTransform(const MatrixF& mat) { // This method should never be called on the client. // This currently converts all rotation in the mat into // rotations around the z axis. Point3F pos,vec; mat.getColumn(1,&vec); mat.getColumn(3,&pos); Point3F rot(0.0f, 0.0f, -mAtan2(-vec.x,vec.y)); setPosition(pos,rot); setMaskBits(MoveMask | NoWarpMask); } void Player::getEyeTransform(MatrixF* mat) { getEyeBaseTransform(mat, true); // The shape instance is animated in getEyeBaseTransform() so we're // good here when attempting to get the eye node position on the server. S32 imageIndex = -1; S32 shapeIndex = -1; MountedImage* image = NULL; ShapeBaseImageData* data = NULL; for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { image = &(mMountedImageList[i]); if (image->dataBlock) { data = image->dataBlock; shapeIndex = getImageShapeIndex(*image); if ( data->useEyeNode && (data->animateOnServer || isGhost()) && isFirstPerson() && data->eyeMountNode[shapeIndex] != -1 && data->eyeNode[shapeIndex] != -1 ) { imageIndex = i; break; } } } if (imageIndex >= 0) { // Get the image's eye node's position relative to the eye mount node MatrixF mountTransform = image->shapeInstance[shapeIndex]->mNodeTransforms[data->eyeMountNode[shapeIndex]]; Point3F eyeMountNodePos = mountTransform.getPosition(); mountTransform = image->shapeInstance[shapeIndex]->mNodeTransforms[data->eyeNode[shapeIndex]]; Point3F eyeNodePos = mountTransform.getPosition() - eyeMountNodePos; // Now transform to the image's eye node (position only) MatrixF xfm(true); xfm.setPosition(eyeNodePos); mat->mul(xfm); } } void Player::getEyeBaseTransform(MatrixF* mat, bool includeBank) { // Eye transform in world space. We only use the eye position // from the animation and supply our own rotation. MatrixF pmat,xmat,zmat; if(!isGhost()) mShapeInstance->animate(); xmat.set(EulerF(mHead.x, 0.0f, 0.0f)); if (mUseHeadZCalc) zmat.set(EulerF(0.0f, 0.0f, mHead.z)); else zmat.identity(); if(includeBank && mDataBlock->cameraCanBank) { // Take mHead.y into account to bank the camera MatrixF imat; imat.mul(zmat, xmat); MatrixF ymat; ymat.set(EulerF(0.0f, mHead.y, 0.0f)); pmat.mul(imat, ymat); } else { pmat.mul(zmat,xmat); } F32 *dp = pmat; F32* sp; MatrixF eyeMat(true); if (mDataBlock->eyeNode != -1) { sp = mShapeInstance->mNodeTransforms[mDataBlock->eyeNode]; } else { Point3F center; mObjBox.getCenter(&center); eyeMat.setPosition(center); sp = eyeMat; } const Point3F& scale = getScale(); dp[3] = sp[3] * scale.x; dp[7] = sp[7] * scale.y; dp[11] = sp[11] * scale.z; mat->mul(getTransform(),pmat); } void Player::getRenderEyeTransform(MatrixF* mat) { getRenderEyeBaseTransform(mat, true); // Use the first image that is set to use the eye node for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i) { MountedImage& image = mMountedImageList[i]; if (image.dataBlock) { ShapeBaseImageData& data = *image.dataBlock; U32 shapeIndex = getImageShapeIndex(image); if ( data.useEyeNode && isFirstPerson() && data.eyeMountNode[shapeIndex] != -1 && data.eyeNode[shapeIndex] != -1 ) { // Get the eye node's position relative to the eye mount node MatrixF mountTransform = image.shapeInstance[shapeIndex]->mNodeTransforms[data.eyeMountNode[shapeIndex]]; Point3F eyeMountNodePos = mountTransform.getPosition(); mountTransform = image.shapeInstance[shapeIndex]->mNodeTransforms[data.eyeNode[shapeIndex]]; Point3F eyeNodePos = mountTransform.getPosition() - eyeMountNodePos; // Now transform to the image's eye node (position only) MatrixF xfm(true); xfm.setPosition(eyeNodePos); mat->mul(xfm); return; } } } } void Player::getRenderEyeBaseTransform(MatrixF* mat, bool includeBank) { // Eye transform in world space. We only use the eye position // from the animation and supply our own rotation. MatrixF pmat,xmat,zmat; xmat.set(EulerF(mDelta.head.x + mDelta.headVec.x * mDelta.dt, 0.0f, 0.0f)); if (mUseHeadZCalc) zmat.set(EulerF(0.0f, 0.0f, mDelta.head.z + mDelta.headVec.z * mDelta.dt)); else zmat.identity(); if(includeBank && mDataBlock->cameraCanBank) { // Take mHead.y delta into account to bank the camera MatrixF imat; imat.mul(zmat, xmat); MatrixF ymat; ymat.set(EulerF(0.0f, mDelta.head.y + mDelta.headVec.y * mDelta.dt, 0.0f)); pmat.mul(imat, ymat); } else { pmat.mul(zmat,xmat); } F32 *dp = pmat; F32* sp; MatrixF eyeMat(true); if (mDataBlock->eyeNode != -1) { sp = mShapeInstance->mNodeTransforms[mDataBlock->eyeNode]; } else { // Use the center of the Player's bounding box for the eye position. Point3F center; mObjBox.getCenter(&center); eyeMat.setPosition(center); sp = eyeMat; } // Only use position of eye node, and take Player's scale // into account. const Point3F& scale = getScale(); dp[3] = sp[3] * scale.x; dp[7] = sp[7] * scale.y; dp[11] = sp[11] * scale.z; mat->mul(getRenderTransform(), pmat); } void Player::getMuzzleTransform(U32 imageSlot,MatrixF* mat) { disableHeadZCalc(); MatrixF nmat; Parent::getRetractionTransform(imageSlot,&nmat); MatrixF smat; Parent::getImageTransform(imageSlot,&smat); disableCollision(); // See if we are pushed into a wall... if (getDamageState() == Enabled) { Point3F start, end; smat.getColumn(3, &start); nmat.getColumn(3, &end); RayInfo rinfo; if (getContainer()->castRay(start, end, sCollisionMoveMask, &rinfo)) { Point3F finalPoint; finalPoint.interpolate(start, end, rinfo.t); nmat.setColumn(3, finalPoint); } else Parent::getMuzzleTransform(imageSlot,&nmat); } else Parent::getMuzzleTransform(imageSlot,&nmat); enableCollision(); enableHeadZCalc(); *mat = nmat; } void Player::getRenderMuzzleTransform(U32 imageSlot,MatrixF* mat) { disableHeadZCalc(); MatrixF nmat; Parent::getRenderRetractionTransform(imageSlot,&nmat); MatrixF smat; Parent::getRenderImageTransform(imageSlot,&smat); disableCollision(); // See if we are pushed into a wall... if (getDamageState() == Enabled) { Point3F start, end; smat.getColumn(3, &start); nmat.getColumn(3, &end); RayInfo rinfo; if (getContainer()->castRay(start, end, sCollisionMoveMask, &rinfo)) { Point3F finalPoint; finalPoint.interpolate(start, end, rinfo.t); nmat.setColumn(3, finalPoint); } else { Parent::getRenderMuzzleTransform(imageSlot,&nmat); } } else { Parent::getRenderMuzzleTransform(imageSlot,&nmat); } enableCollision(); enableHeadZCalc(); *mat = nmat; } void Player::getMuzzleVector(U32 imageSlot,VectorF* vec) { MatrixF mat; getMuzzleTransform(imageSlot,&mat); GameConnection * gc = getControllingClient(); if (gc && !gc->isAIControlled()) { MountedImage& image = mMountedImageList[imageSlot]; bool fp = gc->isFirstPerson(); if ((fp && image.dataBlock->correctMuzzleVector) || (!fp && image.dataBlock->correctMuzzleVectorTP)) { disableHeadZCalc(); if (getCorrectedAim(mat, vec)) { enableHeadZCalc(); return; } enableHeadZCalc(); } } mat.getColumn(1,vec); } void Player::renderMountedImage( U32 imageSlot, TSRenderState &rstate, SceneRenderState *state ) { GFX->pushWorldMatrix(); MatrixF world; MountedImage& image = mMountedImageList[imageSlot]; ShapeBaseImageData& data = *image.dataBlock; U32 imageShapeIndex; if ( state->isShadowPass() ) { // Force the standard image shapes for the shadow pass. imageShapeIndex = ShapeBaseImageData::StandardImageShape; } else { imageShapeIndex = getImageShapeIndex(image); } if ( !state->isShadowPass() && isFirstPerson() && (data.useEyeOffset || (data.useEyeNode && data.eyeMountNode[imageShapeIndex] != -1)) ) { if (data.useEyeNode && data.eyeMountNode[imageShapeIndex] != -1) { MatrixF nmat; getRenderEyeBaseTransform(&nmat, mDataBlock->mountedImagesBank); MatrixF offsetMat = image.shapeInstance[imageShapeIndex]->mNodeTransforms[data.eyeMountNode[imageShapeIndex]]; offsetMat.affineInverse(); world.mul(nmat,offsetMat); } else { MatrixF nmat; getRenderEyeBaseTransform(&nmat, mDataBlock->mountedImagesBank); world.mul(nmat,data.eyeOffset); } if ( imageSlot == 0 ) { MatrixF nmat; MatrixF smat; getRenderRetractionTransform(0,&nmat); getRenderImageTransform(0,&smat); // See if we are pushed into a wall... Point3F start, end; smat.getColumn(3, &start); nmat.getColumn(3, &end); Point3F displace = (start - end) * mWeaponBackFraction; world.setPosition( world.getPosition() + displace ); } } else { MatrixF nmat; getRenderMountTransform( 0.0f, data.mountPoint, MatrixF::Identity, &nmat); world.mul(nmat,data.mountTransform[imageShapeIndex]); } GFX->setWorldMatrix( world ); image.shapeInstance[imageShapeIndex]->animate(); image.shapeInstance[imageShapeIndex]->render( rstate ); // Render the first person mount image shape? if (!state->isShadowPass() && imageShapeIndex == ShapeBaseImageData::FirstPersonImageShape && mShapeFPInstance[imageSlot]) { mShapeFPInstance[imageSlot]->animate(); mShapeFPInstance[imageSlot]->render( rstate ); } GFX->popWorldMatrix(); } // Bot aiming code calls this frequently and will work fine without the check // for being pushed into a wall, which shows up on profile at ~ 3% (eight bots) void Player::getMuzzlePointAI(U32 imageSlot, Point3F* point) { MatrixF nmat; Parent::getMuzzleTransform(imageSlot, &nmat); // If we are in one of the standard player animations, adjust the // muzzle to point in the direction we are looking. if (mActionAnimation.action < PlayerData::NumTableActionAnims) { MatrixF xmat; xmat.set(EulerF(mHead.x, 0, 0)); MatrixF result; result.mul(getTransform(), xmat); F32 *sp = nmat, *dp = result; dp[3] = sp[3]; dp[7] = sp[7]; dp[11] = sp[11]; result.getColumn(3, point); } else nmat.getColumn(3, point); } void Player::getCameraParameters(F32 *min,F32* max,Point3F* off,MatrixF* rot) { if (!mControlObject.isNull() && mControlObject == getObjectMount()) { mControlObject->getCameraParameters(min,max,off,rot); return; } const Point3F& scale = getScale(); *min = mDataBlock->cameraMinDist * scale.y; *max = mDataBlock->cameraMaxDist * scale.y; off->set(0.0f, 0.0f, 0.0f); rot->identity(); } //---------------------------------------------------------------------------- Point3F Player::getVelocity() const { return mVelocity; } F32 Player::getSpeed() const { return mVelocity.len(); } void Player::setVelocity(const VectorF& vel) { AssertFatal( !mIsNaN( vel ), "Player::setVelocity() - The velocity is NaN!" ); mVelocity = vel; setMaskBits(MoveMask); } void Player::applyImpulse(const Point3F&,const VectorF& vec) { AssertFatal( !mIsNaN( vec ), "Player::applyImpulse() - The vector is NaN!" ); // Players ignore angular velocity VectorF vel; vel.x = vec.x / getMass(); vel.y = vec.y / getMass(); vel.z = vec.z / getMass(); // Make sure the impulse isn't too big F32 len = vel.magnitudeSafe(); if (len > sMaxImpulseVelocity) { Point3F excess = vel * ( 1.0f - (sMaxImpulseVelocity / len ) ); vel -= excess; } setVelocity(mVelocity + vel); } //---------------------------------------------------------------------------- bool Player::castRay(const Point3F &start, const Point3F &end, RayInfo* info) { // In standard Torque there's a rather brute force culling of all // non-enabled players (corpses) from the ray cast. But, to // demonstrate a resurrection spell, we need corpses to be // selectable, so this code change allows consideration of corpses // in the ray cast if corpsesHiddenFromRayCast is set to false. if (sCorpsesHiddenFromRayCast && getDamageState() != Enabled) return false; // Collide against bounding box. Need at least this for the editor. F32 st,et,fst = 0.0f,fet = 1.0f; F32 *bmin = &mObjBox.minExtents.x; F32 *bmax = &mObjBox.maxExtents.x; F32 const *si = &start.x; F32 const *ei = &end.x; for (S32 i = 0; i < 3; i++) { if (*si < *ei) { if (*si > *bmax || *ei < *bmin) return false; F32 di = *ei - *si; st = (*si < *bmin)? (*bmin - *si) / di: 0.0f; et = (*ei > *bmax)? (*bmax - *si) / di: 1.0f; } else { if (*ei > *bmax || *si < *bmin) return false; F32 di = *ei - *si; st = (*si > *bmax)? (*bmax - *si) / di: 0.0f; et = (*ei < *bmin)? (*bmin - *si) / di: 1.0f; } if (st > fst) fst = st; if (et < fet) fet = et; if (fet < fst) return false; bmin++; bmax++; si++; ei++; } info->normal = start - end; info->normal.normalizeSafe(); getTransform().mulV( info->normal ); info->t = fst; info->object = this; info->point.interpolate(start,end,fst); info->material = 0; return true; } //---------------------------------------------------------------------------- static MatrixF IMat(1); bool Player::buildPolyList(PolyListContext, AbstractPolyList* polyList, const Box3F&, const SphereF&) { // Collision with the player is always against the player's object // space bounding box axis aligned in world space. Point3F pos; getTransform().getColumn(3,&pos); IMat.setColumn(3,pos); polyList->setTransform(&IMat, Point3F(1.0f,1.0f,1.0f)); polyList->setObject(this); polyList->addBox(mObjBox); return true; } void Player::buildConvex(const Box3F& box, Convex* convex) { if (mShapeInstance == NULL) return; // These should really come out of a pool mConvexList->collectGarbage(); Box3F realBox = box; mWorldToObj.mul(realBox); realBox.minExtents.convolveInverse(mObjScale); realBox.maxExtents.convolveInverse(mObjScale); if (realBox.isOverlapped(getObjBox()) == false) return; Convex* cc = 0; CollisionWorkingList& wl = convex->getWorkingList(); for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext) { if (itr->mConvex->getType() == BoxConvexType && itr->mConvex->getObject() == this) { cc = itr->mConvex; break; } } if (cc) return; // Create a new convex. BoxConvex* cp = new OrthoBoxConvex; mConvexList->registerObject(cp); convex->addToWorkingList(cp); cp->init(this); mObjBox.getCenter(&cp->mCenter); cp->mSize.x = mObjBox.len_x() / 2.0f; cp->mSize.y = mObjBox.len_y() / 2.0f; cp->mSize.z = mObjBox.len_z() / 2.0f; } //---------------------------------------------------------------------------- void Player::updateWorkingCollisionSet() { // First, we need to adjust our velocity for possible acceleration. It is assumed // that we will never accelerate more than 20 m/s for gravity, plus 10 m/s for // jetting, and an equivalent 10 m/s for jumping. We also assume that the // working list is updated on a Tick basis, which means we only expand our // box by the possible movement in that tick. Point3F scaledVelocity = mVelocity * TickSec; F32 len = scaledVelocity.len(); F32 newLen = len + (10.0f * TickSec); // Check to see if it is actually necessary to construct the new working list, // or if we can use the cached version from the last query. We use the x // component of the min member of the mWorkingQueryBox, which is lame, but // it works ok. bool updateSet = false; Box3F convexBox = mConvex.getBoundingBox(getTransform(), getScale()); F32 l = (newLen * 1.1f) + 0.1f; // from Convex::updateWorkingList const Point3F lPoint( l, l, l ); convexBox.minExtents -= lPoint; convexBox.maxExtents += lPoint; // Check containment if (mWorkingQueryBox.minExtents.x != -1e9f) { if (mWorkingQueryBox.isContained(convexBox) == false) // Needed region is outside the cached region. Update it. updateSet = true; } else { // Must update updateSet = true; } // Actually perform the query, if necessary if (updateSet == true) { const Point3F twolPoint( 2.0f * l, 2.0f * l, 2.0f * l ); mWorkingQueryBox = convexBox; mWorkingQueryBox.minExtents -= twolPoint; mWorkingQueryBox.maxExtents += twolPoint; disableCollision(); //We temporarily disable the collisions of anything mounted to us so we don't accidentally walk into things we've attached to us for (SceneObject *ptr = mMount.list; ptr; ptr = ptr->getMountLink()) { ptr->disableCollision(); } mConvex.updateWorkingList(mWorkingQueryBox, isGhost() ? sClientCollisionContactMask : sServerCollisionContactMask); //And now re-enable the collisions of the mounted things for (SceneObject *ptr = mMount.list; ptr; ptr = ptr->getMountLink()) { ptr->enableCollision(); } enableCollision(); } } //---------------------------------------------------------------------------- void Player::writePacketData(GameConnection *connection, BitStream *stream) { Parent::writePacketData(connection, stream); stream->writeInt(mState,NumStateBits); if (stream->writeFlag(mState == RecoverState)) stream->writeInt(mRecoverTicks,PlayerData::RecoverDelayBits); if (stream->writeFlag(mJumpDelay > 0)) stream->writeInt(mJumpDelay,PlayerData::JumpDelayBits); Point3F pos; getTransform().getColumn(3,&pos); if (stream->writeFlag(!isMounted())) { // Will get position from mount stream->setCompressionPoint(pos); stream->write(pos.x); stream->write(pos.y); stream->write(pos.z); stream->write(mVelocity.x); stream->write(mVelocity.y); stream->write(mVelocity.z); stream->writeInt(mJumpSurfaceLastContact > 15 ? 15 : mJumpSurfaceLastContact, 4); if (stream->writeFlag(!mAllowSprinting || !mAllowCrouching || !mAllowProne || !mAllowJumping || !mAllowJetJumping || !mAllowSwimming)) { stream->writeFlag(mAllowJumping); stream->writeFlag(mAllowJetJumping); stream->writeFlag(mAllowSprinting); stream->writeFlag(mAllowCrouching); stream->writeFlag(mAllowProne); stream->writeFlag(mAllowSwimming); } } stream->write(mHead.x); if(stream->writeFlag(mDataBlock->cameraCanBank)) { // Include mHead.y to allow for camera banking stream->write(mHead.y); } stream->write(mHead.z); stream->write(mRot.z); if (mControlObject) { S32 gIndex = connection->getGhostIndex(mControlObject); if (stream->writeFlag(gIndex != -1)) { stream->writeInt(gIndex,NetConnection::GhostIdBitSize); mControlObject->writePacketData(connection, stream); } } else stream->writeFlag(false); } void Player::readPacketData(GameConnection *connection, BitStream *stream) { Parent::readPacketData(connection, stream); mState = (ActionState)stream->readInt(NumStateBits); if (stream->readFlag()) mRecoverTicks = stream->readInt(PlayerData::RecoverDelayBits); if (stream->readFlag()) mJumpDelay = stream->readInt(PlayerData::JumpDelayBits); else mJumpDelay = 0; Point3F pos,rot; if (stream->readFlag()) { // Only written if we are not mounted stream->read(&pos.x); stream->read(&pos.y); stream->read(&pos.z); stream->read(&mVelocity.x); stream->read(&mVelocity.y); stream->read(&mVelocity.z); stream->setCompressionPoint(pos); mDelta.pos = pos; mJumpSurfaceLastContact = stream->readInt(4); if (stream->readFlag()) { mAllowJumping = stream->readFlag(); mAllowJetJumping = stream->readFlag(); mAllowSprinting = stream->readFlag(); mAllowCrouching = stream->readFlag(); mAllowProne = stream->readFlag(); mAllowSwimming = stream->readFlag(); } else { mAllowJumping = true; mAllowJetJumping = true; mAllowSprinting = true; mAllowCrouching = true; mAllowProne = true; mAllowSwimming = true; } } else pos = mDelta.pos; stream->read(&mHead.x); if(stream->readFlag()) { // Include mHead.y to allow for camera banking stream->read(&mHead.y); } stream->read(&mHead.z); stream->read(&rot.z); rot.x = rot.y = 0; if (!ignore_updates) setPosition(pos,rot); mDelta.head = mHead; mDelta.rot = rot; if (stream->readFlag()) { S32 gIndex = stream->readInt(NetConnection::GhostIdBitSize); ShapeBase* obj = static_cast<ShapeBase*>(connection->resolveGhost(gIndex)); setControlObject(obj); obj->readPacketData(connection, stream); } else setControlObject(0); } U32 Player::packUpdate(NetConnection *con, U32 mask, BitStream *stream) { U32 retMask = Parent::packUpdate(con, mask, stream); if (stream->writeFlag((mask & ImpactMask) && !(mask & InitialUpdateMask))) stream->writeInt(mImpactSound, PlayerData::ImpactBits); if (stream->writeFlag(mask & ActionMask && mActionAnimation.action != PlayerData::NullAnimation && mActionAnimation.action >= PlayerData::NumTableActionAnims)) { stream->writeInt(mActionAnimation.action,PlayerData::ActionAnimBits); stream->writeFlag(mActionAnimation.holdAtEnd); stream->writeFlag(mActionAnimation.atEnd); stream->writeFlag(mActionAnimation.firstPerson); if (!mActionAnimation.atEnd) { // If somewhere in middle on initial update, must send position- F32 where = mShapeInstance->getPos(mActionAnimation.thread); if (stream->writeFlag((mask & InitialUpdateMask) != 0 && where > 0)) stream->writeSignedFloat(where, 6); } } if (stream->writeFlag(mask & ActionMask && mArmAnimation.action != PlayerData::NullAnimation && (!(mask & InitialUpdateMask) || mArmAnimation.action != mDataBlock->lookAction))) { stream->writeInt(mArmAnimation.action,PlayerData::ActionAnimBits); } retMask = afx_packUpdate(con, mask, stream, retMask); // The rest of the data is part of the control object packet update. // If we're controlled by this client, we don't need to send it. // we only need to send it if this is the initial update - in that case, // the client won't know this is the control object yet. if(stream->writeFlag(getControllingClient() == con && !(mask & InitialUpdateMask))) return(retMask); if (stream->writeFlag(mask & MoveMask)) { stream->writeFlag(mFalling); stream->writeFlag(mSwimming); stream->writeFlag(mJetting); stream->writeInt(mPose, NumPoseBits); stream->writeInt(mState,NumStateBits); if (stream->writeFlag(mState == RecoverState)) stream->writeInt(mRecoverTicks,PlayerData::RecoverDelayBits); Point3F pos; getTransform().getColumn(3,&pos); stream->writeCompressedPoint(pos); F32 len = mVelocity.len(); if(stream->writeFlag(len > 0.02f)) { Point3F outVel = mVelocity; outVel *= 1.0f/len; stream->writeNormalVector(outVel, 10); len *= 32.0f; // 5 bits of fraction if(len > 8191) len = 8191; stream->writeInt((S32)len, 13); } // constrain the range of mRot.z mWrapF(mRot.z, 0.0f, M_2PI_F); stream->writeFloat(mRot.z / M_2PI_F, 7); stream->writeSignedFloat(mHead.x / (mDataBlock->maxLookAngle - mDataBlock->minLookAngle), 6); stream->writeSignedFloat(mHead.z / mDataBlock->maxFreelookAngle, 6); mDelta.move.pack(stream); stream->writeFlag(!(mask & NoWarpMask)); } // Ghost need energy to predict reliably if (mDataBlock->maxEnergy > 0.f) stream->writeFloat(getEnergyLevel() / mDataBlock->maxEnergy, EnergyLevelBits); else stream->writeFloat(0.f, EnergyLevelBits); return retMask; } void Player::unpackUpdate(NetConnection *con, BitStream *stream) { Parent::unpackUpdate(con,stream); if (stream->readFlag()) mImpactSound = stream->readInt(PlayerData::ImpactBits); // Server specified action animation if (stream->readFlag()) { U32 action = stream->readInt(PlayerData::ActionAnimBits); bool hold = stream->readFlag(); bool atEnd = stream->readFlag(); bool fsp = stream->readFlag(); F32 animPos = -1.0f; if (!atEnd && stream->readFlag()) animPos = stream->readSignedFloat(6); if (isProperlyAdded()) { setActionThread(action,true,hold,true,fsp); bool inDeath = inDeathAnim(); if (atEnd) { mShapeInstance->clearTransition(mActionAnimation.thread); mShapeInstance->setPos(mActionAnimation.thread, mActionAnimation.forward? 1: 0); if (inDeath) mDeath.lastPos = 1.0f; } else if (animPos > 0) { mShapeInstance->setPos(mActionAnimation.thread, animPos); if (inDeath) mDeath.lastPos = animPos; } // mMountPending suppresses tickDelay countdown so players will sit until // their mount, or another animation, comes through (or 13 seconds elapses). mMountPending = (S32) (inSittingAnim() ? sMountPendingTickWait : 0); } else { mActionAnimation.action = action; mActionAnimation.holdAtEnd = hold; mActionAnimation.atEnd = atEnd; mActionAnimation.firstPerson = fsp; } } // Server specified arm animation if (stream->readFlag()) { U32 action = stream->readInt(PlayerData::ActionAnimBits); if (isProperlyAdded()) setArmThread(action); else mArmAnimation.action = action; } afx_unpackUpdate(con, stream); // Done if controlled by client ( and not initial update ) if(stream->readFlag()) return; // MoveMask if (stream->readFlag()) { mPredictionCount = sMaxPredictionTicks; mFalling = stream->readFlag(); mSwimming = stream->readFlag(); mJetting = stream->readFlag(); mPose = (Pose)(stream->readInt(NumPoseBits)); ActionState actionState = (ActionState)stream->readInt(NumStateBits); if (stream->readFlag()) { mRecoverTicks = stream->readInt(PlayerData::RecoverDelayBits); setState(actionState, mRecoverTicks); } else setState(actionState); Point3F pos,rot; stream->readCompressedPoint(&pos); F32 speed = mVelocity.len(); if(stream->readFlag()) { stream->readNormalVector(&mVelocity, 10); mVelocity *= stream->readInt(13) / 32.0f; } else { mVelocity.set(0.0f, 0.0f, 0.0f); } rot.y = rot.x = 0.0f; rot.z = stream->readFloat(7) * M_2PI_F; mHead.x = stream->readSignedFloat(6) * (mDataBlock->maxLookAngle - mDataBlock->minLookAngle); mHead.z = stream->readSignedFloat(6) * mDataBlock->maxFreelookAngle; mDelta.move.unpack(stream); mDelta.head = mHead; mDelta.headVec.set(0.0f, 0.0f, 0.0f); if (stream->readFlag() && isProperlyAdded()) { // Determine number of ticks to warp based on the average // of the client and server velocities. mDelta.warpOffset = pos - mDelta.pos; F32 as = (speed + mVelocity.len()) * 0.5f * TickSec; F32 dt = (as > 0.00001f) ? mDelta.warpOffset.len() / as: sMaxWarpTicks; mDelta.warpTicks = (S32)((dt > sMinWarpTicks) ? getMax(mFloor(dt + 0.5f), 1.0f) : 0.0f); if (mDelta.warpTicks) { // Setup the warp to start on the next tick. if (mDelta.warpTicks > sMaxWarpTicks) mDelta.warpTicks = sMaxWarpTicks; mDelta.warpOffset /= (F32)mDelta.warpTicks; mDelta.rotOffset = rot - mDelta.rot; // Ignore small rotation differences if (mFabs(mDelta.rotOffset.z) < 0.001f) mDelta.rotOffset.z = 0; // Wrap rotation to +/-PI if(mDelta.rotOffset.z < - M_PI_F) mDelta.rotOffset.z += M_2PI_F; else if(mDelta.rotOffset.z > M_PI_F) mDelta.rotOffset.z -= M_2PI_F; mDelta.rotOffset /= (F32)mDelta.warpTicks; } else { // Going to skip the warp, server and client are real close. // Adjust the frame interpolation to move smoothly to the // new position within the current tick. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt; if (mDelta.dt == 0) { mDelta.posVec.set(0.0f, 0.0f, 0.0f); mDelta.rotVec.set(0.0f, 0.0f, 0.0f); } else { F32 dti = 1.0f / mDelta.dt; mDelta.posVec = (cp - pos) * dti; mDelta.rotVec.z = mRot.z - rot.z; if(mDelta.rotVec.z > M_PI_F) mDelta.rotVec.z -= M_2PI_F; else if(mDelta.rotVec.z < -M_PI_F) mDelta.rotVec.z += M_2PI_F; mDelta.rotVec.z *= dti; } mDelta.pos = pos; mDelta.rot = rot; if (!ignore_updates) setPosition(pos,rot); } } else { // Set the player to the server position mDelta.pos = pos; mDelta.rot = rot; mDelta.posVec.set(0.0f, 0.0f, 0.0f); mDelta.rotVec.set(0.0f, 0.0f, 0.0f); mDelta.warpTicks = 0; mDelta.dt = 0.0f; if (!ignore_updates) setPosition(pos,rot); } } F32 energy = stream->readFloat(EnergyLevelBits) * mDataBlock->maxEnergy; setEnergyLevel(energy); } //---------------------------------------------------------------------------- DefineEngineMethod( Player, getPose, const char*, (),, "@brief Get the name of the player's current pose.\n\n" "The pose is one of the following:\n\n<ul>" "<li>Stand - Standard movement pose.</li>" "<li>Sprint - Sprinting pose.</li>" "<li>Crouch - Crouch pose.</li>" "<li>Prone - Prone pose.</li>" "<li>Swim - Swimming pose.</li></ul>\n" "@return The current pose; one of: \"Stand\", \"Sprint\", \"Crouch\", \"Prone\", \"Swim\"\n" ) { return object->getPoseName(); } DefineEngineMethod( Player, allowAllPoses, void, (),, "@brief Allow all poses a chance to occur.\n\n" "This method resets any poses that have manually been blocked from occuring. " "This includes the regular pose states such as sprinting, crouch, being prone " "and swimming. It also includes being able to jump and jet jump. While this " "is allowing these poses to occur it doesn't mean that they all can due to other " "conditions. We're just not manually blocking them from being allowed.\n" "@see allowJumping()\n" "@see allowJetJumping()\n" "@see allowSprinting()\n" "@see allowCrouching()\n" "@see allowProne()\n" "@see allowSwimming()\n" ) { object->allowAllPoses(); } DefineEngineMethod( Player, allowJumping, void, (bool state),, "@brief Set if the Player is allowed to jump.\n\n" "The default is to allow jumping unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow jumping " "at any time.\n" "@param state Set to true to allow jumping, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowJumping(state); } DefineEngineMethod( Player, allowJetJumping, void, (bool state),, "@brief Set if the Player is allowed to jet jump.\n\n" "The default is to allow jet jumping unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow jet jumping " "at any time.\n" "@param state Set to true to allow jet jumping, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowJetJumping(state); } DefineEngineMethod( Player, allowSprinting, void, (bool state),, "@brief Set if the Player is allowed to sprint.\n\n" "The default is to allow sprinting unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow sprinting " "at any time.\n" "@param state Set to true to allow sprinting, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowSprinting(state); } DefineEngineMethod( Player, allowCrouching, void, (bool state),, "@brief Set if the Player is allowed to crouch.\n\n" "The default is to allow crouching unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow crouching " "at any time.\n" "@param state Set to true to allow crouching, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowCrouching(state); } DefineEngineMethod( Player, allowProne, void, (bool state),, "@brief Set if the Player is allowed to go prone.\n\n" "The default is to allow being prone unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow going prone " "at any time.\n" "@param state Set to true to allow being prone, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowProne(state); } DefineEngineMethod( Player, allowSwimming, void, (bool state),, "@brief Set if the Player is allowed to swim.\n\n" "The default is to allow swimming unless there are other environmental concerns " "that prevent it. This method is mainly used to explicitly disallow swimming " "at any time.\n" "@param state Set to true to allow swimming, false to disable it.\n" "@see allowAllPoses()\n" ) { object->allowSwimming(state); } //---------------------------------------------------------------------------- DefineEngineMethod( Player, getState, const char*, (),, "@brief Get the name of the player's current state.\n\n" "The state is one of the following:\n\n<ul>" "<li>Dead - The Player is dead.</li>" "<li>Mounted - The Player is mounted to an object such as a vehicle.</li>" "<li>Move - The Player is free to move. The usual state.</li>" "<li>Recover - The Player is recovering from a fall. See PlayerData::recoverDelay.</li></ul>\n" "@return The current state; one of: \"Dead\", \"Mounted\", \"Move\", \"Recover\"\n" ) { return object->getStateName(); } DefineEngineMethod( Player, getDamageLocation, const char*, ( Point3F pos ),, "@brief Get the named damage location and modifier for a given world position.\n\n" "the Player object can simulate different hit locations based on a pre-defined set " "of PlayerData defined percentages. These hit percentages divide up the Player's " "bounding box into different regions. The diagram below demonstrates how the various " "PlayerData properties split up the bounding volume:\n\n" "<img src=\"images/player_damageloc.png\">\n\n" "While you may pass in any world position and getDamageLocation() will provide a best-fit " "location, you should be aware that this can produce some interesting results. For example, " "any position that is above PlayerData::boxHeadPercentage will be considered a 'head' hit, even " "if the world position is high in the sky. Therefore it may be wise to keep the passed in point " "to somewhere on the surface of, or within, the Player's bounding volume.\n\n" "@note This method will not return an accurate location when the player is " "prone or swimming.\n\n" "@param pos A world position for which to retrieve a body region on this player.\n" "@return a string containing two words (space separated strings), where the " "first is a location and the second is a modifier.\n\n" "Posible locations:<ul>" "<li>head</li>" "<li>torso</li>" "<li>legs</li></ul>\n" "Head modifiers:<ul>" "<li>left_back</li>" "<li>middle_back</li>" "<li>right_back</li>" "<li>left_middle</li>" "<li>middle_middle</li>" "<li>right_middle</li>" "<li>left_front</li>" "<li>middle_front</li>" "<li>right_front</li></ul>\n" "Legs/Torso modifiers:<ul>" "<li>front_left</li>" "<li>front_right</li>" "<li>back_left</li>" "<li>back_right</li></ul>\n" "@see PlayerData::boxHeadPercentage\n" "@see PlayerData::boxHeadFrontPercentage\n" "@see PlayerData::boxHeadBackPercentage\n" "@see PlayerData::boxHeadLeftPercentage\n" "@see PlayerData::boxHeadRightPercentage\n" "@see PlayerData::boxTorsoPercentage\n" ) { const char *buffer1; const char *buffer2; object->getDamageLocation(pos, buffer1, buffer2); static const U32 bufSize = 128; char *buff = Con::getReturnBuffer(bufSize); dSprintf(buff, bufSize, "%s %s", buffer1, buffer2); return buff; } DefineEngineMethod( Player, setArmThread, bool, ( const char* name ),, "@brief Set the sequence that controls the player's arms (dynamically adjusted " "to match look direction).\n\n" "@param name Name of the sequence to play on the player's arms.\n" "@return true if successful, false if failed.\n" "@note By default the 'look' sequence is used, if available.\n") { return object->setArmThread( name ); } DefineEngineMethod( Player, setActionThread, bool, ( const char* name, bool hold, bool fsp ), ( false, true ), "@brief Set the main action sequence to play for this player.\n\n" "@param name Name of the action sequence to set\n" "@param hold Set to false to get a callback on the datablock when the sequence ends (PlayerData::animationDone()). " "When set to true no callback is made.\n" "@param fsp True if first person and none of the spine nodes in the shape should animate. False will allow the shape's " "spine nodes to animate.\n" "@return True if succesful, false if failed\n" "@note The spine nodes for the Player's shape are named as follows:\n\n<ul>" "<li>Bip01 Pelvis</li>" "<li>Bip01 Spine</li>" "<li>Bip01 Spine1</li>" "<li>Bip01 Spine2</li>" "<li>Bip01 Neck</li>" "<li>Bip01 Head</li></ul>\n\n" "You cannot use setActionThread() to have the Player play one of the motion " "determined action animation sequences. These sequences are chosen based on how " "the Player moves and the Player's current pose. The names of these sequences are:\n\n<ul>" "<li>root</li>" "<li>run</li>" "<li>side</li>" "<li>side_right</li>" "<li>crouch_root</li>" "<li>crouch_forward</li>" "<li>crouch_backward</li>" "<li>crouch_side</li>" "<li>crouch_right</li>" "<li>prone_root</li>" "<li>prone_forward</li>" "<li>prone_backward</li>" "<li>swim_root</li>" "<li>swim_forward</li>" "<li>swim_backward</li>" "<li>swim_left</li>" "<li>swim_right</li>" "<li>fall</li>" "<li>jump</li>" "<li>standjump</li>" "<li>land</li>" "<li>jet</li></ul>\n\n" "If the player moves in any direction then the animation sequence set using this " "method will be cancelled and the chosen mation-based sequence will take over. This makes " "great for times when the Player cannot move, such as when mounted, or when it doesn't matter " "if the action sequence changes, such as waving and saluting.\n" "@tsexample\n" "// Place the player in a sitting position after being mounted\n" "%player.setActionThread( \"sitting\", true, true );\n" "@endtsexample\n") { return object->setActionThread( name, hold, true, fsp); } DefineEngineMethod( Player, setControlObject, bool, ( ShapeBase* obj ),, "@brief Set the object to be controlled by this player\n\n" "It is possible to have the moves sent to the Player object from the " "GameConnection to be passed along to another object. This happens, for example " "when a player is mounted to a vehicle. The move commands pass through the Player " "and on to the vehicle (while the player remains stationary within the vehicle). " "With setControlObject() you can have the Player pass along its moves to any object. " "One possible use is for a player to move a remote controlled vehicle. In this case " "the player does not mount the vehicle directly, but still wants to be able to control it.\n" "@param obj Object to control with this player\n" "@return True if the object is valid, false if not\n" "@see getControlObject()\n" "@see clearControlObject()\n" "@see GameConnection::setControlObject()") { if (obj) { object->setControlObject(obj); return true; } else object->setControlObject(0); return false; } DefineEngineMethod( Player, getControlObject, S32, (),, "@brief Get the current object we are controlling.\n\n" "@return ID of the ShapeBase object we control, or 0 if not controlling an " "object.\n" "@see setControlObject()\n" "@see clearControlObject()") { ShapeBase* controlObject = object->getControlObject(); return controlObject ? controlObject->getId(): 0; } DefineEngineMethod( Player, clearControlObject, void, (),, "@brief Clears the player's current control object.\n\n" "Returns control to the player. This internally calls " "Player::setControlObject(0).\n" "@tsexample\n" "%player.clearControlObject();\n" "echo(%player.getControlObject()); //<-- Returns 0, player assumes control\n" "%player.setControlObject(%vehicle);\n" "echo(%player.getControlObject()); //<-- Returns %vehicle, player controls the vehicle now.\n" "@endtsexample\n" "@note If the player does not have a control object, the player will receive all moves " "from its GameConnection. If you're looking to remove control from the player itself " "(i.e. stop sending moves to the player) use GameConnection::setControlObject() to transfer " "control to another object, such as a camera.\n" "@see setControlObject()\n" "@see getControlObject()\n" "@see GameConnection::setControlObject()\n") { object->setControlObject(0); } DefineEngineMethod( Player, checkDismountPoint, bool, ( Point3F oldPos, Point3F pos ),, "@brief Check if it is safe to dismount at this position.\n\n" "Internally this method casts a ray from oldPos to pos to determine if it hits the " "terrain, an interior object, a water object, another player, a static shape, " "a vehicle (exluding the one currently mounted), or physical zone. If this ray " "is in the clear, then the player's bounding box is also checked for a collision at " "the pos position. If this displaced bounding box is also in the clear, then " "checkDismountPoint() returns true.\n" "@param oldPos The player's current position\n" "@param pos The dismount position to check\n" "@return True if the dismount position is clear, false if not\n" "@note The player must be already mounted for this method to not assert.\n") { MatrixF oldPosMat(true); oldPosMat.setColumn(3, oldPos); MatrixF posMat(true); posMat.setColumn(3, pos); return object->checkDismountPosition(oldPosMat, posMat); } DefineEngineMethod( Player, getNumDeathAnimations, S32, ( ),, "@brief Get the number of death animations available to this player.\n\n" "Death animations are assumed to be named death1-N using consecutive indices." ) { S32 count = 0; const PlayerData * db = dynamic_cast<PlayerData*>( object->getDataBlock() ); if ( db ) { for ( S32 i = 0; i < db->actionCount; i++ ) if ( db->actionList[i].death ) count++; } return count; } //---------------------------------------------------------------------------- void Player::consoleInit() { Con::addVariable("$player::renderMyPlayer",TypeBool, &sRenderMyPlayer, "@brief Determines if the player is rendered or not.\n\n" "Used on the client side to disable the rendering of all Player objects. This is " "mainly for the tools or debugging.\n" "@ingroup GameObjects\n"); Con::addVariable("$player::renderMyItems",TypeBool, &sRenderMyItems, "@brief Determines if mounted shapes are rendered or not.\n\n" "Used on the client side to disable the rendering of all Player mounted objects. This is " "mainly used for the tools or debugging.\n" "@ingroup GameObjects\n"); Con::addVariable("$player::renderCollision", TypeBool, &sRenderPlayerCollision, "@brief Determines if the player's collision mesh should be rendered.\n\n" "This is mainly used for the tools and debugging.\n" "@ingroup GameObjects\n"); Con::addVariable("$player::minWarpTicks",TypeF32,&sMinWarpTicks, "@brief Fraction of tick at which instant warp occures on the client.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::maxWarpTicks",TypeS32,&sMaxWarpTicks, "@brief When a warp needs to occur due to the client being too far off from the server, this is the " "maximum number of ticks we'll allow the client to warp to catch up.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::maxPredictionTicks",TypeS32,&sMaxPredictionTicks, "@brief Maximum number of ticks to predict on the client from the last known move obtained from the server.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::maxImpulseVelocity", TypeF32, &sMaxImpulseVelocity, "@brief The maximum velocity allowed due to a single impulse.\n\n" "@ingroup GameObjects\n"); // Move triggers Con::addVariable("$player::jumpTrigger", TypeS32, &sJumpTrigger, "@brief The move trigger index used for player jumping.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::crouchTrigger", TypeS32, &sCrouchTrigger, "@brief The move trigger index used for player crouching.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::proneTrigger", TypeS32, &sProneTrigger, "@brief The move trigger index used for player prone pose.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::sprintTrigger", TypeS32, &sSprintTrigger, "@brief The move trigger index used for player sprinting.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::imageTrigger0", TypeS32, &sImageTrigger0, "@brief The move trigger index used to trigger mounted image 0.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::imageTrigger1", TypeS32, &sImageTrigger1, "@brief The move trigger index used to trigger mounted image 1 or alternate fire " "on mounted image 0.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::jumpJetTrigger", TypeS32, &sJumpJetTrigger, "@brief The move trigger index used for player jump jetting.\n\n" "@ingroup GameObjects\n"); Con::addVariable("$player::vehicleDismountTrigger", TypeS32, &sVehicleDismountTrigger, "@brief The move trigger index used to dismount player.\n\n" "@ingroup GameObjects\n"); // ExtendedMove support Con::addVariable("$player::extendedMoveHeadPosRotIndex", TypeS32, &smExtendedMoveHeadPosRotIndex, "@brief The ExtendedMove position/rotation index used for head movements.\n\n" "@ingroup GameObjects\n"); afx_consoleInit(); } //-------------------------------------------------------------------------- void Player::calcClassRenderData() { Parent::calcClassRenderData(); // If nothing is mounted do not perform the calculations below. Otherwise, // we'll end up with a bad ray cast as both nmat and smat will be the // Player's transform. MountedImage& image = mMountedImageList[0]; if (!image.dataBlock) { mWeaponBackFraction = 0.0f; return; } disableCollision(); MatrixF nmat; MatrixF smat; Parent::getRetractionTransform(0,&nmat); Parent::getImageTransform(0, &smat); // See if we are pushed into a wall... Point3F start, end; smat.getColumn(3, &start); nmat.getColumn(3, &end); RayInfo rinfo; if (getContainer()->castRay(start, end, sCollisionMoveMask & ~(WaterObjectType|PhysicalZoneObjectType|MarkerObjectType), &rinfo)) { if (rinfo.t < 1.0f) mWeaponBackFraction = 1.0f - rinfo.t; else mWeaponBackFraction = 0.0f; } else { mWeaponBackFraction = 0.0f; } enableCollision(); } //----------------------------------------------------------------------------- void Player::playFootstepSound( bool triggeredLeft, Material* contactMaterial, SceneObject* contactObject ) { if (footfallSoundOverride > 0) return; MatrixF footMat = getTransform(); if( mWaterCoverage > 0.0 ) { // Treading water. if ( mWaterCoverage < mDataBlock->footSplashHeight ) SFX->playOnce( mDataBlock->getPlayerSoundProfile( PlayerData::FootShallowSplash ), &footMat ); else { if ( mWaterCoverage < 1.0 ) SFX->playOnce( mDataBlock->getPlayerSoundProfile( PlayerData::FootWading ), &footMat ); else { if ( triggeredLeft ) { SFX->playOnce( mDataBlock->getPlayerSoundProfile( PlayerData::FootUnderWater ), &footMat ); SFX->playOnce( mDataBlock->getPlayerSoundProfile( PlayerData::FootBubbles ), &footMat ); } } } } else if( contactMaterial && contactMaterial->getCustomFootstepSoundProfile()) { // Footstep sound defined on material. SFX->playOnce( contactMaterial->getCustomFootstepSoundProfile(), &footMat ); } else { // Play default sound. S32 sound = -1; if (contactMaterial && (contactMaterial->mFootstepSoundId > -1 && contactMaterial->mFootstepSoundId < PlayerData::WaterStart)) sound = contactMaterial->mFootstepSoundId; else if( contactObject && contactObject->getTypeMask() & VehicleObjectType ) sound = 2; if (sound>=0) SFX->playOnce(mDataBlock->getPlayerSoundProfile(sound), &footMat); } } void Player:: playImpactSound() { if( mWaterCoverage == 0.0f ) { Point3F pos; RayInfo rInfo; MatrixF mat = getTransform(); mat.mulP(Point3F(mDataBlock->decalOffset,0.0f,0.0f), &pos); if( gClientContainer.castRay( Point3F( pos.x, pos.y, pos.z + 0.01f ), Point3F( pos.x, pos.y, pos.z - 2.0f ), STATIC_COLLISION_TYPEMASK | VehicleObjectType, &rInfo ) ) { Material* material = ( rInfo.material ? dynamic_cast< Material* >( rInfo.material->getMaterial() ) : 0 ); if( material && material->getCustomImpactSoundProfile() ) SFX->playOnce( material->getCustomImpactSoundProfile(), &getTransform() ); else { S32 sound = -1; if (material && (material->mImpactSoundId > -1 && material->mImpactSoundId < PlayerData::WaterStart)) sound = material->mImpactSoundId; else if( rInfo.object->getTypeMask() & VehicleObjectType ) sound = 2; // Play metal; if (sound >= 0) SFX->playOnce(mDataBlock->getPlayerSoundProfile(PlayerData::ImpactSoft + sound), &getTransform()); } } } mImpactSound = 0; } //-------------------------------------------------------------------------- // Update splash //-------------------------------------------------------------------------- void Player::updateSplash() { F32 speed = getVelocity().len(); if( speed < mDataBlock->splashVelocity || isMounted() ) return; Point3F curPos = getPosition(); if ( curPos.equal( mLastPos ) ) return; if (pointInWater( curPos )) { if (!pointInWater( mLastPos )) { Point3F norm = getVelocity(); norm.normalize(); // make sure player is moving vertically at good pace before playing splash F32 splashAng = mDataBlock->splashAngle / 360.0; if( mDot( norm, Point3F(0.0, 0.0, -1.0) ) < splashAng ) return; RayInfo rInfo; if (gClientContainer.castRay(mLastPos, curPos, WaterObjectType, &rInfo)) { createSplash( rInfo.point, speed ); mBubbleEmitterTime = 0.0; } } } } //-------------------------------------------------------------------------- void Player::updateFroth( F32 dt ) { // update bubbles Point3F moveDir = getVelocity(); mBubbleEmitterTime += dt; if (mBubbleEmitterTime < mDataBlock->bubbleEmitTime) { if (mSplashEmitter[PlayerData::BUBBLE_EMITTER]) { Point3F emissionPoint = getRenderPosition(); U32 emitNum = PlayerData::BUBBLE_EMITTER; mSplashEmitter[emitNum]->emitParticles(mLastPos, emissionPoint, Point3F( 0.0, 0.0, 1.0 ), moveDir, (U32)(dt * 1000.0)); } } Point3F contactPoint; if (!collidingWithWater(contactPoint)) { mLastWaterPos = mLastPos; return; } F32 speed = moveDir.len(); if ( speed < mDataBlock->splashVelEpsilon ) speed = 0.0; U32 emitRate = (U32) (speed * mDataBlock->splashFreqMod * dt); // If we're in the water, swimming, but not // moving, then lets emit some particles because // we're treading water. if ( mSwimming && speed == 0.0 ) { emitRate = (U32) (2.0f * mDataBlock->splashFreqMod * dt); } U32 i; for ( i=0; i<PlayerData::BUBBLE_EMITTER; i++ ) { if (mSplashEmitter[i] ) mSplashEmitter[i]->emitParticles( mLastWaterPos, contactPoint, Point3F( 0.0, 0.0, 1.0 ), moveDir, emitRate ); } mLastWaterPos = contactPoint; } void Player::updateWaterSounds(F32 dt) { if ( mWaterCoverage < 1.0f || mDamageState != Enabled ) { // Stop everything if ( mMoveBubbleSound ) mMoveBubbleSound->stop(); if ( mWaterBreathSound ) mWaterBreathSound->stop(); return; } if ( mMoveBubbleSound ) { // We're under water and still alive, so let's play something if ( mVelocity.len() > 1.0f ) { if ( !mMoveBubbleSound->isPlaying() ) mMoveBubbleSound->play(); mMoveBubbleSound->setTransform( getTransform() ); } else mMoveBubbleSound->stop(); } if ( mWaterBreathSound ) { if ( !mWaterBreathSound->isPlaying() ) mWaterBreathSound->play(); mWaterBreathSound->setTransform( getTransform() ); } } //-------------------------------------------------------------------------- // Returns true if player is intersecting a water surface //-------------------------------------------------------------------------- bool Player::collidingWithWater( Point3F &waterHeight ) { if ( !mCurrentWaterObject ) return false; Point3F curPos = getPosition(); if ( mWorldBox.maxExtents.z < mLiquidHeight ) return false; curPos.z = mLiquidHeight; waterHeight = getPosition(); waterHeight.z = mLiquidHeight; return true; } //-------------------------------------------------------------------------- void Player::createSplash( Point3F &pos, F32 speed ) { if ( speed >= mDataBlock->hardSplashSoundVel ) SFX->playOnce( mDataBlock->getPlayerSoundProfile(PlayerData::ImpactWaterHard), &getTransform() ); else if ( speed >= mDataBlock->medSplashSoundVel ) SFX->playOnce( mDataBlock->getPlayerSoundProfile(PlayerData::ImpactWaterMedium), &getTransform() ); else SFX->playOnce( mDataBlock->getPlayerSoundProfile(PlayerData::ImpactWaterEasy), &getTransform() ); if( mDataBlock->splash ) { MatrixF trans = getTransform(); trans.setPosition( pos ); Splash *splash = new Splash; splash->onNewDataBlock( mDataBlock->splash, false ); splash->setTransform( trans ); splash->setInitialState( trans.getPosition(), Point3F( 0.0, 0.0, 1.0 ) ); if (!splash->registerObject()) delete splash; } } bool Player::isControlObject() { GameConnection* connection = GameConnection::getConnectionToServer(); if( !connection ) return false; ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject()); return ( obj == this ); } void Player::prepRenderImage( SceneRenderState* state ) { bool renderPlayer = true; bool renderItems = true; /* if ( mPhysicsRep && Con::getBoolVariable("$PhysicsPlayer::DebugRender",false) ) { ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>(); ri->renderDelegate.bind( mPhysicsRep, &PhysicsPlayer::renderDebug ); ri->objectIndex = -1; ri->type = RenderPassManager::RIT_Editor; state->getRenderPass()->addInst( ri ); } */ // Debug rendering for all convexes in the Players working list. if ( sRenderPlayerCollision ) { ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>(); ri->renderDelegate.bind( this, &Player::renderConvex ); ri->objectIndex = -1; ri->type = RenderPassManager::RIT_Editor; state->getRenderPass()->addInst( ri ); } GameConnection* connection = GameConnection::getConnectionToServer(); if( connection && connection->getControlObject() == this && connection->isFirstPerson() ) { // If we're first person and we are not rendering the player // then disable all shadow rendering... a floating gun shadow sucks. if ( state->isShadowPass() && !mDataBlock->renderFirstPerson && !mDataBlock->firstPersonShadows ) return; renderPlayer = mDataBlock->renderFirstPerson || !state->isDiffusePass(); if( !sRenderMyPlayer ) renderPlayer = false; if( !sRenderMyItems ) renderItems = false; } // Call the protected base class to do the work // now that we know if we're rendering the player // and mounted shapes. return ShapeBase::_prepRenderImage( state, renderPlayer, renderItems ); } void Player::renderConvex( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat ) { GFX->enterDebugEvent( ColorI(255,0,255), "Player_renderConvex" ); mConvex.renderWorkingList(); GFX->leaveDebugEvent(); } // static bool Player::sCorpsesHiddenFromRayCast = true; // this default matches stock Torque behavior. // static void Player::afx_consoleInit() { Con::addVariable("pref::Player::corpsesHiddenFromRayCast", TypeBool, &sCorpsesHiddenFromRayCast); } void Player::afx_init() { overrideLookAnimation = false; armLookOverridePos = 0.5f; headVLookOverridePos = 0.5f; headHLookOverridePos = 0.5f; ignore_updates = false; fx_c_triggers = 0; mark_fx_c_triggers = 0; fx_s_triggers = 0; move_trigger_states = 0; z_velocity = 0.0f; mark_idle = false; idle_timer = 0.0f; mark_s_landing = false; speed_bias = 1.0f; speed_bias_goal = 1.0f; override_movement = 0; movement_data.zero(); movement_op = 1; last_movement_tag = 0; footfallDecalOverride = 0; footfallSoundOverride = 0; footfallDustOverride = 0; noFootfallFX = false; } U32 Player::afx_packUpdate(NetConnection* con, U32 mask, BitStream* stream, U32 retMask) { #if 0 if (stream->writeFlag(mask & LookOverrideMask)) #else if (stream->writeFlag(mask & ActionMask)) #endif stream->writeFlag(overrideLookAnimation); if (stream->writeFlag(mask & TriggerMask)) stream->write(fx_s_triggers); return retMask; } void Player::afx_unpackUpdate(NetConnection* con, BitStream* stream) { if (stream->readFlag()) // LookOverrideMask overrideLookAnimation = stream->readFlag(); if (stream->readFlag()) // TriggerMask { U32 mask; stream->read(&mask); mark_fx_c_triggers = mask; } } // Code for overriding player's animation with sequences selected by the // anim-clip component effect. void Player::restoreAnimation(U32 tag) { // check if this is a blended clip if ((tag & BLENDED_CLIP) != 0) { restoreBlendAnimation(tag); return; } if (tag != 0 && tag == last_anim_tag) { bool is_death_anim = ((anim_clip_flags & IS_DEATH_ANIM) != 0); anim_clip_flags &= ~(ANIM_OVERRIDDEN | IS_DEATH_ANIM); if (isClientObject()) { if (mDamageState != Enabled) { if (!is_death_anim) { // this is a bit hardwired and desperate, // but if he's dead he needs to look like it. setActionThread("death10", false, false, false); } } else if (mState != MoveState) { // not sure what happens here } else { pickActionAnimation(); } } last_anim_tag = 0; last_anim_id = -1; } } U32 Player::getAnimationID(const char* name) { for (U32 i = 0; i < mDataBlock->actionCount; i++) { PlayerData::ActionAnimation &anim = mDataBlock->actionList[i]; if (dStricmp(anim.name, name) == 0) return i; } Con::errorf("Player::getAnimationID() -- Player does not contain a sequence that matches the name, %s.", name); return BAD_ANIM_ID; } U32 Player::playAnimationByID(U32 anim_id, F32 pos, F32 rate, F32 trans, bool hold, bool wait, bool is_death_anim) { if (anim_id == BAD_ANIM_ID) return 0; S32 seq_id = mDataBlock->actionList[anim_id].sequence; if (seq_id == -1) { Con::errorf("Player::playAnimation() problem. BAD_SEQ_ID"); return 0; } if (mShapeInstance->getShape()->sequences[seq_id].isBlend()) return playBlendAnimation(seq_id, pos, rate); if (isClientObject()) { PlayerData::ActionAnimation &anim = mDataBlock->actionList[anim_id]; if (anim.sequence != -1) { mActionAnimation.action = anim_id; mActionAnimation.forward = (rate >= 0); mActionAnimation.firstPerson = false; mActionAnimation.holdAtEnd = hold; mActionAnimation.waitForEnd = hold? true: wait; mActionAnimation.animateOnServer = false; mActionAnimation.atEnd = false; mActionAnimation.delayTicks = (S32)sNewAnimationTickTime; F32 transTime = (trans < 0) ? sAnimationTransitionTime : trans; mShapeInstance->setTimeScale(mActionAnimation.thread, rate); mShapeInstance->transitionToSequence(mActionAnimation.thread,anim.sequence, pos, transTime, true); } } if (is_death_anim) anim_clip_flags |= IS_DEATH_ANIM; else anim_clip_flags &= ~IS_DEATH_ANIM; anim_clip_flags |= ANIM_OVERRIDDEN; last_anim_tag = unique_anim_tag_counter++; last_anim_id = anim_id; return last_anim_tag; } F32 Player::getAnimationDurationByID(U32 anim_id) { if (anim_id == BAD_ANIM_ID) return 0.0f; S32 seq_id = mDataBlock->actionList[anim_id].sequence; if (seq_id >= 0 && seq_id < mDataBlock->mShape->sequences.size()) return mDataBlock->mShape->sequences[seq_id].duration; return 0.0f; } bool Player::isBlendAnimation(const char* name) { U32 anim_id = getAnimationID(name); if (anim_id == BAD_ANIM_ID) return false; S32 seq_id = mDataBlock->actionList[anim_id].sequence; if (seq_id >= 0 && seq_id < mDataBlock->mShape->sequences.size()) return mDataBlock->mShape->sequences[seq_id].isBlend(); return false; } const char* Player::getLastClipName(U32 clip_tag) { if (clip_tag != last_anim_tag || last_anim_id >= PlayerData::NumActionAnims) return ""; return mDataBlock->actionList[last_anim_id].name; } void Player::unlockAnimation(U32 tag, bool force) { if ((tag != 0 && tag == last_anim_lock_tag) || force) anim_clip_flags &= ~BLOCK_USER_CONTROL; } U32 Player::lockAnimation() { anim_clip_flags |= BLOCK_USER_CONTROL; last_anim_lock_tag = unique_anim_tag_counter++; return last_anim_lock_tag; } DefineEngineMethod(Player, isAnimationLocked, bool, (),, "") { return object->isAnimationLocked(); } void Player::setLookAnimationOverride(bool flag) { overrideLookAnimation = flag; #if 0 setMaskBits(LookOverrideMask); #else setMaskBits(ActionMask); #endif } DefineEngineMethod(Player, setLookAnimationOverride, void, (bool flag),, "") { object->setLookAnimationOverride(flag); } DefineEngineMethod(Player, copyHeadRotation, void, (Player* other_player),, "") { if (other_player) object->copyHeadRotation(other_player); } void Player::process_client_triggers(bool triggeredLeft, bool triggeredRight) { bool mark_landing = false; Point3F my_vel = getVelocity(); if (my_vel.z > 5.0f) z_velocity = 1; else if (my_vel.z < -5.0f) z_velocity = -1; else { if (z_velocity < 0) mark_landing = true; z_velocity = 0.0f; } fx_c_triggers = mark_fx_c_triggers; if (triggeredLeft) fx_c_triggers |= PLAYER_LF_FOOT_C_TRIGGER; if (triggeredRight) fx_c_triggers |= PLAYER_RT_FOOT_C_TRIGGER; if (mark_landing) fx_c_triggers |= PLAYER_LANDING_C_TRIGGER; if (idle_timer > 10.0f) { fx_c_triggers |= PLAYER_IDLE_C_TRIGGER; idle_timer = 0.0f; } if (fx_c_triggers & PLAYER_LANDING_S_TRIGGER) { fx_c_triggers &= ~(PLAYER_LANDING_S_TRIGGER); } } U32 Player::unique_movement_tag_counter = 1; void Player::setMovementSpeedBias(F32 bias) { speed_bias_goal = bias; } U32 Player::setMovementOverride(F32 bias, const Point3F* mov, U32 op) { if (mov) { movement_data = *mov; override_movement = true; movement_op = (U8)op; } else override_movement = false; speed_bias_goal = bias; last_movement_tag = unique_movement_tag_counter++; return last_movement_tag; } void Player::restoreMovement(U32 tag) { if (tag != 0 && tag == last_movement_tag) { speed_bias_goal = 1.0; override_movement = false; } } DefineEngineMethod(Player, setMovementSpeedBias, void, (F32 bias),, "setMovementSpeedBias(F32 bias)") { object->setMovementSpeedBias(bias); } void Player::overrideFootfallFX(bool decals, bool sounds, bool dust) { if (decals) footfallDecalOverride++; if (sounds) footfallSoundOverride++; if (dust) footfallDustOverride++; noFootfallFX = (footfallDecalOverride > 0 && footfallSoundOverride > 0 && footfallDustOverride > 0); } void Player::restoreFootfallFX(bool decals, bool sounds, bool dust) { if (decals && footfallDecalOverride) footfallDecalOverride--; if (sounds && footfallSoundOverride) footfallSoundOverride--; if (dust && footfallDustOverride) footfallDustOverride--; noFootfallFX = (footfallDecalOverride > 0 && footfallSoundOverride > 0 && footfallDustOverride > 0); } #ifdef TORQUE_OPENVR void Player::setControllers(Vector<OpenVRTrackedObject*> controllerList) { mControllers[0] = controllerList.size() > 0 ? controllerList[0] : NULL; mControllers[1] = controllerList.size() > 1 ? controllerList[1] : NULL; } DefineEngineMethod(Player, setVRControllers, void, (OpenVRTrackedObject* controllerL, OpenVRTrackedObject* controllerR,, "") { Vector<OpenVRTrackedObject*> list; if (controllerL) { list.push_back(controllerL); } else { list.push_back(NULL); } if (controllerR) { list.push_back(controllerR); } else { list.push_back(NULL); } object->setControllers(list); } #endif
/* =========================================================================== Daemon BSD Source Code Copyright (c) 2013-2014, Daemon Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Daemon developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAEMON DEVELOPERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================== */ #include "../qcommon/q_shared.h" #include "../qcommon/qcommon.h" #include "../../common/Log.h" #include "VirtualMachine.h" #include "../sys/sys_loadlib.h" #ifdef _WIN32 #include <windows.h> #undef CopyFile #else #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <sys/wait.h> #ifdef __linux__ #include <sys/prctl.h> #endif #endif // File handle for the root socket #define ROOT_SOCKET_FD 100 // MinGW doesn't define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #ifndef JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 0x2000 #endif // On windows use _snprintf instead of snprintf #ifdef _WIN32 #define snprintf _snprintf #endif namespace VM { // Windows equivalent of strerror #ifdef _WIN32 static std::string Win32StrError(uint32_t error) { std::string out; char* message; if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<char *>(&message), 0, NULL)) { out = message; LocalFree(message); } else out = Str::Format("Unknown error 0x%08lx", error); return out; } #endif // Platform-specific code to load a module static std::pair<IPC::OSHandleType, IPC::Socket> InternalLoadModule(std::pair<IPC::Socket, IPC::Socket> pair, const char* const* args, bool reserve_mem) { #ifdef _WIN32 // Inherit the socket in the child process if (!SetHandleInformation(pair.second.GetHandle(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) Com_Error(ERR_DROP, "VM: Could not make socket inheritable: %s", Win32StrError(GetLastError()).c_str()); // Escape command line arguments std::string cmdline; for (int i = 0; args[i]; i++) { if (i != 0) cmdline += " "; // Enclose parameter in quotes cmdline += "\""; int num_slashes = 0; for (int j = 0; true; j++) { char c = args[i][j]; if (c == '\\') num_slashes++; else if (c == '\"' || c == '\0') { // Backlashes before a quote must be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\\\"; num_slashes = 0; if (c == '\"') cmdline += "\\\""; else break; } else { // Backlashes before any other character must not be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\"; num_slashes = 0; cmdline.push_back(c); } } cmdline += "\""; } // Convert command line to UTF-16 and add a NUL terminator std::wstring wcmdline = Str::UTF8To16(cmdline) + L"\0"; // Create a job object to ensure the process is terminated if the parent dies HANDLE job = CreateJobObject(NULL, NULL); if (!job) Com_Error(ERR_DROP, "VM: Could not create job object: %s", Win32StrError(GetLastError()).c_str()); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli; memset(&jeli, 0, sizeof(jeli)); jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli))) Com_Error(ERR_DROP, "VM: Could not set job object information: %s", Win32StrError(GetLastError()).c_str()); STARTUPINFOW startupInfo; PROCESS_INFORMATION processInfo; memset(&startupInfo, 0, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); if (!CreateProcessW(NULL, &wcmdline[0], NULL, NULL, TRUE, CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB | DETACHED_PROCESS, NULL, NULL, &startupInfo, &processInfo)) { CloseHandle(job); Com_Error(ERR_DROP, "VM: Could create child process: %s", Win32StrError(GetLastError()).c_str()); } if (!AssignProcessToJobObject(job, processInfo.hProcess)) { TerminateProcess(processInfo.hProcess, 0); CloseHandle(job); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); Com_Error(ERR_DROP, "VM: Could not assign process to job object: %s", Win32StrError(GetLastError()).c_str()); } #ifndef _WIN64 // Attempt to reserve 1GB of address space for the NaCl sandbox if (reserve_mem) VirtualAllocEx(processInfo.hProcess, NULL, 1 << 30, MEM_RESERVE, PAGE_NOACCESS); #endif ResumeThread(processInfo.hThread); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); return std::make_pair(job, std::move(pair.first)); #else Q_UNUSED(reserve_mem); // Create a pipe to report errors from the child process int pipefds[2]; if (pipe(pipefds) == -1 || fcntl(pipefds[1], F_SETFD, FD_CLOEXEC)) Com_Error(ERR_DROP, "VM: Failed to create pipe: %s", strerror(errno)); int pid = fork(); if (pid == -1) Com_Error(ERR_DROP, "VM: Failed to fork process: %s", strerror(errno)); if (pid == 0) { // Close the other end of the pipe close(pipefds[0]); // Explicitly destroy the local socket, since destructors are not called pair.first.Close(); // This seems to be required, otherwise killing the child process will // also kill the parent process. setsid(); #ifdef __linux__ // Kill child process if the parent dies. This avoid left-over processes // when using the debug stub. Sadly it is Linux-only. prctl(PR_SET_PDEATHSIG, SIGKILL); #endif // Close standard input/output descriptors // stderr is not closed so that we can see error messages reported by sel_ldr close(0); close(1); // Load the target executable char* env[] = {nullptr}; execve(args[0], const_cast<char* const*>(args), env); // If the exec fails, return errno to the parent through the pipe write(pipefds[1], &errno, sizeof(int)); _exit(-1); } // Try to read from the pipe to see if the child successfully exec'd close(pipefds[1]); ssize_t count; int err; while ((count = read(pipefds[0], &err, sizeof(int))) == -1) { if (errno != EAGAIN && errno != EINTR) break; } close(pipefds[0]); if (count) { waitpid(pid, NULL, 0); Com_Error(ERR_DROP, "VM: Failed to exec: %s", strerror(err)); } return std::make_pair(pid, std::move(pair.first)); #endif } std::pair<IPC::OSHandleType, IPC::Socket> CreateNaClVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, bool debug, bool extract, bool debugLoader) { // Generate command line const std::string& libPath = FS::GetLibPath(); std::vector<const char*> args; char rootSocketRedir[32]; std::string module, sel_ldr, irt, bootstrap, modulePath, loaderLogFile; // Extract the nexe from the pak so that sel_ldr can load it module = name + "-" ARCH_STRING ".nexe"; if (extract) { try { FS::File out = FS::HomePath::OpenWrite(module); FS::PakPath::CopyFile(module, out); out.Close(); } catch (std::system_error& err) { Com_Error(ERR_DROP, "VM: Failed to extract VM module %s: %s\n", module.c_str(), err.what()); } modulePath = FS::Path::Build(FS::GetHomePath(), module); } else modulePath = FS::Path::Build(libPath, module); snprintf(rootSocketRedir, sizeof(rootSocketRedir), "%d:%d", ROOT_SOCKET_FD, (int)(intptr_t)pair.second.GetHandle()); irt = FS::Path::Build(libPath, "irt_core-" ARCH_STRING ".nexe"); // On Windows, even if we are running a 32-bit engine, we must use the // 64-bit sel_ldr if the host operating system is 64-bit. #if defined(_WIN32) && !defined(_WIN64) SYSTEM_INFO systemInfo; GetNativeSystemInfo(&systemInfo); if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) sel_ldr = FS::Path::Build(libPath, "sel_ldr64" EXE_EXT); else sel_ldr = FS::Path::Build(libPath, "sel_ldr" EXE_EXT); #else sel_ldr = FS::Path::Build(libPath, "sel_ldr" EXE_EXT); #endif #ifdef __linux__ bootstrap = FS::Path::Build(libPath, "nacl_helper_bootstrap"); args.push_back(bootstrap.c_str()); args.push_back(sel_ldr.c_str()); args.push_back("--r_debug=0xXXXXXXXXXXXXXXXX"); args.push_back("--reserved_at_zero=0xXXXXXXXXXXXXXXXX"); #else Q_UNUSED(bootstrap); args.push_back(sel_ldr.c_str()); #endif if (debug) { args.push_back("-g"); } if (debugLoader) { loaderLogFile = FS::Path::Build(FS::GetHomePath(), name + ".sel_ldr.log"); args.push_back("-vvvv"); args.push_back("-l"); args.push_back(loaderLogFile.c_str()); } args.push_back("-B"); args.push_back(irt.c_str()); args.push_back("-e"); args.push_back("-i"); args.push_back(rootSocketRedir); args.push_back("--"); args.push_back(modulePath.c_str()); args.push_back(XSTRING(ROOT_SOCKET_FD)); args.push_back(NULL); Com_Printf("Loading VM module %s...\n", module.c_str()); if (debugLoader) { std::string commandLine; for (auto arg : args) { if (arg) { commandLine += " "; commandLine += arg; } } Com_Printf("Using loader args: %s", commandLine.c_str()); } return InternalLoadModule(std::move(pair), args.data(), true); } std::pair<IPC::OSHandleType, IPC::Socket> CreateNativeVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, bool debug) { const std::string& libPath = FS::GetLibPath(); std::vector<const char*> args; std::string handleArg = std::to_string((int)(intptr_t)pair.second.GetHandle()); std::string module = FS::Path::Build(libPath, name + "-nacl-native-exe" + EXE_EXT); if (debug) { args.push_back("/usr/bin/gdbserver"); args.push_back("localhost:4014"); } args.push_back(module.c_str()); args.push_back(handleArg.c_str()); args.push_back(NULL); Com_Printf("Loading VM module %s...\n", module.c_str()); return InternalLoadModule(std::move(pair), args.data(), true); } IPC::Socket CreateInProcessNativeVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, VM::VMBase::InProcessInfo& inProcess) { std::string filename = FS::Path::Build(FS::GetLibPath(), name + "-nacl-native-dll" + DLL_EXT); Com_Printf("Loading VM module %s...\n", filename.c_str()); void* handle = Sys_LoadLibrary(filename.c_str()); if (!handle) { Com_Error(ERR_DROP, "VM: Failed to load shared library VM %s: %s", filename.c_str(), Sys_LibraryError()); } inProcess.sharedLibHandle = handle; int (*vmMain)(int, const char**) = (int (*)(int, const char**))(Sys_LoadFunction(handle, "main")); if (!vmMain) { Com_Error(ERR_DROP, "VM: Could not find main function in shared library VM %s", filename.c_str()); } std::string vmSocketArg = std::to_string((int)(intptr_t)pair.second.ReleaseHandle()); inProcess.running = true; inProcess.thread = std::thread([vmMain, vmSocketArg, &inProcess]() { const char* args[2] = {"vm", vmSocketArg.c_str()}; vmMain(2, args); std::lock_guard<std::mutex> lock(inProcess.mutex); inProcess.running = false; inProcess.condition.notify_one(); }); return std::move(pair.first); } int VMBase::Create() { type = static_cast<vmType_t>(params.vmType.Get()); if (type < 0 || type >= TYPE_END) Com_Error(ERR_DROP, "VM: Invalid type %d", type); int loadStartTime = Sys_Milliseconds(); // Free the VM if it exists Free(); // Open the syscall log if (params.logSyscalls.Get()) { std::string filename = name + ".syscallLog"; try { syscallLogFile = FS::RawPath::OpenWrite(filename); } catch (std::system_error& error) { Log::Warn("Couldn't open %s", filename); } } // Create the socket pair to get the handle for ROOT_SOCKET std::pair<IPC::Socket, IPC::Socket> pair = IPC::Socket::CreatePair(); IPC::Socket rootSocket; if (type == TYPE_NACL || type == TYPE_NACL_DEBUG || type == TYPE_NACL_LIBPATH || type == TYPE_NACL_LIBPATH_DEBUG) { std::tie(processHandle, rootSocket) = CreateNaClVM(std::move(pair), name, type == TYPE_NACL_DEBUG || type == TYPE_NACL_LIBPATH_DEBUG, type == TYPE_NACL || type == TYPE_NACL_DEBUG, params.debugLoader.Get()); } else if (type == TYPE_NATIVE_EXE || type == TYPE_NATIVE_EXE_DEBUG) { std::tie(processHandle, rootSocket) = CreateNativeVM(std::move(pair), name, type == TYPE_NATIVE_EXE_DEBUG); } else { rootSocket = CreateInProcessNativeVM(std::move(pair), name, inProcess); } rootChannel = IPC::Channel(std::move(rootSocket)); if (type == TYPE_NACL_DEBUG || type == TYPE_NATIVE_EXE_DEBUG || type == TYPE_NACL_LIBPATH_DEBUG) Com_Printf("Waiting for GDB connection on localhost:4014\n"); // Read the ABI version from the root socket. // If this fails, we assume the remote process failed to start IPC::Reader reader = rootChannel.RecvMsg(); Com_Printf("Loaded VM module in %d msec\n", Sys_Milliseconds() - loadStartTime); return reader.Read<uint32_t>(); } void VMBase::FreeInProcessVM() { if (inProcess.thread.joinable()) { bool wait = true; if (inProcess.running) { std::unique_lock<std::mutex> lock(inProcess.mutex); auto status = inProcess.condition.wait_for(lock, std::chrono::milliseconds(500)); if (status == std::cv_status::timeout) { wait = false; } } if (wait) { Com_Printf("Waiting for the VM thread...\n"); inProcess.thread.join(); } else { Com_Printf("The VM thread doesn't seem to stop, detaching it (bad things WILL ensue)\n"); inProcess.thread.detach(); } } if (inProcess.sharedLibHandle) { Sys_UnloadLibrary(inProcess.sharedLibHandle); inProcess.sharedLibHandle = nullptr; } inProcess.running = false; } void VMBase::LogMessage(bool vmToEngine, int id) { if (syscallLogFile) { int minor = id & 0xffff; int major = id >> 16; const char* direction = vmToEngine ? "V -> E" : "E -> V"; try { syscallLogFile.Printf("%s (%i, %i)\n", direction, major, minor); } catch (std::system_error& err) { Log::Warn("Error while writing the VM syscall log: %s", err.what()); } } } void VMBase::Free() { if (syscallLogFile) { std::error_code err; syscallLogFile.Close(err); } if (!IsActive()) return; rootChannel = IPC::Channel(); if (type == TYPE_NACL || type == TYPE_NACL_DEBUG || type == TYPE_NATIVE_EXE || type == TYPE_NATIVE_EXE_DEBUG) { #ifdef _WIN32 // Closing the job object should kill the child process CloseHandle(processHandle); #else kill(processHandle, SIGKILL); waitpid(processHandle, NULL, 0); #endif processHandle = IPC::INVALID_HANDLE; } else if (type == TYPE_NATIVE_DLL) { FreeInProcessVM(); } } } // namespace VM Fix an error message /* =========================================================================== Daemon BSD Source Code Copyright (c) 2013-2014, Daemon Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Daemon developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAEMON DEVELOPERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================== */ #include "../qcommon/q_shared.h" #include "../qcommon/qcommon.h" #include "../../common/Log.h" #include "VirtualMachine.h" #include "../sys/sys_loadlib.h" #ifdef _WIN32 #include <windows.h> #undef CopyFile #else #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <sys/wait.h> #ifdef __linux__ #include <sys/prctl.h> #endif #endif // File handle for the root socket #define ROOT_SOCKET_FD 100 // MinGW doesn't define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #ifndef JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 0x2000 #endif // On windows use _snprintf instead of snprintf #ifdef _WIN32 #define snprintf _snprintf #endif namespace VM { // Windows equivalent of strerror #ifdef _WIN32 static std::string Win32StrError(uint32_t error) { std::string out; char* message; if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<char *>(&message), 0, NULL)) { out = message; LocalFree(message); } else out = Str::Format("Unknown error 0x%08lx", error); return out; } #endif // Platform-specific code to load a module static std::pair<IPC::OSHandleType, IPC::Socket> InternalLoadModule(std::pair<IPC::Socket, IPC::Socket> pair, const char* const* args, bool reserve_mem) { #ifdef _WIN32 // Inherit the socket in the child process if (!SetHandleInformation(pair.second.GetHandle(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) Com_Error(ERR_DROP, "VM: Could not make socket inheritable: %s", Win32StrError(GetLastError()).c_str()); // Escape command line arguments std::string cmdline; for (int i = 0; args[i]; i++) { if (i != 0) cmdline += " "; // Enclose parameter in quotes cmdline += "\""; int num_slashes = 0; for (int j = 0; true; j++) { char c = args[i][j]; if (c == '\\') num_slashes++; else if (c == '\"' || c == '\0') { // Backlashes before a quote must be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\\\"; num_slashes = 0; if (c == '\"') cmdline += "\\\""; else break; } else { // Backlashes before any other character must not be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\"; num_slashes = 0; cmdline.push_back(c); } } cmdline += "\""; } // Convert command line to UTF-16 and add a NUL terminator std::wstring wcmdline = Str::UTF8To16(cmdline) + L"\0"; // Create a job object to ensure the process is terminated if the parent dies HANDLE job = CreateJobObject(NULL, NULL); if (!job) Com_Error(ERR_DROP, "VM: Could not create job object: %s", Win32StrError(GetLastError()).c_str()); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli; memset(&jeli, 0, sizeof(jeli)); jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli))) Com_Error(ERR_DROP, "VM: Could not set job object information: %s", Win32StrError(GetLastError()).c_str()); STARTUPINFOW startupInfo; PROCESS_INFORMATION processInfo; memset(&startupInfo, 0, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); if (!CreateProcessW(NULL, &wcmdline[0], NULL, NULL, TRUE, CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB | DETACHED_PROCESS, NULL, NULL, &startupInfo, &processInfo)) { CloseHandle(job); Com_Error(ERR_DROP, "VM: Could not create child process: %s", Win32StrError(GetLastError()).c_str()); } if (!AssignProcessToJobObject(job, processInfo.hProcess)) { TerminateProcess(processInfo.hProcess, 0); CloseHandle(job); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); Com_Error(ERR_DROP, "VM: Could not assign process to job object: %s", Win32StrError(GetLastError()).c_str()); } #ifndef _WIN64 // Attempt to reserve 1GB of address space for the NaCl sandbox if (reserve_mem) VirtualAllocEx(processInfo.hProcess, NULL, 1 << 30, MEM_RESERVE, PAGE_NOACCESS); #endif ResumeThread(processInfo.hThread); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); return std::make_pair(job, std::move(pair.first)); #else Q_UNUSED(reserve_mem); // Create a pipe to report errors from the child process int pipefds[2]; if (pipe(pipefds) == -1 || fcntl(pipefds[1], F_SETFD, FD_CLOEXEC)) Com_Error(ERR_DROP, "VM: Failed to create pipe: %s", strerror(errno)); int pid = fork(); if (pid == -1) Com_Error(ERR_DROP, "VM: Failed to fork process: %s", strerror(errno)); if (pid == 0) { // Close the other end of the pipe close(pipefds[0]); // Explicitly destroy the local socket, since destructors are not called pair.first.Close(); // This seems to be required, otherwise killing the child process will // also kill the parent process. setsid(); #ifdef __linux__ // Kill child process if the parent dies. This avoid left-over processes // when using the debug stub. Sadly it is Linux-only. prctl(PR_SET_PDEATHSIG, SIGKILL); #endif // Close standard input/output descriptors // stderr is not closed so that we can see error messages reported by sel_ldr close(0); close(1); // Load the target executable char* env[] = {nullptr}; execve(args[0], const_cast<char* const*>(args), env); // If the exec fails, return errno to the parent through the pipe write(pipefds[1], &errno, sizeof(int)); _exit(-1); } // Try to read from the pipe to see if the child successfully exec'd close(pipefds[1]); ssize_t count; int err; while ((count = read(pipefds[0], &err, sizeof(int))) == -1) { if (errno != EAGAIN && errno != EINTR) break; } close(pipefds[0]); if (count) { waitpid(pid, NULL, 0); Com_Error(ERR_DROP, "VM: Failed to exec: %s", strerror(err)); } return std::make_pair(pid, std::move(pair.first)); #endif } std::pair<IPC::OSHandleType, IPC::Socket> CreateNaClVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, bool debug, bool extract, bool debugLoader) { // Generate command line const std::string& libPath = FS::GetLibPath(); std::vector<const char*> args; char rootSocketRedir[32]; std::string module, sel_ldr, irt, bootstrap, modulePath, loaderLogFile; // Extract the nexe from the pak so that sel_ldr can load it module = name + "-" ARCH_STRING ".nexe"; if (extract) { try { FS::File out = FS::HomePath::OpenWrite(module); FS::PakPath::CopyFile(module, out); out.Close(); } catch (std::system_error& err) { Com_Error(ERR_DROP, "VM: Failed to extract VM module %s: %s\n", module.c_str(), err.what()); } modulePath = FS::Path::Build(FS::GetHomePath(), module); } else modulePath = FS::Path::Build(libPath, module); snprintf(rootSocketRedir, sizeof(rootSocketRedir), "%d:%d", ROOT_SOCKET_FD, (int)(intptr_t)pair.second.GetHandle()); irt = FS::Path::Build(libPath, "irt_core-" ARCH_STRING ".nexe"); // On Windows, even if we are running a 32-bit engine, we must use the // 64-bit sel_ldr if the host operating system is 64-bit. #if defined(_WIN32) && !defined(_WIN64) SYSTEM_INFO systemInfo; GetNativeSystemInfo(&systemInfo); if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) sel_ldr = FS::Path::Build(libPath, "sel_ldr64" EXE_EXT); else sel_ldr = FS::Path::Build(libPath, "sel_ldr" EXE_EXT); #else sel_ldr = FS::Path::Build(libPath, "sel_ldr" EXE_EXT); #endif #ifdef __linux__ bootstrap = FS::Path::Build(libPath, "nacl_helper_bootstrap"); args.push_back(bootstrap.c_str()); args.push_back(sel_ldr.c_str()); args.push_back("--r_debug=0xXXXXXXXXXXXXXXXX"); args.push_back("--reserved_at_zero=0xXXXXXXXXXXXXXXXX"); #else Q_UNUSED(bootstrap); args.push_back(sel_ldr.c_str()); #endif if (debug) { args.push_back("-g"); } if (debugLoader) { loaderLogFile = FS::Path::Build(FS::GetHomePath(), name + ".sel_ldr.log"); args.push_back("-vvvv"); args.push_back("-l"); args.push_back(loaderLogFile.c_str()); } args.push_back("-B"); args.push_back(irt.c_str()); args.push_back("-e"); args.push_back("-i"); args.push_back(rootSocketRedir); args.push_back("--"); args.push_back(modulePath.c_str()); args.push_back(XSTRING(ROOT_SOCKET_FD)); args.push_back(NULL); Com_Printf("Loading VM module %s...\n", module.c_str()); if (debugLoader) { std::string commandLine; for (auto arg : args) { if (arg) { commandLine += " "; commandLine += arg; } } Com_Printf("Using loader args: %s", commandLine.c_str()); } return InternalLoadModule(std::move(pair), args.data(), true); } std::pair<IPC::OSHandleType, IPC::Socket> CreateNativeVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, bool debug) { const std::string& libPath = FS::GetLibPath(); std::vector<const char*> args; std::string handleArg = std::to_string((int)(intptr_t)pair.second.GetHandle()); std::string module = FS::Path::Build(libPath, name + "-nacl-native-exe" + EXE_EXT); if (debug) { args.push_back("/usr/bin/gdbserver"); args.push_back("localhost:4014"); } args.push_back(module.c_str()); args.push_back(handleArg.c_str()); args.push_back(NULL); Com_Printf("Loading VM module %s...\n", module.c_str()); return InternalLoadModule(std::move(pair), args.data(), true); } IPC::Socket CreateInProcessNativeVM(std::pair<IPC::Socket, IPC::Socket> pair, Str::StringRef name, VM::VMBase::InProcessInfo& inProcess) { std::string filename = FS::Path::Build(FS::GetLibPath(), name + "-nacl-native-dll" + DLL_EXT); Com_Printf("Loading VM module %s...\n", filename.c_str()); void* handle = Sys_LoadLibrary(filename.c_str()); if (!handle) { Com_Error(ERR_DROP, "VM: Failed to load shared library VM %s: %s", filename.c_str(), Sys_LibraryError()); } inProcess.sharedLibHandle = handle; int (*vmMain)(int, const char**) = (int (*)(int, const char**))(Sys_LoadFunction(handle, "main")); if (!vmMain) { Com_Error(ERR_DROP, "VM: Could not find main function in shared library VM %s", filename.c_str()); } std::string vmSocketArg = std::to_string((int)(intptr_t)pair.second.ReleaseHandle()); inProcess.running = true; inProcess.thread = std::thread([vmMain, vmSocketArg, &inProcess]() { const char* args[2] = {"vm", vmSocketArg.c_str()}; vmMain(2, args); std::lock_guard<std::mutex> lock(inProcess.mutex); inProcess.running = false; inProcess.condition.notify_one(); }); return std::move(pair.first); } int VMBase::Create() { type = static_cast<vmType_t>(params.vmType.Get()); if (type < 0 || type >= TYPE_END) Com_Error(ERR_DROP, "VM: Invalid type %d", type); int loadStartTime = Sys_Milliseconds(); // Free the VM if it exists Free(); // Open the syscall log if (params.logSyscalls.Get()) { std::string filename = name + ".syscallLog"; try { syscallLogFile = FS::RawPath::OpenWrite(filename); } catch (std::system_error& error) { Log::Warn("Couldn't open %s", filename); } } // Create the socket pair to get the handle for ROOT_SOCKET std::pair<IPC::Socket, IPC::Socket> pair = IPC::Socket::CreatePair(); IPC::Socket rootSocket; if (type == TYPE_NACL || type == TYPE_NACL_DEBUG || type == TYPE_NACL_LIBPATH || type == TYPE_NACL_LIBPATH_DEBUG) { std::tie(processHandle, rootSocket) = CreateNaClVM(std::move(pair), name, type == TYPE_NACL_DEBUG || type == TYPE_NACL_LIBPATH_DEBUG, type == TYPE_NACL || type == TYPE_NACL_DEBUG, params.debugLoader.Get()); } else if (type == TYPE_NATIVE_EXE || type == TYPE_NATIVE_EXE_DEBUG) { std::tie(processHandle, rootSocket) = CreateNativeVM(std::move(pair), name, type == TYPE_NATIVE_EXE_DEBUG); } else { rootSocket = CreateInProcessNativeVM(std::move(pair), name, inProcess); } rootChannel = IPC::Channel(std::move(rootSocket)); if (type == TYPE_NACL_DEBUG || type == TYPE_NATIVE_EXE_DEBUG || type == TYPE_NACL_LIBPATH_DEBUG) Com_Printf("Waiting for GDB connection on localhost:4014\n"); // Read the ABI version from the root socket. // If this fails, we assume the remote process failed to start IPC::Reader reader = rootChannel.RecvMsg(); Com_Printf("Loaded VM module in %d msec\n", Sys_Milliseconds() - loadStartTime); return reader.Read<uint32_t>(); } void VMBase::FreeInProcessVM() { if (inProcess.thread.joinable()) { bool wait = true; if (inProcess.running) { std::unique_lock<std::mutex> lock(inProcess.mutex); auto status = inProcess.condition.wait_for(lock, std::chrono::milliseconds(500)); if (status == std::cv_status::timeout) { wait = false; } } if (wait) { Com_Printf("Waiting for the VM thread...\n"); inProcess.thread.join(); } else { Com_Printf("The VM thread doesn't seem to stop, detaching it (bad things WILL ensue)\n"); inProcess.thread.detach(); } } if (inProcess.sharedLibHandle) { Sys_UnloadLibrary(inProcess.sharedLibHandle); inProcess.sharedLibHandle = nullptr; } inProcess.running = false; } void VMBase::LogMessage(bool vmToEngine, int id) { if (syscallLogFile) { int minor = id & 0xffff; int major = id >> 16; const char* direction = vmToEngine ? "V -> E" : "E -> V"; try { syscallLogFile.Printf("%s (%i, %i)\n", direction, major, minor); } catch (std::system_error& err) { Log::Warn("Error while writing the VM syscall log: %s", err.what()); } } } void VMBase::Free() { if (syscallLogFile) { std::error_code err; syscallLogFile.Close(err); } if (!IsActive()) return; rootChannel = IPC::Channel(); if (type == TYPE_NACL || type == TYPE_NACL_DEBUG || type == TYPE_NATIVE_EXE || type == TYPE_NATIVE_EXE_DEBUG) { #ifdef _WIN32 // Closing the job object should kill the child process CloseHandle(processHandle); #else kill(processHandle, SIGKILL); waitpid(processHandle, NULL, 0); #endif processHandle = IPC::INVALID_HANDLE; } else if (type == TYPE_NATIVE_DLL) { FreeInProcessVM(); } } } // namespace VM
/** * @author : xiaozhuai * @date : 17/3/20 */ #include "AccessRule.h" AccessRule AccessRule::instance; void AccessRule::loadAccessRule() { string ruleFileName = SERV_ENV.getConfig(KEY_ACCESS_RULE, DEFAULT_ACCESS_RULE); /** * denied .efserv_access and .efserv_config by default */ rules.push_back(Rule(false, ".efserv_config")); rules.push_back(Rule(false, ruleFileName)); string rulePath = SERV_ENV.getAbsoluteWebRoot() + "/" + ruleFileName; FileHandler ruleFile(rulePath); string ruleText = ruleFile.readAsText(); /** * first split by "\n" */ vector<string> lines = StringUtils::split(ruleText, "\n"); /** * parse each line */ for(int i=0; i<lines.size(); i++){ string line = lines[i]; /** * trim line */ trim(line, " "); /** * skip empty line */ if(line.size()==0) continue; /** * skip comment line */ if(line[0]=='#') continue; /** * split by '#' to avoid in-line comment */ vector<string> tmp = StringUtils::split(line, "#", 2); string ruleBody = tmp[0]; trim(ruleBody, " "); if(ruleBody.size()<3){ LOGW("Access rule not recognized, file: %s, line: %d, %s", rulePath, (i+1), ruleBody); continue; } bool permitted; switch (ruleBody[0]){ case '+': permitted = true; break; case '-': permitted = false; break; default: LOGW("Access rule not recognized, file: %s, line: %d, %s", rulePath, (i+1), ruleBody); continue; } if(ruleBody[1]==' '){ string pattern = ruleBody.substr(2); rules.push_back(Rule(permitted, pattern)); LOGD("Access rule recognized, permitted: %s, pattern: %s", permitted?"yes":"no", pattern); }else{ LOGW("Access rule not recognized, file: %s, line: %d, %s", rulePath, (i+1), ruleBody); } } } bool AccessRule::permissible(string url) { bool permitted = true; /** * go through all rules, the last matched rule will be effective */ for(int i=0; i<rules.size(); i++){ regex r(rules[i].pattern); if(regex_match(url, r)) permitted = rules[i].permitted; } return permitted; } fix bug in AccessRule.cpp /** * @author : xiaozhuai * @date : 17/3/20 */ #include "AccessRule.h" AccessRule AccessRule::instance; void AccessRule::loadAccessRule() { string ruleFileName = SERV_ENV.getConfig(KEY_ACCESS_RULE, DEFAULT_ACCESS_RULE); /** * denied .efserv_access and .efserv_config by default */ rules.push_back(Rule(false, "/.efserv_config")); rules.push_back(Rule(false, "/"+ruleFileName)); string rulePath = SERV_ENV.getAbsoluteWebRoot() + "/" + ruleFileName; FileHandler ruleFile(rulePath); string ruleText = ruleFile.readAsText(); /** * first split by "\n" */ vector<string> lines = StringUtils::split(ruleText, "\n"); /** * parse each line */ for(int i=0; i<lines.size(); i++){ string line = lines[i]; /** * trim line */ trim(line, " "); /** * skip empty line */ if(line.size()==0) continue; /** * skip comment line */ if(line[0]=='#') continue; /** * split by '#' to avoid in-line comment */ vector<string> tmp = StringUtils::split(line, "#", 2); string ruleBody = tmp[0]; trim(ruleBody, " "); if(ruleBody.size()<3){ LOGW("Access rule not recognized, file: %s, line: %d, %s", rulePath, (i+1), ruleBody); continue; } bool permitted; switch (ruleBody[0]){ case '+': permitted = true; break; case '-': permitted = false; break; default: LOGW("Access rule not recognized, file: %s, line: %d, %s", rulePath, (i+1), ruleBody); continue; } if(ruleBody[1]==' '){ string pattern = ruleBody.substr(2); rules.push_back(Rule(permitted, pattern)); LOGD("Access rule recognized, permitted: %s, pattern: %s", permitted?"yes":"no", pattern); }else{ LOGW("Access rule not recognized, file: %s, line: %d, %s", rulePath, (i+1), ruleBody); } } } bool AccessRule::permissible(string url) { bool permitted = true; /** * go through all rules, the last matched rule will be effective */ for(int i=0; i<rules.size(); i++){ regex r(rules[i].pattern); if(regex_match(url, r)) permitted = rules[i].permitted; } return permitted; }
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ChartModel_Persistence.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:32:47 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "ChartModel.hxx" #include "ImplChartModel.hxx" #include "MediaDescriptorHelper.hxx" #include "ChartDebugTrace.hxx" #include "macros.hxx" #include "ChartViewHelper.hxx" #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_ #include <com/sun/star/document/XExporter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_ #include <com/sun/star/document/XImporter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_ #include <com/sun/star/document/XFilter.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_ #include <com/sun/star/embed/ElementModes.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_ #include <com/sun/star/embed/XStorage.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_ #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #ifndef _UCBHELPER_CONTENT_HXX #include <ucbhelper/content.hxx> #endif #ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX #include <unotools/ucbstreamhelper.hxx> #endif #ifndef _SV_CVTGRF_HXX #include <vcl/cvtgrf.hxx> #endif #ifndef _COMPHELPER_STORAGEHELPER_HXX #include <comphelper/storagehelper.hxx> #endif #include <algorithm> #include <functional> using namespace ::com::sun::star; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::rtl::OUString; using ::osl::MutexGuard; namespace { struct lcl_PropNameEquals : public ::std::unary_function< beans::PropertyValue, bool > { lcl_PropNameEquals( const OUString & rStrToCompareWith ) : m_aStr( rStrToCompareWith ) {} bool operator() ( const beans::PropertyValue & rProp ) { return rProp.Name.equals( m_aStr ); } private: OUString m_aStr; }; template< typename T > T lcl_getProperty( const Sequence< beans::PropertyValue > & rMediaDescriptor, const OUString & rPropName ) { T aResult; if( rMediaDescriptor.getLength()) { OUString aPropName( rPropName ); const beans::PropertyValue * pIt = rMediaDescriptor.getConstArray(); const beans::PropertyValue * pEndIt = pIt + + rMediaDescriptor.getLength(); pIt = ::std::find_if( pIt, pEndIt, lcl_PropNameEquals( aPropName )); if( pIt != pEndIt ) (*pIt).Value >>= aResult; } return aResult; } void lcl_addStorageToMediaDescriptor( Sequence< beans::PropertyValue > & rOutMD, const Reference< embed::XStorage > & xStorage ) { rOutMD.realloc( rOutMD.getLength() + 1 ); rOutMD[rOutMD.getLength() - 1] = beans::PropertyValue( C2U("Storage"), -1, uno::makeAny( xStorage ), beans::PropertyState_DIRECT_VALUE ); } Reference< embed::XStorage > lcl_createStorage( const OUString & rURL, const Reference< uno::XComponentContext > & xContext, const Sequence< beans::PropertyValue > & rMediaDescriptor ) { // create new storage Reference< embed::XStorage > xStorage; if( !xContext.is()) return xStorage; try { Reference< io::XStream > xStream( ::ucb::Content( rURL, Reference< ::com::sun::star::ucb::XCommandEnvironment >()).openStream(), uno::UNO_QUERY ); Reference< lang::XSingleServiceFactory > xStorageFact( xContext->getServiceManager()->createInstanceWithContext( C2U("com.sun.star.embed.StorageFactory"), xContext ), uno::UNO_QUERY_THROW ); Sequence< uno::Any > aStorageArgs( 3 ); aStorageArgs[0] <<= xStream; aStorageArgs[1] <<= embed::ElementModes::READWRITE; aStorageArgs[2] <<= rMediaDescriptor; xStorage.set( xStorageFact->createInstanceWithArguments( aStorageArgs ), uno::UNO_QUERY_THROW ); OSL_ENSURE( xStorage.is(), "No Storage" ); } catch( ::com::sun::star::ucb::ContentCreationException & rEx ) { ASSERT_EXCEPTION( rEx ); } return xStorage; } } // anonymous namespace namespace chart { Reference< document::XFilter > ChartModel::impl_createFilter( const Sequence< beans::PropertyValue > & rMediaDescriptor ) { Reference< document::XFilter > xFilter; // find FilterName in MediaDescriptor OUString aFilterName( lcl_getProperty< OUString >( rMediaDescriptor, OUString::createFromAscii("FilterName"))); // if FilterName was found, get Filter from factory if( aFilterName.getLength() > 0 ) { try { Reference< container::XNameAccess > xFilterFact( m_xContext->getServiceManager()->createInstanceWithContext( C2U( "com.sun.star.document.FilterFactory" ), m_xContext ), uno::UNO_QUERY_THROW ); uno::Any aFilterProps( xFilterFact->getByName( aFilterName )); Sequence< beans::PropertyValue > aProps; if( aFilterProps.hasValue() && (aFilterProps >>= aProps)) { OUString aFilterServiceName( lcl_getProperty< OUString >( aProps, OUString::createFromAscii("FilterService"))); if( aFilterServiceName.getLength()) { xFilter.set( m_xContext->getServiceManager()->createInstanceWithContext( aFilterServiceName, m_xContext ), uno::UNO_QUERY_THROW ); OSL_TRACE( "Filter found for service %s", U2C( aFilterServiceName )); } } } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } OSL_ENSURE( xFilter.is(), "Filter not found via factory" ); } // fall-back: create XML-Filter if( ! xFilter.is()) { OSL_TRACE( "No FilterName passed in MediaDescriptor" ); xFilter.set( m_xContext->getServiceManager()->createInstanceWithContext( C2U("com.sun.star.comp.chart2.XMLFilter"), m_xContext ), uno::UNO_QUERY_THROW ); } return xFilter; } //----------------------------------------------------------------- // frame::XStorable2 //----------------------------------------------------------------- void SAL_CALL ChartModel::storeSelf( const Sequence< beans::PropertyValue >& rMediaDescriptor ) throw (lang::IllegalArgumentException, io::IOException, uno::RuntimeException) { // only some parameters are allowed (see also SfxBaseModel) // "VersionComment", "Author", "InteractionHandler", "StatusIndicator" // However, they are ignored here. They would become interesting when // charts support a standalone format again. impl_store( rMediaDescriptor, m_xStorage ); } //----------------------------------------------------------------- // frame::XStorable (base of XStorable2) //----------------------------------------------------------------- sal_Bool SAL_CALL ChartModel::hasLocation() throw(uno::RuntimeException) { //@todo guard return m_aResource.getLength()!=0; } ::rtl::OUString SAL_CALL ChartModel::getLocation() throw(uno::RuntimeException) { return impl_g_getLocation(); } sal_Bool SAL_CALL ChartModel::isReadonly() throw(uno::RuntimeException) { //@todo guard return m_bReadOnly; } void SAL_CALL ChartModel::store() throw(io::IOException, uno::RuntimeException) { apphelper::LifeTimeGuard aGuard(m_aLifeTimeManager); if(!aGuard.startApiCall(sal_True)) //start LongLastingCall return; //behave passive if already disposed or closed or throw exception @todo? ::rtl::OUString aLocation = m_aResource; if( aLocation.getLength() == 0 ) throw io::IOException( C2U( "no location specified" ), static_cast< ::cppu::OWeakObject* >(this)); //@todo check wether aLocation is something like private:factory... if( m_bReadOnly ) throw io::IOException( C2U( "document is read only" ), static_cast< ::cppu::OWeakObject* >(this)); aGuard.clear(); // store impl_store( m_aMediaDescriptor, m_xStorage ); } void SAL_CALL ChartModel::storeAsURL( const ::rtl::OUString& rURL, const uno::Sequence< beans::PropertyValue >& rMediaDescriptor ) throw(io::IOException, uno::RuntimeException) { apphelper::LifeTimeGuard aGuard(m_aLifeTimeManager); if(!aGuard.startApiCall(sal_True)) //start LongLastingCall return; //behave passive if already disposed or closed or throw exception @todo? apphelper::MediaDescriptorHelper aMediaDescriptorHelper(rMediaDescriptor); uno::Sequence< beans::PropertyValue > aReducedMediaDescriptor( aMediaDescriptorHelper.getReducedForModel() ); m_bReadOnly = sal_False; aGuard.clear(); // create new storage Reference< embed::XStorage > xStorage( lcl_createStorage( rURL, m_xContext, aReducedMediaDescriptor )); if( xStorage.is()) { impl_store( aReducedMediaDescriptor, xStorage ); attachResource( rURL, aReducedMediaDescriptor ); } } void SAL_CALL ChartModel::storeToURL( const ::rtl::OUString& rURL, const uno::Sequence< beans::PropertyValue >& rMediaDescriptor ) throw(io::IOException, uno::RuntimeException) { apphelper::LifeTimeGuard aGuard(m_aLifeTimeManager); if(!aGuard.startApiCall(sal_True)) //start LongLastingCall return; //behave passive if already disposed or closed or throw exception @todo? //do not change the internal state of the document here //... aGuard.clear(); apphelper::MediaDescriptorHelper aMediaDescriptorHelper(rMediaDescriptor); uno::Sequence< beans::PropertyValue > aReducedMediaDescriptor( aMediaDescriptorHelper.getReducedForModel() ); if( rURL.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("private:stream"))) { try { if( m_xContext.is() && aMediaDescriptorHelper.ISSET_OutputStream ) { Reference< lang::XMultiServiceFactory > xFact( m_xContext->getServiceManager(), uno::UNO_QUERY_THROW ); Reference< io::XStream > xStream( xFact->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.TempFile"))), uno::UNO_QUERY_THROW ); Reference< io::XInputStream > xInputStream( xStream->getInputStream()); Reference< embed::XStorage > xStorage( ::comphelper::OStorageHelper::GetStorageFromStream( xStream, embed::ElementModes::READWRITE, xFact )); if( xStorage.is()) { impl_store( aReducedMediaDescriptor, xStorage ); Reference< io::XSeekable > xSeekable( xStream, uno::UNO_QUERY_THROW ); xSeekable->seek( 0 ); ::comphelper::OStorageHelper::CopyInputToOutput( xInputStream, aMediaDescriptorHelper.OutputStream ); } } } catch( const uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } else { // create new storage Reference< embed::XStorage > xStorage( lcl_createStorage( rURL, m_xContext, aReducedMediaDescriptor )); if( xStorage.is()) impl_store( aReducedMediaDescriptor, xStorage ); } } void ChartModel::impl_store( const Sequence< beans::PropertyValue >& rMediaDescriptor, const Reference< embed::XStorage > & xStorage ) { Reference< document::XFilter > xFilter( impl_createFilter( rMediaDescriptor)); if( xFilter.is() && xStorage.is()) { Sequence< beans::PropertyValue > aMD( rMediaDescriptor ); lcl_addStorageToMediaDescriptor( aMD, xStorage ); try { Reference< document::XExporter > xExporter( xFilter, uno::UNO_QUERY_THROW ); xExporter->setSourceDocument( Reference< lang::XComponent >( this )); xFilter->filter( aMD ); } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } else { OSL_ENSURE( false, "No filter" ); } setModified( sal_False ); //#i66865# //for data change notification during chart is not loaded: //notify parent data provider after saving thus the parent document can store //the ranges for which a load and update of the chart will be necessary Reference< beans::XPropertySet > xPropSet( m_xParent, uno::UNO_QUERY ); if ( !hasInternalDataProvider() && xPropSet.is() ) { apphelper::MediaDescriptorHelper aMDHelper(rMediaDescriptor); try { xPropSet->setPropertyValue( OUString::createFromAscii("SavedObject"), uno::makeAny( aMDHelper.HierarchicalDocumentName ) ); } catch ( uno::Exception& ) { } } } //----------------------------------------------------------------- // frame::XLoadable //----------------------------------------------------------------- void SAL_CALL ChartModel::initNew() throw (frame::DoubleInitializationException, io::IOException, uno::Exception, uno::RuntimeException) { lockControllers(); createInternalDataProvider( sal_False ); try { m_pImplChartModel->CreateDefaultChart(); } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } setModified( sal_False ); unlockControllers(); #if OSL_DEBUG_LEVEL >= CHART_TRACE_OSL_DEBUG_LEVEL OSL_TRACE( "ChartModel::initNew: Showing ChartDocument structure" ); OSL_TRACE( "----------------------------------------------------" ); debug::ChartDebugTraceDocument( Reference< chart2::XChartDocument >( this )); #endif } void SAL_CALL ChartModel::load( const Sequence< beans::PropertyValue >& rMediaDescriptor ) throw (frame::DoubleInitializationException, io::IOException, uno::Exception, uno::RuntimeException) { Reference< embed::XStorage > xStorage; OUString aURL; try { apphelper::MediaDescriptorHelper aMDHelper( rMediaDescriptor ); if( aMDHelper.ISSET_Storage ) { xStorage = aMDHelper.Storage; } else if( aMDHelper.ISSET_Stream || aMDHelper.ISSET_InputStream ) { if( aMDHelper.ISSET_FilterName && aMDHelper.FilterName.equals( C2U("StarChart 5.0")) ) { attachResource( aMDHelper.URL, rMediaDescriptor ); impl_load( rMediaDescriptor, 0 ); // cannot create a storage from binary streams, but I do not need the storage here anyhow m_bReadOnly = sal_True; return; } Reference< lang::XSingleServiceFactory > xStorageFact( m_xContext->getServiceManager()->createInstanceWithContext( C2U("com.sun.star.embed.StorageFactory"), m_xContext ), uno::UNO_QUERY_THROW ); if( aMDHelper.ISSET_Stream ) { // convert XStream to XStorage via the storage factory Sequence< uno::Any > aStorageArgs( 2 ); aStorageArgs[0] <<= aMDHelper.Stream; // todo: check if stream is read-only aStorageArgs[1] <<= (embed::ElementModes::READ); //WRITE | embed::ElementModes::NOCREATE); xStorage.set( xStorageFact->createInstanceWithArguments( aStorageArgs ), uno::UNO_QUERY_THROW ); } else { OSL_ASSERT( aMDHelper.ISSET_InputStream ); // convert XInputStream to XStorage via the storage factory Sequence< uno::Any > aStorageArgs( 2 ); aStorageArgs[0] <<= aMDHelper.InputStream; aStorageArgs[1] <<= (embed::ElementModes::READ); xStorage.set( xStorageFact->createInstanceWithArguments( aStorageArgs ), uno::UNO_QUERY_THROW ); } } if( aMDHelper.ISSET_URL ) aURL = aMDHelper.URL; } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } if( xStorage.is()) { attachResource( aURL, rMediaDescriptor ); impl_load( rMediaDescriptor, xStorage ); } } void ChartModel::impl_load( const Sequence< beans::PropertyValue >& rMediaDescriptor, const Reference< embed::XStorage >& xStorage ) { { MutexGuard aGuard( m_aModelMutex ); m_nInLoad++; } Reference< document::XFilter > xFilter( impl_createFilter( rMediaDescriptor )); if( xFilter.is()) { Reference< document::XImporter > xImporter( xFilter, uno::UNO_QUERY_THROW ); xImporter->setTargetDocument( this ); Sequence< beans::PropertyValue > aMD( rMediaDescriptor ); lcl_addStorageToMediaDescriptor( aMD, xStorage ); xFilter->filter( aMD ); xFilter.clear(); } else { OSL_ENSURE( false, "loadFromStorage cannot create filter" ); } if( xStorage.is() ) impl_loadGraphics( xStorage ); setModified( sal_False ); // switchToStorage without notifying listeners (which shouldn't exist at // this time, anyway) m_xStorage = xStorage; { MutexGuard aGuard( m_aModelMutex ); m_nInLoad--; } } void ChartModel::impl_loadGraphics( const Reference< embed::XStorage >& xStorage ) { try { const Reference< embed::XStorage >& xGraphicsStorage( xStorage->openStorageElement( C2U( "Pictures" ), embed::ElementModes::READ ) ); if( xGraphicsStorage.is() ) { const uno::Sequence< ::rtl::OUString > aElementNames( xGraphicsStorage->getElementNames() ); for( int i = 0; i < aElementNames.getLength(); ++i ) { if( xGraphicsStorage->isStreamElement( aElementNames[ i ] ) ) { uno::Reference< io::XStream > xElementStream( xGraphicsStorage->openStreamElement( aElementNames[ i ], embed::ElementModes::READ ) ); if( xElementStream.is() ) { std::auto_ptr< SvStream > apIStm( ::utl::UcbStreamHelper::CreateStream( xElementStream, true ) ); if( apIStm.get() ) { Graphic aGraphic; if( !GraphicConverter::Import( *apIStm.get(), aGraphic ) ) { m_aGraphicObjectVector.push_back( aGraphic ); } } } } } } } catch ( uno::Exception& ) { } } //----------------------------------------------------------------- // util::XModifiable //----------------------------------------------------------------- void SAL_CALL ChartModel::impl_notifyModifiedListeners() throw( uno::RuntimeException) { { MutexGuard aGuard( m_aModelMutex ); m_bUpdateNotificationsPending = false; } //always notify the view first! ChartViewHelper::setViewToDirtyState( this ); ::cppu::OInterfaceContainerHelper* pIC = m_aLifeTimeManager.m_aListenerContainer .getContainer( ::getCppuType((const uno::Reference< util::XModifyListener >*)0) ); if( pIC ) { lang::EventObject aEvent( static_cast< lang::XComponent*>(this) ); ::cppu::OInterfaceIteratorHelper aIt( *pIC ); while( aIt.hasMoreElements() ) (static_cast< util::XModifyListener*>(aIt.next()))->modified( aEvent ); } } sal_Bool SAL_CALL ChartModel::isModified() throw(uno::RuntimeException) { //@todo guard return m_bModified; } void SAL_CALL ChartModel::setModified( sal_Bool bModified ) throw(beans::PropertyVetoException, uno::RuntimeException) { apphelper::LifeTimeGuard aGuard(m_aLifeTimeManager); if(!aGuard.startApiCall())//@todo ? is this a long lasting call?? return; //behave passive if already disposed or closed or throw exception @todo? m_bModified = bModified; if( m_nControllerLockCount > 0 ) { m_bUpdateNotificationsPending = true; return;//don't call listeners if controllers are locked } aGuard.clear(); if(bModified) impl_notifyModifiedListeners(); } //----------------------------------------------------------------- // util::XModifyBroadcaster (base of XModifiable) //----------------------------------------------------------------- void SAL_CALL ChartModel::addModifyListener( const uno::Reference< util::XModifyListener >& xListener ) throw(uno::RuntimeException) { if( m_aLifeTimeManager.impl_isDisposedOrClosed() ) return; //behave passive if already disposed or closed m_aLifeTimeManager.m_aListenerContainer.addInterface( ::getCppuType((const uno::Reference< util::XModifyListener >*)0), xListener ); } void SAL_CALL ChartModel::removeModifyListener( const uno::Reference< util::XModifyListener >& xListener ) throw(uno::RuntimeException) { if( m_aLifeTimeManager.impl_isDisposedOrClosed() ) return; //behave passive if already disposed or closed m_aLifeTimeManager.m_aListenerContainer.removeInterface( ::getCppuType((const uno::Reference< util::XModifyListener >*)0), xListener ); } //----------------------------------------------------------------- // util::XModifyListener //----------------------------------------------------------------- void SAL_CALL ChartModel::modified( const lang::EventObject& ) throw (uno::RuntimeException) { if( m_nInLoad == 0 ) setModified( sal_True ); } //----------------------------------------------------------------- // lang::XEventListener (base of util::XModifyListener) //----------------------------------------------------------------- void SAL_CALL ChartModel::disposing( const lang::EventObject& ) throw (uno::RuntimeException) { // child was disposed -- should not happen from outside } //----------------------------------------------------------------- // document::XStorageBasedDocument //----------------------------------------------------------------- void SAL_CALL ChartModel::loadFromStorage( const Reference< embed::XStorage >& xStorage, const Sequence< beans::PropertyValue >& rMediaDescriptor ) throw (lang::IllegalArgumentException, frame::DoubleInitializationException, io::IOException, uno::Exception, uno::RuntimeException) { attachResource( OUString(), rMediaDescriptor ); impl_load( rMediaDescriptor, xStorage ); } void SAL_CALL ChartModel::storeToStorage( const Reference< embed::XStorage >& xStorage, const Sequence< beans::PropertyValue >& rMediaDescriptor ) throw (lang::IllegalArgumentException, io::IOException, uno::Exception, uno::RuntimeException) { impl_store( rMediaDescriptor, xStorage ); } void SAL_CALL ChartModel::switchToStorage( const Reference< embed::XStorage >& xStorage ) throw (lang::IllegalArgumentException, io::IOException, uno::Exception, uno::RuntimeException) { m_xStorage = xStorage; impl_notifyStorageChangeListeners(); } Reference< embed::XStorage > SAL_CALL ChartModel::getDocumentStorage() throw (io::IOException, uno::Exception, uno::RuntimeException) { return m_xStorage; } void SAL_CALL ChartModel::impl_notifyStorageChangeListeners() throw( uno::RuntimeException) { ::cppu::OInterfaceContainerHelper* pIC = m_aLifeTimeManager.m_aListenerContainer .getContainer( ::getCppuType((const uno::Reference< document::XStorageChangeListener >*)0) ); if( pIC ) { ::cppu::OInterfaceIteratorHelper aIt( *pIC ); while( aIt.hasMoreElements() ) (static_cast< document::XStorageChangeListener* >(aIt.next()))->notifyStorageChange( static_cast< ::cppu::OWeakObject* >( this ), m_xStorage ); } } void SAL_CALL ChartModel::addStorageChangeListener( const Reference< document::XStorageChangeListener >& xListener ) throw (uno::RuntimeException) { if( m_aLifeTimeManager.impl_isDisposedOrClosed() ) return; //behave passive if already disposed or closed m_aLifeTimeManager.m_aListenerContainer.addInterface( ::getCppuType((const uno::Reference< document::XStorageChangeListener >*)0), xListener ); } void SAL_CALL ChartModel::removeStorageChangeListener( const Reference< document::XStorageChangeListener >& xListener ) throw (uno::RuntimeException) { if( m_aLifeTimeManager.impl_isDisposedOrClosed() ) return; //behave passive if already disposed or closed m_aLifeTimeManager.m_aListenerContainer.removeInterface( ::getCppuType((const uno::Reference< document::XStorageChangeListener >*)0), xListener ); } } // namespace chart INTEGRATION: CWS bgdlremove (1.2.6); FILE MERGED 2007/05/28 17:36:50 kso 1.2.6.1: #i77419# - Adapt to ucbhelper namespace changes. /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ChartModel_Persistence.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: ihi $ $Date: 2007-06-05 17:49:52 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "ChartModel.hxx" #include "ImplChartModel.hxx" #include "MediaDescriptorHelper.hxx" #include "ChartDebugTrace.hxx" #include "macros.hxx" #include "ChartViewHelper.hxx" #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_ #include <com/sun/star/document/XExporter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_ #include <com/sun/star/document/XImporter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_ #include <com/sun/star/document/XFilter.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_ #include <com/sun/star/embed/ElementModes.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_ #include <com/sun/star/embed/XStorage.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_ #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #ifndef _UCBHELPER_CONTENT_HXX #include <ucbhelper/content.hxx> #endif #ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX #include <unotools/ucbstreamhelper.hxx> #endif #ifndef _SV_CVTGRF_HXX #include <vcl/cvtgrf.hxx> #endif #ifndef _COMPHELPER_STORAGEHELPER_HXX #include <comphelper/storagehelper.hxx> #endif #include <algorithm> #include <functional> using namespace ::com::sun::star; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::rtl::OUString; using ::osl::MutexGuard; namespace { struct lcl_PropNameEquals : public ::std::unary_function< beans::PropertyValue, bool > { lcl_PropNameEquals( const OUString & rStrToCompareWith ) : m_aStr( rStrToCompareWith ) {} bool operator() ( const beans::PropertyValue & rProp ) { return rProp.Name.equals( m_aStr ); } private: OUString m_aStr; }; template< typename T > T lcl_getProperty( const Sequence< beans::PropertyValue > & rMediaDescriptor, const OUString & rPropName ) { T aResult; if( rMediaDescriptor.getLength()) { OUString aPropName( rPropName ); const beans::PropertyValue * pIt = rMediaDescriptor.getConstArray(); const beans::PropertyValue * pEndIt = pIt + + rMediaDescriptor.getLength(); pIt = ::std::find_if( pIt, pEndIt, lcl_PropNameEquals( aPropName )); if( pIt != pEndIt ) (*pIt).Value >>= aResult; } return aResult; } void lcl_addStorageToMediaDescriptor( Sequence< beans::PropertyValue > & rOutMD, const Reference< embed::XStorage > & xStorage ) { rOutMD.realloc( rOutMD.getLength() + 1 ); rOutMD[rOutMD.getLength() - 1] = beans::PropertyValue( C2U("Storage"), -1, uno::makeAny( xStorage ), beans::PropertyState_DIRECT_VALUE ); } Reference< embed::XStorage > lcl_createStorage( const OUString & rURL, const Reference< uno::XComponentContext > & xContext, const Sequence< beans::PropertyValue > & rMediaDescriptor ) { // create new storage Reference< embed::XStorage > xStorage; if( !xContext.is()) return xStorage; try { Reference< io::XStream > xStream( ::ucbhelper::Content( rURL, Reference< ::com::sun::star::ucb::XCommandEnvironment >()).openStream(), uno::UNO_QUERY ); Reference< lang::XSingleServiceFactory > xStorageFact( xContext->getServiceManager()->createInstanceWithContext( C2U("com.sun.star.embed.StorageFactory"), xContext ), uno::UNO_QUERY_THROW ); Sequence< uno::Any > aStorageArgs( 3 ); aStorageArgs[0] <<= xStream; aStorageArgs[1] <<= embed::ElementModes::READWRITE; aStorageArgs[2] <<= rMediaDescriptor; xStorage.set( xStorageFact->createInstanceWithArguments( aStorageArgs ), uno::UNO_QUERY_THROW ); OSL_ENSURE( xStorage.is(), "No Storage" ); } catch( ::com::sun::star::ucb::ContentCreationException & rEx ) { ASSERT_EXCEPTION( rEx ); } return xStorage; } } // anonymous namespace namespace chart { Reference< document::XFilter > ChartModel::impl_createFilter( const Sequence< beans::PropertyValue > & rMediaDescriptor ) { Reference< document::XFilter > xFilter; // find FilterName in MediaDescriptor OUString aFilterName( lcl_getProperty< OUString >( rMediaDescriptor, OUString::createFromAscii("FilterName"))); // if FilterName was found, get Filter from factory if( aFilterName.getLength() > 0 ) { try { Reference< container::XNameAccess > xFilterFact( m_xContext->getServiceManager()->createInstanceWithContext( C2U( "com.sun.star.document.FilterFactory" ), m_xContext ), uno::UNO_QUERY_THROW ); uno::Any aFilterProps( xFilterFact->getByName( aFilterName )); Sequence< beans::PropertyValue > aProps; if( aFilterProps.hasValue() && (aFilterProps >>= aProps)) { OUString aFilterServiceName( lcl_getProperty< OUString >( aProps, OUString::createFromAscii("FilterService"))); if( aFilterServiceName.getLength()) { xFilter.set( m_xContext->getServiceManager()->createInstanceWithContext( aFilterServiceName, m_xContext ), uno::UNO_QUERY_THROW ); OSL_TRACE( "Filter found for service %s", U2C( aFilterServiceName )); } } } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } OSL_ENSURE( xFilter.is(), "Filter not found via factory" ); } // fall-back: create XML-Filter if( ! xFilter.is()) { OSL_TRACE( "No FilterName passed in MediaDescriptor" ); xFilter.set( m_xContext->getServiceManager()->createInstanceWithContext( C2U("com.sun.star.comp.chart2.XMLFilter"), m_xContext ), uno::UNO_QUERY_THROW ); } return xFilter; } //----------------------------------------------------------------- // frame::XStorable2 //----------------------------------------------------------------- void SAL_CALL ChartModel::storeSelf( const Sequence< beans::PropertyValue >& rMediaDescriptor ) throw (lang::IllegalArgumentException, io::IOException, uno::RuntimeException) { // only some parameters are allowed (see also SfxBaseModel) // "VersionComment", "Author", "InteractionHandler", "StatusIndicator" // However, they are ignored here. They would become interesting when // charts support a standalone format again. impl_store( rMediaDescriptor, m_xStorage ); } //----------------------------------------------------------------- // frame::XStorable (base of XStorable2) //----------------------------------------------------------------- sal_Bool SAL_CALL ChartModel::hasLocation() throw(uno::RuntimeException) { //@todo guard return m_aResource.getLength()!=0; } ::rtl::OUString SAL_CALL ChartModel::getLocation() throw(uno::RuntimeException) { return impl_g_getLocation(); } sal_Bool SAL_CALL ChartModel::isReadonly() throw(uno::RuntimeException) { //@todo guard return m_bReadOnly; } void SAL_CALL ChartModel::store() throw(io::IOException, uno::RuntimeException) { apphelper::LifeTimeGuard aGuard(m_aLifeTimeManager); if(!aGuard.startApiCall(sal_True)) //start LongLastingCall return; //behave passive if already disposed or closed or throw exception @todo? ::rtl::OUString aLocation = m_aResource; if( aLocation.getLength() == 0 ) throw io::IOException( C2U( "no location specified" ), static_cast< ::cppu::OWeakObject* >(this)); //@todo check wether aLocation is something like private:factory... if( m_bReadOnly ) throw io::IOException( C2U( "document is read only" ), static_cast< ::cppu::OWeakObject* >(this)); aGuard.clear(); // store impl_store( m_aMediaDescriptor, m_xStorage ); } void SAL_CALL ChartModel::storeAsURL( const ::rtl::OUString& rURL, const uno::Sequence< beans::PropertyValue >& rMediaDescriptor ) throw(io::IOException, uno::RuntimeException) { apphelper::LifeTimeGuard aGuard(m_aLifeTimeManager); if(!aGuard.startApiCall(sal_True)) //start LongLastingCall return; //behave passive if already disposed or closed or throw exception @todo? apphelper::MediaDescriptorHelper aMediaDescriptorHelper(rMediaDescriptor); uno::Sequence< beans::PropertyValue > aReducedMediaDescriptor( aMediaDescriptorHelper.getReducedForModel() ); m_bReadOnly = sal_False; aGuard.clear(); // create new storage Reference< embed::XStorage > xStorage( lcl_createStorage( rURL, m_xContext, aReducedMediaDescriptor )); if( xStorage.is()) { impl_store( aReducedMediaDescriptor, xStorage ); attachResource( rURL, aReducedMediaDescriptor ); } } void SAL_CALL ChartModel::storeToURL( const ::rtl::OUString& rURL, const uno::Sequence< beans::PropertyValue >& rMediaDescriptor ) throw(io::IOException, uno::RuntimeException) { apphelper::LifeTimeGuard aGuard(m_aLifeTimeManager); if(!aGuard.startApiCall(sal_True)) //start LongLastingCall return; //behave passive if already disposed or closed or throw exception @todo? //do not change the internal state of the document here //... aGuard.clear(); apphelper::MediaDescriptorHelper aMediaDescriptorHelper(rMediaDescriptor); uno::Sequence< beans::PropertyValue > aReducedMediaDescriptor( aMediaDescriptorHelper.getReducedForModel() ); if( rURL.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("private:stream"))) { try { if( m_xContext.is() && aMediaDescriptorHelper.ISSET_OutputStream ) { Reference< lang::XMultiServiceFactory > xFact( m_xContext->getServiceManager(), uno::UNO_QUERY_THROW ); Reference< io::XStream > xStream( xFact->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.TempFile"))), uno::UNO_QUERY_THROW ); Reference< io::XInputStream > xInputStream( xStream->getInputStream()); Reference< embed::XStorage > xStorage( ::comphelper::OStorageHelper::GetStorageFromStream( xStream, embed::ElementModes::READWRITE, xFact )); if( xStorage.is()) { impl_store( aReducedMediaDescriptor, xStorage ); Reference< io::XSeekable > xSeekable( xStream, uno::UNO_QUERY_THROW ); xSeekable->seek( 0 ); ::comphelper::OStorageHelper::CopyInputToOutput( xInputStream, aMediaDescriptorHelper.OutputStream ); } } } catch( const uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } else { // create new storage Reference< embed::XStorage > xStorage( lcl_createStorage( rURL, m_xContext, aReducedMediaDescriptor )); if( xStorage.is()) impl_store( aReducedMediaDescriptor, xStorage ); } } void ChartModel::impl_store( const Sequence< beans::PropertyValue >& rMediaDescriptor, const Reference< embed::XStorage > & xStorage ) { Reference< document::XFilter > xFilter( impl_createFilter( rMediaDescriptor)); if( xFilter.is() && xStorage.is()) { Sequence< beans::PropertyValue > aMD( rMediaDescriptor ); lcl_addStorageToMediaDescriptor( aMD, xStorage ); try { Reference< document::XExporter > xExporter( xFilter, uno::UNO_QUERY_THROW ); xExporter->setSourceDocument( Reference< lang::XComponent >( this )); xFilter->filter( aMD ); } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } else { OSL_ENSURE( false, "No filter" ); } setModified( sal_False ); //#i66865# //for data change notification during chart is not loaded: //notify parent data provider after saving thus the parent document can store //the ranges for which a load and update of the chart will be necessary Reference< beans::XPropertySet > xPropSet( m_xParent, uno::UNO_QUERY ); if ( !hasInternalDataProvider() && xPropSet.is() ) { apphelper::MediaDescriptorHelper aMDHelper(rMediaDescriptor); try { xPropSet->setPropertyValue( OUString::createFromAscii("SavedObject"), uno::makeAny( aMDHelper.HierarchicalDocumentName ) ); } catch ( uno::Exception& ) { } } } //----------------------------------------------------------------- // frame::XLoadable //----------------------------------------------------------------- void SAL_CALL ChartModel::initNew() throw (frame::DoubleInitializationException, io::IOException, uno::Exception, uno::RuntimeException) { lockControllers(); createInternalDataProvider( sal_False ); try { m_pImplChartModel->CreateDefaultChart(); } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } setModified( sal_False ); unlockControllers(); #if OSL_DEBUG_LEVEL >= CHART_TRACE_OSL_DEBUG_LEVEL OSL_TRACE( "ChartModel::initNew: Showing ChartDocument structure" ); OSL_TRACE( "----------------------------------------------------" ); debug::ChartDebugTraceDocument( Reference< chart2::XChartDocument >( this )); #endif } void SAL_CALL ChartModel::load( const Sequence< beans::PropertyValue >& rMediaDescriptor ) throw (frame::DoubleInitializationException, io::IOException, uno::Exception, uno::RuntimeException) { Reference< embed::XStorage > xStorage; OUString aURL; try { apphelper::MediaDescriptorHelper aMDHelper( rMediaDescriptor ); if( aMDHelper.ISSET_Storage ) { xStorage = aMDHelper.Storage; } else if( aMDHelper.ISSET_Stream || aMDHelper.ISSET_InputStream ) { if( aMDHelper.ISSET_FilterName && aMDHelper.FilterName.equals( C2U("StarChart 5.0")) ) { attachResource( aMDHelper.URL, rMediaDescriptor ); impl_load( rMediaDescriptor, 0 ); // cannot create a storage from binary streams, but I do not need the storage here anyhow m_bReadOnly = sal_True; return; } Reference< lang::XSingleServiceFactory > xStorageFact( m_xContext->getServiceManager()->createInstanceWithContext( C2U("com.sun.star.embed.StorageFactory"), m_xContext ), uno::UNO_QUERY_THROW ); if( aMDHelper.ISSET_Stream ) { // convert XStream to XStorage via the storage factory Sequence< uno::Any > aStorageArgs( 2 ); aStorageArgs[0] <<= aMDHelper.Stream; // todo: check if stream is read-only aStorageArgs[1] <<= (embed::ElementModes::READ); //WRITE | embed::ElementModes::NOCREATE); xStorage.set( xStorageFact->createInstanceWithArguments( aStorageArgs ), uno::UNO_QUERY_THROW ); } else { OSL_ASSERT( aMDHelper.ISSET_InputStream ); // convert XInputStream to XStorage via the storage factory Sequence< uno::Any > aStorageArgs( 2 ); aStorageArgs[0] <<= aMDHelper.InputStream; aStorageArgs[1] <<= (embed::ElementModes::READ); xStorage.set( xStorageFact->createInstanceWithArguments( aStorageArgs ), uno::UNO_QUERY_THROW ); } } if( aMDHelper.ISSET_URL ) aURL = aMDHelper.URL; } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } if( xStorage.is()) { attachResource( aURL, rMediaDescriptor ); impl_load( rMediaDescriptor, xStorage ); } } void ChartModel::impl_load( const Sequence< beans::PropertyValue >& rMediaDescriptor, const Reference< embed::XStorage >& xStorage ) { { MutexGuard aGuard( m_aModelMutex ); m_nInLoad++; } Reference< document::XFilter > xFilter( impl_createFilter( rMediaDescriptor )); if( xFilter.is()) { Reference< document::XImporter > xImporter( xFilter, uno::UNO_QUERY_THROW ); xImporter->setTargetDocument( this ); Sequence< beans::PropertyValue > aMD( rMediaDescriptor ); lcl_addStorageToMediaDescriptor( aMD, xStorage ); xFilter->filter( aMD ); xFilter.clear(); } else { OSL_ENSURE( false, "loadFromStorage cannot create filter" ); } if( xStorage.is() ) impl_loadGraphics( xStorage ); setModified( sal_False ); // switchToStorage without notifying listeners (which shouldn't exist at // this time, anyway) m_xStorage = xStorage; { MutexGuard aGuard( m_aModelMutex ); m_nInLoad--; } } void ChartModel::impl_loadGraphics( const Reference< embed::XStorage >& xStorage ) { try { const Reference< embed::XStorage >& xGraphicsStorage( xStorage->openStorageElement( C2U( "Pictures" ), embed::ElementModes::READ ) ); if( xGraphicsStorage.is() ) { const uno::Sequence< ::rtl::OUString > aElementNames( xGraphicsStorage->getElementNames() ); for( int i = 0; i < aElementNames.getLength(); ++i ) { if( xGraphicsStorage->isStreamElement( aElementNames[ i ] ) ) { uno::Reference< io::XStream > xElementStream( xGraphicsStorage->openStreamElement( aElementNames[ i ], embed::ElementModes::READ ) ); if( xElementStream.is() ) { std::auto_ptr< SvStream > apIStm( ::utl::UcbStreamHelper::CreateStream( xElementStream, true ) ); if( apIStm.get() ) { Graphic aGraphic; if( !GraphicConverter::Import( *apIStm.get(), aGraphic ) ) { m_aGraphicObjectVector.push_back( aGraphic ); } } } } } } } catch ( uno::Exception& ) { } } //----------------------------------------------------------------- // util::XModifiable //----------------------------------------------------------------- void SAL_CALL ChartModel::impl_notifyModifiedListeners() throw( uno::RuntimeException) { { MutexGuard aGuard( m_aModelMutex ); m_bUpdateNotificationsPending = false; } //always notify the view first! ChartViewHelper::setViewToDirtyState( this ); ::cppu::OInterfaceContainerHelper* pIC = m_aLifeTimeManager.m_aListenerContainer .getContainer( ::getCppuType((const uno::Reference< util::XModifyListener >*)0) ); if( pIC ) { lang::EventObject aEvent( static_cast< lang::XComponent*>(this) ); ::cppu::OInterfaceIteratorHelper aIt( *pIC ); while( aIt.hasMoreElements() ) (static_cast< util::XModifyListener*>(aIt.next()))->modified( aEvent ); } } sal_Bool SAL_CALL ChartModel::isModified() throw(uno::RuntimeException) { //@todo guard return m_bModified; } void SAL_CALL ChartModel::setModified( sal_Bool bModified ) throw(beans::PropertyVetoException, uno::RuntimeException) { apphelper::LifeTimeGuard aGuard(m_aLifeTimeManager); if(!aGuard.startApiCall())//@todo ? is this a long lasting call?? return; //behave passive if already disposed or closed or throw exception @todo? m_bModified = bModified; if( m_nControllerLockCount > 0 ) { m_bUpdateNotificationsPending = true; return;//don't call listeners if controllers are locked } aGuard.clear(); if(bModified) impl_notifyModifiedListeners(); } //----------------------------------------------------------------- // util::XModifyBroadcaster (base of XModifiable) //----------------------------------------------------------------- void SAL_CALL ChartModel::addModifyListener( const uno::Reference< util::XModifyListener >& xListener ) throw(uno::RuntimeException) { if( m_aLifeTimeManager.impl_isDisposedOrClosed() ) return; //behave passive if already disposed or closed m_aLifeTimeManager.m_aListenerContainer.addInterface( ::getCppuType((const uno::Reference< util::XModifyListener >*)0), xListener ); } void SAL_CALL ChartModel::removeModifyListener( const uno::Reference< util::XModifyListener >& xListener ) throw(uno::RuntimeException) { if( m_aLifeTimeManager.impl_isDisposedOrClosed() ) return; //behave passive if already disposed or closed m_aLifeTimeManager.m_aListenerContainer.removeInterface( ::getCppuType((const uno::Reference< util::XModifyListener >*)0), xListener ); } //----------------------------------------------------------------- // util::XModifyListener //----------------------------------------------------------------- void SAL_CALL ChartModel::modified( const lang::EventObject& ) throw (uno::RuntimeException) { if( m_nInLoad == 0 ) setModified( sal_True ); } //----------------------------------------------------------------- // lang::XEventListener (base of util::XModifyListener) //----------------------------------------------------------------- void SAL_CALL ChartModel::disposing( const lang::EventObject& ) throw (uno::RuntimeException) { // child was disposed -- should not happen from outside } //----------------------------------------------------------------- // document::XStorageBasedDocument //----------------------------------------------------------------- void SAL_CALL ChartModel::loadFromStorage( const Reference< embed::XStorage >& xStorage, const Sequence< beans::PropertyValue >& rMediaDescriptor ) throw (lang::IllegalArgumentException, frame::DoubleInitializationException, io::IOException, uno::Exception, uno::RuntimeException) { attachResource( OUString(), rMediaDescriptor ); impl_load( rMediaDescriptor, xStorage ); } void SAL_CALL ChartModel::storeToStorage( const Reference< embed::XStorage >& xStorage, const Sequence< beans::PropertyValue >& rMediaDescriptor ) throw (lang::IllegalArgumentException, io::IOException, uno::Exception, uno::RuntimeException) { impl_store( rMediaDescriptor, xStorage ); } void SAL_CALL ChartModel::switchToStorage( const Reference< embed::XStorage >& xStorage ) throw (lang::IllegalArgumentException, io::IOException, uno::Exception, uno::RuntimeException) { m_xStorage = xStorage; impl_notifyStorageChangeListeners(); } Reference< embed::XStorage > SAL_CALL ChartModel::getDocumentStorage() throw (io::IOException, uno::Exception, uno::RuntimeException) { return m_xStorage; } void SAL_CALL ChartModel::impl_notifyStorageChangeListeners() throw( uno::RuntimeException) { ::cppu::OInterfaceContainerHelper* pIC = m_aLifeTimeManager.m_aListenerContainer .getContainer( ::getCppuType((const uno::Reference< document::XStorageChangeListener >*)0) ); if( pIC ) { ::cppu::OInterfaceIteratorHelper aIt( *pIC ); while( aIt.hasMoreElements() ) (static_cast< document::XStorageChangeListener* >(aIt.next()))->notifyStorageChange( static_cast< ::cppu::OWeakObject* >( this ), m_xStorage ); } } void SAL_CALL ChartModel::addStorageChangeListener( const Reference< document::XStorageChangeListener >& xListener ) throw (uno::RuntimeException) { if( m_aLifeTimeManager.impl_isDisposedOrClosed() ) return; //behave passive if already disposed or closed m_aLifeTimeManager.m_aListenerContainer.addInterface( ::getCppuType((const uno::Reference< document::XStorageChangeListener >*)0), xListener ); } void SAL_CALL ChartModel::removeStorageChangeListener( const Reference< document::XStorageChangeListener >& xListener ) throw (uno::RuntimeException) { if( m_aLifeTimeManager.impl_isDisposedOrClosed() ) return; //behave passive if already disposed or closed m_aLifeTimeManager.m_aListenerContainer.removeInterface( ::getCppuType((const uno::Reference< document::XStorageChangeListener >*)0), xListener ); } } // namespace chart
/* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 — Vladimír Vondruš <mosra@centrum.cz> 2019 — Konstantinos Chatzilygeroudis <costashatz@gmail.com> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <dart/collision/dart/DARTCollisionDetector.hpp> #include <dart/constraint/ConstraintSolver.hpp> #include <dart/dynamics/BallJoint.hpp> #include <dart/dynamics/BodyNode.hpp> #include <dart/dynamics/BoxShape.hpp> #include <dart/dynamics/CylinderShape.hpp> #include <dart/dynamics/EllipsoidShape.hpp> #include <dart/dynamics/FreeJoint.hpp> #include <dart/dynamics/MeshShape.hpp> #include <dart/dynamics/RevoluteJoint.hpp> #include <dart/dynamics/SoftBodyNode.hpp> #include <dart/dynamics/SoftMeshShape.hpp> #include <dart/dynamics/Skeleton.hpp> #include <dart/dynamics/WeldJoint.hpp> #include <dart/simulation/World.hpp> #include <Corrade/Containers/Reference.h> #include <Corrade/Utility/Directory.h> #include <Magnum/ResourceManager.h> #include <Magnum/DartIntegration/ConvertShapeNode.h> #include <Magnum/DartIntegration/World.h> #include <Magnum/GL/Buffer.h> #include <Magnum/GL/DefaultFramebuffer.h> #include <Magnum/GL/Mesh.h> #include <Magnum/GL/Renderer.h> #include <Magnum/GL/Texture.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/MatrixTransformation3D.h> #include <Magnum/SceneGraph/Object.hpp> #include <Magnum/SceneGraph/SceneGraph.h> #include <Magnum/Shaders/Phong.h> #include <Magnum/Trade/PhongMaterialData.h> #include "configure.h" #if DART_MAJOR_VERSION == 6 #include <dart/utils/urdf/urdf.hpp> typedef dart::utils::DartLoader DartLoader; #else #include <dart/io/urdf/urdf.hpp> typedef dart::io::DartLoader DartLoader; #endif namespace Magnum { namespace Examples { namespace { /* Helper functions */ dart::dynamics::SkeletonPtr createBox(const std::string& name = "box", const Eigen::Vector3d& color = Eigen::Vector3d{0.8, 0.0, 0.0}) { /* The size of our box */ constexpr Double boxSize = 0.06; /* Calculate the mass of the box */ constexpr Double boxDensity = 260; // kg/m^3 constexpr Double boxMass = boxDensity*Math::pow<3>(boxSize); /* Create a Skeleton with the given name */ dart::dynamics::SkeletonPtr box = dart::dynamics::Skeleton::create(name); /* Create a body for the box */ dart::dynamics::BodyNodePtr body = box ->createJointAndBodyNodePair<dart::dynamics::FreeJoint>(nullptr).second; /* Create a shape for the box */ std::shared_ptr<dart::dynamics::BoxShape> boxShape( new dart::dynamics::BoxShape(Eigen::Vector3d{boxSize, boxSize, boxSize})); auto shapeNode = body->createShapeNodeWith<dart::dynamics::VisualAspect, dart::dynamics::CollisionAspect, dart::dynamics::DynamicsAspect>(boxShape); shapeNode->getVisualAspect()->setColor(color); /* Set up inertia for the box */ dart::dynamics::Inertia inertia; inertia.setMass(boxMass); inertia.setMoment(boxShape->computeInertia(boxMass)); body->setInertia(inertia); /* Setup the center of the box properly */ box->getDof("Joint_pos_z")->setPosition(boxSize/2.0); return box; } dart::dynamics::SkeletonPtr createFloor() { /* Create a floor */ dart::dynamics::SkeletonPtr floorSkel = dart::dynamics::Skeleton::create("floor"); /* Give the floor a body */ dart::dynamics::BodyNodePtr body = floorSkel->createJointAndBodyNodePair<dart::dynamics::WeldJoint>(nullptr).second; /* Give the floor a shape */ constexpr double floorWidth = 10.0; constexpr double floorHeight = 0.1; std::shared_ptr<dart::dynamics::BoxShape> box( new dart::dynamics::BoxShape(Eigen::Vector3d{floorWidth, floorWidth, floorHeight})); auto shapeNode = body->createShapeNodeWith<dart::dynamics::VisualAspect, dart::dynamics::CollisionAspect, dart::dynamics::DynamicsAspect>(box); shapeNode->getVisualAspect()->setColor(Eigen::Vector3d(0.3, 0.3, 0.4)); /* Put the floor into position */ Eigen::Isometry3d tf(Eigen::Isometry3d::Identity()); tf.translation() = Eigen::Vector3d{0.0, 0.0, -floorHeight/2.0}; body->getParentJoint()->setTransformFromParentBodyNode(tf); return floorSkel; } } using namespace Magnum::Math::Literals; typedef ResourceManager<GL::Buffer, GL::Mesh, Shaders::Phong> ViewerResourceManager; typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D; typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D; struct MaterialData{ Vector3 ambientColor, diffuseColor, specularColor; Float shininess; Vector3 scaling; }; class DrawableObject: public Object3D, SceneGraph::Drawable3D { public: explicit DrawableObject(std::vector<std::reference_wrapper<GL::Mesh>>&& meshes, std::vector<MaterialData>&& materials, Object3D* parent, SceneGraph::DrawableGroup3D* group); DrawableObject& setMeshes(std::vector<std::reference_wrapper<GL::Mesh>>&& meshes){ _meshes = std::move(meshes); return *this; } DrawableObject& setMaterials(std::vector<MaterialData>&& materials) { _materials = std::move(materials); return *this; } DrawableObject& setSoftBodies(std::vector<bool>&& softBody) { _isSoftBody = std::move(softBody); return *this; } DrawableObject& setTextures(std::vector<Containers::Optional<std::reference_wrapper<GL::Texture2D>>>&& textures){ _textures = std::move(textures); return *this; } private: void draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) override; Resource<Shaders::Phong> _color_shader; Resource<Shaders::Phong> _texture_shader; std::vector<std::reference_wrapper<GL::Mesh>> _meshes; std::vector<MaterialData> _materials; std::vector<bool> _isSoftBody; std::vector<Containers::Optional<std::reference_wrapper<GL::Texture2D>>> _textures; }; class DartExample: public Platform::Application { public: /* home: go to home position, active: go to active box */ enum State {home, active}; explicit DartExample(const Arguments& arguments); private: void viewportEvent(const Vector2i& size) override; void drawEvent() override; void keyPressEvent(KeyEvent& event) override; void updateManipulator(); ViewerResourceManager _resourceManager; Scene3D _scene; SceneGraph::DrawableGroup3D _drawables; SceneGraph::Camera3D* _camera; Object3D *_cameraRig, *_cameraObject; /* DART */ std::unique_ptr<DartIntegration::World> _dartWorld; std::unordered_map<DartIntegration::Object*, DrawableObject*> _drawableObjects; std::vector<Object3D*> _dartObjs; dart::dynamics::SkeletonPtr _manipulator, _model, _redBoxSkel, _greenBoxSkel, _blueBoxSkel; dart::simulation::WorldPtr _world; Eigen::VectorXd _redInitPosition, _greenInitPosition, _blueInitPosition; /* DART control */ Eigen::VectorXd _desiredPosition; Eigen::MatrixXd _desiredOrientation; Double _gripperDesiredPosition; const Double _pGripperGain = 100.0; const Double _pLinearGain = 500.0; const Double _dLinearGain = 200.0; const Double _pOrientationGain = 100.0; const Double _dOrientationGain = 50.0; const Double _dRegularization = 10.0; const Double _pGain = 2.25; const Double _dGain = 5.0; /* Simple State Machine */ State _state = home; }; DartExample::DartExample(const Arguments& arguments): Platform::Application{arguments, NoCreate} { /* Try 8x MSAA */ Configuration conf; GLConfiguration glConf; conf.setTitle("Magnum Dart Integration Example"); glConf.setSampleCount(8); if(!tryCreate(conf, glConf)) create(conf, glConf.setSampleCount(0)); GL::Renderer::enable(GL::Renderer::Feature::DepthTest); GL::Renderer::enable(GL::Renderer::Feature::FaceCulling); /* Camera setup */ (_cameraRig = new Object3D(&_scene)); (_cameraObject = new Object3D(_cameraRig)); (_camera = new SceneGraph::Camera3D(*_cameraObject)) ->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) .setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 1.0f, 0.001f, 100.0f)) .setViewport(GL::defaultFramebuffer.viewport().size()); /* DART has +Z-axis as up direction*/ _cameraObject->setTransformation(Matrix4::lookAt( {0.0f, 3.0f, 1.5f}, {0.0f, 0.0f, 0.5f}, {0.0f, 0.0f, 1.0f})); /* DART: Load Skeletons/Robots */ DartLoader loader; /* Add packages (needed for URDF loading) */ std::string res_path = Utility::Directory::join(DARTEXAMPLE_DIR, "urdf"); loader.addPackageDirectory("iiwa_description", res_path); loader.addPackageDirectory("robotiq_arg85_description", res_path); std::string filename = Utility::Directory::join(res_path, "iiwa14_simple.urdf"); /* First load the KUKA manipulator */ _manipulator = loader.parseSkeleton(filename); for(std::size_t i = 0; i < _manipulator->getNumJoints(); ++i) _manipulator->getJoint(i)->setPositionLimitEnforced(true); _manipulator->disableSelfCollisionCheck(); /* Clone the KUKA manipulator to use it as model in a model-based controller */ #if DART_VERSION_AT_LEAST(6, 7, 2) _model = _manipulator->cloneSkeleton(); #else _model = _manipulator->clone(); #endif /* Load the Robotiq 2-finger gripper */ filename = Utility::Directory::join(res_path, "robotiq.urdf"); auto gripper_skel = loader.parseSkeleton(filename); /* The gripper is controlled in velocity mode: servo actuator */ gripper_skel->getJoint("finger_joint")->setActuatorType(dart::dynamics::Joint::SERVO); /* Attach gripper to manipulator */ dart::dynamics::WeldJoint::Properties properties = dart::dynamics::WeldJoint::Properties(); properties.mT_ChildBodyToJoint.translation() = Eigen::Vector3d(0, 0, 0.0001); gripper_skel->getRootBodyNode()->moveTo<dart::dynamics::WeldJoint>(_manipulator->getBodyNode("iiwa_link_ee"), properties); /* Create floor */ auto floorSkel = createFloor(); /* Create red box */ _redBoxSkel = createBox("red", Eigen::Vector3d{0.8, 0.0, 0.0}); /* Position it at (0.5, 0.) [x,y] */ _redBoxSkel->setPosition(3, 0.5); /* Save initial position for resetting */ _redInitPosition = _redBoxSkel->getPositions(); /* Create green box */ _greenBoxSkel = createBox("green", Eigen::Vector3d{0.0, 0.8, 0.0}); /* Position it at (0.5, 0.2) */ _greenBoxSkel->setPosition(3, 0.5); _greenBoxSkel->setPosition(4, 0.2); /* Save initial position for resetting */ _greenInitPosition = _greenBoxSkel->getPositions(); /* Create blue box */ _blueBoxSkel = createBox("blue", Eigen::Vector3d{0.0, 0.0, 0.8}); /* Position it at (0.5, -0.2) */ _blueBoxSkel->setPosition(3, 0.5); _blueBoxSkel->setPosition(4, -0.2); /* Save initial position for resetting */ _blueInitPosition = _blueBoxSkel->getPositions(); /* Create the DART world */ _world = dart::simulation::WorldPtr{new dart::simulation::World}; /* Use a simple but very fast collision detector. This plays the most important role for having a fast simulation. */ _world->getConstraintSolver()->setCollisionDetector(dart::collision::DARTCollisionDetector::create()); /* Add the robot/objects in our DART world */ _world->addSkeleton(_manipulator); _world->addSkeleton(floorSkel); _world->addSkeleton(_redBoxSkel); _world->addSkeleton(_greenBoxSkel); _world->addSkeleton(_blueBoxSkel); /* Setup desired locations/orientations */ _desiredOrientation = Eigen::MatrixXd(3, 3); /* 3D rotation matrix */ /* Looking towards -Z direction (towards the floor) */ _desiredOrientation << 1, 0, 0, 0, -1, 0, 0, 0, -1; /* Default desired position is the red box position */ _desiredPosition = _redBoxSkel->getPositions().tail(3); _desiredPosition[2] += 0.17; /* Gripper default desired position: stay in the initial configuration (i.e., open) */ _gripperDesiredPosition = _manipulator->getPosition(7); /* faster simulation step; less accurate simulation/collision detection */ /* _world->setTimeStep(0.015); */ /* slower simulation step; better accuracy */ _world->setTimeStep(0.001); /* Create our DARTIntegration object/world */ auto dartObj = new Object3D{&_scene}; _dartWorld.reset(new DartIntegration::World{*dartObj, *_world}); /* Phong shader instances */ _resourceManager.set("color", new Shaders::Phong{{}, 2}); _resourceManager.set("texture", new Shaders::Phong(Shaders::Phong::Flag::DiffuseTexture, 2)); /* Loop at 60 Hz max */ setSwapInterval(1); setMinimalLoopPeriod(16); redraw(); } void DartExample::viewportEvent(const Vector2i& size) { GL::defaultFramebuffer.setViewport({{}, size}); _camera->setViewport(size); } void DartExample::drawEvent() { GL::defaultFramebuffer.clear( GL::FramebufferClear::Color|GL::FramebufferClear::Depth); /* We want around 60Hz display rate */ UnsignedInt steps = Math::round(1.0/(60.0*_world->getTimeStep())); /* Step DART simulation */ for(UnsignedInt i = 0; i < steps; ++i) { /* Compute control signals for manipulator */ updateManipulator(); /* Step the simulated world */ _dartWorld->step(); } /* Update graphic meshes/materials and render */ _dartWorld->refresh(); /* For each update object */ for(DartIntegration::Object& object : _dartWorld->updatedShapeObjects()) { /* Get material information */ std::vector<MaterialData> materials; std::vector<std::reference_wrapper<GL::Mesh>> meshes; std::vector<bool> isSoftBody; std::vector<Containers::Optional<std::reference_wrapper<GL::Texture2D>>> textures; for(std::size_t i = 0; i < object.drawData().meshes.size(); ++i) { bool isColor = true; if(object.drawData().materials[i].flags() & Trade::PhongMaterialData::Flag::DiffuseTexture) { std::reference_wrapper<GL::Texture2D> texture = *object.drawData().textures[object.drawData().materials[i].diffuseTexture()]; textures.push_back(texture); isColor = false; } else textures.push_back({}); MaterialData mat; mat.ambientColor = object.drawData().materials[i].ambientColor().rgb(); if(isColor) mat.diffuseColor = object.drawData().materials[i].diffuseColor().rgb(); mat.specularColor = object.drawData().materials[i].specularColor().rgb(); mat.shininess = object.drawData().materials[i].shininess(); mat.scaling = object.drawData().scaling; /* Get the modified mesh */ GL::Mesh& mesh = object.drawData().meshes[i]; meshes.push_back(mesh); materials.push_back(mat); if(object.shapeNode()->getShape()->getType() == dart::dynamics::SoftMeshShape::getStaticType()) isSoftBody.push_back(true); else isSoftBody.push_back(false); } /* Check if we already have it and then either add a new one or update the existing. We don't need the mesh / material / texture vectors anywhere else anymore, so move them in to avoid copies. */ auto it = _drawableObjects.insert(std::make_pair(&object, nullptr)); if(it.second) { auto drawableObj = new DrawableObject{ std::move(meshes), std::move(materials), static_cast<Object3D*>(&(object.object())), &_drawables}; drawableObj->setSoftBodies(std::move(isSoftBody)); drawableObj->setTextures(std::move(textures)); it.first->second = drawableObj; } else { (*it.first->second) .setMeshes(std::move(meshes)) .setMaterials(std::move(materials)) .setSoftBodies(std::move(isSoftBody)) .setTextures(std::move(textures)); } } _dartWorld->clearUpdatedShapeObjects(); _camera->draw(_drawables); swapBuffers(); redraw(); } void DartExample::keyPressEvent(KeyEvent& event) { if(event.key() == KeyEvent::Key::Down) { _cameraObject->rotateX(5.0_degf); } else if(event.key() == KeyEvent::Key::Up) { _cameraObject->rotateX(-5.0_degf); } else if(event.key() == KeyEvent::Key::Left) { _cameraRig->rotateY(-5.0_degf); } else if(event.key() == KeyEvent::Key::Right) { _cameraRig->rotateY(5.0_degf); } else if(event.key() == KeyEvent::Key::C) { _gripperDesiredPosition = 0.3; } else if(event.key() == KeyEvent::Key::O) { _gripperDesiredPosition = 0.; } else if(event.key() == KeyEvent::Key::U && _state == 1) { _desiredPosition[2] += 0.1; } else if(event.key() == KeyEvent::Key::D && _state == 1) { _desiredPosition[2] -= 0.1; } else if(event.key() == KeyEvent::Key::Z && _state == 1) { _desiredPosition[1] += 0.2; } else if(event.key() == KeyEvent::Key::X && _state == 1) { _desiredPosition[1] -= 0.2; } else if(event.key() == KeyEvent::Key::R) { _desiredPosition = _redBoxSkel->getPositions().tail(3); _desiredPosition[2] += 0.25; _state = active; } else if(event.key() == KeyEvent::Key::G) { _desiredPosition = _greenBoxSkel->getPositions().tail(3); _desiredPosition[2] += 0.25; _state = active; } else if(event.key() == KeyEvent::Key::B) { _desiredPosition = _blueBoxSkel->getPositions().tail(3); _desiredPosition[2] += 0.25; _state = active; } else if(event.key() == KeyEvent::Key::H) { _state = home; } else if(event.key() == KeyEvent::Key::Space) { /* Reset _state machine */ _state = home; /* Reset manipulator */ _manipulator->resetPositions(); _manipulator->resetVelocities(); _gripperDesiredPosition = 0.; /* Reset boxes */ /* Red box */ _redBoxSkel->resetVelocities(); _redBoxSkel->setPositions(_redInitPosition); /* Green box */ _greenBoxSkel->resetVelocities(); _greenBoxSkel->setPositions(_greenInitPosition); /* Blue box */ _blueBoxSkel->resetVelocities(); _blueBoxSkel->setPositions(_blueInitPosition); } else return; event.setAccepted(); } void DartExample::updateManipulator() { Eigen::VectorXd forces(7); /* Update our model with manipulator's measured joint positions and velocities */ _model->setPositions(_manipulator->getPositions().head(7)); _model->setVelocities(_manipulator->getVelocities().head(7)); if(_state == home) { /* Go to zero (home) position */ Eigen::VectorXd q = _model->getPositions(); Eigen::VectorXd dq = _model->getVelocities(); forces = -_pGain * q - _dGain * dq + _manipulator->getCoriolisAndGravityForces().head(7); } else { /* Get joint velocities of manipulator */ Eigen::VectorXd dq = _model->getVelocities(); /* Get full Jacobian of our end-effector */ Eigen::MatrixXd J = _model->getBodyNode("iiwa_link_ee")->getWorldJacobian(); /* Get current _state of the end-effector */ Eigen::MatrixXd currentWorldTransformation = _model->getBodyNode("iiwa_link_ee")->getWorldTransform().matrix(); Eigen::VectorXd currentWorldPosition = currentWorldTransformation.block(0, 3, 3, 1); Eigen::MatrixXd currentWorldOrientation = currentWorldTransformation.block(0, 0, 3, 3); Eigen::VectorXd currentWorldSpatialVelocity = _model->getBodyNode("iiwa_link_ee")->getSpatialVelocity(dart::dynamics::Frame::World(), dart::dynamics::Frame::World()); /* Compute desired forces and torques */ Eigen::VectorXd linearError = _desiredPosition - currentWorldPosition; Eigen::VectorXd desiredForces = _pLinearGain * linearError - _dLinearGain * currentWorldSpatialVelocity.tail(3); Eigen::VectorXd orientationError = dart::math::logMap(_desiredOrientation * currentWorldOrientation.transpose()); Eigen::VectorXd desiredTorques = _pOrientationGain * orientationError - _dOrientationGain * currentWorldSpatialVelocity.head(3); /* Combine forces and torques in one vector */ Eigen::VectorXd tau(6); tau.head(3) = desiredTorques; tau.tail(3) = desiredForces; /* Compute final forces + gravity compensation + regularization */ forces = J.transpose() * tau + _model->getCoriolisAndGravityForces() - _dRegularization * dq; } /* Compute final command signal */ Eigen::VectorXd commands = _manipulator->getCommands(); commands.setZero(); commands.head(7) = forces; /* Compute command for gripper */ commands[7] = _pGripperGain * (_gripperDesiredPosition - _manipulator->getPosition(7)); _manipulator->setCommands(commands); } DrawableObject::DrawableObject(std::vector<std::reference_wrapper<GL::Mesh>>&& meshes, std::vector<MaterialData>&& materials, Object3D* parent, SceneGraph::DrawableGroup3D* group): Object3D{parent}, SceneGraph::Drawable3D{*this, group}, _color_shader{ViewerResourceManager::instance().get<Shaders::Phong>("color")}, _texture_shader{ViewerResourceManager::instance().get<Shaders::Phong>("texture")}, _meshes{std::move(meshes)}, _materials{std::move(materials)} { CORRADE_INTERNAL_ASSERT(_materials.size() >= meshes.size()); _isSoftBody.resize(_meshes.size(), false); _textures.resize(_meshes.size()); } void DrawableObject::draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) { for(std::size_t i = 0; i < _meshes.size(); ++i) { GL::Mesh& mesh = _meshes[i]; Matrix4 scalingMatrix = Matrix4::scaling(_materials[i].scaling); if(_isSoftBody[i]) GL::Renderer::disable(GL::Renderer::Feature::FaceCulling); if(!_textures[i]) { (*_color_shader) .setAmbientColor(_materials[i].ambientColor) .setDiffuseColor(_materials[i].diffuseColor) .setSpecularColor(_materials[i].specularColor) .setShininess(_materials[i].shininess) .setLightPosition(0, camera.cameraMatrix().transformPoint({0.0f, 2.0f, 3.0f})) .setLightPosition(1, camera.cameraMatrix().transformPoint({0.0f, -2.0f, 3.0f})) .setTransformationMatrix(transformationMatrix*scalingMatrix) .setNormalMatrix((transformationMatrix*scalingMatrix).rotation()) .setProjectionMatrix(camera.projectionMatrix()); mesh.draw(*_color_shader); } else { (*_texture_shader) .setAmbientColor(_materials[i].ambientColor) .bindDiffuseTexture(*_textures[i]) .setSpecularColor(_materials[i].specularColor) .setShininess(_materials[i].shininess) .setLightPosition(0, camera.cameraMatrix().transformPoint({0.0f, 2.0f, 3.0f})) .setLightPosition(1, camera.cameraMatrix().transformPoint({0.0f, -2.0f, 3.0f})) .setTransformationMatrix(transformationMatrix*scalingMatrix) .setNormalMatrix((transformationMatrix*scalingMatrix).rotation()) .setProjectionMatrix(camera.projectionMatrix()); mesh.draw(*_texture_shader); } if(_isSoftBody[i]) GL::Renderer::enable(GL::Renderer::Feature::FaceCulling); } } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::DartExample) dart: an optional reference is just a pointer. No need to get *that* fancy. /* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 — Vladimír Vondruš <mosra@centrum.cz> 2019 — Konstantinos Chatzilygeroudis <costashatz@gmail.com> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <dart/collision/dart/DARTCollisionDetector.hpp> #include <dart/constraint/ConstraintSolver.hpp> #include <dart/dynamics/BallJoint.hpp> #include <dart/dynamics/BodyNode.hpp> #include <dart/dynamics/BoxShape.hpp> #include <dart/dynamics/CylinderShape.hpp> #include <dart/dynamics/EllipsoidShape.hpp> #include <dart/dynamics/FreeJoint.hpp> #include <dart/dynamics/MeshShape.hpp> #include <dart/dynamics/RevoluteJoint.hpp> #include <dart/dynamics/SoftBodyNode.hpp> #include <dart/dynamics/SoftMeshShape.hpp> #include <dart/dynamics/Skeleton.hpp> #include <dart/dynamics/WeldJoint.hpp> #include <dart/simulation/World.hpp> #include <Corrade/Containers/Reference.h> #include <Corrade/Utility/Directory.h> #include <Magnum/ResourceManager.h> #include <Magnum/DartIntegration/ConvertShapeNode.h> #include <Magnum/DartIntegration/World.h> #include <Magnum/GL/Buffer.h> #include <Magnum/GL/DefaultFramebuffer.h> #include <Magnum/GL/Mesh.h> #include <Magnum/GL/Renderer.h> #include <Magnum/GL/Texture.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/MatrixTransformation3D.h> #include <Magnum/SceneGraph/Object.hpp> #include <Magnum/SceneGraph/SceneGraph.h> #include <Magnum/Shaders/Phong.h> #include <Magnum/Trade/PhongMaterialData.h> #include "configure.h" #if DART_MAJOR_VERSION == 6 #include <dart/utils/urdf/urdf.hpp> typedef dart::utils::DartLoader DartLoader; #else #include <dart/io/urdf/urdf.hpp> typedef dart::io::DartLoader DartLoader; #endif namespace Magnum { namespace Examples { namespace { /* Helper functions */ dart::dynamics::SkeletonPtr createBox(const std::string& name = "box", const Eigen::Vector3d& color = Eigen::Vector3d{0.8, 0.0, 0.0}) { /* The size of our box */ constexpr Double boxSize = 0.06; /* Calculate the mass of the box */ constexpr Double boxDensity = 260; // kg/m^3 constexpr Double boxMass = boxDensity*Math::pow<3>(boxSize); /* Create a Skeleton with the given name */ dart::dynamics::SkeletonPtr box = dart::dynamics::Skeleton::create(name); /* Create a body for the box */ dart::dynamics::BodyNodePtr body = box ->createJointAndBodyNodePair<dart::dynamics::FreeJoint>(nullptr).second; /* Create a shape for the box */ std::shared_ptr<dart::dynamics::BoxShape> boxShape( new dart::dynamics::BoxShape(Eigen::Vector3d{boxSize, boxSize, boxSize})); auto shapeNode = body->createShapeNodeWith<dart::dynamics::VisualAspect, dart::dynamics::CollisionAspect, dart::dynamics::DynamicsAspect>(boxShape); shapeNode->getVisualAspect()->setColor(color); /* Set up inertia for the box */ dart::dynamics::Inertia inertia; inertia.setMass(boxMass); inertia.setMoment(boxShape->computeInertia(boxMass)); body->setInertia(inertia); /* Setup the center of the box properly */ box->getDof("Joint_pos_z")->setPosition(boxSize/2.0); return box; } dart::dynamics::SkeletonPtr createFloor() { /* Create a floor */ dart::dynamics::SkeletonPtr floorSkel = dart::dynamics::Skeleton::create("floor"); /* Give the floor a body */ dart::dynamics::BodyNodePtr body = floorSkel->createJointAndBodyNodePair<dart::dynamics::WeldJoint>(nullptr).second; /* Give the floor a shape */ constexpr double floorWidth = 10.0; constexpr double floorHeight = 0.1; std::shared_ptr<dart::dynamics::BoxShape> box( new dart::dynamics::BoxShape(Eigen::Vector3d{floorWidth, floorWidth, floorHeight})); auto shapeNode = body->createShapeNodeWith<dart::dynamics::VisualAspect, dart::dynamics::CollisionAspect, dart::dynamics::DynamicsAspect>(box); shapeNode->getVisualAspect()->setColor(Eigen::Vector3d(0.3, 0.3, 0.4)); /* Put the floor into position */ Eigen::Isometry3d tf(Eigen::Isometry3d::Identity()); tf.translation() = Eigen::Vector3d{0.0, 0.0, -floorHeight/2.0}; body->getParentJoint()->setTransformFromParentBodyNode(tf); return floorSkel; } } using namespace Magnum::Math::Literals; typedef ResourceManager<GL::Buffer, GL::Mesh, Shaders::Phong> ViewerResourceManager; typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D; typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D; struct MaterialData{ Vector3 ambientColor, diffuseColor, specularColor; Float shininess; Vector3 scaling; }; class DrawableObject: public Object3D, SceneGraph::Drawable3D { public: explicit DrawableObject(std::vector<std::reference_wrapper<GL::Mesh>>&& meshes, std::vector<MaterialData>&& materials, Object3D* parent, SceneGraph::DrawableGroup3D* group); DrawableObject& setMeshes(std::vector<std::reference_wrapper<GL::Mesh>>&& meshes){ _meshes = std::move(meshes); return *this; } DrawableObject& setMaterials(std::vector<MaterialData>&& materials) { _materials = std::move(materials); return *this; } DrawableObject& setSoftBodies(std::vector<bool>&& softBody) { _isSoftBody = std::move(softBody); return *this; } DrawableObject& setTextures(std::vector<GL::Texture2D*>&& textures) { _textures = std::move(textures); return *this; } private: void draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) override; Resource<Shaders::Phong> _color_shader; Resource<Shaders::Phong> _texture_shader; std::vector<std::reference_wrapper<GL::Mesh>> _meshes; std::vector<MaterialData> _materials; std::vector<bool> _isSoftBody; std::vector<GL::Texture2D*> _textures; }; class DartExample: public Platform::Application { public: /* home: go to home position, active: go to active box */ enum State {home, active}; explicit DartExample(const Arguments& arguments); private: void viewportEvent(const Vector2i& size) override; void drawEvent() override; void keyPressEvent(KeyEvent& event) override; void updateManipulator(); ViewerResourceManager _resourceManager; Scene3D _scene; SceneGraph::DrawableGroup3D _drawables; SceneGraph::Camera3D* _camera; Object3D *_cameraRig, *_cameraObject; /* DART */ std::unique_ptr<DartIntegration::World> _dartWorld; std::unordered_map<DartIntegration::Object*, DrawableObject*> _drawableObjects; std::vector<Object3D*> _dartObjs; dart::dynamics::SkeletonPtr _manipulator, _model, _redBoxSkel, _greenBoxSkel, _blueBoxSkel; dart::simulation::WorldPtr _world; Eigen::VectorXd _redInitPosition, _greenInitPosition, _blueInitPosition; /* DART control */ Eigen::VectorXd _desiredPosition; Eigen::MatrixXd _desiredOrientation; Double _gripperDesiredPosition; const Double _pGripperGain = 100.0; const Double _pLinearGain = 500.0; const Double _dLinearGain = 200.0; const Double _pOrientationGain = 100.0; const Double _dOrientationGain = 50.0; const Double _dRegularization = 10.0; const Double _pGain = 2.25; const Double _dGain = 5.0; /* Simple State Machine */ State _state = home; }; DartExample::DartExample(const Arguments& arguments): Platform::Application{arguments, NoCreate} { /* Try 8x MSAA */ Configuration conf; GLConfiguration glConf; conf.setTitle("Magnum Dart Integration Example"); glConf.setSampleCount(8); if(!tryCreate(conf, glConf)) create(conf, glConf.setSampleCount(0)); GL::Renderer::enable(GL::Renderer::Feature::DepthTest); GL::Renderer::enable(GL::Renderer::Feature::FaceCulling); /* Camera setup */ (_cameraRig = new Object3D(&_scene)); (_cameraObject = new Object3D(_cameraRig)); (_camera = new SceneGraph::Camera3D(*_cameraObject)) ->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) .setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 1.0f, 0.001f, 100.0f)) .setViewport(GL::defaultFramebuffer.viewport().size()); /* DART has +Z-axis as up direction*/ _cameraObject->setTransformation(Matrix4::lookAt( {0.0f, 3.0f, 1.5f}, {0.0f, 0.0f, 0.5f}, {0.0f, 0.0f, 1.0f})); /* DART: Load Skeletons/Robots */ DartLoader loader; /* Add packages (needed for URDF loading) */ std::string res_path = Utility::Directory::join(DARTEXAMPLE_DIR, "urdf"); loader.addPackageDirectory("iiwa_description", res_path); loader.addPackageDirectory("robotiq_arg85_description", res_path); std::string filename = Utility::Directory::join(res_path, "iiwa14_simple.urdf"); /* First load the KUKA manipulator */ _manipulator = loader.parseSkeleton(filename); for(std::size_t i = 0; i < _manipulator->getNumJoints(); ++i) _manipulator->getJoint(i)->setPositionLimitEnforced(true); _manipulator->disableSelfCollisionCheck(); /* Clone the KUKA manipulator to use it as model in a model-based controller */ #if DART_VERSION_AT_LEAST(6, 7, 2) _model = _manipulator->cloneSkeleton(); #else _model = _manipulator->clone(); #endif /* Load the Robotiq 2-finger gripper */ filename = Utility::Directory::join(res_path, "robotiq.urdf"); auto gripper_skel = loader.parseSkeleton(filename); /* The gripper is controlled in velocity mode: servo actuator */ gripper_skel->getJoint("finger_joint")->setActuatorType(dart::dynamics::Joint::SERVO); /* Attach gripper to manipulator */ dart::dynamics::WeldJoint::Properties properties = dart::dynamics::WeldJoint::Properties(); properties.mT_ChildBodyToJoint.translation() = Eigen::Vector3d(0, 0, 0.0001); gripper_skel->getRootBodyNode()->moveTo<dart::dynamics::WeldJoint>(_manipulator->getBodyNode("iiwa_link_ee"), properties); /* Create floor */ auto floorSkel = createFloor(); /* Create red box */ _redBoxSkel = createBox("red", Eigen::Vector3d{0.8, 0.0, 0.0}); /* Position it at (0.5, 0.) [x,y] */ _redBoxSkel->setPosition(3, 0.5); /* Save initial position for resetting */ _redInitPosition = _redBoxSkel->getPositions(); /* Create green box */ _greenBoxSkel = createBox("green", Eigen::Vector3d{0.0, 0.8, 0.0}); /* Position it at (0.5, 0.2) */ _greenBoxSkel->setPosition(3, 0.5); _greenBoxSkel->setPosition(4, 0.2); /* Save initial position for resetting */ _greenInitPosition = _greenBoxSkel->getPositions(); /* Create blue box */ _blueBoxSkel = createBox("blue", Eigen::Vector3d{0.0, 0.0, 0.8}); /* Position it at (0.5, -0.2) */ _blueBoxSkel->setPosition(3, 0.5); _blueBoxSkel->setPosition(4, -0.2); /* Save initial position for resetting */ _blueInitPosition = _blueBoxSkel->getPositions(); /* Create the DART world */ _world = dart::simulation::WorldPtr{new dart::simulation::World}; /* Use a simple but very fast collision detector. This plays the most important role for having a fast simulation. */ _world->getConstraintSolver()->setCollisionDetector(dart::collision::DARTCollisionDetector::create()); /* Add the robot/objects in our DART world */ _world->addSkeleton(_manipulator); _world->addSkeleton(floorSkel); _world->addSkeleton(_redBoxSkel); _world->addSkeleton(_greenBoxSkel); _world->addSkeleton(_blueBoxSkel); /* Setup desired locations/orientations */ _desiredOrientation = Eigen::MatrixXd(3, 3); /* 3D rotation matrix */ /* Looking towards -Z direction (towards the floor) */ _desiredOrientation << 1, 0, 0, 0, -1, 0, 0, 0, -1; /* Default desired position is the red box position */ _desiredPosition = _redBoxSkel->getPositions().tail(3); _desiredPosition[2] += 0.17; /* Gripper default desired position: stay in the initial configuration (i.e., open) */ _gripperDesiredPosition = _manipulator->getPosition(7); /* faster simulation step; less accurate simulation/collision detection */ /* _world->setTimeStep(0.015); */ /* slower simulation step; better accuracy */ _world->setTimeStep(0.001); /* Create our DARTIntegration object/world */ auto dartObj = new Object3D{&_scene}; _dartWorld.reset(new DartIntegration::World{*dartObj, *_world}); /* Phong shader instances */ _resourceManager.set("color", new Shaders::Phong{{}, 2}); _resourceManager.set("texture", new Shaders::Phong(Shaders::Phong::Flag::DiffuseTexture, 2)); /* Loop at 60 Hz max */ setSwapInterval(1); setMinimalLoopPeriod(16); redraw(); } void DartExample::viewportEvent(const Vector2i& size) { GL::defaultFramebuffer.setViewport({{}, size}); _camera->setViewport(size); } void DartExample::drawEvent() { GL::defaultFramebuffer.clear( GL::FramebufferClear::Color|GL::FramebufferClear::Depth); /* We want around 60Hz display rate */ UnsignedInt steps = Math::round(1.0/(60.0*_world->getTimeStep())); /* Step DART simulation */ for(UnsignedInt i = 0; i < steps; ++i) { /* Compute control signals for manipulator */ updateManipulator(); /* Step the simulated world */ _dartWorld->step(); } /* Update graphic meshes/materials and render */ _dartWorld->refresh(); /* For each update object */ for(DartIntegration::Object& object : _dartWorld->updatedShapeObjects()) { /* Get material information */ std::vector<MaterialData> materials; std::vector<std::reference_wrapper<GL::Mesh>> meshes; std::vector<bool> isSoftBody; std::vector<GL::Texture2D*> textures; for(std::size_t i = 0; i < object.drawData().meshes.size(); ++i) { bool isColor = true; GL::Texture2D* texture = nullptr; if(object.drawData().materials[i].flags() & Trade::PhongMaterialData::Flag::DiffuseTexture) { Containers::Optional<GL::Texture2D>& entry = object.drawData().textures[object.drawData().materials[i].diffuseTexture()]; if(entry) { texture = &*entry; isColor = false; } } textures.push_back(texture); MaterialData mat; mat.ambientColor = object.drawData().materials[i].ambientColor().rgb(); if(isColor) mat.diffuseColor = object.drawData().materials[i].diffuseColor().rgb(); mat.specularColor = object.drawData().materials[i].specularColor().rgb(); mat.shininess = object.drawData().materials[i].shininess(); mat.scaling = object.drawData().scaling; /* Get the modified mesh */ GL::Mesh& mesh = object.drawData().meshes[i]; meshes.push_back(mesh); materials.push_back(mat); if(object.shapeNode()->getShape()->getType() == dart::dynamics::SoftMeshShape::getStaticType()) isSoftBody.push_back(true); else isSoftBody.push_back(false); } /* Check if we already have it and then either add a new one or update the existing. We don't need the mesh / material / texture vectors anywhere else anymore, so move them in to avoid copies. */ auto it = _drawableObjects.insert(std::make_pair(&object, nullptr)); if(it.second) { auto drawableObj = new DrawableObject{ std::move(meshes), std::move(materials), static_cast<Object3D*>(&(object.object())), &_drawables}; drawableObj->setSoftBodies(std::move(isSoftBody)); drawableObj->setTextures(std::move(textures)); it.first->second = drawableObj; } else { (*it.first->second) .setMeshes(std::move(meshes)) .setMaterials(std::move(materials)) .setSoftBodies(std::move(isSoftBody)) .setTextures(std::move(textures)); } } _dartWorld->clearUpdatedShapeObjects(); _camera->draw(_drawables); swapBuffers(); redraw(); } void DartExample::keyPressEvent(KeyEvent& event) { if(event.key() == KeyEvent::Key::Down) { _cameraObject->rotateX(5.0_degf); } else if(event.key() == KeyEvent::Key::Up) { _cameraObject->rotateX(-5.0_degf); } else if(event.key() == KeyEvent::Key::Left) { _cameraRig->rotateY(-5.0_degf); } else if(event.key() == KeyEvent::Key::Right) { _cameraRig->rotateY(5.0_degf); } else if(event.key() == KeyEvent::Key::C) { _gripperDesiredPosition = 0.3; } else if(event.key() == KeyEvent::Key::O) { _gripperDesiredPosition = 0.; } else if(event.key() == KeyEvent::Key::U && _state == 1) { _desiredPosition[2] += 0.1; } else if(event.key() == KeyEvent::Key::D && _state == 1) { _desiredPosition[2] -= 0.1; } else if(event.key() == KeyEvent::Key::Z && _state == 1) { _desiredPosition[1] += 0.2; } else if(event.key() == KeyEvent::Key::X && _state == 1) { _desiredPosition[1] -= 0.2; } else if(event.key() == KeyEvent::Key::R) { _desiredPosition = _redBoxSkel->getPositions().tail(3); _desiredPosition[2] += 0.25; _state = active; } else if(event.key() == KeyEvent::Key::G) { _desiredPosition = _greenBoxSkel->getPositions().tail(3); _desiredPosition[2] += 0.25; _state = active; } else if(event.key() == KeyEvent::Key::B) { _desiredPosition = _blueBoxSkel->getPositions().tail(3); _desiredPosition[2] += 0.25; _state = active; } else if(event.key() == KeyEvent::Key::H) { _state = home; } else if(event.key() == KeyEvent::Key::Space) { /* Reset _state machine */ _state = home; /* Reset manipulator */ _manipulator->resetPositions(); _manipulator->resetVelocities(); _gripperDesiredPosition = 0.; /* Reset boxes */ /* Red box */ _redBoxSkel->resetVelocities(); _redBoxSkel->setPositions(_redInitPosition); /* Green box */ _greenBoxSkel->resetVelocities(); _greenBoxSkel->setPositions(_greenInitPosition); /* Blue box */ _blueBoxSkel->resetVelocities(); _blueBoxSkel->setPositions(_blueInitPosition); } else return; event.setAccepted(); } void DartExample::updateManipulator() { Eigen::VectorXd forces(7); /* Update our model with manipulator's measured joint positions and velocities */ _model->setPositions(_manipulator->getPositions().head(7)); _model->setVelocities(_manipulator->getVelocities().head(7)); if(_state == home) { /* Go to zero (home) position */ Eigen::VectorXd q = _model->getPositions(); Eigen::VectorXd dq = _model->getVelocities(); forces = -_pGain * q - _dGain * dq + _manipulator->getCoriolisAndGravityForces().head(7); } else { /* Get joint velocities of manipulator */ Eigen::VectorXd dq = _model->getVelocities(); /* Get full Jacobian of our end-effector */ Eigen::MatrixXd J = _model->getBodyNode("iiwa_link_ee")->getWorldJacobian(); /* Get current _state of the end-effector */ Eigen::MatrixXd currentWorldTransformation = _model->getBodyNode("iiwa_link_ee")->getWorldTransform().matrix(); Eigen::VectorXd currentWorldPosition = currentWorldTransformation.block(0, 3, 3, 1); Eigen::MatrixXd currentWorldOrientation = currentWorldTransformation.block(0, 0, 3, 3); Eigen::VectorXd currentWorldSpatialVelocity = _model->getBodyNode("iiwa_link_ee")->getSpatialVelocity(dart::dynamics::Frame::World(), dart::dynamics::Frame::World()); /* Compute desired forces and torques */ Eigen::VectorXd linearError = _desiredPosition - currentWorldPosition; Eigen::VectorXd desiredForces = _pLinearGain * linearError - _dLinearGain * currentWorldSpatialVelocity.tail(3); Eigen::VectorXd orientationError = dart::math::logMap(_desiredOrientation * currentWorldOrientation.transpose()); Eigen::VectorXd desiredTorques = _pOrientationGain * orientationError - _dOrientationGain * currentWorldSpatialVelocity.head(3); /* Combine forces and torques in one vector */ Eigen::VectorXd tau(6); tau.head(3) = desiredTorques; tau.tail(3) = desiredForces; /* Compute final forces + gravity compensation + regularization */ forces = J.transpose() * tau + _model->getCoriolisAndGravityForces() - _dRegularization * dq; } /* Compute final command signal */ Eigen::VectorXd commands = _manipulator->getCommands(); commands.setZero(); commands.head(7) = forces; /* Compute command for gripper */ commands[7] = _pGripperGain * (_gripperDesiredPosition - _manipulator->getPosition(7)); _manipulator->setCommands(commands); } DrawableObject::DrawableObject(std::vector<std::reference_wrapper<GL::Mesh>>&& meshes, std::vector<MaterialData>&& materials, Object3D* parent, SceneGraph::DrawableGroup3D* group): Object3D{parent}, SceneGraph::Drawable3D{*this, group}, _color_shader{ViewerResourceManager::instance().get<Shaders::Phong>("color")}, _texture_shader{ViewerResourceManager::instance().get<Shaders::Phong>("texture")}, _meshes{std::move(meshes)}, _materials{std::move(materials)} { CORRADE_INTERNAL_ASSERT(_materials.size() >= meshes.size()); _isSoftBody.resize(_meshes.size(), false); _textures.resize(_meshes.size()); } void DrawableObject::draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) { for(std::size_t i = 0; i < _meshes.size(); ++i) { GL::Mesh& mesh = _meshes[i]; Matrix4 scalingMatrix = Matrix4::scaling(_materials[i].scaling); if(_isSoftBody[i]) GL::Renderer::disable(GL::Renderer::Feature::FaceCulling); if(!_textures[i]) { (*_color_shader) .setAmbientColor(_materials[i].ambientColor) .setDiffuseColor(_materials[i].diffuseColor) .setSpecularColor(_materials[i].specularColor) .setShininess(_materials[i].shininess) .setLightPosition(0, camera.cameraMatrix().transformPoint({0.0f, 2.0f, 3.0f})) .setLightPosition(1, camera.cameraMatrix().transformPoint({0.0f, -2.0f, 3.0f})) .setTransformationMatrix(transformationMatrix*scalingMatrix) .setNormalMatrix((transformationMatrix*scalingMatrix).rotation()) .setProjectionMatrix(camera.projectionMatrix()); mesh.draw(*_color_shader); } else { (*_texture_shader) .setAmbientColor(_materials[i].ambientColor) .bindDiffuseTexture(*_textures[i]) .setSpecularColor(_materials[i].specularColor) .setShininess(_materials[i].shininess) .setLightPosition(0, camera.cameraMatrix().transformPoint({0.0f, 2.0f, 3.0f})) .setLightPosition(1, camera.cameraMatrix().transformPoint({0.0f, -2.0f, 3.0f})) .setTransformationMatrix(transformationMatrix*scalingMatrix) .setNormalMatrix((transformationMatrix*scalingMatrix).rotation()) .setProjectionMatrix(camera.projectionMatrix()); mesh.draw(*_texture_shader); } if(_isSoftBody[i]) GL::Renderer::enable(GL::Renderer::Feature::FaceCulling); } } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::DartExample)
/* * Author: wysaid * Mail: admin@wysaid.org * Blog: http://blog.wysaid.org */ #include "cgeMat.h" #include "cgeVec.h" #include "graphics.h" #include "teapot.h" #include <vector> #include <cassert> using namespace CGE; #define USE_DEPTH_TEST 0 //Not available, must be 0. //Change them as you like #define USE_PERSPECTIVE_PROJ 1 #define RENDER_TRIANGLE_HALF_1 1 #define RENDER_TRIANGLE_HALF_2 0 #define USE_CULL_FACE_BACK 1 #define USE_CULL_FACE_FRONT 0 #define SCREEN_WIDTH 800 #define SCREEN_HEIGHT 600 #if USE_DEPTH_TEST //depth 还存在一点问题, 没有效果 unsigned char g_depthMask[SCREEN_WIDTH][SCREEN_HEIGHT]; const int g_maskSize = sizeof(g_depthMask); #endif color_t g_color; template<class Type> class Triangle { public: static inline void fillTriangle(const Type& v0, const Type& v1, const Type& v2) { if(v0[1] == v2[1]) { _fillSimpleTriangle(v0, v1, v2); } else if(v1[1] == v2[1]) { _fillSimpleTriangle(v1, v0, v2); } else if(v0[1] == v1[1]) { _fillSimpleTriangle(v0, v2, v1); } else { _fillNormalTriangle(v0, v1, v2); } } private: #if USE_DEPTH_TEST static inline void drawPixel(int x, int y, int depth, color_t color) { if(x < 0 || x >= SCREEN_WIDTH || y < 0 || y >= SCREEN_HEIGHT) return; if(depth >=0 && depth < 256 && g_depthMask[x][y] <= depth) { putpixel_f(x, y, color); g_depthMask[x][y] = depth; } } static inline void drawLineL2R(int x0, int depth0, int x1, int depth1, int y, color_t color) { if(x0 == x1) { drawPixel(x0, y, depth0, color); return; } int left, right; int depthL, depthR; if(x0 < x1) { left = x0; right = x1; depthL = depth0; depthR = depth1; } else { left = x1; right = x0; depthL = depth1; depthR = depth0; } float delta = float(depthR - depthL) / (right - left); for(int i = left; i <= right; ++i) { drawPixel(i, y, depthL, color); depthL += delta; } } #endif // 平顶/平底三角形, v0[1] == v2[1], v1[1] 最大 static inline void _fillSimpleTriangle(const Type& v0, const Type& v1, const Type& v2) { assert(v0[1] == v2[1]); float h = v1[1] - v0[1]; float dL = (v1[0] - v0[0]) / h; float dR = (v1[0] - v2[0]) / h; float xL = v0[0], xR = v2[0]; #if USE_DEPTH_TEST static_assert(Type::VEC_DIM >= 3, "Depth-Test is not available now!"); float dDepthL = (v1[2] - v0[2]) / h; float dDepthR = (v1[2] - v2[2]) / h; float depthL = v0[2], depthR = v2[2]; #endif if(v0[1] < v1[1]) { #if RENDER_TRIANGLE_HALF_1 for(int i = v0[1]; i <= v1[1]; ++i) { #if USE_DEPTH_TEST drawLineL2R(xL, depthL, xR, depthR, i, RED); depthL += dDepthL; depthR += dDepthR; #else line(xL, i, xR, i); //A Simple Function That Just Draw A Line #endif //USE_DEPTH_TEST xL += dL; xR += dR; } #endif //RENDER_TRIANGLE_HALF_1 } else { #if RENDER_TRIANGLE_HALF_2 for(int i = v0[1]; i >= v1[1]; --i) { #if USE_DEPTH_TEST drawLineL2R(xL, depthL, xR, depthR, i, YELLOW); depthL -= dDepthL; depthR -= dDepthR; #else line(xL, i, xR, i); //A Simple Function That Just Draw A Line #endif //USE_DEPTH_TEST xL -= dL; xR -= dR; } #endif } } static inline void _fillNormalTriangle(const Type& v0, const Type& v1, const Type& v2) { const Type *pnts[] = {&v0, &v1, &v2}; if((*pnts[0])[1] > (*pnts[1])[1]) std::swap(pnts[0], pnts[1]); if((*pnts[0])[1] > (*pnts[2])[1]) std::swap(pnts[0], pnts[2]); if((*pnts[1])[1] > (*pnts[2])[1]) std::swap(pnts[1], pnts[2]); const Type &vv0 = *pnts[0], &vv1 = *pnts[1], &vv2 = *pnts[2]; Type newPoint(vv1); newPoint[0] = vv0[0] + (vv2[0] - vv0[0]) * (vv1[1] - vv0[1]) / (vv2[1] - vv0[1]); _fillSimpleTriangle(newPoint, vv0, vv1); _fillSimpleTriangle(newPoint, vv2, vv1); } }; class Object { public: Object() { //改变 USE_PERSPECTIVE_PROJ 的值可以切换两种视图 #if USE_PERSPECTIVE_PROJ m_matProj = Mat4::makePerspective(M_PI / 4.0f, 4.0f / 3.0f, 1.0f, 1000.0f); m_matModelView = Mat4::makeLookAt(0.0f, 0.0f, 800.0f, 0.0f, 0.0f, -1000.0f, 0.0f, 1.0f, 0.0f); #else m_matProj = Mat4::makeOrtho(-400.0f, 400.0f, -300.0f, 300.0f, -300.0f, 300.0f); m_matModelView.loadIdentity(); #endif } ~Object() {} void render(float x, float y) { std::vector<Vec2f> vec(m_vecPositions.size()); const Mat4 mvp = m_matProj * m_matModelView; const Vec4f viewPort(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT); auto iter = vec.begin(); for(auto& t : m_vecPositions) { Vec2f coord; Mat4::projectM4f(t, mvp, viewPort, coord); *iter++ = coord; } vec.reserve(g_teapotIndicesNum); for(int i = 0; i < g_teapotIndicesNum; i += 3) { const int index1 = g_teapotIndices[i]; const int index2 = g_teapotIndices[i + 1]; const int index3 = g_teapotIndices[i + 2]; const Vec2i posPoints[] = { Vec2i(x + vec[index1][0], y + vec[index1][1]),// vec[index1][2] * 255.0f), Vec2i(x + vec[index2][0], y + vec[index2][1]),// vec[index2][2] * 255.0f), Vec2i(x + vec[index3][0], y + vec[index3][1]) // vec[index3][2] * 255.0f) }; //设置是否进行面剔除 #if USE_CULL_FACE_BACK || USE_CULL_FACE_FRONT float ax = posPoints[1][0] - posPoints[0][0]; float ay = posPoints[1][1] - posPoints[0][1]; float bx = posPoints[2][0] - posPoints[1][0]; float by = posPoints[2][1] - posPoints[1][1]; float zNorm = ax * by - ay * bx; #if USE_CULL_FACE_BACK if(zNorm <= 0.0f) { goto Render_Wire_Frame; //continue; } #endif #if USE_CULL_FACE_FRONT if(zNorm > 0.0f) { goto Render_Wire_Frame; //continue; } #endif #endif //设置是否显示模拟填充 #if RENDER_TRIANGLE_HALF_1 || RENDER_TRIANGLE_HALF_2 setcolor(g_color ^ 0xffffff); #if USE_DEPTH_TEST memset(g_depthMask, 0, g_maskSize); #endif //USE_DEPTH_TEST Triangle<Vec2i>::fillTriangle(posPoints[0], posPoints[1], posPoints[2]); #endif //RENDER_TRIANGLE_HALF_1 || RENDER_TRIANGLE_HALF_2 Render_Wire_Frame: setcolor(g_color); line(posPoints[0][0], posPoints[0][1], posPoints[1][0], posPoints[1][1]); line(posPoints[1][0], posPoints[1][1], posPoints[2][0], posPoints[2][1]); line(posPoints[2][0], posPoints[2][1], posPoints[0][0], posPoints[0][1]); } } void pushPoint(Vec3f pnt) { m_vecPositions.push_back(pnt); } void pushPoints(Vec3f* pnt, int n) { for(int i = 0; i != n; ++i) { m_vecPositions.push_back(pnt[i]); } } void pushPoint(float x, float y, float z) { m_vecPositions.push_back(Vec3f(x, y, z)); } void rotate(float rad, float x, float y, float z) { m_matModelView.rotate(rad, x, y, z); } void rotateX(float rad) { m_matModelView.rotateX(rad); } void rotateY(float rad) { m_matModelView.rotateY(rad); } void rotateZ(float rad) { m_matModelView.rotateZ(rad); } void translateZ(float z) { m_matModelView.translateZ(z); } void clear() { m_vecPositions.clear(); } std::vector<Vec3f>& getPositions() { return m_vecPositions; } std::vector<int>& getIndices() { return m_vecIndices; } private: std::vector<Vec3f> m_vecPositions; std::vector<int> m_vecIndices; Mat4 m_matProj, m_matModelView; }; bool mouseFunc(Object& obj) { if(!mousemsg()) return false; do { static int s_lastX, s_lastY; static int s_bIsDown = false; mouse_msg msg = getmouse(); switch (msg.msg) { case mouse_msg_down: s_lastX = msg.x; s_lastY = msg.y; s_bIsDown = true; break; case mouse_msg_up: s_bIsDown = false; break; case mouse_msg_wheel: obj.translateZ(msg.wheel / 12.0f); break; default: break; } if(s_bIsDown && msg.is_move()) { obj.rotateX((msg.y - s_lastY) / 100.0f); obj.rotateY((msg.x - s_lastX) / 100.0f); s_lastX = msg.x; s_lastY = msg.y; } }while(mousemsg()); return true; } void genTeapot(Object& obj, float scale) { auto& pos = obj.getPositions(); auto& indices = obj.getIndices(); pos.clear(); pos.reserve(g_teapotIndicesNum / 3); for(int i = 0; i < g_teapotPositionNum; i += 3) { pos.push_back(Vec3f(g_teapotPositions[i] * scale, g_teapotPositions[i + 1] * scale, g_teapotPositions[i + 2] * scale)); } indices.clear(); indices.assign(g_teapotIndices, g_teapotIndices + g_teapotIndicesNum); } int main() { setinitmode(INIT_RENDERMANUAL); initgraph(SCREEN_WIDTH, SCREEN_HEIGHT); setrendermode(RENDER_MANUAL); Object obj; randomize(); genTeapot(obj, 10.0f); int i = 0; static bool s_useBlur = false; float x = 0.0f, y = 0.0f; float dx = randomf()* 5.0f + 1.0f, dy = randomf()* 5.0f + 1.0f; float radX = randomf()*10.0f + 0.001f, radY = randomf() * 10.0f, radZ = randomf() * 10.0f; setbkmode(TRANSPARENT); setfillcolor(DARKGRAY); for(; is_run(); delay_fps(60)) { if(s_useBlur) imagefilter_blurring(0, 0x79, 0x100); else cleardevice(); mouseFunc(obj); obj.render(0, 0); g_color = HSVtoRGB(i*2, 1.0f, 1.0f); outtextxy(20, 10, "点击空格键启用模糊滤镜, 鼠标滚轮移动模型Z值, enter键截屏"); x += dx; y += dy; if(x < 0.0f || x > 800.0f) { dx = -dx; x += dx; } if(y < 0.0f || y > 600.0f) { dy = -dy; y += dy; } ++i %= 360; if(kbhit()) { switch (getch()) { case ' ': s_useBlur = !s_useBlur; break; case '\r':case '\n': { saveimage(NULL, "screen_shot.bmp"); } break; default: break; } flushkey(); } } closegraph(); return 0; } optimize /* * Author: wysaid * Mail: admin@wysaid.org * Blog: http://blog.wysaid.org */ #include "cgeMat.h" #include "cgeVec.h" #include "graphics.h" #include "teapot.h" #include <vector> #include <cassert> using namespace CGE; #define USE_DEPTH_TEST 0 //Not available, must be 0. //Change them as you like #define USE_PERSPECTIVE_PROJ 1 #define RENDER_TRIANGLE_HALF_1 1 #define RENDER_TRIANGLE_HALF_2 0 #define USE_CULL_FACE_BACK 1 #define USE_CULL_FACE_FRONT 0 #define SCREEN_WIDTH 800 #define SCREEN_HEIGHT 600 #if USE_DEPTH_TEST //depth 还存在一点问题, 没有效果 unsigned char g_depthMask[SCREEN_WIDTH][SCREEN_HEIGHT]; const int g_maskSize = sizeof(g_depthMask); #endif color_t g_color; template<class Type> class Triangle { public: static inline void fillTriangle(const Type& v0, const Type& v1, const Type& v2) { if(v0[1] == v2[1]) { _fillSimpleTriangle(v0, v1, v2); } else if(v1[1] == v2[1]) { _fillSimpleTriangle(v1, v0, v2); } else if(v0[1] == v1[1]) { _fillSimpleTriangle(v0, v2, v1); } else { _fillNormalTriangle(v0, v1, v2); } } private: #if USE_DEPTH_TEST static inline void drawPixel(int x, int y, int depth, color_t color) { if(x < 0 || x >= SCREEN_WIDTH || y < 0 || y >= SCREEN_HEIGHT) return; if(depth >=0 && depth < 256 && g_depthMask[x][y] <= depth) { putpixel_f(x, y, color); g_depthMask[x][y] = depth; } } static inline void drawLineL2R(int x0, int depth0, int x1, int depth1, int y, color_t color) { if(x0 == x1) { drawPixel(x0, y, depth0, color); return; } int left, right; int depthL, depthR; if(x0 < x1) { left = x0; right = x1; depthL = depth0; depthR = depth1; } else { left = x1; right = x0; depthL = depth1; depthR = depth0; } float delta = float(depthR - depthL) / (right - left); for(int i = left; i <= right; ++i) { drawPixel(i, y, depthL, color); depthL += delta; } } #endif // 平顶/平底三角形, v0[1] == v2[1], v1[1] 最大 static inline void _fillSimpleTriangle(const Type& v0, const Type& v1, const Type& v2) { assert(v0[1] == v2[1]); float h = v1[1] - v0[1]; float dL = (v1[0] - v0[0]) / h; float dR = (v1[0] - v2[0]) / h; float xL = v0[0], xR = v2[0]; #if USE_DEPTH_TEST static_assert(Type::VEC_DIM >= 3, "Depth-Test is not available now!"); float dDepthL = (v1[2] - v0[2]) / h; float dDepthR = (v1[2] - v2[2]) / h; float depthL = v0[2], depthR = v2[2]; #endif if(v0[1] < v1[1]) { #if RENDER_TRIANGLE_HALF_1 for(int i = v0[1]; i <= v1[1]; ++i) { #if USE_DEPTH_TEST drawLineL2R(xL, depthL, xR, depthR, i, RED); depthL += dDepthL; depthR += dDepthR; #else line(xL, i, xR, i); //A Simple Function That Just Draw A Line #endif //USE_DEPTH_TEST xL += dL; xR += dR; } #endif //RENDER_TRIANGLE_HALF_1 } else { #if RENDER_TRIANGLE_HALF_2 for(int i = v0[1]; i >= v1[1]; --i) { #if USE_DEPTH_TEST drawLineL2R(xL, depthL, xR, depthR, i, YELLOW); depthL -= dDepthL; depthR -= dDepthR; #else line(xL, i, xR, i); //A Simple Function That Just Draw A Line #endif //USE_DEPTH_TEST xL -= dL; xR -= dR; } #endif } } static inline void _fillNormalTriangle(const Type& v0, const Type& v1, const Type& v2) { const Type *pnts[] = {&v0, &v1, &v2}; if((*pnts[0])[1] > (*pnts[1])[1]) std::swap(pnts[0], pnts[1]); if((*pnts[0])[1] > (*pnts[2])[1]) std::swap(pnts[0], pnts[2]); if((*pnts[1])[1] > (*pnts[2])[1]) std::swap(pnts[1], pnts[2]); const Type &vv0 = *pnts[0], &vv1 = *pnts[1], &vv2 = *pnts[2]; Type newPoint(vv1); newPoint[0] = vv0[0] + (vv2[0] - vv0[0]) * (vv1[1] - vv0[1]) / (vv2[1] - vv0[1]); _fillSimpleTriangle(newPoint, vv0, vv1); _fillSimpleTriangle(newPoint, vv2, vv1); } }; class Object { public: Object() { //改变 USE_PERSPECTIVE_PROJ 的值可以切换两种视图 #if USE_PERSPECTIVE_PROJ m_matProj = Mat4::makePerspective(M_PI / 4.0f, 4.0f / 3.0f, 1.0f, 1000.0f); m_matModelView = Mat4::makeLookAt(0.0f, 0.0f, 800.0f, 0.0f, 0.0f, -1000.0f, 0.0f, 1.0f, 0.0f); #else m_matProj = Mat4::makeOrtho(-400.0f, 400.0f, -300.0f, 300.0f, -300.0f, 300.0f); m_matModelView.loadIdentity(); #endif } ~Object() {} void render(float x, float y) { m_winCoords.resize(m_vecPositions.size()); const Mat4 mvp = m_matProj * m_matModelView; const Vec4f viewPort(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT); auto iter = m_winCoords.begin(); for(auto& t : m_vecPositions) { Vec2f coord; Mat4::projectM4f(t, mvp, viewPort, coord); *iter++ = coord; } m_winCoords.reserve(g_teapotIndicesNum); for(int i = 0; i < g_teapotIndicesNum; i += 3) { const int index1 = g_teapotIndices[i]; const int index2 = g_teapotIndices[i + 1]; const int index3 = g_teapotIndices[i + 2]; const Vec2i posPoints[] = { Vec2i(x + m_winCoords[index1][0], y + m_winCoords[index1][1]),// vec[index1][2] * 255.0f), Vec2i(x + m_winCoords[index2][0], y + m_winCoords[index2][1]),// vec[index2][2] * 255.0f), Vec2i(x + m_winCoords[index3][0], y + m_winCoords[index3][1]) // vec[index3][2] * 255.0f) }; //设置是否进行面剔除 #if USE_CULL_FACE_BACK || USE_CULL_FACE_FRONT float ax = posPoints[1][0] - posPoints[0][0]; float ay = posPoints[1][1] - posPoints[0][1]; float bx = posPoints[2][0] - posPoints[1][0]; float by = posPoints[2][1] - posPoints[1][1]; float zNorm = ax * by - ay * bx; #if USE_CULL_FACE_BACK if(zNorm <= 0.0f) { goto Render_Wire_Frame; //continue; } #endif #if USE_CULL_FACE_FRONT if(zNorm > 0.0f) { goto Render_Wire_Frame; //continue; } #endif #endif //设置是否显示模拟填充 #if RENDER_TRIANGLE_HALF_1 || RENDER_TRIANGLE_HALF_2 setcolor(g_color ^ 0xffffff); #if USE_DEPTH_TEST memset(g_depthMask, 0, g_maskSize); #endif //USE_DEPTH_TEST Triangle<Vec2i>::fillTriangle(posPoints[0], posPoints[1], posPoints[2]); #endif //RENDER_TRIANGLE_HALF_1 || RENDER_TRIANGLE_HALF_2 Render_Wire_Frame: setcolor(g_color); line(posPoints[0][0], posPoints[0][1], posPoints[1][0], posPoints[1][1]); line(posPoints[1][0], posPoints[1][1], posPoints[2][0], posPoints[2][1]); line(posPoints[2][0], posPoints[2][1], posPoints[0][0], posPoints[0][1]); } } void pushPoint(Vec3f pnt) { m_vecPositions.push_back(pnt); } void pushPoints(Vec3f* pnt, int n) { for(int i = 0; i != n; ++i) { m_vecPositions.push_back(pnt[i]); } } void pushPoint(float x, float y, float z) { m_vecPositions.push_back(Vec3f(x, y, z)); } void rotate(float rad, float x, float y, float z) { m_matModelView.rotate(rad, x, y, z); } void rotateX(float rad) { m_matModelView.rotateX(rad); } void rotateY(float rad) { m_matModelView.rotateY(rad); } void rotateZ(float rad) { m_matModelView.rotateZ(rad); } void translateZ(float z) { m_matModelView.translateZ(z); } void clear() { m_vecPositions.clear(); } std::vector<Vec3f>& getPositions() { return m_vecPositions; } std::vector<int>& getIndices() { return m_vecIndices; } private: std::vector<Vec3f> m_vecPositions; std::vector<int> m_vecIndices; Mat4 m_matProj, m_matModelView; std::vector<Vec2f> m_winCoords; }; bool mouseFunc(Object& obj) { if(!mousemsg()) return false; do { static int s_lastX, s_lastY; static int s_bIsDown = false; mouse_msg msg = getmouse(); switch (msg.msg) { case mouse_msg_down: s_lastX = msg.x; s_lastY = msg.y; s_bIsDown = true; break; case mouse_msg_up: s_bIsDown = false; break; case mouse_msg_wheel: obj.translateZ(msg.wheel / 12.0f); break; default: break; } if(s_bIsDown && msg.is_move()) { obj.rotateX((msg.y - s_lastY) / 100.0f); obj.rotateY((msg.x - s_lastX) / 100.0f); s_lastX = msg.x; s_lastY = msg.y; } }while(mousemsg()); return true; } void genTeapot(Object& obj, float scale) { auto& pos = obj.getPositions(); auto& indices = obj.getIndices(); pos.clear(); pos.reserve(g_teapotIndicesNum / 3); for(int i = 0; i < g_teapotPositionNum; i += 3) { pos.push_back(Vec3f(g_teapotPositions[i] * scale, g_teapotPositions[i + 1] * scale, g_teapotPositions[i + 2] * scale)); } indices.clear(); indices.assign(g_teapotIndices, g_teapotIndices + g_teapotIndicesNum); } int main() { setinitmode(INIT_RENDERMANUAL); initgraph(SCREEN_WIDTH, SCREEN_HEIGHT); setrendermode(RENDER_MANUAL); Object obj; randomize(); genTeapot(obj, 10.0f); int i = 0; static bool s_useBlur = false; float x = 0.0f, y = 0.0f; float dx = randomf()* 5.0f + 1.0f, dy = randomf()* 5.0f + 1.0f; float radX = randomf()*10.0f + 0.001f, radY = randomf() * 10.0f, radZ = randomf() * 10.0f; setbkmode(TRANSPARENT); setfillcolor(DARKGRAY); for(; is_run(); delay_fps(60)) { if(s_useBlur) imagefilter_blurring(0, 0x79, 0x100); else cleardevice(); mouseFunc(obj); obj.render(0, 0); g_color = HSVtoRGB(i*2, 1.0f, 1.0f); outtextxy(20, 10, "点击空格键启用模糊滤镜, 鼠标滚轮移动模型Z值, enter键截屏"); x += dx; y += dy; if(x < 0.0f || x > 800.0f) { dx = -dx; x += dx; } if(y < 0.0f || y > 600.0f) { dy = -dy; y += dy; } ++i %= 360; if(kbhit()) { switch (getch()) { case ' ': s_useBlur = !s_useBlur; break; case '\r':case '\n': { saveimage(NULL, "screen_shot.bmp"); } break; default: break; } flushkey(); } } closegraph(); return 0; }
fdo#42151 fix RTF import of vertically merged table cells The problem was that \row took care of states (which is right, since \trowd wants to reset row properties to the default state), but it should not respect state pops.
/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the Campcaster project. http://campcaster.campware.org/ To report bugs, send an e-mail to bugs@campware.org Campcaster is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Campcaster is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Campcaster; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author$ Version : $Revision$ Location : $URL$ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #ifdef HAVE_PWD_H #include <pwd.h> #else #error need pwd.h #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #else #error need sys/stat.h #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #else #error need stdlib.h #endif #include <stdexcept> #include <gtkmm/main.h> #include "LiveSupport/Core/LocalizedObject.h" #include "LiveSupport/Core/TimeConversion.h" #include "LiveSupport/Core/XmlRpcInvalidDataException.h" #include "LiveSupport/Authentication/AuthenticationClientFactory.h" #include "LiveSupport/StorageClient/StorageClientFactory.h" #include "LiveSupport/SchedulerClient/SchedulerClientFactory.h" #include "LiveSupport/PlaylistExecutor/AudioPlayerFactory.h" #include "MasterPanelWindow.h" #include "GLiveSupport.h" using namespace boost; using namespace boost::posix_time; using namespace LiveSupport::Core; using namespace LiveSupport::Authentication; using namespace LiveSupport::StorageClient; using namespace LiveSupport::SchedulerClient; using namespace LiveSupport::Widgets; using namespace LiveSupport::GLiveSupport; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /*------------------------------------------------------------------------------ * The name of the config element for this class *----------------------------------------------------------------------------*/ const std::string LiveSupport :: GLiveSupport :: GLiveSupport :: configElementNameStr = "gLiveSupport"; namespace { /*------------------------------------------------------------------------------ * The name of the configuration file for this class *----------------------------------------------------------------------------*/ const std::string configFileDirStr = "/.campcaster/"; /*------------------------------------------------------------------------------ * The name of the configuration file for this class *----------------------------------------------------------------------------*/ const std::string configFileNameStr = "campcaster-studio.xml"; /*------------------------------------------------------------------------------ * The name of the config element for the list of supported languages *----------------------------------------------------------------------------*/ const std::string supportedLanguagesElementName = "supportedLanguages"; /*------------------------------------------------------------------------------ * The name of the config element for a supported language. *----------------------------------------------------------------------------*/ const std::string languageElementName = "language"; /*------------------------------------------------------------------------------ * The name of the attribute for the locale id for a supported language *----------------------------------------------------------------------------*/ const std::string localeAttrName = "locale"; /*------------------------------------------------------------------------------ * The name of the attribute for the name for a supported language *----------------------------------------------------------------------------*/ const std::string nameAttrName = "name"; /*------------------------------------------------------------------------------ * The name of the config element for the scheduler daemon start command *----------------------------------------------------------------------------*/ const std::string schedulerDaemonCommandsElementName = "schedulerDaemonCommands"; /*------------------------------------------------------------------------------ * The name of the config element for the sound output player *----------------------------------------------------------------------------*/ const std::string outputPlayerElementName = "outputPlayer"; /*------------------------------------------------------------------------------ * The name of the config element for the sound cue player *----------------------------------------------------------------------------*/ const std::string cuePlayerElementName = "cuePlayer"; /*------------------------------------------------------------------------------ * The name of the config element for the station logo image *----------------------------------------------------------------------------*/ const std::string stationLogoConfigElementName = "stationLogo"; /*------------------------------------------------------------------------------ * The name of the config element for the taskbar icon images *----------------------------------------------------------------------------*/ const std::string taskbarIconsConfigElementName = "taskbarIcons"; /*------------------------------------------------------------------------------ * The name of the config element for the test audio file location *----------------------------------------------------------------------------*/ const std::string testAudioUrlConfigElementName = "testAudioUrl"; /*------------------------------------------------------------------------------ * The name of the user preference for storing window positions *----------------------------------------------------------------------------*/ const std::string windowPositionsKey = "windowPositions"; /*------------------------------------------------------------------------------ * The name of the user preference for storing the token of the edited p.l. *----------------------------------------------------------------------------*/ const std::string editedPlaylistTokenKey = "editedPlaylistToken"; /*------------------------------------------------------------------------------ * Static constant for the key of the scheduler not available error message *----------------------------------------------------------------------------*/ const std::string schedulerNotReachableKey = "schedulerNotReachableMsg"; /*------------------------------------------------------------------------------ * Static constant for the key of the storage not available error message *----------------------------------------------------------------------------*/ const std::string storageNotReachableKey = "storageNotReachableMsg"; /*------------------------------------------------------------------------------ * Static constant for the key of the authentication not available error msg *----------------------------------------------------------------------------*/ const std::string authenticationNotReachableKey = "authenticationNotReachableMsg"; /*------------------------------------------------------------------------------ * Static constant for the key of the locale not available error message *----------------------------------------------------------------------------*/ const std::string localeNotAvailableKey = "localeNotAvailableMsg"; } /* =============================================== local function prototypes */ /* ============================================================= module code */ /*------------------------------------------------------------------------------ * Configure the gLiveSupport object *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: configure(const xmlpp::Element & element) throw (std::invalid_argument, std::logic_error) { if (element.get_name() != configElementNameStr) { std::string eMsg = "Bad configuration element "; eMsg += element.get_name(); throw std::invalid_argument(eMsg); } xmlpp::Node::NodeList nodes; // read the list of supported languages nodes = element.get_children(supportedLanguagesElementName); if (nodes.size() < 1) { throw std::invalid_argument("no supportedLanguages element"); } configSupportedLanguages( *dynamic_cast<const xmlpp::Element*>(nodes.front())); // configure the resource bundle nodes = element.get_children(LocalizedObject::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no resourceBundle element"); } LocalizedConfigurable::configure( *dynamic_cast<const xmlpp::Element*>(nodes.front()) ); // configure the AuthenticationClientFactory nodes = element.get_children( AuthenticationClientFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no authenticationClientFactory element"); } Ptr<AuthenticationClientFactory>::Ref acf = AuthenticationClientFactory::getInstance(); acf->configure(*dynamic_cast<const xmlpp::Element*>(nodes.front())); authentication = acf->getAuthenticationClient(); // configure the StorageClientFactory nodes = element.get_children(StorageClientFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no storageClientFactory element"); } Ptr<StorageClientFactory>::Ref stcf = StorageClientFactory::getInstance(); stcf->configure(*dynamic_cast<const xmlpp::Element*>(nodes.front())); storage = stcf->getStorageClient(); // configure the WidgetFactory nodes = element.get_children(WidgetFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no widgetFactory element"); } widgetFactory = WidgetFactory::getInstance(); widgetFactory->configure( *dynamic_cast<const xmlpp::Element*>(nodes.front()) ); // configure the SchedulerClientFactory nodes = element.get_children( SchedulerClientFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no schedulerClientFactory element"); } Ptr<SchedulerClientFactory>::Ref schcf = SchedulerClientFactory::getInstance(); schcf->configure(*dynamic_cast<const xmlpp::Element*>(nodes.front())); scheduler = schcf->getSchedulerClient(); // configure the scheduler daemon start and stop command strings nodes = element.get_children(schedulerDaemonCommandsElementName); if (nodes.size() < 1) { throw std::invalid_argument("no scheduler daemon commands element"); } const xmlpp::Element* schedulerDaemonCommandsElement = dynamic_cast<const xmlpp::Element*>(nodes.front()); xmlpp::Attribute * schedulerDaemonStartAttribute = schedulerDaemonCommandsElement->get_attribute( "start"); xmlpp::Attribute * schedulerDaemonStopAttribute = schedulerDaemonCommandsElement->get_attribute( "stop"); if (!schedulerDaemonStartAttribute) { throw std::invalid_argument("missing scheduler start command"); } if (!schedulerDaemonStopAttribute) { throw std::invalid_argument("missing scheduler stop command"); } schedulerDaemonStartCommand.reset(new Glib::ustring( schedulerDaemonStartAttribute->get_value())); schedulerDaemonStopCommand.reset(new Glib::ustring( schedulerDaemonStopAttribute->get_value())); Ptr<AudioPlayerFactory>::Ref apf; xmlpp::Element * elem; // configure the outputPlayer AudioPlayerFactory nodes = element.get_children(outputPlayerElementName); if (nodes.size() < 1) { throw std::invalid_argument("no outputPlayer element"); } elem = (xmlpp::Element*) *(nodes.begin()); nodes = elem->get_children(AudioPlayerFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no audioPlayer element"); } apf = AudioPlayerFactory::getInstance(); apf->configure(*dynamic_cast<const xmlpp::Element*>(nodes.front())); outputPlayer = apf->getAudioPlayer(); outputPlayer->initialize(); outputPlayer->attachListener(this); // configure the cuePlayer AudioPlayerFactory nodes = element.get_children(cuePlayerElementName); if (nodes.size() < 1) { throw std::invalid_argument("no cuePlayer element"); } elem = (xmlpp::Element*) *(nodes.begin()); nodes = elem->get_children(AudioPlayerFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no audioPlayer element"); } apf = AudioPlayerFactory::getInstance(); apf->configure(*dynamic_cast<const xmlpp::Element*>(nodes.front())); cuePlayer = apf->getAudioPlayer(); cuePlayer->initialize(); // configure the station logo image nodes = element.get_children(stationLogoConfigElementName); if (nodes.size() < 1) { throw std::invalid_argument("no station logo element"); } const xmlpp::Element* stationLogoElement = dynamic_cast<const xmlpp::Element*>(nodes.front()); const Glib::ustring stationLogoFileName = stationLogoElement->get_attribute("path") ->get_value(); try { stationLogoPixbuf = Gdk::Pixbuf::create_from_file(stationLogoFileName); } catch (Gdk::PixbufError &e) { throw std::invalid_argument("could not open station logo image file"); } // configure the taskbar icon images nodes = element.get_children(taskbarIconsConfigElementName); if (nodes.size() < 1) { throw std::invalid_argument("no taskbar icons element"); } taskbarIcons.reset(new TaskbarIcons()); taskbarIcons->configure( *dynamic_cast<const xmlpp::Element*>(nodes.front()) ); // configure the MetadataTypeContainer nodes = element.get_children(MetadataTypeContainer::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no metadataTypeContainer element"); } Ptr<ResourceBundle>::Ref metadataBundle = getBundle("metadataTypes"); metadataTypeContainer.reset(new MetadataTypeContainer(metadataBundle)); metadataTypeContainer->configure( *dynamic_cast<const xmlpp::Element*>(nodes.front()) ); // configure the KeyboardShortcutList nodes = element.get_children( KeyboardShortcutList::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no keyboardShortcutList element"); } keyboardShortcutList.reset(new KeyboardShortcutList); keyboardShortcutList->configure( *dynamic_cast<const xmlpp::Element*>(nodes.front()) ); // save the configuration so we can modify it later // TODO: move configuration code to the OptionsContainer class? Ptr<Glib::ustring>::Ref configFileName(new Glib::ustring); configFileName->append(Glib::get_home_dir()); configFileName->append(configFileDirStr); mkdir(configFileName->c_str(), 0700); // create dir if does not exist configFileName->append(configFileNameStr); optionsContainer.reset(new OptionsContainer(element, configFileName)); // read the test audio file location nodes = element.get_children(testAudioUrlConfigElementName); if (nodes.size() < 1) { throw std::invalid_argument("no test audio url element"); } const xmlpp::Element* testAudioUrlElement = dynamic_cast<const xmlpp::Element*>(nodes.front()); testAudioUrl.reset(new Glib::ustring( testAudioUrlElement->get_attribute("path") ->get_value() )); } /*------------------------------------------------------------------------------ * Configure the list of supported languages *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: configSupportedLanguages(const xmlpp::Element & element) throw (std::invalid_argument) { xmlpp::Node::NodeList nodes; xmlpp::Node::NodeList::iterator begin; xmlpp::Node::NodeList::iterator end; supportedLanguages.reset(new LanguageMap()); // read the list of supported languages nodes = element.get_children(languageElementName); begin = nodes.begin(); end = nodes.end(); while (begin != end) { xmlpp::Element * elem = (xmlpp::Element *) *begin; xmlpp::Attribute * localeAttr = elem->get_attribute(localeAttrName); xmlpp::Attribute * nameAttr = elem->get_attribute(nameAttrName); std::string locale = localeAttr->get_value().raw(); Glib::ustring name = nameAttr->get_value(); supportedLanguages->insert(std::make_pair(name, locale)); begin++; } } /*------------------------------------------------------------------------------ * Check all configured resources *----------------------------------------------------------------------------*/ bool LiveSupport :: GLiveSupport :: GLiveSupport :: checkConfiguration(void) throw () { // === FATAL ERRORS === // first, check if resources are available for all configured languages LanguageMap::iterator it = supportedLanguages->begin(); try { LanguageMap::iterator end = supportedLanguages->end(); while (it != end) { changeLocale((*it).second); ++it; } changeLocale(""); } catch (std::invalid_argument &e) { Ptr<Glib::ustring>::Ref language(new Glib::ustring((*it).first)); Ptr<UnicodeString>::Ref uLanguage = ustringToUnicodeString(language); Ptr<Glib::ustring>::Ref msg = formatMessage(localeNotAvailableKey, (*it).first); displayMessageWindow(msg); changeLocale(""); return false; } // check if the authentication server is available try { authentication->getVersion(); } catch (XmlRpcException &e) { displayAuthenticationServerMissingMessage(); return false; } // === NON-FATAL ERRORS === // check if the storage server is available try { storage->getVersion(); storageAvailable = true; } catch (XmlRpcException &e) { storageAvailable = false; displayMessageWindow(getResourceUstring(storageNotReachableKey)); } // no need to check the widget factory // check the scheduler client checkSchedulerClient(); if (!isSchedulerAvailable()) { displayMessageWindow(getResourceUstring(schedulerNotReachableKey)); } // TODO: check the audio player? return true; } /*------------------------------------------------------------------------------ * Display a message window. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: displayMessageWindow(Ptr<Glib::ustring>::Ref message) throw () { std::cerr << "gLiveSupport: " << *message << std::endl; Ptr<DialogWindow>::Ref window(widgetFactory->createDialogWindow( message, getBundle())); window->run(); } /*------------------------------------------------------------------------------ * Show the main window. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: show(void) throw () { masterPanel.reset(new MasterPanelWindow(shared_from_this(), getBundle())); masterPanel->set_icon_list(taskbarIcons->getIconList()); masterPanel->set_default_icon_list(taskbarIcons->getIconList()); // Shows the window and returns when it is closed. Gtk::Main::run(*masterPanel); masterPanel.reset(); } /*------------------------------------------------------------------------------ * Change the language of the application *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: changeLanguage(Ptr<const std::string>::Ref locale) throw (std::invalid_argument) { changeLocale(*locale); metadataTypeContainer->setBundle(getBundle("metadataTypes")); if (masterPanel.get()) { masterPanel->changeLanguage(getBundle()); } } /*------------------------------------------------------------------------------ * Authenticate the user *----------------------------------------------------------------------------*/ bool LiveSupport :: GLiveSupport :: GLiveSupport :: login(const std::string & login, const std::string & password) throw () { try { sessionId = authentication->login(login, password); } catch (XmlRpcException &e) { return false; } Ptr<const Glib::ustring>::Ref editedPlaylistToken; Ptr<const std::string>::Ref editedPlaylistTokenString; try { editedPlaylistToken = authentication->loadPreferencesItem( sessionId, editedPlaylistTokenKey); editedPlaylistTokenString.reset(new const std::string( *editedPlaylistToken )); } catch (std::invalid_argument &e) { // no stuck playlist token found; that's OK } catch (XmlRpcException &e) { std::cerr << "Problem loading " << editedPlaylistTokenKey << " user preference item:" << std::endl << e.what(); } if (editedPlaylistTokenString) { try { storage->revertPlaylist(editedPlaylistTokenString); } catch (XmlRpcException &e) { // sometimes this throws; we don't care } try { authentication->deletePreferencesItem(sessionId, editedPlaylistTokenKey); } catch (XmlRpcException &e) { std::cerr << "Problem deleting " << editedPlaylistTokenKey << " user preference item at login:" << std::endl << e.what(); } } loadWindowPositions(); if (masterPanel) { masterPanel->createScratchpadWindow(); } return true; } /*------------------------------------------------------------------------------ * Log the user out. *----------------------------------------------------------------------------*/ bool LiveSupport :: GLiveSupport :: GLiveSupport :: logout(void) throw () { if (!sessionId) { return false; } if (masterPanel && !masterPanel->cancelEditedPlaylist()) { return false; // do nothing if the user presses the cancel button } stopCueAudio(); showAnonymousUI(); storeWindowPositions(); windowPositions.clear(); try { authentication->logout(sessionId); } catch (XmlRpcException &e) { std::cerr << "error in GLiveSupport::logout: " << e.what() << std::endl; } sessionId.reset(); return true; } /*------------------------------------------------------------------------------ * Store the contents of a window as a user preference *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: storeWindowContents(ContentsStorable * window) throw () { Ptr<const Glib::ustring>::Ref userPreferencesKey = window->getUserPreferencesKey(); Ptr<const Glib::ustring>::Ref windowContents = window->getContents(); try { authentication->savePreferencesItem(sessionId, *userPreferencesKey, windowContents); } catch (XmlRpcException &e) { // TODO: signal error std::cerr << "error saving user preferences: " << e.what() << std::endl; } } /*------------------------------------------------------------------------------ * Load the contents of a window from a user preference *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: loadWindowContents(ContentsStorable * window) throw () { Ptr<const Glib::ustring>::Ref userPreferencesKey = window->getUserPreferencesKey(); Ptr<const Glib::ustring>::Ref windowContents; try { windowContents = authentication->loadPreferencesItem( sessionId, *userPreferencesKey); } catch (XmlRpcException &e) { // TODO: signal error std::cerr << "error loading user preferences: " << e.what() << std::endl; return; } catch (std::invalid_argument &e) { // no scratchpad stored for this user yet; no problem return; } window->setContents(windowContents); } /*------------------------------------------------------------------------------ * Show the anonymous UI *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: showAnonymousUI(void) throw () { if (masterPanel.get()) { masterPanel->showAnonymousUI(); } } /*------------------------------------------------------------------------------ * Show the UI when someone is logged in *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: showLoggedInUI(void) throw () { if (masterPanel.get()) { masterPanel->showLoggedInUI(); } } /*------------------------------------------------------------------------------ * Open an audio clip, and put it into the internal cache of the GLiveSupport * object. *----------------------------------------------------------------------------*/ Ptr<AudioClip>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: getAudioClip(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<AudioClip>::Ref clip; clip = (*openedAudioClips)[id->getId()]; if (!clip.get()) { clip = storage->getAudioClip(sessionId, id); (*openedAudioClips)[id->getId()] = clip; } return clip; } /*------------------------------------------------------------------------------ * Acquire an audio clip, and put it into the internal cache of * the GLiveSupport object. *----------------------------------------------------------------------------*/ Ptr<AudioClip>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: acquireAudioClip(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<AudioClip>::Ref clip; clip = (*openedAudioClips)[id->getId()]; if (!clip.get() || !clip->getToken().get()) { clip = storage->acquireAudioClip(sessionId, id); (*openedAudioClips)[id->getId()] = clip; } return clip; } /*------------------------------------------------------------------------------ * Open an playlist, and put it into the internal cache of the GLiveSupport * object. *----------------------------------------------------------------------------*/ Ptr<Playlist>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: getPlaylist(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<Playlist>::Ref playlist; playlist = (*openedPlaylists)[id->getId()]; if (!playlist.get()) { playlist = storage->getPlaylist(sessionId, id); (*openedPlaylists)[id->getId()] = playlist; } return playlist; } /*------------------------------------------------------------------------------ * Acquire an playlist, and put it into the internal cache of * the GLiveSupport object. *----------------------------------------------------------------------------*/ Ptr<Playlist>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: acquirePlaylist(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<Playlist>::Ref playlist; playlist = (*openedPlaylists)[id->getId()]; if (!playlist.get() || !playlist->getUri().get()) { playlist = storage->acquirePlaylist(sessionId, id); (*openedPlaylists)[id->getId()] = playlist; } return playlist; } /*------------------------------------------------------------------------------ * Open a Playable object. *----------------------------------------------------------------------------*/ Ptr<Playable>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: getPlayable(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<Playable>::Ref playable; if (existsPlaylist(id)) { playable = getPlaylist(id); } else if (existsAudioClip(id)) { playable = getAudioClip(id); } else { throw XmlRpcInvalidArgumentException( "invalid ID in GLiveSupport::acquirePlayable"); } return playable; } /*------------------------------------------------------------------------------ * Acquire a Playable object. *----------------------------------------------------------------------------*/ Ptr<Playable>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: acquirePlayable(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<Playable>::Ref playable; if (existsPlaylist(id)) { playable = acquirePlaylist(id); } else if (existsAudioClip(id)) { playable = acquireAudioClip(id); } else { throw XmlRpcInvalidArgumentException( "invalid ID in GLiveSupport::acquirePlayable"); } return playable; } /*------------------------------------------------------------------------------ * Remove a playlist from the playlist cache. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: uncachePlaylist(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<Playlist>::Ref playlist; PlaylistMap::iterator it; PlaylistMap::iterator end = openedPlaylists->end(); if ((it = openedPlaylists->find(id->getId())) != end) { playlist = (*openedPlaylists)[id->getId()]; if (playlist->getUri().get()) { storage->releasePlaylist(playlist); } openedPlaylists->erase(it); } } /*----------------------------------------------------------------------------- * Release all opened audio clips. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: releaseOpenedAudioClips(void) throw (XmlRpcException) { AudioClipMap::iterator it = openedAudioClips->begin(); AudioClipMap::iterator end = openedAudioClips->end(); while (it != end) { Ptr<AudioClip>::Ref clip = (*it).second; if (clip->getToken().get()) { storage->releaseAudioClip(clip); } ++it; } openedAudioClips->clear(); } /*------------------------------------------------------------------------------ * Release all opened playlists. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: releaseOpenedPlaylists(void) throw (XmlRpcException) { PlaylistMap::iterator it = openedPlaylists->begin(); PlaylistMap::iterator end = openedPlaylists->end(); while (it != end) { Ptr<Playlist>::Ref playlist = (*it).second; if (playlist->getUri().get()) { storage->releasePlaylist(playlist); } ++it; } openedPlaylists->clear(); } /*------------------------------------------------------------------------------ * Upload an audio clip to the local storage. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: uploadAudioClip(Ptr<AudioClip>::Ref audioClip) throw (XmlRpcException) { storage->storeAudioClip(sessionId, audioClip); // this will also add it to the local cache addToScratchpad(audioClip); } /*------------------------------------------------------------------------------ * Upload a playlist archive to the local storage. *----------------------------------------------------------------------------*/ Ptr<Playlist>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: uploadPlaylistArchive(Ptr<const Glib::ustring>::Ref path) throw (XmlRpcException) { Ptr<UniqueId>::Ref id = storage->importPlaylist(sessionId, path); Ptr<Playlist>::Ref playlist = storage->getPlaylist(sessionId, id); // this will also add it to the local cache addToScratchpad(playlist); return playlist; } /*------------------------------------------------------------------------------ * Add a file to the Scratchpad, and update it. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: addToScratchpad(Ptr<Playable>::Ref playable) throw (XmlRpcException) { if (playable->getType() == Playable::AudioClipType) { acquireAudioClip(playable->getId()); } else if (playable->getType() == Playable::PlaylistType) { acquirePlaylist(playable->getId()); } // this will also add it to the local cache masterPanel->updateScratchpadWindow(playable); } /*------------------------------------------------------------------------------ * Add a file to the Live Mode, and update it. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: addToLiveMode(Ptr<Playable>::Ref playable) throw () { masterPanel->updateLiveModeWindow(playable); } /*------------------------------------------------------------------------------ * Display the playable item on the master panel as "now playing". *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: setNowPlaying(Ptr<Playable>::Ref playable) throw () { masterPanel->setNowPlaying(playable); } /*------------------------------------------------------------------------------ * Open a playlist for editing. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: openPlaylistForEditing(Ptr<const UniqueId>::Ref playlistId) throw (XmlRpcException) { if (masterPanel->cancelEditedPlaylist() == false) { return; // the user canceled the operation } if (!playlistId.get()) { playlistId = storage->createPlaylist(sessionId); } else { uncachePlaylist(playlistId); } editedPlaylist = storage->editPlaylist(sessionId, playlistId); try { Ptr<const Glib::ustring>::Ref editToken(new const Glib::ustring( *editedPlaylist->getEditToken() )); authentication->savePreferencesItem(sessionId, editedPlaylistTokenKey, editToken); } catch (XmlRpcException &e) { std::cerr << "Problem saving " << editedPlaylistTokenKey << " user preference item:" << std::endl << e.what(); } editedPlaylist->createSavedCopy(); masterPanel->updateSimplePlaylistMgmtWindow(); } /*------------------------------------------------------------------------------ * Cancel the edited playlist: undo changes and release the lock. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: cancelEditedPlaylist(void) throw (XmlRpcException) { if (editedPlaylist) { if (editedPlaylist->isLocked()) { editedPlaylist->revertToSavedCopy(); storage->savePlaylist(sessionId, editedPlaylist); try { authentication->deletePreferencesItem(sessionId, editedPlaylistTokenKey); } catch (XmlRpcException &e) { std::cerr << "Problem deleting " << editedPlaylistTokenKey << " user preference item at cancel:" << std::endl << e.what(); } } editedPlaylist.reset(); } } /*------------------------------------------------------------------------------ * Add a playlist to the currently edited playlist *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: addToPlaylist(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { if (!editedPlaylist.get()) { openPlaylistForEditing(); } // append the appropriate playable object to the end of the playlist if (existsPlaylist(id)) { Ptr<Playlist>::Ref playlist = getPlaylist(id); editedPlaylist->addPlaylist(playlist, editedPlaylist->getPlaylength()); } else if (existsAudioClip(id)) { Ptr<AudioClip>::Ref clip = getAudioClip(id); editedPlaylist->addAudioClip(clip, editedPlaylist->getPlaylength()); } masterPanel->updateSimplePlaylistMgmtWindow(); emitSignalEditedPlaylistModified(); } /*------------------------------------------------------------------------------ * Save the currently edited playlist in storage *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: savePlaylist(void) throw (XmlRpcException) { if (editedPlaylist) { if (editedPlaylist->isLocked()) { editedPlaylist->deleteSavedCopy(); storage->savePlaylist(sessionId, editedPlaylist); try { authentication->deletePreferencesItem(sessionId, editedPlaylistTokenKey); } catch (XmlRpcException &e) { std::cerr << "Problem deleting " << editedPlaylistTokenKey << " user preference item at save:" << std::endl << e.what(); } // update with new version // this will also add it to the local cache uncachePlaylist(editedPlaylist->getId()); addToScratchpad(editedPlaylist); refreshPlaylistInLiveMode(editedPlaylist); } editedPlaylist.reset(); } } /*------------------------------------------------------------------------------ * Schedule a playlist, then show the scheduler at that timepoint *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: schedulePlaylist(Ptr<Playlist>::Ref playlist, Ptr<posix_time::ptime>::Ref playtime) throw (XmlRpcException) { scheduler->uploadPlaylist(sessionId, playlist->getId(), playtime); masterPanel->updateSchedulerWindow(playtime); } /*------------------------------------------------------------------------------ * Remove a scheduled entry. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: removeFromSchedule(Ptr<const UniqueId>::Ref scheduleEntryId) throw (XmlRpcException) { // for some weird reason, the schedule functions won't accept // Ptr<const UniqueId>::Ref, just a non-const version Ptr<UniqueId>::Ref seid(new UniqueId(scheduleEntryId->getId())); scheduler->removeFromSchedule(sessionId, seid); } /*------------------------------------------------------------------------------ * Play a Playable object using the output audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: playOutputAudio(Ptr<Playable>::Ref playable) throw (std::logic_error, std::runtime_error) { try { switch (playable->getType()) { case Playable::AudioClipType: outputItemPlayingNow = acquireAudioClip(playable->getId()); outputPlayer->open(*outputItemPlayingNow->getUri()); outputPlayer->start(); break; case Playable::PlaylistType: outputItemPlayingNow = acquirePlaylist(playable->getId()); outputPlayer->open(*outputItemPlayingNow->getUri()); outputPlayer->start(); break; default: // this never happens break; } } catch (XmlRpcException &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } catch (std::invalid_argument &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } catch (std::runtime_error &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } outputPlayerIsPaused = false; } /*------------------------------------------------------------------------------ * Pause the output audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: pauseOutputAudio(void) throw (std::logic_error) { if (!outputPlayerIsPaused && outputPlayer->isPlaying()) { outputPlayer->pause(); outputPlayerIsPaused = true; } else if (outputPlayerIsPaused) { outputPlayer->start(); outputPlayerIsPaused = false; } } /*------------------------------------------------------------------------------ * Stop the output audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: stopOutputAudio(void) throw (std::logic_error) { if (outputItemPlayingNow) { outputPlayerIsPaused = false; outputItemPlayingNow.reset(); Ptr<Playable>::Ref nullPointer; setNowPlaying(nullPointer); outputPlayer->close(); } } /*------------------------------------------------------------------------------ * Event handler for the "output audio player has stopped" event. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: onStop(void) throw () { outputItemPlayingNow.reset(); try { outputPlayer->close(); Ptr<Playable>::Ref playable = masterPanel->getNextItemToPlay(); setNowPlaying(playable); if (playable) { playOutputAudio(playable); } } catch (std::logic_error) { std::cerr << "logic_error caught in GLiveSupport::onStop()\n"; std::exit(1); } } /*------------------------------------------------------------------------------ * Play a Playable object using the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: playCueAudio(Ptr<Playable>::Ref playable) throw (std::logic_error, std::runtime_error) { if (cueItemPlayingNow) { stopCueAudio(); // stop the audio player and } // release old resources try { switch (playable->getType()) { case Playable::AudioClipType: cueItemPlayingNow = acquireAudioClip(playable->getId()); cuePlayer->open(*cueItemPlayingNow->getUri()); cuePlayer->start(); break; case Playable::PlaylistType: cueItemPlayingNow = acquirePlaylist(playable->getId()); cuePlayer->open(*cueItemPlayingNow->getUri()); cuePlayer->start(); break; default: // this never happens break; } } catch (XmlRpcException &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } catch (std::invalid_argument &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } catch (std::runtime_error &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } cuePlayerIsPaused = false; } /*------------------------------------------------------------------------------ * Pause the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: pauseCueAudio(void) throw (std::logic_error) { if (!cuePlayerIsPaused && cuePlayer->isPlaying()) { cuePlayer->pause(); cuePlayerIsPaused = true; } else if (cuePlayerIsPaused) { cuePlayer->start(); cuePlayerIsPaused = false; } } /*------------------------------------------------------------------------------ * Stop the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: stopCueAudio(void) throw (std::logic_error) { if (cueItemPlayingNow) { cuePlayer->close(); cuePlayerIsPaused = false; cueItemPlayingNow.reset(); masterPanel->showCuePlayerStopped(); } } /*------------------------------------------------------------------------------ * Attach a listener for the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: attachCueAudioListener(AudioPlayerEventListener * listener) throw () { cuePlayer->attachListener(listener); } /*------------------------------------------------------------------------------ * Detach the listener for the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: detachCueAudioListener(AudioPlayerEventListener * listener) throw (std::invalid_argument) { cuePlayer->detachListener(listener); } /*------------------------------------------------------------------------------ * Return an image containing the radio station logo. *----------------------------------------------------------------------------*/ Gtk::Image * LiveSupport :: GLiveSupport :: GLiveSupport :: getStationLogoImage(void) throw() { return new Gtk::Image(stationLogoPixbuf); } /*------------------------------------------------------------------------------ * Get the localized name of the keyboard shortcut action. *----------------------------------------------------------------------------*/ Ptr<const Glib::ustring>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: getLocalizedKeyboardActionName( Ptr<const Glib::ustring>::Ref actionName) throw (std::invalid_argument) { return getResourceUstring("keyboardShortcuts", actionName->c_str()); } /*------------------------------------------------------------------------------ * Get the localized name of the window. *----------------------------------------------------------------------------*/ Ptr<const Glib::ustring>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: getLocalizedWindowName( Ptr<const Glib::ustring>::Ref windowName) throw (std::invalid_argument) { return getResourceUstring(windowName->c_str(), "windowTitle"); } /*------------------------------------------------------------------------------ * Save the position and size of the window. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: putWindowPosition(Ptr<const Gtk::Window>::Ref window) throw () { WindowPositionType pos; window->get_position(pos.x, pos.y); window->get_size(pos.width, pos.height); windowPositions[window->get_name()] = pos; } /*------------------------------------------------------------------------------ * Apply saved position and size data to the window. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: getWindowPosition(Ptr<Gtk::Window>::Ref window) throw () { WindowPositionsListType::const_iterator it = windowPositions.find( window->get_name()); if (it != windowPositions.end()) { WindowPositionType pos = it->second; window->move(pos.x, pos.y); window->resize(pos.width, pos.height); } } /*------------------------------------------------------------------------------ * Store the saved window positions. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: storeWindowPositions(void) throw () { // just store this as a space-delimited list of window names and numbers std::ostringstream prefsString; WindowPositionsListType::iterator it; WindowPositionsListType::iterator end; WindowPositionType pos; it = windowPositions.begin(); end = windowPositions.end(); while (it != end) { prefsString << it->first << " "; pos = it->second; prefsString << pos.x << " " << pos.y << " " << pos.width << " " << pos.height << " "; ++it; } Ptr<Glib::ustring>::Ref prefsUstring(new Glib::ustring(prefsString.str())); try { authentication->savePreferencesItem(sessionId, windowPositionsKey, prefsUstring); } catch (XmlRpcException &e) { // TODO: signal error std::cerr << "error saving user preferences: " << e.what() << std::endl; } } /*------------------------------------------------------------------------------ * Load the window positions. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: loadWindowPositions(void) throw () { Ptr<Glib::ustring>::Ref prefsUstring; try { prefsUstring = authentication->loadPreferencesItem(sessionId, windowPositionsKey); } catch (XmlRpcException &e) { // TODO: signal error std::cerr << "error loading user preferences: " << e.what() << std::endl; return; } catch (std::invalid_argument &e) { // no window positions were stored for this user yet; no problem return; } // load the prefs, which is a space-delimited list std::istringstream prefsString(prefsUstring->raw()); while (!prefsString.eof()) { Glib::ustring windowName; prefsString >> windowName; if (prefsString.fail()) { break; } WindowPositionType pos; prefsString >> pos.x; if (prefsString.fail()) { continue; } prefsString >> pos.y; if (prefsString.fail()) { continue; } prefsString >> pos.width; if (prefsString.fail()) { continue; } prefsString >> pos.height; if (prefsString.fail()) { continue; } windowPositions[windowName] = pos; } } /*------------------------------------------------------------------------------ * Set the device for the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: setCueAudioDevice(Ptr<const Glib::ustring>::Ref deviceName) throw () { cuePlayer->setAudioDevice(*deviceName); } /*------------------------------------------------------------------------------ * Play a test sound on the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: playTestSoundOnCue(void) throw () { if (cueItemPlayingNow) { stopCueAudio(); // stop the audio player and } // release old resources try { cuePlayer->open(*testAudioUrl); cuePlayer->start(); Ptr<time_duration>::Ref sleepT(new time_duration(microseconds(10))); while (cuePlayer->isPlaying()) { TimeConversion::sleep(sleepT); } } catch (std::runtime_error &e) { // "invalid device" error from open(); do nothing } cuePlayer->close(); } /*------------------------------------------------------------------------------ * Check if the scheduler is available. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: checkSchedulerClient(void) throw () { try { scheduler->getVersion(); schedulerAvailable = true; if (masterPanel) { masterPanel->setSchedulerAvailable(true); } } catch (XmlRpcException &e) { schedulerAvailable = false; if (masterPanel) { masterPanel->setSchedulerAvailable(false); } } } /*------------------------------------------------------------------------------ * Start the scheduler daemon. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: startSchedulerClient(void) throw () { system(schedulerDaemonStartCommand->c_str()); } /*------------------------------------------------------------------------------ * Stop the scheduler daemon. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: stopSchedulerClient(void) throw () { system(schedulerDaemonStopCommand->c_str()); } /*------------------------------------------------------------------------------ * Upload a Playable object to the network hub. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: uploadToHub(Ptr<Playable>::Ref playable) throw () { masterPanel->uploadToHub(playable); } /*------------------------------------------------------------------------------ * Display a message that the authentication server is not available. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: displayAuthenticationServerMissingMessage(void) throw () { Ptr<Glib::ustring>::Ref message; try { message = getResourceUstring("authenticationNotReachableMsg"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; std::exit(1); } // "authentication not available -- would you like to edit the options?" Ptr<DialogWindow>::Ref question(widgetFactory->createDialogWindow( message, getBundle(), DialogWindow::noButton | DialogWindow::yesButton )); DialogWindow::ButtonType answer = question->run(); if (answer == DialogWindow::yesButton) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("optionsWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } Ptr<OptionsWindow>::Ref optionsWindow(new OptionsWindow( shared_from_this(), bundle, 0)); optionsWindow->run(); if (optionsContainer->isTouched()) { optionsContainer->writeToFile(); } } } /*------------------------------------------------------------------------------ * Refresh the playlist in the Live Mode window. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: refreshPlaylistInLiveMode(Ptr<Playlist>::Ref playlist) throw () { masterPanel->refreshPlaylistInLiveMode(playlist); } temporary pseudo-fix for #1898 /*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the Campcaster project. http://campcaster.campware.org/ To report bugs, send an e-mail to bugs@campware.org Campcaster is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Campcaster is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Campcaster; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author$ Version : $Revision$ Location : $URL$ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #ifdef HAVE_PWD_H #include <pwd.h> #else #error need pwd.h #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #else #error need sys/stat.h #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #else #error need stdlib.h #endif #include <stdexcept> #include <gtkmm/main.h> #include "LiveSupport/Core/LocalizedObject.h" #include "LiveSupport/Core/TimeConversion.h" #include "LiveSupport/Core/XmlRpcInvalidDataException.h" #include "LiveSupport/Authentication/AuthenticationClientFactory.h" #include "LiveSupport/StorageClient/StorageClientFactory.h" #include "LiveSupport/SchedulerClient/SchedulerClientFactory.h" #include "LiveSupport/PlaylistExecutor/AudioPlayerFactory.h" #include "MasterPanelWindow.h" #include "GLiveSupport.h" using namespace boost; using namespace boost::posix_time; using namespace LiveSupport::Core; using namespace LiveSupport::Authentication; using namespace LiveSupport::StorageClient; using namespace LiveSupport::SchedulerClient; using namespace LiveSupport::Widgets; using namespace LiveSupport::GLiveSupport; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /*------------------------------------------------------------------------------ * The name of the config element for this class *----------------------------------------------------------------------------*/ const std::string LiveSupport :: GLiveSupport :: GLiveSupport :: configElementNameStr = "gLiveSupport"; namespace { /*------------------------------------------------------------------------------ * The name of the configuration file for this class *----------------------------------------------------------------------------*/ const std::string configFileDirStr = "/.campcaster/"; /*------------------------------------------------------------------------------ * The name of the configuration file for this class *----------------------------------------------------------------------------*/ const std::string configFileNameStr = "campcaster-studio.xml"; /*------------------------------------------------------------------------------ * The name of the config element for the list of supported languages *----------------------------------------------------------------------------*/ const std::string supportedLanguagesElementName = "supportedLanguages"; /*------------------------------------------------------------------------------ * The name of the config element for a supported language. *----------------------------------------------------------------------------*/ const std::string languageElementName = "language"; /*------------------------------------------------------------------------------ * The name of the attribute for the locale id for a supported language *----------------------------------------------------------------------------*/ const std::string localeAttrName = "locale"; /*------------------------------------------------------------------------------ * The name of the attribute for the name for a supported language *----------------------------------------------------------------------------*/ const std::string nameAttrName = "name"; /*------------------------------------------------------------------------------ * The name of the config element for the scheduler daemon start command *----------------------------------------------------------------------------*/ const std::string schedulerDaemonCommandsElementName = "schedulerDaemonCommands"; /*------------------------------------------------------------------------------ * The name of the config element for the sound output player *----------------------------------------------------------------------------*/ const std::string outputPlayerElementName = "outputPlayer"; /*------------------------------------------------------------------------------ * The name of the config element for the sound cue player *----------------------------------------------------------------------------*/ const std::string cuePlayerElementName = "cuePlayer"; /*------------------------------------------------------------------------------ * The name of the config element for the station logo image *----------------------------------------------------------------------------*/ const std::string stationLogoConfigElementName = "stationLogo"; /*------------------------------------------------------------------------------ * The name of the config element for the taskbar icon images *----------------------------------------------------------------------------*/ const std::string taskbarIconsConfigElementName = "taskbarIcons"; /*------------------------------------------------------------------------------ * The name of the config element for the test audio file location *----------------------------------------------------------------------------*/ const std::string testAudioUrlConfigElementName = "testAudioUrl"; /*------------------------------------------------------------------------------ * The name of the user preference for storing window positions *----------------------------------------------------------------------------*/ const std::string windowPositionsKey = "windowPositions"; /*------------------------------------------------------------------------------ * The name of the user preference for storing the token of the edited p.l. *----------------------------------------------------------------------------*/ const std::string editedPlaylistTokenKey = "editedPlaylistToken"; /*------------------------------------------------------------------------------ * Static constant for the key of the scheduler not available error message *----------------------------------------------------------------------------*/ const std::string schedulerNotReachableKey = "schedulerNotReachableMsg"; /*------------------------------------------------------------------------------ * Static constant for the key of the storage not available error message *----------------------------------------------------------------------------*/ const std::string storageNotReachableKey = "storageNotReachableMsg"; /*------------------------------------------------------------------------------ * Static constant for the key of the authentication not available error msg *----------------------------------------------------------------------------*/ const std::string authenticationNotReachableKey = "authenticationNotReachableMsg"; /*------------------------------------------------------------------------------ * Static constant for the key of the locale not available error message *----------------------------------------------------------------------------*/ const std::string localeNotAvailableKey = "localeNotAvailableMsg"; } /* =============================================== local function prototypes */ /* ============================================================= module code */ /*------------------------------------------------------------------------------ * Configure the gLiveSupport object *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: configure(const xmlpp::Element & element) throw (std::invalid_argument, std::logic_error) { if (element.get_name() != configElementNameStr) { std::string eMsg = "Bad configuration element "; eMsg += element.get_name(); throw std::invalid_argument(eMsg); } xmlpp::Node::NodeList nodes; // read the list of supported languages nodes = element.get_children(supportedLanguagesElementName); if (nodes.size() < 1) { throw std::invalid_argument("no supportedLanguages element"); } configSupportedLanguages( *dynamic_cast<const xmlpp::Element*>(nodes.front())); // configure the resource bundle nodes = element.get_children(LocalizedObject::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no resourceBundle element"); } LocalizedConfigurable::configure( *dynamic_cast<const xmlpp::Element*>(nodes.front()) ); // configure the AuthenticationClientFactory nodes = element.get_children( AuthenticationClientFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no authenticationClientFactory element"); } Ptr<AuthenticationClientFactory>::Ref acf = AuthenticationClientFactory::getInstance(); acf->configure(*dynamic_cast<const xmlpp::Element*>(nodes.front())); authentication = acf->getAuthenticationClient(); // configure the StorageClientFactory nodes = element.get_children(StorageClientFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no storageClientFactory element"); } Ptr<StorageClientFactory>::Ref stcf = StorageClientFactory::getInstance(); stcf->configure(*dynamic_cast<const xmlpp::Element*>(nodes.front())); storage = stcf->getStorageClient(); // configure the WidgetFactory nodes = element.get_children(WidgetFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no widgetFactory element"); } widgetFactory = WidgetFactory::getInstance(); widgetFactory->configure( *dynamic_cast<const xmlpp::Element*>(nodes.front()) ); // configure the SchedulerClientFactory nodes = element.get_children( SchedulerClientFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no schedulerClientFactory element"); } Ptr<SchedulerClientFactory>::Ref schcf = SchedulerClientFactory::getInstance(); schcf->configure(*dynamic_cast<const xmlpp::Element*>(nodes.front())); scheduler = schcf->getSchedulerClient(); // configure the scheduler daemon start and stop command strings nodes = element.get_children(schedulerDaemonCommandsElementName); if (nodes.size() < 1) { throw std::invalid_argument("no scheduler daemon commands element"); } const xmlpp::Element* schedulerDaemonCommandsElement = dynamic_cast<const xmlpp::Element*>(nodes.front()); xmlpp::Attribute * schedulerDaemonStartAttribute = schedulerDaemonCommandsElement->get_attribute( "start"); xmlpp::Attribute * schedulerDaemonStopAttribute = schedulerDaemonCommandsElement->get_attribute( "stop"); if (!schedulerDaemonStartAttribute) { throw std::invalid_argument("missing scheduler start command"); } if (!schedulerDaemonStopAttribute) { throw std::invalid_argument("missing scheduler stop command"); } schedulerDaemonStartCommand.reset(new Glib::ustring( schedulerDaemonStartAttribute->get_value())); schedulerDaemonStopCommand.reset(new Glib::ustring( schedulerDaemonStopAttribute->get_value())); Ptr<AudioPlayerFactory>::Ref apf; xmlpp::Element * elem; // configure the outputPlayer AudioPlayerFactory nodes = element.get_children(outputPlayerElementName); if (nodes.size() < 1) { throw std::invalid_argument("no outputPlayer element"); } elem = (xmlpp::Element*) *(nodes.begin()); nodes = elem->get_children(AudioPlayerFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no audioPlayer element"); } apf = AudioPlayerFactory::getInstance(); apf->configure(*dynamic_cast<const xmlpp::Element*>(nodes.front())); outputPlayer = apf->getAudioPlayer(); outputPlayer->initialize(); outputPlayer->attachListener(this); // configure the cuePlayer AudioPlayerFactory nodes = element.get_children(cuePlayerElementName); if (nodes.size() < 1) { throw std::invalid_argument("no cuePlayer element"); } elem = (xmlpp::Element*) *(nodes.begin()); nodes = elem->get_children(AudioPlayerFactory::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no audioPlayer element"); } apf = AudioPlayerFactory::getInstance(); apf->configure(*dynamic_cast<const xmlpp::Element*>(nodes.front())); cuePlayer = apf->getAudioPlayer(); cuePlayer->initialize(); // configure the station logo image nodes = element.get_children(stationLogoConfigElementName); if (nodes.size() < 1) { throw std::invalid_argument("no station logo element"); } const xmlpp::Element* stationLogoElement = dynamic_cast<const xmlpp::Element*>(nodes.front()); const Glib::ustring stationLogoFileName = stationLogoElement->get_attribute("path") ->get_value(); try { stationLogoPixbuf = Gdk::Pixbuf::create_from_file(stationLogoFileName); } catch (Gdk::PixbufError &e) { throw std::invalid_argument("could not open station logo image file"); } // configure the taskbar icon images nodes = element.get_children(taskbarIconsConfigElementName); if (nodes.size() < 1) { throw std::invalid_argument("no taskbar icons element"); } taskbarIcons.reset(new TaskbarIcons()); taskbarIcons->configure( *dynamic_cast<const xmlpp::Element*>(nodes.front()) ); // configure the MetadataTypeContainer nodes = element.get_children(MetadataTypeContainer::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no metadataTypeContainer element"); } Ptr<ResourceBundle>::Ref metadataBundle = getBundle("metadataTypes"); metadataTypeContainer.reset(new MetadataTypeContainer(metadataBundle)); metadataTypeContainer->configure( *dynamic_cast<const xmlpp::Element*>(nodes.front()) ); // configure the KeyboardShortcutList nodes = element.get_children( KeyboardShortcutList::getConfigElementName()); if (nodes.size() < 1) { throw std::invalid_argument("no keyboardShortcutList element"); } keyboardShortcutList.reset(new KeyboardShortcutList); keyboardShortcutList->configure( *dynamic_cast<const xmlpp::Element*>(nodes.front()) ); // save the configuration so we can modify it later // TODO: move configuration code to the OptionsContainer class? Ptr<Glib::ustring>::Ref configFileName(new Glib::ustring); configFileName->append(Glib::get_home_dir()); configFileName->append(configFileDirStr); mkdir(configFileName->c_str(), 0700); // create dir if does not exist configFileName->append(configFileNameStr); optionsContainer.reset(new OptionsContainer(element, configFileName)); // read the test audio file location nodes = element.get_children(testAudioUrlConfigElementName); if (nodes.size() < 1) { throw std::invalid_argument("no test audio url element"); } const xmlpp::Element* testAudioUrlElement = dynamic_cast<const xmlpp::Element*>(nodes.front()); testAudioUrl.reset(new Glib::ustring( testAudioUrlElement->get_attribute("path") ->get_value() )); } /*------------------------------------------------------------------------------ * Configure the list of supported languages *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: configSupportedLanguages(const xmlpp::Element & element) throw (std::invalid_argument) { xmlpp::Node::NodeList nodes; xmlpp::Node::NodeList::iterator begin; xmlpp::Node::NodeList::iterator end; supportedLanguages.reset(new LanguageMap()); // read the list of supported languages nodes = element.get_children(languageElementName); begin = nodes.begin(); end = nodes.end(); while (begin != end) { xmlpp::Element * elem = (xmlpp::Element *) *begin; xmlpp::Attribute * localeAttr = elem->get_attribute(localeAttrName); xmlpp::Attribute * nameAttr = elem->get_attribute(nameAttrName); std::string locale = localeAttr->get_value().raw(); Glib::ustring name = nameAttr->get_value(); supportedLanguages->insert(std::make_pair(name, locale)); begin++; } } /*------------------------------------------------------------------------------ * Check all configured resources *----------------------------------------------------------------------------*/ bool LiveSupport :: GLiveSupport :: GLiveSupport :: checkConfiguration(void) throw () { // === FATAL ERRORS === // first, check if resources are available for all configured languages LanguageMap::iterator it = supportedLanguages->begin(); try { LanguageMap::iterator end = supportedLanguages->end(); while (it != end) { changeLocale((*it).second); ++it; } changeLocale(""); } catch (std::invalid_argument &e) { Ptr<Glib::ustring>::Ref language(new Glib::ustring((*it).first)); Ptr<UnicodeString>::Ref uLanguage = ustringToUnicodeString(language); Ptr<Glib::ustring>::Ref msg = formatMessage(localeNotAvailableKey, (*it).first); displayMessageWindow(msg); changeLocale(""); return false; } // check if the authentication server is available try { authentication->getVersion(); } catch (XmlRpcException &e) { displayAuthenticationServerMissingMessage(); return false; } // === NON-FATAL ERRORS === // check if the storage server is available try { storage->getVersion(); storageAvailable = true; } catch (XmlRpcException &e) { storageAvailable = false; displayMessageWindow(getResourceUstring(storageNotReachableKey)); } // no need to check the widget factory // check the scheduler client checkSchedulerClient(); if (!isSchedulerAvailable()) { displayMessageWindow(getResourceUstring(schedulerNotReachableKey)); } // TODO: check the audio player? return true; } /*------------------------------------------------------------------------------ * Display a message window. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: displayMessageWindow(Ptr<Glib::ustring>::Ref message) throw () { std::cerr << "gLiveSupport: " << *message << std::endl; Ptr<DialogWindow>::Ref window(widgetFactory->createDialogWindow( message, getBundle())); window->run(); } /*------------------------------------------------------------------------------ * Show the main window. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: show(void) throw () { masterPanel.reset(new MasterPanelWindow(shared_from_this(), getBundle())); masterPanel->set_icon_list(taskbarIcons->getIconList()); masterPanel->set_default_icon_list(taskbarIcons->getIconList()); // Shows the window and returns when it is closed. Gtk::Main::run(*masterPanel); masterPanel.reset(); } /*------------------------------------------------------------------------------ * Change the language of the application *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: changeLanguage(Ptr<const std::string>::Ref locale) throw (std::invalid_argument) { changeLocale(*locale); metadataTypeContainer->setBundle(getBundle("metadataTypes")); if (masterPanel.get()) { masterPanel->changeLanguage(getBundle()); } } /*------------------------------------------------------------------------------ * Authenticate the user *----------------------------------------------------------------------------*/ bool LiveSupport :: GLiveSupport :: GLiveSupport :: login(const std::string & login, const std::string & password) throw () { try { sessionId = authentication->login(login, password); } catch (XmlRpcException &e) { return false; } Ptr<const Glib::ustring>::Ref editedPlaylistToken; Ptr<const std::string>::Ref editedPlaylistTokenString; try { editedPlaylistToken = authentication->loadPreferencesItem( sessionId, editedPlaylistTokenKey); editedPlaylistTokenString.reset(new const std::string( *editedPlaylistToken )); } catch (std::invalid_argument &e) { // no stuck playlist token found; that's OK } catch (XmlRpcException &e) { std::cerr << "Problem loading " << editedPlaylistTokenKey << " user preference item:" << std::endl << e.what(); } if (editedPlaylistTokenString) { try { storage->revertPlaylist(editedPlaylistTokenString); } catch (XmlRpcException &e) { // sometimes this throws; we don't care } try { authentication->deletePreferencesItem(sessionId, editedPlaylistTokenKey); } catch (XmlRpcException &e) { std::cerr << "Problem deleting " << editedPlaylistTokenKey << " user preference item at login:" << std::endl << e.what(); } } loadWindowPositions(); if (masterPanel) { masterPanel->createScratchpadWindow(); } return true; } /*------------------------------------------------------------------------------ * Log the user out. *----------------------------------------------------------------------------*/ bool LiveSupport :: GLiveSupport :: GLiveSupport :: logout(void) throw () { if (!sessionId) { return false; } if (masterPanel && !masterPanel->cancelEditedPlaylist()) { return false; // do nothing if the user presses the cancel button } stopCueAudio(); showAnonymousUI(); storeWindowPositions(); windowPositions.clear(); try { authentication->logout(sessionId); } catch (XmlRpcException &e) { std::cerr << "error in GLiveSupport::logout: " << e.what() << std::endl; } sessionId.reset(); return true; } /*------------------------------------------------------------------------------ * Store the contents of a window as a user preference *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: storeWindowContents(ContentsStorable * window) throw () { Ptr<const Glib::ustring>::Ref userPreferencesKey = window->getUserPreferencesKey(); Ptr<const Glib::ustring>::Ref windowContents = window->getContents(); try { authentication->savePreferencesItem(sessionId, *userPreferencesKey, windowContents); } catch (XmlRpcException &e) { // TODO: signal error std::cerr << "error saving user preferences: " << e.what() << std::endl; } } /*------------------------------------------------------------------------------ * Load the contents of a window from a user preference *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: loadWindowContents(ContentsStorable * window) throw () { Ptr<const Glib::ustring>::Ref userPreferencesKey = window->getUserPreferencesKey(); Ptr<const Glib::ustring>::Ref windowContents; try { windowContents = authentication->loadPreferencesItem( sessionId, *userPreferencesKey); } catch (XmlRpcException &e) { // TODO: signal error std::cerr << "error loading user preferences: " << e.what() << std::endl; return; } catch (std::invalid_argument &e) { // no scratchpad stored for this user yet; no problem return; } window->setContents(windowContents); } /*------------------------------------------------------------------------------ * Show the anonymous UI *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: showAnonymousUI(void) throw () { if (masterPanel.get()) { masterPanel->showAnonymousUI(); } } /*------------------------------------------------------------------------------ * Show the UI when someone is logged in *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: showLoggedInUI(void) throw () { if (masterPanel.get()) { masterPanel->showLoggedInUI(); } } /*------------------------------------------------------------------------------ * Open an audio clip, and put it into the internal cache of the GLiveSupport * object. *----------------------------------------------------------------------------*/ Ptr<AudioClip>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: getAudioClip(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<AudioClip>::Ref clip; clip = (*openedAudioClips)[id->getId()]; if (!clip.get()) { clip = storage->getAudioClip(sessionId, id); (*openedAudioClips)[id->getId()] = clip; } return clip; } /*------------------------------------------------------------------------------ * Acquire an audio clip, and put it into the internal cache of * the GLiveSupport object. *----------------------------------------------------------------------------*/ Ptr<AudioClip>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: acquireAudioClip(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<AudioClip>::Ref clip; clip = (*openedAudioClips)[id->getId()]; if (!clip.get() || !clip->getToken().get()) { clip = storage->acquireAudioClip(sessionId, id); (*openedAudioClips)[id->getId()] = clip; } return clip; } /*------------------------------------------------------------------------------ * Open an playlist, and put it into the internal cache of the GLiveSupport * object. *----------------------------------------------------------------------------*/ Ptr<Playlist>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: getPlaylist(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<Playlist>::Ref playlist; playlist = (*openedPlaylists)[id->getId()]; if (!playlist.get()) { playlist = storage->getPlaylist(sessionId, id); (*openedPlaylists)[id->getId()] = playlist; } return playlist; } /*------------------------------------------------------------------------------ * Acquire an playlist, and put it into the internal cache of * the GLiveSupport object. *----------------------------------------------------------------------------*/ Ptr<Playlist>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: acquirePlaylist(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<Playlist>::Ref playlist; playlist = (*openedPlaylists)[id->getId()]; if (!playlist.get() || !playlist->getUri().get()) { playlist = storage->acquirePlaylist(sessionId, id); (*openedPlaylists)[id->getId()] = playlist; } return playlist; } /*------------------------------------------------------------------------------ * Open a Playable object. *----------------------------------------------------------------------------*/ Ptr<Playable>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: getPlayable(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<Playable>::Ref playable; if (existsPlaylist(id)) { playable = getPlaylist(id); } else if (existsAudioClip(id)) { playable = getAudioClip(id); } else { throw XmlRpcInvalidArgumentException( "invalid ID in GLiveSupport::acquirePlayable"); } return playable; } /*------------------------------------------------------------------------------ * Acquire a Playable object. *----------------------------------------------------------------------------*/ Ptr<Playable>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: acquirePlayable(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<Playable>::Ref playable; if (existsPlaylist(id)) { playable = acquirePlaylist(id); } else if (existsAudioClip(id)) { playable = acquireAudioClip(id); } else { throw XmlRpcInvalidArgumentException( "invalid ID in GLiveSupport::acquirePlayable"); } return playable; } /*------------------------------------------------------------------------------ * Remove a playlist from the playlist cache. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: uncachePlaylist(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { Ptr<Playlist>::Ref playlist; PlaylistMap::iterator it; PlaylistMap::iterator end = openedPlaylists->end(); if ((it = openedPlaylists->find(id->getId())) != end) { playlist = (*openedPlaylists)[id->getId()]; if (playlist->getUri().get()) { storage->releasePlaylist(playlist); } openedPlaylists->erase(it); } } /*----------------------------------------------------------------------------- * Release all opened audio clips. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: releaseOpenedAudioClips(void) throw (XmlRpcException) { AudioClipMap::iterator it = openedAudioClips->begin(); AudioClipMap::iterator end = openedAudioClips->end(); while (it != end) { Ptr<AudioClip>::Ref clip = (*it).second; if (clip->getToken().get()) { storage->releaseAudioClip(clip); } ++it; } openedAudioClips->clear(); } /*------------------------------------------------------------------------------ * Release all opened playlists. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: releaseOpenedPlaylists(void) throw (XmlRpcException) { PlaylistMap::iterator it = openedPlaylists->begin(); PlaylistMap::iterator end = openedPlaylists->end(); while (it != end) { Ptr<Playlist>::Ref playlist = (*it).second; if (playlist->getUri().get()) { storage->releasePlaylist(playlist); } ++it; } openedPlaylists->clear(); } /*------------------------------------------------------------------------------ * Upload an audio clip to the local storage. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: uploadAudioClip(Ptr<AudioClip>::Ref audioClip) throw (XmlRpcException) { storage->storeAudioClip(sessionId, audioClip); // this will also add it to the local cache addToScratchpad(audioClip); } /*------------------------------------------------------------------------------ * Upload a playlist archive to the local storage. *----------------------------------------------------------------------------*/ Ptr<Playlist>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: uploadPlaylistArchive(Ptr<const Glib::ustring>::Ref path) throw (XmlRpcException) { Ptr<UniqueId>::Ref id = storage->importPlaylist(sessionId, path); Ptr<Playlist>::Ref playlist = storage->getPlaylist(sessionId, id); // this will also add it to the local cache addToScratchpad(playlist); return playlist; } /*------------------------------------------------------------------------------ * Add a file to the Scratchpad, and update it. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: addToScratchpad(Ptr<Playable>::Ref playable) throw (XmlRpcException) { if (playable->getType() == Playable::AudioClipType) { acquireAudioClip(playable->getId()); } else if (playable->getType() == Playable::PlaylistType) { acquirePlaylist(playable->getId()); } // this will also add it to the local cache masterPanel->updateScratchpadWindow(playable); } /*------------------------------------------------------------------------------ * Add a file to the Live Mode, and update it. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: addToLiveMode(Ptr<Playable>::Ref playable) throw () { masterPanel->updateLiveModeWindow(playable); } /*------------------------------------------------------------------------------ * Display the playable item on the master panel as "now playing". *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: setNowPlaying(Ptr<Playable>::Ref playable) throw () { masterPanel->setNowPlaying(playable); } /*------------------------------------------------------------------------------ * Open a playlist for editing. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: openPlaylistForEditing(Ptr<const UniqueId>::Ref playlistId) throw (XmlRpcException) { if (masterPanel->cancelEditedPlaylist() == false) { return; // the user canceled the operation } if (!playlistId.get()) { playlistId = storage->createPlaylist(sessionId); } else { uncachePlaylist(playlistId); } editedPlaylist = storage->editPlaylist(sessionId, playlistId); try { Ptr<const Glib::ustring>::Ref editToken(new const Glib::ustring( *editedPlaylist->getEditToken() )); authentication->savePreferencesItem(sessionId, editedPlaylistTokenKey, editToken); } catch (XmlRpcException &e) { std::cerr << "Problem saving " << editedPlaylistTokenKey << " user preference item:" << std::endl << e.what(); } editedPlaylist->createSavedCopy(); masterPanel->updateSimplePlaylistMgmtWindow(); } /*------------------------------------------------------------------------------ * Cancel the edited playlist: undo changes and release the lock. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: cancelEditedPlaylist(void) throw (XmlRpcException) { if (editedPlaylist) { if (editedPlaylist->isLocked()) { editedPlaylist->revertToSavedCopy(); storage->savePlaylist(sessionId, editedPlaylist); try { authentication->deletePreferencesItem(sessionId, editedPlaylistTokenKey); } catch (XmlRpcException &e) { std::cerr << "Problem deleting " << editedPlaylistTokenKey << " user preference item at cancel:" << std::endl << e.what(); } } editedPlaylist.reset(); } } /*------------------------------------------------------------------------------ * Add a playlist to the currently edited playlist *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: addToPlaylist(Ptr<const UniqueId>::Ref id) throw (XmlRpcException) { if (!editedPlaylist.get()) { openPlaylistForEditing(); } // append the appropriate playable object to the end of the playlist if (existsPlaylist(id)) { Ptr<Playlist>::Ref playlist = getPlaylist(id); editedPlaylist->addPlaylist(playlist, editedPlaylist->getPlaylength()); } else if (existsAudioClip(id)) { Ptr<AudioClip>::Ref clip = getAudioClip(id); editedPlaylist->addAudioClip(clip, editedPlaylist->getPlaylength()); } masterPanel->updateSimplePlaylistMgmtWindow(); emitSignalEditedPlaylistModified(); } /*------------------------------------------------------------------------------ * Save the currently edited playlist in storage *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: savePlaylist(void) throw (XmlRpcException) { if (editedPlaylist) { if (editedPlaylist->isLocked()) { editedPlaylist->deleteSavedCopy(); storage->savePlaylist(sessionId, editedPlaylist); try { authentication->deletePreferencesItem(sessionId, editedPlaylistTokenKey); } catch (XmlRpcException &e) { std::cerr << "Problem deleting " << editedPlaylistTokenKey << " user preference item at save:" << std::endl << e.what(); } // update with new version // this will also add it to the local cache uncachePlaylist(editedPlaylist->getId()); addToScratchpad(editedPlaylist); refreshPlaylistInLiveMode(editedPlaylist); } editedPlaylist.reset(); } } /*------------------------------------------------------------------------------ * Schedule a playlist, then show the scheduler at that timepoint *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: schedulePlaylist(Ptr<Playlist>::Ref playlist, Ptr<posix_time::ptime>::Ref playtime) throw (XmlRpcException) { scheduler->uploadPlaylist(sessionId, playlist->getId(), playtime); masterPanel->updateSchedulerWindow(playtime); } /*------------------------------------------------------------------------------ * Remove a scheduled entry. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: removeFromSchedule(Ptr<const UniqueId>::Ref scheduleEntryId) throw (XmlRpcException) { // for some weird reason, the schedule functions won't accept // Ptr<const UniqueId>::Ref, just a non-const version Ptr<UniqueId>::Ref seid(new UniqueId(scheduleEntryId->getId())); scheduler->removeFromSchedule(sessionId, seid); } /*------------------------------------------------------------------------------ * Play a Playable object using the output audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: playOutputAudio(Ptr<Playable>::Ref playable) throw (std::logic_error, std::runtime_error) { try { switch (playable->getType()) { case Playable::AudioClipType: outputItemPlayingNow = acquireAudioClip(playable->getId()); outputPlayer->open(*outputItemPlayingNow->getUri()); outputPlayer->start(); std::cerr << "gLiveSupport: Live Mode playing audio clip '" << *playable->getTitle() << "'" << std::endl; break; case Playable::PlaylistType: outputItemPlayingNow = acquirePlaylist(playable->getId()); outputPlayer->open(*outputItemPlayingNow->getUri()); outputPlayer->start(); std::cerr << "gLiveSupport: Live Mode playing playlist '" << *playable->getTitle() << "'" << std::endl; break; default: // this never happens break; } } catch (XmlRpcException &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } catch (std::invalid_argument &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } catch (std::runtime_error &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } outputPlayerIsPaused = false; } /*------------------------------------------------------------------------------ * Pause the output audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: pauseOutputAudio(void) throw (std::logic_error) { if (!outputPlayerIsPaused && outputPlayer->isPlaying()) { outputPlayer->pause(); outputPlayerIsPaused = true; } else if (outputPlayerIsPaused) { outputPlayer->start(); outputPlayerIsPaused = false; } } /*------------------------------------------------------------------------------ * Stop the output audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: stopOutputAudio(void) throw (std::logic_error) { if (outputItemPlayingNow) { outputPlayerIsPaused = false; outputItemPlayingNow.reset(); Ptr<Playable>::Ref nullPointer; setNowPlaying(nullPointer); outputPlayer->close(); } } /*------------------------------------------------------------------------------ * Event handler for the "output audio player has stopped" event. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: onStop(void) throw () { outputItemPlayingNow.reset(); try { outputPlayer->close(); Ptr<Playable>::Ref playable = masterPanel->getNextItemToPlay(); setNowPlaying(playable); if (playable) { playOutputAudio(playable); } } catch (std::logic_error) { std::cerr << "logic_error caught in GLiveSupport::onStop()\n"; std::exit(1); } } /*------------------------------------------------------------------------------ * Play a Playable object using the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: playCueAudio(Ptr<Playable>::Ref playable) throw (std::logic_error, std::runtime_error) { if (cueItemPlayingNow) { stopCueAudio(); // stop the audio player and } // release old resources try { switch (playable->getType()) { case Playable::AudioClipType: cueItemPlayingNow = acquireAudioClip(playable->getId()); cuePlayer->open(*cueItemPlayingNow->getUri()); cuePlayer->start(); std::cerr << "gLiveSupport: Cue playing audio clip '" << *playable->getTitle() << "'" << std::endl; break; case Playable::PlaylistType: cueItemPlayingNow = acquirePlaylist(playable->getId()); cuePlayer->open(*cueItemPlayingNow->getUri()); cuePlayer->start(); std::cerr << "gLiveSupport: Cue playing playlist '" << *playable->getTitle() << "'" << std::endl; break; default: // this never happens break; } } catch (XmlRpcException &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } catch (std::invalid_argument &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } catch (std::runtime_error &e) { Ptr<Glib::ustring>::Ref eMsg = getResourceUstring("audioErrorMsg"); eMsg->append("\n"); eMsg->append(e.what()); displayMessageWindow(eMsg); throw std::runtime_error(e.what()); } cuePlayerIsPaused = false; } /*------------------------------------------------------------------------------ * Pause the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: pauseCueAudio(void) throw (std::logic_error) { if (!cuePlayerIsPaused && cuePlayer->isPlaying()) { cuePlayer->pause(); cuePlayerIsPaused = true; } else if (cuePlayerIsPaused) { cuePlayer->start(); cuePlayerIsPaused = false; } } /*------------------------------------------------------------------------------ * Stop the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: stopCueAudio(void) throw (std::logic_error) { if (cueItemPlayingNow) { cuePlayer->close(); cuePlayerIsPaused = false; cueItemPlayingNow.reset(); masterPanel->showCuePlayerStopped(); } } /*------------------------------------------------------------------------------ * Attach a listener for the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: attachCueAudioListener(AudioPlayerEventListener * listener) throw () { cuePlayer->attachListener(listener); } /*------------------------------------------------------------------------------ * Detach the listener for the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: detachCueAudioListener(AudioPlayerEventListener * listener) throw (std::invalid_argument) { cuePlayer->detachListener(listener); } /*------------------------------------------------------------------------------ * Return an image containing the radio station logo. *----------------------------------------------------------------------------*/ Gtk::Image * LiveSupport :: GLiveSupport :: GLiveSupport :: getStationLogoImage(void) throw() { return new Gtk::Image(stationLogoPixbuf); } /*------------------------------------------------------------------------------ * Get the localized name of the keyboard shortcut action. *----------------------------------------------------------------------------*/ Ptr<const Glib::ustring>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: getLocalizedKeyboardActionName( Ptr<const Glib::ustring>::Ref actionName) throw (std::invalid_argument) { return getResourceUstring("keyboardShortcuts", actionName->c_str()); } /*------------------------------------------------------------------------------ * Get the localized name of the window. *----------------------------------------------------------------------------*/ Ptr<const Glib::ustring>::Ref LiveSupport :: GLiveSupport :: GLiveSupport :: getLocalizedWindowName( Ptr<const Glib::ustring>::Ref windowName) throw (std::invalid_argument) { return getResourceUstring(windowName->c_str(), "windowTitle"); } /*------------------------------------------------------------------------------ * Save the position and size of the window. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: putWindowPosition(Ptr<const Gtk::Window>::Ref window) throw () { WindowPositionType pos; window->get_position(pos.x, pos.y); window->get_size(pos.width, pos.height); windowPositions[window->get_name()] = pos; } /*------------------------------------------------------------------------------ * Apply saved position and size data to the window. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: getWindowPosition(Ptr<Gtk::Window>::Ref window) throw () { WindowPositionsListType::const_iterator it = windowPositions.find( window->get_name()); if (it != windowPositions.end()) { WindowPositionType pos = it->second; window->move(pos.x, pos.y); window->resize(pos.width, pos.height); } } /*------------------------------------------------------------------------------ * Store the saved window positions. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: storeWindowPositions(void) throw () { // just store this as a space-delimited list of window names and numbers std::ostringstream prefsString; WindowPositionsListType::iterator it; WindowPositionsListType::iterator end; WindowPositionType pos; it = windowPositions.begin(); end = windowPositions.end(); while (it != end) { prefsString << it->first << " "; pos = it->second; prefsString << pos.x << " " << pos.y << " " << pos.width << " " << pos.height << " "; ++it; } Ptr<Glib::ustring>::Ref prefsUstring(new Glib::ustring(prefsString.str())); try { authentication->savePreferencesItem(sessionId, windowPositionsKey, prefsUstring); } catch (XmlRpcException &e) { // TODO: signal error std::cerr << "error saving user preferences: " << e.what() << std::endl; } } /*------------------------------------------------------------------------------ * Load the window positions. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: loadWindowPositions(void) throw () { Ptr<Glib::ustring>::Ref prefsUstring; try { prefsUstring = authentication->loadPreferencesItem(sessionId, windowPositionsKey); } catch (XmlRpcException &e) { // TODO: signal error std::cerr << "error loading user preferences: " << e.what() << std::endl; return; } catch (std::invalid_argument &e) { // no window positions were stored for this user yet; no problem return; } // load the prefs, which is a space-delimited list std::istringstream prefsString(prefsUstring->raw()); while (!prefsString.eof()) { Glib::ustring windowName; prefsString >> windowName; if (prefsString.fail()) { break; } WindowPositionType pos; prefsString >> pos.x; if (prefsString.fail()) { continue; } prefsString >> pos.y; if (prefsString.fail()) { continue; } prefsString >> pos.width; if (prefsString.fail()) { continue; } prefsString >> pos.height; if (prefsString.fail()) { continue; } windowPositions[windowName] = pos; } } /*------------------------------------------------------------------------------ * Set the device for the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: setCueAudioDevice(Ptr<const Glib::ustring>::Ref deviceName) throw () { cuePlayer->setAudioDevice(*deviceName); } /*------------------------------------------------------------------------------ * Play a test sound on the cue audio player. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: playTestSoundOnCue(void) throw () { if (cueItemPlayingNow) { stopCueAudio(); // stop the audio player and } // release old resources try { cuePlayer->open(*testAudioUrl); cuePlayer->start(); Ptr<time_duration>::Ref sleepT(new time_duration(microseconds(10))); while (cuePlayer->isPlaying()) { TimeConversion::sleep(sleepT); } } catch (std::runtime_error &e) { // "invalid device" error from open(); do nothing } cuePlayer->close(); } /*------------------------------------------------------------------------------ * Check if the scheduler is available. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: checkSchedulerClient(void) throw () { try { scheduler->getVersion(); schedulerAvailable = true; if (masterPanel) { masterPanel->setSchedulerAvailable(true); } } catch (XmlRpcException &e) { schedulerAvailable = false; if (masterPanel) { masterPanel->setSchedulerAvailable(false); } } } /*------------------------------------------------------------------------------ * Start the scheduler daemon. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: startSchedulerClient(void) throw () { system(schedulerDaemonStartCommand->c_str()); } /*------------------------------------------------------------------------------ * Stop the scheduler daemon. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: stopSchedulerClient(void) throw () { system(schedulerDaemonStopCommand->c_str()); } /*------------------------------------------------------------------------------ * Upload a Playable object to the network hub. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: uploadToHub(Ptr<Playable>::Ref playable) throw () { masterPanel->uploadToHub(playable); } /*------------------------------------------------------------------------------ * Display a message that the authentication server is not available. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: displayAuthenticationServerMissingMessage(void) throw () { Ptr<Glib::ustring>::Ref message; try { message = getResourceUstring("authenticationNotReachableMsg"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; std::exit(1); } // "authentication not available -- would you like to edit the options?" Ptr<DialogWindow>::Ref question(widgetFactory->createDialogWindow( message, getBundle(), DialogWindow::noButton | DialogWindow::yesButton )); DialogWindow::ButtonType answer = question->run(); if (answer == DialogWindow::yesButton) { Ptr<ResourceBundle>::Ref bundle; try { bundle = getBundle("optionsWindow"); } catch (std::invalid_argument &e) { std::cerr << e.what() << std::endl; return; } Ptr<OptionsWindow>::Ref optionsWindow(new OptionsWindow( shared_from_this(), bundle, 0)); optionsWindow->run(); if (optionsContainer->isTouched()) { optionsContainer->writeToFile(); } } } /*------------------------------------------------------------------------------ * Refresh the playlist in the Live Mode window. *----------------------------------------------------------------------------*/ void LiveSupport :: GLiveSupport :: GLiveSupport :: refreshPlaylistInLiveMode(Ptr<Playlist>::Ref playlist) throw () { masterPanel->refreshPlaylistInLiveMode(playlist); }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // render window manager UI module #include "QmitkRenderWindowDataStorageInspector.h" #include "QmitkCustomVariants.h" // mitk core #include <mitkBaseRenderer.h> // qt #include <QSignalMapper> QmitkRenderWindowDataStorageInspector::QmitkRenderWindowDataStorageInspector(QWidget* parent /*=nullptr*/) : QmitkAbstractDataStorageInspector(parent) { m_Controls.setupUi(this); // initialize the render window layer controller and the render window view direction controller m_RenderWindowLayerController = std::make_unique<mitk::RenderWindowLayerController>(); m_RenderWindowViewDirectionController = std::make_unique<mitk::RenderWindowViewDirectionController>(); m_StorageModel = std::make_unique<QmitkRenderWindowDataStorageTreeModel>(this); m_Controls.renderWindowTreeView->setModel(m_StorageModel.get()); m_Controls.renderWindowTreeView->setHeaderHidden(true); m_Controls.renderWindowTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers); m_Controls.renderWindowTreeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_Controls.renderWindowTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_Controls.renderWindowTreeView->setAlternatingRowColors(true); m_Controls.renderWindowTreeView->setDragEnabled(true); m_Controls.renderWindowTreeView->setDropIndicatorShown(true); m_Controls.renderWindowTreeView->setAcceptDrops(true); m_Controls.renderWindowTreeView->setContextMenuPolicy(Qt::CustomContextMenu); SetUpConnections(); } QAbstractItemView* QmitkRenderWindowDataStorageInspector::GetView() { return m_Controls.renderWindowTreeView; } const QAbstractItemView* QmitkRenderWindowDataStorageInspector::GetView() const { return m_Controls.renderWindowTreeView; } void QmitkRenderWindowDataStorageInspector::SetSelectionMode(SelectionMode mode) { m_Controls.renderWindowTreeView->setSelectionMode(mode); } QmitkRenderWindowDataStorageInspector::SelectionMode QmitkRenderWindowDataStorageInspector::GetSelectionMode() const { return m_Controls.renderWindowTreeView->selectionMode(); } void QmitkRenderWindowDataStorageInspector::Initialize() { if (m_DataStorage.IsExpired()) { return; } auto dataStorage = m_DataStorage.Lock(); m_StorageModel->SetDataStorage(dataStorage); m_StorageModel->SetNodePredicate(m_NodePredicate); m_RenderWindowLayerController->SetDataStorage(dataStorage); m_RenderWindowViewDirectionController->SetDataStorage(dataStorage); m_Connector->SetView(m_Controls.renderWindowTreeView); } void QmitkRenderWindowDataStorageInspector::SetUpConnections() { connect(m_StorageModel.get(), &QAbstractItemModel::rowsInserted, this, &QmitkRenderWindowDataStorageInspector::ModelRowsInserted); connect(m_Controls.pushButtonSetAsBaseLayer, &QPushButton::clicked, this, &QmitkRenderWindowDataStorageInspector::SetAsBaseLayer); connect(m_Controls.pushButtonResetRenderer, &QPushButton::clicked, this, &QmitkRenderWindowDataStorageInspector::ResetRenderer); QSignalMapper* changeViewDirectionSignalMapper = new QSignalMapper(this); changeViewDirectionSignalMapper->setMapping(m_Controls.radioButtonAxial, QString("axial")); changeViewDirectionSignalMapper->setMapping(m_Controls.radioButtonCoronal, QString("coronal")); changeViewDirectionSignalMapper->setMapping(m_Controls.radioButtonSagittal, QString("sagittal")); changeViewDirectionSignalMapper->setMapping(m_Controls.radioButton3D, QString("3D")); connect(changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)(const QString&)>(&QSignalMapper::mapped), this, &QmitkRenderWindowDataStorageInspector::ChangeViewDirection); connect(m_Controls.radioButtonAxial, &QPushButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map)); connect(m_Controls.radioButtonCoronal, &QPushButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map)); connect(m_Controls.radioButtonSagittal, &QPushButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map)); connect(m_Controls.radioButton3D, &QPushButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map)); } void QmitkRenderWindowDataStorageInspector::SetControlledRenderer(mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer) { m_StorageModel->SetControlledRenderer(controlledRenderer); m_RenderWindowLayerController->SetControlledRenderer(controlledRenderer); m_RenderWindowViewDirectionController->SetControlledRenderer(controlledRenderer); } void QmitkRenderWindowDataStorageInspector::SetActiveRenderWindow(const QString& renderWindowId) { mitk::BaseRenderer* selectedRenderer = mitk::BaseRenderer::GetByName(renderWindowId.toStdString()); if (nullptr == selectedRenderer) { return; } m_StorageModel->SetCurrentRenderer(selectedRenderer); mitk::SliceNavigationController::ViewDirection viewDirection = selectedRenderer->GetSliceNavigationController()->GetDefaultViewDirection(); switch (viewDirection) { case mitk::SliceNavigationController::Axial: m_Controls.radioButtonAxial->setChecked(true); break; case mitk::SliceNavigationController::Frontal: m_Controls.radioButtonCoronal->setChecked(true); break; case mitk::SliceNavigationController::Sagittal: m_Controls.radioButtonSagittal->setChecked(true); break; default: break; } } void QmitkRenderWindowDataStorageInspector::ModelRowsInserted(const QModelIndex& parent, int start, int end) { m_Controls.renderWindowTreeView->setExpanded(parent, true); } void QmitkRenderWindowDataStorageInspector::SetAsBaseLayer() { QModelIndex selectedIndex = m_Controls.renderWindowTreeView->currentIndex(); if (selectedIndex.isValid()) { QVariant qvariantDataNode = m_StorageModel->data(selectedIndex, Qt::UserRole); if (qvariantDataNode.canConvert<mitk::DataNode*>()) { mitk::DataNode* dataNode = qvariantDataNode.value<mitk::DataNode*>(); m_RenderWindowLayerController->SetBaseDataNode(dataNode, m_StorageModel->GetCurrentRenderer()); m_Controls.renderWindowTreeView->clearSelection(); } } } void QmitkRenderWindowDataStorageInspector::ResetRenderer() { m_RenderWindowLayerController->ResetRenderer(true, m_StorageModel->GetCurrentRenderer()); m_Controls.renderWindowTreeView->clearSelection(); } void QmitkRenderWindowDataStorageInspector::ChangeViewDirection(const QString& viewDirection) { m_RenderWindowViewDirectionController->SetViewDirectionOfRenderer(viewDirection.toStdString(), m_StorageModel->GetCurrentRenderer()); } Fix unused parameter /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // render window manager UI module #include "QmitkRenderWindowDataStorageInspector.h" #include "QmitkCustomVariants.h" // mitk core #include <mitkBaseRenderer.h> // qt #include <QSignalMapper> QmitkRenderWindowDataStorageInspector::QmitkRenderWindowDataStorageInspector(QWidget* parent /*=nullptr*/) : QmitkAbstractDataStorageInspector(parent) { m_Controls.setupUi(this); // initialize the render window layer controller and the render window view direction controller m_RenderWindowLayerController = std::make_unique<mitk::RenderWindowLayerController>(); m_RenderWindowViewDirectionController = std::make_unique<mitk::RenderWindowViewDirectionController>(); m_StorageModel = std::make_unique<QmitkRenderWindowDataStorageTreeModel>(this); m_Controls.renderWindowTreeView->setModel(m_StorageModel.get()); m_Controls.renderWindowTreeView->setHeaderHidden(true); m_Controls.renderWindowTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers); m_Controls.renderWindowTreeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_Controls.renderWindowTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_Controls.renderWindowTreeView->setAlternatingRowColors(true); m_Controls.renderWindowTreeView->setDragEnabled(true); m_Controls.renderWindowTreeView->setDropIndicatorShown(true); m_Controls.renderWindowTreeView->setAcceptDrops(true); m_Controls.renderWindowTreeView->setContextMenuPolicy(Qt::CustomContextMenu); SetUpConnections(); } QAbstractItemView* QmitkRenderWindowDataStorageInspector::GetView() { return m_Controls.renderWindowTreeView; } const QAbstractItemView* QmitkRenderWindowDataStorageInspector::GetView() const { return m_Controls.renderWindowTreeView; } void QmitkRenderWindowDataStorageInspector::SetSelectionMode(SelectionMode mode) { m_Controls.renderWindowTreeView->setSelectionMode(mode); } QmitkRenderWindowDataStorageInspector::SelectionMode QmitkRenderWindowDataStorageInspector::GetSelectionMode() const { return m_Controls.renderWindowTreeView->selectionMode(); } void QmitkRenderWindowDataStorageInspector::Initialize() { if (m_DataStorage.IsExpired()) { return; } auto dataStorage = m_DataStorage.Lock(); m_StorageModel->SetDataStorage(dataStorage); m_StorageModel->SetNodePredicate(m_NodePredicate); m_RenderWindowLayerController->SetDataStorage(dataStorage); m_RenderWindowViewDirectionController->SetDataStorage(dataStorage); m_Connector->SetView(m_Controls.renderWindowTreeView); } void QmitkRenderWindowDataStorageInspector::SetUpConnections() { connect(m_StorageModel.get(), &QAbstractItemModel::rowsInserted, this, &QmitkRenderWindowDataStorageInspector::ModelRowsInserted); connect(m_Controls.pushButtonSetAsBaseLayer, &QPushButton::clicked, this, &QmitkRenderWindowDataStorageInspector::SetAsBaseLayer); connect(m_Controls.pushButtonResetRenderer, &QPushButton::clicked, this, &QmitkRenderWindowDataStorageInspector::ResetRenderer); QSignalMapper* changeViewDirectionSignalMapper = new QSignalMapper(this); changeViewDirectionSignalMapper->setMapping(m_Controls.radioButtonAxial, QString("axial")); changeViewDirectionSignalMapper->setMapping(m_Controls.radioButtonCoronal, QString("coronal")); changeViewDirectionSignalMapper->setMapping(m_Controls.radioButtonSagittal, QString("sagittal")); changeViewDirectionSignalMapper->setMapping(m_Controls.radioButton3D, QString("3D")); connect(changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)(const QString&)>(&QSignalMapper::mapped), this, &QmitkRenderWindowDataStorageInspector::ChangeViewDirection); connect(m_Controls.radioButtonAxial, &QPushButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map)); connect(m_Controls.radioButtonCoronal, &QPushButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map)); connect(m_Controls.radioButtonSagittal, &QPushButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map)); connect(m_Controls.radioButton3D, &QPushButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map)); } void QmitkRenderWindowDataStorageInspector::SetControlledRenderer(mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer) { m_StorageModel->SetControlledRenderer(controlledRenderer); m_RenderWindowLayerController->SetControlledRenderer(controlledRenderer); m_RenderWindowViewDirectionController->SetControlledRenderer(controlledRenderer); } void QmitkRenderWindowDataStorageInspector::SetActiveRenderWindow(const QString& renderWindowId) { mitk::BaseRenderer* selectedRenderer = mitk::BaseRenderer::GetByName(renderWindowId.toStdString()); if (nullptr == selectedRenderer) { return; } m_StorageModel->SetCurrentRenderer(selectedRenderer); mitk::SliceNavigationController::ViewDirection viewDirection = selectedRenderer->GetSliceNavigationController()->GetDefaultViewDirection(); switch (viewDirection) { case mitk::SliceNavigationController::Axial: m_Controls.radioButtonAxial->setChecked(true); break; case mitk::SliceNavigationController::Frontal: m_Controls.radioButtonCoronal->setChecked(true); break; case mitk::SliceNavigationController::Sagittal: m_Controls.radioButtonSagittal->setChecked(true); break; default: break; } } void QmitkRenderWindowDataStorageInspector::ModelRowsInserted(const QModelIndex& parent, int /*start*/, int /*end*/) { m_Controls.renderWindowTreeView->setExpanded(parent, true); } void QmitkRenderWindowDataStorageInspector::SetAsBaseLayer() { QModelIndex selectedIndex = m_Controls.renderWindowTreeView->currentIndex(); if (selectedIndex.isValid()) { QVariant qvariantDataNode = m_StorageModel->data(selectedIndex, Qt::UserRole); if (qvariantDataNode.canConvert<mitk::DataNode*>()) { mitk::DataNode* dataNode = qvariantDataNode.value<mitk::DataNode*>(); m_RenderWindowLayerController->SetBaseDataNode(dataNode, m_StorageModel->GetCurrentRenderer()); m_Controls.renderWindowTreeView->clearSelection(); } } } void QmitkRenderWindowDataStorageInspector::ResetRenderer() { m_RenderWindowLayerController->ResetRenderer(true, m_StorageModel->GetCurrentRenderer()); m_Controls.renderWindowTreeView->clearSelection(); } void QmitkRenderWindowDataStorageInspector::ChangeViewDirection(const QString& viewDirection) { m_RenderWindowViewDirectionController->SetViewDirectionOfRenderer(viewDirection.toStdString(), m_StorageModel->GetCurrentRenderer()); }
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //#define VNET_DEBUG //#define VNET_DEBUG_RX //#define VNET_DEBUG_TX #ifdef VNET_DEBUG #define VDBG(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define VDBG(fmt, ...) /* fmt */ #endif #ifdef VNET_DEBUG_RX #define VDBG_RX(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define VDBG_RX(fmt, ...) /* fmt */ #endif #ifdef VNET_DEBUG_TX #define VDBG_TX(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define VDBG_TX(fmt, ...) /* fmt */ #endif #include "virtionet.hpp" #include <kernel/irq_manager.hpp> #include <malloc.h> #include <cstring> //#define NO_DEFERRED_KICK #ifndef NO_DEFERRED_KICK #include <smp> struct alignas(SMP_ALIGN) smp_deferred_kick { std::vector<VirtioNet*> devs; uint8_t irq; }; static std::array<smp_deferred_kick, SMP_MAX_CORES> deferred_devs; #endif using namespace net; void VirtioNet::get_config() { Virtio::get_config(&_conf, _config_length); } VirtioNet::VirtioNet(hw::PCI_Device& d) : Virtio(d), Link(Link_protocol{{this, &VirtioNet::transmit}, mac()}, 256u, 2048 /* 256x half-page buffers */), packets_rx_{Statman::get().create(Stat::UINT64, device_name() + ".packets_rx").get_uint64()}, packets_tx_{Statman::get().create(Stat::UINT64, device_name() + ".packets_tx").get_uint64()} { INFO("VirtioNet", "Driver initializing"); uint32_t needed_features = 0 | (1 << VIRTIO_NET_F_MAC) | (1 << VIRTIO_NET_F_STATUS) ;//| (1 << VIRTIO_NET_F_MRG_RXBUF); //Merge RX Buffers (Everything i 1 buffer) uint32_t wanted_features = needed_features; negotiate_features(wanted_features); CHECK ((features() & needed_features) == needed_features, "Negotiated needed features"); CHECK ((features() & wanted_features) == wanted_features, "Negotiated wanted features"); CHECK(features() & (1 << VIRTIO_NET_F_CSUM), "Device handles packets w. partial checksum"); CHECK(features() & (1 << VIRTIO_NET_F_GUEST_CSUM), "Guest handles packets w. partial checksum"); CHECK(features() & (1 << VIRTIO_NET_F_CTRL_VQ), "There's a control queue"); CHECK(features() & (1 << VIRTIO_F_ANY_LAYOUT), "Queue can handle any header/data layout"); CHECK(features() & (1 << VIRTIO_F_RING_INDIRECT_DESC), "We can use indirect descriptors"); CHECK(features() & (1 << VIRTIO_F_RING_EVENT_IDX), "There's a Ring Event Index to use"); CHECK(features() & (1 << VIRTIO_NET_F_MQ), "There are multiple queue pairs"); if (features() & (1 << VIRTIO_NET_F_MQ)) printf("\t\t* max_virtqueue_pairs: 0x%x \n",_conf.max_virtq_pairs); CHECK(features() & (1 << VIRTIO_NET_F_MRG_RXBUF), "Merge RX buffers"); /** RX que is 0, TX Queue is 1 - Virtio Std. §5.1.2 */ new (&rx_q) Virtio::Queue(device_name() + ".rx_q", queue_size(0),0,iobase()); new (&tx_q) Virtio::Queue(device_name() + ".tx_q", queue_size(1),1,iobase()); new (&ctrl_q) Virtio::Queue(device_name() + ".ctl_q", queue_size(2),2,iobase()); // Step 1 - Initialize RX/TX queues auto success = assign_queue(0, rx_q.queue_desc()); CHECKSERT(success, "RX queue (%u) assigned (%p) to device", rx_q.size(), rx_q.queue_desc()); success = assign_queue(1, tx_q.queue_desc()); CHECKSERT(success, "TX queue (%u) assigned (%p) to device", tx_q.size(), tx_q.queue_desc()); // Step 2 - Initialize Ctrl-queue if it exists if (features() & (1 << VIRTIO_NET_F_CTRL_VQ)) { success = assign_queue(2, tx_q.queue_desc()); CHECKSERT(success, "CTRL queue (%u) assigned (%p) to device", ctrl_q.size(), ctrl_q.queue_desc()); } // Step 3 - Fill receive queue with buffers // DEBUG: Disable INFO("VirtioNet", "Adding %u receive buffers of size %u", rx_q.size() / 2, (uint32_t) bufstore().bufsize()); for (int i = 0; i < rx_q.size() / 2; i++) { auto buf = bufstore().get_buffer(); assert(bufstore().is_from_pool(buf.addr)); add_receive_buffer(buf.addr); } // Step 4 - If there are many queues, we should negotiate the number. // Set config length, based on whether there are multiple queues if (features() & (1 << VIRTIO_NET_F_MQ)) _config_length = sizeof(config); else _config_length = sizeof(config) - sizeof(uint16_t); // @todo: Specify how many queues we're going to use. // Step 5 - get the mac address (we're demanding this feature) // Step 6 - get the status - demanding this as well. // Getting the MAC + status get_config(); CHECK(_conf.mac.major > 0, "Valid Mac address: %s", _conf.mac.str().c_str()); // Step 7 - 9 - GSO: @todo Not using GSO features yet. // Signal setup complete. setup_complete((features() & needed_features) == needed_features); CHECK((features() & needed_features) == needed_features, "Signalled driver OK"); // Hook up interrupts if (has_msix()) { assert(get_msix_vectors() >= 3); auto& irqs = this->get_irqs(); // update BSP IDT IRQ_manager::get().subscribe(irqs[0], {this, &VirtioNet::msix_recv_handler}); IRQ_manager::get().subscribe(irqs[1], {this, &VirtioNet::msix_xmit_handler}); IRQ_manager::get().subscribe(irqs[2], {this, &VirtioNet::msix_conf_handler}); } else { auto irq = Virtio::get_legacy_irq(); IRQ_manager::get().subscribe(irq, {this, &VirtioNet::legacy_handler}); } #ifndef NO_DEFERRED_KICK static bool init_deferred = false; if (!init_deferred) { init_deferred = true; auto defirq = IRQ_manager::get().get_free_irq(); PER_CPU(deferred_devs).irq = defirq; IRQ_manager::get().subscribe(defirq, handle_deferred_devices); } #endif CHECK(this->link_up(), "Link up"); // Done if (this->link_up()) { rx_q.kick(); } } bool VirtioNet::link_up() const noexcept { return _conf.status & 1; } void VirtioNet::msix_conf_handler() { VDBG("\t <VirtioNet> Configuration change:\n"); // Getting the MAC + status VDBG("\t Old status: 0x%x\n",_conf.status); get_config(); VDBG("\t New status: 0x%x \n",_conf.status); } void VirtioNet::msix_recv_handler() { int dequeued_rx = 0; rx_q.disable_interrupts(); // handle incoming packets as long as bufstore has available buffers while (rx_q.new_incoming()) { auto res = rx_q.dequeue(); VDBG_RX("[virtionet] Recv %u bytes\n", (uint32_t) res.size()); Link::receive( recv_packet(res.data(), res.size()) ); dequeued_rx++; // Requeue a new buffer add_receive_buffer(bufstore().get_buffer().addr); // Stat increase packets received packets_rx_++; } rx_q.enable_interrupts(); if (dequeued_rx) rx_q.kick(); } void VirtioNet::msix_xmit_handler() { int dequeued_tx = 0; tx_q.disable_interrupts(); // Do one TX-packet while (tx_q.new_incoming()) { auto res = tx_q.dequeue(); // get packet offset, and call destructor auto* packet = (net::Packet*) (res.data() - sizeof(net::Packet)); delete packet; // call deleter on Packet to release it dequeued_tx++; } // If we have a transmit queue, eat from it, otherwise let the stack know we // have increased transmit capacity if (dequeued_tx > 0) { VDBG_TX("[virtionet] %d transmitted, tx_q is %p\n", dequeued_tx, transmit_queue_.get()); // transmit as much as possible from the buffer if (transmit_queue_) { transmit(std::move(transmit_queue_)); } // If we now emptied the buffer, offer packets to stack if (!transmit_queue_ && tx_q.num_free() > 1) transmit_queue_available_event_(tx_q.num_free() / 2); } } void VirtioNet::legacy_handler() { msix_recv_handler(); msix_xmit_handler(); } void VirtioNet::add_receive_buffer(uint8_t* pkt) { assert(pkt >= (uint8_t*) 0x1000); // offset pointer to virtionet header auto* vnet = pkt + sizeof(Packet); Token token1 {{vnet, sizeof(virtio_net_hdr)}, Token::IN }; Token token2 {{vnet + sizeof(virtio_net_hdr), packet_len()}, Token::IN }; std::array<Token, 2> tokens {{ token1, token2 }}; rx_q.enqueue(tokens); } net::Packet_ptr VirtioNet::recv_packet(uint8_t* data, uint16_t size) { auto* ptr = (net::Packet*) (data - sizeof(net::Packet)); new (ptr) net::Packet( sizeof(virtio_net_hdr), size - sizeof(virtio_net_hdr), sizeof(virtio_net_hdr) + packet_len(), &bufstore()); return net::Packet_ptr(ptr); } net::Packet_ptr VirtioNet::create_packet(int link_offset) { auto buffer = bufstore().get_buffer(); auto* ptr = (net::Packet*) buffer.addr; new (ptr) net::Packet( sizeof(virtio_net_hdr) + link_offset, 0, sizeof(virtio_net_hdr) + packet_len(), buffer.bufstore); return net::Packet_ptr(ptr); } void VirtioNet::add_to_tx_buffer(net::Packet_ptr pckt){ if (transmit_queue_) transmit_queue_->chain(std::move(pckt)); else transmit_queue_ = std::move(pckt); #ifdef VNET_DEBUG int chain_length = 1; auto* next = transmit_queue_->tail(); while (next) { chain_length++; next = next->tail(); } VDBG_TX("Buffering, %d packets chained\n", chain_length); #endif } void VirtioNet::transmit(net::Packet_ptr pckt) { /** @note We have to send a virtio header first, then the packet. From Virtio std. §5.1.6.6: "When using legacy interfaces, transitional drivers which have not negotiated VIRTIO_F_ANY_LAYOUT MUST use a single descriptor for the struct virtio_net_hdr on both transmit and receive, with the network data in the following descriptors." VirtualBox *does not* accept ANY_LAYOUT, while Qemu does, so this is to support VirtualBox */ int transmitted = 0; net::Packet_ptr tail = std::move(pckt); // Transmit all we can directly while (tx_q.num_free() and tail != nullptr) { VDBG_TX("[virtionet] tx: %u tokens left in TX queue \n", tx_q.num_free()); // next in line auto next = tail->detach_tail(); // write data to network // explicitly release the data to prevent destructor being called enqueue(tail.release()); tail = std::move(next); transmitted++; // Stat increase packets transmitted packets_tx_++; } if (LIKELY(transmitted)) { #ifdef NO_DEFERRED_KICK tx_q.enable_interrupts(); tx_q.kick(); #else begin_deferred_kick(); #endif } // Buffer the rest if (UNLIKELY(tail)) { VDBG_TX("[virtionet] tx: Buffering remaining tail..\n"); add_to_tx_buffer(std::move(tail)); } } void VirtioNet::enqueue(net::Packet* pckt) { Expects(pckt->layer_begin() == pckt->buf() + sizeof(virtio_net_hdr)); auto* hdr = pckt->buf(); VDBG_TX("[virtionet] tx: Transmit %u bytes\n", (uint32_t) pckt->size()); Token token1 {{ hdr, sizeof(virtio_net_hdr)}, Token::OUT }; Token token2 {{ pckt->layer_begin(), pckt->size()}, Token::OUT }; std::array<Token, 2> tokens {{ token1, token2 }}; // Enqueue scatterlist, 2 pieces readable, 0 writable. tx_q.enqueue(tokens); } void VirtioNet::begin_deferred_kick() { #ifndef NO_DEFERRED_KICK if (!deferred_kick) { deferred_kick = true; PER_CPU(deferred_devs).devs.push_back(this); IRQ_manager::get().register_irq(PER_CPU(deferred_devs).irq); } #endif } void VirtioNet::handle_deferred_devices() { #ifndef NO_DEFERRED_KICK for (auto* dev : PER_CPU(deferred_devs).devs) if (dev->deferred_kick) { dev->deferred_kick = false; // kick transmitq dev->tx_q.enable_interrupts(); dev->tx_q.kick(); } PER_CPU(deferred_devs).devs.clear(); #endif } void VirtioNet::deactivate() { VDBG("[virtionet] Disabling device\n"); /// disable interrupts on virtio queues rx_q.disable_interrupts(); tx_q.disable_interrupts(); ctrl_q.disable_interrupts(); /// mask off MSI-X vectors if (has_msix()) deactivate_msix(); } void VirtioNet::move_to_this_cpu() { INFO("VirtioNet", "Moving to CPU %d", SMP::cpu_id()); // update CPU id in bufferstore bufstore().move_to_this_cpu(); // virtio IRQ balancing this->Virtio::move_to_this_cpu(); // reset the IRQ handlers on this CPU auto& irqs = this->Virtio::get_irqs(); IRQ_manager::get().subscribe(irqs[0], {this, &VirtioNet::msix_recv_handler}); IRQ_manager::get().subscribe(irqs[1], {this, &VirtioNet::msix_xmit_handler}); IRQ_manager::get().subscribe(irqs[2], {this, &VirtioNet::msix_conf_handler}); #ifndef NO_DEFERRED_KICK // update deferred kick IRQ auto defirq = IRQ_manager::get().get_free_irq(); PER_CPU(deferred_devs).irq = defirq; IRQ_manager::get().subscribe(defirq, handle_deferred_devices); #endif } #include <kernel/pci_manager.hpp> /** Register VirtioNet's driver factory at the PCI_manager */ __attribute__((constructor)) void autoreg_virtionet() { PCI_manager::register_nic(PCI::VENDOR_VIRTIO, 0x1000, &VirtioNet::new_instance); } virtionet: Zero driver header before transmit() // This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //#define VNET_DEBUG //#define VNET_DEBUG_RX //#define VNET_DEBUG_TX #ifdef VNET_DEBUG #define VDBG(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define VDBG(fmt, ...) /* fmt */ #endif #ifdef VNET_DEBUG_RX #define VDBG_RX(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define VDBG_RX(fmt, ...) /* fmt */ #endif #ifdef VNET_DEBUG_TX #define VDBG_TX(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define VDBG_TX(fmt, ...) /* fmt */ #endif #include "virtionet.hpp" #include <kernel/irq_manager.hpp> #include <malloc.h> #include <cstring> //#define NO_DEFERRED_KICK #ifndef NO_DEFERRED_KICK #include <smp> struct alignas(SMP_ALIGN) smp_deferred_kick { std::vector<VirtioNet*> devs; uint8_t irq; }; static std::array<smp_deferred_kick, SMP_MAX_CORES> deferred_devs; #endif using namespace net; void VirtioNet::get_config() { Virtio::get_config(&_conf, _config_length); } VirtioNet::VirtioNet(hw::PCI_Device& d) : Virtio(d), Link(Link_protocol{{this, &VirtioNet::transmit}, mac()}, 256u, 2048 /* 256x half-page buffers */), packets_rx_{Statman::get().create(Stat::UINT64, device_name() + ".packets_rx").get_uint64()}, packets_tx_{Statman::get().create(Stat::UINT64, device_name() + ".packets_tx").get_uint64()} { INFO("VirtioNet", "Driver initializing"); uint32_t needed_features = 0 | (1 << VIRTIO_NET_F_MAC) | (1 << VIRTIO_NET_F_STATUS) ;//| (1 << VIRTIO_NET_F_MRG_RXBUF); //Merge RX Buffers (Everything i 1 buffer) uint32_t wanted_features = needed_features; negotiate_features(wanted_features); CHECK ((features() & needed_features) == needed_features, "Negotiated needed features"); CHECK ((features() & wanted_features) == wanted_features, "Negotiated wanted features"); CHECK(features() & (1 << VIRTIO_NET_F_CSUM), "Device handles packets w. partial checksum"); CHECK(features() & (1 << VIRTIO_NET_F_GUEST_CSUM), "Guest handles packets w. partial checksum"); CHECK(features() & (1 << VIRTIO_NET_F_CTRL_VQ), "There's a control queue"); CHECK(features() & (1 << VIRTIO_F_ANY_LAYOUT), "Queue can handle any header/data layout"); CHECK(features() & (1 << VIRTIO_F_RING_INDIRECT_DESC), "We can use indirect descriptors"); CHECK(features() & (1 << VIRTIO_F_RING_EVENT_IDX), "There's a Ring Event Index to use"); CHECK(features() & (1 << VIRTIO_NET_F_MQ), "There are multiple queue pairs"); if (features() & (1 << VIRTIO_NET_F_MQ)) printf("\t\t* max_virtqueue_pairs: 0x%x \n",_conf.max_virtq_pairs); CHECK(features() & (1 << VIRTIO_NET_F_MRG_RXBUF), "Merge RX buffers"); /** RX que is 0, TX Queue is 1 - Virtio Std. §5.1.2 */ new (&rx_q) Virtio::Queue(device_name() + ".rx_q", queue_size(0),0,iobase()); new (&tx_q) Virtio::Queue(device_name() + ".tx_q", queue_size(1),1,iobase()); new (&ctrl_q) Virtio::Queue(device_name() + ".ctl_q", queue_size(2),2,iobase()); // Step 1 - Initialize RX/TX queues auto success = assign_queue(0, rx_q.queue_desc()); CHECKSERT(success, "RX queue (%u) assigned (%p) to device", rx_q.size(), rx_q.queue_desc()); success = assign_queue(1, tx_q.queue_desc()); CHECKSERT(success, "TX queue (%u) assigned (%p) to device", tx_q.size(), tx_q.queue_desc()); // Step 2 - Initialize Ctrl-queue if it exists if (features() & (1 << VIRTIO_NET_F_CTRL_VQ)) { success = assign_queue(2, tx_q.queue_desc()); CHECKSERT(success, "CTRL queue (%u) assigned (%p) to device", ctrl_q.size(), ctrl_q.queue_desc()); } // Step 3 - Fill receive queue with buffers // DEBUG: Disable INFO("VirtioNet", "Adding %u receive buffers of size %u", rx_q.size() / 2, (uint32_t) bufstore().bufsize()); for (int i = 0; i < rx_q.size() / 2; i++) { auto buf = bufstore().get_buffer(); assert(bufstore().is_from_pool(buf.addr)); add_receive_buffer(buf.addr); } // Step 4 - If there are many queues, we should negotiate the number. // Set config length, based on whether there are multiple queues if (features() & (1 << VIRTIO_NET_F_MQ)) _config_length = sizeof(config); else _config_length = sizeof(config) - sizeof(uint16_t); // @todo: Specify how many queues we're going to use. // Step 5 - get the mac address (we're demanding this feature) // Step 6 - get the status - demanding this as well. // Getting the MAC + status get_config(); CHECK(_conf.mac.major > 0, "Valid Mac address: %s", _conf.mac.str().c_str()); // Step 7 - 9 - GSO: @todo Not using GSO features yet. // Signal setup complete. setup_complete((features() & needed_features) == needed_features); CHECK((features() & needed_features) == needed_features, "Signalled driver OK"); // Hook up interrupts if (has_msix()) { assert(get_msix_vectors() >= 3); auto& irqs = this->get_irqs(); // update BSP IDT IRQ_manager::get().subscribe(irqs[0], {this, &VirtioNet::msix_recv_handler}); IRQ_manager::get().subscribe(irqs[1], {this, &VirtioNet::msix_xmit_handler}); IRQ_manager::get().subscribe(irqs[2], {this, &VirtioNet::msix_conf_handler}); } else { auto irq = Virtio::get_legacy_irq(); IRQ_manager::get().subscribe(irq, {this, &VirtioNet::legacy_handler}); } #ifndef NO_DEFERRED_KICK static bool init_deferred = false; if (!init_deferred) { init_deferred = true; auto defirq = IRQ_manager::get().get_free_irq(); PER_CPU(deferred_devs).irq = defirq; IRQ_manager::get().subscribe(defirq, handle_deferred_devices); } #endif CHECK(this->link_up(), "Link up"); // Done if (this->link_up()) { rx_q.kick(); } } bool VirtioNet::link_up() const noexcept { return _conf.status & 1; } void VirtioNet::msix_conf_handler() { VDBG("\t <VirtioNet> Configuration change:\n"); // Getting the MAC + status VDBG("\t Old status: 0x%x\n",_conf.status); get_config(); VDBG("\t New status: 0x%x \n",_conf.status); } void VirtioNet::msix_recv_handler() { int dequeued_rx = 0; rx_q.disable_interrupts(); // handle incoming packets as long as bufstore has available buffers while (rx_q.new_incoming()) { auto res = rx_q.dequeue(); VDBG_RX("[virtionet] Recv %u bytes\n", (uint32_t) res.size()); Link::receive( recv_packet(res.data(), res.size()) ); dequeued_rx++; // Requeue a new buffer add_receive_buffer(bufstore().get_buffer().addr); // Stat increase packets received packets_rx_++; } rx_q.enable_interrupts(); if (dequeued_rx) rx_q.kick(); } void VirtioNet::msix_xmit_handler() { int dequeued_tx = 0; tx_q.disable_interrupts(); // Do one TX-packet while (tx_q.new_incoming()) { auto res = tx_q.dequeue(); // get packet offset, and call destructor auto* packet = (net::Packet*) (res.data() - sizeof(net::Packet)); delete packet; // call deleter on Packet to release it dequeued_tx++; } // If we have a transmit queue, eat from it, otherwise let the stack know we // have increased transmit capacity if (dequeued_tx > 0) { VDBG_TX("[virtionet] %d transmitted, tx_q is %p\n", dequeued_tx, transmit_queue_.get()); // transmit as much as possible from the buffer if (transmit_queue_) { transmit(std::move(transmit_queue_)); } // If we now emptied the buffer, offer packets to stack if (!transmit_queue_ && tx_q.num_free() > 1) transmit_queue_available_event_(tx_q.num_free() / 2); } } void VirtioNet::legacy_handler() { msix_recv_handler(); msix_xmit_handler(); } void VirtioNet::add_receive_buffer(uint8_t* pkt) { assert(pkt >= (uint8_t*) 0x1000); // offset pointer to virtionet header auto* vnet = pkt + sizeof(Packet); Token token1 {{vnet, sizeof(virtio_net_hdr)}, Token::IN }; Token token2 {{vnet + sizeof(virtio_net_hdr), packet_len()}, Token::IN }; std::array<Token, 2> tokens {{ token1, token2 }}; rx_q.enqueue(tokens); } net::Packet_ptr VirtioNet::recv_packet(uint8_t* data, uint16_t size) { auto* ptr = (net::Packet*) (data - sizeof(net::Packet)); new (ptr) net::Packet( sizeof(virtio_net_hdr), size - sizeof(virtio_net_hdr), sizeof(virtio_net_hdr) + packet_len(), &bufstore()); return net::Packet_ptr(ptr); } net::Packet_ptr VirtioNet::create_packet(int link_offset) { auto buffer = bufstore().get_buffer(); auto* ptr = (net::Packet*) buffer.addr; new (ptr) net::Packet( sizeof(virtio_net_hdr) + link_offset, 0, sizeof(virtio_net_hdr) + packet_len(), buffer.bufstore); return net::Packet_ptr(ptr); } void VirtioNet::add_to_tx_buffer(net::Packet_ptr pckt){ if (transmit_queue_) transmit_queue_->chain(std::move(pckt)); else transmit_queue_ = std::move(pckt); #ifdef VNET_DEBUG int chain_length = 1; auto* next = transmit_queue_->tail(); while (next) { chain_length++; next = next->tail(); } VDBG_TX("Buffering, %d packets chained\n", chain_length); #endif } void VirtioNet::transmit(net::Packet_ptr pckt) { /** @note We have to send a virtio header first, then the packet. From Virtio std. §5.1.6.6: "When using legacy interfaces, transitional drivers which have not negotiated VIRTIO_F_ANY_LAYOUT MUST use a single descriptor for the struct virtio_net_hdr on both transmit and receive, with the network data in the following descriptors." VirtualBox *does not* accept ANY_LAYOUT, while Qemu does, so this is to support VirtualBox */ int transmitted = 0; net::Packet_ptr tail = std::move(pckt); // Transmit all we can directly while (tx_q.num_free() and tail != nullptr) { VDBG_TX("[virtionet] tx: %u tokens left in TX queue \n", tx_q.num_free()); // next in line auto next = tail->detach_tail(); // write data to network // explicitly release the data to prevent destructor being called enqueue(tail.release()); tail = std::move(next); transmitted++; // Stat increase packets transmitted packets_tx_++; } if (LIKELY(transmitted)) { #ifdef NO_DEFERRED_KICK tx_q.enable_interrupts(); tx_q.kick(); #else begin_deferred_kick(); #endif } // Buffer the rest if (UNLIKELY(tail)) { VDBG_TX("[virtionet] tx: Buffering remaining tail..\n"); add_to_tx_buffer(std::move(tail)); } } void VirtioNet::enqueue(net::Packet* pckt) { Expects(pckt->layer_begin() == pckt->buf() + sizeof(virtio_net_hdr)); auto* hdr = pckt->buf(); memset(hdr, 0, sizeof(virtio_net_hdr)); VDBG_TX("[virtionet] tx: Transmit %u bytes\n", (uint32_t) pckt->size()); Token token1 {{ hdr, sizeof(virtio_net_hdr)}, Token::OUT }; Token token2 {{ pckt->layer_begin(), pckt->size()}, Token::OUT }; std::array<Token, 2> tokens {{ token1, token2 }}; // Enqueue scatterlist, 2 pieces readable, 0 writable. tx_q.enqueue(tokens); } void VirtioNet::begin_deferred_kick() { #ifndef NO_DEFERRED_KICK if (!deferred_kick) { deferred_kick = true; PER_CPU(deferred_devs).devs.push_back(this); IRQ_manager::get().register_irq(PER_CPU(deferred_devs).irq); } #endif } void VirtioNet::handle_deferred_devices() { #ifndef NO_DEFERRED_KICK for (auto* dev : PER_CPU(deferred_devs).devs) if (dev->deferred_kick) { dev->deferred_kick = false; // kick transmitq dev->tx_q.enable_interrupts(); dev->tx_q.kick(); } PER_CPU(deferred_devs).devs.clear(); #endif } void VirtioNet::deactivate() { VDBG("[virtionet] Disabling device\n"); /// disable interrupts on virtio queues rx_q.disable_interrupts(); tx_q.disable_interrupts(); ctrl_q.disable_interrupts(); /// mask off MSI-X vectors if (has_msix()) deactivate_msix(); } void VirtioNet::move_to_this_cpu() { INFO("VirtioNet", "Moving to CPU %d", SMP::cpu_id()); // update CPU id in bufferstore bufstore().move_to_this_cpu(); // virtio IRQ balancing this->Virtio::move_to_this_cpu(); // reset the IRQ handlers on this CPU auto& irqs = this->Virtio::get_irqs(); IRQ_manager::get().subscribe(irqs[0], {this, &VirtioNet::msix_recv_handler}); IRQ_manager::get().subscribe(irqs[1], {this, &VirtioNet::msix_xmit_handler}); IRQ_manager::get().subscribe(irqs[2], {this, &VirtioNet::msix_conf_handler}); #ifndef NO_DEFERRED_KICK // update deferred kick IRQ auto defirq = IRQ_manager::get().get_free_irq(); PER_CPU(deferred_devs).irq = defirq; IRQ_manager::get().subscribe(defirq, handle_deferred_devices); #endif } #include <kernel/pci_manager.hpp> /** Register VirtioNet's driver factory at the PCI_manager */ __attribute__((constructor)) void autoreg_virtionet() { PCI_manager::register_nic(PCI::VENDOR_VIRTIO, 0x1000, &VirtioNet::new_instance); }
Revert 39450 - Disable 3 interactive tests for now. They started failing after the last WebKit roll. TEST=none BUG=36262 Review URL: http://codereview.chromium.org/651035 TBR=jorlow@chromium.org Review URL: http://codereview.chromium.org/650037 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@39454 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
/* * Copyright (c) 2011, Georgia Tech Research Corporation * All rights reserved. * * Author(s): Sehoon Ha <sehoon.ha@gmail.com> * Jeongseok Lee <jslee02@gmail.com> * Date: 05/14/2013 * * Geoorgia Tech Graphics Lab and Humanoid Robotics Lab * * Directed by Prof. C. Karen Liu and Prof. Mike Stilman * <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu> * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "dynamics/BodyNode.h" #include <algorithm> #include <iostream> #include <queue> #include <stack> #include <boost/math/special_functions/fpclassify.hpp> #include "common/Console.h" #include "math/Helpers.h" #include "renderer/RenderInterface.h" #include "dynamics/Joint.h" #include "dynamics/Shape.h" #include "dynamics/Skeleton.h" #include "dynamics/Marker.h" namespace dart { namespace dynamics { int BodyNode::msBodyNodeCount = 0; BodyNode::BodyNode(const std::string& _name) : mSkelIndex(-1), mName(_name), mIsCollidable(true), mIsColliding(false), mSkeleton(NULL), mParentJoint(NULL), mParentBodyNode(NULL), mChildBodyNodes(std::vector<BodyNode*>(0)), mGravityMode(true), mCenterOfMass(Eigen::Vector3d::Zero()), mMass(1.0), mIxx(1.0), mIyy(1.0), mIzz(1.0), mIxy(0.0), mIxz(0.0), mIyz(0.0), mI(Eigen::Matrix6d::Identity()), mW(Eigen::Isometry3d::Identity()), mV(Eigen::Vector6d::Zero()), mEta(Eigen::Vector6d::Zero()), mdV(Eigen::Vector6d::Zero()), mF(Eigen::Vector6d::Zero()), mFext(Eigen::Vector6d::Zero()), mFgravity(Eigen::Vector6d::Zero()), mAI(Eigen::Matrix6d::Identity()), mB(Eigen::Vector6d::Zero()), mBeta(Eigen::Vector6d::Zero()), mID(BodyNode::msBodyNodeCount++) { } BodyNode::~BodyNode() { for (std::vector<Shape*>::const_iterator it = mVizShapes.begin(); it != mVizShapes.end(); ++it) delete (*it); for (std::vector<Shape*>::const_iterator itColShape = mColShapes.begin(); itColShape != mColShapes.end(); ++itColShape) if (mVizShapes.end() == std::find(mVizShapes.begin(), mVizShapes.end(), *itColShape)) delete (*itColShape); for (std::vector<Marker*>::const_iterator it = mMarkers.begin(); it != mMarkers.end(); ++it) delete (*it); if (mParentJoint) delete mParentJoint; } void BodyNode::setName(const std::string& _name) { mName = _name; } const std::string& BodyNode::getName() const { return mName; } void BodyNode::setGravityMode(bool _gravityMode) { mGravityMode = _gravityMode; } bool BodyNode::getGravityMode() const { return mGravityMode; } bool BodyNode::isCollidable() const { return mIsCollidable; } void BodyNode::setCollidable(bool _isCollidable) { mIsCollidable = _isCollidable; } void BodyNode::setMass(double _mass) { assert(_mass >= 0.0 && "Negative mass is not allowable."); mMass = _mass; _updateGeralizedInertia(); } double BodyNode::getMass() const { return mMass; } BodyNode*BodyNode::getParentBodyNode() const { return mParentBodyNode; } void BodyNode::addChildBodyNode(BodyNode* _body) { assert(_body != NULL); mChildBodyNodes.push_back(_body); _body->mParentBodyNode = this; } BodyNode* BodyNode::getChildBodyNode(int _idx) const { assert(0 <= _idx && _idx < mChildBodyNodes.size()); return mChildBodyNodes[_idx]; } int BodyNode::getNumChildBodyNodes() const { return mChildBodyNodes.size(); } void BodyNode::addMarker(Marker* _marker) { mMarkers.push_back(_marker); } int BodyNode::getNumMarkers() const { return mMarkers.size(); } Marker* BodyNode::getMarker(int _idx) const { return mMarkers[_idx]; } bool BodyNode::dependsOn(int _genCoordIndex) const { return std::binary_search(mDependentGenCoordIndices.begin(), mDependentGenCoordIndices.end(), _genCoordIndex); } int BodyNode::getNumDependentGenCoords() const { return mDependentGenCoordIndices.size(); } int BodyNode::getDependentGenCoord(int _arrayIndex) const { assert(0 <= _arrayIndex && _arrayIndex < mDependentGenCoordIndices.size()); return mDependentGenCoordIndices[_arrayIndex]; } const Eigen::Isometry3d& BodyNode::getWorldTransform() const { return mW; } const Eigen::Vector6d& BodyNode::getBodyVelocity() const { return mV; } Eigen::Vector6d BodyNode::getWorldVelocity(const Eigen::Vector3d& _offset) const { Eigen::Isometry3d T = mW; T.translation() = -_offset; return math::AdT(T, mV); } const Eigen::Vector6d&BodyNode::getBodyAcceleration() const { return mdV; } Eigen::Vector6d BodyNode::getWorldAcceleration( const Eigen::Vector3d& _offset) const { Eigen::Isometry3d T = mW; T.translation() = -_offset; return math::AdT(T, mdV); } const math::Jacobian& BodyNode::getBodyJacobian() { if (mIsBodyJacobianDirty) _updateBodyJacobian(); return mBodyJacobian; } math::Jacobian BodyNode::getWorldJacobian(const Eigen::Vector3d& _offset) { Eigen::Isometry3d T = mW; T.translation() = -_offset; return math::AdTJac(T, getBodyJacobian()); } const math::Jacobian& BodyNode::getBodyJacobianTimeDeriv() const { return mBodyJacobianTimeDeriv; } math::Jacobian BodyNode::getWorldJacobianTimeDeriv( const Eigen::Vector3d& _offset) const { Eigen::Isometry3d T = mW; T.translation() = -_offset; return math::AdTJac(T, mBodyJacobianTimeDeriv); } void BodyNode::setColliding(bool _isColliding) { mIsColliding = _isColliding; } bool BodyNode::isColliding() { return mIsColliding; } void BodyNode::init(Skeleton* _skeleton, int _skeletonIndex) { assert(_skeleton); mSkeleton = _skeleton; mSkelIndex = _skeletonIndex; mParentJoint->mSkelIndex = _skeletonIndex; //-------------------------------------------------------------------------- // Fill the list of generalized coordinates this node depends on, and sort // it. //-------------------------------------------------------------------------- if (mParentBodyNode) mDependentGenCoordIndices = mParentBodyNode->mDependentGenCoordIndices; else mDependentGenCoordIndices.clear(); for (int i = 0; i < mParentJoint->getNumGenCoords(); i++) mDependentGenCoordIndices.push_back(mParentJoint->getGenCoord(i)->getSkeletonIndex()); std::sort(mDependentGenCoordIndices.begin(), mDependentGenCoordIndices.end()); #ifndef NDEBUG // Check whether there is duplicated indices. for (int i = 0; i < mDependentGenCoordIndices.size() - 1; i++) { for (int j = i + 1; j < mDependentGenCoordIndices.size(); j++) { assert(mDependentGenCoordIndices[i] != mDependentGenCoordIndices[j] && "Duplicated index is found in mDependentGenCoordIndices."); } } #endif //-------------------------------------------------------------------------- // Fill the list of decendants of this body node. //-------------------------------------------------------------------------- mDescendantBodyNodes.clear(); // A. DFS (Depth First Search). // std::stack<BodyNode*> stack; // for (std::vector<BodyNode*>::const_reverse_iterator it = // mChildBodyNodes.rbegin(); it != mChildBodyNodes.rend(); ++it) // { // stack.push(*it); // } // while (!stack.empty()) // { // BodyNode* itBodyNode = stack.top(); // stack.pop(); // mDescendantBodyNodes.push_back(itBodyNode); // for (int i = itBodyNode->getNumChildBodyNodes() - 1; i > -1 ; -i) // { // stack.push(itBodyNode->getChildBodyNode(i)); // } // } // B. BFS (Breadth First Search) std::queue<BodyNode*> queue; for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { queue.push(*it); } while (!queue.empty()) { BodyNode* itBodyNode = queue.front(); queue.pop(); mDescendantBodyNodes.push_back(itBodyNode); for (int i = 0; i < itBodyNode->getNumChildBodyNodes(); ++i) { queue.push(itBodyNode->getChildBodyNode(i)); } } //-------------------------------------------------------------------------- // Set dimensions of dynamics matrices and vectors. //-------------------------------------------------------------------------- int numDepGenCoords = getNumDependentGenCoords(); mBodyJacobian.setZero(6, numDepGenCoords); mBodyJacobianTimeDeriv.setZero(6, numDepGenCoords); //-------------------------------------------------------------------------- // Set dimensions of cache data for recursive algorithms //-------------------------------------------------------------------------- int dof = mParentJoint->getNumGenCoords(); mAI_S.setZero(6, dof); mPsi.setZero(dof, dof); mPsiK.setZero(dof, dof); mAlpha.setZero(dof); } void BodyNode::draw(renderer::RenderInterface* _ri, const Eigen::Vector4d& _color, bool _useDefaultColor, int _depth) const { if (_ri == NULL) return; _ri->pushMatrix(); // render the self geometry mParentJoint->applyGLTransform(_ri); _ri->pushName((unsigned)mID); for(int i = 0; i < mVizShapes.size(); i++) { _ri->pushMatrix(); mVizShapes[i]->draw(_ri, _color, _useDefaultColor); _ri->popMatrix(); } _ri->popName(); // render the subtree for (unsigned int i = 0; i < mChildBodyNodes.size(); i++) { mChildBodyNodes[i]->draw(_ri, _color, _useDefaultColor); } _ri->popMatrix(); } void BodyNode::drawMarkers(renderer::RenderInterface* _ri, const Eigen::Vector4d& _color, bool _useDefaultColor) const { if (!_ri) return; _ri->pushMatrix(); mParentJoint->applyGLTransform(_ri); // render the corresponding mMarkerss for (unsigned int i = 0; i < mMarkers.size(); i++) mMarkers[i]->draw(_ri, true, _color, _useDefaultColor); for (unsigned int i = 0; i < mChildBodyNodes.size(); i++) mChildBodyNodes[i]->drawMarkers(_ri,_color, _useDefaultColor); _ri->popMatrix(); } void BodyNode::updateTransform() { mParentJoint->updateTransform(); if (mParentBodyNode) { mW = mParentBodyNode->getWorldTransform() * mParentJoint->getLocalTransform(); } else { mW = mParentJoint->getLocalTransform(); } assert(math::verifyTransform(mW)); mParentJoint->updateJacobian(); } void BodyNode::updateVelocity() { //-------------------------------------------------------------------------- // Body velocity update // // V(i) = Ad(T(i, i-1), V(i-1)) + S * dq //-------------------------------------------------------------------------- if (mParentJoint->getNumGenCoords() > 0) { mV.noalias() = mParentJoint->getLocalJacobian() * mParentJoint->get_dq(); if (mParentBodyNode) { mV += math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->getBodyVelocity()); } } assert(!math::isNan(mV)); } void BodyNode::updateEta(bool _updateJacobianDeriv) { mParentJoint->updateJacobianTimeDeriv(); if (mParentJoint->getNumGenCoords() > 0) { mEta = math::ad(mV, mParentJoint->getLocalJacobian() * mParentJoint->get_dq()); mEta.noalias() += mParentJoint->getLocalJacobianTimeDeriv() * mParentJoint->get_dq(); assert(!math::isNan(mEta)); } if (_updateJacobianDeriv == false) return; //-------------------------------------------------------------------------- // Jacobian first derivative update // // dJ = | dJ1 dJ2 ... dJn | // = | Ad(T(i,i-1), dJ_parent) dJ_local | // // dJ_parent: (6 x parentDOF) // dJ_local: (6 x localDOF) // dJi: (6 x 1) se3 // n: number of dependent coordinates //-------------------------------------------------------------------------- const int numLocalDOFs = mParentJoint->getNumGenCoords(); const int numParentDOFs = getNumDependentGenCoords() - numLocalDOFs; // Parent Jacobian if (mParentBodyNode) { assert(mParentBodyNode->mBodyJacobianTimeDeriv.cols() + mParentJoint->getNumGenCoords() == mBodyJacobianTimeDeriv.cols()); assert(mParentJoint); mBodyJacobianTimeDeriv.leftCols(numParentDOFs) = math::AdInvTJac(mParentJoint->getLocalTransform(), mParentBodyNode->mBodyJacobianTimeDeriv); } // Local Jacobian mBodyJacobianTimeDeriv.rightCols(numLocalDOFs) = mParentJoint->getLocalJacobianTimeDeriv(); } void BodyNode::updateAcceleration() { // dV(i) = Ad(T(i, i-1), dV(i-1)) // + ad(V(i), S * dq) + dS * dq // + S * ddq // = Ad(T(i, i-1), dV(i-1)) // + eta // + S * ddq if (mParentJoint->getNumGenCoords() > 0) { mdV = mEta; mdV.noalias() += mParentJoint->getLocalJacobian() * mParentJoint->get_ddq(); if (mParentBodyNode) { mdV = math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->getBodyAcceleration()); } } assert(!math::isNan(mdV)); } void BodyNode::setInertia(double _Ixx, double _Iyy, double _Izz, double _Ixy, double _Ixz, double _Iyz) { assert(_Ixx >= 0.0); assert(_Iyy >= 0.0); assert(_Izz >= 0.0); mIxx = _Ixx; mIyy = _Iyy; mIzz = _Izz; mIxy = _Ixy; mIxz = _Ixz; mIyz = _Iyz; _updateGeralizedInertia(); } void BodyNode::setLocalCOM(const Eigen::Vector3d& _com) { mCenterOfMass = _com; _updateGeralizedInertia(); } const Eigen::Vector3d& BodyNode::getLocalCOM() const { return mCenterOfMass; } Eigen::Vector3d BodyNode::getWorldCOM() const { return mW.linear() * mCenterOfMass; } Eigen::Matrix6d BodyNode::getInertia() const { return mI; } int BodyNode::getSkeletonIndex() const { return mSkelIndex; } void BodyNode::addVisualizationShape(Shape* _p) { mVizShapes.push_back(_p); } int BodyNode::getNumVisualizationShapes() const { return mVizShapes.size(); } Shape*BodyNode::getVisualizationShape(int _idx) const { return mVizShapes[_idx]; } void BodyNode::addCollisionShape(Shape* _p) { mColShapes.push_back(_p); } int BodyNode::getNumCollisionShapes() const { return mColShapes.size(); } Shape*BodyNode::getCollisionShape(int _idx) const { return mColShapes[_idx]; } Skeleton*BodyNode::getSkeleton() const { return mSkeleton; } void BodyNode::setParentJoint(Joint* _joint) { mParentJoint = _joint; } Joint*BodyNode::getParentJoint() const { return mParentJoint; } void BodyNode::addExtForce(const Eigen::Vector3d& _force, const Eigen::Vector3d& _offset, bool _isOffsetLocal, bool _isForceLocal) { Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); Eigen::Vector6d F = Eigen::Vector6d::Zero(); if (_isOffsetLocal) T.translation() = _offset; else T.translation() = getWorldTransform().inverse() * _offset; if (_isForceLocal) F.tail<3>() = _force; else F.tail<3>() = mW.linear().transpose() * _force; mFext += math::dAdInvT(T, F); } void BodyNode::setExtForce(const Eigen::Vector3d& _force, const Eigen::Vector3d& _offset, bool _isOffsetLocal, bool _isForceLocal) { Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); Eigen::Vector6d F = Eigen::Vector6d::Zero(); if (_isOffsetLocal) T.translation() = _offset; else T.translation() = getWorldTransform().inverse() * _offset; if (_isForceLocal) F.tail<3>() = _force; else F.tail<3>() = mW.linear().transpose() * _force; mFext = math::dAdInvT(T, F); } void BodyNode::addExtTorque(const Eigen::Vector3d& _torque, bool _isLocal) { if (_isLocal) mFext.head<3>() += _torque; else mFext.head<3>() += mW.linear() * _torque; } void BodyNode::setExtTorque(const Eigen::Vector3d& _torque, bool _isLocal) { if (_isLocal) mFext.head<3>() = _torque; else mFext.head<3>() = mW.linear() * _torque; } const Eigen::Vector6d& BodyNode::getExternalForceLocal() const { return mFext; } Eigen::Vector6d BodyNode::getExternalForceGlobal() const { return math::dAdInvT(mW, mFext); } void BodyNode::addContactForce(const Eigen::Vector6d& _contactForce) { mContactForces.push_back(_contactForce); } int BodyNode::getNumContactForces() const { return mContactForces.size(); } const Eigen::Vector6d& BodyNode::getContactForce(int _idx) { assert(0 <= _idx && _idx < mContactForces.size()); return mContactForces[_idx]; } void BodyNode::clearContactForces() { mContactForces.clear(); } const Eigen::Vector6d& BodyNode::getBodyForce() const { return mF; } double BodyNode::getKineticEnergy() const { return 0.5 * mV.dot(mI * mV); } Eigen::Vector3d BodyNode::getLinearMomentum() const { return (mI * mV).tail<3>(); } Eigen::Vector3d BodyNode::getAngularMomentum(const Eigen::Vector3d& _pivot) { Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); T.translation() = _pivot; return math::dAdT(T, mI * mV).head<3>(); } void BodyNode::updateBodyForce(const Eigen::Vector3d& _gravity, bool _withExternalForces) { if (mGravityMode == true) mFgravity.noalias() = mI * math::AdInvRLinear(mW, _gravity); else mFgravity.setZero(); mF.noalias() = mI * mdV; // Inertial force if (_withExternalForces) mF -= mFext; // External force mF -= mFgravity; // Gravity force mF -= math::dad(mV, mI * mV); // Coriolis force for (std::vector<BodyNode*>::iterator iChildBody = mChildBodyNodes.begin(); iChildBody != mChildBodyNodes.end(); ++iChildBody) { Joint* childJoint = (*iChildBody)->getParentJoint(); assert(childJoint != NULL); mF += math::dAdInvT(childJoint->getLocalTransform(), (*iChildBody)->getBodyForce()); } assert(!math::isNan(mF)); } void BodyNode::updateGeneralizedForce(bool _withDampingForces) { assert(mParentJoint != NULL); const math::Jacobian& J = mParentJoint->getLocalJacobian(); // if (_withDampingForces) // mF -= mFDamp; assert(!math::isNan(J.transpose()*mF)); mParentJoint->set_tau(J.transpose()*mF); } void BodyNode::updateArticulatedInertia(double _timeStep) { assert(mParentJoint != NULL); // Articulated inertia mAI = mI; Eigen::Matrix6d tmpAdInv; for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mAI += math::transformInertia( (*it)->getParentJoint()->getLocalTransform().inverse(), (*it)->mPi); } assert(!math::isNan(mAI)); // Cache data: PsiK and Psi mAI_S.noalias() = mAI * mParentJoint->getLocalJacobian(); int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { Eigen::MatrixXd K = Eigen::MatrixXd::Zero(dof, dof); for (int i = 0; i < dof; ++i) K(i, i) = mParentJoint->getDampingCoefficient(i); Eigen::MatrixXd omega = mParentJoint->getLocalJacobian().transpose() * mAI_S; #ifndef NDEBUG Eigen::FullPivLU<Eigen::MatrixXd> omegaKLU(omega + _timeStep * K); Eigen::FullPivLU<Eigen::MatrixXd> omegaLU(omega); assert(omegaKLU.isInvertible()); assert(omegaLU.isInvertible()); #endif // mPsiK = (omega + _timeStep * K).inverse(); mPsiK = (omega + _timeStep * K).ldlt().solve( Eigen::MatrixXd::Identity(dof, dof)); // mPsi = (omega).inverse(); mPsi = (omega).ldlt().solve(Eigen::MatrixXd::Identity(dof, dof)); } assert(!math::isNan(mPsiK)); assert(!math::isNan(mPsi)); // Cache data: AI_S_Psi mAI_S_Psi = mAI_S * mPsi; // Cache data: Pi mPi = mAI; if (dof > 0) mPi.noalias() -= mAI_S*mPsiK*mAI_S.transpose(); assert(!math::isNan(mPi)); } void BodyNode::updateBiasForce(const Eigen::Vector3d& _gravity) { // Bias force if (mGravityMode == true) mFgravity.noalias() = mI * math::AdInvRLinear(mW, _gravity); else mFgravity.setZero(); mB = -math::dad(mV, mI*mV) - mFext - mFgravity; assert(!math::isNan(mB)); for (int i = 0; i < mContactForces.size(); ++i) mB -= mContactForces[i]; assert(!math::isNan(mB)); for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mB += math::dAdInvT((*it)->getParentJoint()->getLocalTransform(), (*it)->mBeta); } assert(!math::isNan(mB)); // Cache data: alpha int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { mAlpha = mParentJoint->get_tau() + mParentJoint->getDampingForces(); for (int i = 0; i < dof; i++) mAlpha(i) += mSkeleton->getConstraintForceVector()[mParentJoint->getGenCoord(i)->getSkeletonIndex()]; //mAlpha.noalias() -= mParentJoint->getLocalJacobian().transpose()*(mAI*mEta + mB); mAlpha.noalias() -= mAI_S.transpose() * mEta; mAlpha.noalias() -= mParentJoint->getLocalJacobian().transpose() * mB; assert(!math::isNan(mAlpha)); } // Cache data: beta mBeta = mB; mBeta.noalias() += mAI*mEta; if (dof > 0) { mBeta.noalias() += mAI_S * mPsiK * mAlpha; } assert(!math::isNan(mBeta)); } void BodyNode::update_ddq() { if (mParentJoint->getNumGenCoords() == 0) return; Eigen::VectorXd ddq; if (mParentBodyNode) { ddq.noalias() = mPsiK * (mAlpha - mAI_S.transpose() * math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->getBodyAcceleration())); } else { ddq.noalias() = mPsiK * mAlpha; } mParentJoint->set_ddq(ddq); assert(!math::isNan(ddq)); } void BodyNode::update_F_fs() { mF = mB; mF.noalias() = mAI * mdV; assert(!math::isNan(mF)); } void BodyNode::aggregateCoriolisForceVector(Eigen::VectorXd& _C) { aggregateCombinedVector(_C, Eigen::Vector3d::Zero()); } void BodyNode::aggregateGravityForceVector(Eigen::VectorXd& _g, const Eigen::Vector3d& _gravity) { if (mGravityMode == true) mG_F = mI * math::AdInvRLinear(mW, _gravity); else mG_F.setZero(); for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mG_F += math::dAdInvT((*it)->mParentJoint->getLocalTransform(), (*it)->mG_F); } int nGenCoords = mParentJoint->getNumGenCoords(); if (nGenCoords > 0) { Eigen::VectorXd g = -(mParentJoint->getLocalJacobian().transpose() * mG_F); int iStart = mParentJoint->getGenCoord(0)->getSkeletonIndex(); _g.segment(iStart, nGenCoords) = g; } } void BodyNode::updateCombinedVector() { if (mParentJoint->getNumGenCoords() > 0) { if (mParentBodyNode) { mCg_dV = math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->mCg_dV) + mEta; } else { mCg_dV = mEta; } } } void BodyNode::aggregateCombinedVector(Eigen::VectorXd& _Cg, const Eigen::Vector3d& _gravity) { // H(i) = I(i) * W(i) - // dad{V}(I(i) * V(i)) + sum(k \in children) dAd_{T(i,j)^{-1}}(H(k)) if (mGravityMode == true) mFgravity = mI * math::AdInvRLinear(mW, _gravity); else mFgravity.setZero(); mCg_F = mI * mCg_dV; mCg_F -= mFgravity; mCg_F -= math::dad(mV, mI * mV); for (std::vector<BodyNode*>::iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mCg_F += math::dAdInvT((*it)->getParentJoint()->getLocalTransform(), (*it)->mCg_F); } int nGenCoords = mParentJoint->getNumGenCoords(); if (nGenCoords > 0) { Eigen::VectorXd Cg = mParentJoint->getLocalJacobian().transpose() * mCg_F; int iStart = mParentJoint->getGenCoord(0)->getSkeletonIndex(); _Cg.segment(iStart, nGenCoords) = Cg; } } void BodyNode::aggregateExternalForces(Eigen::VectorXd& _Fext) { mFext_F = mFext; for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mFext_F += math::dAdInvT((*it)->mParentJoint->getLocalTransform(), (*it)->mFext_F); } int nGenCoords = mParentJoint->getNumGenCoords(); if (nGenCoords > 0) { Eigen::VectorXd Fext = mParentJoint->getLocalJacobian().transpose() * mFext_F; int iStart = mParentJoint->getGenCoord(0)->getSkeletonIndex(); _Fext.segment(iStart, nGenCoords) = Fext; } } void BodyNode::updateMassMatrix() { mM_dV.setZero(); int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { mM_dV.noalias() += mParentJoint->getLocalJacobian() * mParentJoint->get_ddq(); assert(!math::isNan(mM_dV)); } if (mParentBodyNode) mM_dV += math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->mM_dV); assert(!math::isNan(mM_dV)); } void BodyNode::aggregateMassMatrix(Eigen::MatrixXd& _MCol, int _col) { mM_F.noalias() = mI * mM_dV; assert(!math::isNan(mM_F)); for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mM_F += math::dAdInvT((*it)->getParentJoint()->getLocalTransform(), (*it)->mM_F); } assert(!math::isNan(mM_F)); int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { int iStart = mParentJoint->getGenCoord(0)->getSkeletonIndex(); _MCol.block(iStart, _col, dof, 1).noalias() = mParentJoint->getLocalJacobian().transpose() * mM_F; } } void BodyNode::updateMassInverseMatrix() { mMInv_c.setZero(); for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mMInv_c += math::dAdInvT((*it)->getParentJoint()->getLocalTransform(), (*it)->mMInv_b); } assert(!math::isNan(mMInv_c)); // Cache data: mMInv2_a int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { mMInv_a = mParentJoint->get_tau(); mMInv_a.noalias() -= mParentJoint->getLocalJacobian().transpose() * mMInv_c; assert(!math::isNan(mMInv_a)); } // Cache data: mMInv2_b if (mParentBodyNode) { mMInv_b = mMInv_c; if (dof > 0) mMInv_b.noalias() += mAI_S_Psi * mMInv_a; } assert(!math::isNan(mMInv_b)); } void BodyNode::aggregateInvMassMatrix(Eigen::MatrixXd& _MCol, int _col) { Eigen::VectorXd MInvCol; int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { if (mParentBodyNode) { MInvCol.noalias() = mPsi * mMInv_a; MInvCol.noalias() -= mAI_S_Psi.transpose() * math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->mMInv_U); } else { MInvCol.noalias() = mPsi * mMInv_a; } assert(!math::isNan(MInvCol)); // Assign int iStart = mParentJoint->getGenCoord(0)->getSkeletonIndex(); _MCol.block(iStart, _col, dof, 1) = MInvCol; } if (mChildBodyNodes.size() > 0) { mMInv_U.noalias() = mParentJoint->getLocalJacobian() * MInvCol; if (mParentBodyNode) { mMInv_U += math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->mMInv_U); } assert(!math::isNan(mMInv_U)); } } void BodyNode::_updateBodyJacobian() { //-------------------------------------------------------------------------- // Jacobian update // // J = | J1 J2 ... Jn | // = | Ad(T(i,i-1), J_parent) J_local | // // J_parent: (6 x parentDOF) // J_local: (6 x localDOF) // Ji: (6 x 1) se3 // n: number of dependent coordinates //-------------------------------------------------------------------------- const int localDof = mParentJoint->getNumGenCoords(); const int ascendantDof = getNumDependentGenCoords() - localDof; // Parent Jacobian if (mParentBodyNode) { assert(mParentBodyNode->getBodyJacobian().cols() + mParentJoint->getNumGenCoords() == mBodyJacobian.cols()); assert(mParentJoint); mBodyJacobian.leftCols(ascendantDof) = math::AdInvTJac(mParentJoint->getLocalTransform(), mParentBodyNode->getBodyJacobian()); } // Local Jacobian mBodyJacobian.rightCols(localDof) = mParentJoint->getLocalJacobian(); mIsBodyJacobianDirty = false; } void BodyNode::_updateGeralizedInertia() { // G = | I - m * [r] * [r] m * [r] | // | -m * [r] m * 1 | // m * r double mr0 = mMass * mCenterOfMass[0]; double mr1 = mMass * mCenterOfMass[1]; double mr2 = mMass * mCenterOfMass[2]; // m * [r] * [r] double mr0r0 = mr0 * mCenterOfMass[0]; double mr1r1 = mr1 * mCenterOfMass[1]; double mr2r2 = mr2 * mCenterOfMass[2]; double mr0r1 = mr0 * mCenterOfMass[1]; double mr1r2 = mr1 * mCenterOfMass[2]; double mr2r0 = mr2 * mCenterOfMass[0]; mI(0,0) = mIxx + mr1r1 + mr2r2; mI(0,1) = mIxy - mr0r1; mI(0,2) = mIxz - mr2r0; assert(mI(0,3) == 0.0); mI(0,4) = -mr2; mI(0,5) = mr1; mI(1,1) = mIyy + mr2r2 + mr0r0; mI(1,2) = mIyz - mr1r2; mI(1,3) = mr2; assert(mI(1,4) == 0.0); mI(1,5) = -mr0; mI(2,2) = mIzz + mr0r0 + mr1r1; mI(2,3) = -mr1; mI(2,4) = mr0; assert(mI(2,5) == 0.0); mI(3,3) = mMass; assert(mI(3,4) == 0.0); assert(mI(3,5) == 0.0); mI(4,4) = mMass; assert(mI(4,5) == 0.0); mI(5,5) = mMass; mI.triangularView<Eigen::StrictlyLower>() = mI.transpose(); } void BodyNode::clearExternalForces() { mFext.setZero(); mContactForces.clear(); } } // namespace dynamics } // namespace dart Fix style /* * Copyright (c) 2011, Georgia Tech Research Corporation * All rights reserved. * * Author(s): Sehoon Ha <sehoon.ha@gmail.com> * Jeongseok Lee <jslee02@gmail.com> * Date: 05/14/2013 * * Geoorgia Tech Graphics Lab and Humanoid Robotics Lab * * Directed by Prof. C. Karen Liu and Prof. Mike Stilman * <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu> * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "dynamics/BodyNode.h" #include <algorithm> #include <iostream> #include <queue> #include <stack> #include <boost/math/special_functions/fpclassify.hpp> #include "common/Console.h" #include "math/Helpers.h" #include "renderer/RenderInterface.h" #include "dynamics/Joint.h" #include "dynamics/Shape.h" #include "dynamics/Skeleton.h" #include "dynamics/Marker.h" namespace dart { namespace dynamics { int BodyNode::msBodyNodeCount = 0; BodyNode::BodyNode(const std::string& _name) : mSkelIndex(-1), mName(_name), mIsCollidable(true), mIsColliding(false), mSkeleton(NULL), mParentJoint(NULL), mParentBodyNode(NULL), mChildBodyNodes(std::vector<BodyNode*>(0)), mGravityMode(true), mCenterOfMass(Eigen::Vector3d::Zero()), mMass(1.0), mIxx(1.0), mIyy(1.0), mIzz(1.0), mIxy(0.0), mIxz(0.0), mIyz(0.0), mI(Eigen::Matrix6d::Identity()), mW(Eigen::Isometry3d::Identity()), mV(Eigen::Vector6d::Zero()), mEta(Eigen::Vector6d::Zero()), mdV(Eigen::Vector6d::Zero()), mF(Eigen::Vector6d::Zero()), mFext(Eigen::Vector6d::Zero()), mFgravity(Eigen::Vector6d::Zero()), mAI(Eigen::Matrix6d::Identity()), mB(Eigen::Vector6d::Zero()), mBeta(Eigen::Vector6d::Zero()), mID(BodyNode::msBodyNodeCount++) { } BodyNode::~BodyNode() { for (std::vector<Shape*>::const_iterator it = mVizShapes.begin(); it != mVizShapes.end(); ++it) delete (*it); for (std::vector<Shape*>::const_iterator itColShape = mColShapes.begin(); itColShape != mColShapes.end(); ++itColShape) if (mVizShapes.end() == std::find(mVizShapes.begin(), mVizShapes.end(), *itColShape)) delete (*itColShape); for (std::vector<Marker*>::const_iterator it = mMarkers.begin(); it != mMarkers.end(); ++it) delete (*it); if (mParentJoint) delete mParentJoint; } void BodyNode::setName(const std::string& _name) { mName = _name; } const std::string& BodyNode::getName() const { return mName; } void BodyNode::setGravityMode(bool _gravityMode) { mGravityMode = _gravityMode; } bool BodyNode::getGravityMode() const { return mGravityMode; } bool BodyNode::isCollidable() const { return mIsCollidable; } void BodyNode::setCollidable(bool _isCollidable) { mIsCollidable = _isCollidable; } void BodyNode::setMass(double _mass) { assert(_mass >= 0.0 && "Negative mass is not allowable."); mMass = _mass; _updateGeralizedInertia(); } double BodyNode::getMass() const { return mMass; } BodyNode*BodyNode::getParentBodyNode() const { return mParentBodyNode; } void BodyNode::addChildBodyNode(BodyNode* _body) { assert(_body != NULL); mChildBodyNodes.push_back(_body); _body->mParentBodyNode = this; } BodyNode* BodyNode::getChildBodyNode(int _idx) const { assert(0 <= _idx && _idx < mChildBodyNodes.size()); return mChildBodyNodes[_idx]; } int BodyNode::getNumChildBodyNodes() const { return mChildBodyNodes.size(); } void BodyNode::addMarker(Marker* _marker) { mMarkers.push_back(_marker); } int BodyNode::getNumMarkers() const { return mMarkers.size(); } Marker* BodyNode::getMarker(int _idx) const { return mMarkers[_idx]; } bool BodyNode::dependsOn(int _genCoordIndex) const { return std::binary_search(mDependentGenCoordIndices.begin(), mDependentGenCoordIndices.end(), _genCoordIndex); } int BodyNode::getNumDependentGenCoords() const { return mDependentGenCoordIndices.size(); } int BodyNode::getDependentGenCoord(int _arrayIndex) const { assert(0 <= _arrayIndex && _arrayIndex < mDependentGenCoordIndices.size()); return mDependentGenCoordIndices[_arrayIndex]; } const Eigen::Isometry3d& BodyNode::getWorldTransform() const { return mW; } const Eigen::Vector6d& BodyNode::getBodyVelocity() const { return mV; } Eigen::Vector6d BodyNode::getWorldVelocity(const Eigen::Vector3d& _offset) const { Eigen::Isometry3d T = mW; T.translation() = -_offset; return math::AdT(T, mV); } const Eigen::Vector6d&BodyNode::getBodyAcceleration() const { return mdV; } Eigen::Vector6d BodyNode::getWorldAcceleration( const Eigen::Vector3d& _offset) const { Eigen::Isometry3d T = mW; T.translation() = -_offset; return math::AdT(T, mdV); } const math::Jacobian& BodyNode::getBodyJacobian() { if (mIsBodyJacobianDirty) _updateBodyJacobian(); return mBodyJacobian; } math::Jacobian BodyNode::getWorldJacobian(const Eigen::Vector3d& _offset) { Eigen::Isometry3d T = mW; T.translation() = -_offset; return math::AdTJac(T, getBodyJacobian()); } const math::Jacobian& BodyNode::getBodyJacobianTimeDeriv() const { return mBodyJacobianTimeDeriv; } math::Jacobian BodyNode::getWorldJacobianTimeDeriv( const Eigen::Vector3d& _offset) const { Eigen::Isometry3d T = mW; T.translation() = -_offset; return math::AdTJac(T, mBodyJacobianTimeDeriv); } void BodyNode::setColliding(bool _isColliding) { mIsColliding = _isColliding; } bool BodyNode::isColliding() { return mIsColliding; } void BodyNode::init(Skeleton* _skeleton, int _skeletonIndex) { assert(_skeleton); mSkeleton = _skeleton; mSkelIndex = _skeletonIndex; mParentJoint->mSkelIndex = _skeletonIndex; //-------------------------------------------------------------------------- // Fill the list of generalized coordinates this node depends on, and sort // it. //-------------------------------------------------------------------------- if (mParentBodyNode) mDependentGenCoordIndices = mParentBodyNode->mDependentGenCoordIndices; else mDependentGenCoordIndices.clear(); for (int i = 0; i < mParentJoint->getNumGenCoords(); i++) mDependentGenCoordIndices.push_back(mParentJoint->getGenCoord(i)->getSkeletonIndex()); std::sort(mDependentGenCoordIndices.begin(), mDependentGenCoordIndices.end()); #ifndef NDEBUG // Check whether there is duplicated indices. for (int i = 0; i < mDependentGenCoordIndices.size() - 1; i++) { for (int j = i + 1; j < mDependentGenCoordIndices.size(); j++) { assert(mDependentGenCoordIndices[i] != mDependentGenCoordIndices[j] && "Duplicated index is found in mDependentGenCoordIndices."); } } #endif //-------------------------------------------------------------------------- // Fill the list of decendants of this body node. //-------------------------------------------------------------------------- mDescendantBodyNodes.clear(); // A. DFS (Depth First Search). // std::stack<BodyNode*> stack; // for (std::vector<BodyNode*>::const_reverse_iterator it = // mChildBodyNodes.rbegin(); it != mChildBodyNodes.rend(); ++it) // { // stack.push(*it); // } // while (!stack.empty()) // { // BodyNode* itBodyNode = stack.top(); // stack.pop(); // mDescendantBodyNodes.push_back(itBodyNode); // for (int i = itBodyNode->getNumChildBodyNodes() - 1; i > -1 ; -i) // { // stack.push(itBodyNode->getChildBodyNode(i)); // } // } // B. BFS (Breadth First Search) std::queue<BodyNode*> queue; for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { queue.push(*it); } while (!queue.empty()) { BodyNode* itBodyNode = queue.front(); queue.pop(); mDescendantBodyNodes.push_back(itBodyNode); for (int i = 0; i < itBodyNode->getNumChildBodyNodes(); ++i) { queue.push(itBodyNode->getChildBodyNode(i)); } } //-------------------------------------------------------------------------- // Set dimensions of dynamics matrices and vectors. //-------------------------------------------------------------------------- int numDepGenCoords = getNumDependentGenCoords(); mBodyJacobian.setZero(6, numDepGenCoords); mBodyJacobianTimeDeriv.setZero(6, numDepGenCoords); //-------------------------------------------------------------------------- // Set dimensions of cache data for recursive algorithms //-------------------------------------------------------------------------- int dof = mParentJoint->getNumGenCoords(); mAI_S.setZero(6, dof); mPsi.setZero(dof, dof); mPsiK.setZero(dof, dof); mAlpha.setZero(dof); } void BodyNode::draw(renderer::RenderInterface* _ri, const Eigen::Vector4d& _color, bool _useDefaultColor, int _depth) const { if (_ri == NULL) return; _ri->pushMatrix(); // render the self geometry mParentJoint->applyGLTransform(_ri); _ri->pushName((unsigned)mID); for(int i = 0; i < mVizShapes.size(); i++) { _ri->pushMatrix(); mVizShapes[i]->draw(_ri, _color, _useDefaultColor); _ri->popMatrix(); } _ri->popName(); // render the subtree for (unsigned int i = 0; i < mChildBodyNodes.size(); i++) { mChildBodyNodes[i]->draw(_ri, _color, _useDefaultColor); } _ri->popMatrix(); } void BodyNode::drawMarkers(renderer::RenderInterface* _ri, const Eigen::Vector4d& _color, bool _useDefaultColor) const { if (!_ri) return; _ri->pushMatrix(); mParentJoint->applyGLTransform(_ri); // render the corresponding mMarkerss for (unsigned int i = 0; i < mMarkers.size(); i++) mMarkers[i]->draw(_ri, true, _color, _useDefaultColor); for (unsigned int i = 0; i < mChildBodyNodes.size(); i++) mChildBodyNodes[i]->drawMarkers(_ri,_color, _useDefaultColor); _ri->popMatrix(); } void BodyNode::updateTransform() { mParentJoint->updateTransform(); if (mParentBodyNode) { mW = mParentBodyNode->getWorldTransform() * mParentJoint->getLocalTransform(); } else { mW = mParentJoint->getLocalTransform(); } assert(math::verifyTransform(mW)); mParentJoint->updateJacobian(); } void BodyNode::updateVelocity() { //-------------------------------------------------------------------------- // Body velocity update // // V(i) = Ad(T(i, i-1), V(i-1)) + S * dq //-------------------------------------------------------------------------- if (mParentJoint->getNumGenCoords() > 0) { mV.noalias() = mParentJoint->getLocalJacobian() * mParentJoint->get_dq(); if (mParentBodyNode) { mV += math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->getBodyVelocity()); } } assert(!math::isNan(mV)); } void BodyNode::updateEta(bool _updateJacobianDeriv) { mParentJoint->updateJacobianTimeDeriv(); if (mParentJoint->getNumGenCoords() > 0) { mEta = math::ad(mV, mParentJoint->getLocalJacobian() * mParentJoint->get_dq()); mEta.noalias() += mParentJoint->getLocalJacobianTimeDeriv() * mParentJoint->get_dq(); assert(!math::isNan(mEta)); } if (_updateJacobianDeriv == false) return; //-------------------------------------------------------------------------- // Jacobian first derivative update // // dJ = | dJ1 dJ2 ... dJn | // = | Ad(T(i,i-1), dJ_parent) dJ_local | // // dJ_parent: (6 x parentDOF) // dJ_local: (6 x localDOF) // dJi: (6 x 1) se3 // n: number of dependent coordinates //-------------------------------------------------------------------------- const int numLocalDOFs = mParentJoint->getNumGenCoords(); const int numParentDOFs = getNumDependentGenCoords() - numLocalDOFs; // Parent Jacobian if (mParentBodyNode) { assert(mParentBodyNode->mBodyJacobianTimeDeriv.cols() + mParentJoint->getNumGenCoords() == mBodyJacobianTimeDeriv.cols()); assert(mParentJoint); mBodyJacobianTimeDeriv.leftCols(numParentDOFs) = math::AdInvTJac(mParentJoint->getLocalTransform(), mParentBodyNode->mBodyJacobianTimeDeriv); } // Local Jacobian mBodyJacobianTimeDeriv.rightCols(numLocalDOFs) = mParentJoint->getLocalJacobianTimeDeriv(); } void BodyNode::updateAcceleration() { // dV(i) = Ad(T(i, i-1), dV(i-1)) // + ad(V(i), S * dq) + dS * dq // + S * ddq // = Ad(T(i, i-1), dV(i-1)) // + eta // + S * ddq if (mParentJoint->getNumGenCoords() > 0) { mdV = mEta; mdV.noalias() += mParentJoint->getLocalJacobian() * mParentJoint->get_ddq(); if (mParentBodyNode) { mdV = math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->getBodyAcceleration()); } } assert(!math::isNan(mdV)); } void BodyNode::setInertia(double _Ixx, double _Iyy, double _Izz, double _Ixy, double _Ixz, double _Iyz) { assert(_Ixx >= 0.0); assert(_Iyy >= 0.0); assert(_Izz >= 0.0); mIxx = _Ixx; mIyy = _Iyy; mIzz = _Izz; mIxy = _Ixy; mIxz = _Ixz; mIyz = _Iyz; _updateGeralizedInertia(); } void BodyNode::setLocalCOM(const Eigen::Vector3d& _com) { mCenterOfMass = _com; _updateGeralizedInertia(); } const Eigen::Vector3d& BodyNode::getLocalCOM() const { return mCenterOfMass; } Eigen::Vector3d BodyNode::getWorldCOM() const { return mW.linear() * mCenterOfMass; } Eigen::Matrix6d BodyNode::getInertia() const { return mI; } int BodyNode::getSkeletonIndex() const { return mSkelIndex; } void BodyNode::addVisualizationShape(Shape* _p) { mVizShapes.push_back(_p); } int BodyNode::getNumVisualizationShapes() const { return mVizShapes.size(); } Shape*BodyNode::getVisualizationShape(int _idx) const { return mVizShapes[_idx]; } void BodyNode::addCollisionShape(Shape* _p) { mColShapes.push_back(_p); } int BodyNode::getNumCollisionShapes() const { return mColShapes.size(); } Shape*BodyNode::getCollisionShape(int _idx) const { return mColShapes[_idx]; } Skeleton*BodyNode::getSkeleton() const { return mSkeleton; } void BodyNode::setParentJoint(Joint* _joint) { mParentJoint = _joint; } Joint*BodyNode::getParentJoint() const { return mParentJoint; } void BodyNode::addExtForce(const Eigen::Vector3d& _force, const Eigen::Vector3d& _offset, bool _isOffsetLocal, bool _isForceLocal) { Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); Eigen::Vector6d F = Eigen::Vector6d::Zero(); if (_isOffsetLocal) T.translation() = _offset; else T.translation() = getWorldTransform().inverse() * _offset; if (_isForceLocal) F.tail<3>() = _force; else F.tail<3>() = mW.linear().transpose() * _force; mFext += math::dAdInvT(T, F); } void BodyNode::setExtForce(const Eigen::Vector3d& _force, const Eigen::Vector3d& _offset, bool _isOffsetLocal, bool _isForceLocal) { Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); Eigen::Vector6d F = Eigen::Vector6d::Zero(); if (_isOffsetLocal) T.translation() = _offset; else T.translation() = getWorldTransform().inverse() * _offset; if (_isForceLocal) F.tail<3>() = _force; else F.tail<3>() = mW.linear().transpose() * _force; mFext = math::dAdInvT(T, F); } void BodyNode::addExtTorque(const Eigen::Vector3d& _torque, bool _isLocal) { if (_isLocal) mFext.head<3>() += _torque; else mFext.head<3>() += mW.linear() * _torque; } void BodyNode::setExtTorque(const Eigen::Vector3d& _torque, bool _isLocal) { if (_isLocal) mFext.head<3>() = _torque; else mFext.head<3>() = mW.linear() * _torque; } const Eigen::Vector6d& BodyNode::getExternalForceLocal() const { return mFext; } Eigen::Vector6d BodyNode::getExternalForceGlobal() const { return math::dAdInvT(mW, mFext); } void BodyNode::addContactForce(const Eigen::Vector6d& _contactForce) { mContactForces.push_back(_contactForce); } int BodyNode::getNumContactForces() const { return mContactForces.size(); } const Eigen::Vector6d& BodyNode::getContactForce(int _idx) { assert(0 <= _idx && _idx < mContactForces.size()); return mContactForces[_idx]; } void BodyNode::clearContactForces() { mContactForces.clear(); } const Eigen::Vector6d& BodyNode::getBodyForce() const { return mF; } double BodyNode::getKineticEnergy() const { return 0.5 * mV.dot(mI * mV); } Eigen::Vector3d BodyNode::getLinearMomentum() const { return (mI * mV).tail<3>(); } Eigen::Vector3d BodyNode::getAngularMomentum(const Eigen::Vector3d& _pivot) { Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); T.translation() = _pivot; return math::dAdT(T, mI * mV).head<3>(); } void BodyNode::updateBodyForce(const Eigen::Vector3d& _gravity, bool _withExternalForces) { if (mGravityMode == true) mFgravity.noalias() = mI * math::AdInvRLinear(mW, _gravity); else mFgravity.setZero(); mF.noalias() = mI * mdV; // Inertial force if (_withExternalForces) mF -= mFext; // External force mF -= mFgravity; // Gravity force mF -= math::dad(mV, mI * mV); // Coriolis force for (std::vector<BodyNode*>::iterator iChildBody = mChildBodyNodes.begin(); iChildBody != mChildBodyNodes.end(); ++iChildBody) { Joint* childJoint = (*iChildBody)->getParentJoint(); assert(childJoint != NULL); mF += math::dAdInvT(childJoint->getLocalTransform(), (*iChildBody)->getBodyForce()); } assert(!math::isNan(mF)); } void BodyNode::updateGeneralizedForce(bool _withDampingForces) { assert(mParentJoint != NULL); const math::Jacobian& J = mParentJoint->getLocalJacobian(); // if (_withDampingForces) // mF -= mFDamp; assert(!math::isNan(J.transpose()*mF)); mParentJoint->set_tau(J.transpose()*mF); } void BodyNode::updateArticulatedInertia(double _timeStep) { assert(mParentJoint != NULL); // Articulated inertia mAI = mI; Eigen::Matrix6d tmpAdInv; for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mAI += math::transformInertia( (*it)->getParentJoint()->getLocalTransform().inverse(), (*it)->mPi); } assert(!math::isNan(mAI)); // Cache data: PsiK and Psi mAI_S.noalias() = mAI * mParentJoint->getLocalJacobian(); int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { Eigen::MatrixXd K = Eigen::MatrixXd::Zero(dof, dof); for (int i = 0; i < dof; ++i) K(i, i) = mParentJoint->getDampingCoefficient(i); Eigen::MatrixXd omega = mParentJoint->getLocalJacobian().transpose() * mAI_S; #ifndef NDEBUG Eigen::FullPivLU<Eigen::MatrixXd> omegaKLU(omega + _timeStep * K); Eigen::FullPivLU<Eigen::MatrixXd> omegaLU(omega); assert(omegaKLU.isInvertible()); assert(omegaLU.isInvertible()); #endif // mPsiK = (omega + _timeStep * K).inverse(); mPsiK = (omega + _timeStep * K).ldlt().solve( Eigen::MatrixXd::Identity(dof, dof)); // mPsi = (omega).inverse(); mPsi = (omega).ldlt().solve(Eigen::MatrixXd::Identity(dof, dof)); } assert(!math::isNan(mPsiK)); assert(!math::isNan(mPsi)); // Cache data: AI_S_Psi mAI_S_Psi = mAI_S * mPsi; // Cache data: Pi mPi = mAI; if (dof > 0) mPi.noalias() -= mAI_S*mPsiK*mAI_S.transpose(); assert(!math::isNan(mPi)); } void BodyNode::updateBiasForce(const Eigen::Vector3d& _gravity) { // Bias force if (mGravityMode == true) mFgravity.noalias() = mI * math::AdInvRLinear(mW, _gravity); else mFgravity.setZero(); mB = -math::dad(mV, mI*mV) - mFext - mFgravity; assert(!math::isNan(mB)); for (int i = 0; i < mContactForces.size(); ++i) mB -= mContactForces[i]; assert(!math::isNan(mB)); for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mB += math::dAdInvT((*it)->getParentJoint()->getLocalTransform(), (*it)->mBeta); } assert(!math::isNan(mB)); // Cache data: alpha int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { mAlpha = mParentJoint->get_tau() + mParentJoint->getDampingForces(); for (int i = 0; i < dof; i++) mAlpha(i) += mSkeleton->getConstraintForceVector()[mParentJoint->getGenCoord(i)->getSkeletonIndex()]; //mAlpha.noalias() -= mParentJoint->getLocalJacobian().transpose()*(mAI*mEta + mB); mAlpha.noalias() -= mAI_S.transpose() * mEta; mAlpha.noalias() -= mParentJoint->getLocalJacobian().transpose() * mB; assert(!math::isNan(mAlpha)); } // Cache data: beta mBeta = mB; mBeta.noalias() += mAI*mEta; if (dof > 0) { mBeta.noalias() += mAI_S * mPsiK * mAlpha; } assert(!math::isNan(mBeta)); } void BodyNode::update_ddq() { if (mParentJoint->getNumGenCoords() == 0) return; Eigen::VectorXd ddq; if (mParentBodyNode) { ddq.noalias() = mPsiK * (mAlpha - mAI_S.transpose() * math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->getBodyAcceleration())); } else { ddq.noalias() = mPsiK * mAlpha; } mParentJoint->set_ddq(ddq); assert(!math::isNan(ddq)); } void BodyNode::update_F_fs() { mF = mB; mF.noalias() = mAI * mdV; assert(!math::isNan(mF)); } void BodyNode::aggregateCoriolisForceVector(Eigen::VectorXd& _C) { aggregateCombinedVector(_C, Eigen::Vector3d::Zero()); } void BodyNode::aggregateGravityForceVector(Eigen::VectorXd& _g, const Eigen::Vector3d& _gravity) { if (mGravityMode == true) mG_F = mI * math::AdInvRLinear(mW, _gravity); else mG_F.setZero(); for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mG_F += math::dAdInvT((*it)->mParentJoint->getLocalTransform(), (*it)->mG_F); } int nGenCoords = mParentJoint->getNumGenCoords(); if (nGenCoords > 0) { Eigen::VectorXd g = -(mParentJoint->getLocalJacobian().transpose() * mG_F); int iStart = mParentJoint->getGenCoord(0)->getSkeletonIndex(); _g.segment(iStart, nGenCoords) = g; } } void BodyNode::updateCombinedVector() { if (mParentJoint->getNumGenCoords() > 0) { if (mParentBodyNode) { mCg_dV = math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->mCg_dV) + mEta; } else { mCg_dV = mEta; } } } void BodyNode::aggregateCombinedVector(Eigen::VectorXd& _Cg, const Eigen::Vector3d& _gravity) { // H(i) = I(i) * W(i) - // dad{V}(I(i) * V(i)) + sum(k \in children) dAd_{T(i,j)^{-1}}(H(k)) if (mGravityMode == true) mFgravity = mI * math::AdInvRLinear(mW, _gravity); else mFgravity.setZero(); mCg_F = mI * mCg_dV; mCg_F -= mFgravity; mCg_F -= math::dad(mV, mI * mV); for (std::vector<BodyNode*>::iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mCg_F += math::dAdInvT((*it)->getParentJoint()->getLocalTransform(), (*it)->mCg_F); } int nGenCoords = mParentJoint->getNumGenCoords(); if (nGenCoords > 0) { Eigen::VectorXd Cg = mParentJoint->getLocalJacobian().transpose() * mCg_F; int iStart = mParentJoint->getGenCoord(0)->getSkeletonIndex(); _Cg.segment(iStart, nGenCoords) = Cg; } } void BodyNode::aggregateExternalForces(Eigen::VectorXd& _Fext) { mFext_F = mFext; for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mFext_F += math::dAdInvT((*it)->mParentJoint->getLocalTransform(), (*it)->mFext_F); } int nGenCoords = mParentJoint->getNumGenCoords(); if (nGenCoords > 0) { Eigen::VectorXd Fext = mParentJoint->getLocalJacobian().transpose() * mFext_F; int iStart = mParentJoint->getGenCoord(0)->getSkeletonIndex(); _Fext.segment(iStart, nGenCoords) = Fext; } } void BodyNode::updateMassMatrix() { mM_dV.setZero(); int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { mM_dV.noalias() += mParentJoint->getLocalJacobian() * mParentJoint->get_ddq(); assert(!math::isNan(mM_dV)); } if (mParentBodyNode) mM_dV += math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->mM_dV); assert(!math::isNan(mM_dV)); } void BodyNode::aggregateMassMatrix(Eigen::MatrixXd& _MCol, int _col) { mM_F.noalias() = mI * mM_dV; assert(!math::isNan(mM_F)); for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mM_F += math::dAdInvT((*it)->getParentJoint()->getLocalTransform(), (*it)->mM_F); } assert(!math::isNan(mM_F)); int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { int iStart = mParentJoint->getGenCoord(0)->getSkeletonIndex(); _MCol.block(iStart, _col, dof, 1).noalias() = mParentJoint->getLocalJacobian().transpose() * mM_F; } } void BodyNode::updateMassInverseMatrix() { mMInv_c.setZero(); for (std::vector<BodyNode*>::const_iterator it = mChildBodyNodes.begin(); it != mChildBodyNodes.end(); ++it) { mMInv_c += math::dAdInvT((*it)->getParentJoint()->getLocalTransform(), (*it)->mMInv_b); } assert(!math::isNan(mMInv_c)); // Cache data: mMInv2_a int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { mMInv_a = mParentJoint->get_tau(); mMInv_a.noalias() -= mParentJoint->getLocalJacobian().transpose() * mMInv_c; assert(!math::isNan(mMInv_a)); } // Cache data: mMInv2_b if (mParentBodyNode) { mMInv_b = mMInv_c; if (dof > 0) mMInv_b.noalias() += mAI_S_Psi * mMInv_a; } assert(!math::isNan(mMInv_b)); } void BodyNode::aggregateInvMassMatrix(Eigen::MatrixXd& _MCol, int _col) { Eigen::VectorXd MInvCol; int dof = mParentJoint->getNumGenCoords(); if (dof > 0) { if (mParentBodyNode) { MInvCol.noalias() = mPsi * mMInv_a; MInvCol.noalias() -= mAI_S_Psi.transpose() * math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->mMInv_U); } else { MInvCol.noalias() = mPsi * mMInv_a; } assert(!math::isNan(MInvCol)); // Assign int iStart = mParentJoint->getGenCoord(0)->getSkeletonIndex(); _MCol.block(iStart, _col, dof, 1) = MInvCol; } if (mChildBodyNodes.size() > 0) { mMInv_U.noalias() = mParentJoint->getLocalJacobian() * MInvCol; if (mParentBodyNode) { mMInv_U += math::AdInvT(mParentJoint->getLocalTransform(), mParentBodyNode->mMInv_U); } assert(!math::isNan(mMInv_U)); } } void BodyNode::_updateBodyJacobian() { //-------------------------------------------------------------------------- // Jacobian update // // J = | J1 J2 ... Jn | // = | Ad(T(i,i-1), J_parent) J_local | // // J_parent: (6 x parentDOF) // J_local: (6 x localDOF) // Ji: (6 x 1) se3 // n: number of dependent coordinates //-------------------------------------------------------------------------- const int localDof = mParentJoint->getNumGenCoords(); const int ascendantDof = getNumDependentGenCoords() - localDof; // Parent Jacobian if (mParentBodyNode) { assert(mParentBodyNode->getBodyJacobian().cols() + mParentJoint->getNumGenCoords() == mBodyJacobian.cols()); assert(mParentJoint); mBodyJacobian.leftCols(ascendantDof) = math::AdInvTJac(mParentJoint->getLocalTransform(), mParentBodyNode->getBodyJacobian()); } // Local Jacobian mBodyJacobian.rightCols(localDof) = mParentJoint->getLocalJacobian(); mIsBodyJacobianDirty = false; } void BodyNode::_updateGeralizedInertia() { // G = | I - m * [r] * [r] m * [r] | // | -m * [r] m * 1 | // m * r double mr0 = mMass * mCenterOfMass[0]; double mr1 = mMass * mCenterOfMass[1]; double mr2 = mMass * mCenterOfMass[2]; // m * [r] * [r] double mr0r0 = mr0 * mCenterOfMass[0]; double mr1r1 = mr1 * mCenterOfMass[1]; double mr2r2 = mr2 * mCenterOfMass[2]; double mr0r1 = mr0 * mCenterOfMass[1]; double mr1r2 = mr1 * mCenterOfMass[2]; double mr2r0 = mr2 * mCenterOfMass[0]; mI(0,0) = mIxx + mr1r1 + mr2r2; mI(0,1) = mIxy - mr0r1; mI(0,2) = mIxz - mr2r0; assert(mI(0,3) == 0.0); mI(0,4) = -mr2; mI(0,5) = mr1; mI(1,1) = mIyy + mr2r2 + mr0r0; mI(1,2) = mIyz - mr1r2; mI(1,3) = mr2; assert(mI(1,4) == 0.0); mI(1,5) = -mr0; mI(2,2) = mIzz + mr0r0 + mr1r1; mI(2,3) = -mr1; mI(2,4) = mr0; assert(mI(2,5) == 0.0); mI(3,3) = mMass; assert(mI(3,4) == 0.0); assert(mI(3,5) == 0.0); mI(4,4) = mMass; assert(mI(4,5) == 0.0); mI(5,5) = mMass; mI.triangularView<Eigen::StrictlyLower>() = mI.transpose(); } void BodyNode::clearExternalForces() { mFext.setZero(); mContactForces.clear(); } } // namespace dynamics } // namespace dart
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html"; const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html"; const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html"; const wchar_t kJsPage[] = L"files/devtools/js_page.html"; const wchar_t kResourceContentLengthTestPage[] = L"files/devtools/image.html"; const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html"; const wchar_t kSimplePage[] = L"files/devtools/simple_page.html"; const wchar_t kSyntaxErrorTestPage[] = L"files/devtools/script_syntax_error.html"; const wchar_t kDebuggerStepTestPage[] = L"files/devtools/debugger_step.html"; const wchar_t kDebuggerClosurePage[] = L"files/devtools/debugger_closure.html"; const wchar_t kDebuggerIntrinsicPropertiesPage[] = L"files/devtools/debugger_intrinsic_properties.html"; const wchar_t kCompletionOnPause[] = L"files/devtools/completion_on_pause.html"; const wchar_t kPageWithContentScript[] = L"files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::wstring& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::wstring& test_page) { HTTPTestServer* server = StartHTTPServer(); GURL url = server->TestServerPageW(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Tests resources have correct sizes. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceContentLength) { RunTest("testResourceContentLength", kResourceContentLengthTestPage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Reset inspector settings to defaults to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings( WebPreferences().inspector_settings); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests eval on call frame. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) { RunTest("testEvalOnCallFrame", kDebuggerTestPage); } // Tests step over functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) { RunTest("testStepOver", kDebuggerStepTestPage); } // Tests step out functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) { RunTest("testStepOut", kDebuggerStepTestPage); } // Tests step in functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepIn) { RunTest("testStepIn", kDebuggerStepTestPage); } // Tests that scope can be expanded and contains expected variables. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) { RunTest("testExpandScope", kDebuggerClosurePage); } // Tests that intrinsic properties(__proto__, prototype, constructor) are // present. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDebugIntrinsicProperties) { RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage); } // Tests that execution continues automatically when there is a syntax error in // script and DevTools are open. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) { RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) { RunTest("testCompletionOnPause", kCompletionOnPause); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Tests console eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) { RunTest("testConsoleEval", kConsoleTestPage); } // Tests console log. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) { RunTest("testConsoleLog", kConsoleTestPage); } // Tests eval global values. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) { RunTest("testEvalGlobal", kEvalTestPage); } } // namespace Reenabled a bunch of interactive UI tests on Linux, one of them still fails. BUG=26540 TEST=Run interactive ui tests on Linux. TBR=willchan Review URL: http://codereview.chromium.org/374021 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@31345 0039d316-1c4b-4281-b951-d872f2087c98 // Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html"; const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html"; const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html"; const wchar_t kJsPage[] = L"files/devtools/js_page.html"; const wchar_t kResourceContentLengthTestPage[] = L"files/devtools/image.html"; const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html"; const wchar_t kSimplePage[] = L"files/devtools/simple_page.html"; const wchar_t kSyntaxErrorTestPage[] = L"files/devtools/script_syntax_error.html"; const wchar_t kDebuggerStepTestPage[] = L"files/devtools/debugger_step.html"; const wchar_t kDebuggerClosurePage[] = L"files/devtools/debugger_closure.html"; const wchar_t kDebuggerIntrinsicPropertiesPage[] = L"files/devtools/debugger_intrinsic_properties.html"; const wchar_t kCompletionOnPause[] = L"files/devtools/completion_on_pause.html"; const wchar_t kPageWithContentScript[] = L"files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::wstring& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::wstring& test_page) { HTTPTestServer* server = StartHTTPServer(); GURL url = server->TestServerPageW(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Tests resources have correct sizes. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceContentLength) { RunTest("testResourceContentLength", kResourceContentLengthTestPage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests scripts panel showing. // TODO(pfeldman): http://crbug.com/26540 This test fails on Linux. #if !defined(OS_LINUX) IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } #endif // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Reset inspector settings to defaults to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings( WebPreferences().inspector_settings); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests eval on call frame. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) { RunTest("testEvalOnCallFrame", kDebuggerTestPage); } // Tests step over functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) { RunTest("testStepOver", kDebuggerStepTestPage); } // Tests step out functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) { RunTest("testStepOut", kDebuggerStepTestPage); } // Tests step in functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepIn) { RunTest("testStepIn", kDebuggerStepTestPage); } // Tests that scope can be expanded and contains expected variables. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) { RunTest("testExpandScope", kDebuggerClosurePage); } // Tests that intrinsic properties(__proto__, prototype, constructor) are // present. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDebugIntrinsicProperties) { RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage); } // Tests that execution continues automatically when there is a syntax error in // script and DevTools are open. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) { RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) { RunTest("testCompletionOnPause", kCompletionOnPause); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Tests console eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) { RunTest("testConsoleEval", kConsoleTestPage); } // Tests console log. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) { RunTest("testConsoleLog", kConsoleTestPage); } // Tests eval global values. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) { RunTest("testEvalGlobal", kEvalTestPage); } } // namespace
Fix a strict-aliasing issue in BlacklistStoreInput::ReadUInt. Review URL: http://codereview.chromium.org/155622 git-svn-id: http://src.chromium.org/svn/trunk/src@20869 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 6fac391bda7f2bdadba78a59a5f720b49c289469
// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh_common.h" #ifdef LIBMESH_HAVE_PETSC // C++ includes // Local Includes #include "auto_ptr.h" #include "petsc_preconditioner.h" #include "petsc_macro.h" #include "petsc_matrix.h" #include "petsc_vector.h" #include "petsc_macro.h" #include "libmesh_common.h" namespace libMesh { template <typename T> void PetscPreconditioner<T>::apply(const NumericVector<T> & x, NumericVector<T> & y) { PetscVector<T> & x_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(x)); PetscVector<T> & y_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(y)); Vec x_vec = x_pvec.vec(); Vec y_vec = y_pvec.vec(); PCApply(_pc,x_vec,y_vec); } template <typename T> void PetscPreconditioner<T>::init () { if(!this->_matrix) { libMesh::err << "ERROR: No matrix set for PetscPreconditioner, but init() called" << std::endl; libmesh_error(); } //Clear the preconditioner in case it has been created in the past if(!this->_is_initialized) { //Create the preconditioning object PCCreate(libMesh::COMM_WORLD,&_pc); //Set the PCType set_petsc_preconditioner_type(this->_preconditioner_type, _pc); #ifdef LIBMESH_HAVE_PETSC_HYPRE if(this->_preconditioner_type == AMG_PRECOND) PCHYPRESetType(this->_pc, "boomeramg"); #endif PetscMatrix<T> * pmatrix = libmesh_cast_ptr<PetscMatrix<T>*, SparseMatrix<T> >(this->_matrix); _mat = pmatrix->mat(); } PCSetOperators(_pc,_mat,_mat,SAME_NONZERO_PATTERN); this->_is_initialized = true; } template <typename T> void PetscPreconditioner<T>::set_petsc_preconditioner_type (const PreconditionerType & preconditioner_type, PC & pc) { int ierr = 0; switch (preconditioner_type) { case IDENTITY_PRECOND: ierr = PCSetType (pc, (char*) PCNONE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case CHOLESKY_PRECOND: ierr = PCSetType (pc, (char*) PCCHOLESKY); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ICC_PRECOND: ierr = PCSetType (pc, (char*) PCICC); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ILU_PRECOND: ierr = PCSetType (pc, (char*) PCILU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case LU_PRECOND: ierr = PCSetType (pc, (char*) PCLU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ASM_PRECOND: ierr = PCSetType (pc, (char*) PCASM); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case JACOBI_PRECOND: ierr = PCSetType (pc, (char*) PCJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case BLOCK_JACOBI_PRECOND: ierr = PCSetType (pc, (char*) PCBJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case SOR_PRECOND: ierr = PCSetType (pc, (char*) PCSOR); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case EISENSTAT_PRECOND: ierr = PCSetType (pc, (char*) PCEISENSTAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case AMG_PRECOND: ierr = PCSetType (pc, (char*) PCHYPRE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; #if !(PETSC_VERSION_LESS_THAN(2,1,2)) // Only available for PETSC >= 2.1.2 case USER_PRECOND: ierr = PCSetType (pc, (char*) PCMAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; #endif case SHELL_PRECOND: ierr = PCSetType (pc, (char*) PCSHELL); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; default: libMesh::err << "ERROR: Unsupported PETSC Preconditioner: " << preconditioner_type << std::endl << "Continuing with PETSC defaults" << std::endl; } //Let the commandline override stuff if( preconditioner_type != AMG_PRECOND ) PCSetFromOptions(pc); } //------------------------------------------------------------------ // Explicit instantiations template class PetscPreconditioner<Number>; } // namespace libMesh #endif // #ifdef LIBMESH_HAVE_PETSC Added missing calls to CHKERRABORT(). git-svn-id: ffc1bc5b3feaf8644044862cc38c386ade156493@3979 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf // $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh_common.h" #ifdef LIBMESH_HAVE_PETSC // C++ includes // Local Includes #include "auto_ptr.h" #include "petsc_preconditioner.h" #include "petsc_macro.h" #include "petsc_matrix.h" #include "petsc_vector.h" #include "petsc_macro.h" #include "libmesh_common.h" namespace libMesh { template <typename T> void PetscPreconditioner<T>::apply(const NumericVector<T> & x, NumericVector<T> & y) { PetscVector<T> & x_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(x)); PetscVector<T> & y_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(y)); Vec x_vec = x_pvec.vec(); Vec y_vec = y_pvec.vec(); int ierr = PCApply(_pc,x_vec,y_vec); CHKERRABORT(libMesh::COMM_WORLD,ierr); } template <typename T> void PetscPreconditioner<T>::init () { if(!this->_matrix) { libMesh::err << "ERROR: No matrix set for PetscPreconditioner, but init() called" << std::endl; libmesh_error(); } //Clear the preconditioner in case it has been created in the past if(!this->_is_initialized) { //Create the preconditioning object int ierr = PCCreate(libMesh::COMM_WORLD,&_pc); CHKERRABORT(libMesh::COMM_WORLD,ierr); //Set the PCType set_petsc_preconditioner_type(this->_preconditioner_type, _pc); #ifdef LIBMESH_HAVE_PETSC_HYPRE if(this->_preconditioner_type == AMG_PRECOND) { PCHYPRESetType(this->_pc, "boomeramg"); CHKERRABORT(libMesh::COMM_WORLD,ierr); } #endif PetscMatrix<T> * pmatrix = libmesh_cast_ptr<PetscMatrix<T>*, SparseMatrix<T> >(this->_matrix); _mat = pmatrix->mat(); } int ierr = PCSetOperators(_pc,_mat,_mat,SAME_NONZERO_PATTERN); CHKERRABORT(libMesh::COMM_WORLD,ierr); this->_is_initialized = true; } template <typename T> void PetscPreconditioner<T>::set_petsc_preconditioner_type (const PreconditionerType & preconditioner_type, PC & pc) { int ierr = 0; switch (preconditioner_type) { case IDENTITY_PRECOND: ierr = PCSetType (pc, (char*) PCNONE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case CHOLESKY_PRECOND: ierr = PCSetType (pc, (char*) PCCHOLESKY); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ICC_PRECOND: ierr = PCSetType (pc, (char*) PCICC); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ILU_PRECOND: ierr = PCSetType (pc, (char*) PCILU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case LU_PRECOND: ierr = PCSetType (pc, (char*) PCLU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ASM_PRECOND: ierr = PCSetType (pc, (char*) PCASM); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case JACOBI_PRECOND: ierr = PCSetType (pc, (char*) PCJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case BLOCK_JACOBI_PRECOND: ierr = PCSetType (pc, (char*) PCBJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case SOR_PRECOND: ierr = PCSetType (pc, (char*) PCSOR); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case EISENSTAT_PRECOND: ierr = PCSetType (pc, (char*) PCEISENSTAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case AMG_PRECOND: ierr = PCSetType (pc, (char*) PCHYPRE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; #if !(PETSC_VERSION_LESS_THAN(2,1,2)) // Only available for PETSC >= 2.1.2 case USER_PRECOND: ierr = PCSetType (pc, (char*) PCMAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; #endif case SHELL_PRECOND: ierr = PCSetType (pc, (char*) PCSHELL); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; default: libMesh::err << "ERROR: Unsupported PETSC Preconditioner: " << preconditioner_type << std::endl << "Continuing with PETSC defaults" << std::endl; } //Let the commandline override stuff if( preconditioner_type != AMG_PRECOND ) { PCSetFromOptions(pc); CHKERRABORT(libMesh::COMM_WORLD,ierr); } } //------------------------------------------------------------------ // Explicit instantiations template class PetscPreconditioner<Number>; } // namespace libMesh #endif // #ifdef LIBMESH_HAVE_PETSC
#include "studio_app.h" #include "asset_browser.h" #include "audio/audio_scene.h" #include "audio/clip_manager.h" #include "editor/asset_compiler.h" #include "editor/file_system_watcher.h" #include "editor/gizmo.h" #include "editor/prefab_system.h" #include "editor/render_interface.h" #include "editor/world_editor.h" #include "engine/command_line_parser.h" #include "engine/crc32.h" #include "engine/debug/debug.h" #include "engine/default_allocator.h" #include "engine/engine.h" #include "engine/fs/disk_file_device.h" #include "engine/fs/file_system.h" #include "engine/fs/os_file.h" #include "engine/input_system.h" #include "engine/log.h" #include "engine/lua_wrapper.h" #include "engine/mt/thread.h" #include "engine/os.h" #include "engine/path_utils.h" #include "engine/plugin_manager.h" #include "engine/profiler.h" #include "engine/quat.h" #include "engine/reflection.h" #include "engine/resource_manager.h" #include "engine/timer.h" #include "engine/universe/universe.h" #include "engine/viewport.h" #include "imgui/imgui.h" #include "log_ui.h" #include "profiler_ui.h" #include "property_grid.h" #include "settings.h" #include "utils.h" namespace Lumix { struct LuaPlugin : public StudioApp::GUIPlugin { LuaPlugin(StudioApp& app, const char* src, const char* filename) : editor(app.getWorldEditor()) { L = lua_newthread(editor.getEngine().getState()); // [thread] thread_ref = luaL_ref(editor.getEngine().getState(), LUA_REGISTRYINDEX); // [] lua_newtable(L); // [env] // reference environment lua_pushvalue(L, -1); // [env, env] env_ref = luaL_ref(L, LUA_REGISTRYINDEX); // [env] // environment's metatable & __index lua_pushvalue(L, -1); // [env, env] lua_setmetatable(L, -2); // [env] lua_pushvalue(L, LUA_GLOBALSINDEX); lua_setfield(L, -2, "__index"); // [env] bool errors = luaL_loadbuffer(L, src, stringLength(src), filename) != 0; // [env, func] lua_pushvalue(L, -2); // [env, func, env] lua_setfenv(L, -2); // function's environment [env, func] errors = errors || lua_pcall(L, 0, 0, 0) != 0; // [env] if (errors) { g_log_error.log("Editor") << filename << ": " << lua_tostring(L, -1); lua_pop(L, 1); } lua_pop(L, 1); // [] const char* name = "LuaPlugin"; lua_getglobal(L, "plugin_name"); if (lua_type(L, -1) == LUA_TSTRING) { name = lua_tostring(L, -1); } Action* action = LUMIX_NEW(editor.getAllocator(), Action)(name, name, name); action->func.bind<LuaPlugin, &LuaPlugin::onAction>(this); app.addWindowAction(action); m_is_open = false; lua_pop(L, 1); // plugin_name } ~LuaPlugin() { lua_State* L = editor.getEngine().getState(); luaL_unref(L, LUA_REGISTRYINDEX, env_ref); luaL_unref(L, LUA_REGISTRYINDEX, thread_ref); } const char* getName() const override { return "lua_script"; } void onAction() { m_is_open = !m_is_open; } void onWindowGUI() override { if (!m_is_open) return; lua_getglobal(L, "onGUI"); if (lua_type(L, -1) == LUA_TFUNCTION) { if (lua_pcall(L, 0, 0, 0) != 0) { g_log_error.log("Editor") << "LuaPlugin:" << lua_tostring(L, -1); lua_pop(L, 1); } } else { lua_pop(L, 1); } } WorldEditor& editor; lua_State* L; int thread_ref; int env_ref; bool m_is_open; }; class StudioAppImpl final : public StudioApp { public: StudioAppImpl() : m_is_entity_list_open(true) , m_is_save_as_dialog_open(false) , m_finished(false) , m_deferred_game_mode_exit(false) , m_profiler_ui(nullptr) , m_asset_browser(nullptr) , m_asset_compiler(nullptr) , m_property_grid(nullptr) , m_actions(m_allocator) , m_window_actions(m_allocator) , m_toolbar_actions(m_allocator) , m_is_welcome_screen_open(true) , m_is_pack_data_dialog_open(false) , m_editor(nullptr) , m_settings(*this) , m_gui_plugins(m_allocator) , m_plugins(m_allocator) , m_add_cmp_plugins(m_allocator) , m_component_labels(m_allocator) , m_confirm_load(false) , m_confirm_new(false) , m_confirm_exit(false) , m_exit_code(0) , m_allocator(m_main_allocator) , m_universes(m_allocator) , m_events(m_allocator) , m_fps_timer(nullptr) { } void onEvent(const OS::Event& event) { m_events.push(event); switch (event.type) { case OS::Event::Type::MOUSE_BUTTON: { ImGuiIO& io = ImGui::GetIO(); m_editor->setToggleSelection(io.KeyCtrl); m_editor->setSnapMode(io.KeyShift, io.KeyCtrl); io.MouseDown[(int)event.mouse_button.button] = event.mouse_button.down; break; } case OS::Event::Type::MOUSE_WHEEL: { ImGuiIO& io = ImGui::GetIO(); io.MouseWheel = event.mouse_wheel.amount; break; } case OS::Event::Type::MOUSE_MOVE: { ImGuiIO& io = ImGui::GetIO(); const OS::Point cp = OS::getMousePos(event.window); m_mouse_move += {(float)event.mouse_move.xrel, (float)event.mouse_move.yrel}; io.MousePos.x = (float)cp.x; io.MousePos.y = (float)cp.y; break; } case OS::Event::Type::WINDOW_SIZE: if (event.window == m_window && event.win_size.h > 0 && event.win_size.w > 0) { m_settings.m_window.w = event.win_size.w; m_settings.m_window.h = event.win_size.h; m_settings.m_is_maximized = OS::isMaximized(m_window); } break; case OS::Event::Type::WINDOW_MOVE: if (event.window == m_window) { m_settings.m_window.x = event.win_move.x; m_settings.m_window.y = event.win_move.y; m_settings.m_is_maximized = OS::isMaximized(m_window); } break; case OS::Event::Type::WINDOW_CLOSE: case OS::Event::Type::QUIT: exit(); break; case OS::Event::Type::CHAR: { ImGuiIO& io = ImGui::GetIO(); char utf8[5]; OS::UTF32ToUTF8(event.text_input.utf32, utf8); utf8[4] = 0; io.AddInputCharactersUTF8(utf8); break; } case OS::Event::Type::KEY: { ImGuiIO& io = ImGui::GetIO(); io.KeysDown[(int)event.key.keycode] = event.key.down; io.KeyShift = OS::isKeyDown(OS::Keycode::SHIFT); io.KeyCtrl = OS::isKeyDown(OS::Keycode::CTRL); io.KeyAlt = OS::isKeyDown(OS::Keycode::MENU); checkShortcuts(); break; } case OS::Event::Type::DROP_FILE: for(int i = 0, c = OS::getDropFileCount(event); i < c; ++i) { char tmp[MAX_PATH_LENGTH]; OS::getDropFile(event, i, tmp, lengthOf(tmp)); for (GUIPlugin* plugin : m_gui_plugins) { if (plugin->onDropFile(tmp)) break; } } break; } } void onIdle() override { update(); if (m_sleep_when_inactive && OS::getFocused() != m_window) { const float frame_time = m_fps_timer->tick(); const float wanted_fps = 5.0f; if (frame_time < 1 / wanted_fps) { PROFILE_BLOCK("sleep"); MT::sleep(u32(1000 / wanted_fps - frame_time * 1000)); } m_fps_timer->tick(); } Profiler::frame(); m_events.clear(); } void onInit() override { m_add_cmp_root.label[0] = '\0'; m_template_name[0] = '\0'; m_open_filter[0] = '\0'; checkWorkingDirector(); char current_dir[MAX_PATH_LENGTH]; OS::getCurrentDirectory(current_dir, lengthOf(current_dir)); char data_dir_path[MAX_PATH_LENGTH] = {}; checkDataDirCommandLine(data_dir_path, lengthOf(data_dir_path)); m_engine = Engine::create(current_dir, nullptr, m_allocator); createLua(); m_editor = WorldEditor::create(current_dir, *m_engine, m_allocator); m_window = m_editor->getWindow(); m_settings.m_editor = m_editor; scanUniverses(); loadUserPlugins(); addActions(); m_asset_compiler = AssetCompiler::create(*this); m_asset_browser = LUMIX_NEW(m_allocator, AssetBrowser)(*this); m_property_grid = LUMIX_NEW(m_allocator, PropertyGrid)(*this); m_profiler_ui = ProfilerUI::create(*m_engine); m_log_ui = LUMIX_NEW(m_allocator, LogUI)(m_editor->getAllocator()); ImGui::CreateContext(); loadSettings(); initIMGUI(); #ifdef _WIN32 // TODO // ImGui::GetPlatformIO().ImeWindowHandle = m_window; #endif m_custom_pivot_action = LUMIX_NEW(m_editor->getAllocator(), Action)("Set Custom Pivot", "Set Custom Pivot", "set_custom_pivot", OS::Keycode::K, OS::Keycode::INVALID, OS::Keycode::INVALID); m_custom_pivot_action->is_global = false; addAction(m_custom_pivot_action); setStudioApp(); loadIcons(); loadSettings(); loadUniverseFromCommandLine(); findLuaPlugins("plugins/lua/"); m_asset_compiler->onInitFinished(); m_sleep_when_inactive = shouldSleepWhenInactive(); checkScriptCommandLine(); m_fps_timer = Timer::create(m_allocator); } ~StudioAppImpl() { Timer::destroy(m_fps_timer); if (m_watched_plugin.watcher) FileSystemWatcher::destroy(m_watched_plugin.watcher); saveSettings(); unloadIcons(); while (m_editor->getEngine().getFileSystem().hasWork()) { m_editor->getEngine().getFileSystem().updateAsyncTransactions(); } m_editor->newUniverse(); destroyAddCmpTreeNode(m_add_cmp_root.child); for (auto* i : m_plugins) { LUMIX_DELETE(m_editor->getAllocator(), i); } m_plugins.clear(); PrefabSystem::destroyEditorPlugins(*this); ASSERT(m_gui_plugins.empty()); for (auto* i : m_add_cmp_plugins) { LUMIX_DELETE(m_editor->getAllocator(), i); } m_add_cmp_plugins.clear(); for (auto* a : m_actions) { LUMIX_DELETE(m_editor->getAllocator(), a); } m_actions.clear(); ProfilerUI::destroy(*m_profiler_ui); LUMIX_DELETE(m_allocator, m_asset_browser); LUMIX_DELETE(m_allocator, m_property_grid); LUMIX_DELETE(m_allocator, m_log_ui); AssetCompiler::destroy(*m_asset_compiler); WorldEditor::destroy(m_editor, m_allocator); Engine::destroy(m_engine, m_allocator); m_engine = nullptr; m_editor = nullptr; OS::destroyWindow(m_window); } bool makeFile(const char* path, const char* content) override { FS::OsFile file; if (!file.open(path, FS::Mode::CREATE_AND_WRITE)) return false; bool success = file.writeText(content); file.close(); return success; } void destroyAddCmpTreeNode(AddCmpTreeNode* node) { if (!node) return; destroyAddCmpTreeNode(node->child); destroyAddCmpTreeNode(node->next); LUMIX_DELETE(m_allocator, node); } const char* getComponentTypeName(ComponentType cmp_type) const override { auto iter = m_component_labels.find(cmp_type); if (iter == m_component_labels.end()) return "Unknown"; return iter.value().c_str(); } const AddCmpTreeNode& getAddComponentTreeRoot() const override { return m_add_cmp_root; } void addPlugin(IAddComponentPlugin& plugin) { int i = 0; while (i < m_add_cmp_plugins.size() && compareString(plugin.getLabel(), m_add_cmp_plugins[i]->getLabel()) > 0) { ++i; } m_add_cmp_plugins.insert(i, &plugin); auto* node = LUMIX_NEW(m_allocator, AddCmpTreeNode); copyString(node->label, plugin.getLabel()); node->plugin = &plugin; insertAddCmpNode(m_add_cmp_root, node); } static void insertAddCmpNodeOrdered(AddCmpTreeNode& parent, AddCmpTreeNode* node) { if (!parent.child) { parent.child = node; return; } if (compareString(parent.child->label, node->label) > 0) { node->next = parent.child; parent.child = node; return; } auto* i = parent.child; while (i->next && compareString(i->next->label, node->label) < 0) { i = i->next; } node->next = i->next; i->next = node; } void insertAddCmpNode(AddCmpTreeNode& parent, AddCmpTreeNode* node) { for (auto* i = parent.child; i; i = i->next) { if (!i->plugin && startsWith(node->label, i->label)) { insertAddCmpNode(*i, node); return; } } const char* rest = node->label + stringLength(parent.label); if (parent.label[0] != '\0') ++rest; // include '/' const char* slash = findSubstring(rest, "/"); if (!slash) { insertAddCmpNodeOrdered(parent, node); return; } auto* new_group = LUMIX_NEW(m_allocator, AddCmpTreeNode); copyNString(new_group->label, (int)sizeof(new_group->label), node->label, int(slash - node->label)); insertAddCmpNodeOrdered(parent, new_group); insertAddCmpNode(*new_group, node); } void registerComponentWithResource(const char* type, const char* label, ResourceType resource_type, const Reflection::PropertyBase& property) override { struct Plugin final : public IAddComponentPlugin { void onGUI(bool create_entity, bool from_filter) override { ImGui::SetNextWindowSize(ImVec2(300, 300)); const char* last = reverseFind(label, nullptr, '/'); if (!ImGui::BeginMenu(last && !from_filter ? last + 1 : label)) return; char buf[MAX_PATH_LENGTH]; bool create_empty = ImGui::MenuItem("Empty"); if (asset_browser->resourceList(buf, lengthOf(buf), resource_type, 0) || create_empty) { if (create_entity) { EntityRef entity = editor->addEntity(); editor->selectEntities(&entity, 1, false); } editor->addComponent(type); if (!create_empty) { editor->setProperty(type, -1, *property, &editor->getSelectedEntities()[0], editor->getSelectedEntities().size(), buf, stringLength(buf) + 1); } ImGui::CloseCurrentPopup(); } ImGui::EndMenu(); } const char* getLabel() const override { return label; } PropertyGrid* property_grid; AssetBrowser* asset_browser; WorldEditor* editor; ComponentType type; ResourceType resource_type; const Reflection::PropertyBase* property; char label[50]; }; auto& allocator = m_editor->getAllocator(); auto* plugin = LUMIX_NEW(allocator, Plugin); plugin->property_grid = m_property_grid; plugin->asset_browser = m_asset_browser; plugin->type = Reflection::getComponentType(type); plugin->editor = m_editor; plugin->property = &property; plugin->resource_type = resource_type; copyString(plugin->label, label); addPlugin(*plugin); m_component_labels.insert(plugin->type, string(label, m_allocator)); } void registerComponent(const char* id, IAddComponentPlugin& plugin) override { addPlugin(plugin); m_component_labels.insert(Reflection::getComponentType(id), string(plugin.getLabel(), m_allocator)); } void registerComponent(const char* type, const char* label) override { struct Plugin final : public IAddComponentPlugin { void onGUI(bool create_entity, bool from_filter) override { const char* last = reverseFind(label, nullptr, '/'); if (ImGui::MenuItem(last && !from_filter ? last + 1 : label)) { if (create_entity) { EntityRef entity = editor->addEntity(); editor->selectEntities(&entity, 1, false); } editor->addComponent(type); } } const char* getLabel() const override { return label; } WorldEditor* editor; PropertyGrid* property_grid; ComponentType type; char label[64]; }; auto& allocator = m_editor->getAllocator(); auto* plugin = LUMIX_NEW(allocator, Plugin); plugin->property_grid = m_property_grid; plugin->editor = m_editor; plugin->type = Reflection::getComponentType(type); copyString(plugin->label, label); addPlugin(*plugin); m_component_labels.insert(plugin->type, string(label, m_allocator)); } const Array<Action*>& getActions() override { return m_actions; } Array<Action*>& getToolbarActions() override { return m_toolbar_actions; } void guiBeginFrame() const { PROFILE_FUNCTION(); ImGuiIO& io = ImGui::GetIO(); const OS::Point size = OS::getWindowClientSize(m_window); if (size.x > 0 && size.y > 0) { io.DisplaySize = ImVec2(float(size.x), float(size.y)); } else if(io.DisplaySize.x <= 0) { io.DisplaySize.x = 800; io.DisplaySize.y = 600; } io.DeltaTime = m_engine->getLastTimeDelta(); io.KeyShift = OS::isKeyDown(OS::Keycode::SHIFT); io.KeyCtrl = OS::isKeyDown(OS::Keycode::CTRL); io.KeyAlt = OS::isKeyDown(OS::Keycode::MENU); ImGui::NewFrame(); ImGui::PushFont(m_font); } float showMainToolbar(float menu_height) { if (m_toolbar_actions.empty()) { ImGui::SetCursorPosY(menu_height); return menu_height; } auto frame_padding = ImGui::GetStyle().FramePadding; float padding = frame_padding.y * 2; ImVec2 toolbar_size(ImGui::GetIO().DisplaySize.x, 24 + padding); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); if (ImGui::BeginToolbar("main_toolbar", ImVec2(1, menu_height), toolbar_size)) { for (auto* action : m_toolbar_actions) { action->toolbarButton(); } } ImGui::EndToolbar(); ImGui::PopStyleVar(); return menu_height + 24 + padding; } void guiEndFrame() { if (m_is_welcome_screen_open) { ImGuiID dockspace_id = ImGui::GetID("MyDockspace"); ImGui::DockSpace(dockspace_id, ImVec2(0, 0), ImGuiDockNodeFlags_KeepAliveOnly); showWelcomeScreen(); } else { if (ImGui::GetIO().DisplaySize.y > 0) { auto pos = ImVec2(0, 0); auto size = ImGui::GetIO().DisplaySize; size.y -= pos.y; ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; ImGui::SetNextWindowSize(size); ImGui::SetNextWindowPos({0, 0}, ImGuiCond_FirstUseEver); if (ImGui::Begin("MainDockspace", nullptr, flags)) { float menu_height = showMainMenu(); showMainToolbar(menu_height); ImGuiID dockspace_id = ImGui::GetID("MyDockspace"); ImGui::DockSpace(dockspace_id, ImVec2(0, 0)); } ImGui::End(); // TODO // ImGui::RootDock(pos, size); } m_profiler_ui->onGUI(); m_asset_browser->onGUI(); m_log_ui->onGUI(); m_property_grid->onGUI(); onEntityListGUI(); onEditCameraGUI(); onSaveAsDialogGUI(); for (auto* plugin : m_gui_plugins) { plugin->onWindowGUI(); } m_settings.onGUI(); onPackDataGUI(); } ImGui::PopFont(); ImGui::Render(); for (auto* plugin : m_gui_plugins) { plugin->guiEndFrame(); } } void update() { PROFILE_FUNCTION(); m_asset_compiler->update(); if (m_watched_plugin.reload_request) tryReloadPlugin(); guiBeginFrame(); float time_delta = m_editor->getEngine().getLastTimeDelta(); ImGuiIO& io = ImGui::GetIO(); if (!io.KeyShift) { m_editor->setSnapMode(false, false); } else if (io.KeyCtrl) { m_editor->setSnapMode(io.KeyShift, io.KeyCtrl); } if (m_custom_pivot_action->isActive()) { m_editor->setCustomPivot(); } m_editor->setMouseSensitivity(m_settings.m_mouse_sensitivity.x, m_settings.m_mouse_sensitivity.y); m_editor->update(); m_engine->update(*m_editor->getUniverse()); if (m_deferred_game_mode_exit) { m_deferred_game_mode_exit = false; m_editor->toggleGameMode(); } for (auto* plugin : m_gui_plugins) { plugin->update(time_delta); } m_asset_browser->update(); m_log_ui->update(time_delta); guiEndFrame(); } void showWelcomeScreen() { ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings; const OS::Point size = OS::getWindowClientSize(m_window); ImGui::SetNextWindowSize(ImVec2((float)size.x, (float)size.y)); ImGui::SetNextWindowPos({0, 0}, ImGuiCond_FirstUseEver); if (ImGui::Begin("Welcome", nullptr, flags)) { ImGui::Text("Welcome to Lumix Studio"); ImVec2 half_size = ImGui::GetContentRegionAvail(); half_size.x = half_size.x * 0.5f - ImGui::GetStyle().FramePadding.x; half_size.y *= 0.75f; auto right_pos = ImGui::GetCursorPos(); right_pos.x += half_size.x + ImGui::GetStyle().FramePadding.x; if (ImGui::BeginChild("left", half_size, true)) { if (ImGui::Button("New Universe")) m_is_welcome_screen_open = false; ImGui::Separator(); ImGui::Text("Open universe:"); ImGui::Indent(); for (auto& univ : m_universes) { if (ImGui::MenuItem(univ.data)) { m_editor->loadUniverse(univ.data); setTitle(univ.data); m_is_welcome_screen_open = false; } } ImGui::Unindent(); } ImGui::EndChild(); ImGui::SetCursorPos(right_pos); if (ImGui::BeginChild("right", half_size, true)) { ImGui::Text("Using NVidia PhysX"); if (ImGui::Button("Wiki")) { OS::shellExecuteOpen("https://github.com/nem0/LumixEngine/wiki"); } if (ImGui::Button("Download new version")) { OS::shellExecuteOpen( "https://github.com/nem0/lumixengine_data/archive/master.zip"); } if (ImGui::Button("Show major releases")) { OS::shellExecuteOpen("https://github.com/nem0/LumixEngine/releases"); } if (ImGui::Button("Show latest commits")) { OS::shellExecuteOpen("https://github.com/nem0/LumixEngine/commits/master"); } if (ImGui::Button("Show issues")) { OS::shellExecuteOpen("https://github.com/nem0/lumixengine/issues"); } } ImGui::EndChild(); } ImGui::End(); } void setTitle(const char* title) const { char tmp[100]; copyString(tmp, "Lumix Studio - "); catString(tmp, title); OS::setWindowTitle(m_window, tmp); } static void getShortcut(const Action& action, char* buf, int max_size) { buf[0] = 0; for (int i = 0; i < lengthOf(action.shortcut); ++i) { char tmp[64]; OS::getKeyName(action.shortcut[i], tmp, sizeof(tmp)); if (tmp[0] == 0) return; if (i > 0) catString(buf, max_size, " - "); catString(buf, max_size, tmp); } } void doMenuItem(Action& a, bool enabled) const { char buf[20]; getShortcut(a, buf, sizeof(buf)); if (ImGui::MenuItem(a.label_short, buf, a.is_selected.invoke(), enabled)) { a.func.invoke(); } } void save() { if (m_editor->isGameMode()) { g_log_error.log("Editor") << "Could not save while the game is running"; return; } if (m_editor->getUniverse()->getName()[0]) { m_editor->saveUniverse(m_editor->getUniverse()->getName(), true); } else { saveAs(); } } void onSaveAsDialogGUI() { if (!m_is_save_as_dialog_open) return; if (ImGui::Begin("Save Universe As", &m_is_save_as_dialog_open)) { static char name[64] = ""; ImGui::InputText("Name", name, lengthOf(name)); if (ImGui::Button("Save")) { m_is_save_as_dialog_open = false; setTitle(name); m_editor->saveUniverse(name, true); scanUniverses(); } ImGui::SameLine(); if (ImGui::Button("Close")) m_is_save_as_dialog_open = false; } ImGui::End(); } void saveAs() { if (m_editor->isGameMode()) { g_log_error.log("Editor") << "Could not save while the game is running"; return; } m_is_save_as_dialog_open = true; } void exit() { if (m_editor->isUniverseChanged()) { m_confirm_exit = true; } else { OS::quit(); m_finished = true; } } void newUniverse() { if (m_editor->isUniverseChanged()) { m_confirm_new = true; } else { m_editor->newUniverse(); } } GUIPlugin* getFocusedPlugin() { for (GUIPlugin* plugin : m_gui_plugins) { if (plugin->hasFocus()) return plugin; } return nullptr; } void undo() { m_editor->undo(); } void redo() { m_editor->redo(); } void copy() { m_editor->copyEntities(); } void paste() { m_editor->pasteEntities(); } void duplicate() { m_editor->duplicateEntities(); } bool isOrbitCamera() { return m_editor->isOrbitCamera(); } void toggleOrbitCamera() { m_editor->setOrbitCamera(!m_editor->isOrbitCamera()); } void setTopView() { m_editor->setTopView(); } void setFrontView() { m_editor->setFrontView(); } void setSideView() { m_editor->setSideView(); } void setLocalCoordSystem() { m_editor->getGizmo().setLocalCoordSystem(); } void setGlobalCoordSystem() { m_editor->getGizmo().setGlobalCoordSystem(); } void setPivotOrigin() { m_editor->getGizmo().setPivotOrigin(); } void setPivotCenter() { m_editor->getGizmo().setPivotCenter(); } void addEntity() { m_editor->addEntity(); } void toggleMeasure() { m_editor->toggleMeasure(); } void snapDown() { m_editor->snapDown(); } void setEditCamTransform() { m_is_edit_cam_transform_ui_open = !m_is_edit_cam_transform_ui_open; } void lookAtSelected() { m_editor->lookAtSelected(); } void toggleSettings() { m_settings.m_is_open = !m_settings.m_is_open; } bool areSettingsOpen() const { return m_settings.m_is_open; } void toggleEntityList() { m_is_entity_list_open = !m_is_entity_list_open; } bool isEntityListOpen() const { return m_is_entity_list_open; } void toggleAssetBrowser() { m_asset_browser->m_is_open = !m_asset_browser->m_is_open; } bool isAssetBrowserOpen() const { return m_asset_browser->m_is_open; } int getExitCode() const override { return m_exit_code; } AssetBrowser& getAssetBrowser() override { ASSERT(m_asset_browser); return *m_asset_browser; } AssetCompiler& getAssetCompiler() override { ASSERT(m_asset_compiler); return *m_asset_compiler; } PropertyGrid& getPropertyGrid() override { ASSERT(m_property_grid); return *m_property_grid; } LogUI& getLogUI() override { ASSERT(m_log_ui); return *m_log_ui; } void toggleGameMode() { m_editor->toggleGameMode(); } void setTranslateGizmoMode() { m_editor->getGizmo().setTranslateMode(); } void setRotateGizmoMode() { m_editor->getGizmo().setRotateMode(); } void setScaleGizmoMode() { m_editor->getGizmo().setScaleMode(); } void makeParent() { const auto& entities = m_editor->getSelectedEntities(); ASSERT(entities.size() == 2); m_editor->makeParent(entities[0], entities[1]); } void unparent() { const auto& entities = m_editor->getSelectedEntities(); ASSERT(entities.size() == 1); m_editor->makeParent(INVALID_ENTITY, entities[0]); } void savePrefab() { char filename[MAX_PATH_LENGTH]; char tmp[MAX_PATH_LENGTH]; if (OS::getSaveFilename(tmp, lengthOf(tmp), "Prefab files\0*.fab\0", "fab")) { PathUtils::normalize(tmp, filename, lengthOf(tmp)); const char* base_path = m_engine->getDiskFileDevice()->getBasePath(); if (startsWith(filename, base_path)) { m_editor->getPrefabSystem().savePrefab(Path(filename + stringLength(base_path))); } else { m_editor->getPrefabSystem().savePrefab(Path(filename)); } } } void autosnapDown() { auto& gizmo = m_editor->getGizmo(); gizmo.setAutosnapDown(!gizmo.isAutosnapDown()); } void destroySelectedEntity() { auto& selected_entities = m_editor->getSelectedEntities(); if (selected_entities.empty()) return; m_editor->destroyEntities(&selected_entities[0], selected_entities.size()); } void loadAndExecuteCommands() { char filename[MAX_PATH_LENGTH]; if (OS::getOpenFilename(filename, lengthOf(filename), "JSON files\0*.json\0", nullptr)) { m_editor->executeUndoStack(Path(filename)); } } void saveUndoStack() { char filename[MAX_PATH_LENGTH]; if (OS::getSaveFilename(filename, lengthOf(filename), "JSON files\0*.json\0", "json")) { m_editor->saveUndoStack(Path(filename)); } } void removeAction(Action* action) override { m_actions.eraseItem(action); m_window_actions.eraseItem(action); } void addWindowAction(Action* action) override { addAction(action); for (int i = 0; i < m_window_actions.size(); ++i) { if (compareString(m_window_actions[i]->label_long, action->label_long) > 0) { m_window_actions.insert(i, action); return; } } m_window_actions.push(action); } void addAction(Action* action) override { for (int i = 0; i < m_actions.size(); ++i) { if (compareString(m_actions[i]->label_long, action->label_long) > 0) { m_actions.insert(i, action); return; } } m_actions.push(action); } template <void (StudioAppImpl::*Func)()> Action& addAction(const char* label_short, const char* label_long, const char* name) { auto* a = LUMIX_NEW(m_editor->getAllocator(), Action)(label_short, label_long, name); a->func.bind<StudioAppImpl, Func>(this); addAction(a); return *a; } template <void (StudioAppImpl::*Func)()> void addAction(const char* label_short, const char* label_long, const char* name, OS::Keycode shortcut0, OS::Keycode shortcut1, OS::Keycode shortcut2) { auto* a = LUMIX_NEW(m_editor->getAllocator(), Action)(label_short, label_long, name, shortcut0, shortcut1, shortcut2); a->func.bind<StudioAppImpl, Func>(this); addAction(a); } Action* getAction(const char* name) override { for (auto* a : m_actions) { if (equalStrings(a->name, name)) return a; } return nullptr; } static void showAddComponentNode(const StudioApp::AddCmpTreeNode* node, const char* filter) { if (!node) return; if (filter[0]) { if (!node->plugin) showAddComponentNode(node->child, filter); else if (stristr(node->plugin->getLabel(), filter)) node->plugin->onGUI(false, true); showAddComponentNode(node->next, filter); return; } if (node->plugin) { node->plugin->onGUI(true, false); showAddComponentNode(node->next, filter); return; } const char* last = reverseFind(node->label, nullptr, '/'); if (ImGui::BeginMenu(last ? last + 1 : node->label)) { showAddComponentNode(node->child, filter); ImGui::EndMenu(); } showAddComponentNode(node->next, filter); } void onCreateEntityWithComponentGUI() { doMenuItem(*getAction("createEntity"), true); ImGui::Separator(); ImGui::LabellessInputText("Filter", m_component_filter, sizeof(m_component_filter)); showAddComponentNode(m_add_cmp_root.child, m_component_filter); } void entityMenu() { if (!ImGui::BeginMenu("Entity")) return; const auto& selected_entities = m_editor->getSelectedEntities(); bool is_any_entity_selected = !selected_entities.empty(); if (ImGui::BeginMenu("Create")) { onCreateEntityWithComponentGUI(); ImGui::EndMenu(); } doMenuItem(*getAction("destroyEntity"), is_any_entity_selected); doMenuItem(*getAction("savePrefab"), selected_entities.size() == 1); doMenuItem(*getAction("makeParent"), selected_entities.size() == 2); bool can_unparent = selected_entities.size() == 1 && m_editor->getUniverse()->getParent(selected_entities[0]).isValid(); doMenuItem(*getAction("unparent"), can_unparent); ImGui::EndMenu(); } void editMenu() { if (!ImGui::BeginMenu("Edit")) return; bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); doMenuItem(*getAction("undo"), m_editor->canUndo()); doMenuItem(*getAction("redo"), m_editor->canRedo()); ImGui::Separator(); doMenuItem(*getAction("copy"), is_any_entity_selected); doMenuItem(*getAction("paste"), m_editor->canPasteEntities()); doMenuItem(*getAction("duplicate"), is_any_entity_selected); ImGui::Separator(); doMenuItem(*getAction("orbitCamera"), is_any_entity_selected || m_editor->isOrbitCamera()); doMenuItem(*getAction("setTranslateGizmoMode"), true); doMenuItem(*getAction("setRotateGizmoMode"), true); doMenuItem(*getAction("setScaleGizmoMode"), true); doMenuItem(*getAction("setPivotCenter"), true); doMenuItem(*getAction("setPivotOrigin"), true); doMenuItem(*getAction("setLocalCoordSystem"), true); doMenuItem(*getAction("setGlobalCoordSystem"), true); if (ImGui::BeginMenu("View", true)) { doMenuItem(*getAction("viewTop"), true); doMenuItem(*getAction("viewFront"), true); doMenuItem(*getAction("viewSide"), true); ImGui::EndMenu(); } ImGui::EndMenu(); } void fileMenu() { if (!ImGui::BeginMenu("File")) return; doMenuItem(*getAction("newUniverse"), true); if (ImGui::BeginMenu("Open")) { ImGui::LabellessInputText("Filter", m_open_filter, sizeof(m_open_filter)); for (auto& univ : m_universes) { if ((m_open_filter[0] == '\0' || stristr(univ.data, m_open_filter)) && ImGui::MenuItem(univ.data)) { if (m_editor->isUniverseChanged()) { copyString(m_universe_to_load, univ.data); m_confirm_load = true; } else { m_editor->loadUniverse(univ.data); setTitle(univ.data); } } } ImGui::EndMenu(); } doMenuItem(*getAction("save"), !m_editor->isGameMode()); doMenuItem(*getAction("saveAs"), !m_editor->isGameMode()); doMenuItem(*getAction("exit"), true); ImGui::EndMenu(); } void toolsMenu() { if (!ImGui::BeginMenu("Tools")) return; bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); doMenuItem(*getAction("setEditCamTransform"), true); doMenuItem(*getAction("lookAtSelected"), is_any_entity_selected); doMenuItem(*getAction("toggleGameMode"), true); doMenuItem(*getAction("toggleMeasure"), true); doMenuItem(*getAction("snapDown"), is_any_entity_selected); doMenuItem(*getAction("autosnapDown"), true); if (ImGui::MenuItem("Save commands")) saveUndoStack(); if (ImGui::MenuItem("Load commands")) loadAndExecuteCommands(); doMenuItem(*getAction("pack_data"), true); ImGui::EndMenu(); } void viewMenu() { if (!ImGui::BeginMenu("View")) return; ImGui::MenuItem("Asset browser", nullptr, &m_asset_browser->m_is_open); doMenuItem(*getAction("entityList"), true); ImGui::MenuItem("Log", nullptr, &m_log_ui->m_is_open); ImGui::MenuItem("Profiler", nullptr, &m_profiler_ui->m_is_open); ImGui::MenuItem("Properties", nullptr, &m_property_grid->m_is_open); doMenuItem(*getAction("settings"), true); ImGui::Separator(); for (Action* action : m_window_actions) { doMenuItem(*action, true); } ImGui::EndMenu(); } float showMainMenu() { if (m_confirm_exit) { ImGui::OpenPopup("confirm_exit"); m_confirm_exit = false; } if (ImGui::BeginPopupModal("confirm_exit")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { OS::quit(); m_finished = true; ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } if (m_confirm_new) { ImGui::OpenPopup("confirm_new"); m_confirm_new = false; } if (ImGui::BeginPopupModal("confirm_new")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { m_editor->newUniverse(); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } if (m_confirm_load) { ImGui::OpenPopup("Confirm"); m_confirm_load = false; } if (ImGui::BeginPopupModal("Confirm")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { m_editor->loadUniverse(m_universe_to_load); setTitle(m_universe_to_load); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } float menu_height = 0; ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); if (ImGui::BeginMainMenuBar()) { fileMenu(); editMenu(); entityMenu(); toolsMenu(); viewMenu(); StaticString<200> stats(""); if (m_engine->getFileSystem().hasWork()) stats << "Loading... | "; stats << "FPS: "; stats << m_engine->getFPS(); if (OS::getFocused() != m_window) stats << " - inactive window"; auto stats_size = ImGui::CalcTextSize(stats); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); ImGui::Text("%s", (const char*)stats); if (m_log_ui->getUnreadErrorCount() == 1) { ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); auto error_stats_size = ImGui::CalcTextSize("1 error | "); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x - error_stats_size.x); ImGui::TextColored(ImVec4(1, 0, 0, 1), "1 error | "); } else if (m_log_ui->getUnreadErrorCount() > 1) { StaticString<50> error_stats("", m_log_ui->getUnreadErrorCount(), " errors | "); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); auto error_stats_size = ImGui::CalcTextSize(error_stats); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x - error_stats_size.x); ImGui::TextColored(ImVec4(1, 0, 0, 1), "%s", (const char*)error_stats); } menu_height = ImGui::GetWindowSize().y; ImGui::EndMainMenuBar(); } ImGui::PopStyleVar(); return menu_height; } void showHierarchy(EntityRef entity, const Array<EntityRef>& selected_entities) { char buffer[1024]; Universe* universe = m_editor->getUniverse(); getEntityListDisplayName(*m_editor, buffer, sizeof(buffer), entity); bool selected = selected_entities.indexOf(entity) >= 0; ImGui::PushID(entity.index); ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_AllowItemOverlap; bool has_child = universe->getFirstChild(entity).isValid(); if (!has_child) flags = ImGuiTreeNodeFlags_Leaf; if (selected) flags |= ImGuiTreeNodeFlags_Selected; bool node_open = ImGui::TreeNodeEx(buffer, flags); if (ImGui::IsItemClicked(0)) m_editor->selectEntities(&entity, 1, true); if (ImGui::IsMouseReleased(1) && ImGui::IsItemHovered()) ImGui::OpenPopup("entity_context_menu"); if (ImGui::BeginPopup("entity_context_menu")) { if (ImGui::MenuItem("Create child")) { m_editor->beginCommandGroup(crc32("create_child_entity")); EntityRef child = m_editor->addEntity(); m_editor->makeParent(entity, child); const DVec3 pos = m_editor->getUniverse()->getPosition(entity); m_editor->setEntitiesPositions(&child, &pos, 1); m_editor->endCommandGroup(); } ImGui::EndPopup(); } ImGui::PopID(); if (ImGui::BeginDragDropSource()) { ImGui::Text("%s", buffer); ImGui::SetDragDropPayload("entity", &entity, sizeof(entity)); ImGui::EndDragDropSource(); } if (ImGui::BeginDragDropTarget()) { if (auto* payload = ImGui::AcceptDragDropPayload("entity")) { EntityRef dropped_entity = *(EntityRef*)payload->Data; if (dropped_entity != entity) { m_editor->makeParent(entity, dropped_entity); if (node_open) ImGui::TreePop(); return; } } ImGui::EndDragDropTarget(); } if (node_open) { for (EntityPtr e_ptr = universe->getFirstChild(entity); e_ptr.isValid(); e_ptr = universe->getNextSibling((EntityRef)e_ptr)) { showHierarchy((EntityRef)e_ptr, selected_entities); } ImGui::TreePop(); } } void onEditCameraGUI() { if (!m_is_edit_cam_transform_ui_open) return; if (ImGui::Begin("Edit camera")) { Viewport vp = m_editor->getViewport(); if (ImGui::DragScalarN("Position", ImGuiDataType_Double, &vp.pos.x, 3, 1.f)) { m_editor->setViewport(vp); } Vec3 angles = vp.rot.toEuler(); if (ImGui::DragFloat3("Rotation", &angles.x, 0.01f)) { vp.rot.fromEuler(angles); m_editor->setViewport(vp); } } ImGui::End(); } void onEntityListGUI() { PROFILE_FUNCTION(); const Array<EntityRef>& entities = m_editor->getSelectedEntities(); static char filter[64] = ""; if (!m_is_entity_list_open) return; if (ImGui::Begin("Entity List", &m_is_entity_list_open)) { auto* universe = m_editor->getUniverse(); ImGui::LabellessInputText("Filter", filter, sizeof(filter)); if (ImGui::BeginChild("entities")) { ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() - ImGui::GetStyle().FramePadding.x); if (filter[0] == '\0') { for (EntityPtr e = universe->getFirstEntity(); e.isValid(); e = universe->getNextEntity((EntityRef)e)) { const EntityRef e_ref = (EntityRef)e; if (!universe->getParent(e_ref).isValid()) { showHierarchy(e_ref, entities); } } } else { for (EntityPtr e = universe->getFirstEntity(); e.isValid(); e = universe->getNextEntity((EntityRef)e)) { char buffer[1024]; getEntityListDisplayName(*m_editor, buffer, sizeof(buffer), e); if (stristr(buffer, filter) == nullptr) continue; ImGui::PushID(e.index); const EntityRef e_ref = (EntityRef)e; bool selected = entities.indexOf(e_ref) >= 0; if (ImGui::Selectable(buffer, &selected)) { m_editor->selectEntities(&e_ref, 1, true); } if (ImGui::BeginDragDropSource()) { ImGui::Text("%s", buffer); ImGui::SetDragDropPayload("entity", &e, sizeof(e)); ImGui::EndDragDropSource(); } ImGui::PopID(); } } ImGui::PopItemWidth(); } ImGui::EndChild(); // TODO uncomment once it's fixed in imgui /*if (ImGui::BeginDragDropTarget()) { if (auto* payload = ImGui::AcceptDragDropPayload("entity")) { EntityRef dropped_entity = *(EntityRef*)payload->Data; m_editor->makeParent(INVALID_ENTITY, dropped_entity); } ImGui::EndDragDropTarget(); }*/ } ImGui::End(); } void dummy() {} void setFullscreen(bool fullscreen) override { ASSERT(false); // TODO // SDL_SetWindowFullscreen(m_window, fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0); } void saveSettings() { m_settings.m_is_asset_browser_open = m_asset_browser->m_is_open; m_settings.m_asset_browser_left_column_width = m_asset_browser->m_left_column_width; m_settings.m_is_entity_list_open = m_is_entity_list_open; m_settings.m_is_log_open = m_log_ui->m_is_open; m_settings.m_is_profiler_open = m_profiler_ui->m_is_open; m_settings.m_is_properties_open = m_property_grid->m_is_open; m_settings.m_mouse_sensitivity.x = m_editor->getMouseSensitivity().x; m_settings.m_mouse_sensitivity.y = m_editor->getMouseSensitivity().y; m_settings.save(); } void initIMGUI() { ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard | ImGuiConfigFlags_DockingEnable; const int dpi = OS::getDPI(); float font_scale = dpi / 96.f; m_font = io.Fonts->AddFontFromFileTTF( "editor/fonts/OpenSans-Regular.ttf", (float)m_settings.m_font_size * font_scale); m_bold_font = io.Fonts->AddFontFromFileTTF("editor/fonts/OpenSans-Bold.ttf", (float)m_settings.m_font_size * font_scale); m_font->DisplayOffset.y = 0; m_bold_font->DisplayOffset.y = 0; io.KeyMap[ImGuiKey_Space] = (int)OS::Keycode::SPACE; io.KeyMap[ImGuiKey_Tab] = (int)OS::Keycode::TAB; io.KeyMap[ImGuiKey_LeftArrow] = (int)OS::Keycode::LEFT; io.KeyMap[ImGuiKey_RightArrow] = (int)OS::Keycode::RIGHT; io.KeyMap[ImGuiKey_UpArrow] = (int)OS::Keycode::UP; io.KeyMap[ImGuiKey_DownArrow] = (int)OS::Keycode::DOWN; io.KeyMap[ImGuiKey_PageUp] = (int)OS::Keycode::PAGEUP; io.KeyMap[ImGuiKey_PageDown] = (int)OS::Keycode::PAGEDOWN; io.KeyMap[ImGuiKey_Home] = (int)OS::Keycode::HOME; io.KeyMap[ImGuiKey_End] = (int)OS::Keycode::END; io.KeyMap[ImGuiKey_Delete] = (int)OS::Keycode::DEL; io.KeyMap[ImGuiKey_Backspace] = (int)OS::Keycode::BACKSPACE; io.KeyMap[ImGuiKey_Enter] = (int)OS::Keycode::RETURN; io.KeyMap[ImGuiKey_Escape] = (int)OS::Keycode::ESCAPE; io.KeyMap[ImGuiKey_A] = (int)OS::Keycode::A; io.KeyMap[ImGuiKey_C] = (int)OS::Keycode::C; io.KeyMap[ImGuiKey_V] = (int)OS::Keycode::V; io.KeyMap[ImGuiKey_X] = (int)OS::Keycode::X; io.KeyMap[ImGuiKey_Y] = (int)OS::Keycode::Y; io.KeyMap[ImGuiKey_Z] = (int)OS::Keycode::Z; ImGuiStyle& style = ImGui::GetStyle(); style.FramePadding.y = 0; style.ItemSpacing.y = 2; style.ItemInnerSpacing.x = 2; } void loadSettings() { char cmd_line[2048]; OS::getCommandLine(cmd_line, lengthOf(cmd_line)); CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-no_crash_report")) continue; m_settings.m_force_no_crash_report = true; break; } m_settings.load(); m_asset_browser->m_is_open = m_settings.m_is_asset_browser_open; m_asset_browser->m_left_column_width = m_settings.m_asset_browser_left_column_width; m_is_entity_list_open = m_settings.m_is_entity_list_open; m_log_ui->m_is_open = m_settings.m_is_log_open; m_profiler_ui->m_is_open = m_settings.m_is_profiler_open; m_property_grid->m_is_open = m_settings.m_is_properties_open; if (m_settings.m_is_maximized) { OS::maximizeWindow(m_window); } else if (m_settings.m_window.w > 0) { OS::Rect r; r.left = m_settings.m_window.x; r.top = m_settings.m_window.y; r.width = m_settings.m_window.w; r.height = m_settings.m_window.h; OS::setWindowScreenRect(m_window, r); } } void addActions() { addAction<&StudioAppImpl::newUniverse>("New", "New universe", "newUniverse"); addAction<&StudioAppImpl::save>( "Save", "Save universe", "save", OS::Keycode::LCTRL, OS::Keycode::S, OS::Keycode::INVALID); addAction<&StudioAppImpl::saveAs>( "Save As", "Save universe as", "saveAs", OS::Keycode::LCTRL, OS::Keycode::LSHIFT, OS::Keycode::S); addAction<&StudioAppImpl::exit>( "Exit", "Exit Studio", "exit", OS::Keycode::LCTRL, OS::Keycode::X, OS::Keycode::INVALID); addAction<&StudioAppImpl::redo>( "Redo", "Redo scene action", "redo", OS::Keycode::LCTRL, OS::Keycode::LSHIFT, OS::Keycode::Z); addAction<&StudioAppImpl::undo>( "Undo", "Undo scene action", "undo", OS::Keycode::LCTRL, OS::Keycode::Z, OS::Keycode::INVALID); addAction<&StudioAppImpl::copy>( "Copy", "Copy entity", "copy", OS::Keycode::LCTRL, OS::Keycode::C, OS::Keycode::INVALID); addAction<&StudioAppImpl::paste>( "Paste", "Paste entity", "paste", OS::Keycode::LCTRL, OS::Keycode::V, OS::Keycode::INVALID); addAction<&StudioAppImpl::duplicate>( "Duplicate", "Duplicate entity", "duplicate", OS::Keycode::LCTRL, OS::Keycode::D, OS::Keycode::INVALID); addAction<&StudioAppImpl::toggleOrbitCamera>("Orbit camera", "Orbit camera", "orbitCamera") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isOrbitCamera>(this); addAction<&StudioAppImpl::setTranslateGizmoMode>("Translate", "Set translate mode", "setTranslateGizmoMode") .is_selected.bind<Gizmo, &Gizmo::isTranslateMode>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setRotateGizmoMode>("Rotate", "Set rotate mode", "setRotateGizmoMode") .is_selected.bind<Gizmo, &Gizmo::isRotateMode>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setScaleGizmoMode>("Scale", "Set scale mode", "setScaleGizmoMode") .is_selected.bind<Gizmo, &Gizmo::isScaleMode>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setTopView>("Top", "Set top camera view", "viewTop"); addAction<&StudioAppImpl::setFrontView>("Front", "Set front camera view", "viewFront"); addAction<&StudioAppImpl::setSideView>("Side", "Set side camera view", "viewSide"); addAction<&StudioAppImpl::setLocalCoordSystem>("Local", "Set local transform system", "setLocalCoordSystem") .is_selected.bind<Gizmo, &Gizmo::isLocalCoordSystem>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setGlobalCoordSystem>("Global", "Set global transform system", "setGlobalCoordSystem") .is_selected.bind<Gizmo, &Gizmo::isGlobalCoordSystem>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setPivotCenter>("Center", "Set center transform system", "setPivotCenter") .is_selected.bind<Gizmo, &Gizmo::isPivotCenter>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setPivotOrigin>("Pivot", "Set pivot transform system", "setPivotOrigin") .is_selected.bind<Gizmo, &Gizmo::isPivotOrigin>(&m_editor->getGizmo()); addAction<&StudioAppImpl::addEntity>("Create empty", "Create empty entity", "createEntity"); addAction<&StudioAppImpl::destroySelectedEntity>("Destroy", "Destroy entity", "destroyEntity", OS::Keycode::DEL, OS::Keycode::INVALID, OS::Keycode::INVALID); addAction<&StudioAppImpl::savePrefab>("Save prefab", "Save selected entities as prefab", "savePrefab"); addAction<&StudioAppImpl::makeParent>("Make parent", "Make entity parent", "makeParent"); addAction<&StudioAppImpl::unparent>("Unparent", "Unparent entity", "unparent"); addAction<&StudioAppImpl::toggleGameMode>("Game Mode", "Toggle game mode", "toggleGameMode") .is_selected.bind<WorldEditor, &WorldEditor::isGameMode>(m_editor); addAction<&StudioAppImpl::toggleMeasure>("Toggle measure", "Toggle measure mode", "toggleMeasure") .is_selected.bind<WorldEditor, &WorldEditor::isMeasureToolActive>(m_editor); addAction<&StudioAppImpl::autosnapDown>("Autosnap down", "Toggle autosnap down", "autosnapDown") .is_selected.bind<Gizmo, &Gizmo::isAutosnapDown>(&m_editor->getGizmo()); addAction<&StudioAppImpl::snapDown>("Snap down", "Snap entities down", "snapDown"); addAction<&StudioAppImpl::setEditCamTransform>("Camera transform", "Set camera transformation", "setEditCamTransform"); addAction<&StudioAppImpl::lookAtSelected>("Look at selected", "Look at selected entity", "lookAtSelected"); addAction<&StudioAppImpl::toggleAssetBrowser>("Asset Browser", "Toggle asset browser", "assetBrowser") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isAssetBrowserOpen>(this); addAction<&StudioAppImpl::toggleEntityList>("Entity List", "Toggle entity list", "entityList") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isEntityListOpen>(this); addAction<&StudioAppImpl::toggleSettings>("Settings", "Toggle settings UI", "settings") .is_selected.bind<StudioAppImpl, &StudioAppImpl::areSettingsOpen>(this); addAction<&StudioAppImpl::showPackDataDialog>("Pack data", "Pack data", "pack_data"); } static bool copyPlugin(const char* src, int iteration, char (&out)[MAX_PATH_LENGTH]) { char tmp_path[MAX_PATH_LENGTH]; OS::getExecutablePath(tmp_path, lengthOf(tmp_path)); StaticString<MAX_PATH_LENGTH> copy_path; PathUtils::getDir(copy_path.data, lengthOf(copy_path.data), tmp_path); copy_path << "plugins/" << iteration; OS::makePath(copy_path); PathUtils::getBasename(tmp_path, lengthOf(tmp_path), src); copy_path << "/" << tmp_path << "." << getPluginExtension(); #ifdef _WIN32 StaticString<MAX_PATH_LENGTH> src_pdb(src); StaticString<MAX_PATH_LENGTH> dest_pdb(copy_path); if (PathUtils::replaceExtension(dest_pdb.data, "pdb") && PathUtils::replaceExtension(src_pdb.data, "pda")) { OS::deleteFile(dest_pdb); if (!OS::copyFile(src_pdb, dest_pdb)) { copyString(out, src); return false; } } #endif OS::deleteFile(copy_path); if (!OS::copyFile(src, copy_path)) { copyString(out, src); return false; } copyString(out, copy_path); return true; } void loadUserPlugins() { char cmd_line[2048]; OS::getCommandLine(cmd_line, lengthOf(cmd_line)); CommandLineParser parser(cmd_line); auto& plugin_manager = m_editor->getEngine().getPluginManager(); while (parser.next()) { if (!parser.currentEquals("-plugin")) continue; if (!parser.next()) break; char src[MAX_PATH_LENGTH]; parser.getCurrent(src, lengthOf(src)); bool is_full_path = findSubstring(src, ".") != nullptr; Lumix::IPlugin* loaded_plugin; if (is_full_path) { char copy_path[MAX_PATH_LENGTH]; copyPlugin(src, 0, copy_path); loaded_plugin = plugin_manager.load(copy_path); } else { loaded_plugin = plugin_manager.load(src); } if (!loaded_plugin) { g_log_error.log("Editor") << "Could not load plugin " << src << " requested by command line"; } else if (is_full_path && !m_watched_plugin.watcher) { char dir[MAX_PATH_LENGTH]; char basename[MAX_PATH_LENGTH]; PathUtils::getBasename(basename, lengthOf(basename), src); m_watched_plugin.basename = basename; PathUtils::getDir(dir, lengthOf(dir), src); m_watched_plugin.watcher = FileSystemWatcher::create(dir, m_allocator); m_watched_plugin.watcher->getCallback().bind<StudioAppImpl, &StudioAppImpl::onPluginChanged>(this); m_watched_plugin.dir = dir; m_watched_plugin.plugin = loaded_plugin; } } } static const char* getPluginExtension() { const char* ext = #ifdef _WIN32 "dll"; #elif defined __linux__ "so"; #else #error Unknown platform #endif return ext; } void onPluginChanged(const char* path) { const char* ext = getPluginExtension(); if (!PathUtils::hasExtension(path, ext) #ifdef _WIN32 && !PathUtils::hasExtension(path, "pda") #endif ) return; char basename[MAX_PATH_LENGTH]; PathUtils::getBasename(basename, lengthOf(basename), path); if (!equalIStrings(basename, m_watched_plugin.basename)) return; m_watched_plugin.reload_request = true; } void tryReloadPlugin() { m_watched_plugin.reload_request = false; StaticString<MAX_PATH_LENGTH> src(m_watched_plugin.dir, m_watched_plugin.basename, ".", getPluginExtension()); char copy_path[MAX_PATH_LENGTH]; ++m_watched_plugin.iteration; if (!copyPlugin(src, m_watched_plugin.iteration, copy_path)) return; g_log_info.log("Editor") << "Trying to reload plugin " << m_watched_plugin.basename; OutputBlob blob(m_allocator); blob.reserve(16 * 1024); PluginManager& plugin_manager = m_editor->getEngine().getPluginManager(); void* lib = plugin_manager.getLibrary(m_watched_plugin.plugin); Universe* universe = m_editor->getUniverse(); for (IScene* scene : universe->getScenes()) { if (&scene->getPlugin() != m_watched_plugin.plugin) continue; if (m_editor->isGameMode()) scene->stopGame(); scene->serialize(blob); universe->removeScene(scene); scene->getPlugin().destroyScene(scene); } plugin_manager.unload(m_watched_plugin.plugin); // TODO try to delete the old version m_watched_plugin.plugin = plugin_manager.load(copy_path); if (!m_watched_plugin.plugin) { g_log_error.log("Editor") << "Failed to load plugin " << copy_path << ". Reload failed."; return; } InputBlob input_blob(blob); m_watched_plugin.plugin->createScenes(*universe); for (IScene* scene : universe->getScenes()) { if (&scene->getPlugin() != m_watched_plugin.plugin) continue; scene->deserialize(input_blob); if (m_editor->isGameMode()) scene->startGame(); } g_log_info.log("Editor") << "Finished reloading plugin."; } bool shouldSleepWhenInactive() { char cmd_line[2048]; OS::getCommandLine(cmd_line, lengthOf(cmd_line)); CommandLineParser parser(cmd_line); while (parser.next()) { if (parser.currentEquals("-no_sleep_inactive")) return false; } return true; } void loadUniverseFromCommandLine() { char cmd_line[2048]; char path[MAX_PATH_LENGTH]; OS::getCommandLine(cmd_line, lengthOf(cmd_line)); CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-open")) continue; if (!parser.next()) break; parser.getCurrent(path, lengthOf(path)); m_editor->loadUniverse(path); setTitle(path); m_is_welcome_screen_open = false; break; } } static void checkDataDirCommandLine(char* dir, int max_size) { char cmd_line[2048]; OS::getCommandLine(cmd_line, lengthOf(cmd_line)); CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-data_dir")) continue; if (!parser.next()) break; parser.getCurrent(dir, max_size); break; } } GUIPlugin* getPlugin(const char* name) override { for (auto* i : m_gui_plugins) { if (equalStrings(i->getName(), name)) return i; } return nullptr; } void initPlugins() override { for (int i = 1, c = m_plugins.size(); i < c; ++i) { for (int j = 0; j < i; ++j) { IPlugin* p = m_plugins[i]; if (m_plugins[j]->dependsOn(*p)) { m_plugins.erase(i); --i; m_plugins.insert(j, p); } } } for (IPlugin* plugin : m_plugins) { plugin->init(); } } void addPlugin(IPlugin& plugin) override { m_plugins.push(&plugin); } void addPlugin(GUIPlugin& plugin) override { m_gui_plugins.push(&plugin); for (auto* i : m_gui_plugins) { i->pluginAdded(plugin); plugin.pluginAdded(*i); } } void removePlugin(GUIPlugin& plugin) override { m_gui_plugins.eraseItemFast(&plugin); } void setStudioApp() { #ifdef STATIC_PLUGINS StudioApp::StaticPluginRegister::create(*this); #else auto& plugin_manager = m_editor->getEngine().getPluginManager(); for (auto* lib : plugin_manager.getLibraries()) { auto* f = (StudioApp::IPlugin * (*)(StudioApp&)) getLibrarySymbol(lib, "setStudioApp"); if (f) { StudioApp::IPlugin* plugin = f(*this); addPlugin(*plugin); } } #endif PrefabSystem::createEditorPlugins(*this, m_editor->getPrefabSystem()); } void runScript(const char* src, const char* script_name) override { lua_State* L = m_engine->getState(); bool errors = luaL_loadbuffer(L, src, stringLength(src), script_name) != 0; errors = errors || lua_pcall(L, 0, 0, 0) != 0; if (errors) { g_log_error.log("Editor") << script_name << ": " << lua_tostring(L, -1); lua_pop(L, 1); } } void savePrefabAs(const char* path) { m_editor->getPrefabSystem().savePrefab(Path(path)); } void destroyEntity(EntityRef e) { m_editor->destroyEntities(&e, 1); } void selectEntity(EntityRef e) { m_editor->selectEntities(&e, 1, false); } EntityRef createEntity() { return m_editor->addEntity(); } void createComponent(EntityRef e, int type) { m_editor->selectEntities(&e, 1, false); m_editor->addComponent({type}); } void exitGameMode() { m_deferred_game_mode_exit = true; } void exitWithCode(int exit_code) { OS::quit(); m_finished = true; m_exit_code = exit_code; } struct SetPropertyVisitor : public Reflection::IPropertyVisitor { void visit(const Reflection::Property<int>& prop) override { if (!equalStrings(property_name, prop.name)) return; if (!lua_isnumber(L, -1)) return; int val = (int)lua_tointeger(L, -1); editor->setProperty(cmp_type, 0, prop, &entity, 1, &val, sizeof(val)); } // TODO void visit(const Reflection::Property<float>& prop) override { notSupported(prop); } void visit(const Reflection::Property<EntityPtr>& prop) override { notSupported(prop); } void visit(const Reflection::Property<IVec2>& prop) override { notSupported(prop); } void visit(const Reflection::Property<Vec2>& prop) override { notSupported(prop); } void visit(const Reflection::Property<Vec3>& prop) override { notSupported(prop); } void visit(const Reflection::Property<Vec4>& prop) override { notSupported(prop); } void visit(const Reflection::Property<const char*>& prop) override { if (!equalStrings(property_name, prop.name)) return; if (!lua_isstring(L, -1)) return; const char* str = lua_tostring(L, -1); editor->setProperty(cmp_type, 0, prop, &entity, 1, str, stringLength(str) + 1); } void visit(const Reflection::Property<Path>& prop) override { if (!equalStrings(property_name, prop.name)) return; if (!lua_isstring(L, -1)) return; const char* str = lua_tostring(L, -1); editor->setProperty(cmp_type, 0, prop, &entity, 1, str, stringLength(str) + 1); } void visit(const Reflection::Property<bool>& prop) override { if (!equalStrings(property_name, prop.name)) return; if (!lua_isboolean(L, -1)) return; bool val = lua_toboolean(L, -1) != 0; editor->setProperty(cmp_type, 0, prop, &entity, 1, &val, sizeof(val)); } void visit(const Reflection::IArrayProperty& prop) override { notSupported(prop); } void visit(const Reflection::IEnumProperty& prop) override { notSupported(prop); } void visit(const Reflection::IBlobProperty& prop) override { notSupported(prop); } void visit(const Reflection::ISampledFuncProperty& prop) override { notSupported(prop); } void notSupported(const Reflection::PropertyBase& prop) { if (!equalStrings(property_name, prop.name)) return; g_log_error.log("Lua Script") << "Property " << prop.name << " has unsupported type"; } lua_State* L; EntityRef entity; ComponentType cmp_type; const char* property_name; WorldEditor* editor; }; static int createEntityEx(lua_State* L) { auto* studio = LuaWrapper::checkArg<StudioAppImpl*>(L, 1); LuaWrapper::checkTableArg(L, 2); WorldEditor& editor = *studio->m_editor; editor.beginCommandGroup(crc32("createEntityEx")); EntityRef e = editor.addEntity(); editor.selectEntities(&e, 1, false); lua_pushvalue(L, 2); lua_pushnil(L); while (lua_next(L, -2) != 0) { const char* parameter_name = luaL_checkstring(L, -2); if (equalStrings(parameter_name, "position")) { const DVec3 pos = LuaWrapper::toType<DVec3>(L, -1); editor.setEntitiesPositions(&e, &pos, 1); } else if (equalStrings(parameter_name, "rotation")) { const Quat rot = LuaWrapper::toType<Quat>(L, -1); editor.setEntitiesRotations(&e, &rot, 1); } else { ComponentType cmp_type = Reflection::getComponentType(parameter_name); editor.addComponent(cmp_type); IScene* scene = editor.getUniverse()->getScene(cmp_type); if (scene) { ComponentUID cmp(e, cmp_type, scene); const Reflection::ComponentBase* cmp_des = Reflection::getComponent(cmp_type); if (cmp.isValid()) { lua_pushvalue(L, -1); lua_pushnil(L); while (lua_next(L, -2) != 0) { const char* property_name = luaL_checkstring(L, -2); SetPropertyVisitor v; v.property_name = property_name; v.entity = (EntityRef)cmp.entity; v.cmp_type = cmp.type; v.L = L; v.editor = &editor; cmp_des->visit(v); lua_pop(L, 1); } lua_pop(L, 1); } } } lua_pop(L, 1); } lua_pop(L, 1); editor.endCommandGroup(); LuaWrapper::push(L, e); return 1; } static int getResources(lua_State* L) { auto* studio = LuaWrapper::checkArg<StudioAppImpl*>(L, 1); auto* type = LuaWrapper::checkArg<const char*>(L, 2); AssetCompiler& compiler = studio->getAssetCompiler(); if (ResourceType(type) == INVALID_RESOURCE_TYPE) return 0; auto& resources_paths = compiler.getResources(ResourceType(type)); lua_createtable(L, resources_paths.size(), 0); int i = 0; for (auto& path : resources_paths) { LuaWrapper::push(L, path.c_str()); lua_rawseti(L, -2, i + 1); ++i; } return 1; } void executeUndoStack(const char* path) { m_editor->executeUndoStack(Path(path)); } void saveUniverseAs(const char* basename, bool save_path) { m_editor->saveUniverse(basename, save_path); } void saveUniverse() { save(); } bool runTest(const char* dir, const char* name) { return m_editor->runTest(dir, name); } void createLua() { lua_State* L = m_engine->getState(); LuaWrapper::createSystemVariable(L, "Editor", "editor", this); #define REGISTER_FUNCTION(F) \ do \ { \ auto f = &LuaWrapper::wrapMethodClosure<StudioAppImpl, decltype(&StudioAppImpl::F), &StudioAppImpl::F>; \ LuaWrapper::createSystemClosure(L, "Editor", this, #F, f); \ } while (false) REGISTER_FUNCTION(savePrefabAs); REGISTER_FUNCTION(selectEntity); REGISTER_FUNCTION(createEntity); REGISTER_FUNCTION(createComponent); REGISTER_FUNCTION(destroyEntity); REGISTER_FUNCTION(newUniverse); REGISTER_FUNCTION(saveUniverse); REGISTER_FUNCTION(saveUniverseAs); REGISTER_FUNCTION(runTest); REGISTER_FUNCTION(executeUndoStack); REGISTER_FUNCTION(exitWithCode); REGISTER_FUNCTION(exitGameMode); #undef REGISTER_FUNCTION LuaWrapper::createSystemFunction(L, "Editor", "getResources", &getResources); LuaWrapper::createSystemFunction(L, "Editor", "createEntityEx", &createEntityEx); } void checkScriptCommandLine() { char command_line[1024]; OS::getCommandLine(command_line, lengthOf(command_line)); CommandLineParser parser(command_line); while (parser.next()) { if (parser.currentEquals("-run_script")) { if (!parser.next()) break; char tmp[MAX_PATH_LENGTH]; parser.getCurrent(tmp, lengthOf(tmp)); FS::OsFile file; if (file.open(tmp, FS::Mode::OPEN_AND_READ)) { auto size = file.size(); auto* src = (char*)m_allocator.allocate(size + 1); file.read(src, size); src[size] = 0; runScript((const char*)src, tmp); m_allocator.deallocate(src); file.close(); } else { g_log_error.log("Editor") << "Could not open " << tmp; } break; } } } static bool includeFileInPack(const char* filename) { if (filename[0] == '.') return false; if (compareStringN("bin/", filename, 4) == 0) return false; if (compareStringN("bin32/", filename, 4) == 0) return false; if (equalStrings("data.pak", filename)) return false; if (equalStrings("error.log", filename)) return false; return true; } static bool includeDirInPack(const char* filename) { if (filename[0] == '.') return false; if (compareStringN("bin", filename, 4) == 0) return false; if (compareStringN("bin32", filename, 4) == 0) return false; return true; } #pragma pack(1) struct PackFileInfo { u32 hash; u64 offset; u64 size; char path[MAX_PATH_LENGTH]; }; #pragma pack() void packDataScan(const char* dir_path, AssociativeArray<u32, PackFileInfo>& infos) { auto* iter = OS::createFileIterator(dir_path, m_allocator); OS::FileInfo info; while (OS::getNextFile(iter, &info)) { char normalized_path[MAX_PATH_LENGTH]; PathUtils::normalize(info.filename, normalized_path, lengthOf(normalized_path)); if (info.is_directory) { if (!includeDirInPack(normalized_path)) continue; char dir[MAX_PATH_LENGTH] = {0}; if (dir_path[0] != '.') copyString(dir, dir_path); catString(dir, info.filename); catString(dir, "/"); packDataScan(dir, infos); continue; } if (!includeFileInPack(normalized_path)) continue; StaticString<MAX_PATH_LENGTH> out_path; if (dir_path[0] == '.') { copyString(out_path.data, normalized_path); } else { copyString(out_path.data, dir_path); catString(out_path.data, normalized_path); } u32 hash = crc32(out_path.data); if (infos.find(hash) >= 0) continue; auto& out_info = infos.emplace(hash); copyString(out_info.path, out_path); out_info.hash = hash; out_info.size = OS::getFileSize(out_path.data); out_info.offset = ~0UL; } OS::destroyFileIterator(iter); } void packDataScanResources(AssociativeArray<u32, PackFileInfo>& infos) { ResourceManagerHub& rm = m_editor->getEngine().getResourceManager(); for (auto iter = rm.getAll().begin(), end = rm.getAll().end(); iter != end; ++iter) { const auto& resources = iter.value()->getResourceTable(); for (Resource* res : resources) { u32 hash = crc32(res->getPath().c_str()); auto& out_info = infos.emplace(hash); copyString(out_info.path, MAX_PATH_LENGTH, res->getPath().c_str()); out_info.hash = hash; out_info.size = OS::getFileSize(res->getPath().c_str()); out_info.offset = ~0UL; } } packDataScan("pipelines/", infos); StaticString<MAX_PATH_LENGTH> unv_path; unv_path << "universes/" << m_editor->getUniverse()->getName() << "/"; packDataScan(unv_path, infos); unv_path.data[0] = 0; unv_path << "universes/" << m_editor->getUniverse()->getName() << ".unv"; u32 hash = crc32(unv_path); auto& out_info = infos.emplace(hash); copyString(out_info.path, MAX_PATH_LENGTH, unv_path); out_info.hash = hash; out_info.size = OS::getFileSize(unv_path); out_info.offset = ~0UL; } void showPackDataDialog() { m_is_pack_data_dialog_open = true; } void onPackDataGUI() { if (!m_is_pack_data_dialog_open) return; if (ImGui::Begin("Pack data", &m_is_pack_data_dialog_open)) { ImGui::LabelText("Destination dir", "%s", m_pack.dest_dir.data); ImGui::SameLine(); if (ImGui::Button("Choose dir")) { if (OS::getOpenDirectory(m_pack.dest_dir.data, lengthOf(m_pack.dest_dir.data), ".")) { m_pack.dest_dir << "/"; } } ImGui::Combo("Mode", (int*)&m_pack.mode, "All files\0Loaded universe\0"); if (ImGui::Button("Pack")) packData(); } ImGui::End(); } void packData() { if (m_pack.dest_dir.empty()) return; char dest[MAX_PATH_LENGTH]; static const char* OUT_FILENAME = "data.pak"; copyString(dest, m_pack.dest_dir); catString(dest, OUT_FILENAME); AssociativeArray<u32, PackFileInfo> infos(m_allocator); infos.reserve(10000); switch (m_pack.mode) { case PackConfig::Mode::ALL_FILES: packDataScan("./", infos); break; case PackConfig::Mode::CURRENT_UNIVERSE: packDataScanResources(infos); break; default: ASSERT(false); break; } if (infos.size() == 0) { g_log_error.log("Editor") << "No files found while trying to create " << dest; return; } FS::OsFile file; if (!file.open(dest, FS::Mode::CREATE_AND_WRITE)) { g_log_error.log("Editor") << "Could not create " << dest; return; } int count = infos.size(); file.write(&count, sizeof(count)); u64 offset = sizeof(count) + (sizeof(u32) + sizeof(u64) * 2) * count; for (auto& info : infos) { info.offset = offset; offset += info.size; } for (auto& info : infos) { file.write(&info.hash, sizeof(info.hash)); file.write(&info.offset, sizeof(info.offset)); file.write(&info.size, sizeof(info.size)); } for (auto& info : infos) { FS::OsFile src; size_t src_size = OS::getFileSize(info.path); if (!src.open(info.path, FS::Mode::OPEN_AND_READ)) { file.close(); g_log_error.log("Editor") << "Could not open " << info.path; return; } u8 buf[4096]; for (; src_size > 0; src_size -= Math::minimum(sizeof(buf), src_size)) { size_t batch_size = Math::minimum(sizeof(buf), src_size); if (!src.read(buf, batch_size)) { file.close(); g_log_error.log("Editor") << "Could not read " << info.path; return; } file.write(buf, batch_size); } src.close(); } file.close(); const char* bin_files[] = {"app.exe", "dbghelp.dll", "dbgcore.dll"}; StaticString<MAX_PATH_LENGTH> src_dir("bin/"); if (!OS::fileExists("bin/app.exe")) { char tmp[MAX_PATH_LENGTH]; OS::getExecutablePath(tmp, lengthOf(tmp)); PathUtils::getDir(src_dir.data, lengthOf(src_dir.data), tmp); } for (auto& file : bin_files) { StaticString<MAX_PATH_LENGTH> tmp(m_pack.dest_dir, file); StaticString<MAX_PATH_LENGTH> src(src_dir, file); if (!OS::copyFile(src, tmp)) { g_log_error.log("Editor") << "Failed to copy " << src << " to " << tmp; } } for (GUIPlugin* plugin : m_gui_plugins) { if (!plugin->packData(m_pack.dest_dir)) { g_log_error.log("Editor") << "Plugin " << plugin->getName() << " failed to pack data."; } } } void loadLuaPlugin(const char* dir, const char* filename) { StaticString<MAX_PATH_LENGTH> path(dir, filename); FS::OsFile file; if (file.open(path, FS::Mode::OPEN_AND_READ)) { const int size = (int)file.size(); Array<u8> src(m_engine->getAllocator()); src.resize(size + 1); file.read(src.begin(), size); src[size] = 0; LuaPlugin* plugin = LUMIX_NEW(m_editor->getAllocator(), LuaPlugin)(*this, (const char*)src.begin(), filename); addPlugin(*plugin); file.close(); } else { g_log_warning.log("Editor") << "Failed to open " << path; } } void scanUniverses() { m_universes.clear(); auto* iter = OS::createFileIterator("universes/", m_allocator); OS::FileInfo info; while (OS::getNextFile(iter, &info)) { if (info.filename[0] == '.') continue; if (!info.is_directory) continue; if (startsWith(info.filename, "__")) continue; char basename[MAX_PATH_LENGTH]; PathUtils::getBasename(basename, lengthOf(basename), info.filename); m_universes.emplace(basename); } OS::destroyFileIterator(iter); } void findLuaPlugins(const char* dir) { auto* iter = OS::createFileIterator(dir, m_allocator); OS::FileInfo info; while (OS::getNextFile(iter, &info)) { char normalized_path[MAX_PATH_LENGTH]; PathUtils::normalize(info.filename, normalized_path, lengthOf(normalized_path)); if (normalized_path[0] == '.') continue; if (info.is_directory) { char dir_path[MAX_PATH_LENGTH] = {0}; if (dir[0] != '.') copyString(dir_path, dir); catString(dir_path, info.filename); catString(dir_path, "/"); findLuaPlugins(dir_path); } else { char ext[5]; PathUtils::getExtension(ext, lengthOf(ext), info.filename); if (equalStrings(ext, "lua")) { loadLuaPlugin(dir, info.filename); } } } OS::destroyFileIterator(iter); } const OS::Event* getEvents() const override { return m_events.empty() ? nullptr : &m_events[0]; } int getEventsCount() const override { return m_events.size(); } Vec2 getMouseMove() const override { return m_mouse_move; } void run() override {} static void checkWorkingDirector() { if (!OS::fileExists("../LumixStudio.lnk")) return; if (!OS::dirExists("bin") && OS::dirExists("../bin") && OS::dirExists("../pipelines")) { OS::setCurrentDirectory("../"); } if (!OS::dirExists("bin")) { OS::messageBox("Bin directory not found, please check working directory."); } else if (!OS::dirExists("pipelines")) { OS::messageBox("Pipelines directory not found, please check working directory."); } } void unloadIcons() { auto& render_interface = *m_editor->getRenderInterface(); for (auto* action : m_actions) { render_interface.unloadTexture(action->icon); } } void loadIcons() { RenderInterface& render_interface = *m_editor->getRenderInterface(); for (auto* action : m_actions) { char tmp[MAX_PATH_LENGTH]; action->getIconPath(tmp, lengthOf(tmp)); if (OS::fileExists(tmp)) { action->icon = render_interface.loadTexture(Path(tmp)); } else { action->icon = nullptr; } } } void checkShortcuts() { if (ImGui::IsAnyItemActive()) return; GUIPlugin* plugin = getFocusedPlugin(); u32 pressed_modifiers = 0; if (OS::isKeyDown(OS::Keycode::SHIFT)) pressed_modifiers |= 1; if (OS::isKeyDown(OS::Keycode::CTRL)) pressed_modifiers |= 2; if (OS::isKeyDown(OS::Keycode::MENU)) pressed_modifiers |= 4; for (Action* a : m_actions) { if (!a->is_global || a->shortcut[0] == OS::Keycode::INVALID) continue; if (a->plugin != plugin) continue; u32 action_modifiers = 0; for (int i = 0; i < lengthOf(a->shortcut) + 1; ++i) { if ((i == lengthOf(a->shortcut) || a->shortcut[i] == OS::Keycode::INVALID) && action_modifiers == pressed_modifiers) { a->func.invoke(); return; } if (i == lengthOf(a->shortcut)) break; if (a->shortcut[i] == OS::Keycode::INVALID) break; if (!OS::isKeyDown(a->shortcut[i])) break; if (a->shortcut[i] == OS::Keycode::CTRL) action_modifiers |= 2; else if (a->shortcut[i] == OS::Keycode::MENU) action_modifiers |= 4; else if (a->shortcut[i] == OS::Keycode::SHIFT) action_modifiers |= 1; } } } void* getWindow() override { return m_window; } WorldEditor& getWorldEditor() override { ASSERT(m_editor); return *m_editor; } ImFont* getBoldFont() override { return m_bold_font; } DefaultAllocator m_main_allocator; Debug::Allocator m_allocator; Engine* m_engine; OS::WindowHandle m_window; Array<Action*> m_actions; Array<Action*> m_window_actions; Array<Action*> m_toolbar_actions; Array<GUIPlugin*> m_gui_plugins; Array<IPlugin*> m_plugins; Array<IAddComponentPlugin*> m_add_cmp_plugins; Array<StaticString<MAX_PATH_LENGTH>> m_universes; AddCmpTreeNode m_add_cmp_root; HashMap<ComponentType, string> m_component_labels; WorldEditor* m_editor; Action* m_custom_pivot_action; bool m_confirm_exit; bool m_confirm_load; bool m_confirm_new; char m_universe_to_load[MAX_PATH_LENGTH]; AssetBrowser* m_asset_browser; AssetCompiler* m_asset_compiler; PropertyGrid* m_property_grid; LogUI* m_log_ui; ProfilerUI* m_profiler_ui; Settings m_settings; Array<OS::Event> m_events; Vec2 m_mouse_move; Timer* m_fps_timer; char m_template_name[100]; char m_open_filter[64]; char m_component_filter[32]; struct PackConfig { enum class Mode : int { ALL_FILES, CURRENT_UNIVERSE }; Mode mode; StaticString<MAX_PATH_LENGTH> dest_dir; }; PackConfig m_pack; bool m_finished; bool m_deferred_game_mode_exit; int m_exit_code; bool m_sleep_when_inactive; bool m_is_welcome_screen_open; bool m_is_pack_data_dialog_open; bool m_is_entity_list_open; bool m_is_save_as_dialog_open; bool m_is_edit_cam_transform_ui_open = false; ImFont* m_font; ImFont* m_bold_font; struct WatchedPlugin { FileSystemWatcher* watcher = nullptr; StaticString<MAX_PATH_LENGTH> dir; StaticString<MAX_PATH_LENGTH> basename; Lumix::IPlugin* plugin = nullptr; int iteration = 0; bool reload_request = false; } m_watched_plugin; }; static size_t alignMask(size_t _value, size_t _mask) { return (_value + _mask) & ((~0) & (~_mask)); } static void* alignPtr(void* _ptr, size_t _align) { union { void* ptr; size_t addr; } un; un.ptr = _ptr; size_t mask = _align - 1; size_t aligned = alignMask(un.addr, mask); un.addr = aligned; return un.ptr; } StudioApp* StudioApp::create() { static char buf[sizeof(StudioAppImpl) * 2]; return new (NewPlaceholder(), alignPtr(buf, alignof(StudioAppImpl))) StudioAppImpl; } void StudioApp::destroy(StudioApp& app) { app.~StudioApp(); } static StudioApp::StaticPluginRegister* s_first_plugin = nullptr; StudioApp::StaticPluginRegister::StaticPluginRegister(const char* name, Creator creator) { this->creator = creator; this->name = name; next = s_first_plugin; s_first_plugin = this; } void StudioApp::StaticPluginRegister::create(StudioApp& app) { auto* i = s_first_plugin; while (i) { StudioApp::IPlugin* plugin = i->creator(app); if (plugin) app.addPlugin(*plugin); i = i->next; } app.initPlugins(); } } // namespace Lumix fixed handling ctrl and shift in shortcuts #include "studio_app.h" #include "asset_browser.h" #include "audio/audio_scene.h" #include "audio/clip_manager.h" #include "editor/asset_compiler.h" #include "editor/file_system_watcher.h" #include "editor/gizmo.h" #include "editor/prefab_system.h" #include "editor/render_interface.h" #include "editor/world_editor.h" #include "engine/command_line_parser.h" #include "engine/crc32.h" #include "engine/debug/debug.h" #include "engine/default_allocator.h" #include "engine/engine.h" #include "engine/fs/disk_file_device.h" #include "engine/fs/file_system.h" #include "engine/fs/os_file.h" #include "engine/input_system.h" #include "engine/log.h" #include "engine/lua_wrapper.h" #include "engine/mt/thread.h" #include "engine/os.h" #include "engine/path_utils.h" #include "engine/plugin_manager.h" #include "engine/profiler.h" #include "engine/quat.h" #include "engine/reflection.h" #include "engine/resource_manager.h" #include "engine/timer.h" #include "engine/universe/universe.h" #include "engine/viewport.h" #include "imgui/imgui.h" #include "log_ui.h" #include "profiler_ui.h" #include "property_grid.h" #include "settings.h" #include "utils.h" namespace Lumix { struct LuaPlugin : public StudioApp::GUIPlugin { LuaPlugin(StudioApp& app, const char* src, const char* filename) : editor(app.getWorldEditor()) { L = lua_newthread(editor.getEngine().getState()); // [thread] thread_ref = luaL_ref(editor.getEngine().getState(), LUA_REGISTRYINDEX); // [] lua_newtable(L); // [env] // reference environment lua_pushvalue(L, -1); // [env, env] env_ref = luaL_ref(L, LUA_REGISTRYINDEX); // [env] // environment's metatable & __index lua_pushvalue(L, -1); // [env, env] lua_setmetatable(L, -2); // [env] lua_pushvalue(L, LUA_GLOBALSINDEX); lua_setfield(L, -2, "__index"); // [env] bool errors = luaL_loadbuffer(L, src, stringLength(src), filename) != 0; // [env, func] lua_pushvalue(L, -2); // [env, func, env] lua_setfenv(L, -2); // function's environment [env, func] errors = errors || lua_pcall(L, 0, 0, 0) != 0; // [env] if (errors) { g_log_error.log("Editor") << filename << ": " << lua_tostring(L, -1); lua_pop(L, 1); } lua_pop(L, 1); // [] const char* name = "LuaPlugin"; lua_getglobal(L, "plugin_name"); if (lua_type(L, -1) == LUA_TSTRING) { name = lua_tostring(L, -1); } Action* action = LUMIX_NEW(editor.getAllocator(), Action)(name, name, name); action->func.bind<LuaPlugin, &LuaPlugin::onAction>(this); app.addWindowAction(action); m_is_open = false; lua_pop(L, 1); // plugin_name } ~LuaPlugin() { lua_State* L = editor.getEngine().getState(); luaL_unref(L, LUA_REGISTRYINDEX, env_ref); luaL_unref(L, LUA_REGISTRYINDEX, thread_ref); } const char* getName() const override { return "lua_script"; } void onAction() { m_is_open = !m_is_open; } void onWindowGUI() override { if (!m_is_open) return; lua_getglobal(L, "onGUI"); if (lua_type(L, -1) == LUA_TFUNCTION) { if (lua_pcall(L, 0, 0, 0) != 0) { g_log_error.log("Editor") << "LuaPlugin:" << lua_tostring(L, -1); lua_pop(L, 1); } } else { lua_pop(L, 1); } } WorldEditor& editor; lua_State* L; int thread_ref; int env_ref; bool m_is_open; }; class StudioAppImpl final : public StudioApp { public: StudioAppImpl() : m_is_entity_list_open(true) , m_is_save_as_dialog_open(false) , m_finished(false) , m_deferred_game_mode_exit(false) , m_profiler_ui(nullptr) , m_asset_browser(nullptr) , m_asset_compiler(nullptr) , m_property_grid(nullptr) , m_actions(m_allocator) , m_window_actions(m_allocator) , m_toolbar_actions(m_allocator) , m_is_welcome_screen_open(true) , m_is_pack_data_dialog_open(false) , m_editor(nullptr) , m_settings(*this) , m_gui_plugins(m_allocator) , m_plugins(m_allocator) , m_add_cmp_plugins(m_allocator) , m_component_labels(m_allocator) , m_confirm_load(false) , m_confirm_new(false) , m_confirm_exit(false) , m_exit_code(0) , m_allocator(m_main_allocator) , m_universes(m_allocator) , m_events(m_allocator) , m_fps_timer(nullptr) { } void onEvent(const OS::Event& event) { m_events.push(event); switch (event.type) { case OS::Event::Type::MOUSE_BUTTON: { ImGuiIO& io = ImGui::GetIO(); m_editor->setToggleSelection(io.KeyCtrl); m_editor->setSnapMode(io.KeyShift, io.KeyCtrl); io.MouseDown[(int)event.mouse_button.button] = event.mouse_button.down; break; } case OS::Event::Type::MOUSE_WHEEL: { ImGuiIO& io = ImGui::GetIO(); io.MouseWheel = event.mouse_wheel.amount; break; } case OS::Event::Type::MOUSE_MOVE: { ImGuiIO& io = ImGui::GetIO(); const OS::Point cp = OS::getMousePos(event.window); m_mouse_move += {(float)event.mouse_move.xrel, (float)event.mouse_move.yrel}; io.MousePos.x = (float)cp.x; io.MousePos.y = (float)cp.y; break; } case OS::Event::Type::WINDOW_SIZE: if (event.window == m_window && event.win_size.h > 0 && event.win_size.w > 0) { m_settings.m_window.w = event.win_size.w; m_settings.m_window.h = event.win_size.h; m_settings.m_is_maximized = OS::isMaximized(m_window); } break; case OS::Event::Type::WINDOW_MOVE: if (event.window == m_window) { m_settings.m_window.x = event.win_move.x; m_settings.m_window.y = event.win_move.y; m_settings.m_is_maximized = OS::isMaximized(m_window); } break; case OS::Event::Type::WINDOW_CLOSE: case OS::Event::Type::QUIT: exit(); break; case OS::Event::Type::CHAR: { ImGuiIO& io = ImGui::GetIO(); char utf8[5]; OS::UTF32ToUTF8(event.text_input.utf32, utf8); utf8[4] = 0; io.AddInputCharactersUTF8(utf8); break; } case OS::Event::Type::KEY: { ImGuiIO& io = ImGui::GetIO(); io.KeysDown[(int)event.key.keycode] = event.key.down; io.KeyShift = OS::isKeyDown(OS::Keycode::SHIFT); io.KeyCtrl = OS::isKeyDown(OS::Keycode::CTRL); io.KeyAlt = OS::isKeyDown(OS::Keycode::MENU); checkShortcuts(); break; } case OS::Event::Type::DROP_FILE: for(int i = 0, c = OS::getDropFileCount(event); i < c; ++i) { char tmp[MAX_PATH_LENGTH]; OS::getDropFile(event, i, tmp, lengthOf(tmp)); for (GUIPlugin* plugin : m_gui_plugins) { if (plugin->onDropFile(tmp)) break; } } break; } } void onIdle() override { update(); if (m_sleep_when_inactive && OS::getFocused() != m_window) { const float frame_time = m_fps_timer->tick(); const float wanted_fps = 5.0f; if (frame_time < 1 / wanted_fps) { PROFILE_BLOCK("sleep"); MT::sleep(u32(1000 / wanted_fps - frame_time * 1000)); } m_fps_timer->tick(); } Profiler::frame(); m_events.clear(); } void onInit() override { m_add_cmp_root.label[0] = '\0'; m_template_name[0] = '\0'; m_open_filter[0] = '\0'; checkWorkingDirector(); char current_dir[MAX_PATH_LENGTH]; OS::getCurrentDirectory(current_dir, lengthOf(current_dir)); char data_dir_path[MAX_PATH_LENGTH] = {}; checkDataDirCommandLine(data_dir_path, lengthOf(data_dir_path)); m_engine = Engine::create(current_dir, nullptr, m_allocator); createLua(); m_editor = WorldEditor::create(current_dir, *m_engine, m_allocator); m_window = m_editor->getWindow(); m_settings.m_editor = m_editor; scanUniverses(); loadUserPlugins(); addActions(); m_asset_compiler = AssetCompiler::create(*this); m_asset_browser = LUMIX_NEW(m_allocator, AssetBrowser)(*this); m_property_grid = LUMIX_NEW(m_allocator, PropertyGrid)(*this); m_profiler_ui = ProfilerUI::create(*m_engine); m_log_ui = LUMIX_NEW(m_allocator, LogUI)(m_editor->getAllocator()); ImGui::CreateContext(); loadSettings(); initIMGUI(); #ifdef _WIN32 // TODO // ImGui::GetPlatformIO().ImeWindowHandle = m_window; #endif m_custom_pivot_action = LUMIX_NEW(m_editor->getAllocator(), Action)("Set Custom Pivot", "Set Custom Pivot", "set_custom_pivot", OS::Keycode::K, OS::Keycode::INVALID, OS::Keycode::INVALID); m_custom_pivot_action->is_global = false; addAction(m_custom_pivot_action); setStudioApp(); loadIcons(); loadSettings(); loadUniverseFromCommandLine(); findLuaPlugins("plugins/lua/"); m_asset_compiler->onInitFinished(); m_sleep_when_inactive = shouldSleepWhenInactive(); checkScriptCommandLine(); m_fps_timer = Timer::create(m_allocator); } ~StudioAppImpl() { Timer::destroy(m_fps_timer); if (m_watched_plugin.watcher) FileSystemWatcher::destroy(m_watched_plugin.watcher); saveSettings(); unloadIcons(); while (m_editor->getEngine().getFileSystem().hasWork()) { m_editor->getEngine().getFileSystem().updateAsyncTransactions(); } m_editor->newUniverse(); destroyAddCmpTreeNode(m_add_cmp_root.child); for (auto* i : m_plugins) { LUMIX_DELETE(m_editor->getAllocator(), i); } m_plugins.clear(); PrefabSystem::destroyEditorPlugins(*this); ASSERT(m_gui_plugins.empty()); for (auto* i : m_add_cmp_plugins) { LUMIX_DELETE(m_editor->getAllocator(), i); } m_add_cmp_plugins.clear(); for (auto* a : m_actions) { LUMIX_DELETE(m_editor->getAllocator(), a); } m_actions.clear(); ProfilerUI::destroy(*m_profiler_ui); LUMIX_DELETE(m_allocator, m_asset_browser); LUMIX_DELETE(m_allocator, m_property_grid); LUMIX_DELETE(m_allocator, m_log_ui); AssetCompiler::destroy(*m_asset_compiler); WorldEditor::destroy(m_editor, m_allocator); Engine::destroy(m_engine, m_allocator); m_engine = nullptr; m_editor = nullptr; OS::destroyWindow(m_window); } bool makeFile(const char* path, const char* content) override { FS::OsFile file; if (!file.open(path, FS::Mode::CREATE_AND_WRITE)) return false; bool success = file.writeText(content); file.close(); return success; } void destroyAddCmpTreeNode(AddCmpTreeNode* node) { if (!node) return; destroyAddCmpTreeNode(node->child); destroyAddCmpTreeNode(node->next); LUMIX_DELETE(m_allocator, node); } const char* getComponentTypeName(ComponentType cmp_type) const override { auto iter = m_component_labels.find(cmp_type); if (iter == m_component_labels.end()) return "Unknown"; return iter.value().c_str(); } const AddCmpTreeNode& getAddComponentTreeRoot() const override { return m_add_cmp_root; } void addPlugin(IAddComponentPlugin& plugin) { int i = 0; while (i < m_add_cmp_plugins.size() && compareString(plugin.getLabel(), m_add_cmp_plugins[i]->getLabel()) > 0) { ++i; } m_add_cmp_plugins.insert(i, &plugin); auto* node = LUMIX_NEW(m_allocator, AddCmpTreeNode); copyString(node->label, plugin.getLabel()); node->plugin = &plugin; insertAddCmpNode(m_add_cmp_root, node); } static void insertAddCmpNodeOrdered(AddCmpTreeNode& parent, AddCmpTreeNode* node) { if (!parent.child) { parent.child = node; return; } if (compareString(parent.child->label, node->label) > 0) { node->next = parent.child; parent.child = node; return; } auto* i = parent.child; while (i->next && compareString(i->next->label, node->label) < 0) { i = i->next; } node->next = i->next; i->next = node; } void insertAddCmpNode(AddCmpTreeNode& parent, AddCmpTreeNode* node) { for (auto* i = parent.child; i; i = i->next) { if (!i->plugin && startsWith(node->label, i->label)) { insertAddCmpNode(*i, node); return; } } const char* rest = node->label + stringLength(parent.label); if (parent.label[0] != '\0') ++rest; // include '/' const char* slash = findSubstring(rest, "/"); if (!slash) { insertAddCmpNodeOrdered(parent, node); return; } auto* new_group = LUMIX_NEW(m_allocator, AddCmpTreeNode); copyNString(new_group->label, (int)sizeof(new_group->label), node->label, int(slash - node->label)); insertAddCmpNodeOrdered(parent, new_group); insertAddCmpNode(*new_group, node); } void registerComponentWithResource(const char* type, const char* label, ResourceType resource_type, const Reflection::PropertyBase& property) override { struct Plugin final : public IAddComponentPlugin { void onGUI(bool create_entity, bool from_filter) override { ImGui::SetNextWindowSize(ImVec2(300, 300)); const char* last = reverseFind(label, nullptr, '/'); if (!ImGui::BeginMenu(last && !from_filter ? last + 1 : label)) return; char buf[MAX_PATH_LENGTH]; bool create_empty = ImGui::MenuItem("Empty"); if (asset_browser->resourceList(buf, lengthOf(buf), resource_type, 0) || create_empty) { if (create_entity) { EntityRef entity = editor->addEntity(); editor->selectEntities(&entity, 1, false); } editor->addComponent(type); if (!create_empty) { editor->setProperty(type, -1, *property, &editor->getSelectedEntities()[0], editor->getSelectedEntities().size(), buf, stringLength(buf) + 1); } ImGui::CloseCurrentPopup(); } ImGui::EndMenu(); } const char* getLabel() const override { return label; } PropertyGrid* property_grid; AssetBrowser* asset_browser; WorldEditor* editor; ComponentType type; ResourceType resource_type; const Reflection::PropertyBase* property; char label[50]; }; auto& allocator = m_editor->getAllocator(); auto* plugin = LUMIX_NEW(allocator, Plugin); plugin->property_grid = m_property_grid; plugin->asset_browser = m_asset_browser; plugin->type = Reflection::getComponentType(type); plugin->editor = m_editor; plugin->property = &property; plugin->resource_type = resource_type; copyString(plugin->label, label); addPlugin(*plugin); m_component_labels.insert(plugin->type, string(label, m_allocator)); } void registerComponent(const char* id, IAddComponentPlugin& plugin) override { addPlugin(plugin); m_component_labels.insert(Reflection::getComponentType(id), string(plugin.getLabel(), m_allocator)); } void registerComponent(const char* type, const char* label) override { struct Plugin final : public IAddComponentPlugin { void onGUI(bool create_entity, bool from_filter) override { const char* last = reverseFind(label, nullptr, '/'); if (ImGui::MenuItem(last && !from_filter ? last + 1 : label)) { if (create_entity) { EntityRef entity = editor->addEntity(); editor->selectEntities(&entity, 1, false); } editor->addComponent(type); } } const char* getLabel() const override { return label; } WorldEditor* editor; PropertyGrid* property_grid; ComponentType type; char label[64]; }; auto& allocator = m_editor->getAllocator(); auto* plugin = LUMIX_NEW(allocator, Plugin); plugin->property_grid = m_property_grid; plugin->editor = m_editor; plugin->type = Reflection::getComponentType(type); copyString(plugin->label, label); addPlugin(*plugin); m_component_labels.insert(plugin->type, string(label, m_allocator)); } const Array<Action*>& getActions() override { return m_actions; } Array<Action*>& getToolbarActions() override { return m_toolbar_actions; } void guiBeginFrame() const { PROFILE_FUNCTION(); ImGuiIO& io = ImGui::GetIO(); const OS::Point size = OS::getWindowClientSize(m_window); if (size.x > 0 && size.y > 0) { io.DisplaySize = ImVec2(float(size.x), float(size.y)); } else if(io.DisplaySize.x <= 0) { io.DisplaySize.x = 800; io.DisplaySize.y = 600; } io.DeltaTime = m_engine->getLastTimeDelta(); io.KeyShift = OS::isKeyDown(OS::Keycode::SHIFT); io.KeyCtrl = OS::isKeyDown(OS::Keycode::CTRL); io.KeyAlt = OS::isKeyDown(OS::Keycode::MENU); ImGui::NewFrame(); ImGui::PushFont(m_font); } float showMainToolbar(float menu_height) { if (m_toolbar_actions.empty()) { ImGui::SetCursorPosY(menu_height); return menu_height; } auto frame_padding = ImGui::GetStyle().FramePadding; float padding = frame_padding.y * 2; ImVec2 toolbar_size(ImGui::GetIO().DisplaySize.x, 24 + padding); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); if (ImGui::BeginToolbar("main_toolbar", ImVec2(1, menu_height), toolbar_size)) { for (auto* action : m_toolbar_actions) { action->toolbarButton(); } } ImGui::EndToolbar(); ImGui::PopStyleVar(); return menu_height + 24 + padding; } void guiEndFrame() { if (m_is_welcome_screen_open) { ImGuiID dockspace_id = ImGui::GetID("MyDockspace"); ImGui::DockSpace(dockspace_id, ImVec2(0, 0), ImGuiDockNodeFlags_KeepAliveOnly); showWelcomeScreen(); } else { if (ImGui::GetIO().DisplaySize.y > 0) { auto pos = ImVec2(0, 0); auto size = ImGui::GetIO().DisplaySize; size.y -= pos.y; ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; ImGui::SetNextWindowSize(size); ImGui::SetNextWindowPos({0, 0}, ImGuiCond_FirstUseEver); if (ImGui::Begin("MainDockspace", nullptr, flags)) { float menu_height = showMainMenu(); showMainToolbar(menu_height); ImGuiID dockspace_id = ImGui::GetID("MyDockspace"); ImGui::DockSpace(dockspace_id, ImVec2(0, 0)); } ImGui::End(); // TODO // ImGui::RootDock(pos, size); } m_profiler_ui->onGUI(); m_asset_browser->onGUI(); m_log_ui->onGUI(); m_property_grid->onGUI(); onEntityListGUI(); onEditCameraGUI(); onSaveAsDialogGUI(); for (auto* plugin : m_gui_plugins) { plugin->onWindowGUI(); } m_settings.onGUI(); onPackDataGUI(); } ImGui::PopFont(); ImGui::Render(); for (auto* plugin : m_gui_plugins) { plugin->guiEndFrame(); } } void update() { PROFILE_FUNCTION(); m_asset_compiler->update(); if (m_watched_plugin.reload_request) tryReloadPlugin(); guiBeginFrame(); float time_delta = m_editor->getEngine().getLastTimeDelta(); ImGuiIO& io = ImGui::GetIO(); if (!io.KeyShift) { m_editor->setSnapMode(false, false); } else if (io.KeyCtrl) { m_editor->setSnapMode(io.KeyShift, io.KeyCtrl); } if (m_custom_pivot_action->isActive()) { m_editor->setCustomPivot(); } m_editor->setMouseSensitivity(m_settings.m_mouse_sensitivity.x, m_settings.m_mouse_sensitivity.y); m_editor->update(); m_engine->update(*m_editor->getUniverse()); if (m_deferred_game_mode_exit) { m_deferred_game_mode_exit = false; m_editor->toggleGameMode(); } for (auto* plugin : m_gui_plugins) { plugin->update(time_delta); } m_asset_browser->update(); m_log_ui->update(time_delta); guiEndFrame(); } void showWelcomeScreen() { ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings; const OS::Point size = OS::getWindowClientSize(m_window); ImGui::SetNextWindowSize(ImVec2((float)size.x, (float)size.y)); ImGui::SetNextWindowPos({0, 0}, ImGuiCond_FirstUseEver); if (ImGui::Begin("Welcome", nullptr, flags)) { ImGui::Text("Welcome to Lumix Studio"); ImVec2 half_size = ImGui::GetContentRegionAvail(); half_size.x = half_size.x * 0.5f - ImGui::GetStyle().FramePadding.x; half_size.y *= 0.75f; auto right_pos = ImGui::GetCursorPos(); right_pos.x += half_size.x + ImGui::GetStyle().FramePadding.x; if (ImGui::BeginChild("left", half_size, true)) { if (ImGui::Button("New Universe")) m_is_welcome_screen_open = false; ImGui::Separator(); ImGui::Text("Open universe:"); ImGui::Indent(); for (auto& univ : m_universes) { if (ImGui::MenuItem(univ.data)) { m_editor->loadUniverse(univ.data); setTitle(univ.data); m_is_welcome_screen_open = false; } } ImGui::Unindent(); } ImGui::EndChild(); ImGui::SetCursorPos(right_pos); if (ImGui::BeginChild("right", half_size, true)) { ImGui::Text("Using NVidia PhysX"); if (ImGui::Button("Wiki")) { OS::shellExecuteOpen("https://github.com/nem0/LumixEngine/wiki"); } if (ImGui::Button("Download new version")) { OS::shellExecuteOpen( "https://github.com/nem0/lumixengine_data/archive/master.zip"); } if (ImGui::Button("Show major releases")) { OS::shellExecuteOpen("https://github.com/nem0/LumixEngine/releases"); } if (ImGui::Button("Show latest commits")) { OS::shellExecuteOpen("https://github.com/nem0/LumixEngine/commits/master"); } if (ImGui::Button("Show issues")) { OS::shellExecuteOpen("https://github.com/nem0/lumixengine/issues"); } } ImGui::EndChild(); } ImGui::End(); } void setTitle(const char* title) const { char tmp[100]; copyString(tmp, "Lumix Studio - "); catString(tmp, title); OS::setWindowTitle(m_window, tmp); } static void getShortcut(const Action& action, char* buf, int max_size) { buf[0] = 0; for (int i = 0; i < lengthOf(action.shortcut); ++i) { char tmp[64]; OS::getKeyName(action.shortcut[i], tmp, sizeof(tmp)); if (tmp[0] == 0) return; if (i > 0) catString(buf, max_size, " - "); catString(buf, max_size, tmp); } } void doMenuItem(Action& a, bool enabled) const { char buf[20]; getShortcut(a, buf, sizeof(buf)); if (ImGui::MenuItem(a.label_short, buf, a.is_selected.invoke(), enabled)) { a.func.invoke(); } } void save() { if (m_editor->isGameMode()) { g_log_error.log("Editor") << "Could not save while the game is running"; return; } if (m_editor->getUniverse()->getName()[0]) { m_editor->saveUniverse(m_editor->getUniverse()->getName(), true); } else { saveAs(); } } void onSaveAsDialogGUI() { if (!m_is_save_as_dialog_open) return; if (ImGui::Begin("Save Universe As", &m_is_save_as_dialog_open)) { static char name[64] = ""; ImGui::InputText("Name", name, lengthOf(name)); if (ImGui::Button("Save")) { m_is_save_as_dialog_open = false; setTitle(name); m_editor->saveUniverse(name, true); scanUniverses(); } ImGui::SameLine(); if (ImGui::Button("Close")) m_is_save_as_dialog_open = false; } ImGui::End(); } void saveAs() { if (m_editor->isGameMode()) { g_log_error.log("Editor") << "Could not save while the game is running"; return; } m_is_save_as_dialog_open = true; } void exit() { if (m_editor->isUniverseChanged()) { m_confirm_exit = true; } else { OS::quit(); m_finished = true; } } void newUniverse() { if (m_editor->isUniverseChanged()) { m_confirm_new = true; } else { m_editor->newUniverse(); } } GUIPlugin* getFocusedPlugin() { for (GUIPlugin* plugin : m_gui_plugins) { if (plugin->hasFocus()) return plugin; } return nullptr; } void undo() { m_editor->undo(); } void redo() { m_editor->redo(); } void copy() { m_editor->copyEntities(); } void paste() { m_editor->pasteEntities(); } void duplicate() { m_editor->duplicateEntities(); } bool isOrbitCamera() { return m_editor->isOrbitCamera(); } void toggleOrbitCamera() { m_editor->setOrbitCamera(!m_editor->isOrbitCamera()); } void setTopView() { m_editor->setTopView(); } void setFrontView() { m_editor->setFrontView(); } void setSideView() { m_editor->setSideView(); } void setLocalCoordSystem() { m_editor->getGizmo().setLocalCoordSystem(); } void setGlobalCoordSystem() { m_editor->getGizmo().setGlobalCoordSystem(); } void setPivotOrigin() { m_editor->getGizmo().setPivotOrigin(); } void setPivotCenter() { m_editor->getGizmo().setPivotCenter(); } void addEntity() { m_editor->addEntity(); } void toggleMeasure() { m_editor->toggleMeasure(); } void snapDown() { m_editor->snapDown(); } void setEditCamTransform() { m_is_edit_cam_transform_ui_open = !m_is_edit_cam_transform_ui_open; } void lookAtSelected() { m_editor->lookAtSelected(); } void toggleSettings() { m_settings.m_is_open = !m_settings.m_is_open; } bool areSettingsOpen() const { return m_settings.m_is_open; } void toggleEntityList() { m_is_entity_list_open = !m_is_entity_list_open; } bool isEntityListOpen() const { return m_is_entity_list_open; } void toggleAssetBrowser() { m_asset_browser->m_is_open = !m_asset_browser->m_is_open; } bool isAssetBrowserOpen() const { return m_asset_browser->m_is_open; } int getExitCode() const override { return m_exit_code; } AssetBrowser& getAssetBrowser() override { ASSERT(m_asset_browser); return *m_asset_browser; } AssetCompiler& getAssetCompiler() override { ASSERT(m_asset_compiler); return *m_asset_compiler; } PropertyGrid& getPropertyGrid() override { ASSERT(m_property_grid); return *m_property_grid; } LogUI& getLogUI() override { ASSERT(m_log_ui); return *m_log_ui; } void toggleGameMode() { m_editor->toggleGameMode(); } void setTranslateGizmoMode() { m_editor->getGizmo().setTranslateMode(); } void setRotateGizmoMode() { m_editor->getGizmo().setRotateMode(); } void setScaleGizmoMode() { m_editor->getGizmo().setScaleMode(); } void makeParent() { const auto& entities = m_editor->getSelectedEntities(); ASSERT(entities.size() == 2); m_editor->makeParent(entities[0], entities[1]); } void unparent() { const auto& entities = m_editor->getSelectedEntities(); ASSERT(entities.size() == 1); m_editor->makeParent(INVALID_ENTITY, entities[0]); } void savePrefab() { char filename[MAX_PATH_LENGTH]; char tmp[MAX_PATH_LENGTH]; if (OS::getSaveFilename(tmp, lengthOf(tmp), "Prefab files\0*.fab\0", "fab")) { PathUtils::normalize(tmp, filename, lengthOf(tmp)); const char* base_path = m_engine->getDiskFileDevice()->getBasePath(); if (startsWith(filename, base_path)) { m_editor->getPrefabSystem().savePrefab(Path(filename + stringLength(base_path))); } else { m_editor->getPrefabSystem().savePrefab(Path(filename)); } } } void autosnapDown() { auto& gizmo = m_editor->getGizmo(); gizmo.setAutosnapDown(!gizmo.isAutosnapDown()); } void destroySelectedEntity() { auto& selected_entities = m_editor->getSelectedEntities(); if (selected_entities.empty()) return; m_editor->destroyEntities(&selected_entities[0], selected_entities.size()); } void loadAndExecuteCommands() { char filename[MAX_PATH_LENGTH]; if (OS::getOpenFilename(filename, lengthOf(filename), "JSON files\0*.json\0", nullptr)) { m_editor->executeUndoStack(Path(filename)); } } void saveUndoStack() { char filename[MAX_PATH_LENGTH]; if (OS::getSaveFilename(filename, lengthOf(filename), "JSON files\0*.json\0", "json")) { m_editor->saveUndoStack(Path(filename)); } } void removeAction(Action* action) override { m_actions.eraseItem(action); m_window_actions.eraseItem(action); } void addWindowAction(Action* action) override { addAction(action); for (int i = 0; i < m_window_actions.size(); ++i) { if (compareString(m_window_actions[i]->label_long, action->label_long) > 0) { m_window_actions.insert(i, action); return; } } m_window_actions.push(action); } void addAction(Action* action) override { for (int i = 0; i < m_actions.size(); ++i) { if (compareString(m_actions[i]->label_long, action->label_long) > 0) { m_actions.insert(i, action); return; } } m_actions.push(action); } template <void (StudioAppImpl::*Func)()> Action& addAction(const char* label_short, const char* label_long, const char* name) { auto* a = LUMIX_NEW(m_editor->getAllocator(), Action)(label_short, label_long, name); a->func.bind<StudioAppImpl, Func>(this); addAction(a); return *a; } template <void (StudioAppImpl::*Func)()> void addAction(const char* label_short, const char* label_long, const char* name, OS::Keycode shortcut0, OS::Keycode shortcut1, OS::Keycode shortcut2) { auto* a = LUMIX_NEW(m_editor->getAllocator(), Action)(label_short, label_long, name, shortcut0, shortcut1, shortcut2); a->func.bind<StudioAppImpl, Func>(this); addAction(a); } Action* getAction(const char* name) override { for (auto* a : m_actions) { if (equalStrings(a->name, name)) return a; } return nullptr; } static void showAddComponentNode(const StudioApp::AddCmpTreeNode* node, const char* filter) { if (!node) return; if (filter[0]) { if (!node->plugin) showAddComponentNode(node->child, filter); else if (stristr(node->plugin->getLabel(), filter)) node->plugin->onGUI(false, true); showAddComponentNode(node->next, filter); return; } if (node->plugin) { node->plugin->onGUI(true, false); showAddComponentNode(node->next, filter); return; } const char* last = reverseFind(node->label, nullptr, '/'); if (ImGui::BeginMenu(last ? last + 1 : node->label)) { showAddComponentNode(node->child, filter); ImGui::EndMenu(); } showAddComponentNode(node->next, filter); } void onCreateEntityWithComponentGUI() { doMenuItem(*getAction("createEntity"), true); ImGui::Separator(); ImGui::LabellessInputText("Filter", m_component_filter, sizeof(m_component_filter)); showAddComponentNode(m_add_cmp_root.child, m_component_filter); } void entityMenu() { if (!ImGui::BeginMenu("Entity")) return; const auto& selected_entities = m_editor->getSelectedEntities(); bool is_any_entity_selected = !selected_entities.empty(); if (ImGui::BeginMenu("Create")) { onCreateEntityWithComponentGUI(); ImGui::EndMenu(); } doMenuItem(*getAction("destroyEntity"), is_any_entity_selected); doMenuItem(*getAction("savePrefab"), selected_entities.size() == 1); doMenuItem(*getAction("makeParent"), selected_entities.size() == 2); bool can_unparent = selected_entities.size() == 1 && m_editor->getUniverse()->getParent(selected_entities[0]).isValid(); doMenuItem(*getAction("unparent"), can_unparent); ImGui::EndMenu(); } void editMenu() { if (!ImGui::BeginMenu("Edit")) return; bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); doMenuItem(*getAction("undo"), m_editor->canUndo()); doMenuItem(*getAction("redo"), m_editor->canRedo()); ImGui::Separator(); doMenuItem(*getAction("copy"), is_any_entity_selected); doMenuItem(*getAction("paste"), m_editor->canPasteEntities()); doMenuItem(*getAction("duplicate"), is_any_entity_selected); ImGui::Separator(); doMenuItem(*getAction("orbitCamera"), is_any_entity_selected || m_editor->isOrbitCamera()); doMenuItem(*getAction("setTranslateGizmoMode"), true); doMenuItem(*getAction("setRotateGizmoMode"), true); doMenuItem(*getAction("setScaleGizmoMode"), true); doMenuItem(*getAction("setPivotCenter"), true); doMenuItem(*getAction("setPivotOrigin"), true); doMenuItem(*getAction("setLocalCoordSystem"), true); doMenuItem(*getAction("setGlobalCoordSystem"), true); if (ImGui::BeginMenu("View", true)) { doMenuItem(*getAction("viewTop"), true); doMenuItem(*getAction("viewFront"), true); doMenuItem(*getAction("viewSide"), true); ImGui::EndMenu(); } ImGui::EndMenu(); } void fileMenu() { if (!ImGui::BeginMenu("File")) return; doMenuItem(*getAction("newUniverse"), true); if (ImGui::BeginMenu("Open")) { ImGui::LabellessInputText("Filter", m_open_filter, sizeof(m_open_filter)); for (auto& univ : m_universes) { if ((m_open_filter[0] == '\0' || stristr(univ.data, m_open_filter)) && ImGui::MenuItem(univ.data)) { if (m_editor->isUniverseChanged()) { copyString(m_universe_to_load, univ.data); m_confirm_load = true; } else { m_editor->loadUniverse(univ.data); setTitle(univ.data); } } } ImGui::EndMenu(); } doMenuItem(*getAction("save"), !m_editor->isGameMode()); doMenuItem(*getAction("saveAs"), !m_editor->isGameMode()); doMenuItem(*getAction("exit"), true); ImGui::EndMenu(); } void toolsMenu() { if (!ImGui::BeginMenu("Tools")) return; bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); doMenuItem(*getAction("setEditCamTransform"), true); doMenuItem(*getAction("lookAtSelected"), is_any_entity_selected); doMenuItem(*getAction("toggleGameMode"), true); doMenuItem(*getAction("toggleMeasure"), true); doMenuItem(*getAction("snapDown"), is_any_entity_selected); doMenuItem(*getAction("autosnapDown"), true); if (ImGui::MenuItem("Save commands")) saveUndoStack(); if (ImGui::MenuItem("Load commands")) loadAndExecuteCommands(); doMenuItem(*getAction("pack_data"), true); ImGui::EndMenu(); } void viewMenu() { if (!ImGui::BeginMenu("View")) return; ImGui::MenuItem("Asset browser", nullptr, &m_asset_browser->m_is_open); doMenuItem(*getAction("entityList"), true); ImGui::MenuItem("Log", nullptr, &m_log_ui->m_is_open); ImGui::MenuItem("Profiler", nullptr, &m_profiler_ui->m_is_open); ImGui::MenuItem("Properties", nullptr, &m_property_grid->m_is_open); doMenuItem(*getAction("settings"), true); ImGui::Separator(); for (Action* action : m_window_actions) { doMenuItem(*action, true); } ImGui::EndMenu(); } float showMainMenu() { if (m_confirm_exit) { ImGui::OpenPopup("confirm_exit"); m_confirm_exit = false; } if (ImGui::BeginPopupModal("confirm_exit")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { OS::quit(); m_finished = true; ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } if (m_confirm_new) { ImGui::OpenPopup("confirm_new"); m_confirm_new = false; } if (ImGui::BeginPopupModal("confirm_new")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { m_editor->newUniverse(); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } if (m_confirm_load) { ImGui::OpenPopup("Confirm"); m_confirm_load = false; } if (ImGui::BeginPopupModal("Confirm")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { m_editor->loadUniverse(m_universe_to_load); setTitle(m_universe_to_load); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } float menu_height = 0; ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); if (ImGui::BeginMainMenuBar()) { fileMenu(); editMenu(); entityMenu(); toolsMenu(); viewMenu(); StaticString<200> stats(""); if (m_engine->getFileSystem().hasWork()) stats << "Loading... | "; stats << "FPS: "; stats << m_engine->getFPS(); if (OS::getFocused() != m_window) stats << " - inactive window"; auto stats_size = ImGui::CalcTextSize(stats); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); ImGui::Text("%s", (const char*)stats); if (m_log_ui->getUnreadErrorCount() == 1) { ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); auto error_stats_size = ImGui::CalcTextSize("1 error | "); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x - error_stats_size.x); ImGui::TextColored(ImVec4(1, 0, 0, 1), "1 error | "); } else if (m_log_ui->getUnreadErrorCount() > 1) { StaticString<50> error_stats("", m_log_ui->getUnreadErrorCount(), " errors | "); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); auto error_stats_size = ImGui::CalcTextSize(error_stats); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x - error_stats_size.x); ImGui::TextColored(ImVec4(1, 0, 0, 1), "%s", (const char*)error_stats); } menu_height = ImGui::GetWindowSize().y; ImGui::EndMainMenuBar(); } ImGui::PopStyleVar(); return menu_height; } void showHierarchy(EntityRef entity, const Array<EntityRef>& selected_entities) { char buffer[1024]; Universe* universe = m_editor->getUniverse(); getEntityListDisplayName(*m_editor, buffer, sizeof(buffer), entity); bool selected = selected_entities.indexOf(entity) >= 0; ImGui::PushID(entity.index); ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_AllowItemOverlap; bool has_child = universe->getFirstChild(entity).isValid(); if (!has_child) flags = ImGuiTreeNodeFlags_Leaf; if (selected) flags |= ImGuiTreeNodeFlags_Selected; bool node_open = ImGui::TreeNodeEx(buffer, flags); if (ImGui::IsItemClicked(0)) m_editor->selectEntities(&entity, 1, true); if (ImGui::IsMouseReleased(1) && ImGui::IsItemHovered()) ImGui::OpenPopup("entity_context_menu"); if (ImGui::BeginPopup("entity_context_menu")) { if (ImGui::MenuItem("Create child")) { m_editor->beginCommandGroup(crc32("create_child_entity")); EntityRef child = m_editor->addEntity(); m_editor->makeParent(entity, child); const DVec3 pos = m_editor->getUniverse()->getPosition(entity); m_editor->setEntitiesPositions(&child, &pos, 1); m_editor->endCommandGroup(); } ImGui::EndPopup(); } ImGui::PopID(); if (ImGui::BeginDragDropSource()) { ImGui::Text("%s", buffer); ImGui::SetDragDropPayload("entity", &entity, sizeof(entity)); ImGui::EndDragDropSource(); } if (ImGui::BeginDragDropTarget()) { if (auto* payload = ImGui::AcceptDragDropPayload("entity")) { EntityRef dropped_entity = *(EntityRef*)payload->Data; if (dropped_entity != entity) { m_editor->makeParent(entity, dropped_entity); if (node_open) ImGui::TreePop(); return; } } ImGui::EndDragDropTarget(); } if (node_open) { for (EntityPtr e_ptr = universe->getFirstChild(entity); e_ptr.isValid(); e_ptr = universe->getNextSibling((EntityRef)e_ptr)) { showHierarchy((EntityRef)e_ptr, selected_entities); } ImGui::TreePop(); } } void onEditCameraGUI() { if (!m_is_edit_cam_transform_ui_open) return; if (ImGui::Begin("Edit camera")) { Viewport vp = m_editor->getViewport(); if (ImGui::DragScalarN("Position", ImGuiDataType_Double, &vp.pos.x, 3, 1.f)) { m_editor->setViewport(vp); } Vec3 angles = vp.rot.toEuler(); if (ImGui::DragFloat3("Rotation", &angles.x, 0.01f)) { vp.rot.fromEuler(angles); m_editor->setViewport(vp); } } ImGui::End(); } void onEntityListGUI() { PROFILE_FUNCTION(); const Array<EntityRef>& entities = m_editor->getSelectedEntities(); static char filter[64] = ""; if (!m_is_entity_list_open) return; if (ImGui::Begin("Entity List", &m_is_entity_list_open)) { auto* universe = m_editor->getUniverse(); ImGui::LabellessInputText("Filter", filter, sizeof(filter)); if (ImGui::BeginChild("entities")) { ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() - ImGui::GetStyle().FramePadding.x); if (filter[0] == '\0') { for (EntityPtr e = universe->getFirstEntity(); e.isValid(); e = universe->getNextEntity((EntityRef)e)) { const EntityRef e_ref = (EntityRef)e; if (!universe->getParent(e_ref).isValid()) { showHierarchy(e_ref, entities); } } } else { for (EntityPtr e = universe->getFirstEntity(); e.isValid(); e = universe->getNextEntity((EntityRef)e)) { char buffer[1024]; getEntityListDisplayName(*m_editor, buffer, sizeof(buffer), e); if (stristr(buffer, filter) == nullptr) continue; ImGui::PushID(e.index); const EntityRef e_ref = (EntityRef)e; bool selected = entities.indexOf(e_ref) >= 0; if (ImGui::Selectable(buffer, &selected)) { m_editor->selectEntities(&e_ref, 1, true); } if (ImGui::BeginDragDropSource()) { ImGui::Text("%s", buffer); ImGui::SetDragDropPayload("entity", &e, sizeof(e)); ImGui::EndDragDropSource(); } ImGui::PopID(); } } ImGui::PopItemWidth(); } ImGui::EndChild(); // TODO uncomment once it's fixed in imgui /*if (ImGui::BeginDragDropTarget()) { if (auto* payload = ImGui::AcceptDragDropPayload("entity")) { EntityRef dropped_entity = *(EntityRef*)payload->Data; m_editor->makeParent(INVALID_ENTITY, dropped_entity); } ImGui::EndDragDropTarget(); }*/ } ImGui::End(); } void dummy() {} void setFullscreen(bool fullscreen) override { ASSERT(false); // TODO // SDL_SetWindowFullscreen(m_window, fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0); } void saveSettings() { m_settings.m_is_asset_browser_open = m_asset_browser->m_is_open; m_settings.m_asset_browser_left_column_width = m_asset_browser->m_left_column_width; m_settings.m_is_entity_list_open = m_is_entity_list_open; m_settings.m_is_log_open = m_log_ui->m_is_open; m_settings.m_is_profiler_open = m_profiler_ui->m_is_open; m_settings.m_is_properties_open = m_property_grid->m_is_open; m_settings.m_mouse_sensitivity.x = m_editor->getMouseSensitivity().x; m_settings.m_mouse_sensitivity.y = m_editor->getMouseSensitivity().y; m_settings.save(); } void initIMGUI() { ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard | ImGuiConfigFlags_DockingEnable; const int dpi = OS::getDPI(); float font_scale = dpi / 96.f; m_font = io.Fonts->AddFontFromFileTTF( "editor/fonts/OpenSans-Regular.ttf", (float)m_settings.m_font_size * font_scale); m_bold_font = io.Fonts->AddFontFromFileTTF("editor/fonts/OpenSans-Bold.ttf", (float)m_settings.m_font_size * font_scale); m_font->DisplayOffset.y = 0; m_bold_font->DisplayOffset.y = 0; io.KeyMap[ImGuiKey_Space] = (int)OS::Keycode::SPACE; io.KeyMap[ImGuiKey_Tab] = (int)OS::Keycode::TAB; io.KeyMap[ImGuiKey_LeftArrow] = (int)OS::Keycode::LEFT; io.KeyMap[ImGuiKey_RightArrow] = (int)OS::Keycode::RIGHT; io.KeyMap[ImGuiKey_UpArrow] = (int)OS::Keycode::UP; io.KeyMap[ImGuiKey_DownArrow] = (int)OS::Keycode::DOWN; io.KeyMap[ImGuiKey_PageUp] = (int)OS::Keycode::PAGEUP; io.KeyMap[ImGuiKey_PageDown] = (int)OS::Keycode::PAGEDOWN; io.KeyMap[ImGuiKey_Home] = (int)OS::Keycode::HOME; io.KeyMap[ImGuiKey_End] = (int)OS::Keycode::END; io.KeyMap[ImGuiKey_Delete] = (int)OS::Keycode::DEL; io.KeyMap[ImGuiKey_Backspace] = (int)OS::Keycode::BACKSPACE; io.KeyMap[ImGuiKey_Enter] = (int)OS::Keycode::RETURN; io.KeyMap[ImGuiKey_Escape] = (int)OS::Keycode::ESCAPE; io.KeyMap[ImGuiKey_A] = (int)OS::Keycode::A; io.KeyMap[ImGuiKey_C] = (int)OS::Keycode::C; io.KeyMap[ImGuiKey_V] = (int)OS::Keycode::V; io.KeyMap[ImGuiKey_X] = (int)OS::Keycode::X; io.KeyMap[ImGuiKey_Y] = (int)OS::Keycode::Y; io.KeyMap[ImGuiKey_Z] = (int)OS::Keycode::Z; ImGuiStyle& style = ImGui::GetStyle(); style.FramePadding.y = 0; style.ItemSpacing.y = 2; style.ItemInnerSpacing.x = 2; } void loadSettings() { char cmd_line[2048]; OS::getCommandLine(cmd_line, lengthOf(cmd_line)); CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-no_crash_report")) continue; m_settings.m_force_no_crash_report = true; break; } m_settings.load(); m_asset_browser->m_is_open = m_settings.m_is_asset_browser_open; m_asset_browser->m_left_column_width = m_settings.m_asset_browser_left_column_width; m_is_entity_list_open = m_settings.m_is_entity_list_open; m_log_ui->m_is_open = m_settings.m_is_log_open; m_profiler_ui->m_is_open = m_settings.m_is_profiler_open; m_property_grid->m_is_open = m_settings.m_is_properties_open; if (m_settings.m_is_maximized) { OS::maximizeWindow(m_window); } else if (m_settings.m_window.w > 0) { OS::Rect r; r.left = m_settings.m_window.x; r.top = m_settings.m_window.y; r.width = m_settings.m_window.w; r.height = m_settings.m_window.h; OS::setWindowScreenRect(m_window, r); } } void addActions() { addAction<&StudioAppImpl::newUniverse>("New", "New universe", "newUniverse"); addAction<&StudioAppImpl::save>( "Save", "Save universe", "save", OS::Keycode::LCTRL, OS::Keycode::S, OS::Keycode::INVALID); addAction<&StudioAppImpl::saveAs>( "Save As", "Save universe as", "saveAs", OS::Keycode::LCTRL, OS::Keycode::LSHIFT, OS::Keycode::S); addAction<&StudioAppImpl::exit>( "Exit", "Exit Studio", "exit", OS::Keycode::LCTRL, OS::Keycode::X, OS::Keycode::INVALID); addAction<&StudioAppImpl::redo>( "Redo", "Redo scene action", "redo", OS::Keycode::LCTRL, OS::Keycode::LSHIFT, OS::Keycode::Z); addAction<&StudioAppImpl::undo>( "Undo", "Undo scene action", "undo", OS::Keycode::LCTRL, OS::Keycode::Z, OS::Keycode::INVALID); addAction<&StudioAppImpl::copy>( "Copy", "Copy entity", "copy", OS::Keycode::LCTRL, OS::Keycode::C, OS::Keycode::INVALID); addAction<&StudioAppImpl::paste>( "Paste", "Paste entity", "paste", OS::Keycode::LCTRL, OS::Keycode::V, OS::Keycode::INVALID); addAction<&StudioAppImpl::duplicate>( "Duplicate", "Duplicate entity", "duplicate", OS::Keycode::LCTRL, OS::Keycode::D, OS::Keycode::INVALID); addAction<&StudioAppImpl::toggleOrbitCamera>("Orbit camera", "Orbit camera", "orbitCamera") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isOrbitCamera>(this); addAction<&StudioAppImpl::setTranslateGizmoMode>("Translate", "Set translate mode", "setTranslateGizmoMode") .is_selected.bind<Gizmo, &Gizmo::isTranslateMode>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setRotateGizmoMode>("Rotate", "Set rotate mode", "setRotateGizmoMode") .is_selected.bind<Gizmo, &Gizmo::isRotateMode>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setScaleGizmoMode>("Scale", "Set scale mode", "setScaleGizmoMode") .is_selected.bind<Gizmo, &Gizmo::isScaleMode>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setTopView>("Top", "Set top camera view", "viewTop"); addAction<&StudioAppImpl::setFrontView>("Front", "Set front camera view", "viewFront"); addAction<&StudioAppImpl::setSideView>("Side", "Set side camera view", "viewSide"); addAction<&StudioAppImpl::setLocalCoordSystem>("Local", "Set local transform system", "setLocalCoordSystem") .is_selected.bind<Gizmo, &Gizmo::isLocalCoordSystem>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setGlobalCoordSystem>("Global", "Set global transform system", "setGlobalCoordSystem") .is_selected.bind<Gizmo, &Gizmo::isGlobalCoordSystem>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setPivotCenter>("Center", "Set center transform system", "setPivotCenter") .is_selected.bind<Gizmo, &Gizmo::isPivotCenter>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setPivotOrigin>("Pivot", "Set pivot transform system", "setPivotOrigin") .is_selected.bind<Gizmo, &Gizmo::isPivotOrigin>(&m_editor->getGizmo()); addAction<&StudioAppImpl::addEntity>("Create empty", "Create empty entity", "createEntity"); addAction<&StudioAppImpl::destroySelectedEntity>("Destroy", "Destroy entity", "destroyEntity", OS::Keycode::DEL, OS::Keycode::INVALID, OS::Keycode::INVALID); addAction<&StudioAppImpl::savePrefab>("Save prefab", "Save selected entities as prefab", "savePrefab"); addAction<&StudioAppImpl::makeParent>("Make parent", "Make entity parent", "makeParent"); addAction<&StudioAppImpl::unparent>("Unparent", "Unparent entity", "unparent"); addAction<&StudioAppImpl::toggleGameMode>("Game Mode", "Toggle game mode", "toggleGameMode") .is_selected.bind<WorldEditor, &WorldEditor::isGameMode>(m_editor); addAction<&StudioAppImpl::toggleMeasure>("Toggle measure", "Toggle measure mode", "toggleMeasure") .is_selected.bind<WorldEditor, &WorldEditor::isMeasureToolActive>(m_editor); addAction<&StudioAppImpl::autosnapDown>("Autosnap down", "Toggle autosnap down", "autosnapDown") .is_selected.bind<Gizmo, &Gizmo::isAutosnapDown>(&m_editor->getGizmo()); addAction<&StudioAppImpl::snapDown>("Snap down", "Snap entities down", "snapDown"); addAction<&StudioAppImpl::setEditCamTransform>("Camera transform", "Set camera transformation", "setEditCamTransform"); addAction<&StudioAppImpl::lookAtSelected>("Look at selected", "Look at selected entity", "lookAtSelected"); addAction<&StudioAppImpl::toggleAssetBrowser>("Asset Browser", "Toggle asset browser", "assetBrowser") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isAssetBrowserOpen>(this); addAction<&StudioAppImpl::toggleEntityList>("Entity List", "Toggle entity list", "entityList") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isEntityListOpen>(this); addAction<&StudioAppImpl::toggleSettings>("Settings", "Toggle settings UI", "settings") .is_selected.bind<StudioAppImpl, &StudioAppImpl::areSettingsOpen>(this); addAction<&StudioAppImpl::showPackDataDialog>("Pack data", "Pack data", "pack_data"); } static bool copyPlugin(const char* src, int iteration, char (&out)[MAX_PATH_LENGTH]) { char tmp_path[MAX_PATH_LENGTH]; OS::getExecutablePath(tmp_path, lengthOf(tmp_path)); StaticString<MAX_PATH_LENGTH> copy_path; PathUtils::getDir(copy_path.data, lengthOf(copy_path.data), tmp_path); copy_path << "plugins/" << iteration; OS::makePath(copy_path); PathUtils::getBasename(tmp_path, lengthOf(tmp_path), src); copy_path << "/" << tmp_path << "." << getPluginExtension(); #ifdef _WIN32 StaticString<MAX_PATH_LENGTH> src_pdb(src); StaticString<MAX_PATH_LENGTH> dest_pdb(copy_path); if (PathUtils::replaceExtension(dest_pdb.data, "pdb") && PathUtils::replaceExtension(src_pdb.data, "pda")) { OS::deleteFile(dest_pdb); if (!OS::copyFile(src_pdb, dest_pdb)) { copyString(out, src); return false; } } #endif OS::deleteFile(copy_path); if (!OS::copyFile(src, copy_path)) { copyString(out, src); return false; } copyString(out, copy_path); return true; } void loadUserPlugins() { char cmd_line[2048]; OS::getCommandLine(cmd_line, lengthOf(cmd_line)); CommandLineParser parser(cmd_line); auto& plugin_manager = m_editor->getEngine().getPluginManager(); while (parser.next()) { if (!parser.currentEquals("-plugin")) continue; if (!parser.next()) break; char src[MAX_PATH_LENGTH]; parser.getCurrent(src, lengthOf(src)); bool is_full_path = findSubstring(src, ".") != nullptr; Lumix::IPlugin* loaded_plugin; if (is_full_path) { char copy_path[MAX_PATH_LENGTH]; copyPlugin(src, 0, copy_path); loaded_plugin = plugin_manager.load(copy_path); } else { loaded_plugin = plugin_manager.load(src); } if (!loaded_plugin) { g_log_error.log("Editor") << "Could not load plugin " << src << " requested by command line"; } else if (is_full_path && !m_watched_plugin.watcher) { char dir[MAX_PATH_LENGTH]; char basename[MAX_PATH_LENGTH]; PathUtils::getBasename(basename, lengthOf(basename), src); m_watched_plugin.basename = basename; PathUtils::getDir(dir, lengthOf(dir), src); m_watched_plugin.watcher = FileSystemWatcher::create(dir, m_allocator); m_watched_plugin.watcher->getCallback().bind<StudioAppImpl, &StudioAppImpl::onPluginChanged>(this); m_watched_plugin.dir = dir; m_watched_plugin.plugin = loaded_plugin; } } } static const char* getPluginExtension() { const char* ext = #ifdef _WIN32 "dll"; #elif defined __linux__ "so"; #else #error Unknown platform #endif return ext; } void onPluginChanged(const char* path) { const char* ext = getPluginExtension(); if (!PathUtils::hasExtension(path, ext) #ifdef _WIN32 && !PathUtils::hasExtension(path, "pda") #endif ) return; char basename[MAX_PATH_LENGTH]; PathUtils::getBasename(basename, lengthOf(basename), path); if (!equalIStrings(basename, m_watched_plugin.basename)) return; m_watched_plugin.reload_request = true; } void tryReloadPlugin() { m_watched_plugin.reload_request = false; StaticString<MAX_PATH_LENGTH> src(m_watched_plugin.dir, m_watched_plugin.basename, ".", getPluginExtension()); char copy_path[MAX_PATH_LENGTH]; ++m_watched_plugin.iteration; if (!copyPlugin(src, m_watched_plugin.iteration, copy_path)) return; g_log_info.log("Editor") << "Trying to reload plugin " << m_watched_plugin.basename; OutputBlob blob(m_allocator); blob.reserve(16 * 1024); PluginManager& plugin_manager = m_editor->getEngine().getPluginManager(); void* lib = plugin_manager.getLibrary(m_watched_plugin.plugin); Universe* universe = m_editor->getUniverse(); for (IScene* scene : universe->getScenes()) { if (&scene->getPlugin() != m_watched_plugin.plugin) continue; if (m_editor->isGameMode()) scene->stopGame(); scene->serialize(blob); universe->removeScene(scene); scene->getPlugin().destroyScene(scene); } plugin_manager.unload(m_watched_plugin.plugin); // TODO try to delete the old version m_watched_plugin.plugin = plugin_manager.load(copy_path); if (!m_watched_plugin.plugin) { g_log_error.log("Editor") << "Failed to load plugin " << copy_path << ". Reload failed."; return; } InputBlob input_blob(blob); m_watched_plugin.plugin->createScenes(*universe); for (IScene* scene : universe->getScenes()) { if (&scene->getPlugin() != m_watched_plugin.plugin) continue; scene->deserialize(input_blob); if (m_editor->isGameMode()) scene->startGame(); } g_log_info.log("Editor") << "Finished reloading plugin."; } bool shouldSleepWhenInactive() { char cmd_line[2048]; OS::getCommandLine(cmd_line, lengthOf(cmd_line)); CommandLineParser parser(cmd_line); while (parser.next()) { if (parser.currentEquals("-no_sleep_inactive")) return false; } return true; } void loadUniverseFromCommandLine() { char cmd_line[2048]; char path[MAX_PATH_LENGTH]; OS::getCommandLine(cmd_line, lengthOf(cmd_line)); CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-open")) continue; if (!parser.next()) break; parser.getCurrent(path, lengthOf(path)); m_editor->loadUniverse(path); setTitle(path); m_is_welcome_screen_open = false; break; } } static void checkDataDirCommandLine(char* dir, int max_size) { char cmd_line[2048]; OS::getCommandLine(cmd_line, lengthOf(cmd_line)); CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-data_dir")) continue; if (!parser.next()) break; parser.getCurrent(dir, max_size); break; } } GUIPlugin* getPlugin(const char* name) override { for (auto* i : m_gui_plugins) { if (equalStrings(i->getName(), name)) return i; } return nullptr; } void initPlugins() override { for (int i = 1, c = m_plugins.size(); i < c; ++i) { for (int j = 0; j < i; ++j) { IPlugin* p = m_plugins[i]; if (m_plugins[j]->dependsOn(*p)) { m_plugins.erase(i); --i; m_plugins.insert(j, p); } } } for (IPlugin* plugin : m_plugins) { plugin->init(); } } void addPlugin(IPlugin& plugin) override { m_plugins.push(&plugin); } void addPlugin(GUIPlugin& plugin) override { m_gui_plugins.push(&plugin); for (auto* i : m_gui_plugins) { i->pluginAdded(plugin); plugin.pluginAdded(*i); } } void removePlugin(GUIPlugin& plugin) override { m_gui_plugins.eraseItemFast(&plugin); } void setStudioApp() { #ifdef STATIC_PLUGINS StudioApp::StaticPluginRegister::create(*this); #else auto& plugin_manager = m_editor->getEngine().getPluginManager(); for (auto* lib : plugin_manager.getLibraries()) { auto* f = (StudioApp::IPlugin * (*)(StudioApp&)) getLibrarySymbol(lib, "setStudioApp"); if (f) { StudioApp::IPlugin* plugin = f(*this); addPlugin(*plugin); } } #endif PrefabSystem::createEditorPlugins(*this, m_editor->getPrefabSystem()); } void runScript(const char* src, const char* script_name) override { lua_State* L = m_engine->getState(); bool errors = luaL_loadbuffer(L, src, stringLength(src), script_name) != 0; errors = errors || lua_pcall(L, 0, 0, 0) != 0; if (errors) { g_log_error.log("Editor") << script_name << ": " << lua_tostring(L, -1); lua_pop(L, 1); } } void savePrefabAs(const char* path) { m_editor->getPrefabSystem().savePrefab(Path(path)); } void destroyEntity(EntityRef e) { m_editor->destroyEntities(&e, 1); } void selectEntity(EntityRef e) { m_editor->selectEntities(&e, 1, false); } EntityRef createEntity() { return m_editor->addEntity(); } void createComponent(EntityRef e, int type) { m_editor->selectEntities(&e, 1, false); m_editor->addComponent({type}); } void exitGameMode() { m_deferred_game_mode_exit = true; } void exitWithCode(int exit_code) { OS::quit(); m_finished = true; m_exit_code = exit_code; } struct SetPropertyVisitor : public Reflection::IPropertyVisitor { void visit(const Reflection::Property<int>& prop) override { if (!equalStrings(property_name, prop.name)) return; if (!lua_isnumber(L, -1)) return; int val = (int)lua_tointeger(L, -1); editor->setProperty(cmp_type, 0, prop, &entity, 1, &val, sizeof(val)); } // TODO void visit(const Reflection::Property<float>& prop) override { notSupported(prop); } void visit(const Reflection::Property<EntityPtr>& prop) override { notSupported(prop); } void visit(const Reflection::Property<IVec2>& prop) override { notSupported(prop); } void visit(const Reflection::Property<Vec2>& prop) override { notSupported(prop); } void visit(const Reflection::Property<Vec3>& prop) override { notSupported(prop); } void visit(const Reflection::Property<Vec4>& prop) override { notSupported(prop); } void visit(const Reflection::Property<const char*>& prop) override { if (!equalStrings(property_name, prop.name)) return; if (!lua_isstring(L, -1)) return; const char* str = lua_tostring(L, -1); editor->setProperty(cmp_type, 0, prop, &entity, 1, str, stringLength(str) + 1); } void visit(const Reflection::Property<Path>& prop) override { if (!equalStrings(property_name, prop.name)) return; if (!lua_isstring(L, -1)) return; const char* str = lua_tostring(L, -1); editor->setProperty(cmp_type, 0, prop, &entity, 1, str, stringLength(str) + 1); } void visit(const Reflection::Property<bool>& prop) override { if (!equalStrings(property_name, prop.name)) return; if (!lua_isboolean(L, -1)) return; bool val = lua_toboolean(L, -1) != 0; editor->setProperty(cmp_type, 0, prop, &entity, 1, &val, sizeof(val)); } void visit(const Reflection::IArrayProperty& prop) override { notSupported(prop); } void visit(const Reflection::IEnumProperty& prop) override { notSupported(prop); } void visit(const Reflection::IBlobProperty& prop) override { notSupported(prop); } void visit(const Reflection::ISampledFuncProperty& prop) override { notSupported(prop); } void notSupported(const Reflection::PropertyBase& prop) { if (!equalStrings(property_name, prop.name)) return; g_log_error.log("Lua Script") << "Property " << prop.name << " has unsupported type"; } lua_State* L; EntityRef entity; ComponentType cmp_type; const char* property_name; WorldEditor* editor; }; static int createEntityEx(lua_State* L) { auto* studio = LuaWrapper::checkArg<StudioAppImpl*>(L, 1); LuaWrapper::checkTableArg(L, 2); WorldEditor& editor = *studio->m_editor; editor.beginCommandGroup(crc32("createEntityEx")); EntityRef e = editor.addEntity(); editor.selectEntities(&e, 1, false); lua_pushvalue(L, 2); lua_pushnil(L); while (lua_next(L, -2) != 0) { const char* parameter_name = luaL_checkstring(L, -2); if (equalStrings(parameter_name, "position")) { const DVec3 pos = LuaWrapper::toType<DVec3>(L, -1); editor.setEntitiesPositions(&e, &pos, 1); } else if (equalStrings(parameter_name, "rotation")) { const Quat rot = LuaWrapper::toType<Quat>(L, -1); editor.setEntitiesRotations(&e, &rot, 1); } else { ComponentType cmp_type = Reflection::getComponentType(parameter_name); editor.addComponent(cmp_type); IScene* scene = editor.getUniverse()->getScene(cmp_type); if (scene) { ComponentUID cmp(e, cmp_type, scene); const Reflection::ComponentBase* cmp_des = Reflection::getComponent(cmp_type); if (cmp.isValid()) { lua_pushvalue(L, -1); lua_pushnil(L); while (lua_next(L, -2) != 0) { const char* property_name = luaL_checkstring(L, -2); SetPropertyVisitor v; v.property_name = property_name; v.entity = (EntityRef)cmp.entity; v.cmp_type = cmp.type; v.L = L; v.editor = &editor; cmp_des->visit(v); lua_pop(L, 1); } lua_pop(L, 1); } } } lua_pop(L, 1); } lua_pop(L, 1); editor.endCommandGroup(); LuaWrapper::push(L, e); return 1; } static int getResources(lua_State* L) { auto* studio = LuaWrapper::checkArg<StudioAppImpl*>(L, 1); auto* type = LuaWrapper::checkArg<const char*>(L, 2); AssetCompiler& compiler = studio->getAssetCompiler(); if (ResourceType(type) == INVALID_RESOURCE_TYPE) return 0; auto& resources_paths = compiler.getResources(ResourceType(type)); lua_createtable(L, resources_paths.size(), 0); int i = 0; for (auto& path : resources_paths) { LuaWrapper::push(L, path.c_str()); lua_rawseti(L, -2, i + 1); ++i; } return 1; } void executeUndoStack(const char* path) { m_editor->executeUndoStack(Path(path)); } void saveUniverseAs(const char* basename, bool save_path) { m_editor->saveUniverse(basename, save_path); } void saveUniverse() { save(); } bool runTest(const char* dir, const char* name) { return m_editor->runTest(dir, name); } void createLua() { lua_State* L = m_engine->getState(); LuaWrapper::createSystemVariable(L, "Editor", "editor", this); #define REGISTER_FUNCTION(F) \ do \ { \ auto f = &LuaWrapper::wrapMethodClosure<StudioAppImpl, decltype(&StudioAppImpl::F), &StudioAppImpl::F>; \ LuaWrapper::createSystemClosure(L, "Editor", this, #F, f); \ } while (false) REGISTER_FUNCTION(savePrefabAs); REGISTER_FUNCTION(selectEntity); REGISTER_FUNCTION(createEntity); REGISTER_FUNCTION(createComponent); REGISTER_FUNCTION(destroyEntity); REGISTER_FUNCTION(newUniverse); REGISTER_FUNCTION(saveUniverse); REGISTER_FUNCTION(saveUniverseAs); REGISTER_FUNCTION(runTest); REGISTER_FUNCTION(executeUndoStack); REGISTER_FUNCTION(exitWithCode); REGISTER_FUNCTION(exitGameMode); #undef REGISTER_FUNCTION LuaWrapper::createSystemFunction(L, "Editor", "getResources", &getResources); LuaWrapper::createSystemFunction(L, "Editor", "createEntityEx", &createEntityEx); } void checkScriptCommandLine() { char command_line[1024]; OS::getCommandLine(command_line, lengthOf(command_line)); CommandLineParser parser(command_line); while (parser.next()) { if (parser.currentEquals("-run_script")) { if (!parser.next()) break; char tmp[MAX_PATH_LENGTH]; parser.getCurrent(tmp, lengthOf(tmp)); FS::OsFile file; if (file.open(tmp, FS::Mode::OPEN_AND_READ)) { auto size = file.size(); auto* src = (char*)m_allocator.allocate(size + 1); file.read(src, size); src[size] = 0; runScript((const char*)src, tmp); m_allocator.deallocate(src); file.close(); } else { g_log_error.log("Editor") << "Could not open " << tmp; } break; } } } static bool includeFileInPack(const char* filename) { if (filename[0] == '.') return false; if (compareStringN("bin/", filename, 4) == 0) return false; if (compareStringN("bin32/", filename, 4) == 0) return false; if (equalStrings("data.pak", filename)) return false; if (equalStrings("error.log", filename)) return false; return true; } static bool includeDirInPack(const char* filename) { if (filename[0] == '.') return false; if (compareStringN("bin", filename, 4) == 0) return false; if (compareStringN("bin32", filename, 4) == 0) return false; return true; } #pragma pack(1) struct PackFileInfo { u32 hash; u64 offset; u64 size; char path[MAX_PATH_LENGTH]; }; #pragma pack() void packDataScan(const char* dir_path, AssociativeArray<u32, PackFileInfo>& infos) { auto* iter = OS::createFileIterator(dir_path, m_allocator); OS::FileInfo info; while (OS::getNextFile(iter, &info)) { char normalized_path[MAX_PATH_LENGTH]; PathUtils::normalize(info.filename, normalized_path, lengthOf(normalized_path)); if (info.is_directory) { if (!includeDirInPack(normalized_path)) continue; char dir[MAX_PATH_LENGTH] = {0}; if (dir_path[0] != '.') copyString(dir, dir_path); catString(dir, info.filename); catString(dir, "/"); packDataScan(dir, infos); continue; } if (!includeFileInPack(normalized_path)) continue; StaticString<MAX_PATH_LENGTH> out_path; if (dir_path[0] == '.') { copyString(out_path.data, normalized_path); } else { copyString(out_path.data, dir_path); catString(out_path.data, normalized_path); } u32 hash = crc32(out_path.data); if (infos.find(hash) >= 0) continue; auto& out_info = infos.emplace(hash); copyString(out_info.path, out_path); out_info.hash = hash; out_info.size = OS::getFileSize(out_path.data); out_info.offset = ~0UL; } OS::destroyFileIterator(iter); } void packDataScanResources(AssociativeArray<u32, PackFileInfo>& infos) { ResourceManagerHub& rm = m_editor->getEngine().getResourceManager(); for (auto iter = rm.getAll().begin(), end = rm.getAll().end(); iter != end; ++iter) { const auto& resources = iter.value()->getResourceTable(); for (Resource* res : resources) { u32 hash = crc32(res->getPath().c_str()); auto& out_info = infos.emplace(hash); copyString(out_info.path, MAX_PATH_LENGTH, res->getPath().c_str()); out_info.hash = hash; out_info.size = OS::getFileSize(res->getPath().c_str()); out_info.offset = ~0UL; } } packDataScan("pipelines/", infos); StaticString<MAX_PATH_LENGTH> unv_path; unv_path << "universes/" << m_editor->getUniverse()->getName() << "/"; packDataScan(unv_path, infos); unv_path.data[0] = 0; unv_path << "universes/" << m_editor->getUniverse()->getName() << ".unv"; u32 hash = crc32(unv_path); auto& out_info = infos.emplace(hash); copyString(out_info.path, MAX_PATH_LENGTH, unv_path); out_info.hash = hash; out_info.size = OS::getFileSize(unv_path); out_info.offset = ~0UL; } void showPackDataDialog() { m_is_pack_data_dialog_open = true; } void onPackDataGUI() { if (!m_is_pack_data_dialog_open) return; if (ImGui::Begin("Pack data", &m_is_pack_data_dialog_open)) { ImGui::LabelText("Destination dir", "%s", m_pack.dest_dir.data); ImGui::SameLine(); if (ImGui::Button("Choose dir")) { if (OS::getOpenDirectory(m_pack.dest_dir.data, lengthOf(m_pack.dest_dir.data), ".")) { m_pack.dest_dir << "/"; } } ImGui::Combo("Mode", (int*)&m_pack.mode, "All files\0Loaded universe\0"); if (ImGui::Button("Pack")) packData(); } ImGui::End(); } void packData() { if (m_pack.dest_dir.empty()) return; char dest[MAX_PATH_LENGTH]; static const char* OUT_FILENAME = "data.pak"; copyString(dest, m_pack.dest_dir); catString(dest, OUT_FILENAME); AssociativeArray<u32, PackFileInfo> infos(m_allocator); infos.reserve(10000); switch (m_pack.mode) { case PackConfig::Mode::ALL_FILES: packDataScan("./", infos); break; case PackConfig::Mode::CURRENT_UNIVERSE: packDataScanResources(infos); break; default: ASSERT(false); break; } if (infos.size() == 0) { g_log_error.log("Editor") << "No files found while trying to create " << dest; return; } FS::OsFile file; if (!file.open(dest, FS::Mode::CREATE_AND_WRITE)) { g_log_error.log("Editor") << "Could not create " << dest; return; } int count = infos.size(); file.write(&count, sizeof(count)); u64 offset = sizeof(count) + (sizeof(u32) + sizeof(u64) * 2) * count; for (auto& info : infos) { info.offset = offset; offset += info.size; } for (auto& info : infos) { file.write(&info.hash, sizeof(info.hash)); file.write(&info.offset, sizeof(info.offset)); file.write(&info.size, sizeof(info.size)); } for (auto& info : infos) { FS::OsFile src; size_t src_size = OS::getFileSize(info.path); if (!src.open(info.path, FS::Mode::OPEN_AND_READ)) { file.close(); g_log_error.log("Editor") << "Could not open " << info.path; return; } u8 buf[4096]; for (; src_size > 0; src_size -= Math::minimum(sizeof(buf), src_size)) { size_t batch_size = Math::minimum(sizeof(buf), src_size); if (!src.read(buf, batch_size)) { file.close(); g_log_error.log("Editor") << "Could not read " << info.path; return; } file.write(buf, batch_size); } src.close(); } file.close(); const char* bin_files[] = {"app.exe", "dbghelp.dll", "dbgcore.dll"}; StaticString<MAX_PATH_LENGTH> src_dir("bin/"); if (!OS::fileExists("bin/app.exe")) { char tmp[MAX_PATH_LENGTH]; OS::getExecutablePath(tmp, lengthOf(tmp)); PathUtils::getDir(src_dir.data, lengthOf(src_dir.data), tmp); } for (auto& file : bin_files) { StaticString<MAX_PATH_LENGTH> tmp(m_pack.dest_dir, file); StaticString<MAX_PATH_LENGTH> src(src_dir, file); if (!OS::copyFile(src, tmp)) { g_log_error.log("Editor") << "Failed to copy " << src << " to " << tmp; } } for (GUIPlugin* plugin : m_gui_plugins) { if (!plugin->packData(m_pack.dest_dir)) { g_log_error.log("Editor") << "Plugin " << plugin->getName() << " failed to pack data."; } } } void loadLuaPlugin(const char* dir, const char* filename) { StaticString<MAX_PATH_LENGTH> path(dir, filename); FS::OsFile file; if (file.open(path, FS::Mode::OPEN_AND_READ)) { const int size = (int)file.size(); Array<u8> src(m_engine->getAllocator()); src.resize(size + 1); file.read(src.begin(), size); src[size] = 0; LuaPlugin* plugin = LUMIX_NEW(m_editor->getAllocator(), LuaPlugin)(*this, (const char*)src.begin(), filename); addPlugin(*plugin); file.close(); } else { g_log_warning.log("Editor") << "Failed to open " << path; } } void scanUniverses() { m_universes.clear(); auto* iter = OS::createFileIterator("universes/", m_allocator); OS::FileInfo info; while (OS::getNextFile(iter, &info)) { if (info.filename[0] == '.') continue; if (!info.is_directory) continue; if (startsWith(info.filename, "__")) continue; char basename[MAX_PATH_LENGTH]; PathUtils::getBasename(basename, lengthOf(basename), info.filename); m_universes.emplace(basename); } OS::destroyFileIterator(iter); } void findLuaPlugins(const char* dir) { auto* iter = OS::createFileIterator(dir, m_allocator); OS::FileInfo info; while (OS::getNextFile(iter, &info)) { char normalized_path[MAX_PATH_LENGTH]; PathUtils::normalize(info.filename, normalized_path, lengthOf(normalized_path)); if (normalized_path[0] == '.') continue; if (info.is_directory) { char dir_path[MAX_PATH_LENGTH] = {0}; if (dir[0] != '.') copyString(dir_path, dir); catString(dir_path, info.filename); catString(dir_path, "/"); findLuaPlugins(dir_path); } else { char ext[5]; PathUtils::getExtension(ext, lengthOf(ext), info.filename); if (equalStrings(ext, "lua")) { loadLuaPlugin(dir, info.filename); } } } OS::destroyFileIterator(iter); } const OS::Event* getEvents() const override { return m_events.empty() ? nullptr : &m_events[0]; } int getEventsCount() const override { return m_events.size(); } Vec2 getMouseMove() const override { return m_mouse_move; } void run() override {} static void checkWorkingDirector() { if (!OS::fileExists("../LumixStudio.lnk")) return; if (!OS::dirExists("bin") && OS::dirExists("../bin") && OS::dirExists("../pipelines")) { OS::setCurrentDirectory("../"); } if (!OS::dirExists("bin")) { OS::messageBox("Bin directory not found, please check working directory."); } else if (!OS::dirExists("pipelines")) { OS::messageBox("Pipelines directory not found, please check working directory."); } } void unloadIcons() { auto& render_interface = *m_editor->getRenderInterface(); for (auto* action : m_actions) { render_interface.unloadTexture(action->icon); } } void loadIcons() { RenderInterface& render_interface = *m_editor->getRenderInterface(); for (auto* action : m_actions) { char tmp[MAX_PATH_LENGTH]; action->getIconPath(tmp, lengthOf(tmp)); if (OS::fileExists(tmp)) { action->icon = render_interface.loadTexture(Path(tmp)); } else { action->icon = nullptr; } } } void checkShortcuts() { if (ImGui::IsAnyItemActive()) return; GUIPlugin* plugin = getFocusedPlugin(); u32 pressed_modifiers = 0; if (OS::isKeyDown(OS::Keycode::SHIFT)) pressed_modifiers |= 1; if (OS::isKeyDown(OS::Keycode::CTRL)) pressed_modifiers |= 2; if (OS::isKeyDown(OS::Keycode::MENU)) pressed_modifiers |= 4; for (Action* a : m_actions) { if (!a->is_global || a->shortcut[0] == OS::Keycode::INVALID) continue; if (a->plugin != plugin) continue; u32 action_modifiers = 0; for (int i = 0; i < lengthOf(a->shortcut) + 1; ++i) { if ((i == lengthOf(a->shortcut) || a->shortcut[i] == OS::Keycode::INVALID) && action_modifiers == pressed_modifiers) { a->func.invoke(); return; } if (i == lengthOf(a->shortcut)) break; if (a->shortcut[i] == OS::Keycode::INVALID) break; if (!OS::isKeyDown(a->shortcut[i])) break; switch (a->shortcut[i]) { case OS::Keycode::LSHIFT: case OS::Keycode::RSHIFT: case OS::Keycode::SHIFT: action_modifiers |= 1; break; case OS::Keycode::CTRL: case OS::Keycode::LCTRL: case OS::Keycode::RCTRL: action_modifiers |= 2; break; case OS::Keycode::MENU: action_modifiers |= 4; break; } } } } void* getWindow() override { return m_window; } WorldEditor& getWorldEditor() override { ASSERT(m_editor); return *m_editor; } ImFont* getBoldFont() override { return m_bold_font; } DefaultAllocator m_main_allocator; Debug::Allocator m_allocator; Engine* m_engine; OS::WindowHandle m_window; Array<Action*> m_actions; Array<Action*> m_window_actions; Array<Action*> m_toolbar_actions; Array<GUIPlugin*> m_gui_plugins; Array<IPlugin*> m_plugins; Array<IAddComponentPlugin*> m_add_cmp_plugins; Array<StaticString<MAX_PATH_LENGTH>> m_universes; AddCmpTreeNode m_add_cmp_root; HashMap<ComponentType, string> m_component_labels; WorldEditor* m_editor; Action* m_custom_pivot_action; bool m_confirm_exit; bool m_confirm_load; bool m_confirm_new; char m_universe_to_load[MAX_PATH_LENGTH]; AssetBrowser* m_asset_browser; AssetCompiler* m_asset_compiler; PropertyGrid* m_property_grid; LogUI* m_log_ui; ProfilerUI* m_profiler_ui; Settings m_settings; Array<OS::Event> m_events; Vec2 m_mouse_move; Timer* m_fps_timer; char m_template_name[100]; char m_open_filter[64]; char m_component_filter[32]; struct PackConfig { enum class Mode : int { ALL_FILES, CURRENT_UNIVERSE }; Mode mode; StaticString<MAX_PATH_LENGTH> dest_dir; }; PackConfig m_pack; bool m_finished; bool m_deferred_game_mode_exit; int m_exit_code; bool m_sleep_when_inactive; bool m_is_welcome_screen_open; bool m_is_pack_data_dialog_open; bool m_is_entity_list_open; bool m_is_save_as_dialog_open; bool m_is_edit_cam_transform_ui_open = false; ImFont* m_font; ImFont* m_bold_font; struct WatchedPlugin { FileSystemWatcher* watcher = nullptr; StaticString<MAX_PATH_LENGTH> dir; StaticString<MAX_PATH_LENGTH> basename; Lumix::IPlugin* plugin = nullptr; int iteration = 0; bool reload_request = false; } m_watched_plugin; }; static size_t alignMask(size_t _value, size_t _mask) { return (_value + _mask) & ((~0) & (~_mask)); } static void* alignPtr(void* _ptr, size_t _align) { union { void* ptr; size_t addr; } un; un.ptr = _ptr; size_t mask = _align - 1; size_t aligned = alignMask(un.addr, mask); un.addr = aligned; return un.ptr; } StudioApp* StudioApp::create() { static char buf[sizeof(StudioAppImpl) * 2]; return new (NewPlaceholder(), alignPtr(buf, alignof(StudioAppImpl))) StudioAppImpl; } void StudioApp::destroy(StudioApp& app) { app.~StudioApp(); } static StudioApp::StaticPluginRegister* s_first_plugin = nullptr; StudioApp::StaticPluginRegister::StaticPluginRegister(const char* name, Creator creator) { this->creator = creator; this->name = name; next = s_first_plugin; s_first_plugin = this; } void StudioApp::StaticPluginRegister::create(StudioApp& app) { auto* i = s_first_plugin; while (i) { StudioApp::IPlugin* plugin = i->creator(app); if (plugin) app.addPlugin(*plugin); i = i->next; } app.initPlugins(); } } // namespace Lumix
#include "studio_app.h" #include "asset_browser.h" #include "audio/audio_scene.h" #include "audio/clip_manager.h" #include "editor/entity_groups.h" #include "editor/gizmo.h" #include "editor/prefab_system.h" #include "editor/render_interface.h" #include "editor/world_editor.h" #include "engine/blob.h" #include "engine/command_line_parser.h" #include "engine/crc32.h" #include "engine/debug/debug.h" #include "engine/default_allocator.h" #include "engine/engine.h" #include "engine/fs/disk_file_device.h" #include "engine/fs/file_system.h" #include "engine/fs/os_file.h" #include "engine/input_system.h" #include "engine/log.h" #include "engine/lua_wrapper.h" #include "engine/mt/thread.h" #include "engine/path_utils.h" #include "engine/plugin_manager.h" #include "engine/profiler.h" #include "engine/property_register.h" #include "engine/quat.h" #include "engine/resource_manager.h" #include "engine/system.h" #include "engine/timer.h" #include "engine/universe/universe.h" #include "imgui/imgui.h" #include "log_ui.h" #include "metadata.h" #include "platform_interface.h" #include "profiler_ui.h" #include "property_grid.h" #include "settings.h" #include "utils.h" #include <SDL.h> #include <SDL_syswm.h> struct LuaPlugin : public StudioApp::IPlugin { LuaPlugin(StudioApp& app, const char* src, const char* filename) : editor(*app.getWorldEditor()) { L = lua_newthread(editor.getEngine().getState()); thread_ref = luaL_ref(editor.getEngine().getState(), LUA_REGISTRYINDEX); bool errors = luaL_loadbuffer(L, src, Lumix::stringLength(src), filename) != LUA_OK; errors = errors || lua_pcall(L, 0, 0, 0) != LUA_OK; if (errors) { Lumix::g_log_error.log("Editor") << filename << ": " << lua_tostring(L, -1); lua_pop(L, 1); } const char* name = "LuaPlugin"; if (lua_getglobal(L, "plugin_name") == LUA_TSTRING) { name = lua_tostring(L, -1); } Action* action = LUMIX_NEW(editor.getAllocator(), Action)(name, name); action->func.bind<LuaPlugin, &LuaPlugin::onAction>(this); app.addWindowAction(action); m_is_opened = false; lua_pop(L, 1); // plugin_name } ~LuaPlugin() { luaL_unref(editor.getEngine().getState(), LUA_REGISTRYINDEX, thread_ref); } const char* getName() const override { return "lua_script"; } void onAction() { m_is_opened = !m_is_opened; } void onWindowGUI() override { if (!m_is_opened) return; if (lua_getglobal(L, "onGUI") == LUA_TFUNCTION) { if (lua_pcall(L, 0, 0, 0) != LUA_OK) { Lumix::g_log_error.log("Editor") << "LuaPlugin:" << lua_tostring(L, -1); lua_pop(L, 1); } } else { lua_pop(L, 1); } } Lumix::WorldEditor& editor; lua_State* L; int thread_ref; bool m_is_opened; }; class StudioAppImpl LUMIX_FINAL : public StudioApp { public: StudioAppImpl() : m_is_entity_list_opened(true) , m_is_save_as_dialog_opened(false) , m_finished(false) , m_selected_template_name(m_allocator) , m_profiler_ui(nullptr) , m_asset_browser(nullptr) , m_property_grid(nullptr) , m_actions(m_allocator) , m_window_actions(m_allocator) , m_toolbar_actions(m_allocator) , m_metadata(m_allocator) , m_is_welcome_screen_opened(true) , m_editor(nullptr) , m_settings(*this) , m_plugins(m_allocator) , m_add_cmp_plugins(m_allocator) , m_component_labels(m_allocator) , m_confirm_load(false) , m_confirm_new(false) , m_confirm_exit(false) , m_exit_code(0) , m_allocator(m_main_allocator) , m_universes(m_allocator) { m_add_cmp_root.label[0] = '\0'; m_drag_data = {DragData::NONE, nullptr, 0}; m_template_name[0] = '\0'; m_open_filter[0] = '\0'; init(); registerComponent("hierarchy", "Hierarchy"); } ~StudioAppImpl() { m_allocator.deallocate(m_drag_data.data); saveSettings(); unloadIcons(); while (m_editor->getEngine().getFileSystem().hasWork()) { m_editor->getEngine().getFileSystem().updateAsyncTransactions(); } m_editor->newUniverse(); destroyAddCmpTreeNode(m_add_cmp_root.child); for (auto* plugin : m_plugins) { LUMIX_DELETE(m_editor->getAllocator(), plugin); } m_plugins.clear(); for (auto* i : m_add_cmp_plugins) { LUMIX_DELETE(m_editor->getAllocator(), i); } m_add_cmp_plugins.clear(); for (auto* a : m_actions) { LUMIX_DELETE(m_editor->getAllocator(), a); } m_actions.clear(); ProfilerUI::destroy(*m_profiler_ui); LUMIX_DELETE(m_allocator, m_asset_browser); LUMIX_DELETE(m_allocator, m_property_grid); LUMIX_DELETE(m_allocator, m_log_ui); Lumix::WorldEditor::destroy(m_editor, m_allocator); Lumix::Engine::destroy(m_engine, m_allocator); m_engine = nullptr; m_editor = nullptr; SDL_DestroyWindow(m_window); SDL_Quit(); } void destroyAddCmpTreeNode(AddCmpTreeNode* node) { if (!node) return; destroyAddCmpTreeNode(node->child); destroyAddCmpTreeNode(node->next); LUMIX_DELETE(m_allocator, node); } const char* getComponentTypeName(Lumix::ComponentType cmp_type) const override { auto iter = m_component_labels.find(cmp_type); if (iter == m_component_labels.end()) return "Unknown"; return iter.value().c_str(); } const AddCmpTreeNode& getAddComponentTreeRoot() const override { return m_add_cmp_root; } void addPlugin(IAddComponentPlugin& plugin) { int i = 0; while (i < m_add_cmp_plugins.size() && Lumix::compareString(plugin.getLabel(), m_add_cmp_plugins[i]->getLabel()) > 0) { ++i; } m_add_cmp_plugins.insert(i, &plugin); auto* node = LUMIX_NEW(m_allocator, AddCmpTreeNode); Lumix::copyString(node->label, plugin.getLabel()); node->plugin = &plugin; insertAddCmpNode(m_add_cmp_root, node); } void insertAddCmpNodeOrdered(AddCmpTreeNode& parent, AddCmpTreeNode* node) { if (!parent.child) { parent.child = node; return; } if (Lumix::compareString(parent.child->label, node->label) > 0) { node->next = parent.child; parent.child = node; return; } auto* i = parent.child; while (i->next && Lumix::compareString(i->next->label, node->label) < 0) { i = i->next; } node->next = i->next; i->next = node; } void insertAddCmpNode(AddCmpTreeNode& parent, AddCmpTreeNode* node) { for (auto* i = parent.child; i; i = i->next) { if (!i->plugin && Lumix::startsWith(node->label, i->label)) { insertAddCmpNode(*i, node); return; } } const char* rest = node->label + Lumix::stringLength(parent.label); if (parent.label[0] != '\0') ++rest; // include '/' const char* slash = Lumix::findSubstring(rest, "/"); if (!slash) { insertAddCmpNodeOrdered(parent, node); return; } auto* new_group = LUMIX_NEW(m_allocator, AddCmpTreeNode); Lumix::copyNString(new_group->label, (int)sizeof(new_group->label), node->label, int(slash - node->label)); insertAddCmpNodeOrdered(parent, new_group); insertAddCmpNode(*new_group, node); } void registerComponentWithResource(const char* type, const char* label, Lumix::ResourceType resource_type, const char* property_name) override { struct Plugin LUMIX_FINAL : public IAddComponentPlugin { void onGUI(bool create_entity, bool from_filter) override { ImGui::SetNextWindowSize(ImVec2(300, 300)); const char* last = Lumix::reverseFind(label, nullptr, '/'); if (!ImGui::BeginMenu(last && !from_filter ? last + 1 : label)) return; auto* desc = Lumix::PropertyRegister::getDescriptor(type, property_id); char buf[Lumix::MAX_PATH_LENGTH]; bool create_empty = ImGui::Selectable("Empty", false); if (asset_browser->resourceList(buf, Lumix::lengthOf(buf), resource_type, 0) || create_empty) { if (create_entity) { Lumix::Entity entity = editor->addEntity(); editor->selectEntities(&entity, 1); } editor->addComponent(type); if (!create_empty) { editor->setProperty(type, -1, *desc, &editor->getSelectedEntities()[0], editor->getSelectedEntities().size(), buf, Lumix::stringLength(buf) + 1); } ImGui::CloseCurrentPopup(); } ImGui::EndMenu(); } const char* getLabel() const override { return label; } PropertyGrid* property_grid; AssetBrowser* asset_browser; Lumix::WorldEditor* editor; Lumix::ComponentType type; Lumix::ResourceType resource_type; Lumix::u32 property_id; char label[50]; }; auto& allocator = m_editor->getAllocator(); auto* plugin = LUMIX_NEW(allocator, Plugin); plugin->property_grid = m_property_grid; plugin->asset_browser = m_asset_browser; plugin->type = Lumix::PropertyRegister::getComponentType(type); plugin->editor = m_editor; plugin->property_id = Lumix::crc32(property_name); plugin->resource_type = resource_type; Lumix::copyString(plugin->label, label); addPlugin(*plugin); m_component_labels.insert(plugin->type, Lumix::string(label, m_allocator)); } void registerComponent(const char* id, const char* label, IAddComponentPlugin& plugin) override { addPlugin(plugin); auto& allocator = m_editor->getAllocator(); m_component_labels.insert(Lumix::PropertyRegister::getComponentType(id), Lumix::string(label, m_allocator)); } void registerComponent(const char* type, const char* label) override { struct Plugin LUMIX_FINAL : public IAddComponentPlugin { void onGUI(bool create_entity, bool from_filter) override { const char* last = Lumix::reverseFind(label, nullptr, '/'); if (ImGui::Selectable(last && !from_filter ? last + 1 : label)) { if (create_entity) { Lumix::Entity entity = editor->addEntity(); editor->selectEntities(&entity, 1); } editor->addComponent(type); } } const char* getLabel() const override { return label; } Lumix::WorldEditor* editor; PropertyGrid* property_grid; Lumix::ComponentType type; char label[64]; }; auto& allocator = m_editor->getAllocator(); auto* plugin = LUMIX_NEW(allocator, Plugin); plugin->property_grid = m_property_grid; plugin->editor = m_editor; plugin->type = Lumix::PropertyRegister::getComponentType(type); Lumix::copyString(plugin->label, label); addPlugin(*plugin); m_component_labels.insert(plugin->type, Lumix::string(label, m_allocator)); } const Lumix::Array<Action*>& getActions() override { return m_actions; } Lumix::Array<Action*>& getToolbarActions() override { return m_toolbar_actions; } void guiBeginFrame() { PROFILE_FUNCTION(); ImGuiIO& io = ImGui::GetIO(); int w, h; SDL_GetWindowSize(m_window, &w, &h); io.DisplaySize = ImVec2((float)w, (float)h); io.DeltaTime = m_engine->getLastTimeDelta(); io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); ImGui::NewFrame(); ImGui::PushFont(m_font); if (m_drag_data.type == DragData::PATH) { ImGui::BeginTooltip(); char tmp[Lumix::MAX_PATH_LENGTH]; Lumix::PathUtils::getFilename(tmp, Lumix::lengthOf(tmp), (const char*)m_drag_data.data); ImGui::Text("%s", tmp); ImGui::EndTooltip(); } else if (m_drag_data.type == DragData::ENTITY) { ImGui::BeginTooltip(); char buf[1024]; getEntityListDisplayName(*m_editor, buf, Lumix::lengthOf(buf), *(Lumix::Entity*)m_drag_data.data); ImGui::Text("%s", buf); ImGui::EndTooltip(); } } float showMainToolbar(float menu_height) { if (m_toolbar_actions.empty()) return menu_height; auto frame_padding = ImGui::GetStyle().FramePadding; float padding = frame_padding.y * 2; ImVec4 active_color = ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]; ImVec4 inactive_color(0, 0, 0, 0); ImVec2 toolbar_size(ImGui::GetIO().DisplaySize.x, 24 + padding); if (ImGui::BeginToolbar("main_toolbar", ImVec2(1, menu_height), toolbar_size)) { auto& render_interface = *m_editor->getRenderInterface(); for (auto* action : m_toolbar_actions) { action->toolbarButton(); } } ImGui::EndToolbar(); return menu_height + 24 + padding; } void guiEndFrame() { if (m_is_welcome_screen_opened) { showWelcomeScreen(); } else { float menu_height = showMainMenu(); float toolbar_bottom = showMainToolbar(menu_height); if (ImGui::GetIO().DisplaySize.y > 0) { auto pos = ImVec2(0, toolbar_bottom); auto size = ImGui::GetIO().DisplaySize; size.y -= pos.y; ImGui::RootDock(pos, size); } m_profiler_ui->onGUI(); m_asset_browser->onGUI(); m_log_ui->onGUI(); m_property_grid->onGUI(); onEntityListGUI(); onSaveAsDialogGUI(); for (auto* plugin : m_plugins) { plugin->onWindowGUI(); } m_settings.onGUI(); } ImGui::PopFont(); ImGui::Render(); if (ImGui::GetIO().MouseReleased[0]) { m_allocator.deallocate(m_drag_data.data); m_drag_data.data = nullptr; m_drag_data.size = 0; m_drag_data.type = DragData::NONE; } } void update() { PROFILE_FUNCTION(); guiBeginFrame(); float time_delta = m_editor->getEngine().getLastTimeDelta(); m_editor->setMouseSensitivity(m_settings.m_mouse_sensitivity_x, m_settings.m_mouse_sensitivity_y); m_editor->update(); m_engine->update(*m_editor->getUniverse()); for (auto* plugin : m_plugins) { plugin->update(time_delta); } m_asset_browser->update(); m_log_ui->update(time_delta); guiEndFrame(); } void showWelcomeScreen() { ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings; int w, h; SDL_GetWindowSize(m_window, &w, &h); ImVec2 size((float)w, (float)h); if (ImGui::Begin("Welcome", nullptr, size, -1, flags)) { ImGui::Text("Welcome to Lumix Studio"); ImVec2 half_size = ImGui::GetContentRegionAvail(); half_size.x = half_size.x * 0.5f - ImGui::GetStyle().FramePadding.x; half_size.y *= 0.75f; auto right_pos = ImGui::GetCursorPos(); right_pos.x += half_size.x + ImGui::GetStyle().FramePadding.x; if (ImGui::BeginChild("left", half_size, true)) { if (ImGui::Button("New Universe")) m_is_welcome_screen_opened = false; ImGui::Separator(); ImGui::Text("Open universe:"); ImGui::Indent(); for (auto& univ : m_universes) { if (ImGui::MenuItem(univ.data)) { m_editor->loadUniverse(univ.data); setTitle(univ.data); m_is_welcome_screen_opened = false; } } ImGui::Unindent(); } ImGui::EndChild(); ImGui::SetCursorPos(right_pos); if (ImGui::BeginChild("right", half_size, true)) { if (ImGui::Button("Wiki")) { PlatformInterface::shellExecuteOpen("https://github.com/nem0/LumixEngine/wiki"); } if (ImGui::Button("Download new version")) { PlatformInterface::shellExecuteOpen("https://github.com/nem0/lumixengine_data/archive/master.zip"); } if (ImGui::Button("Show major releases")) { PlatformInterface::shellExecuteOpen("https://github.com/nem0/LumixEngine/releases"); } if (ImGui::Button("Show latest commits")) { PlatformInterface::shellExecuteOpen("https://github.com/nem0/LumixEngine/commits/master"); } if (ImGui::Button("Show issues")) { PlatformInterface::shellExecuteOpen("https://github.com/nem0/lumixengine/issues"); } } ImGui::EndChild(); } ImGui::End(); } void setTitle(const char* title) { char tmp[100]; Lumix::copyString(tmp, "Lumix Studio - "); Lumix::catString(tmp, title); SDL_SetWindowTitle(m_window, tmp); } static void getShortcut(const Action& action, char* buf, int max_size) { buf[0] = 0; for (int i = 0; i < Lumix::lengthOf(action.shortcut); ++i) { const char* str = SDL_GetKeyName(SDL_GetKeyFromScancode((SDL_Scancode)action.shortcut[i])); if (str[0] == 0) return; if (i > 0) Lumix::catString(buf, max_size, " - "); Lumix::catString(buf, max_size, str); } } void doMenuItem(Action& a, bool enabled) { char buf[20]; getShortcut(a, buf, sizeof(buf)); if (ImGui::MenuItem(a.label, buf, a.is_selected.invoke(), enabled)) { a.func.invoke(); } } void save() { if (m_editor->isGameMode()) { Lumix::g_log_error.log("Editor") << "Could not save while the game is running"; return; } if (m_editor->getUniverse()->getName()[0]) { m_editor->saveUniverse(m_editor->getUniverse()->getName(), true); } else { saveAs(); } } void onSaveAsDialogGUI() { if (!m_is_save_as_dialog_opened) return; if (ImGui::Begin("Save Universe As")) { static char name[64] = ""; ImGui::InputText("Name", name, Lumix::lengthOf(name)); if (ImGui::Button("Save")) { m_is_save_as_dialog_opened = false; setTitle(name); m_editor->saveUniverse(name, true); } } ImGui::End(); } void saveAs() { if (m_editor->isGameMode()) { Lumix::g_log_error.log("Editor") << "Could not save while the game is running"; return; } m_is_save_as_dialog_opened = true; } void exit() { if (m_editor->isUniverseChanged()) { m_confirm_exit = true; } else { m_finished = true; } } void newUniverse() { if (m_editor->isUniverseChanged()) { m_confirm_new = true; } else { m_editor->newUniverse(); } } bool hasPluginFocus() { for(auto* plugin : m_plugins) { if(plugin->hasFocus()) return true; } return false; } void undo() { if (!hasPluginFocus()) m_editor->undo(); } void redo() { if (!hasPluginFocus()) m_editor->redo(); } void copy() { m_editor->copyEntities(); } void paste() { m_editor->pasteEntities(); } bool isOrbitCamera() { return m_editor->isOrbitCamera(); } void toggleOrbitCamera() { m_editor->setOrbitCamera(!m_editor->isOrbitCamera()); } void setTopView() { m_editor->setTopView(); } void setFrontView() { m_editor->setFrontView(); } void setSideView() { m_editor->setSideView(); } void setLocalCoordSystem() { m_editor->getGizmo().setLocalCoordSystem(); } void setGlobalCoordSystem() { m_editor->getGizmo().setGlobalCoordSystem(); } void setPivotOrigin() { m_editor->getGizmo().setPivotOrigin(); } void setPivotCenter() { m_editor->getGizmo().setPivotCenter(); } void createEntity() { m_editor->addEntity(); } void showEntities() { m_editor->showSelectedEntities(); } void hideEntities() { m_editor->hideSelectedEntities(); } void toggleMeasure() { m_editor->toggleMeasure(); } void snapDown() { m_editor->snapDown(); } void lookAtSelected() { m_editor->lookAtSelected(); } void toggleSettings() { m_settings.m_is_opened = !m_settings.m_is_opened; } bool areSettingsOpened() const { return m_settings.m_is_opened; } void toggleEntityList() { m_is_entity_list_opened = !m_is_entity_list_opened; } bool isEntityListOpened() const { return m_is_entity_list_opened; } void toggleAssetBrowser() { m_asset_browser->m_is_opened = !m_asset_browser->m_is_opened; } bool isAssetBrowserOpened() const { return m_asset_browser->m_is_opened; } int getExitCode() const override { return m_exit_code; } AssetBrowser* getAssetBrowser() override { return m_asset_browser; } PropertyGrid* getPropertyGrid() override { return m_property_grid; } Metadata* getMetadata() override { return &m_metadata; } LogUI* getLogUI() override { return m_log_ui; } void toggleGameMode() { m_editor->toggleGameMode(); } void setTranslateGizmoMode() { m_editor->getGizmo().setTranslateMode(); } void setRotateGizmoMode() { m_editor->getGizmo().setRotateMode(); } void savePrefab() { char filename[Lumix::MAX_PATH_LENGTH]; char tmp[Lumix::MAX_PATH_LENGTH]; if (PlatformInterface::getSaveFilename(tmp, Lumix::lengthOf(tmp), "Prefab files\0*.fab\0", "fab")) { Lumix::PathUtils::normalize(tmp, filename, Lumix::lengthOf(tmp)); const char* base_path = m_engine->getDiskFileDevice()->getBasePath(); if (Lumix::startsWith(filename, base_path)) { m_editor->getPrefabSystem().savePrefab(Lumix::Path(filename + Lumix::stringLength(base_path))); } else { base_path = m_engine->getPatchFileDevice() ? m_engine->getPatchFileDevice()->getBasePath() : nullptr; if (base_path && Lumix::startsWith(filename, base_path)) { m_editor->getPrefabSystem().savePrefab(Lumix::Path(filename + Lumix::stringLength(base_path))); } else { m_editor->getPrefabSystem().savePrefab(Lumix::Path(filename)); } } } } void autosnapDown() { auto& gizmo = m_editor->getGizmo(); gizmo.setAutosnapDown(!gizmo.isAutosnapDown()); } void destroyEntity() { auto& selected_entities = m_editor->getSelectedEntities(); if (selected_entities.empty()) return; m_editor->destroyEntities(&selected_entities[0], selected_entities.size()); } void loadAndExecuteCommands() { char filename[Lumix::MAX_PATH_LENGTH]; if (PlatformInterface::getOpenFilename(filename, Lumix::lengthOf(filename), "JSON files\0*.json\0", nullptr)) { m_editor->executeUndoStack(Lumix::Path(filename)); } } void saveUndoStack() { char filename[Lumix::MAX_PATH_LENGTH]; if (PlatformInterface::getSaveFilename(filename, Lumix::lengthOf(filename), "JSON files\0*.json\0", "json")) { m_editor->saveUndoStack(Lumix::Path(filename)); } } void addWindowAction(Action* action) override { addAction(action); for (int i = 0; i < m_window_actions.size(); ++i) { if (Lumix::compareString(m_window_actions[i]->label, action->label) > 0) { m_window_actions.insert(i, action); return; } } m_window_actions.push(action); } void addAction(Action* action) override { for (int i = 0; i < m_actions.size(); ++i) { if (Lumix::compareString(m_actions[i]->label, action->label) > 0) { m_actions.insert(i, action); return; } } m_actions.push(action); } template <void (StudioAppImpl::*func)()> Action& addAction(const char* label, const char* name) { auto* a = LUMIX_NEW(m_editor->getAllocator(), Action)(label, name); a->func.bind<StudioAppImpl, func>(this); addAction(a); return *a; } template <void (StudioAppImpl::*func)()> void addAction(const char* label, const char* name, int shortcut0, int shortcut1, int shortcut2) { auto* a = LUMIX_NEW(m_editor->getAllocator(), Action)( label, name, shortcut0, shortcut1, shortcut2); a->func.bind<StudioAppImpl, func>(this); addAction(a); } Action* getAction(const char* name) override { for (auto* a : m_actions) { if (Lumix::equalStrings(a->name, name)) return a; } return nullptr; } static void showAddComponentNode(const StudioApp::AddCmpTreeNode* node, const char* filter) { if (!node) return; if (filter[0]) { if (!node->plugin) showAddComponentNode(node->child, filter); else if (Lumix::stristr(node->plugin->getLabel(), filter)) node->plugin->onGUI(false, true); showAddComponentNode(node->next, filter); return; } if (node->plugin) { node->plugin->onGUI(false, false); showAddComponentNode(node->next, filter); return; } const char* last = Lumix::reverseFind(node->label, nullptr, '/'); if (ImGui::BeginMenu(last ? last + 1 : node->label)) { showAddComponentNode(node->child, filter); ImGui::EndMenu(); } showAddComponentNode(node->next, filter); } void onCreateEntityWithComponentGUI() { doMenuItem(*getAction("createEntity"), true); ImGui::Separator(); ImGui::FilterInput("Filter", m_component_filter, sizeof(m_component_filter)); showAddComponentNode(m_add_cmp_root.child, m_component_filter); } void entityMenu() { if (!ImGui::BeginMenu("Entity")) return; bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); if (ImGui::BeginMenu("Create")) { onCreateEntityWithComponentGUI(); ImGui::EndMenu(); } doMenuItem(*getAction("destroyEntity"), is_any_entity_selected); doMenuItem(*getAction("savePrefab"), is_any_entity_selected); doMenuItem(*getAction("showEntities"), is_any_entity_selected); doMenuItem(*getAction("hideEntities"), is_any_entity_selected); ImGui::EndMenu(); } void editMenu() { if (!ImGui::BeginMenu("Edit")) return; bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); doMenuItem(*getAction("undo"), m_editor->canUndo()); doMenuItem(*getAction("redo"), m_editor->canRedo()); ImGui::Separator(); doMenuItem(*getAction("copy"), is_any_entity_selected); doMenuItem(*getAction("paste"), m_editor->canPasteEntities()); ImGui::Separator(); doMenuItem(*getAction("orbitCamera"), is_any_entity_selected || m_editor->isOrbitCamera()); doMenuItem(*getAction("setTranslateGizmoMode"), true); doMenuItem(*getAction("setRotateGizmoMode"), true); doMenuItem(*getAction("setPivotCenter"), true); doMenuItem(*getAction("setPivotOrigin"), true); doMenuItem(*getAction("setLocalCoordSystem"), true); doMenuItem(*getAction("setGlobalCoordSystem"), true); if (ImGui::BeginMenu("View", true)) { doMenuItem(*getAction("viewTop"), true); doMenuItem(*getAction("viewFront"), true); doMenuItem(*getAction("viewSide"), true); ImGui::EndMenu(); } ImGui::EndMenu(); } void fileMenu() { if (!ImGui::BeginMenu("File")) return; doMenuItem(*getAction("newUniverse"), true); if (ImGui::BeginMenu("Open")) { ImGui::FilterInput("Filter", m_open_filter, sizeof(m_open_filter)); for (auto& univ : m_universes) { if ((m_open_filter[0] == '\0' || Lumix::stristr(univ.data, m_open_filter)) && ImGui::MenuItem(univ.data)) { if (m_editor->isUniverseChanged()) { Lumix::copyString(m_universe_to_load, univ.data); m_confirm_load = true; } else { m_editor->loadUniverse(univ.data); setTitle(univ.data); } } } ImGui::EndMenu(); } doMenuItem(*getAction("save"), !m_editor->isGameMode()); doMenuItem(*getAction("saveAs"), !m_editor->isGameMode()); doMenuItem(*getAction("exit"), true); ImGui::EndMenu(); } void toolsMenu() { if (!ImGui::BeginMenu("Tools")) return; bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); doMenuItem(*getAction("lookAtSelected"), is_any_entity_selected); doMenuItem(*getAction("toggleGameMode"), true); doMenuItem(*getAction("toggleMeasure"), true); doMenuItem(*getAction("snapDown"), is_any_entity_selected); doMenuItem(*getAction("autosnapDown"), true); if (ImGui::MenuItem("Save commands")) saveUndoStack(); if (ImGui::MenuItem("Load commands")) loadAndExecuteCommands(); if (ImGui::MenuItem("Pack data")) packData(); ImGui::EndMenu(); } void viewMenu() { if (!ImGui::BeginMenu("View")) return; ImGui::MenuItem("Asset browser", nullptr, &m_asset_browser->m_is_opened); doMenuItem(*getAction("entityList"), true); ImGui::MenuItem("Log", nullptr, &m_log_ui->m_is_opened); ImGui::MenuItem("Profiler", nullptr, &m_profiler_ui->m_is_opened); ImGui::MenuItem("Properties", nullptr, &m_property_grid->m_is_opened); doMenuItem(*getAction("settings"), true); ImGui::Separator(); for (Action* action : m_window_actions) { doMenuItem(*action, true); } ImGui::EndMenu(); } float showMainMenu() { bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); if (m_confirm_exit) { ImGui::OpenPopup("confirm_exit"); m_confirm_exit = false; } if (ImGui::BeginPopupModal("confirm_exit")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { m_finished = true; ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } if (m_confirm_new) { ImGui::OpenPopup("confirm_new"); m_confirm_new = false; } if (ImGui::BeginPopupModal("confirm_new")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { m_editor->newUniverse(); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } if (m_confirm_load) { ImGui::OpenPopup("confirm_load"); m_confirm_load = false; } if(ImGui::BeginPopupModal("confirm_load")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { m_editor->loadUniverse(m_universe_to_load); setTitle(m_universe_to_load); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } float menu_height = 0; if (ImGui::BeginMainMenuBar()) { fileMenu(); editMenu(); entityMenu(); toolsMenu(); viewMenu(); Lumix::StaticString<200> stats(""); if (m_engine->getFileSystem().hasWork()) stats << "Loading... | "; stats << "FPS: "; stats << m_engine->getFPS(); if ((SDL_GetWindowFlags(m_window) & SDL_WINDOW_INPUT_FOCUS) == 0) stats << " - inactive window"; auto stats_size = ImGui::CalcTextSize(stats); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); ImGui::Text("%s", (const char*)stats); if (m_log_ui->getUnreadErrorCount() == 1) { ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); auto error_stats_size = ImGui::CalcTextSize("1 error | "); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x - error_stats_size.x); ImGui::TextColored(ImVec4(1, 0, 0, 1), "1 error | "); } else if (m_log_ui->getUnreadErrorCount() > 1) { Lumix::StaticString<50> error_stats("", m_log_ui->getUnreadErrorCount(), " errors | "); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); auto error_stats_size = ImGui::CalcTextSize(error_stats); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x - error_stats_size.x); ImGui::TextColored(ImVec4(1, 0, 0, 1), "%s", (const char*)error_stats); } menu_height = ImGui::GetWindowSize().y; ImGui::EndMainMenuBar(); } return menu_height; } void showEntityListToolbar() { auto pos = ImGui::GetCursorScreenPos(); ImGui::BeginToolbar("entity_list_toolbar", pos, ImVec2(0, 24)); auto& groups = m_editor->getEntityGroups(); if (getAction("createGroup")->toolbarButton()) { ImGui::OpenPopup("create_entity_group_popup"); } if (groups.getGroupCount() > 1 && getAction("removeGroup")->toolbarButton()) { groups.deleteGroup(groups.current_group); groups.current_group = groups.current_group % groups.getGroupCount(); } if (getAction("selectAssigned")->toolbarButton()) { m_editor->selectEntities( groups.getGroupEntities(groups.current_group), groups.getGroupEntitiesCount(groups.current_group)); } if (getAction("assignSelected")->toolbarButton()) { auto& selected = m_editor->getSelectedEntities(); for (auto e : selected) { groups.setGroup(e, groups.current_group); } } if (getAction("lock")->toolbarButton()) groups.freezeGroup(groups.current_group, true); if (getAction("unlock")->toolbarButton()) groups.freezeGroup(groups.current_group, false); if (getAction("show")->toolbarButton()) { m_editor->showEntities( groups.getGroupEntities(groups.current_group), groups.getGroupEntitiesCount(groups.current_group)); } if (getAction("hide")->toolbarButton()) { m_editor->hideEntities( groups.getGroupEntities(groups.current_group), groups.getGroupEntitiesCount(groups.current_group)); } if (ImGui::BeginPopup("create_entity_group_popup")) { static char group_name[20] = ""; ImGui::InputText("New group name", group_name, Lumix::lengthOf(group_name)); if (group_name[0] == 0) { ImGui::Text("Group name can not be empty"); } else if (groups.getGroup(group_name) != -1) { ImGui::Text("Group with that name already exists"); } else if (ImGui::Button("Create")) { groups.createGroup(group_name); group_name[0] = 0; ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } ImGui::EndToolbar(); } void onEntityListGUI() { PROFILE_FUNCTION(); if (ImGui::BeginDock("Entity List", &m_is_entity_list_opened)) { showEntityListToolbar(); if (ImGui::BeginChild("")) { auto* universe = m_editor->getUniverse(); auto& groups = m_editor->getEntityGroups(); groups.current_group = groups.current_group % groups.getGroupCount(); for (int i = 0; i < groups.getGroupCount(); ++i) { auto* name = groups.getGroupName(i); int entities_count = groups.getGroupEntitiesCount(i); const char* locked_text = groups.isGroupFrozen(i) ? "locked" : ""; const char* current_text = groups.current_group == i ? "<-" : ""; if (ImGui::TreeNode(name, "%s (%d) %s %s", name, entities_count, locked_text, current_text)) { ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() - ImGui::GetStyle().FramePadding.x); static ImVec2 size(0, 200); char buffer[1024]; ImGui::ListBoxHeader("Resources", size); ImGuiListClipper clipper(groups.getGroupEntitiesCount(i), ImGui::GetTextLineHeightWithSpacing()); while (clipper.Step()) { for (int j = clipper.DisplayStart; j < clipper.DisplayEnd; ++j) { Lumix::Entity entity = groups.getGroupEntities(i)[j]; getEntityListDisplayName(*m_editor, buffer, sizeof(buffer), entity); if (ImGui::Selectable(buffer)) { m_editor->selectEntities(&entity, 1); } if (ImGui::IsMouseDragging() && ImGui::IsItemActive()) { startDrag(StudioApp::DragData::ENTITY, &entity, sizeof(entity)); } } } ImGui::ListBoxFooter(); ImGui::PopItemWidth(); ImGui::TreePop(); } if (ImGui::IsItemClicked()) groups.current_group = i; } } ImGui::EndChild(); } ImGui::EndDock(); } void dummy() {} void startDrag(DragData::Type type, const void* data, int size) override { m_allocator.deallocate(m_drag_data.data); m_drag_data.type = type; if (size > 0) { m_drag_data.data = m_allocator.allocate(size); Lumix::copyMemory(m_drag_data.data, data, size); m_drag_data.size = size; } else { m_drag_data.data = nullptr; m_drag_data.size = 0; } } DragData getDragData() override { return m_drag_data; } void saveSettings() { m_settings.m_is_asset_browser_opened = m_asset_browser->m_is_opened; m_settings.m_is_entity_list_opened = m_is_entity_list_opened; m_settings.m_is_log_opened = m_log_ui->m_is_opened; m_settings.m_is_profiler_opened = m_profiler_ui->m_is_opened; m_settings.m_is_properties_opened = m_property_grid->m_is_opened; m_settings.m_mouse_sensitivity_x = m_editor->getMouseSensitivity().x; m_settings.m_mouse_sensitivity_y = m_editor->getMouseSensitivity().y; m_settings.save(); if (!m_metadata.save()) { Lumix::g_log_warning.log("Editor") << "Could not save metadata"; } } void initIMGUI() { ImGuiIO& io = ImGui::GetIO(); m_font = io.Fonts->AddFontFromFileTTF("bin/VeraMono.ttf", 13); io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE; io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN; io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE; io.KeyMap[ImGuiKey_A] = SDLK_a; io.KeyMap[ImGuiKey_C] = SDLK_c; io.KeyMap[ImGuiKey_V] = SDLK_v; io.KeyMap[ImGuiKey_X] = SDLK_x; io.KeyMap[ImGuiKey_Y] = SDLK_y; io.KeyMap[ImGuiKey_Z] = SDLK_z; } void loadSettings() { char cmd_line[2048]; Lumix::getCommandLine(cmd_line, Lumix::lengthOf(cmd_line)); Lumix::CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-no_crash_report")) continue; m_settings.m_force_no_crash_report = true; break; } m_settings.load(); m_asset_browser->m_is_opened = m_settings.m_is_asset_browser_opened; m_is_entity_list_opened = m_settings.m_is_entity_list_opened; m_log_ui->m_is_opened = m_settings.m_is_log_opened; m_profiler_ui->m_is_opened = m_settings.m_is_profiler_opened; m_property_grid->m_is_opened = m_settings.m_is_properties_opened; if (m_settings.m_is_maximized) { SDL_MaximizeWindow(m_window); } else if (m_settings.m_window.w > 0) { SDL_SetWindowPosition(m_window, m_settings.m_window.x, m_settings.m_window.y); SDL_SetWindowSize(m_window, m_settings.m_window.w, m_settings.m_window.h); } } void addActions() { addAction<&StudioAppImpl::newUniverse>("New", "newUniverse"); addAction<&StudioAppImpl::save>("Save", "save", KMOD_CTRL, 'S', -1); addAction<&StudioAppImpl::saveAs>("Save As", "saveAs", KMOD_CTRL, KMOD_SHIFT, 'S'); addAction<&StudioAppImpl::exit>("Exit", "exit", KMOD_CTRL, 'X', -1); addAction<&StudioAppImpl::redo>("Redo", "redo", KMOD_CTRL, KMOD_SHIFT, 'Z'); addAction<&StudioAppImpl::undo>("Undo", "undo", KMOD_CTRL, 'Z', -1); addAction<&StudioAppImpl::copy>("Copy", "copy", KMOD_CTRL, 'C', -1); addAction<&StudioAppImpl::paste>("Paste", "paste", KMOD_CTRL, 'V', -1); addAction<&StudioAppImpl::toggleOrbitCamera>("Orbit camera", "orbitCamera") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isOrbitCamera>(this); addAction<&StudioAppImpl::setTranslateGizmoMode>("Translate", "setTranslateGizmoMode") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isTranslateMode>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setRotateGizmoMode>("Rotate", "setRotateGizmoMode") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isRotateMode>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setTopView>("Top", "viewTop"); addAction<&StudioAppImpl::setFrontView>("Front", "viewFront"); addAction<&StudioAppImpl::setSideView>("Side", "viewSide"); addAction<&StudioAppImpl::setLocalCoordSystem>("Local", "setLocalCoordSystem") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isLocalCoordSystem>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setGlobalCoordSystem>("Global", "setGlobalCoordSystem") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isGlobalCoordSystem>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setPivotCenter>("Center", "setPivotCenter") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isPivotCenter>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setPivotOrigin>("Origin", "setPivotOrigin") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isPivotOrigin>(&m_editor->getGizmo()); addAction<&StudioAppImpl::createEntity>("Create empty", "createEntity"); addAction<&StudioAppImpl::destroyEntity>("Destroy", "destroyEntity", SDLK_DELETE, -1, -1); addAction<&StudioAppImpl::showEntities>("Show", "showEntities"); addAction<&StudioAppImpl::hideEntities>("Hide", "hideEntities"); addAction<&StudioAppImpl::savePrefab>("Save prefab", "savePrefab"); addAction<&StudioAppImpl::toggleGameMode>("Game Mode", "toggleGameMode") .is_selected.bind<Lumix::WorldEditor, &Lumix::WorldEditor::isGameMode>(m_editor); addAction<&StudioAppImpl::toggleMeasure>("Toggle measure", "toggleMeasure") .is_selected.bind<Lumix::WorldEditor, &Lumix::WorldEditor::isMeasureToolActive>(m_editor); addAction<&StudioAppImpl::autosnapDown>("Autosnap down", "autosnapDown") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isAutosnapDown>(&m_editor->getGizmo()); addAction<&StudioAppImpl::snapDown>("Snap down", "snapDown"); addAction<&StudioAppImpl::lookAtSelected>("Look at selected", "lookAtSelected"); addAction<&StudioAppImpl::toggleAssetBrowser>("Asset Browser", "assetBrowser") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isAssetBrowserOpened>(this); addAction<&StudioAppImpl::toggleEntityList>("Entity List", "entityList") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isEntityListOpened>(this); addAction<&StudioAppImpl::toggleSettings>("Settings", "settings") .is_selected.bind<StudioAppImpl, &StudioAppImpl::areSettingsOpened>(this); addAction<&StudioAppImpl::dummy>("Unhide entities from group", "show").is_global = false; addAction<&StudioAppImpl::dummy>("Hide entities from group", "hide").is_global = false; addAction<&StudioAppImpl::dummy>("Lock group", "lock").is_global = false; addAction<&StudioAppImpl::dummy>("Unlock group", "unlock").is_global = false; addAction<&StudioAppImpl::dummy>("Create group", "createGroup").is_global = false; addAction<&StudioAppImpl::dummy>("Remove group", "removeGroup").is_global = false; addAction<&StudioAppImpl::dummy>("Select assigned", "selectAssigned").is_global = false; addAction<&StudioAppImpl::dummy>("Assigned selected", "assignSelected").is_global = false; } void loadUserPlugins() { char cmd_line[2048]; Lumix::getCommandLine(cmd_line, Lumix::lengthOf(cmd_line)); Lumix::CommandLineParser parser(cmd_line); auto& plugin_manager = m_editor->getEngine().getPluginManager(); while (parser.next()) { if (!parser.currentEquals("-plugin")) continue; if (!parser.next()) break; char tmp[Lumix::MAX_PATH_LENGTH]; parser.getCurrent(tmp, Lumix::lengthOf(tmp)); bool loaded = plugin_manager.load(tmp) != nullptr; if (!loaded) { Lumix::g_log_error.log("Editor") << "Could not load plugin " << tmp << " requested by command line"; } } } void loadUniverseFromCommandLine() { char cmd_line[2048]; char path[Lumix::MAX_PATH_LENGTH]; Lumix::getCommandLine(cmd_line, Lumix::lengthOf(cmd_line)); Lumix::CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-open")) continue; if (!parser.next()) break; parser.getCurrent(path, Lumix::lengthOf(path)); m_editor->loadUniverse(path); setTitle(path); m_is_welcome_screen_opened = false; break; } } static void checkDataDirCommandLine(char* dir, int max_size) { char cmd_line[2048]; Lumix::getCommandLine(cmd_line, Lumix::lengthOf(cmd_line)); Lumix::CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-data_dir")) continue; if (!parser.next()) break; parser.getCurrent(dir, max_size); break; } } void addPlugin(IPlugin& plugin) override { m_plugins.push(&plugin); for (auto* i : m_plugins) { i->pluginAdded(plugin); plugin.pluginAdded(*i); } } void removePlugin(IPlugin& plugin) override { m_plugins.eraseItemFast(&plugin); } void setStudioApp() { m_editor->getPrefabSystem().setStudioApp(*this); auto& plugin_manager = m_editor->getEngine().getPluginManager(); #ifdef STATIC_PLUGINS for (auto* plugin : plugin_manager.getPlugins()) { StudioApp::StaticPluginRegister::create(plugin->getName(), *this); } #else for (auto* lib : plugin_manager.getLibraries()) { auto* f = (void (*)(StudioApp&))Lumix::getLibrarySymbol(lib, "setStudioApp"); if (f) f(*this); } #endif } void runScript(const char* src, const char* script_name) override { lua_State* L = m_engine->getState(); bool errors = luaL_loadbuffer(L, src, Lumix::stringLength(src), script_name) != LUA_OK; errors = errors || lua_pcall(L, 0, 0, 0) != LUA_OK; if (errors) { Lumix::g_log_error.log("Editor") << script_name << ": " << lua_tostring(L, -1); lua_pop(L, 1); } } void LUA_exitGameMode() { m_editor->toggleGameMode(); } void LUA_exit(int exit_code) { m_finished = true; m_exit_code = exit_code; } bool LUA_runTest(const char* dir, const char* name) { return m_editor->runTest(dir, name); } void createLua() { lua_State* L = m_engine->getState(); Lumix::LuaWrapper::createSystemVariable(L, "Editor", "editor", this); #define REGISTER_FUNCTION(F) \ do { \ auto* f = &Lumix::LuaWrapper::wrapMethod<StudioAppImpl, decltype(&StudioAppImpl::LUA_##F), &StudioAppImpl::LUA_##F>; \ Lumix::LuaWrapper::createSystemFunction(L, "Editor", #F, f); \ } while(false) \ REGISTER_FUNCTION(runTest); REGISTER_FUNCTION(exit); REGISTER_FUNCTION(exitGameMode); #undef REGISTER_FUNCTION } void checkScriptCommandLine() { char command_line[1024]; Lumix::getCommandLine(command_line, Lumix::lengthOf(command_line)); Lumix::CommandLineParser parser(command_line); while (parser.next()) { if (parser.currentEquals("-run_script")) { if (!parser.next()) break; char tmp[Lumix::MAX_PATH_LENGTH]; parser.getCurrent(tmp, Lumix::lengthOf(tmp)); Lumix::FS::OsFile file; if (file.open(tmp, Lumix::FS::Mode::OPEN_AND_READ, m_allocator)) { auto size = file.size(); auto* src = (char*)m_allocator.allocate(size + 1); file.read(src, size); src[size] = 0; runScript((const char*)src, tmp); m_allocator.deallocate(src); file.close(); } else { Lumix::g_log_error.log("Editor") << "Could not open " << tmp; } break; } } } static bool includeFileInPack(const char* filename) { if (filename[0] == '.') return false; if (Lumix::compareStringN("bin/", filename, 4) == 0) return false; if (Lumix::compareStringN("bin32/", filename, 4) == 0) return false; if (Lumix::equalStrings("data.pak", filename)) return false; if (Lumix::equalStrings("error.log", filename)) return false; return true; } static bool includeDirInPack(const char* filename) { if (filename[0] == '.') return false; if (Lumix::compareStringN("bin", filename, 4) == 0) return false; if (Lumix::compareStringN("bin32", filename, 4) == 0) return false; return true; } #pragma pack(1) struct PackFileInfo { Lumix::u32 hash; Lumix::u64 offset; Lumix::u64 size; using Path = Lumix::StaticString<Lumix::MAX_PATH_LENGTH>; }; #pragma pack() void packDataScan(const char* dir_path, Lumix::Array<PackFileInfo>& infos, Lumix::Array<PackFileInfo::Path>& paths) { auto* iter = PlatformInterface::createFileIterator(dir_path, m_allocator); PlatformInterface::FileInfo info; while (PlatformInterface::getNextFile(iter, &info)) { char normalized_path[Lumix::MAX_PATH_LENGTH]; Lumix::PathUtils::normalize(info.filename, normalized_path, Lumix::lengthOf(normalized_path)); if (info.is_directory) { if (!includeDirInPack(normalized_path)) continue; char dir[Lumix::MAX_PATH_LENGTH] = {0}; if (dir_path[0] != '.') Lumix::copyString(dir, dir_path); Lumix::catString(dir, info.filename); Lumix::catString(dir, "/"); packDataScan(dir, infos, paths); continue; } if(!includeFileInPack(normalized_path)) continue; auto& out_path = paths.emplace(); if(dir_path[0] == '.') { Lumix::copyString(out_path.data, Lumix::lengthOf(out_path.data), normalized_path); } else { Lumix::copyString(out_path.data, Lumix::lengthOf(out_path.data), dir_path); Lumix::catString(out_path.data, Lumix::lengthOf(out_path.data), normalized_path); } auto& out_info = infos.emplace(); out_info.hash = Lumix::crc32(out_path.data); out_info.size = PlatformInterface::getFileSize(out_path.data); out_info.offset = ~0UL; } PlatformInterface::destroyFileIterator(iter); } void packDataScanResources(Lumix::Array<PackFileInfo>& infos, Lumix::Array<PackFileInfo::Path>& paths) { Lumix::ResourceManager& rm = m_editor->getEngine().getResourceManager(); for (auto iter = rm.getAll().begin(), end = rm.getAll().end(); iter != end; ++iter) { const auto& resources = iter.value()->getResourceTable(); for (auto res_iter = resources.begin(), res_iter_end = resources.end(); res_iter != res_iter_end; ++res_iter) { Lumix::Resource* res = res_iter.value(); Lumix::copyString(paths.emplace().data, Lumix::MAX_PATH_LENGTH, res->getPath().c_str()); auto& out_info = infos.emplace(); out_info.hash = Lumix::crc32(res->getPath().c_str()); out_info.size = PlatformInterface::getFileSize(res->getPath().c_str()); out_info.offset = ~0UL; } } } void packData() { char dest[Lumix::MAX_PATH_LENGTH]; char dest_dir[Lumix::MAX_PATH_LENGTH]; if (!PlatformInterface::getOpenDirectory(dest_dir, Lumix::lengthOf(dest_dir), ".")) return; static const char* OUT_FILENAME = "data.pak"; Lumix::catString(dest_dir, "/"); Lumix::copyString(dest, dest_dir); Lumix::catString(dest, OUT_FILENAME); Lumix::Array<PackFileInfo> infos(m_allocator); Lumix::Array<PackFileInfo::Path> paths(m_allocator); infos.reserve(10000); paths.reserve(10000); packDataScan("./", infos, paths); if (infos.empty()) { Lumix::g_log_error.log("Editor") << "No files found while trying to create " << dest; return; } Lumix::FS::OsFile file; if (!file.open(dest, Lumix::FS::Mode::CREATE_AND_WRITE, m_allocator)) { Lumix::g_log_error.log("Editor") << "Could not create " << dest; return; } int count = infos.size(); file.write(&count, sizeof(count)); Lumix::u64 offset = sizeof(count) + sizeof(infos[0]) * count; for (auto& info : infos) { info.offset = offset; offset += info.size; } file.write(&infos[0], sizeof(infos[0]) * count); for (auto& path : paths) { Lumix::FS::OsFile src; size_t src_size = PlatformInterface::getFileSize(path.data); if (!src.open(path.data, Lumix::FS::Mode::OPEN_AND_READ, m_allocator)) { file.close(); Lumix::g_log_error.log("Editor") << "Could not open " << path.data; return; } Lumix::u8 buf[4096]; for (; src_size > 0; src_size -= Lumix::Math::minimum(sizeof(buf), src_size)) { size_t batch_size = Lumix::Math::minimum(sizeof(buf), src_size); if (!src.read(buf, batch_size)) { file.close(); Lumix::g_log_error.log("Editor") << "Could not read " << path.data; return; } file.write(buf, batch_size); } src.close(); } file.close(); const char* bin_files[] = { "app.exe", "assimp.dll", "nvToolsExt64_1.dll", "PhysX3CharacterKinematicCHECKED_x64.dll", "PhysX3CHECKED_x64.dll", "PhysX3CommonCHECKED_x64.dll", "PhysX3CookingCHECKED_x64.dll" }; for(auto& file : bin_files) { Lumix::StaticString<Lumix::MAX_PATH_LENGTH> tmp(dest_dir, file); Lumix::StaticString<Lumix::MAX_PATH_LENGTH> src("bin/", file); if (!Lumix::copyFile(src, tmp)) { Lumix::g_log_error.log("Editor") << "Failed to copy " << src << " to " << tmp; } } Lumix::StaticString<Lumix::MAX_PATH_LENGTH> tmp(dest_dir); tmp << "startup.lua"; if (!Lumix::copyFile("startup.lua", tmp)) { Lumix::g_log_error.log("Editor") << "Failed to copy startup.lua to " << tmp; } } void loadLuaPlugin(const char* dir, const char* filename) { Lumix::StaticString<Lumix::MAX_PATH_LENGTH> path(dir, filename); Lumix::FS::OsFile file; if (file.open(path, Lumix::FS::Mode::OPEN_AND_READ, m_allocator)) { auto size = file.size(); auto* src = (char*)m_engine->getLIFOAllocator().allocate(size + 1); file.read(src, size); src[size] = 0; LuaPlugin* plugin = LUMIX_NEW(m_editor->getAllocator(), LuaPlugin)(*this, src, filename); addPlugin(*plugin); m_engine->getLIFOAllocator().deallocate(src); file.close(); } else { Lumix::g_log_warning.log("Editor") << "Failed to open " << path; } } void scanUniverses() { auto* iter = PlatformInterface::createFileIterator("universes/", m_allocator); PlatformInterface::FileInfo info; while (PlatformInterface::getNextFile(iter, &info)) { if (info.filename[0] == '.') continue; if (!info.is_directory) continue; char basename[Lumix::MAX_PATH_LENGTH]; Lumix::PathUtils::getBasename(basename, Lumix::lengthOf(basename), info.filename); m_universes.emplace(basename); } PlatformInterface::destroyFileIterator(iter); } void findLuaPlugins(const char* dir) { auto* iter = PlatformInterface::createFileIterator(dir, m_allocator); PlatformInterface::FileInfo info; while (PlatformInterface::getNextFile(iter, &info)) { char normalized_path[Lumix::MAX_PATH_LENGTH]; Lumix::PathUtils::normalize(info.filename, normalized_path, Lumix::lengthOf(normalized_path)); if (normalized_path[0] == '.') continue; if (info.is_directory) { char dir_path[Lumix::MAX_PATH_LENGTH] = { 0 }; if (dir[0] != '.') Lumix::copyString(dir_path, dir); Lumix::catString(dir_path, info.filename); Lumix::catString(dir_path, "/"); findLuaPlugins(dir_path); } else { char ext[5]; Lumix::PathUtils::getExtension(ext, Lumix::lengthOf(ext), info.filename); if (Lumix::equalStrings(ext, "lua")) { loadLuaPlugin(dir, info.filename); } } } PlatformInterface::destroyFileIterator(iter); } void processSystemEvents() { SDL_Event event; auto& io = ImGui::GetIO(); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_MOVED: case SDL_WINDOWEVENT_SIZE_CHANGED: { int x, y, w, h; SDL_GetWindowSize(m_window, &w, &h); SDL_GetWindowPosition(m_window, &x, &y); onWindowTransformed(x, y, w, h); } break; case SDL_WINDOWEVENT_CLOSE: exit(); break; } break; case SDL_QUIT: exit(); break; case SDL_MOUSEBUTTONDOWN: m_editor->setAdditiveSelection(io.KeyCtrl); m_editor->setSnapMode(io.KeyShift); switch (event.button.button) { case SDL_BUTTON_LEFT: io.MouseDown[0] = true; break; case SDL_BUTTON_RIGHT: io.MouseDown[1] = true; break; case SDL_BUTTON_MIDDLE: io.MouseDown[2] = true; break; } break; case SDL_MOUSEBUTTONUP: switch (event.button.button) { case SDL_BUTTON_LEFT: io.MouseDown[0] = false; break; case SDL_BUTTON_RIGHT: io.MouseDown[1] = false; break; case SDL_BUTTON_MIDDLE: io.MouseDown[2] = false; break; } break; case SDL_MOUSEMOTION: { auto& input_system = m_editor->getEngine().getInputSystem(); input_system.injectMouseXMove(float(event.motion.xrel), float(event.motion.x)); input_system.injectMouseYMove(float(event.motion.yrel), float(event.motion.y)); if (SDL_GetRelativeMouseMode() == SDL_FALSE) { io.MousePos.x = (float)event.motion.x; io.MousePos.y = (float)event.motion.y; } } break; case SDL_TEXTINPUT: io.AddInputCharactersUTF8(event.text.text); break; case SDL_KEYDOWN: case SDL_KEYUP: { int key = event.key.keysym.sym & ~SDLK_SCANCODE_MASK; io.KeysDown[key] = (event.type == SDL_KEYDOWN); if (event.key.keysym.scancode == SDL_SCANCODE_KP_ENTER) { io.KeysDown[SDLK_RETURN] = (event.type == SDL_KEYDOWN); } io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); checkShortcuts(); } break; case SDL_MOUSEWHEEL: { io.MouseWheel = float(event.wheel.x != 0 ? event.wheel.x : event.wheel.y); break; } } } } void run() override { checkScriptCommandLine(); Lumix::Timer* timer = Lumix::Timer::create(m_allocator); while (!m_finished) { { timer->tick(); PROFILE_BLOCK("all"); float frame_time; { PROFILE_BLOCK("tick"); processSystemEvents(); if (!m_finished) update(); frame_time = timer->tick(); } float wanted_fps = (SDL_GetWindowFlags(m_window) & SDL_WINDOW_INPUT_FOCUS) != 0 ? 60.0f : 5.0f; if (frame_time < 1 / wanted_fps) { PROFILE_BLOCK("sleep"); Lumix::MT::sleep(Lumix::u32(1000 / wanted_fps - frame_time * 1000)); } } Lumix::Profiler::frame(); } Lumix::Timer::destroy(timer); } void checkWorkingDirector() { if (!PlatformInterface::dirExists("bin")) { Lumix::messageBox("Bin directory not found, please check working directory."); } else if (!PlatformInterface::dirExists("pipelines")) { Lumix::messageBox("Pipelines directory not found, please check working directory."); } } void unloadIcons() { auto& render_interface = *m_editor->getRenderInterface(); for (auto* action : m_actions) { render_interface.unloadTexture(action->icon); } } void loadIcons() { auto& render_interface = *m_editor->getRenderInterface(); for (auto* action : m_actions) { char tmp[Lumix::MAX_PATH_LENGTH]; action->getIconPath(tmp, Lumix::lengthOf(tmp)); if (PlatformInterface::fileExists(tmp)) { action->icon = render_interface.loadTexture(Lumix::Path(tmp)); } else { action->icon = nullptr; } } } void init() { SDL_SetMainReady(); SDL_Init(SDL_INIT_VIDEO); checkWorkingDirector(); m_window = SDL_CreateWindow("Lumix Studio", 0, 0, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); char current_dir[Lumix::MAX_PATH_LENGTH]; PlatformInterface::getCurrentDirectory(current_dir, Lumix::lengthOf(current_dir)); PlatformInterface::setWindow(m_window); char data_dir_path[Lumix::MAX_PATH_LENGTH] = {}; checkDataDirCommandLine(data_dir_path, Lumix::lengthOf(data_dir_path)); m_engine = Lumix::Engine::create(current_dir, data_dir_path, nullptr, m_allocator); createLua(); SDL_SysWMinfo window_info; SDL_VERSION(&window_info.version); SDL_GetWindowWMInfo(m_window, &window_info); Lumix::Engine::PlatformData platform_data = {}; #ifdef _WIN32 platform_data.window_handle = window_info.info.win.window; ImGui::GetIO().ImeWindowHandle = window_info.info.win.window; #elif defined(__linux__) platform_data.window_handle = (void*)(uintptr_t)window_info.info.x11.window; platform_data.display = window_info.info.x11.display; #endif m_engine->setPlatformData(platform_data); m_editor = Lumix::WorldEditor::create(current_dir, *m_engine, m_allocator); m_settings.m_editor = m_editor; scanUniverses(); loadUserPlugins(); addActions(); m_asset_browser = LUMIX_NEW(m_allocator, AssetBrowser)(*this); m_property_grid = LUMIX_NEW(m_allocator, PropertyGrid)(*this); auto engine_allocator = static_cast<Lumix::Debug::Allocator*>(&m_engine->getAllocator()); m_profiler_ui = ProfilerUI::create(*m_engine); m_log_ui = LUMIX_NEW(m_allocator, LogUI)(m_editor->getAllocator()); initIMGUI(); if (!m_metadata.load()) Lumix::g_log_info.log("Editor") << "Could not load metadata"; setStudioApp(); loadIcons(); loadSettings(); loadUniverseFromCommandLine(); findLuaPlugins("plugins/lua/"); } void checkShortcuts() { if (ImGui::IsAnyItemActive()) return; int key_count; auto* state = SDL_GetKeyboardState(&key_count); Lumix::u32 pressed_modifiers = SDL_GetModState() & (KMOD_CTRL | KMOD_ALT | KMOD_SHIFT); for (auto* a : m_actions) { if (!a->is_global || a->shortcut[0] == -1) continue; Lumix::u32 action_modifiers = 0; for (int i = 0; i < Lumix::lengthOf(a->shortcut) + 1; ++i) { if ((i == Lumix::lengthOf(a->shortcut) || a->shortcut[i] == -1) && action_modifiers == pressed_modifiers) { a->func.invoke(); return; } if (i == Lumix::lengthOf(a->shortcut)) break; if (a->shortcut[i] == -1) break; if (a->shortcut[i] >= key_count) break; if (!state[a->shortcut[i]]) break; if (a->shortcut[i] == SDL_SCANCODE_LCTRL) action_modifiers |= KMOD_LCTRL; else if (a->shortcut[i] == SDL_SCANCODE_LALT) action_modifiers |= KMOD_LALT; else if (a->shortcut[i] == SDL_SCANCODE_LSHIFT) action_modifiers |= KMOD_LSHIFT; else if (a->shortcut[i] == SDL_SCANCODE_RCTRL) action_modifiers |= KMOD_RCTRL; else if (a->shortcut[i] == SDL_SCANCODE_RALT) action_modifiers |= KMOD_RALT; else if (a->shortcut[i] == SDL_SCANCODE_RSHIFT) action_modifiers |= KMOD_RSHIFT; } } } void onWindowTransformed(int x, int y, int width, int height) { if (height == 0) return; m_settings.m_window.x = x; m_settings.m_window.y = y; m_settings.m_window.w = width; m_settings.m_window.h = height; m_settings.m_is_maximized = (SDL_GetWindowFlags(m_window) & SDL_WINDOW_MAXIMIZED) != 0; } void clearInputs() { auto& io = ImGui::GetIO(); io.KeyAlt = false; io.KeyCtrl = false; io.KeyShift = false; memset(io.KeysDown, 0, sizeof(io.KeysDown)); memset(io.MouseDown, 0, sizeof(io.MouseDown)); } SDL_Window* getWindow() override { return m_window; } Lumix::WorldEditor* getWorldEditor() override { return m_editor; } Lumix::DefaultAllocator m_main_allocator; Lumix::Debug::Allocator m_allocator; Lumix::Engine* m_engine; SDL_Window* m_window; Lumix::Array<Action*> m_actions; Lumix::Array<Action*> m_window_actions; Lumix::Array<Action*> m_toolbar_actions; Lumix::Array<IPlugin*> m_plugins; Lumix::Array<IAddComponentPlugin*> m_add_cmp_plugins; Lumix::Array<Lumix::StaticString<Lumix::MAX_PATH_LENGTH>> m_universes; AddCmpTreeNode m_add_cmp_root; Lumix::HashMap<Lumix::ComponentType, Lumix::string> m_component_labels; Lumix::WorldEditor* m_editor; bool m_confirm_exit; bool m_confirm_load; bool m_confirm_new; char m_universe_to_load[Lumix::MAX_PATH_LENGTH]; AssetBrowser* m_asset_browser; PropertyGrid* m_property_grid; LogUI* m_log_ui; ProfilerUI* m_profiler_ui; Lumix::string m_selected_template_name; Settings m_settings; Metadata m_metadata; char m_template_name[100]; char m_open_filter[64]; char m_component_filter[32]; bool m_finished; int m_exit_code; bool m_is_welcome_screen_opened; bool m_is_entity_list_opened; bool m_is_save_as_dialog_opened; DragData m_drag_data; ImFont* m_font; }; static size_t alignMask(size_t _value, size_t _mask) { return (_value + _mask) & ((~0) & (~_mask)); } static void* alignPtr(void* _ptr, size_t _align) { union { void* ptr; size_t addr; } un; un.ptr = _ptr; size_t mask = _align - 1; size_t aligned = alignMask(un.addr, mask); un.addr = aligned; return un.ptr; } StudioApp* StudioApp::create() { static char buf[sizeof(StudioAppImpl) * 2]; return new (Lumix::NewPlaceholder(), alignPtr(buf, ALIGN_OF(StudioAppImpl))) StudioAppImpl; } void StudioApp::destroy(StudioApp& app) { app.~StudioApp(); } static StudioApp::StaticPluginRegister* s_first_plugin = nullptr; StudioApp::StaticPluginRegister::StaticPluginRegister(const char* name, Creator creator) { this->creator = creator; this->name = name; next = s_first_plugin; s_first_plugin = this; } void StudioApp::StaticPluginRegister::create(const char* name, StudioApp& app) { auto* i = s_first_plugin; while (i) { if (Lumix::equalStrings(name, i->name)) { i->creator(app); return; } i = i->next; } } ignore engine-reserved universe names when scanning #include "studio_app.h" #include "asset_browser.h" #include "audio/audio_scene.h" #include "audio/clip_manager.h" #include "editor/entity_groups.h" #include "editor/gizmo.h" #include "editor/prefab_system.h" #include "editor/render_interface.h" #include "editor/world_editor.h" #include "engine/blob.h" #include "engine/command_line_parser.h" #include "engine/crc32.h" #include "engine/debug/debug.h" #include "engine/default_allocator.h" #include "engine/engine.h" #include "engine/fs/disk_file_device.h" #include "engine/fs/file_system.h" #include "engine/fs/os_file.h" #include "engine/input_system.h" #include "engine/log.h" #include "engine/lua_wrapper.h" #include "engine/mt/thread.h" #include "engine/path_utils.h" #include "engine/plugin_manager.h" #include "engine/profiler.h" #include "engine/property_register.h" #include "engine/quat.h" #include "engine/resource_manager.h" #include "engine/system.h" #include "engine/timer.h" #include "engine/universe/universe.h" #include "imgui/imgui.h" #include "log_ui.h" #include "metadata.h" #include "platform_interface.h" #include "profiler_ui.h" #include "property_grid.h" #include "settings.h" #include "utils.h" #include <SDL.h> #include <SDL_syswm.h> struct LuaPlugin : public StudioApp::IPlugin { LuaPlugin(StudioApp& app, const char* src, const char* filename) : editor(*app.getWorldEditor()) { L = lua_newthread(editor.getEngine().getState()); thread_ref = luaL_ref(editor.getEngine().getState(), LUA_REGISTRYINDEX); bool errors = luaL_loadbuffer(L, src, Lumix::stringLength(src), filename) != LUA_OK; errors = errors || lua_pcall(L, 0, 0, 0) != LUA_OK; if (errors) { Lumix::g_log_error.log("Editor") << filename << ": " << lua_tostring(L, -1); lua_pop(L, 1); } const char* name = "LuaPlugin"; if (lua_getglobal(L, "plugin_name") == LUA_TSTRING) { name = lua_tostring(L, -1); } Action* action = LUMIX_NEW(editor.getAllocator(), Action)(name, name); action->func.bind<LuaPlugin, &LuaPlugin::onAction>(this); app.addWindowAction(action); m_is_opened = false; lua_pop(L, 1); // plugin_name } ~LuaPlugin() { luaL_unref(editor.getEngine().getState(), LUA_REGISTRYINDEX, thread_ref); } const char* getName() const override { return "lua_script"; } void onAction() { m_is_opened = !m_is_opened; } void onWindowGUI() override { if (!m_is_opened) return; if (lua_getglobal(L, "onGUI") == LUA_TFUNCTION) { if (lua_pcall(L, 0, 0, 0) != LUA_OK) { Lumix::g_log_error.log("Editor") << "LuaPlugin:" << lua_tostring(L, -1); lua_pop(L, 1); } } else { lua_pop(L, 1); } } Lumix::WorldEditor& editor; lua_State* L; int thread_ref; bool m_is_opened; }; class StudioAppImpl LUMIX_FINAL : public StudioApp { public: StudioAppImpl() : m_is_entity_list_opened(true) , m_is_save_as_dialog_opened(false) , m_finished(false) , m_selected_template_name(m_allocator) , m_profiler_ui(nullptr) , m_asset_browser(nullptr) , m_property_grid(nullptr) , m_actions(m_allocator) , m_window_actions(m_allocator) , m_toolbar_actions(m_allocator) , m_metadata(m_allocator) , m_is_welcome_screen_opened(true) , m_editor(nullptr) , m_settings(*this) , m_plugins(m_allocator) , m_add_cmp_plugins(m_allocator) , m_component_labels(m_allocator) , m_confirm_load(false) , m_confirm_new(false) , m_confirm_exit(false) , m_exit_code(0) , m_allocator(m_main_allocator) , m_universes(m_allocator) { m_add_cmp_root.label[0] = '\0'; m_drag_data = {DragData::NONE, nullptr, 0}; m_template_name[0] = '\0'; m_open_filter[0] = '\0'; init(); registerComponent("hierarchy", "Hierarchy"); } ~StudioAppImpl() { m_allocator.deallocate(m_drag_data.data); saveSettings(); unloadIcons(); while (m_editor->getEngine().getFileSystem().hasWork()) { m_editor->getEngine().getFileSystem().updateAsyncTransactions(); } m_editor->newUniverse(); destroyAddCmpTreeNode(m_add_cmp_root.child); for (auto* plugin : m_plugins) { LUMIX_DELETE(m_editor->getAllocator(), plugin); } m_plugins.clear(); for (auto* i : m_add_cmp_plugins) { LUMIX_DELETE(m_editor->getAllocator(), i); } m_add_cmp_plugins.clear(); for (auto* a : m_actions) { LUMIX_DELETE(m_editor->getAllocator(), a); } m_actions.clear(); ProfilerUI::destroy(*m_profiler_ui); LUMIX_DELETE(m_allocator, m_asset_browser); LUMIX_DELETE(m_allocator, m_property_grid); LUMIX_DELETE(m_allocator, m_log_ui); Lumix::WorldEditor::destroy(m_editor, m_allocator); Lumix::Engine::destroy(m_engine, m_allocator); m_engine = nullptr; m_editor = nullptr; SDL_DestroyWindow(m_window); SDL_Quit(); } void destroyAddCmpTreeNode(AddCmpTreeNode* node) { if (!node) return; destroyAddCmpTreeNode(node->child); destroyAddCmpTreeNode(node->next); LUMIX_DELETE(m_allocator, node); } const char* getComponentTypeName(Lumix::ComponentType cmp_type) const override { auto iter = m_component_labels.find(cmp_type); if (iter == m_component_labels.end()) return "Unknown"; return iter.value().c_str(); } const AddCmpTreeNode& getAddComponentTreeRoot() const override { return m_add_cmp_root; } void addPlugin(IAddComponentPlugin& plugin) { int i = 0; while (i < m_add_cmp_plugins.size() && Lumix::compareString(plugin.getLabel(), m_add_cmp_plugins[i]->getLabel()) > 0) { ++i; } m_add_cmp_plugins.insert(i, &plugin); auto* node = LUMIX_NEW(m_allocator, AddCmpTreeNode); Lumix::copyString(node->label, plugin.getLabel()); node->plugin = &plugin; insertAddCmpNode(m_add_cmp_root, node); } void insertAddCmpNodeOrdered(AddCmpTreeNode& parent, AddCmpTreeNode* node) { if (!parent.child) { parent.child = node; return; } if (Lumix::compareString(parent.child->label, node->label) > 0) { node->next = parent.child; parent.child = node; return; } auto* i = parent.child; while (i->next && Lumix::compareString(i->next->label, node->label) < 0) { i = i->next; } node->next = i->next; i->next = node; } void insertAddCmpNode(AddCmpTreeNode& parent, AddCmpTreeNode* node) { for (auto* i = parent.child; i; i = i->next) { if (!i->plugin && Lumix::startsWith(node->label, i->label)) { insertAddCmpNode(*i, node); return; } } const char* rest = node->label + Lumix::stringLength(parent.label); if (parent.label[0] != '\0') ++rest; // include '/' const char* slash = Lumix::findSubstring(rest, "/"); if (!slash) { insertAddCmpNodeOrdered(parent, node); return; } auto* new_group = LUMIX_NEW(m_allocator, AddCmpTreeNode); Lumix::copyNString(new_group->label, (int)sizeof(new_group->label), node->label, int(slash - node->label)); insertAddCmpNodeOrdered(parent, new_group); insertAddCmpNode(*new_group, node); } void registerComponentWithResource(const char* type, const char* label, Lumix::ResourceType resource_type, const char* property_name) override { struct Plugin LUMIX_FINAL : public IAddComponentPlugin { void onGUI(bool create_entity, bool from_filter) override { ImGui::SetNextWindowSize(ImVec2(300, 300)); const char* last = Lumix::reverseFind(label, nullptr, '/'); if (!ImGui::BeginMenu(last && !from_filter ? last + 1 : label)) return; auto* desc = Lumix::PropertyRegister::getDescriptor(type, property_id); char buf[Lumix::MAX_PATH_LENGTH]; bool create_empty = ImGui::Selectable("Empty", false); if (asset_browser->resourceList(buf, Lumix::lengthOf(buf), resource_type, 0) || create_empty) { if (create_entity) { Lumix::Entity entity = editor->addEntity(); editor->selectEntities(&entity, 1); } editor->addComponent(type); if (!create_empty) { editor->setProperty(type, -1, *desc, &editor->getSelectedEntities()[0], editor->getSelectedEntities().size(), buf, Lumix::stringLength(buf) + 1); } ImGui::CloseCurrentPopup(); } ImGui::EndMenu(); } const char* getLabel() const override { return label; } PropertyGrid* property_grid; AssetBrowser* asset_browser; Lumix::WorldEditor* editor; Lumix::ComponentType type; Lumix::ResourceType resource_type; Lumix::u32 property_id; char label[50]; }; auto& allocator = m_editor->getAllocator(); auto* plugin = LUMIX_NEW(allocator, Plugin); plugin->property_grid = m_property_grid; plugin->asset_browser = m_asset_browser; plugin->type = Lumix::PropertyRegister::getComponentType(type); plugin->editor = m_editor; plugin->property_id = Lumix::crc32(property_name); plugin->resource_type = resource_type; Lumix::copyString(plugin->label, label); addPlugin(*plugin); m_component_labels.insert(plugin->type, Lumix::string(label, m_allocator)); } void registerComponent(const char* id, const char* label, IAddComponentPlugin& plugin) override { addPlugin(plugin); auto& allocator = m_editor->getAllocator(); m_component_labels.insert(Lumix::PropertyRegister::getComponentType(id), Lumix::string(label, m_allocator)); } void registerComponent(const char* type, const char* label) override { struct Plugin LUMIX_FINAL : public IAddComponentPlugin { void onGUI(bool create_entity, bool from_filter) override { const char* last = Lumix::reverseFind(label, nullptr, '/'); if (ImGui::Selectable(last && !from_filter ? last + 1 : label)) { if (create_entity) { Lumix::Entity entity = editor->addEntity(); editor->selectEntities(&entity, 1); } editor->addComponent(type); } } const char* getLabel() const override { return label; } Lumix::WorldEditor* editor; PropertyGrid* property_grid; Lumix::ComponentType type; char label[64]; }; auto& allocator = m_editor->getAllocator(); auto* plugin = LUMIX_NEW(allocator, Plugin); plugin->property_grid = m_property_grid; plugin->editor = m_editor; plugin->type = Lumix::PropertyRegister::getComponentType(type); Lumix::copyString(plugin->label, label); addPlugin(*plugin); m_component_labels.insert(plugin->type, Lumix::string(label, m_allocator)); } const Lumix::Array<Action*>& getActions() override { return m_actions; } Lumix::Array<Action*>& getToolbarActions() override { return m_toolbar_actions; } void guiBeginFrame() { PROFILE_FUNCTION(); ImGuiIO& io = ImGui::GetIO(); int w, h; SDL_GetWindowSize(m_window, &w, &h); io.DisplaySize = ImVec2((float)w, (float)h); io.DeltaTime = m_engine->getLastTimeDelta(); io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); ImGui::NewFrame(); ImGui::PushFont(m_font); if (m_drag_data.type == DragData::PATH) { ImGui::BeginTooltip(); char tmp[Lumix::MAX_PATH_LENGTH]; Lumix::PathUtils::getFilename(tmp, Lumix::lengthOf(tmp), (const char*)m_drag_data.data); ImGui::Text("%s", tmp); ImGui::EndTooltip(); } else if (m_drag_data.type == DragData::ENTITY) { ImGui::BeginTooltip(); char buf[1024]; getEntityListDisplayName(*m_editor, buf, Lumix::lengthOf(buf), *(Lumix::Entity*)m_drag_data.data); ImGui::Text("%s", buf); ImGui::EndTooltip(); } } float showMainToolbar(float menu_height) { if (m_toolbar_actions.empty()) return menu_height; auto frame_padding = ImGui::GetStyle().FramePadding; float padding = frame_padding.y * 2; ImVec4 active_color = ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]; ImVec4 inactive_color(0, 0, 0, 0); ImVec2 toolbar_size(ImGui::GetIO().DisplaySize.x, 24 + padding); if (ImGui::BeginToolbar("main_toolbar", ImVec2(1, menu_height), toolbar_size)) { auto& render_interface = *m_editor->getRenderInterface(); for (auto* action : m_toolbar_actions) { action->toolbarButton(); } } ImGui::EndToolbar(); return menu_height + 24 + padding; } void guiEndFrame() { if (m_is_welcome_screen_opened) { showWelcomeScreen(); } else { float menu_height = showMainMenu(); float toolbar_bottom = showMainToolbar(menu_height); if (ImGui::GetIO().DisplaySize.y > 0) { auto pos = ImVec2(0, toolbar_bottom); auto size = ImGui::GetIO().DisplaySize; size.y -= pos.y; ImGui::RootDock(pos, size); } m_profiler_ui->onGUI(); m_asset_browser->onGUI(); m_log_ui->onGUI(); m_property_grid->onGUI(); onEntityListGUI(); onSaveAsDialogGUI(); for (auto* plugin : m_plugins) { plugin->onWindowGUI(); } m_settings.onGUI(); } ImGui::PopFont(); ImGui::Render(); if (ImGui::GetIO().MouseReleased[0]) { m_allocator.deallocate(m_drag_data.data); m_drag_data.data = nullptr; m_drag_data.size = 0; m_drag_data.type = DragData::NONE; } } void update() { PROFILE_FUNCTION(); guiBeginFrame(); float time_delta = m_editor->getEngine().getLastTimeDelta(); m_editor->setMouseSensitivity(m_settings.m_mouse_sensitivity_x, m_settings.m_mouse_sensitivity_y); m_editor->update(); m_engine->update(*m_editor->getUniverse()); for (auto* plugin : m_plugins) { plugin->update(time_delta); } m_asset_browser->update(); m_log_ui->update(time_delta); guiEndFrame(); } void showWelcomeScreen() { ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings; int w, h; SDL_GetWindowSize(m_window, &w, &h); ImVec2 size((float)w, (float)h); if (ImGui::Begin("Welcome", nullptr, size, -1, flags)) { ImGui::Text("Welcome to Lumix Studio"); ImVec2 half_size = ImGui::GetContentRegionAvail(); half_size.x = half_size.x * 0.5f - ImGui::GetStyle().FramePadding.x; half_size.y *= 0.75f; auto right_pos = ImGui::GetCursorPos(); right_pos.x += half_size.x + ImGui::GetStyle().FramePadding.x; if (ImGui::BeginChild("left", half_size, true)) { if (ImGui::Button("New Universe")) m_is_welcome_screen_opened = false; ImGui::Separator(); ImGui::Text("Open universe:"); ImGui::Indent(); for (auto& univ : m_universes) { if (ImGui::MenuItem(univ.data)) { m_editor->loadUniverse(univ.data); setTitle(univ.data); m_is_welcome_screen_opened = false; } } ImGui::Unindent(); } ImGui::EndChild(); ImGui::SetCursorPos(right_pos); if (ImGui::BeginChild("right", half_size, true)) { if (ImGui::Button("Wiki")) { PlatformInterface::shellExecuteOpen("https://github.com/nem0/LumixEngine/wiki"); } if (ImGui::Button("Download new version")) { PlatformInterface::shellExecuteOpen("https://github.com/nem0/lumixengine_data/archive/master.zip"); } if (ImGui::Button("Show major releases")) { PlatformInterface::shellExecuteOpen("https://github.com/nem0/LumixEngine/releases"); } if (ImGui::Button("Show latest commits")) { PlatformInterface::shellExecuteOpen("https://github.com/nem0/LumixEngine/commits/master"); } if (ImGui::Button("Show issues")) { PlatformInterface::shellExecuteOpen("https://github.com/nem0/lumixengine/issues"); } } ImGui::EndChild(); } ImGui::End(); } void setTitle(const char* title) { char tmp[100]; Lumix::copyString(tmp, "Lumix Studio - "); Lumix::catString(tmp, title); SDL_SetWindowTitle(m_window, tmp); } static void getShortcut(const Action& action, char* buf, int max_size) { buf[0] = 0; for (int i = 0; i < Lumix::lengthOf(action.shortcut); ++i) { const char* str = SDL_GetKeyName(SDL_GetKeyFromScancode((SDL_Scancode)action.shortcut[i])); if (str[0] == 0) return; if (i > 0) Lumix::catString(buf, max_size, " - "); Lumix::catString(buf, max_size, str); } } void doMenuItem(Action& a, bool enabled) { char buf[20]; getShortcut(a, buf, sizeof(buf)); if (ImGui::MenuItem(a.label, buf, a.is_selected.invoke(), enabled)) { a.func.invoke(); } } void save() { if (m_editor->isGameMode()) { Lumix::g_log_error.log("Editor") << "Could not save while the game is running"; return; } if (m_editor->getUniverse()->getName()[0]) { m_editor->saveUniverse(m_editor->getUniverse()->getName(), true); } else { saveAs(); } } void onSaveAsDialogGUI() { if (!m_is_save_as_dialog_opened) return; if (ImGui::Begin("Save Universe As")) { static char name[64] = ""; ImGui::InputText("Name", name, Lumix::lengthOf(name)); if (ImGui::Button("Save")) { m_is_save_as_dialog_opened = false; setTitle(name); m_editor->saveUniverse(name, true); } } ImGui::End(); } void saveAs() { if (m_editor->isGameMode()) { Lumix::g_log_error.log("Editor") << "Could not save while the game is running"; return; } m_is_save_as_dialog_opened = true; } void exit() { if (m_editor->isUniverseChanged()) { m_confirm_exit = true; } else { m_finished = true; } } void newUniverse() { if (m_editor->isUniverseChanged()) { m_confirm_new = true; } else { m_editor->newUniverse(); } } bool hasPluginFocus() { for(auto* plugin : m_plugins) { if(plugin->hasFocus()) return true; } return false; } void undo() { if (!hasPluginFocus()) m_editor->undo(); } void redo() { if (!hasPluginFocus()) m_editor->redo(); } void copy() { m_editor->copyEntities(); } void paste() { m_editor->pasteEntities(); } bool isOrbitCamera() { return m_editor->isOrbitCamera(); } void toggleOrbitCamera() { m_editor->setOrbitCamera(!m_editor->isOrbitCamera()); } void setTopView() { m_editor->setTopView(); } void setFrontView() { m_editor->setFrontView(); } void setSideView() { m_editor->setSideView(); } void setLocalCoordSystem() { m_editor->getGizmo().setLocalCoordSystem(); } void setGlobalCoordSystem() { m_editor->getGizmo().setGlobalCoordSystem(); } void setPivotOrigin() { m_editor->getGizmo().setPivotOrigin(); } void setPivotCenter() { m_editor->getGizmo().setPivotCenter(); } void createEntity() { m_editor->addEntity(); } void showEntities() { m_editor->showSelectedEntities(); } void hideEntities() { m_editor->hideSelectedEntities(); } void toggleMeasure() { m_editor->toggleMeasure(); } void snapDown() { m_editor->snapDown(); } void lookAtSelected() { m_editor->lookAtSelected(); } void toggleSettings() { m_settings.m_is_opened = !m_settings.m_is_opened; } bool areSettingsOpened() const { return m_settings.m_is_opened; } void toggleEntityList() { m_is_entity_list_opened = !m_is_entity_list_opened; } bool isEntityListOpened() const { return m_is_entity_list_opened; } void toggleAssetBrowser() { m_asset_browser->m_is_opened = !m_asset_browser->m_is_opened; } bool isAssetBrowserOpened() const { return m_asset_browser->m_is_opened; } int getExitCode() const override { return m_exit_code; } AssetBrowser* getAssetBrowser() override { return m_asset_browser; } PropertyGrid* getPropertyGrid() override { return m_property_grid; } Metadata* getMetadata() override { return &m_metadata; } LogUI* getLogUI() override { return m_log_ui; } void toggleGameMode() { m_editor->toggleGameMode(); } void setTranslateGizmoMode() { m_editor->getGizmo().setTranslateMode(); } void setRotateGizmoMode() { m_editor->getGizmo().setRotateMode(); } void savePrefab() { char filename[Lumix::MAX_PATH_LENGTH]; char tmp[Lumix::MAX_PATH_LENGTH]; if (PlatformInterface::getSaveFilename(tmp, Lumix::lengthOf(tmp), "Prefab files\0*.fab\0", "fab")) { Lumix::PathUtils::normalize(tmp, filename, Lumix::lengthOf(tmp)); const char* base_path = m_engine->getDiskFileDevice()->getBasePath(); if (Lumix::startsWith(filename, base_path)) { m_editor->getPrefabSystem().savePrefab(Lumix::Path(filename + Lumix::stringLength(base_path))); } else { base_path = m_engine->getPatchFileDevice() ? m_engine->getPatchFileDevice()->getBasePath() : nullptr; if (base_path && Lumix::startsWith(filename, base_path)) { m_editor->getPrefabSystem().savePrefab(Lumix::Path(filename + Lumix::stringLength(base_path))); } else { m_editor->getPrefabSystem().savePrefab(Lumix::Path(filename)); } } } } void autosnapDown() { auto& gizmo = m_editor->getGizmo(); gizmo.setAutosnapDown(!gizmo.isAutosnapDown()); } void destroyEntity() { auto& selected_entities = m_editor->getSelectedEntities(); if (selected_entities.empty()) return; m_editor->destroyEntities(&selected_entities[0], selected_entities.size()); } void loadAndExecuteCommands() { char filename[Lumix::MAX_PATH_LENGTH]; if (PlatformInterface::getOpenFilename(filename, Lumix::lengthOf(filename), "JSON files\0*.json\0", nullptr)) { m_editor->executeUndoStack(Lumix::Path(filename)); } } void saveUndoStack() { char filename[Lumix::MAX_PATH_LENGTH]; if (PlatformInterface::getSaveFilename(filename, Lumix::lengthOf(filename), "JSON files\0*.json\0", "json")) { m_editor->saveUndoStack(Lumix::Path(filename)); } } void addWindowAction(Action* action) override { addAction(action); for (int i = 0; i < m_window_actions.size(); ++i) { if (Lumix::compareString(m_window_actions[i]->label, action->label) > 0) { m_window_actions.insert(i, action); return; } } m_window_actions.push(action); } void addAction(Action* action) override { for (int i = 0; i < m_actions.size(); ++i) { if (Lumix::compareString(m_actions[i]->label, action->label) > 0) { m_actions.insert(i, action); return; } } m_actions.push(action); } template <void (StudioAppImpl::*func)()> Action& addAction(const char* label, const char* name) { auto* a = LUMIX_NEW(m_editor->getAllocator(), Action)(label, name); a->func.bind<StudioAppImpl, func>(this); addAction(a); return *a; } template <void (StudioAppImpl::*func)()> void addAction(const char* label, const char* name, int shortcut0, int shortcut1, int shortcut2) { auto* a = LUMIX_NEW(m_editor->getAllocator(), Action)( label, name, shortcut0, shortcut1, shortcut2); a->func.bind<StudioAppImpl, func>(this); addAction(a); } Action* getAction(const char* name) override { for (auto* a : m_actions) { if (Lumix::equalStrings(a->name, name)) return a; } return nullptr; } static void showAddComponentNode(const StudioApp::AddCmpTreeNode* node, const char* filter) { if (!node) return; if (filter[0]) { if (!node->plugin) showAddComponentNode(node->child, filter); else if (Lumix::stristr(node->plugin->getLabel(), filter)) node->plugin->onGUI(false, true); showAddComponentNode(node->next, filter); return; } if (node->plugin) { node->plugin->onGUI(false, false); showAddComponentNode(node->next, filter); return; } const char* last = Lumix::reverseFind(node->label, nullptr, '/'); if (ImGui::BeginMenu(last ? last + 1 : node->label)) { showAddComponentNode(node->child, filter); ImGui::EndMenu(); } showAddComponentNode(node->next, filter); } void onCreateEntityWithComponentGUI() { doMenuItem(*getAction("createEntity"), true); ImGui::Separator(); ImGui::FilterInput("Filter", m_component_filter, sizeof(m_component_filter)); showAddComponentNode(m_add_cmp_root.child, m_component_filter); } void entityMenu() { if (!ImGui::BeginMenu("Entity")) return; bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); if (ImGui::BeginMenu("Create")) { onCreateEntityWithComponentGUI(); ImGui::EndMenu(); } doMenuItem(*getAction("destroyEntity"), is_any_entity_selected); doMenuItem(*getAction("savePrefab"), is_any_entity_selected); doMenuItem(*getAction("showEntities"), is_any_entity_selected); doMenuItem(*getAction("hideEntities"), is_any_entity_selected); ImGui::EndMenu(); } void editMenu() { if (!ImGui::BeginMenu("Edit")) return; bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); doMenuItem(*getAction("undo"), m_editor->canUndo()); doMenuItem(*getAction("redo"), m_editor->canRedo()); ImGui::Separator(); doMenuItem(*getAction("copy"), is_any_entity_selected); doMenuItem(*getAction("paste"), m_editor->canPasteEntities()); ImGui::Separator(); doMenuItem(*getAction("orbitCamera"), is_any_entity_selected || m_editor->isOrbitCamera()); doMenuItem(*getAction("setTranslateGizmoMode"), true); doMenuItem(*getAction("setRotateGizmoMode"), true); doMenuItem(*getAction("setPivotCenter"), true); doMenuItem(*getAction("setPivotOrigin"), true); doMenuItem(*getAction("setLocalCoordSystem"), true); doMenuItem(*getAction("setGlobalCoordSystem"), true); if (ImGui::BeginMenu("View", true)) { doMenuItem(*getAction("viewTop"), true); doMenuItem(*getAction("viewFront"), true); doMenuItem(*getAction("viewSide"), true); ImGui::EndMenu(); } ImGui::EndMenu(); } void fileMenu() { if (!ImGui::BeginMenu("File")) return; doMenuItem(*getAction("newUniverse"), true); if (ImGui::BeginMenu("Open")) { ImGui::FilterInput("Filter", m_open_filter, sizeof(m_open_filter)); for (auto& univ : m_universes) { if ((m_open_filter[0] == '\0' || Lumix::stristr(univ.data, m_open_filter)) && ImGui::MenuItem(univ.data)) { if (m_editor->isUniverseChanged()) { Lumix::copyString(m_universe_to_load, univ.data); m_confirm_load = true; } else { m_editor->loadUniverse(univ.data); setTitle(univ.data); } } } ImGui::EndMenu(); } doMenuItem(*getAction("save"), !m_editor->isGameMode()); doMenuItem(*getAction("saveAs"), !m_editor->isGameMode()); doMenuItem(*getAction("exit"), true); ImGui::EndMenu(); } void toolsMenu() { if (!ImGui::BeginMenu("Tools")) return; bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); doMenuItem(*getAction("lookAtSelected"), is_any_entity_selected); doMenuItem(*getAction("toggleGameMode"), true); doMenuItem(*getAction("toggleMeasure"), true); doMenuItem(*getAction("snapDown"), is_any_entity_selected); doMenuItem(*getAction("autosnapDown"), true); if (ImGui::MenuItem("Save commands")) saveUndoStack(); if (ImGui::MenuItem("Load commands")) loadAndExecuteCommands(); if (ImGui::MenuItem("Pack data")) packData(); ImGui::EndMenu(); } void viewMenu() { if (!ImGui::BeginMenu("View")) return; ImGui::MenuItem("Asset browser", nullptr, &m_asset_browser->m_is_opened); doMenuItem(*getAction("entityList"), true); ImGui::MenuItem("Log", nullptr, &m_log_ui->m_is_opened); ImGui::MenuItem("Profiler", nullptr, &m_profiler_ui->m_is_opened); ImGui::MenuItem("Properties", nullptr, &m_property_grid->m_is_opened); doMenuItem(*getAction("settings"), true); ImGui::Separator(); for (Action* action : m_window_actions) { doMenuItem(*action, true); } ImGui::EndMenu(); } float showMainMenu() { bool is_any_entity_selected = !m_editor->getSelectedEntities().empty(); if (m_confirm_exit) { ImGui::OpenPopup("confirm_exit"); m_confirm_exit = false; } if (ImGui::BeginPopupModal("confirm_exit")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { m_finished = true; ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } if (m_confirm_new) { ImGui::OpenPopup("confirm_new"); m_confirm_new = false; } if (ImGui::BeginPopupModal("confirm_new")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { m_editor->newUniverse(); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } if (m_confirm_load) { ImGui::OpenPopup("confirm_load"); m_confirm_load = false; } if(ImGui::BeginPopupModal("confirm_load")) { ImGui::Text("All unsaved changes will be lost, do you want to continue?"); if (ImGui::Button("Continue")) { m_editor->loadUniverse(m_universe_to_load); setTitle(m_universe_to_load); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } float menu_height = 0; if (ImGui::BeginMainMenuBar()) { fileMenu(); editMenu(); entityMenu(); toolsMenu(); viewMenu(); Lumix::StaticString<200> stats(""); if (m_engine->getFileSystem().hasWork()) stats << "Loading... | "; stats << "FPS: "; stats << m_engine->getFPS(); if ((SDL_GetWindowFlags(m_window) & SDL_WINDOW_INPUT_FOCUS) == 0) stats << " - inactive window"; auto stats_size = ImGui::CalcTextSize(stats); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); ImGui::Text("%s", (const char*)stats); if (m_log_ui->getUnreadErrorCount() == 1) { ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); auto error_stats_size = ImGui::CalcTextSize("1 error | "); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x - error_stats_size.x); ImGui::TextColored(ImVec4(1, 0, 0, 1), "1 error | "); } else if (m_log_ui->getUnreadErrorCount() > 1) { Lumix::StaticString<50> error_stats("", m_log_ui->getUnreadErrorCount(), " errors | "); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x); auto error_stats_size = ImGui::CalcTextSize(error_stats); ImGui::SameLine(ImGui::GetContentRegionMax().x - stats_size.x - error_stats_size.x); ImGui::TextColored(ImVec4(1, 0, 0, 1), "%s", (const char*)error_stats); } menu_height = ImGui::GetWindowSize().y; ImGui::EndMainMenuBar(); } return menu_height; } void showEntityListToolbar() { auto pos = ImGui::GetCursorScreenPos(); ImGui::BeginToolbar("entity_list_toolbar", pos, ImVec2(0, 24)); auto& groups = m_editor->getEntityGroups(); if (getAction("createGroup")->toolbarButton()) { ImGui::OpenPopup("create_entity_group_popup"); } if (groups.getGroupCount() > 1 && getAction("removeGroup")->toolbarButton()) { groups.deleteGroup(groups.current_group); groups.current_group = groups.current_group % groups.getGroupCount(); } if (getAction("selectAssigned")->toolbarButton()) { m_editor->selectEntities( groups.getGroupEntities(groups.current_group), groups.getGroupEntitiesCount(groups.current_group)); } if (getAction("assignSelected")->toolbarButton()) { auto& selected = m_editor->getSelectedEntities(); for (auto e : selected) { groups.setGroup(e, groups.current_group); } } if (getAction("lock")->toolbarButton()) groups.freezeGroup(groups.current_group, true); if (getAction("unlock")->toolbarButton()) groups.freezeGroup(groups.current_group, false); if (getAction("show")->toolbarButton()) { m_editor->showEntities( groups.getGroupEntities(groups.current_group), groups.getGroupEntitiesCount(groups.current_group)); } if (getAction("hide")->toolbarButton()) { m_editor->hideEntities( groups.getGroupEntities(groups.current_group), groups.getGroupEntitiesCount(groups.current_group)); } if (ImGui::BeginPopup("create_entity_group_popup")) { static char group_name[20] = ""; ImGui::InputText("New group name", group_name, Lumix::lengthOf(group_name)); if (group_name[0] == 0) { ImGui::Text("Group name can not be empty"); } else if (groups.getGroup(group_name) != -1) { ImGui::Text("Group with that name already exists"); } else if (ImGui::Button("Create")) { groups.createGroup(group_name); group_name[0] = 0; ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } ImGui::EndToolbar(); } void onEntityListGUI() { PROFILE_FUNCTION(); if (ImGui::BeginDock("Entity List", &m_is_entity_list_opened)) { showEntityListToolbar(); if (ImGui::BeginChild("")) { auto* universe = m_editor->getUniverse(); auto& groups = m_editor->getEntityGroups(); groups.current_group = groups.current_group % groups.getGroupCount(); for (int i = 0; i < groups.getGroupCount(); ++i) { auto* name = groups.getGroupName(i); int entities_count = groups.getGroupEntitiesCount(i); const char* locked_text = groups.isGroupFrozen(i) ? "locked" : ""; const char* current_text = groups.current_group == i ? "<-" : ""; if (ImGui::TreeNode(name, "%s (%d) %s %s", name, entities_count, locked_text, current_text)) { ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() - ImGui::GetStyle().FramePadding.x); static ImVec2 size(0, 200); char buffer[1024]; ImGui::ListBoxHeader("Resources", size); ImGuiListClipper clipper(groups.getGroupEntitiesCount(i), ImGui::GetTextLineHeightWithSpacing()); while (clipper.Step()) { for (int j = clipper.DisplayStart; j < clipper.DisplayEnd; ++j) { Lumix::Entity entity = groups.getGroupEntities(i)[j]; getEntityListDisplayName(*m_editor, buffer, sizeof(buffer), entity); if (ImGui::Selectable(buffer)) { m_editor->selectEntities(&entity, 1); } if (ImGui::IsMouseDragging() && ImGui::IsItemActive()) { startDrag(StudioApp::DragData::ENTITY, &entity, sizeof(entity)); } } } ImGui::ListBoxFooter(); ImGui::PopItemWidth(); ImGui::TreePop(); } if (ImGui::IsItemClicked()) groups.current_group = i; } } ImGui::EndChild(); } ImGui::EndDock(); } void dummy() {} void startDrag(DragData::Type type, const void* data, int size) override { m_allocator.deallocate(m_drag_data.data); m_drag_data.type = type; if (size > 0) { m_drag_data.data = m_allocator.allocate(size); Lumix::copyMemory(m_drag_data.data, data, size); m_drag_data.size = size; } else { m_drag_data.data = nullptr; m_drag_data.size = 0; } } DragData getDragData() override { return m_drag_data; } void saveSettings() { m_settings.m_is_asset_browser_opened = m_asset_browser->m_is_opened; m_settings.m_is_entity_list_opened = m_is_entity_list_opened; m_settings.m_is_log_opened = m_log_ui->m_is_opened; m_settings.m_is_profiler_opened = m_profiler_ui->m_is_opened; m_settings.m_is_properties_opened = m_property_grid->m_is_opened; m_settings.m_mouse_sensitivity_x = m_editor->getMouseSensitivity().x; m_settings.m_mouse_sensitivity_y = m_editor->getMouseSensitivity().y; m_settings.save(); if (!m_metadata.save()) { Lumix::g_log_warning.log("Editor") << "Could not save metadata"; } } void initIMGUI() { ImGuiIO& io = ImGui::GetIO(); m_font = io.Fonts->AddFontFromFileTTF("bin/VeraMono.ttf", 13); io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE; io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN; io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE; io.KeyMap[ImGuiKey_A] = SDLK_a; io.KeyMap[ImGuiKey_C] = SDLK_c; io.KeyMap[ImGuiKey_V] = SDLK_v; io.KeyMap[ImGuiKey_X] = SDLK_x; io.KeyMap[ImGuiKey_Y] = SDLK_y; io.KeyMap[ImGuiKey_Z] = SDLK_z; } void loadSettings() { char cmd_line[2048]; Lumix::getCommandLine(cmd_line, Lumix::lengthOf(cmd_line)); Lumix::CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-no_crash_report")) continue; m_settings.m_force_no_crash_report = true; break; } m_settings.load(); m_asset_browser->m_is_opened = m_settings.m_is_asset_browser_opened; m_is_entity_list_opened = m_settings.m_is_entity_list_opened; m_log_ui->m_is_opened = m_settings.m_is_log_opened; m_profiler_ui->m_is_opened = m_settings.m_is_profiler_opened; m_property_grid->m_is_opened = m_settings.m_is_properties_opened; if (m_settings.m_is_maximized) { SDL_MaximizeWindow(m_window); } else if (m_settings.m_window.w > 0) { SDL_SetWindowPosition(m_window, m_settings.m_window.x, m_settings.m_window.y); SDL_SetWindowSize(m_window, m_settings.m_window.w, m_settings.m_window.h); } } void addActions() { addAction<&StudioAppImpl::newUniverse>("New", "newUniverse"); addAction<&StudioAppImpl::save>("Save", "save", KMOD_CTRL, 'S', -1); addAction<&StudioAppImpl::saveAs>("Save As", "saveAs", KMOD_CTRL, KMOD_SHIFT, 'S'); addAction<&StudioAppImpl::exit>("Exit", "exit", KMOD_CTRL, 'X', -1); addAction<&StudioAppImpl::redo>("Redo", "redo", KMOD_CTRL, KMOD_SHIFT, 'Z'); addAction<&StudioAppImpl::undo>("Undo", "undo", KMOD_CTRL, 'Z', -1); addAction<&StudioAppImpl::copy>("Copy", "copy", KMOD_CTRL, 'C', -1); addAction<&StudioAppImpl::paste>("Paste", "paste", KMOD_CTRL, 'V', -1); addAction<&StudioAppImpl::toggleOrbitCamera>("Orbit camera", "orbitCamera") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isOrbitCamera>(this); addAction<&StudioAppImpl::setTranslateGizmoMode>("Translate", "setTranslateGizmoMode") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isTranslateMode>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setRotateGizmoMode>("Rotate", "setRotateGizmoMode") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isRotateMode>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setTopView>("Top", "viewTop"); addAction<&StudioAppImpl::setFrontView>("Front", "viewFront"); addAction<&StudioAppImpl::setSideView>("Side", "viewSide"); addAction<&StudioAppImpl::setLocalCoordSystem>("Local", "setLocalCoordSystem") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isLocalCoordSystem>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setGlobalCoordSystem>("Global", "setGlobalCoordSystem") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isGlobalCoordSystem>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setPivotCenter>("Center", "setPivotCenter") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isPivotCenter>(&m_editor->getGizmo()); addAction<&StudioAppImpl::setPivotOrigin>("Origin", "setPivotOrigin") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isPivotOrigin>(&m_editor->getGizmo()); addAction<&StudioAppImpl::createEntity>("Create empty", "createEntity"); addAction<&StudioAppImpl::destroyEntity>("Destroy", "destroyEntity", SDLK_DELETE, -1, -1); addAction<&StudioAppImpl::showEntities>("Show", "showEntities"); addAction<&StudioAppImpl::hideEntities>("Hide", "hideEntities"); addAction<&StudioAppImpl::savePrefab>("Save prefab", "savePrefab"); addAction<&StudioAppImpl::toggleGameMode>("Game Mode", "toggleGameMode") .is_selected.bind<Lumix::WorldEditor, &Lumix::WorldEditor::isGameMode>(m_editor); addAction<&StudioAppImpl::toggleMeasure>("Toggle measure", "toggleMeasure") .is_selected.bind<Lumix::WorldEditor, &Lumix::WorldEditor::isMeasureToolActive>(m_editor); addAction<&StudioAppImpl::autosnapDown>("Autosnap down", "autosnapDown") .is_selected.bind<Lumix::Gizmo, &Lumix::Gizmo::isAutosnapDown>(&m_editor->getGizmo()); addAction<&StudioAppImpl::snapDown>("Snap down", "snapDown"); addAction<&StudioAppImpl::lookAtSelected>("Look at selected", "lookAtSelected"); addAction<&StudioAppImpl::toggleAssetBrowser>("Asset Browser", "assetBrowser") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isAssetBrowserOpened>(this); addAction<&StudioAppImpl::toggleEntityList>("Entity List", "entityList") .is_selected.bind<StudioAppImpl, &StudioAppImpl::isEntityListOpened>(this); addAction<&StudioAppImpl::toggleSettings>("Settings", "settings") .is_selected.bind<StudioAppImpl, &StudioAppImpl::areSettingsOpened>(this); addAction<&StudioAppImpl::dummy>("Unhide entities from group", "show").is_global = false; addAction<&StudioAppImpl::dummy>("Hide entities from group", "hide").is_global = false; addAction<&StudioAppImpl::dummy>("Lock group", "lock").is_global = false; addAction<&StudioAppImpl::dummy>("Unlock group", "unlock").is_global = false; addAction<&StudioAppImpl::dummy>("Create group", "createGroup").is_global = false; addAction<&StudioAppImpl::dummy>("Remove group", "removeGroup").is_global = false; addAction<&StudioAppImpl::dummy>("Select assigned", "selectAssigned").is_global = false; addAction<&StudioAppImpl::dummy>("Assigned selected", "assignSelected").is_global = false; } void loadUserPlugins() { char cmd_line[2048]; Lumix::getCommandLine(cmd_line, Lumix::lengthOf(cmd_line)); Lumix::CommandLineParser parser(cmd_line); auto& plugin_manager = m_editor->getEngine().getPluginManager(); while (parser.next()) { if (!parser.currentEquals("-plugin")) continue; if (!parser.next()) break; char tmp[Lumix::MAX_PATH_LENGTH]; parser.getCurrent(tmp, Lumix::lengthOf(tmp)); bool loaded = plugin_manager.load(tmp) != nullptr; if (!loaded) { Lumix::g_log_error.log("Editor") << "Could not load plugin " << tmp << " requested by command line"; } } } void loadUniverseFromCommandLine() { char cmd_line[2048]; char path[Lumix::MAX_PATH_LENGTH]; Lumix::getCommandLine(cmd_line, Lumix::lengthOf(cmd_line)); Lumix::CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-open")) continue; if (!parser.next()) break; parser.getCurrent(path, Lumix::lengthOf(path)); m_editor->loadUniverse(path); setTitle(path); m_is_welcome_screen_opened = false; break; } } static void checkDataDirCommandLine(char* dir, int max_size) { char cmd_line[2048]; Lumix::getCommandLine(cmd_line, Lumix::lengthOf(cmd_line)); Lumix::CommandLineParser parser(cmd_line); while (parser.next()) { if (!parser.currentEquals("-data_dir")) continue; if (!parser.next()) break; parser.getCurrent(dir, max_size); break; } } void addPlugin(IPlugin& plugin) override { m_plugins.push(&plugin); for (auto* i : m_plugins) { i->pluginAdded(plugin); plugin.pluginAdded(*i); } } void removePlugin(IPlugin& plugin) override { m_plugins.eraseItemFast(&plugin); } void setStudioApp() { m_editor->getPrefabSystem().setStudioApp(*this); auto& plugin_manager = m_editor->getEngine().getPluginManager(); #ifdef STATIC_PLUGINS for (auto* plugin : plugin_manager.getPlugins()) { StudioApp::StaticPluginRegister::create(plugin->getName(), *this); } #else for (auto* lib : plugin_manager.getLibraries()) { auto* f = (void (*)(StudioApp&))Lumix::getLibrarySymbol(lib, "setStudioApp"); if (f) f(*this); } #endif } void runScript(const char* src, const char* script_name) override { lua_State* L = m_engine->getState(); bool errors = luaL_loadbuffer(L, src, Lumix::stringLength(src), script_name) != LUA_OK; errors = errors || lua_pcall(L, 0, 0, 0) != LUA_OK; if (errors) { Lumix::g_log_error.log("Editor") << script_name << ": " << lua_tostring(L, -1); lua_pop(L, 1); } } void LUA_exitGameMode() { m_editor->toggleGameMode(); } void LUA_exit(int exit_code) { m_finished = true; m_exit_code = exit_code; } bool LUA_runTest(const char* dir, const char* name) { return m_editor->runTest(dir, name); } void createLua() { lua_State* L = m_engine->getState(); Lumix::LuaWrapper::createSystemVariable(L, "Editor", "editor", this); #define REGISTER_FUNCTION(F) \ do { \ auto* f = &Lumix::LuaWrapper::wrapMethod<StudioAppImpl, decltype(&StudioAppImpl::LUA_##F), &StudioAppImpl::LUA_##F>; \ Lumix::LuaWrapper::createSystemFunction(L, "Editor", #F, f); \ } while(false) \ REGISTER_FUNCTION(runTest); REGISTER_FUNCTION(exit); REGISTER_FUNCTION(exitGameMode); #undef REGISTER_FUNCTION } void checkScriptCommandLine() { char command_line[1024]; Lumix::getCommandLine(command_line, Lumix::lengthOf(command_line)); Lumix::CommandLineParser parser(command_line); while (parser.next()) { if (parser.currentEquals("-run_script")) { if (!parser.next()) break; char tmp[Lumix::MAX_PATH_LENGTH]; parser.getCurrent(tmp, Lumix::lengthOf(tmp)); Lumix::FS::OsFile file; if (file.open(tmp, Lumix::FS::Mode::OPEN_AND_READ, m_allocator)) { auto size = file.size(); auto* src = (char*)m_allocator.allocate(size + 1); file.read(src, size); src[size] = 0; runScript((const char*)src, tmp); m_allocator.deallocate(src); file.close(); } else { Lumix::g_log_error.log("Editor") << "Could not open " << tmp; } break; } } } static bool includeFileInPack(const char* filename) { if (filename[0] == '.') return false; if (Lumix::compareStringN("bin/", filename, 4) == 0) return false; if (Lumix::compareStringN("bin32/", filename, 4) == 0) return false; if (Lumix::equalStrings("data.pak", filename)) return false; if (Lumix::equalStrings("error.log", filename)) return false; return true; } static bool includeDirInPack(const char* filename) { if (filename[0] == '.') return false; if (Lumix::compareStringN("bin", filename, 4) == 0) return false; if (Lumix::compareStringN("bin32", filename, 4) == 0) return false; return true; } #pragma pack(1) struct PackFileInfo { Lumix::u32 hash; Lumix::u64 offset; Lumix::u64 size; using Path = Lumix::StaticString<Lumix::MAX_PATH_LENGTH>; }; #pragma pack() void packDataScan(const char* dir_path, Lumix::Array<PackFileInfo>& infos, Lumix::Array<PackFileInfo::Path>& paths) { auto* iter = PlatformInterface::createFileIterator(dir_path, m_allocator); PlatformInterface::FileInfo info; while (PlatformInterface::getNextFile(iter, &info)) { char normalized_path[Lumix::MAX_PATH_LENGTH]; Lumix::PathUtils::normalize(info.filename, normalized_path, Lumix::lengthOf(normalized_path)); if (info.is_directory) { if (!includeDirInPack(normalized_path)) continue; char dir[Lumix::MAX_PATH_LENGTH] = {0}; if (dir_path[0] != '.') Lumix::copyString(dir, dir_path); Lumix::catString(dir, info.filename); Lumix::catString(dir, "/"); packDataScan(dir, infos, paths); continue; } if(!includeFileInPack(normalized_path)) continue; auto& out_path = paths.emplace(); if(dir_path[0] == '.') { Lumix::copyString(out_path.data, Lumix::lengthOf(out_path.data), normalized_path); } else { Lumix::copyString(out_path.data, Lumix::lengthOf(out_path.data), dir_path); Lumix::catString(out_path.data, Lumix::lengthOf(out_path.data), normalized_path); } auto& out_info = infos.emplace(); out_info.hash = Lumix::crc32(out_path.data); out_info.size = PlatformInterface::getFileSize(out_path.data); out_info.offset = ~0UL; } PlatformInterface::destroyFileIterator(iter); } void packDataScanResources(Lumix::Array<PackFileInfo>& infos, Lumix::Array<PackFileInfo::Path>& paths) { Lumix::ResourceManager& rm = m_editor->getEngine().getResourceManager(); for (auto iter = rm.getAll().begin(), end = rm.getAll().end(); iter != end; ++iter) { const auto& resources = iter.value()->getResourceTable(); for (auto res_iter = resources.begin(), res_iter_end = resources.end(); res_iter != res_iter_end; ++res_iter) { Lumix::Resource* res = res_iter.value(); Lumix::copyString(paths.emplace().data, Lumix::MAX_PATH_LENGTH, res->getPath().c_str()); auto& out_info = infos.emplace(); out_info.hash = Lumix::crc32(res->getPath().c_str()); out_info.size = PlatformInterface::getFileSize(res->getPath().c_str()); out_info.offset = ~0UL; } } } void packData() { char dest[Lumix::MAX_PATH_LENGTH]; char dest_dir[Lumix::MAX_PATH_LENGTH]; if (!PlatformInterface::getOpenDirectory(dest_dir, Lumix::lengthOf(dest_dir), ".")) return; static const char* OUT_FILENAME = "data.pak"; Lumix::catString(dest_dir, "/"); Lumix::copyString(dest, dest_dir); Lumix::catString(dest, OUT_FILENAME); Lumix::Array<PackFileInfo> infos(m_allocator); Lumix::Array<PackFileInfo::Path> paths(m_allocator); infos.reserve(10000); paths.reserve(10000); packDataScan("./", infos, paths); if (infos.empty()) { Lumix::g_log_error.log("Editor") << "No files found while trying to create " << dest; return; } Lumix::FS::OsFile file; if (!file.open(dest, Lumix::FS::Mode::CREATE_AND_WRITE, m_allocator)) { Lumix::g_log_error.log("Editor") << "Could not create " << dest; return; } int count = infos.size(); file.write(&count, sizeof(count)); Lumix::u64 offset = sizeof(count) + sizeof(infos[0]) * count; for (auto& info : infos) { info.offset = offset; offset += info.size; } file.write(&infos[0], sizeof(infos[0]) * count); for (auto& path : paths) { Lumix::FS::OsFile src; size_t src_size = PlatformInterface::getFileSize(path.data); if (!src.open(path.data, Lumix::FS::Mode::OPEN_AND_READ, m_allocator)) { file.close(); Lumix::g_log_error.log("Editor") << "Could not open " << path.data; return; } Lumix::u8 buf[4096]; for (; src_size > 0; src_size -= Lumix::Math::minimum(sizeof(buf), src_size)) { size_t batch_size = Lumix::Math::minimum(sizeof(buf), src_size); if (!src.read(buf, batch_size)) { file.close(); Lumix::g_log_error.log("Editor") << "Could not read " << path.data; return; } file.write(buf, batch_size); } src.close(); } file.close(); const char* bin_files[] = { "app.exe", "assimp.dll", "nvToolsExt64_1.dll", "PhysX3CharacterKinematicCHECKED_x64.dll", "PhysX3CHECKED_x64.dll", "PhysX3CommonCHECKED_x64.dll", "PhysX3CookingCHECKED_x64.dll" }; for(auto& file : bin_files) { Lumix::StaticString<Lumix::MAX_PATH_LENGTH> tmp(dest_dir, file); Lumix::StaticString<Lumix::MAX_PATH_LENGTH> src("bin/", file); if (!Lumix::copyFile(src, tmp)) { Lumix::g_log_error.log("Editor") << "Failed to copy " << src << " to " << tmp; } } Lumix::StaticString<Lumix::MAX_PATH_LENGTH> tmp(dest_dir); tmp << "startup.lua"; if (!Lumix::copyFile("startup.lua", tmp)) { Lumix::g_log_error.log("Editor") << "Failed to copy startup.lua to " << tmp; } } void loadLuaPlugin(const char* dir, const char* filename) { Lumix::StaticString<Lumix::MAX_PATH_LENGTH> path(dir, filename); Lumix::FS::OsFile file; if (file.open(path, Lumix::FS::Mode::OPEN_AND_READ, m_allocator)) { auto size = file.size(); auto* src = (char*)m_engine->getLIFOAllocator().allocate(size + 1); file.read(src, size); src[size] = 0; LuaPlugin* plugin = LUMIX_NEW(m_editor->getAllocator(), LuaPlugin)(*this, src, filename); addPlugin(*plugin); m_engine->getLIFOAllocator().deallocate(src); file.close(); } else { Lumix::g_log_warning.log("Editor") << "Failed to open " << path; } } void scanUniverses() { auto* iter = PlatformInterface::createFileIterator("universes/", m_allocator); PlatformInterface::FileInfo info; while (PlatformInterface::getNextFile(iter, &info)) { if (info.filename[0] == '.') continue; if (!info.is_directory) continue; if (Lumix::startsWith(info.filename, "__")) continue; char basename[Lumix::MAX_PATH_LENGTH]; Lumix::PathUtils::getBasename(basename, Lumix::lengthOf(basename), info.filename); m_universes.emplace(basename); } PlatformInterface::destroyFileIterator(iter); } void findLuaPlugins(const char* dir) { auto* iter = PlatformInterface::createFileIterator(dir, m_allocator); PlatformInterface::FileInfo info; while (PlatformInterface::getNextFile(iter, &info)) { char normalized_path[Lumix::MAX_PATH_LENGTH]; Lumix::PathUtils::normalize(info.filename, normalized_path, Lumix::lengthOf(normalized_path)); if (normalized_path[0] == '.') continue; if (info.is_directory) { char dir_path[Lumix::MAX_PATH_LENGTH] = { 0 }; if (dir[0] != '.') Lumix::copyString(dir_path, dir); Lumix::catString(dir_path, info.filename); Lumix::catString(dir_path, "/"); findLuaPlugins(dir_path); } else { char ext[5]; Lumix::PathUtils::getExtension(ext, Lumix::lengthOf(ext), info.filename); if (Lumix::equalStrings(ext, "lua")) { loadLuaPlugin(dir, info.filename); } } } PlatformInterface::destroyFileIterator(iter); } void processSystemEvents() { SDL_Event event; auto& io = ImGui::GetIO(); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_MOVED: case SDL_WINDOWEVENT_SIZE_CHANGED: { int x, y, w, h; SDL_GetWindowSize(m_window, &w, &h); SDL_GetWindowPosition(m_window, &x, &y); onWindowTransformed(x, y, w, h); } break; case SDL_WINDOWEVENT_CLOSE: exit(); break; } break; case SDL_QUIT: exit(); break; case SDL_MOUSEBUTTONDOWN: m_editor->setAdditiveSelection(io.KeyCtrl); m_editor->setSnapMode(io.KeyShift); switch (event.button.button) { case SDL_BUTTON_LEFT: io.MouseDown[0] = true; break; case SDL_BUTTON_RIGHT: io.MouseDown[1] = true; break; case SDL_BUTTON_MIDDLE: io.MouseDown[2] = true; break; } break; case SDL_MOUSEBUTTONUP: switch (event.button.button) { case SDL_BUTTON_LEFT: io.MouseDown[0] = false; break; case SDL_BUTTON_RIGHT: io.MouseDown[1] = false; break; case SDL_BUTTON_MIDDLE: io.MouseDown[2] = false; break; } break; case SDL_MOUSEMOTION: { auto& input_system = m_editor->getEngine().getInputSystem(); input_system.injectMouseXMove(float(event.motion.xrel), float(event.motion.x)); input_system.injectMouseYMove(float(event.motion.yrel), float(event.motion.y)); if (SDL_GetRelativeMouseMode() == SDL_FALSE) { io.MousePos.x = (float)event.motion.x; io.MousePos.y = (float)event.motion.y; } } break; case SDL_TEXTINPUT: io.AddInputCharactersUTF8(event.text.text); break; case SDL_KEYDOWN: case SDL_KEYUP: { int key = event.key.keysym.sym & ~SDLK_SCANCODE_MASK; io.KeysDown[key] = (event.type == SDL_KEYDOWN); if (event.key.keysym.scancode == SDL_SCANCODE_KP_ENTER) { io.KeysDown[SDLK_RETURN] = (event.type == SDL_KEYDOWN); } io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); checkShortcuts(); } break; case SDL_MOUSEWHEEL: { io.MouseWheel = float(event.wheel.x != 0 ? event.wheel.x : event.wheel.y); break; } } } } void run() override { checkScriptCommandLine(); Lumix::Timer* timer = Lumix::Timer::create(m_allocator); while (!m_finished) { { timer->tick(); PROFILE_BLOCK("all"); float frame_time; { PROFILE_BLOCK("tick"); processSystemEvents(); if (!m_finished) update(); frame_time = timer->tick(); } float wanted_fps = (SDL_GetWindowFlags(m_window) & SDL_WINDOW_INPUT_FOCUS) != 0 ? 60.0f : 5.0f; if (frame_time < 1 / wanted_fps) { PROFILE_BLOCK("sleep"); Lumix::MT::sleep(Lumix::u32(1000 / wanted_fps - frame_time * 1000)); } } Lumix::Profiler::frame(); } Lumix::Timer::destroy(timer); } void checkWorkingDirector() { if (!PlatformInterface::dirExists("bin")) { Lumix::messageBox("Bin directory not found, please check working directory."); } else if (!PlatformInterface::dirExists("pipelines")) { Lumix::messageBox("Pipelines directory not found, please check working directory."); } } void unloadIcons() { auto& render_interface = *m_editor->getRenderInterface(); for (auto* action : m_actions) { render_interface.unloadTexture(action->icon); } } void loadIcons() { auto& render_interface = *m_editor->getRenderInterface(); for (auto* action : m_actions) { char tmp[Lumix::MAX_PATH_LENGTH]; action->getIconPath(tmp, Lumix::lengthOf(tmp)); if (PlatformInterface::fileExists(tmp)) { action->icon = render_interface.loadTexture(Lumix::Path(tmp)); } else { action->icon = nullptr; } } } void init() { SDL_SetMainReady(); SDL_Init(SDL_INIT_VIDEO); checkWorkingDirector(); m_window = SDL_CreateWindow("Lumix Studio", 0, 0, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); char current_dir[Lumix::MAX_PATH_LENGTH]; PlatformInterface::getCurrentDirectory(current_dir, Lumix::lengthOf(current_dir)); PlatformInterface::setWindow(m_window); char data_dir_path[Lumix::MAX_PATH_LENGTH] = {}; checkDataDirCommandLine(data_dir_path, Lumix::lengthOf(data_dir_path)); m_engine = Lumix::Engine::create(current_dir, data_dir_path, nullptr, m_allocator); createLua(); SDL_SysWMinfo window_info; SDL_VERSION(&window_info.version); SDL_GetWindowWMInfo(m_window, &window_info); Lumix::Engine::PlatformData platform_data = {}; #ifdef _WIN32 platform_data.window_handle = window_info.info.win.window; ImGui::GetIO().ImeWindowHandle = window_info.info.win.window; #elif defined(__linux__) platform_data.window_handle = (void*)(uintptr_t)window_info.info.x11.window; platform_data.display = window_info.info.x11.display; #endif m_engine->setPlatformData(platform_data); m_editor = Lumix::WorldEditor::create(current_dir, *m_engine, m_allocator); m_settings.m_editor = m_editor; scanUniverses(); loadUserPlugins(); addActions(); m_asset_browser = LUMIX_NEW(m_allocator, AssetBrowser)(*this); m_property_grid = LUMIX_NEW(m_allocator, PropertyGrid)(*this); auto engine_allocator = static_cast<Lumix::Debug::Allocator*>(&m_engine->getAllocator()); m_profiler_ui = ProfilerUI::create(*m_engine); m_log_ui = LUMIX_NEW(m_allocator, LogUI)(m_editor->getAllocator()); initIMGUI(); if (!m_metadata.load()) Lumix::g_log_info.log("Editor") << "Could not load metadata"; setStudioApp(); loadIcons(); loadSettings(); loadUniverseFromCommandLine(); findLuaPlugins("plugins/lua/"); } void checkShortcuts() { if (ImGui::IsAnyItemActive()) return; int key_count; auto* state = SDL_GetKeyboardState(&key_count); Lumix::u32 pressed_modifiers = SDL_GetModState() & (KMOD_CTRL | KMOD_ALT | KMOD_SHIFT); for (auto* a : m_actions) { if (!a->is_global || a->shortcut[0] == -1) continue; Lumix::u32 action_modifiers = 0; for (int i = 0; i < Lumix::lengthOf(a->shortcut) + 1; ++i) { if ((i == Lumix::lengthOf(a->shortcut) || a->shortcut[i] == -1) && action_modifiers == pressed_modifiers) { a->func.invoke(); return; } if (i == Lumix::lengthOf(a->shortcut)) break; if (a->shortcut[i] == -1) break; if (a->shortcut[i] >= key_count) break; if (!state[a->shortcut[i]]) break; if (a->shortcut[i] == SDL_SCANCODE_LCTRL) action_modifiers |= KMOD_LCTRL; else if (a->shortcut[i] == SDL_SCANCODE_LALT) action_modifiers |= KMOD_LALT; else if (a->shortcut[i] == SDL_SCANCODE_LSHIFT) action_modifiers |= KMOD_LSHIFT; else if (a->shortcut[i] == SDL_SCANCODE_RCTRL) action_modifiers |= KMOD_RCTRL; else if (a->shortcut[i] == SDL_SCANCODE_RALT) action_modifiers |= KMOD_RALT; else if (a->shortcut[i] == SDL_SCANCODE_RSHIFT) action_modifiers |= KMOD_RSHIFT; } } } void onWindowTransformed(int x, int y, int width, int height) { if (height == 0) return; m_settings.m_window.x = x; m_settings.m_window.y = y; m_settings.m_window.w = width; m_settings.m_window.h = height; m_settings.m_is_maximized = (SDL_GetWindowFlags(m_window) & SDL_WINDOW_MAXIMIZED) != 0; } void clearInputs() { auto& io = ImGui::GetIO(); io.KeyAlt = false; io.KeyCtrl = false; io.KeyShift = false; memset(io.KeysDown, 0, sizeof(io.KeysDown)); memset(io.MouseDown, 0, sizeof(io.MouseDown)); } SDL_Window* getWindow() override { return m_window; } Lumix::WorldEditor* getWorldEditor() override { return m_editor; } Lumix::DefaultAllocator m_main_allocator; Lumix::Debug::Allocator m_allocator; Lumix::Engine* m_engine; SDL_Window* m_window; Lumix::Array<Action*> m_actions; Lumix::Array<Action*> m_window_actions; Lumix::Array<Action*> m_toolbar_actions; Lumix::Array<IPlugin*> m_plugins; Lumix::Array<IAddComponentPlugin*> m_add_cmp_plugins; Lumix::Array<Lumix::StaticString<Lumix::MAX_PATH_LENGTH>> m_universes; AddCmpTreeNode m_add_cmp_root; Lumix::HashMap<Lumix::ComponentType, Lumix::string> m_component_labels; Lumix::WorldEditor* m_editor; bool m_confirm_exit; bool m_confirm_load; bool m_confirm_new; char m_universe_to_load[Lumix::MAX_PATH_LENGTH]; AssetBrowser* m_asset_browser; PropertyGrid* m_property_grid; LogUI* m_log_ui; ProfilerUI* m_profiler_ui; Lumix::string m_selected_template_name; Settings m_settings; Metadata m_metadata; char m_template_name[100]; char m_open_filter[64]; char m_component_filter[32]; bool m_finished; int m_exit_code; bool m_is_welcome_screen_opened; bool m_is_entity_list_opened; bool m_is_save_as_dialog_opened; DragData m_drag_data; ImFont* m_font; }; static size_t alignMask(size_t _value, size_t _mask) { return (_value + _mask) & ((~0) & (~_mask)); } static void* alignPtr(void* _ptr, size_t _align) { union { void* ptr; size_t addr; } un; un.ptr = _ptr; size_t mask = _align - 1; size_t aligned = alignMask(un.addr, mask); un.addr = aligned; return un.ptr; } StudioApp* StudioApp::create() { static char buf[sizeof(StudioAppImpl) * 2]; return new (Lumix::NewPlaceholder(), alignPtr(buf, ALIGN_OF(StudioAppImpl))) StudioAppImpl; } void StudioApp::destroy(StudioApp& app) { app.~StudioApp(); } static StudioApp::StaticPluginRegister* s_first_plugin = nullptr; StudioApp::StaticPluginRegister::StaticPluginRegister(const char* name, Creator creator) { this->creator = creator; this->name = name; next = s_first_plugin; s_first_plugin = this; } void StudioApp::StaticPluginRegister::create(const char* name, StudioApp& app) { auto* i = s_first_plugin; while (i) { if (Lumix::equalStrings(name, i->name)) { i->creator(app); return; } i = i->next; } }
#include "RGTopFrame.h" #include "RGBrowser.h" #include "RGEditor.h" #include "VSDSelector.h" #include <Reve/RenderElement.h> #include <TGMenu.h> #include <TGTab.h> #include <TGToolBar.h> #include <TGLabel.h> #include <TGTextEntry.h> #include <TGSplitter.h> #include <TRootEmbeddedCanvas.h> #include <TGLSAViewer.h> #include <TH1F.h> #include <TView.h> #include <TROOT.h> #include <TFile.h> #include <TStyle.h> #include <TPad.h> #include <TCanvas.h> #include <TSystem.h> #include <TRint.h> #include <TVirtualX.h> #include <TPolyLine3D.h> #include <TPolyMarker3D.h> #include <TEnv.h> #include <TStyle.h> #include <KeySymbols.h> #include "TVirtualGL.h" #include "TPluginManager.h" #include <iostream> using namespace Reve; using namespace Reve; Reve::RGTopFrame* gReve = 0; namespace { enum RGBrowserMT { M_LAYOUT_1, M_LAYOUT_2, M_LAYOUT_3 }; const char *xpm_names[] = { "lay1.xpm", "lay2.xpm", "lay3.xpm", 0 }; ToolBarData_t tb_data[] = { { "", "Standard list layout", kFALSE, M_LAYOUT_1, NULL }, { "", "TParticle latout", kFALSE, M_LAYOUT_2, NULL }, { "", "TGeo layout", kFALSE, M_LAYOUT_3, NULL }, { NULL, NULL, 0, 0, NULL } }; } // unnamed namespace /**************************************************************************/ void RGTopFrame::Init(){ fCC = 0; fHistoCanvas = 0; fSelector = 0; fBrowser = 0; fStatusBar = 0; fVSDFile = ""; fEditor = 0; fCurrentEvent = 0; fCurrentEventLTI = 0; fGeometryLTI = 0; fRedrawDisabled = false; fTimerActive = false; fRedrawTimer.Connect("Timeout()", "Reve::RGTopFrame", this, "DoRedraw3D()"); } RGTopFrame::RGTopFrame(const TGWindow *p, UInt_t w, UInt_t h, LookType_e look) : TGMainFrame(p, w, h) { Init(); TGLayoutHints *fL0 = new TGLayoutHints(kLHintsCenterX |kLHintsCenterY | kLHintsExpandY| kLHintsExpandX); TGLayoutHints *fL1 = new TGLayoutHints(kLHintsCenterX |kLHintsCenterY | kLHintsExpandY| kLHintsExpandX,2,0,2,2); TGLayoutHints* fL2 = new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 2, 2, 2, 2); TGCompositeFrame* fMainFrame = new TGCompositeFrame(this, w, h,kHorizontalFrame | kRaisedFrame); fMainFrame->SetCleanup(kDeepCleanup); TGVerticalFrame* fV2 = new TGVerticalFrame(fMainFrame, GetWidth()-40, GetHeight()-40, kSunkenFrame); fMainFrame->AddFrame(fV2, fL1); // ??? TGCanvas* fCanvasWindow = new TGCanvas(fV2,w,h); TGTab* fDisplayFrame = new TGTab(fV2, GetWidth(), GetHeight()); // browser tab TGCompositeFrame* tFrame1 = fDisplayFrame->AddTab("Object Browser"); fBrowser = new RGBrowser(tFrame1, w, h); tFrame1->AddFrame(fBrowser, fL2); // tree selection tab TGCompositeFrame* tFrame2 = fDisplayFrame->AddTab("Tree Selections"); fSelector = new VSDSelector(fBrowser->GetListTree(), tFrame2); // canvas Reve::PushPad(); TGCompositeFrame* tFrame3 = fDisplayFrame->AddTab("Canvas"); TRootEmbeddedCanvas* fEmbeddedCanvas3 = new TRootEmbeddedCanvas("fEmbeddedCanvas3", tFrame3, 580, 360); tFrame3->AddFrame(fEmbeddedCanvas3, fL2); fEmbeddedCanvas3->GetCanvas()->SetBorderMode(0); fCC = fEmbeddedCanvas3->GetCanvas(); // fCC->SetFillColor(1); Reve::PopPad(); // histo canvas TGCompositeFrame* frame4 = fDisplayFrame->AddTab("HistoCanvas"); TRootEmbeddedCanvas* ecanvas4 = new TRootEmbeddedCanvas("HistoCanvas", frame4, 580, 360); frame4->AddFrame(ecanvas4, fL2); fHistoCanvas = ecanvas4->GetCanvas(); fHistoCanvas->SetBorderMode(0); fV2->AddFrame(fDisplayFrame, fL0); AddFrame(fMainFrame, fL0); // Create status bar Int_t parts[] = {45, 45, 10}; fStatusBar = new TGStatusBar(this, 50, 10, kHorizontalFrame); fStatusBar->SetParts(parts, 3); TGLayoutHints* fL6 = new TGLayoutHints(kLHintsBottom| kLHintsExpandX, 0, 0, 0, 0); AddFrame(fStatusBar, fL6); fStatusBar->SetText("GUI created", 0); MapSubwindows(); /**************************************************************************/ /**************************************************************************/ fEditor = new RGEditor(fCC); fEditor->GetCan()->ChangeOptions(0); switch(look) { case LT_Classic: { fBrowser->SetupClassicLook(); // Need push/pop pad around here? Not. fCC->GetViewer3D("ogl"); break; } case LT_Editor: { fBrowser->SetupEditorLook(fEditor); fCC->GetViewer3D("ogl"); break; } case LT_GLViewer: { fBrowser->SetupGLViewerLook(fEditor, fCC); printf("Crap1 %d %d\n", GetWidth(), GetHeight()); break; } default: { printf("RGTopFrame unknown look-type, ignoring.\n"); break; } } TGLViewer* glv = dynamic_cast<TGLViewer*>(fCC->GetViewer3D()); if(glv) { glv->SetSmartRefresh(true); } /**************************************************************************/ /**************************************************************************/ fGeometryLTI = GetListTree()->AddItem(0, "Geometry"); GetListTree()->OpenItem(fGeometryLTI); Resize(GetDefaultSize()); // this is used here to init layout algorithm SetWindowName("Reve"); MapWindow(); fEditor->DisplayObject(0); gSystem->ProcessEvents(); } /**************************************************************************/ TGListTree* RGTopFrame::GetListTree() { return fBrowser->GetListTree(); } TGListTreeItem* RGTopFrame::GetEventTreeItem() { // return fBrowser->GetListTree()->FindItemByPathname("Event"); return fCurrentEventLTI; } TGListTreeItem* RGTopFrame::GetGlobalTreeItem() { return fGeometryLTI; } /**************************************************************************/ // Editor /**************************************************************************/ void RGTopFrame::EditRenderElement(RenderElement* rnr_element) { static const Exc_t eH("RGTopFrame::EditRenderElement "); TObject* tobj = 0; if(rnr_element) tobj = rnr_element->GetObject(); fEditor->DisplayObject(tobj); } /**************************************************************************/ // 3D Pad management /**************************************************************************/ void RGTopFrame::RegisterRedraw3D() { fRedrawTimer.Start(0, kTRUE); fTimerActive = true; } void RGTopFrame::DoRedraw3D() { // printf("RGTopFrame::DoRedraw3D redraw triggered\n"); fCC->Modified(); fCC->Update(); fTimerActive = false; } /**************************************************************************/ int RGTopFrame::SpawnGuiAndRun(int argc, char **argv) { LookType_e revemode = LT_Editor; if(argc >= 3 && (strcmp(argv[1], "-revemode")==0 || strcmp(argv[1], "-mode")==0)) { LookType_e m = LookType_e(atoi(argv[2])); if(m >= LT_Classic && m <= LT_GLViewer) revemode = m; printf("revemode = %d\n", revemode); } TRint theApp("App", &argc, argv); Int_t w = 800; Int_t h = 600; gReve = new RGTopFrame(gClient->GetRoot(), w, h, revemode); run_loop: try { theApp.Run(); } catch(std::string exc) { gReve->GetStatusBar()->SetText(exc.c_str()); goto run_loop; } return 0; } /**************************************************************************/ /**************************************************************************/ TGListTreeItem* RGTopFrame::AddEvent(TObject* event) { fCurrentEvent = event; RenderElementObjPtr* rnrEv = new RenderElementObjPtr(event); fCurrentEventLTI = rnrEv->AddIntoListTree(GetListTree(), 0); GetListTree()->OpenItem(fCurrentEventLTI); return fCurrentEventLTI; } TGListTreeItem* RGTopFrame::AddRenderElement(RenderElement* rnr_element) { return AddRenderElement(GetEventTreeItem(), rnr_element); } TGListTreeItem* RGTopFrame::AddRenderElement(TGListTreeItem* parent, RenderElement* rnr_element) { static const Exc_t eH("RGTopFrame::AddRenderElement "); // Here could route rnr-element to several browsers/pads. TGListTreeItem* newitem = rnr_element->AddIntoListTree(GetListTree(), parent); NotifyBrowser(); return newitem; } TGListTreeItem* RGTopFrame::AddGlobalRenderElement(RenderElement* rnr_element) { return AddGlobalRenderElement(GetGlobalTreeItem(), rnr_element); } TGListTreeItem* RGTopFrame::AddGlobalRenderElement(TGListTreeItem* parent, RenderElement* rnr_element) { static const Exc_t eH("RGTopFrame::AddGlobalRenderElement "); // Here could route rnr-element to several browsers/pads. TGListTreeItem* newitem = rnr_element->AddIntoListTree(GetListTree(), parent); NotifyBrowser(); return newitem; } /**************************************************************************/ void RGTopFrame::DrawRenderElement(RenderElement* rnr_element, TVirtualPad* pad) { if(pad == 0) pad = GetCC(); { Reve::PadHolder pHolder(false, pad); rnr_element->GetObject()->Draw(); } Redraw3D(); } void RGTopFrame::UndrawRenderElement(RenderElement* rnr_element, TVirtualPad* pad) { if(pad == 0) pad = GetCC(); { Reve::PadHolder pHolder(false, pad); pad->GetListOfPrimitives()->Remove(rnr_element->GetObject()); } Redraw3D(); } /**************************************************************************/ void RGTopFrame::RenderElementChecked(TObject* obj, Bool_t state) { // Item's user-data is blindly casted into TObject. // We recast it blindly back into the render element. RenderElement* rnrEl = (RenderElement*) obj; rnrEl->SetRnrElement(state); } /**************************************************************************/ void RGTopFrame::NotifyBrowser(TGListTreeItem* parent) { TGListTree* l_tree = GetListTree(); if(parent) l_tree->OpenItem(parent); gClient->NeedRedraw(l_tree); } /**************************************************************************/ // GeoManager registration /**************************************************************************/ TGeoManager* RGTopFrame::GetGeometry(const TString& filename) { static const Exc_t eH("RGTopFrame::GetGeometry "); TString exp_filename = filename; gSystem->ExpandPathName(exp_filename); printf("%s loading: '%s' -> '%s'.\n", eH.Data(), filename.Data(), exp_filename.Data()); std::map<TString, TGeoManager*>::iterator g = fGeometries.find(filename); if(g != fGeometries.end()) { return g->second; } else { if(gSystem->AccessPathName(exp_filename, kReadPermission)) throw(eH + "file '" + exp_filename + "' not readable."); gGeoManager = 0; TGeoManager::Import(filename); if(gGeoManager == 0) throw(eH + "GeoManager import failed."); gGeoManager->GetTopVolume()->VisibleDaughters(1); // Import colors exported by Gled, if they exist. { TFile f(exp_filename, "READ"); TObjArray* collist = (TObjArray*) f.Get("ColorList"); f.Close(); if(collist != 0) { TSeqCollection* glist = gROOT->GetListOfColors(); glist->Clear(); glist->AddAll(collist); } } fGeometries[filename] = gGeoManager; return gGeoManager; } } Print exceptions to terminal also. #include "RGTopFrame.h" #include "RGBrowser.h" #include "RGEditor.h" #include "VSDSelector.h" #include <Reve/RenderElement.h> #include <TGMenu.h> #include <TGTab.h> #include <TGToolBar.h> #include <TGLabel.h> #include <TGTextEntry.h> #include <TGSplitter.h> #include <TRootEmbeddedCanvas.h> #include <TGLSAViewer.h> #include <TH1F.h> #include <TView.h> #include <TROOT.h> #include <TFile.h> #include <TStyle.h> #include <TPad.h> #include <TCanvas.h> #include <TSystem.h> #include <TRint.h> #include <TVirtualX.h> #include <TPolyLine3D.h> #include <TPolyMarker3D.h> #include <TEnv.h> #include <TStyle.h> #include <KeySymbols.h> #include "TVirtualGL.h" #include "TPluginManager.h" #include <iostream> using namespace Reve; using namespace Reve; Reve::RGTopFrame* gReve = 0; namespace { enum RGBrowserMT { M_LAYOUT_1, M_LAYOUT_2, M_LAYOUT_3 }; const char *xpm_names[] = { "lay1.xpm", "lay2.xpm", "lay3.xpm", 0 }; ToolBarData_t tb_data[] = { { "", "Standard list layout", kFALSE, M_LAYOUT_1, NULL }, { "", "TParticle latout", kFALSE, M_LAYOUT_2, NULL }, { "", "TGeo layout", kFALSE, M_LAYOUT_3, NULL }, { NULL, NULL, 0, 0, NULL } }; } // unnamed namespace /**************************************************************************/ void RGTopFrame::Init(){ fCC = 0; fHistoCanvas = 0; fSelector = 0; fBrowser = 0; fStatusBar = 0; fVSDFile = ""; fEditor = 0; fCurrentEvent = 0; fCurrentEventLTI = 0; fGeometryLTI = 0; fRedrawDisabled = false; fTimerActive = false; fRedrawTimer.Connect("Timeout()", "Reve::RGTopFrame", this, "DoRedraw3D()"); } RGTopFrame::RGTopFrame(const TGWindow *p, UInt_t w, UInt_t h, LookType_e look) : TGMainFrame(p, w, h) { Init(); TGLayoutHints *fL0 = new TGLayoutHints(kLHintsCenterX |kLHintsCenterY | kLHintsExpandY| kLHintsExpandX); TGLayoutHints *fL1 = new TGLayoutHints(kLHintsCenterX |kLHintsCenterY | kLHintsExpandY| kLHintsExpandX,2,0,2,2); TGLayoutHints* fL2 = new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 2, 2, 2, 2); TGCompositeFrame* fMainFrame = new TGCompositeFrame(this, w, h,kHorizontalFrame | kRaisedFrame); fMainFrame->SetCleanup(kDeepCleanup); TGVerticalFrame* fV2 = new TGVerticalFrame(fMainFrame, GetWidth()-40, GetHeight()-40, kSunkenFrame); fMainFrame->AddFrame(fV2, fL1); // ??? TGCanvas* fCanvasWindow = new TGCanvas(fV2,w,h); TGTab* fDisplayFrame = new TGTab(fV2, GetWidth(), GetHeight()); // browser tab TGCompositeFrame* tFrame1 = fDisplayFrame->AddTab("Object Browser"); fBrowser = new RGBrowser(tFrame1, w, h); tFrame1->AddFrame(fBrowser, fL2); // tree selection tab TGCompositeFrame* tFrame2 = fDisplayFrame->AddTab("Tree Selections"); fSelector = new VSDSelector(fBrowser->GetListTree(), tFrame2); // canvas Reve::PushPad(); TGCompositeFrame* tFrame3 = fDisplayFrame->AddTab("Canvas"); TRootEmbeddedCanvas* fEmbeddedCanvas3 = new TRootEmbeddedCanvas("fEmbeddedCanvas3", tFrame3, 580, 360); tFrame3->AddFrame(fEmbeddedCanvas3, fL2); fEmbeddedCanvas3->GetCanvas()->SetBorderMode(0); fCC = fEmbeddedCanvas3->GetCanvas(); // fCC->SetFillColor(1); Reve::PopPad(); // histo canvas TGCompositeFrame* frame4 = fDisplayFrame->AddTab("HistoCanvas"); TRootEmbeddedCanvas* ecanvas4 = new TRootEmbeddedCanvas("HistoCanvas", frame4, 580, 360); frame4->AddFrame(ecanvas4, fL2); fHistoCanvas = ecanvas4->GetCanvas(); fHistoCanvas->SetBorderMode(0); fV2->AddFrame(fDisplayFrame, fL0); AddFrame(fMainFrame, fL0); // Create status bar Int_t parts[] = {45, 45, 10}; fStatusBar = new TGStatusBar(this, 50, 10, kHorizontalFrame); fStatusBar->SetParts(parts, 3); TGLayoutHints* fL6 = new TGLayoutHints(kLHintsBottom| kLHintsExpandX, 0, 0, 0, 0); AddFrame(fStatusBar, fL6); fStatusBar->SetText("GUI created", 0); MapSubwindows(); /**************************************************************************/ /**************************************************************************/ fEditor = new RGEditor(fCC); fEditor->GetCan()->ChangeOptions(0); switch(look) { case LT_Classic: { fBrowser->SetupClassicLook(); // Need push/pop pad around here? Not. fCC->GetViewer3D("ogl"); break; } case LT_Editor: { fBrowser->SetupEditorLook(fEditor); fCC->GetViewer3D("ogl"); break; } case LT_GLViewer: { fBrowser->SetupGLViewerLook(fEditor, fCC); printf("Crap1 %d %d\n", GetWidth(), GetHeight()); break; } default: { printf("RGTopFrame unknown look-type, ignoring.\n"); break; } } TGLViewer* glv = dynamic_cast<TGLViewer*>(fCC->GetViewer3D()); if(glv) { glv->SetSmartRefresh(true); } /**************************************************************************/ /**************************************************************************/ fGeometryLTI = GetListTree()->AddItem(0, "Geometry"); GetListTree()->OpenItem(fGeometryLTI); Resize(GetDefaultSize()); // this is used here to init layout algorithm SetWindowName("Reve"); MapWindow(); fEditor->DisplayObject(0); gSystem->ProcessEvents(); } /**************************************************************************/ TGListTree* RGTopFrame::GetListTree() { return fBrowser->GetListTree(); } TGListTreeItem* RGTopFrame::GetEventTreeItem() { // return fBrowser->GetListTree()->FindItemByPathname("Event"); return fCurrentEventLTI; } TGListTreeItem* RGTopFrame::GetGlobalTreeItem() { return fGeometryLTI; } /**************************************************************************/ // Editor /**************************************************************************/ void RGTopFrame::EditRenderElement(RenderElement* rnr_element) { static const Exc_t eH("RGTopFrame::EditRenderElement "); TObject* tobj = 0; if(rnr_element) tobj = rnr_element->GetObject(); fEditor->DisplayObject(tobj); } /**************************************************************************/ // 3D Pad management /**************************************************************************/ void RGTopFrame::RegisterRedraw3D() { fRedrawTimer.Start(0, kTRUE); fTimerActive = true; } void RGTopFrame::DoRedraw3D() { // printf("RGTopFrame::DoRedraw3D redraw triggered\n"); fCC->Modified(); fCC->Update(); fTimerActive = false; } /**************************************************************************/ int RGTopFrame::SpawnGuiAndRun(int argc, char **argv) { LookType_e revemode = LT_Editor; if(argc >= 3 && (strcmp(argv[1], "-revemode")==0 || strcmp(argv[1], "-mode")==0)) { LookType_e m = LookType_e(atoi(argv[2])); if(m >= LT_Classic && m <= LT_GLViewer) revemode = m; printf("revemode = %d\n", revemode); } TRint theApp("App", &argc, argv); Int_t w = 800; Int_t h = 600; gReve = new RGTopFrame(gClient->GetRoot(), w, h, revemode); run_loop: try { theApp.Run(); } catch(std::string exc) { gReve->GetStatusBar()->SetText(exc.c_str()); fprintf(stderr, "Exception: %s\n", exc.c_str()); goto run_loop; } return 0; } /**************************************************************************/ /**************************************************************************/ TGListTreeItem* RGTopFrame::AddEvent(TObject* event) { fCurrentEvent = event; RenderElementObjPtr* rnrEv = new RenderElementObjPtr(event); fCurrentEventLTI = rnrEv->AddIntoListTree(GetListTree(), 0); GetListTree()->OpenItem(fCurrentEventLTI); return fCurrentEventLTI; } TGListTreeItem* RGTopFrame::AddRenderElement(RenderElement* rnr_element) { return AddRenderElement(GetEventTreeItem(), rnr_element); } TGListTreeItem* RGTopFrame::AddRenderElement(TGListTreeItem* parent, RenderElement* rnr_element) { static const Exc_t eH("RGTopFrame::AddRenderElement "); // Here could route rnr-element to several browsers/pads. TGListTreeItem* newitem = rnr_element->AddIntoListTree(GetListTree(), parent); NotifyBrowser(); return newitem; } TGListTreeItem* RGTopFrame::AddGlobalRenderElement(RenderElement* rnr_element) { return AddGlobalRenderElement(GetGlobalTreeItem(), rnr_element); } TGListTreeItem* RGTopFrame::AddGlobalRenderElement(TGListTreeItem* parent, RenderElement* rnr_element) { static const Exc_t eH("RGTopFrame::AddGlobalRenderElement "); // Here could route rnr-element to several browsers/pads. TGListTreeItem* newitem = rnr_element->AddIntoListTree(GetListTree(), parent); NotifyBrowser(); return newitem; } /**************************************************************************/ void RGTopFrame::DrawRenderElement(RenderElement* rnr_element, TVirtualPad* pad) { if(pad == 0) pad = GetCC(); { Reve::PadHolder pHolder(false, pad); rnr_element->GetObject()->Draw(); } Redraw3D(); } void RGTopFrame::UndrawRenderElement(RenderElement* rnr_element, TVirtualPad* pad) { if(pad == 0) pad = GetCC(); { Reve::PadHolder pHolder(false, pad); pad->GetListOfPrimitives()->Remove(rnr_element->GetObject()); } Redraw3D(); } /**************************************************************************/ void RGTopFrame::RenderElementChecked(TObject* obj, Bool_t state) { // Item's user-data is blindly casted into TObject. // We recast it blindly back into the render element. RenderElement* rnrEl = (RenderElement*) obj; rnrEl->SetRnrElement(state); } /**************************************************************************/ void RGTopFrame::NotifyBrowser(TGListTreeItem* parent) { TGListTree* l_tree = GetListTree(); if(parent) l_tree->OpenItem(parent); gClient->NeedRedraw(l_tree); } /**************************************************************************/ // GeoManager registration /**************************************************************************/ TGeoManager* RGTopFrame::GetGeometry(const TString& filename) { static const Exc_t eH("RGTopFrame::GetGeometry "); TString exp_filename = filename; gSystem->ExpandPathName(exp_filename); printf("%s loading: '%s' -> '%s'.\n", eH.Data(), filename.Data(), exp_filename.Data()); std::map<TString, TGeoManager*>::iterator g = fGeometries.find(filename); if(g != fGeometries.end()) { return g->second; } else { if(gSystem->AccessPathName(exp_filename, kReadPermission)) throw(eH + "file '" + exp_filename + "' not readable."); gGeoManager = 0; TGeoManager::Import(filename); if(gGeoManager == 0) throw(eH + "GeoManager import failed."); gGeoManager->GetTopVolume()->VisibleDaughters(1); // Import colors exported by Gled, if they exist. { TFile f(exp_filename, "READ"); TObjArray* collist = (TObjArray*) f.Get("ColorList"); f.Close(); if(collist != 0) { TSeqCollection* glist = gROOT->GetListOfColors(); glist->Clear(); glist->AddAll(collist); } } fGeometries[filename] = gGeoManager; return gGeoManager; } }
#include "AliAnalysisTaskNucleiYield.h" // ROOT includes #include <TAxis.h> #include <TChain.h> #include <TH1F.h> #include <TH2F.h> #include <TH3F.h> #include <TList.h> #include <TMath.h> #include <TParticle.h> #include <TClonesArray.h> #include <TTree.h> #include <TRandom3.h> // ALIROOT includes #include "AliAnalysisManager.h" #include "AliCentrality.h" #include "AliPID.h" #include "AliTPCPIDResponse.h" #include "AliTOFPIDResponse.h" #include "AliVTrack.h" #include "AliVVertex.h" #include "AliVEvent.h" #include "AliPIDResponse.h" #include "AliVParticle.h" #include "AliMCEvent.h" #include "AliInputEventHandler.h" #include "AliVEventHandler.h" #include "AliStack.h" #include "AliAODTrack.h" #include "AliAODMCParticle.h" #include "AliAODVertex.h" #define LIGHT_SPEED 2.99792457999999984e-02 #define EPS 1.e-15 using TMath::TwoPi; /// \cond CLASSIMP ClassImp(AliAnalysisTaskNucleiYield); /// \endcond CLASSIMP /// Standard and default constructor of the class. /// /// \param taskname Name of the task /// \param partname Name of the analysed particle /// AliAnalysisTaskNucleiYield::AliAnalysisTaskNucleiYield(TString taskname) :AliAnalysisTaskSE(taskname.Data()) // ,fList(0x0) ,fPDG(0x0) ,fPDGMass(0) ,fPDGMassOverZ(0) ,fIsMC(kFALSE) ,fPID(0x0) ,fMagField(0.f) ,fPrimaryVertex(0x0) ,fMmc() ,fAmc() ,fDCAzLimit(10.) ,fDCAzNbins(400) ,fPtCorrectionA(3) ,fPtCorrectionM(3) ,fTOFlowBoundary(-2.4) ,fTOFhighBoundary(3.6) ,fTOFnBins(75) ,fRequireITSrefit(kTRUE) ,fRequireTPCrefit(kTRUE) ,fRequireNoKinks(kTRUE) ,fRequireITSrecPoints(2u) ,fRequireITSsignal(0u) ,fRequireSPDrecPoints(1u) ,fRequireTPCrecPoints(70u) ,fRequireTPCsignal(70u) ,fRequireEtaMin(-0.8f) ,fRequireEtaMax(0.8f) ,fRequireYmin(-0.5f) ,fRequireYmax(0.5f) ,fRequireMaxChi2(4.f) ,fRequireMaxDCAxy(0.5f) ,fRequireMaxDCAz(1.f) ,fRequireTPCpidSigmas(3.f) ,fRequireITSpidSigmas(-1.f) ,fParticle(AliPID::kUnknown) ,fCentBins(0x0) ,fDCABins(0x0) ,fPtBins(0x0) ,fCustomTPCpid(0) ,fCentrality(0x0) ,fFlattenedCentrality(0x0) ,fCentralityClasses(0x0) ,fProduction(0x0) ,fAITS_TPC(0x0) ,fAITS_TPC_TOF(0x0) ,fATotal(0x0) ,fAPtCorrection(0x0) ,fMITS_TPC(0x0) ,fMITS_TPC_TOF(0x0) ,fMTotal(0x0) ,fMPtCorrection(0x0) ,fMDCAPrimary(0x0) ,fMDCASecondary(0x0) ,fATOFsignal(0x0) ,fATPCcounts(0x0) ,fMDCAxy(0x0) ,fMDCAz(0x0) ,fMTOFsignal(0x0) ,fMTPCcounts(0x0) { Float_t aCorrection[3] = {-2.10154e-03,-4.53472e-01,-3.01246e+00}; Float_t mCorrection[3] = {-2.00277e-03,-4.93461e-01,-3.05463e+00}; fPtCorrectionA.Set(3, aCorrection); fPtCorrectionM.Set(3,mCorrection); DefineInput(0, TChain::Class()); DefineOutput(1, TList::Class()); } /// Standard destructor /// AliAnalysisTaskNucleiYield::~AliAnalysisTaskNucleiYield(){ // Destructor if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) return; if (fList) delete fList; } /// This function creates all the histograms and all the objects in general used during the analysis /// \return void /// void AliAnalysisTaskNucleiYield::UserCreateOutputObjects(){ fList = new TList(); fList->SetOwner(kTRUE); const Int_t nPtBins = fPtBins.GetSize() - 1; const Int_t nCentBins = fCentBins.GetSize() - 1; const Int_t nDCAbins = fDCABins.GetSize() - 1; const Float_t *pTbins = fPtBins.GetArray(); const Float_t *centBins = fCentBins.GetArray(); const Float_t *dcaBins = fDCABins.GetArray(); fCentrality = new TH1F("fCentrality",";Centrality (%);Events / 1%;",100,0.,100.); fCentralityClasses = new TH1F("fCentralityClasses",";Centrality classes(%);Events / Class;",nCentBins,centBins); fFlattenedCentrality = new TH1F("fFlattenCentrality","Centrality distribution after the flattening;Centrality (%);Events / 1%;",100,0.,100.); fList->Add(fCentrality); fList->Add(fCentralityClasses); fList->Add(fFlattenedCentrality); if (fIsMC) { fMTotal = new TH2F("fMTotal",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fATotal = new TH2F("fATotal",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fMITS_TPC = new TH2F("fMITS_TPC",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fAITS_TPC = new TH2F("fAITS_TPC",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fMITS_TPC_TOF = new TH2F("fMITS_TPC_TOF",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fAITS_TPC_TOF = new TH2F("fAITS_TPC_TOF",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fMDCAPrimary = new TH3F("fMDCAPrimary",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)", nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins); fMDCASecondary = new TH3F("fMDCASecondary",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)", nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins); fAPtCorrection = new TH2F("fAPtCorrection", ";p_{T}^{rec} (GeV/c);p_{T}^{MC}-p_{T}^{rec} (GeV/c);Entries", 160,0.4,6.,80,-1.,1.); fMPtCorrection = new TH2F("fMPtCorrection", ";p_{T}^{rec} (GeV/c);p_{T}^{MC}-p_{T}^{rec} (GeV/c);Entries", 160,0.4,6.,80,-1.,1.); fProduction = new TH1F("fProduction",";p (GeV/c);Entries",100,-10,10); fList->Add(fProduction); fList->Add(fMTotal); fList->Add(fATotal); fList->Add(fMITS_TPC); fList->Add(fAITS_TPC); fList->Add(fMITS_TPC_TOF); fList->Add(fAITS_TPC_TOF); fList->Add(fMDCAPrimary); fList->Add(fMDCASecondary); fList->Add(fAPtCorrection); fList->Add(fMPtCorrection); } else { float tofBins[fTOFnBins + 1]; const float deltaTOF = (fTOFhighBoundary - fTOFlowBoundary) / fTOFnBins; for (int i = 0; i <= fTOFnBins; ++i) tofBins[i] = i * deltaTOF + fTOFlowBoundary; float dcazBins[fDCAzNbins + 1]; const float deltaDCAz = 2.f * fDCAzLimit / fDCAzNbins; for (int i = 0; i <= fDCAzNbins; ++i) dcazBins[i] = i * deltaDCAz - fDCAzLimit; const int nTpcBins = 40; float tpcBins[nTpcBins + 1]; for (int i = 0; i <= nTpcBins; ++i) { tpcBins[i] = -4.f + i * 0.2f; } fATOFsignal = new TH3F("fATOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,fTOFnBins,tofBins); fATPCcounts = new TH3F("fATPCcounts",";Centrality (%);p_{T} (GeV/c); ITS ##sigma", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); fMDCAxy = new TH3F("fMDCAxy",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)", nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins); fMDCAz = new TH3F("fMDCAz",";Centrality (%);p_{T} (GeV/c); DCA_{z} (cm)", nCentBins,centBins,nPtBins,pTbins,fDCAzNbins,dcazBins); fMTOFsignal = new TH3F("fMTOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,fTOFnBins,tofBins); fMTPCcounts = new TH3F("fMTPCcounts",";Centrality (%);p_{T} (GeV/c); ITS ##sigma", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); fList->Add(fATOFsignal); fList->Add(fATPCcounts); fList->Add(fMDCAxy); fList->Add(fMDCAz); fList->Add(fMTOFsignal); fList->Add(fMTPCcounts); } PostData(1,fList); } /// This is the function that is evaluated for each event. The analysis code stays here. /// /// \param options Deprecated parameter /// \return void /// void AliAnalysisTaskNucleiYield::UserExec(Option_t *){ AliVEvent *ev = dynamic_cast<AliVEvent*> (InputEvent()); // Check event selection mask AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler* handl = (AliInputEventHandler*)mgr->GetInputEventHandler(); UInt_t mask = handl->IsEventSelected(); if (!(mask & 0xffffffff)) { PostData(1, fList); return; } if (!((mask & AliVEvent::kMB) || (mask & AliVEvent::kCentral) || (mask & AliVEvent::kSemiCentral))) { PostData(1, fList); return; } fPID = handl->GetPIDResponse(); AliCentrality *centr = ev->GetCentrality(); // Centrality selection in PbPb, percentile determined with V0 float centrality = centr->GetCentralityPercentile("V0M"); //select only events with centralities between 0 and 80 % if (centrality < 0. || centrality > 80.) { PostData(1, fList); return; } // Primary vertex displacement cut fPrimaryVertex = (AliVVertex*)ev->GetPrimaryVertex(); if(TMath::Abs(fPrimaryVertex->GetZ()) > 10.) { PostData(1, fList); return; } fMagField = ev->GetMagneticField(); fCentrality->Fill(centrality); if (Flatten(centrality) && !fIsMC) { PostData(1, fList); return; } fCentralityClasses->Fill(centrality); fFlattenedCentrality->Fill(centrality); if (fParticle == AliPID::kUnknown) { ::Error("AliAnalysisTaskNucleiYield::UserExec", "No particle type set"); PostData(1, fList); return; } TClonesArray *stack = 0x0; if (fIsMC) { // get branch "mcparticles" stack = (TClonesArray*)ev->GetList()->FindObject(AliAODMCParticle::StdBranchName()); if (!stack) { PostData(1, fList); return; } // Making the list of deuterons in acceptance fMmc.SetOwner(kFALSE); fAmc.SetOwner(kFALSE); for (int iMC = 0; iMC < stack->GetEntriesFast(); ++iMC) { AliAODMCParticle *part = (AliAODMCParticle*)stack->UncheckedAt(iMC); const int pdg = part->GetPdgCode(); if (pdg == fPDG) fProduction->Fill(part->P()); else if (pdg == -fPDG) fProduction->Fill(-part->P()); if (part->Eta() > fRequireEtaMax || part->Eta() < fRequireEtaMin) continue; if (part->Y() > fRequireYmax || part->Y() < fRequireYmin) continue; if (pdg == fPDG) { if (part->IsPhysicalPrimary()) fMTotal->Fill(centrality,part->Pt()); fMmc.Add(part); } else if (pdg == -fPDG) { if (part->IsPhysicalPrimary()) fATotal->Fill(centrality,part->Pt()); fAmc.Add(part); } } } // Checking how many deuterons in acceptance are reconstructed well for (Int_t iT = 0; iT < (Int_t)ev->GetNumberOfTracks(); ++iT) { AliAODTrack *track = dynamic_cast<AliAODTrack*>(ev->GetTrack(iT)); if (track->GetID() <= 0) continue; Double_t dca[2]; if (!AcceptTrack(track,dca)) continue; const float beta = HasTOF(track); float pT = track->Pt(); PtCorrection(pT,track->Charge() > 0); if (fIsMC) { AliAODMCParticle *part = (AliAODMCParticle*)stack->At(TMath::Abs(track->GetLabel())); if (!part) continue; if (part->GetPdgCode() > 0) { if (!fMmc.Contains(part)) continue; if (part->IsPhysicalPrimary()) fMITS_TPC->Fill(centrality,pT); else fMDCASecondary->Fill(centrality,pT,dca[0]); fMPtCorrection->Fill(pT,part->Pt() - pT); if (beta > 0) { if (part->IsPhysicalPrimary()) { fMDCAPrimary->Fill(centrality,pT,dca[0]); fMITS_TPC_TOF->Fill(centrality,part->Pt()); } } } else { if (!fAmc.Contains(part)) continue; fAPtCorrection->Fill(pT,part->Pt() - pT); if (part->IsPhysicalPrimary()) { fAITS_TPC->Fill(centrality,part->Pt()); if (beta > 0) fAITS_TPC_TOF->Fill(centrality,part->Pt()); } } } else { if (!PassesPIDSelection(track)) continue; AliITSPIDResponse &itsPidResp = fPID->GetITSResponse(); if (track->Charge() > 0) fMTPCcounts->Fill(centrality, pT, itsPidResp.GetNumberOfSigmas(track, fParticle)); else fATPCcounts->Fill(centrality, pT, itsPidResp.GetNumberOfSigmas(track, fParticle)); if (beta < 0) continue; /// \f$ m = \frac{p}{\beta\gamma} \f$ const float m = track->GetTPCmomentum() * (TMath::Sqrt(1.f - beta * beta) / beta); if (track->Charge() > 0) { fMDCAxy->Fill(centrality, pT, dca[0]); fMDCAz->Fill(centrality, pT, dca[1]); fMTOFsignal->Fill(centrality, pT, m * m - fPDGMassOverZ * fPDGMassOverZ); } else { fATOFsignal->Fill(centrality, pT, m * m - fPDGMassOverZ * fPDGMassOverZ); } } } // End AOD track loop fAmc.Clear(); fMmc.Clear(); // Post output data. PostData(1,fList); } /// Merge the output. Called once at the end of the query. /// /// \return void /// void AliAnalysisTaskNucleiYield::Terminate(Option_t *) { return; } /// This function checks whether a track passes the cuts required in this task /// /// \param track Track that is going to be checked /// \param dca[2] Projections on the transverse plane and on z of the distance of closest approach /// of the track to the primary vertex /// \return Boolean value: true means that the track has passed all the cuts. /// Bool_t AliAnalysisTaskNucleiYield::AcceptTrack(AliAODTrack *track, Double_t dca[2]) { ULong_t status = track->GetStatus(); if (!(status & AliVTrack::kITSrefit) && fRequireITSrefit) return kFALSE; if (!(status & AliVTrack::kTPCrefit) && fRequireTPCrefit) return kFALSE; AliAODVertex *vtx1 = (AliAODVertex*)track->GetProdVertex(); if(Int_t(vtx1->GetType()) == AliAODVertex::kKink && fRequireNoKinks) return kFALSE; unsigned int nSPD = 0, nITS = 0; for (int i = 0; i < 6; ++i) { if (track->HasPointOnITSLayer(i)) { if(i < 2) nSPD++; nITS++; } } if (nITS < fRequireITSrecPoints) return kFALSE; if (nSPD < fRequireSPDrecPoints) return kFALSE; if (track->Chi2perNDF() > fRequireMaxChi2) return kFALSE; Double_t cov[3]; if (!track->PropagateToDCA(fPrimaryVertex, fMagField, 100, dca, cov)) return kFALSE; if (dca[0] > fRequireMaxDCAxy) return kFALSE; if (dca[1] > fRequireMaxDCAz) return kFALSE; return kTRUE; } /// This function checks whether a track has or has not a prolongation in TOF. /// /// \param track Track that has to be checked /// \return \f$\beta\f$ of the particle, -1 means that there is no correct prolongation in TOF. /// Float_t AliAnalysisTaskNucleiYield::HasTOF(AliAODTrack *track) { Bool_t hasTOFout = track->GetStatus() & AliVTrack::kTOFout; Bool_t hasTOFtime = track->GetStatus() & AliVTrack::kTIME; Float_t length = track->GetIntegratedLength(); Bool_t hasTOF = Bool_t(hasTOFout & hasTOFtime) && length > 350.f; if (!hasTOF) return -1.; const float len = track->GetIntegratedLength(); const float p = track->GetTPCmomentum(); const float tim = track->GetTOFsignal() - fPID->GetTOFResponse().GetStartTime(p); if (tim < len / LIGHT_SPEED) return -1.; else { const float beta = len / (tim * LIGHT_SPEED); if (beta < EPS || beta > (1. - EPS)) return -1.f; else return beta; } } /// This functions sets the centrality bins used in the analysis /// /// \param nbins Number of centrality bins /// \param bins Array with nbins + 1 elements contanining the edges of the bins /// \return void /// void AliAnalysisTaskNucleiYield::SetCentBins(Int_t nbins, Float_t *bins) { fCentBins.Set(nbins + 1, bins); } /// This functions sets the \f$\mathrm{DCA}_{xy}\f$ bins used in the analysis /// /// \param nbins Number of \f$\mathrm{DCA}_{xy}\f$ bins /// \param bins Array with nbins + 1 elements contanining the edges of the bins /// \return void /// void AliAnalysisTaskNucleiYield::SetDCABins(Int_t nbins, Float_t min, Float_t max) { const float delta = (max - min) / nbins; fDCABins.Set(nbins + 1); for (int iB = 0; iB < nbins; ++iB) { fDCABins[iB] = min + iB * delta; } fDCABins[nbins] = max; } /// This functions sets the \f$p_{\mathrm{T}}\f$ bins used in the analysis /// /// \param nbins Number of \f$p_{\mathrm{T}}\f$ bins /// \param bins Array with nbins + 1 elements contanining the edges of the bins /// \return void /// void AliAnalysisTaskNucleiYield::SetPtBins(Int_t nbins, Float_t *bins) { fPtBins.Set(nbins + 1, bins); } /// This function allows to set a custom parametrisation for the TPC response function /// /// \param par Array of 5 values corresponding to the Bethe Bloch parametrisation /// \param sigma Sigma of the parametrisation /// \return void /// void AliAnalysisTaskNucleiYield::SetCustomTPCpid(Float_t *par, Float_t sigma) { if (par == 0x0 && sigma <= 0) { fCustomTPCpid.Set(1); } else { fCustomTPCpid.Set(6); for (int i = 0; i < 5; ++i) fCustomTPCpid.AddAt(par[i],i); fCustomTPCpid.AddAt(sigma, 5); } } /// This function checks if the track passes the PID selection /// /// \param t Track to be tested /// \param sigmas Number of sigmas /// \return Boolean value: true means that the track passes the PID selection /// Bool_t AliAnalysisTaskNucleiYield::PassesPIDSelection(AliAODTrack *t) { if (fCustomTPCpid.GetSize() < 6 || fIsMC) { bool itsPID = kTRUE; AliITSPIDResponse &itsPidResp = fPID->GetITSResponse(); AliTPCPIDResponse &tpcPidResp = fPID->GetTPCResponse(); if (fRequireITSpidSigmas > 0) { itsPID = TMath::Abs(itsPidResp.GetNumberOfSigmas(t, fParticle)) < fRequireITSpidSigmas; } return itsPID && TMath::Abs(tpcPidResp.GetNumberOfSigmas(t, fParticle)) < fRequireTPCpidSigmas; } else { const float p = t->GetTPCmomentum() / fPDGMassOverZ; const float r = AliExternalTrackParam::BetheBlochAleph(p, fCustomTPCpid[0], fCustomTPCpid[1], fCustomTPCpid[2], fCustomTPCpid[3], fCustomTPCpid[4]); return TMath::Abs(t->GetTPCsignal() - r) < fRequireTPCpidSigmas * fCustomTPCpid[5] * r; } } /// This function sets the number of TOF bins and the boundaries of the histograms /// /// \param nbins Number of bins /// \param min Lower boundary of the histogram /// \param max Higher boundary of the histogram /// \return void /// void AliAnalysisTaskNucleiYield::SetTOFBins(Int_t nbins, Float_t min, Float_t max) { fTOFnBins = nbins; fTOFlowBoundary = min; fTOFhighBoundary = max; } /// This function sets the number of DCA\f$_{z}\f$ bins and the boundaries of the histogram /// /// \param nbins Number of bins /// \param limit Boundaries of the histogram (symmetrical with respect to zero) /// \return void /// void AliAnalysisTaskNucleiYield::SetDCAzBins(Int_t nbins, Float_t limit) { fDCAzNbins = nbins; fDCAzLimit = limit; } /// This function sets the particle type to be analysed /// /// \param part Particle type /// \return void /// void AliAnalysisTaskNucleiYield::SetParticleType(AliPID::EParticleType part) { fParticle = part; fPDGMass = AliPID::ParticleMass(part); fPDGMassOverZ = AliPID::ParticleMassZ(part); } //TODO: avoid hardcoded flattening /// This function provides the flattening of the centrality distribution /// /// \param cent Event centrality /// \return Boolean value: true means that the event must be skipped /// Bool_t AliAnalysisTaskNucleiYield::Flatten(float cent) { float prob[13] = { 0.855566,0.846964,0.829618,0.829259,0.830984, 0.85094,0.844346,0.851818,0.874758,1, 0.374767,0.650491,0.946963 }; if (cent >= 13.f) return kFALSE; else return gRandom->Rndm() > prob[int(cent)]; } /// This function provides the correction for wrongly calculated \f$p_{\mathrm{T}}\f$. /// /// \param pt \f$p_{\mathrm{T}}\f$ of the track /// \param positiveCharge True if the track has positive sign. /// \return void /// void AliAnalysisTaskNucleiYield::PtCorrection(float &pt, bool positiveCharge) { Float_t *par = (positiveCharge) ? fPtCorrectionM.GetArray() : fPtCorrectionA.GetArray(); const Float_t correction = par[0] + par[1] * TMath::Exp(par[2] * pt); pt -= correction; } Fixed track cuts #include "AliAnalysisTaskNucleiYield.h" // ROOT includes #include <TAxis.h> #include <TChain.h> #include <TH1F.h> #include <TH2F.h> #include <TH3F.h> #include <TList.h> #include <TMath.h> #include <TParticle.h> #include <TClonesArray.h> #include <TTree.h> #include <TRandom3.h> // ALIROOT includes #include "AliAnalysisManager.h" #include "AliCentrality.h" #include "AliPID.h" #include "AliTPCPIDResponse.h" #include "AliTOFPIDResponse.h" #include "AliVTrack.h" #include "AliVVertex.h" #include "AliVEvent.h" #include "AliPIDResponse.h" #include "AliVParticle.h" #include "AliMCEvent.h" #include "AliInputEventHandler.h" #include "AliVEventHandler.h" #include "AliStack.h" #include "AliAODTrack.h" #include "AliAODMCParticle.h" #include "AliAODVertex.h" #define LIGHT_SPEED 2.99792457999999984e-02 #define EPS 1.e-15 using TMath::TwoPi; /// \cond CLASSIMP ClassImp(AliAnalysisTaskNucleiYield); /// \endcond CLASSIMP /// Standard and default constructor of the class. /// /// \param taskname Name of the task /// \param partname Name of the analysed particle /// AliAnalysisTaskNucleiYield::AliAnalysisTaskNucleiYield(TString taskname) :AliAnalysisTaskSE(taskname.Data()) // ,fList(0x0) ,fPDG(0x0) ,fPDGMass(0) ,fPDGMassOverZ(0) ,fIsMC(kFALSE) ,fPID(0x0) ,fMagField(0.f) ,fPrimaryVertex(0x0) ,fMmc() ,fAmc() ,fDCAzLimit(10.) ,fDCAzNbins(400) ,fPtCorrectionA(3) ,fPtCorrectionM(3) ,fTOFlowBoundary(-2.4) ,fTOFhighBoundary(3.6) ,fTOFnBins(75) ,fRequireITSrefit(kTRUE) ,fRequireTPCrefit(kTRUE) ,fRequireNoKinks(kTRUE) ,fRequireITSrecPoints(2u) ,fRequireITSsignal(0u) ,fRequireSPDrecPoints(1u) ,fRequireTPCrecPoints(70u) ,fRequireTPCsignal(70u) ,fRequireEtaMin(-0.8f) ,fRequireEtaMax(0.8f) ,fRequireYmin(-0.5f) ,fRequireYmax(0.5f) ,fRequireMaxChi2(4.f) ,fRequireMaxDCAxy(0.5f) ,fRequireMaxDCAz(1.f) ,fRequireTPCpidSigmas(3.f) ,fRequireITSpidSigmas(-1.f) ,fParticle(AliPID::kUnknown) ,fCentBins(0x0) ,fDCABins(0x0) ,fPtBins(0x0) ,fCustomTPCpid(0) ,fCentrality(0x0) ,fFlattenedCentrality(0x0) ,fCentralityClasses(0x0) ,fProduction(0x0) ,fAITS_TPC(0x0) ,fAITS_TPC_TOF(0x0) ,fATotal(0x0) ,fAPtCorrection(0x0) ,fMITS_TPC(0x0) ,fMITS_TPC_TOF(0x0) ,fMTotal(0x0) ,fMPtCorrection(0x0) ,fMDCAPrimary(0x0) ,fMDCASecondary(0x0) ,fATOFsignal(0x0) ,fATPCcounts(0x0) ,fMDCAxy(0x0) ,fMDCAz(0x0) ,fMTOFsignal(0x0) ,fMTPCcounts(0x0) { Float_t aCorrection[3] = {-2.10154e-03,-4.53472e-01,-3.01246e+00}; Float_t mCorrection[3] = {-2.00277e-03,-4.93461e-01,-3.05463e+00}; fPtCorrectionA.Set(3, aCorrection); fPtCorrectionM.Set(3,mCorrection); DefineInput(0, TChain::Class()); DefineOutput(1, TList::Class()); } /// Standard destructor /// AliAnalysisTaskNucleiYield::~AliAnalysisTaskNucleiYield(){ // Destructor if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) return; if (fList) delete fList; } /// This function creates all the histograms and all the objects in general used during the analysis /// \return void /// void AliAnalysisTaskNucleiYield::UserCreateOutputObjects(){ fList = new TList(); fList->SetOwner(kTRUE); const Int_t nPtBins = fPtBins.GetSize() - 1; const Int_t nCentBins = fCentBins.GetSize() - 1; const Int_t nDCAbins = fDCABins.GetSize() - 1; const Float_t *pTbins = fPtBins.GetArray(); const Float_t *centBins = fCentBins.GetArray(); const Float_t *dcaBins = fDCABins.GetArray(); fCentrality = new TH1F("fCentrality",";Centrality (%);Events / 1%;",100,0.,100.); fCentralityClasses = new TH1F("fCentralityClasses",";Centrality classes(%);Events / Class;",nCentBins,centBins); fFlattenedCentrality = new TH1F("fFlattenCentrality","Centrality distribution after the flattening;Centrality (%);Events / 1%;",100,0.,100.); fList->Add(fCentrality); fList->Add(fCentralityClasses); fList->Add(fFlattenedCentrality); if (fIsMC) { fMTotal = new TH2F("fMTotal",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fATotal = new TH2F("fATotal",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fMITS_TPC = new TH2F("fMITS_TPC",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fAITS_TPC = new TH2F("fAITS_TPC",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fMITS_TPC_TOF = new TH2F("fMITS_TPC_TOF",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fAITS_TPC_TOF = new TH2F("fAITS_TPC_TOF",";Centrality (%);p_{T} (GeV/c); Counts", nCentBins,centBins,nPtBins,pTbins); fMDCAPrimary = new TH3F("fMDCAPrimary",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)", nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins); fMDCASecondary = new TH3F("fMDCASecondary",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)", nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins); fAPtCorrection = new TH2F("fAPtCorrection", ";p_{T}^{rec} (GeV/c);p_{T}^{MC}-p_{T}^{rec} (GeV/c);Entries", 160,0.4,6.,80,-1.,1.); fMPtCorrection = new TH2F("fMPtCorrection", ";p_{T}^{rec} (GeV/c);p_{T}^{MC}-p_{T}^{rec} (GeV/c);Entries", 160,0.4,6.,80,-1.,1.); fProduction = new TH1F("fProduction",";p (GeV/c);Entries",100,-10,10); fList->Add(fProduction); fList->Add(fMTotal); fList->Add(fATotal); fList->Add(fMITS_TPC); fList->Add(fAITS_TPC); fList->Add(fMITS_TPC_TOF); fList->Add(fAITS_TPC_TOF); fList->Add(fMDCAPrimary); fList->Add(fMDCASecondary); fList->Add(fAPtCorrection); fList->Add(fMPtCorrection); } else { float tofBins[fTOFnBins + 1]; const float deltaTOF = (fTOFhighBoundary - fTOFlowBoundary) / fTOFnBins; for (int i = 0; i <= fTOFnBins; ++i) tofBins[i] = i * deltaTOF + fTOFlowBoundary; float dcazBins[fDCAzNbins + 1]; const float deltaDCAz = 2.f * fDCAzLimit / fDCAzNbins; for (int i = 0; i <= fDCAzNbins; ++i) dcazBins[i] = i * deltaDCAz - fDCAzLimit; const int nTpcBins = 40; float tpcBins[nTpcBins + 1]; for (int i = 0; i <= nTpcBins; ++i) { tpcBins[i] = -4.f + i * 0.2f; } fATOFsignal = new TH3F("fATOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,fTOFnBins,tofBins); fATPCcounts = new TH3F("fATPCcounts",";Centrality (%);p_{T} (GeV/c); ITS ##sigma", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); fMDCAxy = new TH3F("fMDCAxy",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)", nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins); fMDCAz = new TH3F("fMDCAz",";Centrality (%);p_{T} (GeV/c); DCA_{z} (cm)", nCentBins,centBins,nPtBins,pTbins,fDCAzNbins,dcazBins); fMTOFsignal = new TH3F("fMTOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,fTOFnBins,tofBins); fMTPCcounts = new TH3F("fMTPCcounts",";Centrality (%);p_{T} (GeV/c); ITS ##sigma", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); fList->Add(fATOFsignal); fList->Add(fATPCcounts); fList->Add(fMDCAxy); fList->Add(fMDCAz); fList->Add(fMTOFsignal); fList->Add(fMTPCcounts); } PostData(1,fList); } /// This is the function that is evaluated for each event. The analysis code stays here. /// /// \param options Deprecated parameter /// \return void /// void AliAnalysisTaskNucleiYield::UserExec(Option_t *){ AliVEvent *ev = dynamic_cast<AliVEvent*> (InputEvent()); // Check event selection mask AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler* handl = (AliInputEventHandler*)mgr->GetInputEventHandler(); UInt_t mask = handl->IsEventSelected(); if (!(mask & 0xffffffff)) { PostData(1, fList); return; } if (!((mask & AliVEvent::kMB) || (mask & AliVEvent::kCentral) || (mask & AliVEvent::kSemiCentral))) { PostData(1, fList); return; } fPID = handl->GetPIDResponse(); AliCentrality *centr = ev->GetCentrality(); // Centrality selection in PbPb, percentile determined with V0 float centrality = centr->GetCentralityPercentile("V0M"); //select only events with centralities between 0 and 80 % if (centrality < 0. || centrality > 80.) { PostData(1, fList); return; } // Primary vertex displacement cut fPrimaryVertex = (AliVVertex*)ev->GetPrimaryVertex(); if(TMath::Abs(fPrimaryVertex->GetZ()) > 10.) { PostData(1, fList); return; } fMagField = ev->GetMagneticField(); fCentrality->Fill(centrality); if (Flatten(centrality) && !fIsMC) { PostData(1, fList); return; } fCentralityClasses->Fill(centrality); fFlattenedCentrality->Fill(centrality); if (fParticle == AliPID::kUnknown) { ::Error("AliAnalysisTaskNucleiYield::UserExec", "No particle type set"); PostData(1, fList); return; } TClonesArray *stack = 0x0; if (fIsMC) { // get branch "mcparticles" stack = (TClonesArray*)ev->GetList()->FindObject(AliAODMCParticle::StdBranchName()); if (!stack) { PostData(1, fList); return; } // Making the list of deuterons in acceptance fMmc.SetOwner(kFALSE); fAmc.SetOwner(kFALSE); for (int iMC = 0; iMC < stack->GetEntriesFast(); ++iMC) { AliAODMCParticle *part = (AliAODMCParticle*)stack->UncheckedAt(iMC); const int pdg = part->GetPdgCode(); if (pdg == fPDG) fProduction->Fill(part->P()); else if (pdg == -fPDG) fProduction->Fill(-part->P()); if (part->Eta() > fRequireEtaMax || part->Eta() < fRequireEtaMin) continue; if (part->Y() > fRequireYmax || part->Y() < fRequireYmin) continue; if (pdg == fPDG) { if (part->IsPhysicalPrimary()) fMTotal->Fill(centrality,part->Pt()); fMmc.Add(part); } else if (pdg == -fPDG) { if (part->IsPhysicalPrimary()) fATotal->Fill(centrality,part->Pt()); fAmc.Add(part); } } } // Checking how many deuterons in acceptance are reconstructed well for (Int_t iT = 0; iT < (Int_t)ev->GetNumberOfTracks(); ++iT) { AliAODTrack *track = dynamic_cast<AliAODTrack*>(ev->GetTrack(iT)); if (track->GetID() <= 0) continue; Double_t dca[2]; if (!AcceptTrack(track,dca)) continue; const float beta = HasTOF(track); float pT = track->Pt(); PtCorrection(pT,track->Charge() > 0); if (fIsMC) { AliAODMCParticle *part = (AliAODMCParticle*)stack->At(TMath::Abs(track->GetLabel())); if (!part) continue; if (part->GetPdgCode() > 0) { if (!fMmc.Contains(part)) continue; if (part->IsPhysicalPrimary()) fMITS_TPC->Fill(centrality,pT); else fMDCASecondary->Fill(centrality,pT,dca[0]); fMPtCorrection->Fill(pT,part->Pt() - pT); if (beta > 0) { if (part->IsPhysicalPrimary()) { fMDCAPrimary->Fill(centrality,pT,dca[0]); fMITS_TPC_TOF->Fill(centrality,part->Pt()); } } } else { if (!fAmc.Contains(part)) continue; fAPtCorrection->Fill(pT,part->Pt() - pT); if (part->IsPhysicalPrimary()) { fAITS_TPC->Fill(centrality,part->Pt()); if (beta > 0) fAITS_TPC_TOF->Fill(centrality,part->Pt()); } } } else { if (!PassesPIDSelection(track)) continue; AliITSPIDResponse &itsPidResp = fPID->GetITSResponse(); if (track->Charge() > 0) fMTPCcounts->Fill(centrality, pT, itsPidResp.GetNumberOfSigmas(track, fParticle)); else fATPCcounts->Fill(centrality, pT, itsPidResp.GetNumberOfSigmas(track, fParticle)); if (beta < 0) continue; /// \f$ m = \frac{p}{\beta\gamma} \f$ const float m = track->GetTPCmomentum() * (TMath::Sqrt(1.f - beta * beta) / beta); if (track->Charge() > 0) { fMDCAxy->Fill(centrality, pT, dca[0]); fMDCAz->Fill(centrality, pT, dca[1]); fMTOFsignal->Fill(centrality, pT, m * m - fPDGMassOverZ * fPDGMassOverZ); } else { fATOFsignal->Fill(centrality, pT, m * m - fPDGMassOverZ * fPDGMassOverZ); } } } // End AOD track loop fAmc.Clear(); fMmc.Clear(); // Post output data. PostData(1,fList); } /// Merge the output. Called once at the end of the query. /// /// \return void /// void AliAnalysisTaskNucleiYield::Terminate(Option_t *) { return; } /// This function checks whether a track passes the cuts required in this task /// /// \param track Track that is going to be checked /// \param dca[2] Projections on the transverse plane and on z of the distance of closest approach /// of the track to the primary vertex /// \return Boolean value: true means that the track has passed all the cuts. /// Bool_t AliAnalysisTaskNucleiYield::AcceptTrack(AliAODTrack *track, Double_t dca[2]) { ULong_t status = track->GetStatus(); if (!(status & AliVTrack::kITSrefit) && fRequireITSrefit) return kFALSE; if (!(status & AliVTrack::kTPCrefit) && fRequireTPCrefit) return kFALSE; if (track->Eta() < fRequireEtaMin || track->Eta() > fRequireEtaMax) return kFALSE; if (track->Y(fPDGMass) < fRequireYmin || track->Y(fPDGMass) > fRequireYmax) return kFALSE; AliAODVertex *vtx1 = (AliAODVertex*)track->GetProdVertex(); if(Int_t(vtx1->GetType()) == AliAODVertex::kKink && fRequireNoKinks) return kFALSE; unsigned int nSPD = 0, nITS = 0; for (int i = 0; i < 6; ++i) { if (track->HasPointOnITSLayer(i)) { if(i < 2) nSPD++; nITS++; } } if (nITS < fRequireITSrecPoints) return kFALSE; if (nSPD < fRequireSPDrecPoints) return kFALSE; if (track->Chi2perNDF() > fRequireMaxChi2) return kFALSE; Double_t cov[3]; if (!track->PropagateToDCA(fPrimaryVertex, fMagField, 100, dca, cov)) return kFALSE; if (dca[0] > fRequireMaxDCAxy) return kFALSE; if (dca[1] > fRequireMaxDCAz) return kFALSE; return kTRUE; } /// This function checks whether a track has or has not a prolongation in TOF. /// /// \param track Track that has to be checked /// \return \f$\beta\f$ of the particle, -1 means that there is no correct prolongation in TOF. /// Float_t AliAnalysisTaskNucleiYield::HasTOF(AliAODTrack *track) { Bool_t hasTOFout = track->GetStatus() & AliVTrack::kTOFout; Bool_t hasTOFtime = track->GetStatus() & AliVTrack::kTIME; const float len = track->GetIntegratedLength(); Bool_t hasTOF = Bool_t(hasTOFout & hasTOFtime) && len > 350.f; if (!hasTOF) return -1.; const float p = track->GetTPCmomentum(); const float tim = track->GetTOFsignal() - fPID->GetTOFResponse().GetStartTime(p); if (tim < len / LIGHT_SPEED) return -1.; else { const float beta = len / (tim * LIGHT_SPEED); if (beta < EPS || beta > (1. - EPS)) return -1.f; else return beta; } } /// This functions sets the centrality bins used in the analysis /// /// \param nbins Number of centrality bins /// \param bins Array with nbins + 1 elements contanining the edges of the bins /// \return void /// void AliAnalysisTaskNucleiYield::SetCentBins(Int_t nbins, Float_t *bins) { fCentBins.Set(nbins + 1, bins); } /// This functions sets the \f$\mathrm{DCA}_{xy}\f$ bins used in the analysis /// /// \param nbins Number of \f$\mathrm{DCA}_{xy}\f$ bins /// \param bins Array with nbins + 1 elements contanining the edges of the bins /// \return void /// void AliAnalysisTaskNucleiYield::SetDCABins(Int_t nbins, Float_t min, Float_t max) { const float delta = (max - min) / nbins; fDCABins.Set(nbins + 1); for (int iB = 0; iB < nbins; ++iB) { fDCABins[iB] = min + iB * delta; } fDCABins[nbins] = max; } /// This functions sets the \f$p_{\mathrm{T}}\f$ bins used in the analysis /// /// \param nbins Number of \f$p_{\mathrm{T}}\f$ bins /// \param bins Array with nbins + 1 elements contanining the edges of the bins /// \return void /// void AliAnalysisTaskNucleiYield::SetPtBins(Int_t nbins, Float_t *bins) { fPtBins.Set(nbins + 1, bins); } /// This function allows to set a custom parametrisation for the TPC response function /// /// \param par Array of 5 values corresponding to the Bethe Bloch parametrisation /// \param sigma Sigma of the parametrisation /// \return void /// void AliAnalysisTaskNucleiYield::SetCustomTPCpid(Float_t *par, Float_t sigma) { if (par == 0x0 && sigma <= 0) { fCustomTPCpid.Set(1); } else { fCustomTPCpid.Set(6); for (int i = 0; i < 5; ++i) fCustomTPCpid.AddAt(par[i],i); fCustomTPCpid.AddAt(sigma, 5); } } /// This function checks if the track passes the PID selection /// /// \param t Track to be tested /// \param sigmas Number of sigmas /// \return Boolean value: true means that the track passes the PID selection /// Bool_t AliAnalysisTaskNucleiYield::PassesPIDSelection(AliAODTrack *t) { if (fCustomTPCpid.GetSize() < 6 || fIsMC) { bool itsPID = kTRUE; AliITSPIDResponse &itsPidResp = fPID->GetITSResponse(); AliTPCPIDResponse &tpcPidResp = fPID->GetTPCResponse(); if (fRequireITSpidSigmas > 0) { itsPID = TMath::Abs(itsPidResp.GetNumberOfSigmas(t, fParticle)) < fRequireITSpidSigmas; } return itsPID && TMath::Abs(tpcPidResp.GetNumberOfSigmas(t, fParticle)) < fRequireTPCpidSigmas; } else { const float p = t->GetTPCmomentum() / fPDGMassOverZ; const float r = AliExternalTrackParam::BetheBlochAleph(p, fCustomTPCpid[0], fCustomTPCpid[1], fCustomTPCpid[2], fCustomTPCpid[3], fCustomTPCpid[4]); return TMath::Abs(t->GetTPCsignal() - r) < fRequireTPCpidSigmas * fCustomTPCpid[5] * r; } } /// This function sets the number of TOF bins and the boundaries of the histograms /// /// \param nbins Number of bins /// \param min Lower boundary of the histogram /// \param max Higher boundary of the histogram /// \return void /// void AliAnalysisTaskNucleiYield::SetTOFBins(Int_t nbins, Float_t min, Float_t max) { fTOFnBins = nbins; fTOFlowBoundary = min; fTOFhighBoundary = max; } /// This function sets the number of DCA\f$_{z}\f$ bins and the boundaries of the histogram /// /// \param nbins Number of bins /// \param limit Boundaries of the histogram (symmetrical with respect to zero) /// \return void /// void AliAnalysisTaskNucleiYield::SetDCAzBins(Int_t nbins, Float_t limit) { fDCAzNbins = nbins; fDCAzLimit = limit; } /// This function sets the particle type to be analysed /// /// \param part Particle type /// \return void /// void AliAnalysisTaskNucleiYield::SetParticleType(AliPID::EParticleType part) { fParticle = part; fPDGMass = AliPID::ParticleMass(part); fPDGMassOverZ = AliPID::ParticleMassZ(part); } //TODO: avoid hardcoded flattening /// This function provides the flattening of the centrality distribution /// /// \param cent Event centrality /// \return Boolean value: true means that the event must be skipped /// Bool_t AliAnalysisTaskNucleiYield::Flatten(float cent) { float prob[13] = { 0.855566,0.846964,0.829618,0.829259,0.830984, 0.85094,0.844346,0.851818,0.874758,1, 0.374767,0.650491,0.946963 }; if (cent >= 13.f) return kFALSE; else return gRandom->Rndm() > prob[int(cent)]; } /// This function provides the correction for wrongly calculated \f$p_{\mathrm{T}}\f$. /// /// \param pt \f$p_{\mathrm{T}}\f$ of the track /// \param positiveCharge True if the track has positive sign. /// \return void /// void AliAnalysisTaskNucleiYield::PtCorrection(float &pt, bool positiveCharge) { Float_t *par = (positiveCharge) ? fPtCorrectionM.GetArray() : fPtCorrectionA.GetArray(); const Float_t correction = par[0] + par[1] * TMath::Exp(par[2] * pt); pt -= correction; }
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /* COPYING CONDITIONS NOTICE: This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation, and provided that the following conditions are met: * Redistributions of source code must retain this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below). * Redistributions in binary form must reproduce this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below) in the documentation and/or other materials provided with the distribution. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. COPYRIGHT NOTICE: TokuDB, Tokutek Fractal Tree Indexing Library. Copyright (C) 2007-2013 Tokutek, Inc. DISCLAIMER: This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. UNIVERSITY PATENT NOTICE: The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it. PATENT MARKING NOTICE: This software is covered by US Patent No. 8,185,551. This software is covered by US Patent No. 8,489,638. PATENT RIGHTS GRANT: "THIS IMPLEMENTATION" means the copyrightable works distributed by Tokutek as part of the Fractal Tree project. "PATENT CLAIMS" means the claims of patents that are owned or licensable by Tokutek, both currently or in the future; and that in the absence of this license would be infringed by THIS IMPLEMENTATION or by using or running THIS IMPLEMENTATION. "PATENT CHALLENGE" shall mean a challenge to the validity, patentability, enforceability and/or non-infringement of any of the PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS. Tokutek hereby grants to you, for the term and geographical scope of the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer, and otherwise run, modify, and propagate the contents of THIS IMPLEMENTATION, where such license applies only to the PATENT CLAIMS. This grant does not include claims that would be infringed only as a consequence of further modifications of THIS IMPLEMENTATION. If you or your agent or licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that THIS IMPLEMENTATION constitutes direct or contributory patent infringement, or inducement of patent infringement, then any rights granted to you under this License shall terminate as of the date such litigation is filed. If you or your agent or exclusive licensee institute or order or agree to the institution of a PATENT CHALLENGE, then Tokutek may terminate any rights granted to you under this License. */ #ident "Copyright (c) 2007-2013 Tokutek Inc. All rights reserved." #include "toku_config.h" #include <toku_portability.h> #include "toku_assert.h" #include <db.h> #include <stdlib.h> #include <stdio.h> #if defined(HAVE_MALLOC_H) # include <malloc.h> #elif defined(HAVE_SYS_MALLOC_H) # include <sys/malloc.h> #endif #include <dlfcn.h> #if !TOKU_WINDOWS #include <execinfo.h> #endif #if !TOKU_WINDOWS #define N_POINTERS 1000 // These are statically allocated so that the backtrace can run without any calls to malloc() static void *backtrace_pointers[N_POINTERS]; #endif static uint64_t engine_status_num_rows = 0; typedef void (*malloc_stats_fun_t)(void); static malloc_stats_fun_t malloc_stats_f; void toku_assert_init(void) { malloc_stats_f = (malloc_stats_fun_t) dlsym(RTLD_DEFAULT, "malloc_stats"); } // Function pointers are zero by default so asserts can be used by brt-layer tests without an environment. static int (*toku_maybe_get_engine_status_text_p)(char* buff, int buffsize) = 0; static void (*toku_maybe_set_env_panic_p)(int code, const char* msg) = 0; void toku_assert_set_fpointers(int (*toku_maybe_get_engine_status_text_pointer)(char*, int), void (*toku_maybe_set_env_panic_pointer)(int, const char*), uint64_t num_rows) { toku_maybe_get_engine_status_text_p = toku_maybe_get_engine_status_text_pointer; toku_maybe_set_env_panic_p = toku_maybe_set_env_panic_pointer; engine_status_num_rows = num_rows; } bool toku_gdb_dump_on_assert = false; void (*do_assert_hook)(void) = NULL; void db_env_do_backtrace(void) { // backtrace #if !TOKU_WINDOWS int n = backtrace(backtrace_pointers, N_POINTERS); fprintf(stderr, "Backtrace: (Note: toku_do_assert=0x%p)\n", toku_do_assert); fflush(stderr); backtrace_symbols_fd(backtrace_pointers, n, fileno(stderr)); #endif fflush(stderr); if (engine_status_num_rows && toku_maybe_get_engine_status_text_p) { int buffsize = engine_status_num_rows * 128; // assume 128 characters per row (gross overestimate, should be safe) char buff[buffsize]; toku_maybe_get_engine_status_text_p(buff, buffsize); fprintf(stderr, "Engine status:\n%s\n", buff); } else fprintf(stderr, "Engine status function not available\n"); fprintf(stderr, "Memory usage:\n"); fflush(stderr); // just in case malloc_stats() crashes, we still want engine status (and to know that malloc_stats() failed) if (malloc_stats_f) { malloc_stats_f(); } fflush(stderr); if (do_assert_hook) do_assert_hook(); if (toku_gdb_dump_on_assert) { toku_try_gdb_stack_trace(nullptr); } } __attribute__((noreturn)) static void toku_do_backtrace_abort(void) { db_env_do_backtrace(); #if TOKU_WINDOWS //Following commented methods will not always end the process (could hang). //They could be unacceptable for other reasons as well (popups, //flush buffers before quitting, etc) // abort() // assert(false) (assert.h assert) // raise(SIGABRT) // divide by 0 // null dereference // _exit // exit // ExitProcess TerminateProcess(GetCurrentProcess(), 134); //Only way found so far to unconditionally //Terminate the process #endif abort(); } static void set_panic_if_not_panicked(int caller_errno, char * msg) { int code = caller_errno ? caller_errno : -1; if (toku_maybe_set_env_panic_p) { toku_maybe_set_env_panic_p(code, msg); } } #define MSGLEN 1024 void toku_do_assert_fail (const char *expr_as_string, const char *function, const char *file, int line, int caller_errno) { char msg[MSGLEN]; snprintf(msg, MSGLEN, "%s:%d %s: Assertion `%s' failed (errno=%d)\n", file, line, function, expr_as_string, caller_errno); perror(msg); set_panic_if_not_panicked(caller_errno, msg); toku_do_backtrace_abort(); } void toku_do_assert_zero_fail (uintptr_t expr, const char *expr_as_string, const char *function, const char *file, int line, int caller_errno) { char msg[MSGLEN]; snprintf(msg, MSGLEN, "%s:%d %s: Assertion `%s == 0' failed (errno=%d) (%s=%" PRIuPTR ")\n", file, line, function, expr_as_string, caller_errno, expr_as_string, expr); perror(msg); set_panic_if_not_panicked(caller_errno, msg); toku_do_backtrace_abort(); } void toku_do_assert_expected_fail (uintptr_t expr, uintptr_t expected, const char *expr_as_string, const char *function, const char *file, int line, int caller_errno) { char msg[MSGLEN]; snprintf(msg, MSGLEN, "%s:%d %s: Assertion `%s == %" PRIuPTR "' failed (errno=%d) (%s=%" PRIuPTR ")\n", file, line, function, expr_as_string, expected, caller_errno, expr_as_string, expr); perror(msg); set_panic_if_not_panicked(caller_errno, msg); toku_do_backtrace_abort(); } void toku_do_assert(int expr, const char *expr_as_string, const char *function, const char* file, int line, int caller_errno) { if (expr == 0) toku_do_assert_fail(expr_as_string, function, file, line, caller_errno); } compilation fix Tokutek/mongo#987 /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /* COPYING CONDITIONS NOTICE: This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation, and provided that the following conditions are met: * Redistributions of source code must retain this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below). * Redistributions in binary form must reproduce this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below) in the documentation and/or other materials provided with the distribution. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. COPYRIGHT NOTICE: TokuDB, Tokutek Fractal Tree Indexing Library. Copyright (C) 2007-2013 Tokutek, Inc. DISCLAIMER: This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. UNIVERSITY PATENT NOTICE: The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it. PATENT MARKING NOTICE: This software is covered by US Patent No. 8,185,551. This software is covered by US Patent No. 8,489,638. PATENT RIGHTS GRANT: "THIS IMPLEMENTATION" means the copyrightable works distributed by Tokutek as part of the Fractal Tree project. "PATENT CLAIMS" means the claims of patents that are owned or licensable by Tokutek, both currently or in the future; and that in the absence of this license would be infringed by THIS IMPLEMENTATION or by using or running THIS IMPLEMENTATION. "PATENT CHALLENGE" shall mean a challenge to the validity, patentability, enforceability and/or non-infringement of any of the PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS. Tokutek hereby grants to you, for the term and geographical scope of the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer, and otherwise run, modify, and propagate the contents of THIS IMPLEMENTATION, where such license applies only to the PATENT CLAIMS. This grant does not include claims that would be infringed only as a consequence of further modifications of THIS IMPLEMENTATION. If you or your agent or licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that THIS IMPLEMENTATION constitutes direct or contributory patent infringement, or inducement of patent infringement, then any rights granted to you under this License shall terminate as of the date such litigation is filed. If you or your agent or exclusive licensee institute or order or agree to the institution of a PATENT CHALLENGE, then Tokutek may terminate any rights granted to you under this License. */ #ident "Copyright (c) 2007-2013 Tokutek Inc. All rights reserved." #include "toku_config.h" #include <toku_portability.h> #include "toku_assert.h" #include <stdlib.h> #include <stdio.h> #if defined(HAVE_MALLOC_H) # include <malloc.h> #elif defined(HAVE_SYS_MALLOC_H) # include <sys/malloc.h> #endif #include <dlfcn.h> #if !TOKU_WINDOWS #include <execinfo.h> #endif #if !TOKU_WINDOWS #define N_POINTERS 1000 // These are statically allocated so that the backtrace can run without any calls to malloc() static void *backtrace_pointers[N_POINTERS]; #endif static uint64_t engine_status_num_rows = 0; typedef void (*malloc_stats_fun_t)(void); static malloc_stats_fun_t malloc_stats_f; void toku_assert_init(void) { malloc_stats_f = (malloc_stats_fun_t) dlsym(RTLD_DEFAULT, "malloc_stats"); } // Function pointers are zero by default so asserts can be used by brt-layer tests without an environment. static int (*toku_maybe_get_engine_status_text_p)(char* buff, int buffsize) = 0; static void (*toku_maybe_set_env_panic_p)(int code, const char* msg) = 0; void toku_assert_set_fpointers(int (*toku_maybe_get_engine_status_text_pointer)(char*, int), void (*toku_maybe_set_env_panic_pointer)(int, const char*), uint64_t num_rows) { toku_maybe_get_engine_status_text_p = toku_maybe_get_engine_status_text_pointer; toku_maybe_set_env_panic_p = toku_maybe_set_env_panic_pointer; engine_status_num_rows = num_rows; } bool toku_gdb_dump_on_assert = false; void (*do_assert_hook)(void) = NULL; void db_env_do_backtrace(void); // also declared in db.h for consumers of that API void db_env_do_backtrace(void) { // backtrace #if !TOKU_WINDOWS int n = backtrace(backtrace_pointers, N_POINTERS); fprintf(stderr, "Backtrace: (Note: toku_do_assert=0x%p)\n", toku_do_assert); fflush(stderr); backtrace_symbols_fd(backtrace_pointers, n, fileno(stderr)); #endif fflush(stderr); if (engine_status_num_rows && toku_maybe_get_engine_status_text_p) { int buffsize = engine_status_num_rows * 128; // assume 128 characters per row (gross overestimate, should be safe) char buff[buffsize]; toku_maybe_get_engine_status_text_p(buff, buffsize); fprintf(stderr, "Engine status:\n%s\n", buff); } else fprintf(stderr, "Engine status function not available\n"); fprintf(stderr, "Memory usage:\n"); fflush(stderr); // just in case malloc_stats() crashes, we still want engine status (and to know that malloc_stats() failed) if (malloc_stats_f) { malloc_stats_f(); } fflush(stderr); if (do_assert_hook) do_assert_hook(); if (toku_gdb_dump_on_assert) { toku_try_gdb_stack_trace(nullptr); } } __attribute__((noreturn)) static void toku_do_backtrace_abort(void) { db_env_do_backtrace(); #if TOKU_WINDOWS //Following commented methods will not always end the process (could hang). //They could be unacceptable for other reasons as well (popups, //flush buffers before quitting, etc) // abort() // assert(false) (assert.h assert) // raise(SIGABRT) // divide by 0 // null dereference // _exit // exit // ExitProcess TerminateProcess(GetCurrentProcess(), 134); //Only way found so far to unconditionally //Terminate the process #endif abort(); } static void set_panic_if_not_panicked(int caller_errno, char * msg) { int code = caller_errno ? caller_errno : -1; if (toku_maybe_set_env_panic_p) { toku_maybe_set_env_panic_p(code, msg); } } #define MSGLEN 1024 void toku_do_assert_fail (const char *expr_as_string, const char *function, const char *file, int line, int caller_errno) { char msg[MSGLEN]; snprintf(msg, MSGLEN, "%s:%d %s: Assertion `%s' failed (errno=%d)\n", file, line, function, expr_as_string, caller_errno); perror(msg); set_panic_if_not_panicked(caller_errno, msg); toku_do_backtrace_abort(); } void toku_do_assert_zero_fail (uintptr_t expr, const char *expr_as_string, const char *function, const char *file, int line, int caller_errno) { char msg[MSGLEN]; snprintf(msg, MSGLEN, "%s:%d %s: Assertion `%s == 0' failed (errno=%d) (%s=%" PRIuPTR ")\n", file, line, function, expr_as_string, caller_errno, expr_as_string, expr); perror(msg); set_panic_if_not_panicked(caller_errno, msg); toku_do_backtrace_abort(); } void toku_do_assert_expected_fail (uintptr_t expr, uintptr_t expected, const char *expr_as_string, const char *function, const char *file, int line, int caller_errno) { char msg[MSGLEN]; snprintf(msg, MSGLEN, "%s:%d %s: Assertion `%s == %" PRIuPTR "' failed (errno=%d) (%s=%" PRIuPTR ")\n", file, line, function, expr_as_string, expected, caller_errno, expr_as_string, expr); perror(msg); set_panic_if_not_panicked(caller_errno, msg); toku_do_backtrace_abort(); } void toku_do_assert(int expr, const char *expr_as_string, const char *function, const char* file, int line, int caller_errno) { if (expr == 0) toku_do_assert_fail(expr_as_string, function, file, line, caller_errno); }
#ifndef EVALUATOR_HPP #define EVALUATOR_HPP #include <algorithm> #include <boost/variant.hpp> #include <cmath> #include <ctype.h> #include <sstream> #include <stack> #include <stdexcept> #include <unordered_map> #include <vector> #include "Function.hpp" namespace Expressio { /** * An expression evaluator class which can evaluate an expression consisting of (ValueType)s. * * The following functions have to be defined for ValueType: * * @code * std::istream& operator>>(std::istream&, ValueType&); * ValueType operator+(const ValueType&, const ValueType&); * ValueType operator-(const ValueType&, const ValueType&); * ValueType operator*(const ValueType&, const ValueType&); * ValueType operator/(const ValueType&, const ValueType&); * ValueType operator-(const ValueType&); * ValueType std::pow(const ValueType&, const ValueType&); * @endcode * * All builtin integer types (`int`, `short`, ...), floating point types (`float`, `double`, ...) and complex types (`std::complex<double>`, ...) * can naturally be used to instantiate `Evaluator`, as they provide the required interface. */ template<class ValueType> class Evaluator { public: using ArgumentIterator = typename std::vector<ValueType>::const_iterator; /** * A type which can constructed with any callable object of the form: * @code ValueType(ValueType...) @endcode */ using Function = Detail::Function<ValueType, ArgumentIterator>; /** * Add user-defined function to the evaluator * * @param funcName The name of the function * @param function The function */ void addFunction(const std::string& funcName, const Function& function); /** * Evaluate the expression * * @param expression The expression to evaluate * @throws std::invalid_argument Invalid or erroneous expression * @return the result of the evaluation */ ValueType evaluate(const std::string& expression) const; private: struct Comma { }; ///< Represents a comma struct LeftParen { }; ///< Represents a left parenthesis struct RightParen { }; ///< Represents a right parenthesis /** * The Operator struct represents either a unary or binary operator. * * An operator is basically a specialized form of a function, so it naturally * derives from Function. */ struct Operator : public Function { int precedence; ///< The precedence of the operator /// Associativity type enum class Associativity { left, ///< If the operator is left associative, operators of equal precedence will be evaluated from left to right right ///< If the operator is right associative, operators of equal precedence will be evaluated from right to left }; Associativity associativity; ///< The associativity of the operator /** * Construct an operator * * @param function The underlying callable object * @param precedence The precedence of the operator * @param a The associativity of the operator */ template<class Func> Operator(const Func& function, int precedence, Associativity a) : Function(function), precedence(precedence), associativity(a) { } }; /** * A string to operator dictionary. Same for all Evaluators, and therfore static (and constant). */ static const std::unordered_map<std::string, Operator> operatorMap; /** * A string to function dictionary. Can be modified during the lifetime of the Evalutor. * Each user-defined function has to be present here before evaluation. */ std::unordered_map<std::string, Function> functionMap; /** * A token in an infix expression. This can be either a value, a comma, a parenthesis, an operator or a function. */ using InfixToken = boost::variant<ValueType, Comma, LeftParen, RightParen, Operator, Function>; /** * A token in a postfix expression. This can be either a value or a function */ using PostfixToken = boost::variant<ValueType, Function>; /** * Get the first sequence of consecutive characters that obey the character predicate requirements. * * @param s The string to search * @param func Callable object of the form @code bool(char) @endcode that returns true when the character * satisfies the requirements. * @return The string representation of the sequence, or an empty string if the sequence is empty. */ template<class CharacterPredicate> static std::string nextPredicatedString(const std::string& s, CharacterPredicate func); /** * Search the operator map for the symbol and return the corresponding operator if found. * * @param operatorSymbol The operator's symbol * @throws std::invalid_argument Invalid operator symbol * @return The corresponding operator */ static Operator getOperator(const std::string& operatorSymbol); /** * Search the function map for the function's name and return the corresponding function it if found. * * @param functionName The function's name * @throws std::invalid_argument Invalid function name * @return The corresponding operator */ Function getFunction(const std::string& functionName) const; /** * Strip and replace leading unary minuses in the expression with the alternative unary negation symbol. * * @param expression The expression string * @return The new expression string */ std::string handleLeadingUnaryNegation(const std::string& expression) const; /** * Tokenize the expression string to a list of infix tokens. * * @param expression The expression string * @throws std::invalid_argument Invalid expression * @return A vector of infix tokens representing the expression */ std::vector<InfixToken> tokenize(std::string expression) const; /** * Convert the infix expression (consisting of infix tokens) to a postfix expression * (consisting of postfix tokens). This function performs the Sunting Yard algorithm. * * @param infixTokens A vector of infix tokens representing an infix expression * @return A vector of postfix tokens representing a postfix expression */ std::vector<PostfixToken> infixToPostfix(const std::vector<InfixToken>& infixTokens) const; /** * Evaluate the postfix expression (consisting of postfix tokens), and return the result. * * @param postfixTokens A vector of postfix tokens representing the postfix expression * @return The result of the evaluation */ ValueType evaluatePostfix(const std::vector<PostfixToken>& postfixTokens) const; }; template<class ValueType> void Evaluator<ValueType>::addFunction(const std::string& funcName, const Function& function) { functionMap.emplace(funcName, function); } template<class ValueType> ValueType Evaluator<ValueType>::evaluate(const std::string& expression) const { return evaluatePostfix(infixToPostfix(tokenize(expression))); } template<class ValueType> const std::unordered_map<std::string, typename Evaluator<ValueType>::Operator> Evaluator<ValueType>::operatorMap { { "+" , { [](ValueType x, ValueType y) { return x + y; }, 1, Operator::Associativity::left } }, { "-" , { [](ValueType x, ValueType y) { return x - y; }, 1, Operator::Associativity::left } }, { "*" , { [](ValueType x, ValueType y) { return x * y; }, 2, Operator::Associativity::left } }, { "/" , { [](ValueType x, ValueType y) { if (y == ValueType(0)) throw std::invalid_argument("Math error: Division by zero"); return x / y; }, 2, Operator::Associativity::left } }, { "@" , { [](ValueType x) { return -x; }, 3, Operator::Associativity::right } }, { "^" , { [](ValueType x, ValueType y) { return std::pow(x, y); }, 4, Operator::Associativity::right } }, }; template<class ValueType> template<class CharacterPredicate> std::string Evaluator<ValueType>::nextPredicatedString(const std::string& s, CharacterPredicate func) { auto firstBadCharacter = std::find_if_not(s.begin(), s.end(), func); if (firstBadCharacter != s.end()) // sequence is not empty return s.substr(0, firstBadCharacter - s.begin()); // return the substring [0, firstBadCharacterIndex) return ""; // Sequence is empty } template<class ValueType> typename Evaluator<ValueType>::Operator Evaluator<ValueType>::getOperator(const std::string& operatorSymbol) { auto pair = operatorMap.find(operatorSymbol); if (pair == operatorMap.end()) throw std::invalid_argument("Syntax error: Unknown operator " + operatorSymbol); return pair->second; // The second item in the pair is the operator itself } template<class ValueType> typename Evaluator<ValueType>::Function Evaluator<ValueType>::getFunction(const std::string& functionName) const { auto pair = functionMap.find(functionName); if (pair == functionMap.end()) throw std::invalid_argument("Syntax error: Unknown function " + functionName); return pair->second; // The second item in the pair is the function itself } template<class ValueType> std::string Evaluator<ValueType>::handleLeadingUnaryNegation(const std::string& expression) const { std::size_t unaryMinusCount = 0; while (expression[unaryMinusCount] == '-') ++unaryMinusCount; // The new string doesn't contain the leading minuses std::string newExpr(expression, unaryMinusCount); // If the number of minuses was odd, unary negation ('@') is added to the expression's begining if (unaryMinusCount % 2 == 1) newExpr.insert(0, 1, '@'); return newExpr; } template<class ValueType> std::vector<typename Evaluator<ValueType>::InfixToken> Evaluator<ValueType>::tokenize(std::string expression) const { // Remove all whitespace from the expression expression.erase(std::remove_if(expression.begin(), expression.end(), ::isspace), expression.end()); expression = handleLeadingUnaryNegation(expression); std::vector<InfixToken> tokens; InfixToken prevToken; // Used to determine whether a minus represents substraction of unary negation. while (expression.length() > 0) { InfixToken token; std::string subStr; std::stringstream valueStream; ValueType value; // The minus represents negation if the previous token wasn't either a value or a right parenthesis if (expression[0] == '-' && !boost::get<ValueType*>(&prevToken) && !boost::get<RightParen*>(&prevToken)) expression[0] = '@'; char c = expression[0]; if (!isalnum(c) && !isspace(c) && std::string("(),.").find(c) == std::string::npos) // Operator { token = getOperator(std::string(1, c)); expression.erase(0, 1); } else if ([&]() -> bool { valueStream << expression; return valueStream >> value; }()) // Value { token = value; // copy the rest of valueStream (after numeric input has been discarded) back into the expression expression = std::string(std::istreambuf_iterator<char>(valueStream), std::istreambuf_iterator<char>()); } else if (c == '(') // Left parenthesis { token = LeftParen(); expression.erase(0, 1); } else if (c == ')') // Right parenthesis { token = RightParen(); expression.erase(0, 1); } else if (c == ',') // Comma { token = Comma(); expression.erase(0, 1); } else if (!isdigit(c) && (subStr = nextPredicatedString(expression, [](char c) { return isalnum(c) || c == '_'; })) != "") // Function { token = getFunction(subStr); expression.erase(0, subStr.length()); } else { throw std::invalid_argument("Syntax error: Invalid input"); } tokens.emplace_back(token); prevToken = token; } return tokens; } template<class ValueType> std::vector<typename Evaluator<ValueType>::PostfixToken> Evaluator<ValueType>::infixToPostfix(const std::vector<InfixToken>& infixTokens) const { // A token in a FunctionStack is either a function, an operator or a left-parenthesis using FunctionToken = boost::variant<Function, Operator, LeftParen>; // The function stack is a stack of function tokens using FunctionStack = std::stack<FunctionToken, std::vector<FunctionToken>>; std::vector<PostfixToken> output; FunctionStack functionStack; // boost::variant visitor for InfixTokens. Will be called for each token // in 'infixTokens' class InfixTokenVisitor : public boost::static_visitor<void> { std::vector<PostfixToken>& output; FunctionStack& functionStack; // boost::variant visitor for FunctionTokens. Inserts the function token // to the output vector when it's a function (operator are functions as well). // Returns whether the FunctionToken is a function (operator are functions as well). class FunctionTokenVisitor : public boost::static_visitor<bool> { std::vector<PostfixToken>& output; public: FunctionTokenVisitor(std::vector<PostfixToken>& output) : output(output) { } bool operator()(const LeftParen&) const { return true; } bool operator()(const Function& f) const { output.emplace_back(f); return false; } }; public: InfixTokenVisitor(std::vector<PostfixToken>& output, FunctionStack& functionStack): output(output), functionStack(functionStack) { } // Insert values to the output vector void operator()(const ValueType& x) const { output.emplace_back(x); } // Insert functions to the function stack void operator()(const Function& f) const { functionStack.emplace(f); } // Insert the left parenthesis to the function stack void operator()(const LeftParen& lp) const { functionStack.emplace(lp); } // Pop out all functions in the function stack to the output vecto // till a left parenthesis is matched void operator()(const RightParen&) const { while (!functionStack.empty()) { if (boost::apply_visitor(FunctionTokenVisitor(output), functionStack.top())) { functionStack.pop(); // Pop the left parenthesis out too return; } functionStack.pop(); } throw std::invalid_argument("Syntax error: Mismatched parentheses"); } // Pop out all functions in the function stack to the output vector // till a left parenthesis (of a function call) is matched void operator()(const Comma&) const { while (!functionStack.empty()) { if (boost::apply_visitor(FunctionTokenVisitor(output), functionStack.top())) return; functionStack.pop(); } throw std::invalid_argument("Syntax error: Mismatched parentheses or misplaced comma"); } // Place operators according to precdence and associativity rules void operator()(const Operator& op) const { // boost::variant visitor for FunctionTokens. Returns true when the function token // is placed on the output vector. class OperatorVisitor : public boost::static_visitor<bool> { const Operator& op1; std::vector<PostfixToken>& output; public: OperatorVisitor(const Operator& op1, std::vector<PostfixToken>& output) : op1(op1), output(output) { } bool operator()(const LeftParen&) const { return false; } bool operator()(const Function& f) const { output.emplace_back(f); return true; } bool operator()(const Operator& op2) const { if ((op1.associativity == Operator::Associativity::left && op1.precedence == op2.precedence) || (op1.precedence < op2.precedence)) { output.emplace_back(op2); return true; } return false; } }; // Do not consider prefix unary operators, as they are always added by order while (op.getArgsNum() != 1 && !functionStack.empty() && boost::apply_visitor(OperatorVisitor(op, output), functionStack.top())) { functionStack.pop(); } // After all higher-precedence operators have been popped out, // add the current one to the top functionStack.emplace(op); } }; // Apply the infix token visitor for each token for (const auto& token : infixTokens) boost::apply_visitor(InfixTokenVisitor(output, functionStack), token); // boost::variant visitor for FunctionTokens levt-over on the FunctionStack. // This places all the remaining functions onto the output vector. class FunctionStackLeftOverVisior : public boost::static_visitor<void> { std::vector<PostfixToken>& output; public: FunctionStackLeftOverVisior(std::vector<PostfixToken>& output): output(output) { } void operator()(const LeftParen&) const { throw std::invalid_argument("Syntax error: Mismatched parentheses"); } void operator()(const Function& f) const { output.emplace_back(f); } }; // Apply the left over visitor for the left over functions on the function stack while (!functionStack.empty()) { boost::apply_visitor(FunctionStackLeftOverVisior(output), functionStack.top()); functionStack.pop(); } return output; } template<class ValueType> ValueType Evaluator<ValueType>::evaluatePostfix(const std::vector<PostfixToken>& postfixTokens) const { std::vector<ValueType> valueStack; // boost::variant visitor for PostfixTokens. This performs the reverse polish notation // evaluation algorithm, where each value is pushed on the stack and each function evaluates // the popped out arguments from the stack and pushed the result to the stack. class PostfixTokenVisitor : public boost::static_visitor<void> { std::vector<ValueType>& valueStack; public: PostfixTokenVisitor(std::vector<ValueType>& valueStack) : valueStack(valueStack) { } void operator()(const ValueType& v) const { valueStack.emplace_back(v); } void operator()(const Function& f) const { if (valueStack.size() < f.getArgsNum()) throw std::invalid_argument("Syntax error: Not enough arguments!"); const auto endArgs = valueStack.end(); const auto beginArgs = endArgs - f.getArgsNum(); auto result = f(beginArgs, endArgs); valueStack.erase(beginArgs, endArgs); valueStack.emplace_back(result); } }; // Apply the postfix token visitor for each postfix token for (const auto& token : postfixTokens) boost::apply_visitor(PostfixTokenVisitor(valueStack), token); if (valueStack.size() > 1) throw std::invalid_argument("Syntax error: Too many arguments!"); if (valueStack.size() == 0) throw std::invalid_argument("Syntax error: No expression to evaluate!"); // Return the value at the top of the stack return valueStack.back(); } } // namespace Expressio #endif // EVALUATOR_HPP Typo (oops) #ifndef EVALUATOR_HPP #define EVALUATOR_HPP #include <algorithm> #include <boost/variant.hpp> #include <cmath> #include <ctype.h> #include <sstream> #include <stack> #include <stdexcept> #include <unordered_map> #include <vector> #include "Function.hpp" namespace Expressio { /** * An expression evaluator class which can evaluate an expression consisting of (ValueType)s. * * The following functions have to be defined for ValueType: * * @code * std::istream& operator>>(std::istream&, ValueType&); * ValueType operator+(const ValueType&, const ValueType&); * ValueType operator-(const ValueType&, const ValueType&); * ValueType operator*(const ValueType&, const ValueType&); * ValueType operator/(const ValueType&, const ValueType&); * ValueType operator-(const ValueType&); * ValueType std::pow(const ValueType&, const ValueType&); * @endcode * * All builtin integer types (`int`, `short`, ...), floating point types (`float`, `double`, ...) and complex types (`std::complex<double>`, ...) * can naturally be used to instantiate `Evaluator`, as they provide the required interface. */ template<class ValueType> class Evaluator { public: using ArgumentIterator = typename std::vector<ValueType>::const_iterator; /** * A type which can constructed with any callable object of the form: * @code ValueType(ValueType...) @endcode */ using Function = Detail::Function<ValueType, ArgumentIterator>; /** * Add user-defined function to the evaluator * * @param funcName The name of the function * @param function The function */ void addFunction(const std::string& funcName, const Function& function); /** * Evaluate the expression * * @param expression The expression to evaluate * @throws std::invalid_argument Invalid or erroneous expression * @return the result of the evaluation */ ValueType evaluate(const std::string& expression) const; private: struct Comma { }; ///< Represents a comma struct LeftParen { }; ///< Represents a left parenthesis struct RightParen { }; ///< Represents a right parenthesis /** * The Operator struct represents either a unary or binary operator. * * An operator is basically a specialized form of a function, so it naturally * derives from Function. */ struct Operator : public Function { int precedence; ///< The precedence of the operator /// Associativity type enum class Associativity { left, ///< If the operator is left associative, operators of equal precedence will be evaluated from left to right right ///< If the operator is right associative, operators of equal precedence will be evaluated from right to left }; Associativity associativity; ///< The associativity of the operator /** * Construct an operator * * @param function The underlying callable object * @param precedence The precedence of the operator * @param a The associativity of the operator */ template<class Func> Operator(const Func& function, int precedence, Associativity a) : Function(function), precedence(precedence), associativity(a) { } }; /** * A string to operator dictionary. Same for all Evaluators, and therfore static (and constant). */ static const std::unordered_map<std::string, Operator> operatorMap; /** * A string to function dictionary. Can be modified during the lifetime of the Evalutor. * Each user-defined function has to be present here before evaluation. */ std::unordered_map<std::string, Function> functionMap; /** * A token in an infix expression. This can be either a value, a comma, a parenthesis, an operator or a function. */ using InfixToken = boost::variant<ValueType, Comma, LeftParen, RightParen, Operator, Function>; /** * A token in a postfix expression. This can be either a value or a function */ using PostfixToken = boost::variant<ValueType, Function>; /** * Get the first sequence of consecutive characters that obey the character predicate requirements. * * @param s The string to search * @param func Callable object of the form @code bool(char) @endcode that returns true when the character * satisfies the requirements. * @return The string representation of the sequence, or an empty string if the sequence is empty. */ template<class CharacterPredicate> static std::string nextPredicatedString(const std::string& s, CharacterPredicate func); /** * Search the operator map for the symbol and return the corresponding operator if found. * * @param operatorSymbol The operator's symbol * @throws std::invalid_argument Invalid operator symbol * @return The corresponding operator */ static Operator getOperator(const std::string& operatorSymbol); /** * Search the function map for the function's name and return the corresponding function it if found. * * @param functionName The function's name * @throws std::invalid_argument Invalid function name * @return The corresponding operator */ Function getFunction(const std::string& functionName) const; /** * Strip and replace leading unary minuses in the expression with the alternative unary negation symbol. * * @param expression The expression string * @return The new expression string */ std::string handleLeadingUnaryNegation(const std::string& expression) const; /** * Tokenize the expression string to a list of infix tokens. * * @param expression The expression string * @throws std::invalid_argument Invalid expression * @return A vector of infix tokens representing the expression */ std::vector<InfixToken> tokenize(std::string expression) const; /** * Convert the infix expression (consisting of infix tokens) to a postfix expression * (consisting of postfix tokens). This function performs the Sunting Yard algorithm. * * @param infixTokens A vector of infix tokens representing an infix expression * @return A vector of postfix tokens representing a postfix expression */ std::vector<PostfixToken> infixToPostfix(const std::vector<InfixToken>& infixTokens) const; /** * Evaluate the postfix expression (consisting of postfix tokens), and return the result. * * @param postfixTokens A vector of postfix tokens representing the postfix expression * @return The result of the evaluation */ ValueType evaluatePostfix(const std::vector<PostfixToken>& postfixTokens) const; }; template<class ValueType> void Evaluator<ValueType>::addFunction(const std::string& funcName, const Function& function) { functionMap.emplace(funcName, function); } template<class ValueType> ValueType Evaluator<ValueType>::evaluate(const std::string& expression) const { return evaluatePostfix(infixToPostfix(tokenize(expression))); } template<class ValueType> const std::unordered_map<std::string, typename Evaluator<ValueType>::Operator> Evaluator<ValueType>::operatorMap { { "+" , { [](ValueType x, ValueType y) { return x + y; }, 1, Operator::Associativity::left } }, { "-" , { [](ValueType x, ValueType y) { return x - y; }, 1, Operator::Associativity::left } }, { "*" , { [](ValueType x, ValueType y) { return x * y; }, 2, Operator::Associativity::left } }, { "/" , { [](ValueType x, ValueType y) { if (y == ValueType(0)) throw std::invalid_argument("Math error: Division by zero"); return x / y; }, 2, Operator::Associativity::left } }, { "@" , { [](ValueType x) { return -x; }, 3, Operator::Associativity::right } }, { "^" , { [](ValueType x, ValueType y) { return std::pow(x, y); }, 4, Operator::Associativity::right } }, }; template<class ValueType> template<class CharacterPredicate> std::string Evaluator<ValueType>::nextPredicatedString(const std::string& s, CharacterPredicate func) { auto firstBadCharacter = std::find_if_not(s.begin(), s.end(), func); if (firstBadCharacter != s.end()) // sequence is not empty return s.substr(0, firstBadCharacter - s.begin()); // return the substring [0, firstBadCharacterIndex) return ""; // Sequence is empty } template<class ValueType> typename Evaluator<ValueType>::Operator Evaluator<ValueType>::getOperator(const std::string& operatorSymbol) { auto pair = operatorMap.find(operatorSymbol); if (pair == operatorMap.end()) throw std::invalid_argument("Syntax error: Unknown operator " + operatorSymbol); return pair->second; // The second item in the pair is the operator itself } template<class ValueType> typename Evaluator<ValueType>::Function Evaluator<ValueType>::getFunction(const std::string& functionName) const { auto pair = functionMap.find(functionName); if (pair == functionMap.end()) throw std::invalid_argument("Syntax error: Unknown function " + functionName); return pair->second; // The second item in the pair is the function itself } template<class ValueType> std::string Evaluator<ValueType>::handleLeadingUnaryNegation(const std::string& expression) const { std::size_t unaryMinusCount = 0; while (expression[unaryMinusCount] == '-') ++unaryMinusCount; // The new string doesn't contain the leading minuses std::string newExpr(expression, unaryMinusCount); // If the number of minuses was odd, unary negation ('@') is added to the expression's begining if (unaryMinusCount % 2 == 1) newExpr.insert(0, 1, '@'); return newExpr; } template<class ValueType> std::vector<typename Evaluator<ValueType>::InfixToken> Evaluator<ValueType>::tokenize(std::string expression) const { // Remove all whitespace from the expression expression.erase(std::remove_if(expression.begin(), expression.end(), ::isspace), expression.end()); expression = handleLeadingUnaryNegation(expression); std::vector<InfixToken> tokens; InfixToken prevToken; // Used to determine whether a minus represents substraction or unary negation. while (expression.length() > 0) { InfixToken token; std::string subStr; std::stringstream valueStream; ValueType value; // The minus represents negation if the previous token wasn't either a value or a right parenthesis if (expression[0] == '-' && !boost::get<ValueType*>(&prevToken) && !boost::get<RightParen*>(&prevToken)) expression[0] = '@'; char c = expression[0]; if (!isalnum(c) && !isspace(c) && std::string("(),.").find(c) == std::string::npos) // Operator { token = getOperator(std::string(1, c)); expression.erase(0, 1); } else if ([&]() -> bool { valueStream << expression; return valueStream >> value; }()) // Value { token = value; // copy the rest of valueStream (after numeric input has been discarded) back into the expression expression = std::string(std::istreambuf_iterator<char>(valueStream), std::istreambuf_iterator<char>()); } else if (c == '(') // Left parenthesis { token = LeftParen(); expression.erase(0, 1); } else if (c == ')') // Right parenthesis { token = RightParen(); expression.erase(0, 1); } else if (c == ',') // Comma { token = Comma(); expression.erase(0, 1); } else if (!isdigit(c) && (subStr = nextPredicatedString(expression, [](char c) { return isalnum(c) || c == '_'; })) != "") // Function { token = getFunction(subStr); expression.erase(0, subStr.length()); } else { throw std::invalid_argument("Syntax error: Invalid input"); } tokens.emplace_back(token); prevToken = token; } return tokens; } template<class ValueType> std::vector<typename Evaluator<ValueType>::PostfixToken> Evaluator<ValueType>::infixToPostfix(const std::vector<InfixToken>& infixTokens) const { // A token in a FunctionStack is either a function, an operator or a left-parenthesis using FunctionToken = boost::variant<Function, Operator, LeftParen>; // The function stack is a stack of function tokens using FunctionStack = std::stack<FunctionToken, std::vector<FunctionToken>>; std::vector<PostfixToken> output; FunctionStack functionStack; // boost::variant visitor for InfixTokens. Will be called for each token // in 'infixTokens' class InfixTokenVisitor : public boost::static_visitor<void> { std::vector<PostfixToken>& output; FunctionStack& functionStack; // boost::variant visitor for FunctionTokens. Inserts the function token // to the output vector when it's a function (operator are functions as well). // Returns whether the FunctionToken is a function (operator are functions as well). class FunctionTokenVisitor : public boost::static_visitor<bool> { std::vector<PostfixToken>& output; public: FunctionTokenVisitor(std::vector<PostfixToken>& output) : output(output) { } bool operator()(const LeftParen&) const { return true; } bool operator()(const Function& f) const { output.emplace_back(f); return false; } }; public: InfixTokenVisitor(std::vector<PostfixToken>& output, FunctionStack& functionStack): output(output), functionStack(functionStack) { } // Insert values to the output vector void operator()(const ValueType& x) const { output.emplace_back(x); } // Insert functions to the function stack void operator()(const Function& f) const { functionStack.emplace(f); } // Insert the left parenthesis to the function stack void operator()(const LeftParen& lp) const { functionStack.emplace(lp); } // Pop out all functions in the function stack to the output vecto // till a left parenthesis is matched void operator()(const RightParen&) const { while (!functionStack.empty()) { if (boost::apply_visitor(FunctionTokenVisitor(output), functionStack.top())) { functionStack.pop(); // Pop the left parenthesis out too return; } functionStack.pop(); } throw std::invalid_argument("Syntax error: Mismatched parentheses"); } // Pop out all functions in the function stack to the output vector // till a left parenthesis (of a function call) is matched void operator()(const Comma&) const { while (!functionStack.empty()) { if (boost::apply_visitor(FunctionTokenVisitor(output), functionStack.top())) return; functionStack.pop(); } throw std::invalid_argument("Syntax error: Mismatched parentheses or misplaced comma"); } // Place operators according to precdence and associativity rules void operator()(const Operator& op) const { // boost::variant visitor for FunctionTokens. Returns true when the function token // is placed on the output vector. class OperatorVisitor : public boost::static_visitor<bool> { const Operator& op1; std::vector<PostfixToken>& output; public: OperatorVisitor(const Operator& op1, std::vector<PostfixToken>& output) : op1(op1), output(output) { } bool operator()(const LeftParen&) const { return false; } bool operator()(const Function& f) const { output.emplace_back(f); return true; } bool operator()(const Operator& op2) const { if ((op1.associativity == Operator::Associativity::left && op1.precedence == op2.precedence) || (op1.precedence < op2.precedence)) { output.emplace_back(op2); return true; } return false; } }; // Do not consider prefix unary operators, as they are always added by order while (op.getArgsNum() != 1 && !functionStack.empty() && boost::apply_visitor(OperatorVisitor(op, output), functionStack.top())) { functionStack.pop(); } // After all higher-precedence operators have been popped out, // add the current one to the top functionStack.emplace(op); } }; // Apply the infix token visitor for each token for (const auto& token : infixTokens) boost::apply_visitor(InfixTokenVisitor(output, functionStack), token); // boost::variant visitor for FunctionTokens levt-over on the FunctionStack. // This places all the remaining functions onto the output vector. class FunctionStackLeftOverVisior : public boost::static_visitor<void> { std::vector<PostfixToken>& output; public: FunctionStackLeftOverVisior(std::vector<PostfixToken>& output): output(output) { } void operator()(const LeftParen&) const { throw std::invalid_argument("Syntax error: Mismatched parentheses"); } void operator()(const Function& f) const { output.emplace_back(f); } }; // Apply the left over visitor for the left over functions on the function stack while (!functionStack.empty()) { boost::apply_visitor(FunctionStackLeftOverVisior(output), functionStack.top()); functionStack.pop(); } return output; } template<class ValueType> ValueType Evaluator<ValueType>::evaluatePostfix(const std::vector<PostfixToken>& postfixTokens) const { std::vector<ValueType> valueStack; // boost::variant visitor for PostfixTokens. This performs the reverse polish notation // evaluation algorithm, where each value is pushed on the stack and each function evaluates // the popped out arguments from the stack and pushed the result to the stack. class PostfixTokenVisitor : public boost::static_visitor<void> { std::vector<ValueType>& valueStack; public: PostfixTokenVisitor(std::vector<ValueType>& valueStack) : valueStack(valueStack) { } void operator()(const ValueType& v) const { valueStack.emplace_back(v); } void operator()(const Function& f) const { if (valueStack.size() < f.getArgsNum()) throw std::invalid_argument("Syntax error: Not enough arguments!"); const auto endArgs = valueStack.end(); const auto beginArgs = endArgs - f.getArgsNum(); auto result = f(beginArgs, endArgs); valueStack.erase(beginArgs, endArgs); valueStack.emplace_back(result); } }; // Apply the postfix token visitor for each postfix token for (const auto& token : postfixTokens) boost::apply_visitor(PostfixTokenVisitor(valueStack), token); if (valueStack.size() > 1) throw std::invalid_argument("Syntax error: Too many arguments!"); if (valueStack.size() == 0) throw std::invalid_argument("Syntax error: No expression to evaluate!"); // Return the value at the top of the stack return valueStack.back(); } } // namespace Expressio #endif // EVALUATOR_HPP
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "cppeditor.h" #include "cppeditorconstants.h" #include "cppplugin.h" #include "cpphighlighter.h" #include "cppchecksymbols.h" #include "cppquickfix.h" #include "cpplocalsymbols.h" #include <AST.h> #include <Control.h> #include <Token.h> #include <Scope.h> #include <Symbols.h> #include <Names.h> #include <CoreTypes.h> #include <Literals.h> #include <ASTVisitor.h> #include <SymbolVisitor.h> #include <TranslationUnit.h> #include <cplusplus/ExpressionUnderCursor.h> #include <cplusplus/TypeOfExpression.h> #include <cplusplus/Overview.h> #include <cplusplus/OverviewModel.h> #include <cplusplus/SimpleLexer.h> #include <cplusplus/MatchingText.h> #include <cplusplus/BackwardsScanner.h> #include <cplusplus/FastPreprocessor.h> #include <cpptools/cpptoolsplugin.h> #include <cpptools/cppmodelmanagerinterface.h> #include <cpptools/cpptoolsconstants.h> #include <cpptools/cppcodeformatter.h> #include <coreplugin/icore.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/mimedatabase.h> #include <utils/uncommentselection.h> #include <extensionsystem/pluginmanager.h> #include <projectexplorer/projectexplorerconstants.h> #include <texteditor/basetextdocument.h> #include <texteditor/fontsettings.h> #include <texteditor/texteditorconstants.h> #include <QtCore/QDebug> #include <QtCore/QTime> #include <QtCore/QTimer> #include <QtCore/QStack> #include <QtCore/QSettings> #include <QtCore/QSignalMapper> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QHeaderView> #include <QtGui/QLayout> #include <QtGui/QMenu> #include <QtGui/QShortcut> #include <QtGui/QTextEdit> #include <QtGui/QComboBox> #include <QtGui/QToolBar> #include <QtGui/QTreeView> #include <QtGui/QSortFilterProxyModel> #include <sstream> enum { UPDATE_OUTLINE_INTERVAL = 500, UPDATE_USES_INTERVAL = 500 }; using namespace CPlusPlus; using namespace CppEditor::Internal; static QList<QTextEdit::ExtraSelection> createSelections(QTextDocument *document, const QList<CPlusPlus::Document::DiagnosticMessage> &msgs, const QTextCharFormat &format) { QList<QTextEdit::ExtraSelection> selections; foreach (const Document::DiagnosticMessage &m, msgs) { const int pos = document->findBlockByNumber(m.line() - 1).position() + m.column() - 1; if (pos < 0) continue; QTextCursor cursor(document); cursor.setPosition(pos); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, m.length()); QTextEdit::ExtraSelection sel; sel.cursor = cursor; sel.format = format; sel.format.setToolTip(m.text()); selections.append(sel); } return selections; } namespace { class OverviewTreeView : public QTreeView { public: OverviewTreeView(QWidget *parent = 0) : QTreeView(parent) { // TODO: Disable the root for all items (with a custom delegate?) setRootIsDecorated(false); } void sync() { expandAll(); setMinimumWidth(qMax(sizeHintForColumn(0), minimumSizeHint().width())); } }; class OverviewProxyModel : public QSortFilterProxyModel { Q_OBJECT public: OverviewProxyModel(CPlusPlus::OverviewModel *sourceModel, QObject *parent) : QSortFilterProxyModel(parent), m_sourceModel(sourceModel) { setSourceModel(m_sourceModel); } bool filterAcceptsRow(int sourceRow,const QModelIndex &sourceParent) const { // ignore generated symbols, e.g. by macro expansion (Q_OBJECT) const QModelIndex sourceIndex = m_sourceModel->index(sourceRow, 0, sourceParent); CPlusPlus::Symbol *symbol = m_sourceModel->symbolFromIndex(sourceIndex); if (symbol && symbol->isGenerated()) return false; return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); } private: CPlusPlus::OverviewModel *m_sourceModel; }; class FunctionDefinitionUnderCursor: protected ASTVisitor { unsigned _line; unsigned _column; DeclarationAST *_functionDefinition; public: FunctionDefinitionUnderCursor(TranslationUnit *translationUnit) : ASTVisitor(translationUnit), _line(0), _column(0) { } DeclarationAST *operator()(AST *ast, unsigned line, unsigned column) { _functionDefinition = 0; _line = line; _column = column; accept(ast); return _functionDefinition; } protected: virtual bool preVisit(AST *ast) { if (_functionDefinition) return false; else if (FunctionDefinitionAST *def = ast->asFunctionDefinition()) { return checkDeclaration(def); } else if (ObjCMethodDeclarationAST *method = ast->asObjCMethodDeclaration()) { if (method->function_body) return checkDeclaration(method); } return true; } private: bool checkDeclaration(DeclarationAST *ast) { unsigned startLine, startColumn; unsigned endLine, endColumn; getTokenStartPosition(ast->firstToken(), &startLine, &startColumn); getTokenEndPosition(ast->lastToken() - 1, &endLine, &endColumn); if (_line > startLine || (_line == startLine && _column >= startColumn)) { if (_line < endLine || (_line == endLine && _column < endColumn)) { _functionDefinition = ast; return false; } } return true; } }; class FindFunctionDefinitions: protected SymbolVisitor { const Name *_declarationName; QList<Function *> *_functions; public: FindFunctionDefinitions() : _declarationName(0), _functions(0) { } void operator()(const Name *declarationName, Scope *globals, QList<Function *> *functions) { _declarationName = declarationName; _functions = functions; for (unsigned i = 0; i < globals->memberCount(); ++i) { accept(globals->memberAt(i)); } } protected: using SymbolVisitor::visit; virtual bool visit(Function *function) { const Name *name = function->name(); if (const QualifiedNameId *q = name->asQualifiedNameId()) name = q->name(); if (_declarationName->isEqualTo(name)) _functions->append(function); return false; } }; struct CanonicalSymbol { CPPEditor *editor; TypeOfExpression typeOfExpression; SemanticInfo info; CanonicalSymbol(CPPEditor *editor, const SemanticInfo &info) : editor(editor), info(info) { typeOfExpression.init(info.doc, info.snapshot); } const LookupContext &context() const { return typeOfExpression.context(); } static inline bool isIdentifierChar(const QChar &ch) { return ch.isLetterOrNumber() || ch == QLatin1Char('_'); } Scope *getScopeAndExpression(const QTextCursor &cursor, QString *code) { return getScopeAndExpression(editor, info, cursor, code); } static Scope *getScopeAndExpression(CPPEditor *editor, const SemanticInfo &info, const QTextCursor &cursor, QString *code) { if (! info.doc) return 0; QTextCursor tc = cursor; int line, col; editor->convertPosition(tc.position(), &line, &col); ++col; // 1-based line and 1-based column QTextDocument *document = editor->document(); int pos = tc.position(); if (! isIdentifierChar(document->characterAt(pos))) if (! (pos > 0 && isIdentifierChar(document->characterAt(pos - 1)))) return 0; while (isIdentifierChar(document->characterAt(pos))) ++pos; tc.setPosition(pos); ExpressionUnderCursor expressionUnderCursor; *code = expressionUnderCursor(tc); return info.doc->scopeAt(line, col); } Symbol *operator()(const QTextCursor &cursor) { QString code; if (Scope *scope = getScopeAndExpression(cursor, &code)) return operator()(scope, code); return 0; } Symbol *operator()(Scope *scope, const QString &code) { return canonicalSymbol(scope, code, typeOfExpression); } static Symbol *canonicalSymbol(Scope *scope, const QString &code, TypeOfExpression &typeOfExpression) { const QList<LookupItem> results = typeOfExpression(code, scope, TypeOfExpression::Preprocess); for (int i = results.size() - 1; i != -1; --i) { const LookupItem &r = results.at(i); Symbol *decl = r.declaration(); if (! (decl && decl->scope())) break; if (Class *classScope = r.declaration()->scope()->asClass()) { const Identifier *declId = decl->identifier(); const Identifier *classId = classScope->identifier(); if (classId && classId->isEqualTo(declId)) continue; // skip it, it's a ctor or a dtor. else if (Function *funTy = r.declaration()->type()->asFunctionType()) { if (funTy->isVirtual()) return r.declaration(); } } } for (int i = 0; i < results.size(); ++i) { const LookupItem &r = results.at(i); if (r.declaration()) return r.declaration(); } return 0; } }; } // end of anonymous namespace CPPEditorEditable::CPPEditorEditable(CPPEditor *editor) : BaseTextEditorEditable(editor) { m_context.add(CppEditor::Constants::C_CPPEDITOR); m_context.add(ProjectExplorer::Constants::LANG_CXX); m_context.add(TextEditor::Constants::C_TEXTEDITOR); } CPPEditor::CPPEditor(QWidget *parent) : TextEditor::BaseTextEditor(parent) , m_currentRenameSelection(NoCurrentRenameSelection) , m_inRename(false) , m_inRenameChanged(false) , m_firstRenameChange(false) , m_objcEnabled(false) { m_initialized = false; qRegisterMetaType<CppEditor::Internal::SemanticInfo>("CppEditor::Internal::SemanticInfo"); m_semanticHighlighter = new SemanticHighlighter(this); m_semanticHighlighter->start(); setParenthesesMatchingEnabled(true); setMarksVisible(true); setCodeFoldingSupported(true); setCodeFoldingVisible(true); baseTextDocument()->setSyntaxHighlighter(new CppHighlighter); m_modelManager = CppTools::CppModelManagerInterface::instance(); if (m_modelManager) { connect(m_modelManager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)), this, SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr))); } m_highlightRevision = 0; m_nextHighlightBlockNumber = 0; connect(&m_highlightWatcher, SIGNAL(resultsReadyAt(int,int)), SLOT(highlightSymbolUsages(int,int))); connect(&m_highlightWatcher, SIGNAL(finished()), SLOT(finishHighlightSymbolUsages())); m_referencesRevision = 0; m_referencesCursorPosition = 0; connect(&m_referencesWatcher, SIGNAL(finished()), SLOT(markSymbolsNow())); } CPPEditor::~CPPEditor() { Core::EditorManager::instance()->hideEditorInfoBar(QLatin1String("CppEditor.Rename")); m_semanticHighlighter->abort(); m_semanticHighlighter->wait(); } TextEditor::BaseTextEditorEditable *CPPEditor::createEditableInterface() { CPPEditorEditable *editable = new CPPEditorEditable(this); createToolBar(editable); return editable; } void CPPEditor::createToolBar(CPPEditorEditable *editable) { m_outlineCombo = new QComboBox; m_outlineCombo->setMinimumContentsLength(22); // Make the combo box prefer to expand QSizePolicy policy = m_outlineCombo->sizePolicy(); policy.setHorizontalPolicy(QSizePolicy::Expanding); m_outlineCombo->setSizePolicy(policy); QTreeView *outlineView = new OverviewTreeView; outlineView->header()->hide(); outlineView->setItemsExpandable(false); m_outlineCombo->setView(outlineView); m_outlineCombo->setMaxVisibleItems(20); m_outlineModel = new OverviewModel(this); m_proxyModel = new OverviewProxyModel(m_outlineModel, this); if (CppPlugin::instance()->sortedOutline()) m_proxyModel->sort(0, Qt::AscendingOrder); else m_proxyModel->sort(-1, Qt::AscendingOrder); // don't sort yet, but set column for sortedOutline() m_proxyModel->setDynamicSortFilter(true); m_proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_outlineCombo->setModel(m_proxyModel); m_outlineCombo->setContextMenuPolicy(Qt::ActionsContextMenu); m_sortAction = new QAction(tr("Sort Alphabetically"), m_outlineCombo); m_sortAction->setCheckable(true); m_sortAction->setChecked(sortedOutline()); connect(m_sortAction, SIGNAL(toggled(bool)), CppPlugin::instance(), SLOT(setSortedOutline(bool))); m_outlineCombo->addAction(m_sortAction); m_updateOutlineTimer = new QTimer(this); m_updateOutlineTimer->setSingleShot(true); m_updateOutlineTimer->setInterval(UPDATE_OUTLINE_INTERVAL); connect(m_updateOutlineTimer, SIGNAL(timeout()), this, SLOT(updateOutlineNow())); m_updateOutlineIndexTimer = new QTimer(this); m_updateOutlineIndexTimer->setSingleShot(true); m_updateOutlineIndexTimer->setInterval(UPDATE_OUTLINE_INTERVAL); connect(m_updateOutlineIndexTimer, SIGNAL(timeout()), this, SLOT(updateOutlineIndexNow())); m_updateUsesTimer = new QTimer(this); m_updateUsesTimer->setSingleShot(true); m_updateUsesTimer->setInterval(UPDATE_USES_INTERVAL); connect(m_updateUsesTimer, SIGNAL(timeout()), this, SLOT(updateUsesNow())); connect(m_outlineCombo, SIGNAL(activated(int)), this, SLOT(jumpToOutlineElement(int))); connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateOutlineIndex())); connect(m_outlineCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(updateOutlineToolTip())); connect(document(), SIGNAL(contentsChange(int,int,int)), this, SLOT(onContentsChanged(int,int,int))); connect(file(), SIGNAL(changed()), this, SLOT(updateFileName())); // set up the semantic highlighter connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateUses())); connect(this, SIGNAL(textChanged()), this, SLOT(updateUses())); connect(m_semanticHighlighter, SIGNAL(changed(CppEditor::Internal::SemanticInfo)), this, SLOT(updateSemanticInfo(CppEditor::Internal::SemanticInfo))); QToolBar *toolBar = static_cast<QToolBar*>(editable->toolBar()); QList<QAction*> actions = toolBar->actions(); QWidget *w = toolBar->widgetForAction(actions.first()); static_cast<QHBoxLayout*>(w->layout())->insertWidget(0, m_outlineCombo, 1); } void CPPEditor::paste() { if (m_currentRenameSelection == NoCurrentRenameSelection) { BaseTextEditor::paste(); return; } startRename(); BaseTextEditor::paste(); finishRename(); } void CPPEditor::cut() { if (m_currentRenameSelection == NoCurrentRenameSelection) { BaseTextEditor::cut(); return; } startRename(); BaseTextEditor::cut(); finishRename(); } CppTools::CppModelManagerInterface *CPPEditor::modelManager() const { return m_modelManager; } void CPPEditor::setMimeType(const QString &mt) { BaseTextEditor::setMimeType(mt); setObjCEnabled(mt == CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE); } void CPPEditor::setObjCEnabled(bool onoff) { m_objcEnabled = onoff; } bool CPPEditor::isObjCEnabled() const { return m_objcEnabled; } void CPPEditor::startRename() { m_inRenameChanged = false; } void CPPEditor::finishRename() { if (!m_inRenameChanged) return; m_inRename = true; QTextCursor cursor = textCursor(); cursor.joinPreviousEditBlock(); cursor.setPosition(m_currentRenameSelectionEnd.position()); cursor.setPosition(m_currentRenameSelectionBegin.position(), QTextCursor::KeepAnchor); m_renameSelections[m_currentRenameSelection].cursor = cursor; QString text = cursor.selectedText(); for (int i = 0; i < m_renameSelections.size(); ++i) { if (i == m_currentRenameSelection) continue; QTextEdit::ExtraSelection &s = m_renameSelections[i]; int pos = s.cursor.selectionStart(); s.cursor.removeSelectedText(); s.cursor.insertText(text); s.cursor.setPosition(pos, QTextCursor::KeepAnchor); } setExtraSelections(CodeSemanticsSelection, m_renameSelections); cursor.endEditBlock(); m_inRename = false; } void CPPEditor::abortRename() { if (m_currentRenameSelection <= NoCurrentRenameSelection) return; m_renameSelections[m_currentRenameSelection].format = m_occurrencesFormat; m_currentRenameSelection = NoCurrentRenameSelection; m_currentRenameSelectionBegin = QTextCursor(); m_currentRenameSelectionEnd = QTextCursor(); setExtraSelections(CodeSemanticsSelection, m_renameSelections); } void CPPEditor::rehighlight(bool force) { const SemanticHighlighter::Source source = currentSource(force); m_semanticHighlighter->rehighlight(source); } void CPPEditor::onDocumentUpdated(Document::Ptr doc) { if (doc->fileName() != file()->fileName()) return; if (doc->editorRevision() != editorRevision()) return; if (! m_initialized) { m_initialized = true; rehighlight(/* force = */ true); } m_updateOutlineTimer->start(); } const Macro *CPPEditor::findCanonicalMacro(const QTextCursor &cursor, Document::Ptr doc) const { if (! doc) return 0; int line, col; convertPosition(cursor.position(), &line, &col); if (const Macro *macro = doc->findMacroDefinitionAt(line)) return macro; if (const Document::MacroUse *use = doc->findMacroUseAt(cursor.position())) return &use->macro(); return 0; } void CPPEditor::findUsages() { SemanticInfo info = m_lastSemanticInfo; info.snapshot = CppTools::CppModelManagerInterface::instance()->snapshot(); info.snapshot.insert(info.doc); CanonicalSymbol cs(this, info); Symbol *canonicalSymbol = cs(textCursor()); if (canonicalSymbol) { m_modelManager->findUsages(canonicalSymbol, cs.context()); } else if (const Macro *macro = findCanonicalMacro(textCursor(), info.doc)) { m_modelManager->findMacroUsages(*macro); } } void CPPEditor::renameUsagesNow(const QString &replacement) { SemanticInfo info = m_lastSemanticInfo; info.snapshot = CppTools::CppModelManagerInterface::instance()->snapshot(); info.snapshot.insert(info.doc); CanonicalSymbol cs(this, info); if (Symbol *canonicalSymbol = cs(textCursor())) { if (canonicalSymbol->identifier() != 0) { if (showWarningMessage()) { Core::EditorManager::instance()->showEditorInfoBar(QLatin1String("CppEditor.Rename"), tr("This change cannot be undone."), tr("Yes, I know what I am doing."), this, SLOT(hideRenameNotification())); } m_modelManager->renameUsages(canonicalSymbol, cs.context(), replacement); } } } void CPPEditor::renameUsages() { renameUsagesNow(); } bool CPPEditor::showWarningMessage() const { // Restore settings QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup(QLatin1String("CppEditor")); settings->beginGroup(QLatin1String("Rename")); const bool showWarningMessage = settings->value(QLatin1String("ShowWarningMessage"), true).toBool(); settings->endGroup(); settings->endGroup(); return showWarningMessage; } void CPPEditor::setShowWarningMessage(bool showWarningMessage) { // Restore settings QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup(QLatin1String("CppEditor")); settings->beginGroup(QLatin1String("Rename")); settings->setValue(QLatin1String("ShowWarningMessage"), showWarningMessage); settings->endGroup(); settings->endGroup(); } void CPPEditor::hideRenameNotification() { setShowWarningMessage(false); Core::EditorManager::instance()->hideEditorInfoBar(QLatin1String("CppEditor.Rename")); } void CPPEditor::markSymbolsNow() { if (m_references.isCanceled()) return; else if (m_referencesCursorPosition != position()) return; else if (m_referencesRevision != editorRevision()) return; const SemanticInfo info = m_lastSemanticInfo; TranslationUnit *unit = info.doc->translationUnit(); const QList<int> result = m_references.result(); QList<QTextEdit::ExtraSelection> selections; foreach (int index, result) { unsigned line, column; unit->getTokenPosition(index, &line, &column); if (column) --column; // adjust the column position. const int len = unit->tokenAt(index).f.length; QTextCursor cursor(document()->findBlockByNumber(line - 1)); cursor.setPosition(cursor.position() + column); cursor.setPosition(cursor.position() + len, QTextCursor::KeepAnchor); QTextEdit::ExtraSelection sel; sel.format = m_occurrencesFormat; sel.cursor = cursor; selections.append(sel); } setExtraSelections(CodeSemanticsSelection, selections); } static QList<int> lazyFindReferences(Scope *scope, QString code, Document::Ptr doc, Snapshot snapshot) { TypeOfExpression typeOfExpression; snapshot.insert(doc); typeOfExpression.init(doc, snapshot); if (Symbol *canonicalSymbol = CanonicalSymbol::canonicalSymbol(scope, code, typeOfExpression)) { return CppTools::CppModelManagerInterface::instance()->references(canonicalSymbol, typeOfExpression.context()); } return QList<int>(); } void CPPEditor::markSymbols(const QTextCursor &tc, const SemanticInfo &info) { abortRename(); if (! info.doc) return; CanonicalSymbol cs(this, info); QString expression; if (Scope *scope = cs.getScopeAndExpression(this, info, tc, &expression)) { m_references.cancel(); m_referencesRevision = info.revision; m_referencesCursorPosition = position(); m_references = QtConcurrent::run(&lazyFindReferences, scope, expression, info.doc, info.snapshot); m_referencesWatcher.setFuture(m_references); } else { const QList<QTextEdit::ExtraSelection> selections = extraSelections(CodeSemanticsSelection); if (! selections.isEmpty()) setExtraSelections(CodeSemanticsSelection, QList<QTextEdit::ExtraSelection>()); } } void CPPEditor::renameSymbolUnderCursor() { updateSemanticInfo(m_semanticHighlighter->semanticInfo(currentSource())); abortRename(); QTextCursor c = textCursor(); for (int i = 0; i < m_renameSelections.size(); ++i) { QTextEdit::ExtraSelection s = m_renameSelections.at(i); if (c.position() >= s.cursor.anchor() && c.position() <= s.cursor.position()) { m_currentRenameSelection = i; m_firstRenameChange = true; m_currentRenameSelectionBegin = QTextCursor(c.document()->docHandle(), m_renameSelections[i].cursor.selectionStart()); m_currentRenameSelectionEnd = QTextCursor(c.document()->docHandle(), m_renameSelections[i].cursor.selectionEnd()); m_renameSelections[i].format = m_occurrenceRenameFormat; setExtraSelections(CodeSemanticsSelection, m_renameSelections); break; } } if (m_renameSelections.isEmpty()) renameUsages(); } void CPPEditor::onContentsChanged(int position, int charsRemoved, int charsAdded) { Q_UNUSED(position) if (m_currentRenameSelection == NoCurrentRenameSelection || m_inRename) return; if (position + charsAdded == m_currentRenameSelectionBegin.position()) { // we are inserting at the beginning of the rename selection => expand m_currentRenameSelectionBegin.setPosition(position); m_renameSelections[m_currentRenameSelection].cursor.setPosition(position, QTextCursor::KeepAnchor); } // the condition looks odd, but keep in mind that the begin and end cursors do move automatically m_inRenameChanged = (position >= m_currentRenameSelectionBegin.position() && position + charsAdded <= m_currentRenameSelectionEnd.position()); if (!m_inRenameChanged) abortRename(); if (charsRemoved > 0) updateUses(); } void CPPEditor::updateFileName() { } void CPPEditor::jumpToOutlineElement(int) { QModelIndex index = m_proxyModel->mapToSource(m_outlineCombo->view()->currentIndex()); Symbol *symbol = m_outlineModel->symbolFromIndex(index); if (! symbol) return; openCppEditorAt(linkToSymbol(symbol)); } void CPPEditor::setSortedOutline(bool sort) { if (sort != sortedOutline()) { if (sort) m_proxyModel->sort(0, Qt::AscendingOrder); else m_proxyModel->sort(-1, Qt::AscendingOrder); bool block = m_sortAction->blockSignals(true); m_sortAction->setChecked(m_proxyModel->sortColumn() == 0); m_sortAction->blockSignals(block); updateOutlineIndexNow(); } } bool CPPEditor::sortedOutline() const { return (m_proxyModel->sortColumn() == 0); } void CPPEditor::updateOutlineNow() { const Snapshot snapshot = m_modelManager->snapshot(); Document::Ptr document = snapshot.document(file()->fileName()); if (!document) return; if (document->editorRevision() != editorRevision()) { m_updateOutlineTimer->start(); return; } m_outlineModel->rebuild(document); OverviewTreeView *treeView = static_cast<OverviewTreeView *>(m_outlineCombo->view()); treeView->sync(); updateOutlineIndexNow(); } void CPPEditor::updateOutlineIndex() { m_updateOutlineIndexTimer->start(); } void CPPEditor::highlightUses(const QList<SemanticInfo::Use> &uses, const SemanticInfo &semanticInfo, QList<QTextEdit::ExtraSelection> *selections) { bool isUnused = false; if (uses.size() == 1) isUnused = true; foreach (const SemanticInfo::Use &use, uses) { QTextEdit::ExtraSelection sel; if (isUnused) sel.format = m_occurrencesUnusedFormat; else sel.format = m_occurrencesFormat; const int anchor = document()->findBlockByNumber(use.line - 1).position() + use.column - 1; const int position = anchor + use.length; sel.cursor = QTextCursor(document()); sel.cursor.setPosition(anchor); sel.cursor.setPosition(position, QTextCursor::KeepAnchor); if (isUnused) { if (semanticInfo.hasQ && sel.cursor.selectedText() == QLatin1String("q")) continue; // skip q else if (semanticInfo.hasD && sel.cursor.selectedText() == QLatin1String("d")) continue; // skip d } selections->append(sel); } } void CPPEditor::updateOutlineIndexNow() { if (!m_outlineModel->document()) return; if (m_outlineModel->document()->editorRevision() != editorRevision()) { m_updateOutlineIndexTimer->start(); return; } m_updateOutlineIndexTimer->stop(); m_outlineModelIndex = QModelIndex(); //invalidate QModelIndex comboIndex = outlineModelIndex(); if (comboIndex.isValid()) { bool blocked = m_outlineCombo->blockSignals(true); // There is no direct way to select a non-root item m_outlineCombo->setRootModelIndex(m_proxyModel->mapFromSource(comboIndex.parent())); m_outlineCombo->setCurrentIndex(m_proxyModel->mapFromSource(comboIndex).row()); m_outlineCombo->setRootModelIndex(QModelIndex()); updateOutlineToolTip(); m_outlineCombo->blockSignals(blocked); } } void CPPEditor::updateOutlineToolTip() { m_outlineCombo->setToolTip(m_outlineCombo->currentText()); } void CPPEditor::updateUses() { if (editorRevision() != m_highlightRevision) m_highlighter.cancel(); m_updateUsesTimer->start(); } void CPPEditor::updateUsesNow() { if (m_currentRenameSelection != NoCurrentRenameSelection) return; semanticRehighlight(); } void CPPEditor::highlightSymbolUsages(int from, int to) { if (editorRevision() != m_highlightRevision) return; // outdated else if (m_highlighter.isCanceled()) return; // aborted CppHighlighter *highlighter = qobject_cast<CppHighlighter*>(baseTextDocument()->syntaxHighlighter()); Q_ASSERT(highlighter); QTextDocument *doc = document(); if (m_nextHighlightBlockNumber >= doc->blockCount()) return; QMap<int, QVector<SemanticInfo::Use> > chunks = CheckSymbols::chunks(m_highlighter, from, to); if (chunks.isEmpty()) return; QTextBlock b = doc->findBlockByNumber(m_nextHighlightBlockNumber); QMapIterator<int, QVector<SemanticInfo::Use> > it(chunks); while (b.isValid() && it.hasNext()) { it.next(); const int blockNumber = it.key(); Q_ASSERT(blockNumber < doc->blockCount()); while (m_nextHighlightBlockNumber < blockNumber) { highlighter->setExtraAdditionalFormats(b, QList<QTextLayout::FormatRange>()); b = b.next(); ++m_nextHighlightBlockNumber; } QList<QTextLayout::FormatRange> formats; foreach (const SemanticInfo::Use &use, it.value()) { QTextLayout::FormatRange formatRange; switch (use.kind) { case SemanticInfo::Use::Type: formatRange.format = m_typeFormat; break; case SemanticInfo::Use::Field: formatRange.format = m_fieldFormat; break; case SemanticInfo::Use::Local: formatRange.format = m_localFormat; break; case SemanticInfo::Use::Static: formatRange.format = m_staticFormat; break; case SemanticInfo::Use::VirtualMethod: formatRange.format = m_virtualMethodFormat; break; default: continue; } formatRange.start = use.column - 1; formatRange.length = use.length; formats.append(formatRange); } highlighter->setExtraAdditionalFormats(b, formats); b = b.next(); ++m_nextHighlightBlockNumber; } } void CPPEditor::finishHighlightSymbolUsages() { if (editorRevision() != m_highlightRevision) return; // outdated else if (m_highlighter.isCanceled()) return; // aborted CppHighlighter *highlighter = qobject_cast<CppHighlighter*>(baseTextDocument()->syntaxHighlighter()); Q_ASSERT(highlighter); QTextDocument *doc = document(); if (m_nextHighlightBlockNumber >= doc->blockCount()) return; QTextBlock b = doc->findBlockByNumber(m_nextHighlightBlockNumber); while (b.isValid()) { highlighter->setExtraAdditionalFormats(b, QList<QTextLayout::FormatRange>()); b = b.next(); ++m_nextHighlightBlockNumber; } } void CPPEditor::switchDeclarationDefinition() { if (! m_modelManager) return; const Snapshot snapshot = m_modelManager->snapshot(); if (Document::Ptr thisDocument = snapshot.document(file()->fileName())) { int line = 0, positionInBlock = 0; convertPosition(position(), &line, &positionInBlock); Symbol *lastVisibleSymbol = thisDocument->lastVisibleSymbolAt(line, positionInBlock + 1); if (! lastVisibleSymbol) return; Function *functionScope = lastVisibleSymbol->asFunction(); if (! functionScope) functionScope = lastVisibleSymbol->enclosingFunction(); if (functionScope) { LookupContext context(thisDocument, snapshot); Function *functionDefinition = functionScope->asFunction(); const QList<LookupItem> declarations = context.lookup(functionDefinition->name(), functionDefinition->scope()); foreach (const LookupItem &r, declarations) { Symbol *decl = r.declaration(); // TODO: check decl. openCppEditorAt(linkToSymbol(decl)); break; } } else if (lastVisibleSymbol && lastVisibleSymbol->isDeclaration() && lastVisibleSymbol->type()->isFunctionType()) { if (Symbol *def = snapshot.findMatchingDefinition(lastVisibleSymbol)) openCppEditorAt(linkToSymbol(def)); } } } static inline LookupItem skipForwardDeclarations(const QList<LookupItem> &resolvedSymbols) { QList<LookupItem> candidates = resolvedSymbols; LookupItem result = candidates.first(); const FullySpecifiedType ty = result.type().simplified(); if (ty->isForwardClassDeclarationType()) { while (! candidates.isEmpty()) { LookupItem r = candidates.takeFirst(); if (! r.type()->isForwardClassDeclarationType()) { result = r; break; } } } if (ty->isObjCForwardClassDeclarationType()) { while (! candidates.isEmpty()) { LookupItem r = candidates.takeFirst(); if (! r.type()->isObjCForwardClassDeclarationType()) { result = r; break; } } } if (ty->isObjCForwardProtocolDeclarationType()) { while (! candidates.isEmpty()) { LookupItem r = candidates.takeFirst(); if (! r.type()->isObjCForwardProtocolDeclarationType()) { result = r; break; } } } return result; } CPPEditor::Link CPPEditor::findLinkAt(const QTextCursor &cursor, bool resolveTarget) { Link link; if (!m_modelManager) return link; const Snapshot snapshot = m_modelManager->snapshot(); int lineNumber = 0, positionInBlock = 0; convertPosition(cursor.position(), &lineNumber, &positionInBlock); Document::Ptr doc = snapshot.document(file()->fileName()); if (!doc) return link; const unsigned line = lineNumber; const unsigned column = positionInBlock + 1; QTextCursor tc = cursor; // Make sure we're not at the start of a word { const QChar c = characterAt(tc.position()); if (c.isLetter() || c == QLatin1Char('_')) tc.movePosition(QTextCursor::Right); } int beginOfToken = 0; int endOfToken = 0; SimpleLexer tokenize; tokenize.setQtMocRunEnabled(true); const QString blockText = cursor.block().text(); const QList<Token> tokens = tokenize(blockText, BackwardsScanner::previousBlockState(cursor.block())); bool recognizedQtMethod = false; for (int i = 0; i < tokens.size(); ++i) { const Token &tk = tokens.at(i); if (((unsigned) positionInBlock) >= tk.begin() && ((unsigned) positionInBlock) <= tk.end()) { if (i >= 2 && tokens.at(i).is(T_IDENTIFIER) && tokens.at(i - 1).is(T_LPAREN) && (tokens.at(i - 2).is(T_SIGNAL) || tokens.at(i - 2).is(T_SLOT))) { // token[i] == T_IDENTIFIER // token[i + 1] == T_LPAREN // token[.....] == .... // token[i + n] == T_RPAREN if (i + 1 < tokens.size() && tokens.at(i + 1).is(T_LPAREN)) { // skip matched parenthesis int j = i - 1; int depth = 0; for (; j < tokens.size(); ++j) { if (tokens.at(j).is(T_LPAREN)) ++depth; else if (tokens.at(j).is(T_RPAREN)) { if (! --depth) break; } } if (j < tokens.size()) { QTextBlock block = cursor.block(); beginOfToken = block.position() + tokens.at(i).begin(); endOfToken = block.position() + tokens.at(i).end(); tc.setPosition(block.position() + tokens.at(j).end()); recognizedQtMethod = true; } } } break; } } if (! recognizedQtMethod) { const QTextBlock block = tc.block(); int pos = cursor.positionInBlock(); QChar ch = document()->characterAt(cursor.position()); if (pos > 0 && ! (ch.isLetterOrNumber() || ch == QLatin1Char('_'))) --pos; // positionInBlock points to a delimiter character. const Token tk = SimpleLexer::tokenAt(block.text(), pos, BackwardsScanner::previousBlockState(block), true); beginOfToken = block.position() + tk.begin(); endOfToken = block.position() + tk.end(); // Handle include directives if (tk.is(T_STRING_LITERAL) || tk.is(T_ANGLE_STRING_LITERAL)) { const unsigned lineno = cursor.blockNumber() + 1; foreach (const Document::Include &incl, doc->includes()) { if (incl.line() == lineno && incl.resolved()) { link.fileName = incl.fileName(); link.begin = beginOfToken + 1; link.end = endOfToken - 1; return link; } } } if (tk.isNot(T_IDENTIFIER)) return link; tc.setPosition(endOfToken); } // Find the last symbol up to the cursor position Scope *scope = doc->scopeAt(line, column); if (!scope) return link; // Evaluate the type of the expression under the cursor ExpressionUnderCursor expressionUnderCursor; const QString expression = expressionUnderCursor(tc); TypeOfExpression typeOfExpression; typeOfExpression.init(doc, snapshot); const QList<LookupItem> resolvedSymbols = typeOfExpression(expression, scope, TypeOfExpression::Preprocess); if (!resolvedSymbols.isEmpty()) { LookupItem result = skipForwardDeclarations(resolvedSymbols); foreach (const LookupItem &r, resolvedSymbols) { if (Symbol *d = r.declaration()) { if (d->isDeclaration() || d->isFunction()) { if (file()->fileName() == QString::fromUtf8(d->fileName(), d->fileNameLength())) { if (unsigned(lineNumber) == d->line() && unsigned(positionInBlock) >= d->column()) { // ### TODO: check the end result = r; // take the symbol under cursor. break; } } } } } if (Symbol *symbol = result.declaration()) { Symbol *def = 0; if (resolveTarget) { Symbol *lastVisibleSymbol = doc->lastVisibleSymbolAt(line, column); def = findDefinition(symbol, snapshot); if (def == lastVisibleSymbol) def = 0; // jump to declaration then. } if (symbol->isForwardClassDeclaration()) { def = snapshot.findMatchingClassDeclaration(symbol); } link = linkToSymbol(def ? def : symbol); link.begin = beginOfToken; link.end = endOfToken; return link; // This would jump to the type of a name #if 0 } else if (NamedType *namedType = firstType->asNamedType()) { QList<Symbol *> candidates = context.resolve(namedType->name()); if (!candidates.isEmpty()) { Symbol *s = candidates.takeFirst(); openCppEditorAt(s->fileName(), s->line(), s->column()); } #endif } } else { // Handle macro uses const Document::MacroUse *use = doc->findMacroUseAt(endOfToken - 1); if (use) { const Macro &macro = use->macro(); link.fileName = macro.fileName(); link.line = macro.line(); link.begin = use->begin(); link.end = use->end(); return link; } } return link; } void CPPEditor::jumpToDefinition() { openLink(findLinkAt(textCursor())); } Symbol *CPPEditor::findDefinition(Symbol *symbol, const Snapshot &snapshot) { if (symbol->isFunction()) return 0; // symbol is a function definition. else if (! symbol->type()->isFunctionType()) return 0; // not a function declaration return snapshot.findMatchingDefinition(symbol); } unsigned CPPEditor::editorRevision() const { return document()->revision(); } bool CPPEditor::isOutdated() const { if (m_lastSemanticInfo.revision != editorRevision()) return true; return false; } SemanticInfo CPPEditor::semanticInfo() const { return m_lastSemanticInfo; } CPlusPlus::OverviewModel *CPPEditor::outlineModel() const { return m_outlineModel; } QModelIndex CPPEditor::outlineModelIndex() { if (!m_outlineModelIndex.isValid()) { int line = 0, column = 0; convertPosition(position(), &line, &column); m_outlineModelIndex = indexForPosition(line, column); emit outlineModelIndexChanged(m_outlineModelIndex); } return m_outlineModelIndex; } bool CPPEditor::isElectricCharacter(QChar ch) const { if (ch == QLatin1Char('{') || ch == QLatin1Char('}') || ch == QLatin1Char(':') || ch == QLatin1Char('#')) { return true; } return false; } QString CPPEditor::insertMatchingBrace(const QTextCursor &tc, const QString &text, QChar la, int *skippedChars) const { MatchingText m; return m.insertMatchingBrace(tc, text, la, skippedChars); } QString CPPEditor::insertParagraphSeparator(const QTextCursor &tc) const { MatchingText m; return m.insertParagraphSeparator(tc); } bool CPPEditor::contextAllowsAutoParentheses(const QTextCursor &cursor, const QString &textToInsert) const { QChar ch; if (! textToInsert.isEmpty()) ch = textToInsert.at(0); if (! (MatchingText::shouldInsertMatchingText(cursor) || ch == QLatin1Char('\'') || ch == QLatin1Char('"'))) return false; else if (isInComment(cursor)) return false; return true; } bool CPPEditor::contextAllowsElectricCharacters(const QTextCursor &cursor) const { const Token tk = SimpleLexer::tokenAt(cursor.block().text(), cursor.positionInBlock(), BackwardsScanner::previousBlockState(cursor.block())); // XXX Duplicated from CPPEditor::isInComment to avoid tokenizing twice if (tk.isComment()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos == tk.end()) { if (tk.is(T_CPP_COMMENT) || tk.is(T_CPP_DOXY_COMMENT)) return false; const int state = cursor.block().userState() & 0xFF; if (state > 0) return false; } if (pos < tk.end()) return false; } else if (tk.is(T_STRING_LITERAL) || tk.is(T_WIDE_STRING_LITERAL) || tk.is(T_CHAR_LITERAL) || tk.is(T_WIDE_CHAR_LITERAL)) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos <= tk.end()) return false; } return true; } bool CPPEditor::isInComment(const QTextCursor &cursor) const { const Token tk = SimpleLexer::tokenAt(cursor.block().text(), cursor.positionInBlock(), BackwardsScanner::previousBlockState(cursor.block())); if (tk.isComment()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos == tk.end()) { if (tk.is(T_CPP_COMMENT) || tk.is(T_CPP_DOXY_COMMENT)) return true; const int state = cursor.block().userState() & 0xFF; if (state > 0) return true; } if (pos < tk.end()) return true; } return false; } void CPPEditor::indentBlock(QTextDocument *doc, QTextBlock block, QChar typedChar) { Q_UNUSED(doc) Q_UNUSED(typedChar) const TabSettings &ts = tabSettings(); CppTools::QtStyleCodeFormatter codeFormatter(ts); codeFormatter.updateStateUntil(block); const int depth = codeFormatter.indentFor(block); ts.indentLine(block, depth); } void CPPEditor::indent(QTextDocument *doc, const QTextCursor &cursor, QChar typedChar) { Q_UNUSED(doc) Q_UNUSED(typedChar) maybeClearSomeExtraSelections(cursor); if (cursor.hasSelection()) { QTextBlock block = doc->findBlock(cursor.selectionStart()); const QTextBlock end = doc->findBlock(cursor.selectionEnd()).next(); const TabSettings &ts = tabSettings(); CppTools::QtStyleCodeFormatter codeFormatter(ts); codeFormatter.updateStateUntil(block); QTextCursor tc = textCursor(); tc.beginEditBlock(); do { ts.indentLine(block, codeFormatter.indentFor(block)); codeFormatter.updateLineStateChange(block); block = block.next(); } while (block.isValid() && block != end); tc.endEditBlock(); } else { indentBlock(doc, cursor.block(), typedChar); } } bool CPPEditor::event(QEvent *e) { switch (e->type()) { case QEvent::ShortcutOverride: if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape && m_currentRenameSelection != NoCurrentRenameSelection) { e->accept(); return true; } break; default: break; } return BaseTextEditor::event(e); } void CPPEditor::performQuickFix(int index) { TextEditor::QuickFixOperation::Ptr op = m_quickFixes.at(index); op->perform(); } void CPPEditor::contextMenuEvent(QContextMenuEvent *e) { // ### enable // updateSemanticInfo(m_semanticHighlighter->semanticInfo(currentSource())); QMenu *menu = new QMenu; Core::ActionManager *am = Core::ICore::instance()->actionManager(); Core::ActionContainer *mcontext = am->actionContainer(CppEditor::Constants::M_CONTEXT); QMenu *contextMenu = mcontext->menu(); CppQuickFixCollector *quickFixCollector = CppPlugin::instance()->quickFixCollector(); QSignalMapper mapper; connect(&mapper, SIGNAL(mapped(int)), this, SLOT(performQuickFix(int))); if (! isOutdated()) { if (quickFixCollector->startCompletion(editableInterface()) != -1) { m_quickFixes = quickFixCollector->quickFixes(); for (int index = 0; index < m_quickFixes.size(); ++index) { TextEditor::QuickFixOperation::Ptr op = m_quickFixes.at(index); QAction *action = menu->addAction(op->description()); mapper.setMapping(action, index); connect(action, SIGNAL(triggered()), &mapper, SLOT(map())); } if (! m_quickFixes.isEmpty()) menu->addSeparator(); } } foreach (QAction *action, contextMenu->actions()) menu->addAction(action); appendStandardContextMenuActions(menu); menu->exec(e->globalPos()); quickFixCollector->cleanup(); m_quickFixes.clear(); delete menu; } void CPPEditor::keyPressEvent(QKeyEvent *e) { if (m_currentRenameSelection == NoCurrentRenameSelection) { TextEditor::BaseTextEditor::keyPressEvent(e); return; } QTextCursor cursor = textCursor(); const QTextCursor::MoveMode moveMode = (e->modifiers() & Qt::ShiftModifier) ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Escape: abortRename(); e->accept(); return; case Qt::Key_Home: { // Send home to start of name when within the name and not at the start if (cursor.position() > m_currentRenameSelectionBegin.position() && cursor.position() <= m_currentRenameSelectionEnd.position()) { cursor.setPosition(m_currentRenameSelectionBegin.position(), moveMode); setTextCursor(cursor); e->accept(); return; } break; } case Qt::Key_End: { // Send end to end of name when within the name and not at the end if (cursor.position() >= m_currentRenameSelectionBegin.position() && cursor.position() < m_currentRenameSelectionEnd.position()) { cursor.setPosition(m_currentRenameSelectionEnd.position(), moveMode); setTextCursor(cursor); e->accept(); return; } break; } case Qt::Key_Backspace: { if (cursor.position() == m_currentRenameSelectionBegin.position() && !cursor.hasSelection()) { // Eat backspace at start of name when there is no selection e->accept(); return; } break; } case Qt::Key_Delete: { if (cursor.position() == m_currentRenameSelectionEnd.position() && !cursor.hasSelection()) { // Eat delete at end of name when there is no selection e->accept(); return; } break; } default: { break; } } // switch startRename(); bool wantEditBlock = (cursor.position() >= m_currentRenameSelectionBegin.position() && cursor.position() <= m_currentRenameSelectionEnd.position()); if (wantEditBlock) { // possible change inside rename selection if (m_firstRenameChange) cursor.beginEditBlock(); else cursor.joinPreviousEditBlock(); m_firstRenameChange = false; } TextEditor::BaseTextEditor::keyPressEvent(e); if (wantEditBlock) cursor.endEditBlock(); finishRename(); } Core::Context CPPEditorEditable::context() const { return m_context; } Core::IEditor *CPPEditorEditable::duplicate(QWidget *parent) { CPPEditor *newEditor = new CPPEditor(parent); newEditor->duplicateFrom(editor()); CppPlugin::instance()->initializeEditor(newEditor); return newEditor->editableInterface(); } QString CPPEditorEditable::id() const { return QLatin1String(CppEditor::Constants::CPPEDITOR_ID); } bool CPPEditorEditable::open(const QString & fileName) { bool b = TextEditor::BaseTextEditorEditable::open(fileName); editor()->setMimeType(Core::ICore::instance()->mimeDatabase()->findByFile(QFileInfo(fileName)).type()); return b; } void CPPEditor::setFontSettings(const TextEditor::FontSettings &fs) { TextEditor::BaseTextEditor::setFontSettings(fs); CppHighlighter *highlighter = qobject_cast<CppHighlighter*>(baseTextDocument()->syntaxHighlighter()); if (!highlighter) return; static QVector<QString> categories; if (categories.isEmpty()) { categories << QLatin1String(TextEditor::Constants::C_NUMBER) << QLatin1String(TextEditor::Constants::C_STRING) << QLatin1String(TextEditor::Constants::C_TYPE) << QLatin1String(TextEditor::Constants::C_KEYWORD) << QLatin1String(TextEditor::Constants::C_OPERATOR) << QLatin1String(TextEditor::Constants::C_PREPROCESSOR) << QLatin1String(TextEditor::Constants::C_LABEL) << QLatin1String(TextEditor::Constants::C_COMMENT) << QLatin1String(TextEditor::Constants::C_DOXYGEN_COMMENT) << QLatin1String(TextEditor::Constants::C_DOXYGEN_TAG) << QLatin1String(TextEditor::Constants::C_VISUAL_WHITESPACE); } const QVector<QTextCharFormat> formats = fs.toTextCharFormats(categories); highlighter->setFormats(formats.constBegin(), formats.constEnd()); m_occurrencesFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES)); m_occurrencesUnusedFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES_UNUSED)); m_occurrencesUnusedFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline); m_occurrencesUnusedFormat.setUnderlineColor(m_occurrencesUnusedFormat.foreground().color()); m_occurrencesUnusedFormat.clearForeground(); m_occurrencesUnusedFormat.setToolTip(tr("Unused variable")); m_occurrenceRenameFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES_RENAME)); m_typeFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_TYPE)); m_localFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_LOCAL)); m_fieldFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_FIELD)); m_staticFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_STATIC)); m_virtualMethodFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_VIRTUAL_METHOD)); m_keywordFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_KEYWORD)); // only set the background, we do not want to modify foreground properties set by the syntax highlighter or the link m_occurrencesFormat.clearForeground(); m_occurrenceRenameFormat.clearForeground(); // Clear all additional formats since they may have changed QTextBlock b = document()->firstBlock(); while (b.isValid()) { highlighter->setExtraAdditionalFormats(b, QList<QTextLayout::FormatRange>()); b = b.next(); } // This also triggers an update of the additional formats highlighter->rehighlight(); } void CPPEditor::setTabSettings(const TextEditor::TabSettings &ts) { CppTools::QtStyleCodeFormatter formatter; formatter.invalidateCache(document()); TextEditor::BaseTextEditor::setTabSettings(ts); } void CPPEditor::unCommentSelection() { Utils::unCommentSelection(this); } CPPEditor::Link CPPEditor::linkToSymbol(CPlusPlus::Symbol *symbol) { if (!symbol) return Link(); const QString fileName = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength()); unsigned line = symbol->line(); unsigned column = symbol->column(); if (column) --column; if (symbol->isGenerated()) column = 0; return Link(fileName, line, column); } bool CPPEditor::openCppEditorAt(const Link &link) { if (link.fileName.isEmpty()) return false; if (baseTextDocument()->fileName() == link.fileName) { Core::EditorManager *editorManager = Core::EditorManager::instance(); editorManager->cutForwardNavigationHistory(); editorManager->addCurrentPositionToNavigationHistory(); gotoLine(link.line, link.column); setFocus(); return true; } return TextEditor::BaseTextEditor::openEditorAt(link.fileName, link.line, link.column, Constants::CPPEDITOR_ID); } void CPPEditor::semanticRehighlight() { m_semanticHighlighter->rehighlight(currentSource()); } void CPPEditor::updateSemanticInfo(const SemanticInfo &semanticInfo) { if (semanticInfo.revision != editorRevision()) { // got outdated semantic info semanticRehighlight(); return; } const SemanticInfo previousSemanticInfo = m_lastSemanticInfo; m_lastSemanticInfo = semanticInfo; // update the semantic info int line = 0, column = 0; convertPosition(position(), &line, &column); QList<QTextEdit::ExtraSelection> unusedSelections; m_renameSelections.clear(); m_currentRenameSelection = NoCurrentRenameSelection; SemanticInfo::LocalUseIterator it(semanticInfo.localUses); while (it.hasNext()) { it.next(); const QList<SemanticInfo::Use> &uses = it.value(); bool good = false; foreach (const SemanticInfo::Use &use, uses) { unsigned l = line; unsigned c = column + 1; // convertCursorPosition() returns a 0-based column number. if (l == use.line && c >= use.column && c <= (use.column + use.length)) { good = true; break; } } if (uses.size() == 1) // it's an unused declaration highlightUses(uses, semanticInfo, &unusedSelections); else if (good && m_renameSelections.isEmpty()) highlightUses(uses, semanticInfo, &m_renameSelections); } if (m_lastSemanticInfo.forced || previousSemanticInfo.revision != semanticInfo.revision) { QTextCharFormat diagnosticMessageFormat; diagnosticMessageFormat.setUnderlineColor(Qt::darkYellow); // ### hardcoded diagnosticMessageFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline); // ### hardcoded setExtraSelections(UndefinedSymbolSelection, createSelections(document(), semanticInfo.diagnosticMessages, diagnosticMessageFormat)); m_highlighter.cancel(); if (semanticInfo.doc) { LookupContext context(semanticInfo.doc, semanticInfo.snapshot); CheckSymbols::Future f = CheckSymbols::go(semanticInfo.doc, context); m_highlighter = f; m_highlightRevision = semanticInfo.revision; m_nextHighlightBlockNumber = 0; m_highlightWatcher.setFuture(m_highlighter); } #if 0 // ### TODO: enable objc semantic highlighting setExtraSelections(ObjCSelection, createSelections(document(), semanticInfo.objcKeywords, m_keywordFormat)); #endif } setExtraSelections(UnusedSymbolSelection, unusedSelections); if (! m_renameSelections.isEmpty()) setExtraSelections(CodeSemanticsSelection, m_renameSelections); // ### else { markSymbols(textCursor(), semanticInfo); } m_lastSemanticInfo.forced = false; // clear the forced flag } namespace { class FindObjCKeywords: public ASTVisitor { public: FindObjCKeywords(TranslationUnit *unit) : ASTVisitor(unit) {} QList<SemanticInfo::Use> operator()() { _keywords.clear(); accept(translationUnit()->ast()); return _keywords; } virtual bool visit(ObjCClassDeclarationAST *ast) { addToken(ast->interface_token); addToken(ast->implementation_token); addToken(ast->end_token); return true; } virtual bool visit(ObjCClassForwardDeclarationAST *ast) { addToken(ast->class_token); return true; } virtual bool visit(ObjCProtocolDeclarationAST *ast) { addToken(ast->protocol_token); addToken(ast->end_token); return true; } virtual bool visit(ObjCProtocolForwardDeclarationAST *ast) { addToken(ast->protocol_token); return true; } virtual bool visit(ObjCProtocolExpressionAST *ast) { addToken(ast->protocol_token); return true; } virtual bool visit(ObjCTypeNameAST *) { return true; } virtual bool visit(ObjCEncodeExpressionAST *ast) { addToken(ast->encode_token); return true; } virtual bool visit(ObjCSelectorExpressionAST *ast) { addToken(ast->selector_token); return true; } virtual bool visit(ObjCVisibilityDeclarationAST *ast) { addToken(ast->visibility_token); return true; } virtual bool visit(ObjCPropertyAttributeAST *ast) { const Identifier *attrId = identifier(ast->attribute_identifier_token); if (attrId == control()->objcAssignId() || attrId == control()->objcCopyId() || attrId == control()->objcGetterId() || attrId == control()->objcNonatomicId() || attrId == control()->objcReadonlyId() || attrId == control()->objcReadwriteId() || attrId == control()->objcRetainId() || attrId == control()->objcSetterId()) addToken(ast->attribute_identifier_token); return true; } virtual bool visit(ObjCPropertyDeclarationAST *ast) { addToken(ast->property_token); return true; } virtual bool visit(ObjCSynthesizedPropertiesDeclarationAST *ast) { addToken(ast->synthesized_token); return true; } virtual bool visit(ObjCDynamicPropertiesDeclarationAST *ast) { addToken(ast->dynamic_token); return true; } virtual bool visit(ObjCFastEnumerationAST *ast) { addToken(ast->for_token); addToken(ast->in_token); return true; } virtual bool visit(ObjCSynchronizedStatementAST *ast) { addToken(ast->synchronized_token); return true; } protected: void addToken(unsigned token) { if (token) { SemanticInfo::Use use; getTokenStartPosition(token, &use.line, &use.column); use.length = tokenAt(token).length(); _keywords.append(use); } } private: QList<SemanticInfo::Use> _keywords; }; } // anonymous namespace SemanticHighlighter::Source CPPEditor::currentSource(bool force) { int line = 0, column = 0; convertPosition(position(), &line, &column); const Snapshot snapshot = m_modelManager->snapshot(); const QString fileName = file()->fileName(); QString code; if (force || m_lastSemanticInfo.revision != editorRevision()) code = toPlainText(); // get the source code only when needed. const unsigned revision = editorRevision(); SemanticHighlighter::Source source(snapshot, fileName, code, line, column, revision); source.force = force; return source; } SemanticHighlighter::SemanticHighlighter(QObject *parent) : QThread(parent), m_done(false) { } SemanticHighlighter::~SemanticHighlighter() { } void SemanticHighlighter::abort() { QMutexLocker locker(&m_mutex); m_done = true; m_condition.wakeOne(); } void SemanticHighlighter::rehighlight(const Source &source) { QMutexLocker locker(&m_mutex); m_source = source; m_condition.wakeOne(); } bool SemanticHighlighter::isOutdated() { QMutexLocker locker(&m_mutex); const bool outdated = ! m_source.fileName.isEmpty() || m_done; return outdated; } void SemanticHighlighter::run() { setPriority(QThread::LowestPriority); forever { m_mutex.lock(); while (! (m_done || ! m_source.fileName.isEmpty())) m_condition.wait(&m_mutex); const bool done = m_done; const Source source = m_source; m_source.clear(); m_mutex.unlock(); if (done) break; const SemanticInfo info = semanticInfo(source); if (! isOutdated()) { m_mutex.lock(); m_lastSemanticInfo = info; m_mutex.unlock(); emit changed(info); } } } SemanticInfo SemanticHighlighter::semanticInfo(const Source &source) { m_mutex.lock(); const int revision = m_lastSemanticInfo.revision; m_mutex.unlock(); Snapshot snapshot; Document::Ptr doc; QList<Document::DiagnosticMessage> diagnosticMessages; QList<SemanticInfo::Use> objcKeywords; if (! source.force && revision == source.revision) { m_mutex.lock(); snapshot = m_lastSemanticInfo.snapshot; // ### TODO: use the new snapshot. doc = m_lastSemanticInfo.doc; diagnosticMessages = m_lastSemanticInfo.diagnosticMessages; objcKeywords = m_lastSemanticInfo.objcKeywords; m_mutex.unlock(); } if (! doc) { snapshot = source.snapshot; const QByteArray preprocessedCode = snapshot.preprocessedCode(source.code, source.fileName); doc = snapshot.documentFromSource(preprocessedCode, source.fileName); doc->check(); #if 0 if (TranslationUnit *unit = doc->translationUnit()) { FindObjCKeywords findObjCKeywords(unit); // ### remove me objcKeywords = findObjCKeywords(); } #endif } TranslationUnit *translationUnit = doc->translationUnit(); AST *ast = translationUnit->ast(); FunctionDefinitionUnderCursor functionDefinitionUnderCursor(translationUnit); DeclarationAST *currentFunctionDefinition = functionDefinitionUnderCursor(ast, source.line, source.column); const LocalSymbols useTable(doc, currentFunctionDefinition); SemanticInfo semanticInfo; semanticInfo.revision = source.revision; semanticInfo.snapshot = snapshot; semanticInfo.doc = doc; semanticInfo.localUses = useTable.uses; semanticInfo.hasQ = useTable.hasQ; semanticInfo.hasD = useTable.hasD; semanticInfo.forced = source.force; semanticInfo.diagnosticMessages = diagnosticMessages; semanticInfo.objcKeywords = objcKeywords; return semanticInfo; } QModelIndex CPPEditor::indexForPosition(int line, int column, const QModelIndex &rootIndex) const { QModelIndex lastIndex = rootIndex; const int rowCount = m_outlineModel->rowCount(rootIndex); for (int row = 0; row < rowCount; ++row) { const QModelIndex index = m_outlineModel->index(row, 0, rootIndex); Symbol *symbol = m_outlineModel->symbolFromIndex(index); if (symbol && symbol->line() > unsigned(line)) break; lastIndex = index; } if (lastIndex != rootIndex) { // recurse lastIndex = indexForPosition(line, column, lastIndex); } return lastIndex; } #include "cppeditor.moc" Check the editormanager's current document before to request a new highlight. /************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "cppeditor.h" #include "cppeditorconstants.h" #include "cppplugin.h" #include "cpphighlighter.h" #include "cppchecksymbols.h" #include "cppquickfix.h" #include "cpplocalsymbols.h" #include <AST.h> #include <Control.h> #include <Token.h> #include <Scope.h> #include <Symbols.h> #include <Names.h> #include <CoreTypes.h> #include <Literals.h> #include <ASTVisitor.h> #include <SymbolVisitor.h> #include <TranslationUnit.h> #include <cplusplus/ExpressionUnderCursor.h> #include <cplusplus/TypeOfExpression.h> #include <cplusplus/Overview.h> #include <cplusplus/OverviewModel.h> #include <cplusplus/SimpleLexer.h> #include <cplusplus/MatchingText.h> #include <cplusplus/BackwardsScanner.h> #include <cplusplus/FastPreprocessor.h> #include <cpptools/cpptoolsplugin.h> #include <cpptools/cppmodelmanagerinterface.h> #include <cpptools/cpptoolsconstants.h> #include <cpptools/cppcodeformatter.h> #include <coreplugin/icore.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/mimedatabase.h> #include <utils/uncommentselection.h> #include <extensionsystem/pluginmanager.h> #include <projectexplorer/projectexplorerconstants.h> #include <texteditor/basetextdocument.h> #include <texteditor/fontsettings.h> #include <texteditor/texteditorconstants.h> #include <QtCore/QDebug> #include <QtCore/QTime> #include <QtCore/QTimer> #include <QtCore/QStack> #include <QtCore/QSettings> #include <QtCore/QSignalMapper> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QHeaderView> #include <QtGui/QLayout> #include <QtGui/QMenu> #include <QtGui/QShortcut> #include <QtGui/QTextEdit> #include <QtGui/QComboBox> #include <QtGui/QToolBar> #include <QtGui/QTreeView> #include <QtGui/QSortFilterProxyModel> #include <sstream> enum { UPDATE_OUTLINE_INTERVAL = 500, UPDATE_USES_INTERVAL = 500 }; using namespace CPlusPlus; using namespace CppEditor::Internal; static QList<QTextEdit::ExtraSelection> createSelections(QTextDocument *document, const QList<CPlusPlus::Document::DiagnosticMessage> &msgs, const QTextCharFormat &format) { QList<QTextEdit::ExtraSelection> selections; foreach (const Document::DiagnosticMessage &m, msgs) { const int pos = document->findBlockByNumber(m.line() - 1).position() + m.column() - 1; if (pos < 0) continue; QTextCursor cursor(document); cursor.setPosition(pos); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, m.length()); QTextEdit::ExtraSelection sel; sel.cursor = cursor; sel.format = format; sel.format.setToolTip(m.text()); selections.append(sel); } return selections; } namespace { class OverviewTreeView : public QTreeView { public: OverviewTreeView(QWidget *parent = 0) : QTreeView(parent) { // TODO: Disable the root for all items (with a custom delegate?) setRootIsDecorated(false); } void sync() { expandAll(); setMinimumWidth(qMax(sizeHintForColumn(0), minimumSizeHint().width())); } }; class OverviewProxyModel : public QSortFilterProxyModel { Q_OBJECT public: OverviewProxyModel(CPlusPlus::OverviewModel *sourceModel, QObject *parent) : QSortFilterProxyModel(parent), m_sourceModel(sourceModel) { setSourceModel(m_sourceModel); } bool filterAcceptsRow(int sourceRow,const QModelIndex &sourceParent) const { // ignore generated symbols, e.g. by macro expansion (Q_OBJECT) const QModelIndex sourceIndex = m_sourceModel->index(sourceRow, 0, sourceParent); CPlusPlus::Symbol *symbol = m_sourceModel->symbolFromIndex(sourceIndex); if (symbol && symbol->isGenerated()) return false; return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); } private: CPlusPlus::OverviewModel *m_sourceModel; }; class FunctionDefinitionUnderCursor: protected ASTVisitor { unsigned _line; unsigned _column; DeclarationAST *_functionDefinition; public: FunctionDefinitionUnderCursor(TranslationUnit *translationUnit) : ASTVisitor(translationUnit), _line(0), _column(0) { } DeclarationAST *operator()(AST *ast, unsigned line, unsigned column) { _functionDefinition = 0; _line = line; _column = column; accept(ast); return _functionDefinition; } protected: virtual bool preVisit(AST *ast) { if (_functionDefinition) return false; else if (FunctionDefinitionAST *def = ast->asFunctionDefinition()) { return checkDeclaration(def); } else if (ObjCMethodDeclarationAST *method = ast->asObjCMethodDeclaration()) { if (method->function_body) return checkDeclaration(method); } return true; } private: bool checkDeclaration(DeclarationAST *ast) { unsigned startLine, startColumn; unsigned endLine, endColumn; getTokenStartPosition(ast->firstToken(), &startLine, &startColumn); getTokenEndPosition(ast->lastToken() - 1, &endLine, &endColumn); if (_line > startLine || (_line == startLine && _column >= startColumn)) { if (_line < endLine || (_line == endLine && _column < endColumn)) { _functionDefinition = ast; return false; } } return true; } }; class FindFunctionDefinitions: protected SymbolVisitor { const Name *_declarationName; QList<Function *> *_functions; public: FindFunctionDefinitions() : _declarationName(0), _functions(0) { } void operator()(const Name *declarationName, Scope *globals, QList<Function *> *functions) { _declarationName = declarationName; _functions = functions; for (unsigned i = 0; i < globals->memberCount(); ++i) { accept(globals->memberAt(i)); } } protected: using SymbolVisitor::visit; virtual bool visit(Function *function) { const Name *name = function->name(); if (const QualifiedNameId *q = name->asQualifiedNameId()) name = q->name(); if (_declarationName->isEqualTo(name)) _functions->append(function); return false; } }; struct CanonicalSymbol { CPPEditor *editor; TypeOfExpression typeOfExpression; SemanticInfo info; CanonicalSymbol(CPPEditor *editor, const SemanticInfo &info) : editor(editor), info(info) { typeOfExpression.init(info.doc, info.snapshot); } const LookupContext &context() const { return typeOfExpression.context(); } static inline bool isIdentifierChar(const QChar &ch) { return ch.isLetterOrNumber() || ch == QLatin1Char('_'); } Scope *getScopeAndExpression(const QTextCursor &cursor, QString *code) { return getScopeAndExpression(editor, info, cursor, code); } static Scope *getScopeAndExpression(CPPEditor *editor, const SemanticInfo &info, const QTextCursor &cursor, QString *code) { if (! info.doc) return 0; QTextCursor tc = cursor; int line, col; editor->convertPosition(tc.position(), &line, &col); ++col; // 1-based line and 1-based column QTextDocument *document = editor->document(); int pos = tc.position(); if (! isIdentifierChar(document->characterAt(pos))) if (! (pos > 0 && isIdentifierChar(document->characterAt(pos - 1)))) return 0; while (isIdentifierChar(document->characterAt(pos))) ++pos; tc.setPosition(pos); ExpressionUnderCursor expressionUnderCursor; *code = expressionUnderCursor(tc); return info.doc->scopeAt(line, col); } Symbol *operator()(const QTextCursor &cursor) { QString code; if (Scope *scope = getScopeAndExpression(cursor, &code)) return operator()(scope, code); return 0; } Symbol *operator()(Scope *scope, const QString &code) { return canonicalSymbol(scope, code, typeOfExpression); } static Symbol *canonicalSymbol(Scope *scope, const QString &code, TypeOfExpression &typeOfExpression) { const QList<LookupItem> results = typeOfExpression(code, scope, TypeOfExpression::Preprocess); for (int i = results.size() - 1; i != -1; --i) { const LookupItem &r = results.at(i); Symbol *decl = r.declaration(); if (! (decl && decl->scope())) break; if (Class *classScope = r.declaration()->scope()->asClass()) { const Identifier *declId = decl->identifier(); const Identifier *classId = classScope->identifier(); if (classId && classId->isEqualTo(declId)) continue; // skip it, it's a ctor or a dtor. else if (Function *funTy = r.declaration()->type()->asFunctionType()) { if (funTy->isVirtual()) return r.declaration(); } } } for (int i = 0; i < results.size(); ++i) { const LookupItem &r = results.at(i); if (r.declaration()) return r.declaration(); } return 0; } }; } // end of anonymous namespace CPPEditorEditable::CPPEditorEditable(CPPEditor *editor) : BaseTextEditorEditable(editor) { m_context.add(CppEditor::Constants::C_CPPEDITOR); m_context.add(ProjectExplorer::Constants::LANG_CXX); m_context.add(TextEditor::Constants::C_TEXTEDITOR); } CPPEditor::CPPEditor(QWidget *parent) : TextEditor::BaseTextEditor(parent) , m_currentRenameSelection(NoCurrentRenameSelection) , m_inRename(false) , m_inRenameChanged(false) , m_firstRenameChange(false) , m_objcEnabled(false) { m_initialized = false; qRegisterMetaType<CppEditor::Internal::SemanticInfo>("CppEditor::Internal::SemanticInfo"); m_semanticHighlighter = new SemanticHighlighter(this); m_semanticHighlighter->start(); setParenthesesMatchingEnabled(true); setMarksVisible(true); setCodeFoldingSupported(true); setCodeFoldingVisible(true); baseTextDocument()->setSyntaxHighlighter(new CppHighlighter); m_modelManager = CppTools::CppModelManagerInterface::instance(); if (m_modelManager) { connect(m_modelManager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)), this, SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr))); } m_highlightRevision = 0; m_nextHighlightBlockNumber = 0; connect(&m_highlightWatcher, SIGNAL(resultsReadyAt(int,int)), SLOT(highlightSymbolUsages(int,int))); connect(&m_highlightWatcher, SIGNAL(finished()), SLOT(finishHighlightSymbolUsages())); m_referencesRevision = 0; m_referencesCursorPosition = 0; connect(&m_referencesWatcher, SIGNAL(finished()), SLOT(markSymbolsNow())); } CPPEditor::~CPPEditor() { Core::EditorManager::instance()->hideEditorInfoBar(QLatin1String("CppEditor.Rename")); m_semanticHighlighter->abort(); m_semanticHighlighter->wait(); } TextEditor::BaseTextEditorEditable *CPPEditor::createEditableInterface() { CPPEditorEditable *editable = new CPPEditorEditable(this); createToolBar(editable); return editable; } void CPPEditor::createToolBar(CPPEditorEditable *editable) { m_outlineCombo = new QComboBox; m_outlineCombo->setMinimumContentsLength(22); // Make the combo box prefer to expand QSizePolicy policy = m_outlineCombo->sizePolicy(); policy.setHorizontalPolicy(QSizePolicy::Expanding); m_outlineCombo->setSizePolicy(policy); QTreeView *outlineView = new OverviewTreeView; outlineView->header()->hide(); outlineView->setItemsExpandable(false); m_outlineCombo->setView(outlineView); m_outlineCombo->setMaxVisibleItems(20); m_outlineModel = new OverviewModel(this); m_proxyModel = new OverviewProxyModel(m_outlineModel, this); if (CppPlugin::instance()->sortedOutline()) m_proxyModel->sort(0, Qt::AscendingOrder); else m_proxyModel->sort(-1, Qt::AscendingOrder); // don't sort yet, but set column for sortedOutline() m_proxyModel->setDynamicSortFilter(true); m_proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_outlineCombo->setModel(m_proxyModel); m_outlineCombo->setContextMenuPolicy(Qt::ActionsContextMenu); m_sortAction = new QAction(tr("Sort Alphabetically"), m_outlineCombo); m_sortAction->setCheckable(true); m_sortAction->setChecked(sortedOutline()); connect(m_sortAction, SIGNAL(toggled(bool)), CppPlugin::instance(), SLOT(setSortedOutline(bool))); m_outlineCombo->addAction(m_sortAction); m_updateOutlineTimer = new QTimer(this); m_updateOutlineTimer->setSingleShot(true); m_updateOutlineTimer->setInterval(UPDATE_OUTLINE_INTERVAL); connect(m_updateOutlineTimer, SIGNAL(timeout()), this, SLOT(updateOutlineNow())); m_updateOutlineIndexTimer = new QTimer(this); m_updateOutlineIndexTimer->setSingleShot(true); m_updateOutlineIndexTimer->setInterval(UPDATE_OUTLINE_INTERVAL); connect(m_updateOutlineIndexTimer, SIGNAL(timeout()), this, SLOT(updateOutlineIndexNow())); m_updateUsesTimer = new QTimer(this); m_updateUsesTimer->setSingleShot(true); m_updateUsesTimer->setInterval(UPDATE_USES_INTERVAL); connect(m_updateUsesTimer, SIGNAL(timeout()), this, SLOT(updateUsesNow())); connect(m_outlineCombo, SIGNAL(activated(int)), this, SLOT(jumpToOutlineElement(int))); connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateOutlineIndex())); connect(m_outlineCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(updateOutlineToolTip())); connect(document(), SIGNAL(contentsChange(int,int,int)), this, SLOT(onContentsChanged(int,int,int))); connect(file(), SIGNAL(changed()), this, SLOT(updateFileName())); // set up the semantic highlighter connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateUses())); connect(this, SIGNAL(textChanged()), this, SLOT(updateUses())); connect(m_semanticHighlighter, SIGNAL(changed(CppEditor::Internal::SemanticInfo)), this, SLOT(updateSemanticInfo(CppEditor::Internal::SemanticInfo))); QToolBar *toolBar = static_cast<QToolBar*>(editable->toolBar()); QList<QAction*> actions = toolBar->actions(); QWidget *w = toolBar->widgetForAction(actions.first()); static_cast<QHBoxLayout*>(w->layout())->insertWidget(0, m_outlineCombo, 1); } void CPPEditor::paste() { if (m_currentRenameSelection == NoCurrentRenameSelection) { BaseTextEditor::paste(); return; } startRename(); BaseTextEditor::paste(); finishRename(); } void CPPEditor::cut() { if (m_currentRenameSelection == NoCurrentRenameSelection) { BaseTextEditor::cut(); return; } startRename(); BaseTextEditor::cut(); finishRename(); } CppTools::CppModelManagerInterface *CPPEditor::modelManager() const { return m_modelManager; } void CPPEditor::setMimeType(const QString &mt) { BaseTextEditor::setMimeType(mt); setObjCEnabled(mt == CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE); } void CPPEditor::setObjCEnabled(bool onoff) { m_objcEnabled = onoff; } bool CPPEditor::isObjCEnabled() const { return m_objcEnabled; } void CPPEditor::startRename() { m_inRenameChanged = false; } void CPPEditor::finishRename() { if (!m_inRenameChanged) return; m_inRename = true; QTextCursor cursor = textCursor(); cursor.joinPreviousEditBlock(); cursor.setPosition(m_currentRenameSelectionEnd.position()); cursor.setPosition(m_currentRenameSelectionBegin.position(), QTextCursor::KeepAnchor); m_renameSelections[m_currentRenameSelection].cursor = cursor; QString text = cursor.selectedText(); for (int i = 0; i < m_renameSelections.size(); ++i) { if (i == m_currentRenameSelection) continue; QTextEdit::ExtraSelection &s = m_renameSelections[i]; int pos = s.cursor.selectionStart(); s.cursor.removeSelectedText(); s.cursor.insertText(text); s.cursor.setPosition(pos, QTextCursor::KeepAnchor); } setExtraSelections(CodeSemanticsSelection, m_renameSelections); cursor.endEditBlock(); m_inRename = false; } void CPPEditor::abortRename() { if (m_currentRenameSelection <= NoCurrentRenameSelection) return; m_renameSelections[m_currentRenameSelection].format = m_occurrencesFormat; m_currentRenameSelection = NoCurrentRenameSelection; m_currentRenameSelectionBegin = QTextCursor(); m_currentRenameSelectionEnd = QTextCursor(); setExtraSelections(CodeSemanticsSelection, m_renameSelections); } void CPPEditor::rehighlight(bool force) { const SemanticHighlighter::Source source = currentSource(force); m_semanticHighlighter->rehighlight(source); } void CPPEditor::onDocumentUpdated(Document::Ptr doc) { if (doc->fileName() != file()->fileName()) return; if (doc->editorRevision() != editorRevision()) return; if (! m_initialized) { m_initialized = true; rehighlight(/* force = */ true); } m_updateOutlineTimer->start(); } const Macro *CPPEditor::findCanonicalMacro(const QTextCursor &cursor, Document::Ptr doc) const { if (! doc) return 0; int line, col; convertPosition(cursor.position(), &line, &col); if (const Macro *macro = doc->findMacroDefinitionAt(line)) return macro; if (const Document::MacroUse *use = doc->findMacroUseAt(cursor.position())) return &use->macro(); return 0; } void CPPEditor::findUsages() { SemanticInfo info = m_lastSemanticInfo; info.snapshot = CppTools::CppModelManagerInterface::instance()->snapshot(); info.snapshot.insert(info.doc); CanonicalSymbol cs(this, info); Symbol *canonicalSymbol = cs(textCursor()); if (canonicalSymbol) { m_modelManager->findUsages(canonicalSymbol, cs.context()); } else if (const Macro *macro = findCanonicalMacro(textCursor(), info.doc)) { m_modelManager->findMacroUsages(*macro); } } void CPPEditor::renameUsagesNow(const QString &replacement) { SemanticInfo info = m_lastSemanticInfo; info.snapshot = CppTools::CppModelManagerInterface::instance()->snapshot(); info.snapshot.insert(info.doc); CanonicalSymbol cs(this, info); if (Symbol *canonicalSymbol = cs(textCursor())) { if (canonicalSymbol->identifier() != 0) { if (showWarningMessage()) { Core::EditorManager::instance()->showEditorInfoBar(QLatin1String("CppEditor.Rename"), tr("This change cannot be undone."), tr("Yes, I know what I am doing."), this, SLOT(hideRenameNotification())); } m_modelManager->renameUsages(canonicalSymbol, cs.context(), replacement); } } } void CPPEditor::renameUsages() { renameUsagesNow(); } bool CPPEditor::showWarningMessage() const { // Restore settings QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup(QLatin1String("CppEditor")); settings->beginGroup(QLatin1String("Rename")); const bool showWarningMessage = settings->value(QLatin1String("ShowWarningMessage"), true).toBool(); settings->endGroup(); settings->endGroup(); return showWarningMessage; } void CPPEditor::setShowWarningMessage(bool showWarningMessage) { // Restore settings QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup(QLatin1String("CppEditor")); settings->beginGroup(QLatin1String("Rename")); settings->setValue(QLatin1String("ShowWarningMessage"), showWarningMessage); settings->endGroup(); settings->endGroup(); } void CPPEditor::hideRenameNotification() { setShowWarningMessage(false); Core::EditorManager::instance()->hideEditorInfoBar(QLatin1String("CppEditor.Rename")); } void CPPEditor::markSymbolsNow() { if (m_references.isCanceled()) return; else if (m_referencesCursorPosition != position()) return; else if (m_referencesRevision != editorRevision()) return; const SemanticInfo info = m_lastSemanticInfo; TranslationUnit *unit = info.doc->translationUnit(); const QList<int> result = m_references.result(); QList<QTextEdit::ExtraSelection> selections; foreach (int index, result) { unsigned line, column; unit->getTokenPosition(index, &line, &column); if (column) --column; // adjust the column position. const int len = unit->tokenAt(index).f.length; QTextCursor cursor(document()->findBlockByNumber(line - 1)); cursor.setPosition(cursor.position() + column); cursor.setPosition(cursor.position() + len, QTextCursor::KeepAnchor); QTextEdit::ExtraSelection sel; sel.format = m_occurrencesFormat; sel.cursor = cursor; selections.append(sel); } setExtraSelections(CodeSemanticsSelection, selections); } static QList<int> lazyFindReferences(Scope *scope, QString code, Document::Ptr doc, Snapshot snapshot) { TypeOfExpression typeOfExpression; snapshot.insert(doc); typeOfExpression.init(doc, snapshot); if (Symbol *canonicalSymbol = CanonicalSymbol::canonicalSymbol(scope, code, typeOfExpression)) { return CppTools::CppModelManagerInterface::instance()->references(canonicalSymbol, typeOfExpression.context()); } return QList<int>(); } void CPPEditor::markSymbols(const QTextCursor &tc, const SemanticInfo &info) { abortRename(); if (! info.doc) return; CanonicalSymbol cs(this, info); QString expression; if (Scope *scope = cs.getScopeAndExpression(this, info, tc, &expression)) { m_references.cancel(); m_referencesRevision = info.revision; m_referencesCursorPosition = position(); m_references = QtConcurrent::run(&lazyFindReferences, scope, expression, info.doc, info.snapshot); m_referencesWatcher.setFuture(m_references); } else { const QList<QTextEdit::ExtraSelection> selections = extraSelections(CodeSemanticsSelection); if (! selections.isEmpty()) setExtraSelections(CodeSemanticsSelection, QList<QTextEdit::ExtraSelection>()); } } void CPPEditor::renameSymbolUnderCursor() { updateSemanticInfo(m_semanticHighlighter->semanticInfo(currentSource())); abortRename(); QTextCursor c = textCursor(); for (int i = 0; i < m_renameSelections.size(); ++i) { QTextEdit::ExtraSelection s = m_renameSelections.at(i); if (c.position() >= s.cursor.anchor() && c.position() <= s.cursor.position()) { m_currentRenameSelection = i; m_firstRenameChange = true; m_currentRenameSelectionBegin = QTextCursor(c.document()->docHandle(), m_renameSelections[i].cursor.selectionStart()); m_currentRenameSelectionEnd = QTextCursor(c.document()->docHandle(), m_renameSelections[i].cursor.selectionEnd()); m_renameSelections[i].format = m_occurrenceRenameFormat; setExtraSelections(CodeSemanticsSelection, m_renameSelections); break; } } if (m_renameSelections.isEmpty()) renameUsages(); } void CPPEditor::onContentsChanged(int position, int charsRemoved, int charsAdded) { Q_UNUSED(position) if (m_currentRenameSelection == NoCurrentRenameSelection || m_inRename) return; if (position + charsAdded == m_currentRenameSelectionBegin.position()) { // we are inserting at the beginning of the rename selection => expand m_currentRenameSelectionBegin.setPosition(position); m_renameSelections[m_currentRenameSelection].cursor.setPosition(position, QTextCursor::KeepAnchor); } // the condition looks odd, but keep in mind that the begin and end cursors do move automatically m_inRenameChanged = (position >= m_currentRenameSelectionBegin.position() && position + charsAdded <= m_currentRenameSelectionEnd.position()); if (!m_inRenameChanged) abortRename(); if (charsRemoved > 0) updateUses(); } void CPPEditor::updateFileName() { } void CPPEditor::jumpToOutlineElement(int) { QModelIndex index = m_proxyModel->mapToSource(m_outlineCombo->view()->currentIndex()); Symbol *symbol = m_outlineModel->symbolFromIndex(index); if (! symbol) return; openCppEditorAt(linkToSymbol(symbol)); } void CPPEditor::setSortedOutline(bool sort) { if (sort != sortedOutline()) { if (sort) m_proxyModel->sort(0, Qt::AscendingOrder); else m_proxyModel->sort(-1, Qt::AscendingOrder); bool block = m_sortAction->blockSignals(true); m_sortAction->setChecked(m_proxyModel->sortColumn() == 0); m_sortAction->blockSignals(block); updateOutlineIndexNow(); } } bool CPPEditor::sortedOutline() const { return (m_proxyModel->sortColumn() == 0); } void CPPEditor::updateOutlineNow() { const Snapshot snapshot = m_modelManager->snapshot(); Document::Ptr document = snapshot.document(file()->fileName()); if (!document) return; if (document->editorRevision() != editorRevision()) { m_updateOutlineTimer->start(); return; } m_outlineModel->rebuild(document); OverviewTreeView *treeView = static_cast<OverviewTreeView *>(m_outlineCombo->view()); treeView->sync(); updateOutlineIndexNow(); } void CPPEditor::updateOutlineIndex() { m_updateOutlineIndexTimer->start(); } void CPPEditor::highlightUses(const QList<SemanticInfo::Use> &uses, const SemanticInfo &semanticInfo, QList<QTextEdit::ExtraSelection> *selections) { bool isUnused = false; if (uses.size() == 1) isUnused = true; foreach (const SemanticInfo::Use &use, uses) { QTextEdit::ExtraSelection sel; if (isUnused) sel.format = m_occurrencesUnusedFormat; else sel.format = m_occurrencesFormat; const int anchor = document()->findBlockByNumber(use.line - 1).position() + use.column - 1; const int position = anchor + use.length; sel.cursor = QTextCursor(document()); sel.cursor.setPosition(anchor); sel.cursor.setPosition(position, QTextCursor::KeepAnchor); if (isUnused) { if (semanticInfo.hasQ && sel.cursor.selectedText() == QLatin1String("q")) continue; // skip q else if (semanticInfo.hasD && sel.cursor.selectedText() == QLatin1String("d")) continue; // skip d } selections->append(sel); } } void CPPEditor::updateOutlineIndexNow() { if (!m_outlineModel->document()) return; if (m_outlineModel->document()->editorRevision() != editorRevision()) { m_updateOutlineIndexTimer->start(); return; } m_updateOutlineIndexTimer->stop(); m_outlineModelIndex = QModelIndex(); //invalidate QModelIndex comboIndex = outlineModelIndex(); if (comboIndex.isValid()) { bool blocked = m_outlineCombo->blockSignals(true); // There is no direct way to select a non-root item m_outlineCombo->setRootModelIndex(m_proxyModel->mapFromSource(comboIndex.parent())); m_outlineCombo->setCurrentIndex(m_proxyModel->mapFromSource(comboIndex).row()); m_outlineCombo->setRootModelIndex(QModelIndex()); updateOutlineToolTip(); m_outlineCombo->blockSignals(blocked); } } void CPPEditor::updateOutlineToolTip() { m_outlineCombo->setToolTip(m_outlineCombo->currentText()); } void CPPEditor::updateUses() { if (editorRevision() != m_highlightRevision) m_highlighter.cancel(); m_updateUsesTimer->start(); } void CPPEditor::updateUsesNow() { if (m_currentRenameSelection != NoCurrentRenameSelection) return; semanticRehighlight(); } void CPPEditor::highlightSymbolUsages(int from, int to) { if (editorRevision() != m_highlightRevision) return; // outdated else if (m_highlighter.isCanceled()) return; // aborted CppHighlighter *highlighter = qobject_cast<CppHighlighter*>(baseTextDocument()->syntaxHighlighter()); Q_ASSERT(highlighter); QTextDocument *doc = document(); if (m_nextHighlightBlockNumber >= doc->blockCount()) return; QMap<int, QVector<SemanticInfo::Use> > chunks = CheckSymbols::chunks(m_highlighter, from, to); if (chunks.isEmpty()) return; QTextBlock b = doc->findBlockByNumber(m_nextHighlightBlockNumber); QMapIterator<int, QVector<SemanticInfo::Use> > it(chunks); while (b.isValid() && it.hasNext()) { it.next(); const int blockNumber = it.key(); Q_ASSERT(blockNumber < doc->blockCount()); while (m_nextHighlightBlockNumber < blockNumber) { highlighter->setExtraAdditionalFormats(b, QList<QTextLayout::FormatRange>()); b = b.next(); ++m_nextHighlightBlockNumber; } QList<QTextLayout::FormatRange> formats; foreach (const SemanticInfo::Use &use, it.value()) { QTextLayout::FormatRange formatRange; switch (use.kind) { case SemanticInfo::Use::Type: formatRange.format = m_typeFormat; break; case SemanticInfo::Use::Field: formatRange.format = m_fieldFormat; break; case SemanticInfo::Use::Local: formatRange.format = m_localFormat; break; case SemanticInfo::Use::Static: formatRange.format = m_staticFormat; break; case SemanticInfo::Use::VirtualMethod: formatRange.format = m_virtualMethodFormat; break; default: continue; } formatRange.start = use.column - 1; formatRange.length = use.length; formats.append(formatRange); } highlighter->setExtraAdditionalFormats(b, formats); b = b.next(); ++m_nextHighlightBlockNumber; } } void CPPEditor::finishHighlightSymbolUsages() { if (editorRevision() != m_highlightRevision) return; // outdated else if (m_highlighter.isCanceled()) return; // aborted CppHighlighter *highlighter = qobject_cast<CppHighlighter*>(baseTextDocument()->syntaxHighlighter()); Q_ASSERT(highlighter); QTextDocument *doc = document(); if (m_nextHighlightBlockNumber >= doc->blockCount()) return; QTextBlock b = doc->findBlockByNumber(m_nextHighlightBlockNumber); while (b.isValid()) { highlighter->setExtraAdditionalFormats(b, QList<QTextLayout::FormatRange>()); b = b.next(); ++m_nextHighlightBlockNumber; } } void CPPEditor::switchDeclarationDefinition() { if (! m_modelManager) return; const Snapshot snapshot = m_modelManager->snapshot(); if (Document::Ptr thisDocument = snapshot.document(file()->fileName())) { int line = 0, positionInBlock = 0; convertPosition(position(), &line, &positionInBlock); Symbol *lastVisibleSymbol = thisDocument->lastVisibleSymbolAt(line, positionInBlock + 1); if (! lastVisibleSymbol) return; Function *functionScope = lastVisibleSymbol->asFunction(); if (! functionScope) functionScope = lastVisibleSymbol->enclosingFunction(); if (functionScope) { LookupContext context(thisDocument, snapshot); Function *functionDefinition = functionScope->asFunction(); const QList<LookupItem> declarations = context.lookup(functionDefinition->name(), functionDefinition->scope()); foreach (const LookupItem &r, declarations) { Symbol *decl = r.declaration(); // TODO: check decl. openCppEditorAt(linkToSymbol(decl)); break; } } else if (lastVisibleSymbol && lastVisibleSymbol->isDeclaration() && lastVisibleSymbol->type()->isFunctionType()) { if (Symbol *def = snapshot.findMatchingDefinition(lastVisibleSymbol)) openCppEditorAt(linkToSymbol(def)); } } } static inline LookupItem skipForwardDeclarations(const QList<LookupItem> &resolvedSymbols) { QList<LookupItem> candidates = resolvedSymbols; LookupItem result = candidates.first(); const FullySpecifiedType ty = result.type().simplified(); if (ty->isForwardClassDeclarationType()) { while (! candidates.isEmpty()) { LookupItem r = candidates.takeFirst(); if (! r.type()->isForwardClassDeclarationType()) { result = r; break; } } } if (ty->isObjCForwardClassDeclarationType()) { while (! candidates.isEmpty()) { LookupItem r = candidates.takeFirst(); if (! r.type()->isObjCForwardClassDeclarationType()) { result = r; break; } } } if (ty->isObjCForwardProtocolDeclarationType()) { while (! candidates.isEmpty()) { LookupItem r = candidates.takeFirst(); if (! r.type()->isObjCForwardProtocolDeclarationType()) { result = r; break; } } } return result; } CPPEditor::Link CPPEditor::findLinkAt(const QTextCursor &cursor, bool resolveTarget) { Link link; if (!m_modelManager) return link; const Snapshot snapshot = m_modelManager->snapshot(); int lineNumber = 0, positionInBlock = 0; convertPosition(cursor.position(), &lineNumber, &positionInBlock); Document::Ptr doc = snapshot.document(file()->fileName()); if (!doc) return link; const unsigned line = lineNumber; const unsigned column = positionInBlock + 1; QTextCursor tc = cursor; // Make sure we're not at the start of a word { const QChar c = characterAt(tc.position()); if (c.isLetter() || c == QLatin1Char('_')) tc.movePosition(QTextCursor::Right); } int beginOfToken = 0; int endOfToken = 0; SimpleLexer tokenize; tokenize.setQtMocRunEnabled(true); const QString blockText = cursor.block().text(); const QList<Token> tokens = tokenize(blockText, BackwardsScanner::previousBlockState(cursor.block())); bool recognizedQtMethod = false; for (int i = 0; i < tokens.size(); ++i) { const Token &tk = tokens.at(i); if (((unsigned) positionInBlock) >= tk.begin() && ((unsigned) positionInBlock) <= tk.end()) { if (i >= 2 && tokens.at(i).is(T_IDENTIFIER) && tokens.at(i - 1).is(T_LPAREN) && (tokens.at(i - 2).is(T_SIGNAL) || tokens.at(i - 2).is(T_SLOT))) { // token[i] == T_IDENTIFIER // token[i + 1] == T_LPAREN // token[.....] == .... // token[i + n] == T_RPAREN if (i + 1 < tokens.size() && tokens.at(i + 1).is(T_LPAREN)) { // skip matched parenthesis int j = i - 1; int depth = 0; for (; j < tokens.size(); ++j) { if (tokens.at(j).is(T_LPAREN)) ++depth; else if (tokens.at(j).is(T_RPAREN)) { if (! --depth) break; } } if (j < tokens.size()) { QTextBlock block = cursor.block(); beginOfToken = block.position() + tokens.at(i).begin(); endOfToken = block.position() + tokens.at(i).end(); tc.setPosition(block.position() + tokens.at(j).end()); recognizedQtMethod = true; } } } break; } } if (! recognizedQtMethod) { const QTextBlock block = tc.block(); int pos = cursor.positionInBlock(); QChar ch = document()->characterAt(cursor.position()); if (pos > 0 && ! (ch.isLetterOrNumber() || ch == QLatin1Char('_'))) --pos; // positionInBlock points to a delimiter character. const Token tk = SimpleLexer::tokenAt(block.text(), pos, BackwardsScanner::previousBlockState(block), true); beginOfToken = block.position() + tk.begin(); endOfToken = block.position() + tk.end(); // Handle include directives if (tk.is(T_STRING_LITERAL) || tk.is(T_ANGLE_STRING_LITERAL)) { const unsigned lineno = cursor.blockNumber() + 1; foreach (const Document::Include &incl, doc->includes()) { if (incl.line() == lineno && incl.resolved()) { link.fileName = incl.fileName(); link.begin = beginOfToken + 1; link.end = endOfToken - 1; return link; } } } if (tk.isNot(T_IDENTIFIER)) return link; tc.setPosition(endOfToken); } // Find the last symbol up to the cursor position Scope *scope = doc->scopeAt(line, column); if (!scope) return link; // Evaluate the type of the expression under the cursor ExpressionUnderCursor expressionUnderCursor; const QString expression = expressionUnderCursor(tc); TypeOfExpression typeOfExpression; typeOfExpression.init(doc, snapshot); const QList<LookupItem> resolvedSymbols = typeOfExpression(expression, scope, TypeOfExpression::Preprocess); if (!resolvedSymbols.isEmpty()) { LookupItem result = skipForwardDeclarations(resolvedSymbols); foreach (const LookupItem &r, resolvedSymbols) { if (Symbol *d = r.declaration()) { if (d->isDeclaration() || d->isFunction()) { if (file()->fileName() == QString::fromUtf8(d->fileName(), d->fileNameLength())) { if (unsigned(lineNumber) == d->line() && unsigned(positionInBlock) >= d->column()) { // ### TODO: check the end result = r; // take the symbol under cursor. break; } } } } } if (Symbol *symbol = result.declaration()) { Symbol *def = 0; if (resolveTarget) { Symbol *lastVisibleSymbol = doc->lastVisibleSymbolAt(line, column); def = findDefinition(symbol, snapshot); if (def == lastVisibleSymbol) def = 0; // jump to declaration then. } if (symbol->isForwardClassDeclaration()) { def = snapshot.findMatchingClassDeclaration(symbol); } link = linkToSymbol(def ? def : symbol); link.begin = beginOfToken; link.end = endOfToken; return link; // This would jump to the type of a name #if 0 } else if (NamedType *namedType = firstType->asNamedType()) { QList<Symbol *> candidates = context.resolve(namedType->name()); if (!candidates.isEmpty()) { Symbol *s = candidates.takeFirst(); openCppEditorAt(s->fileName(), s->line(), s->column()); } #endif } } else { // Handle macro uses const Document::MacroUse *use = doc->findMacroUseAt(endOfToken - 1); if (use) { const Macro &macro = use->macro(); link.fileName = macro.fileName(); link.line = macro.line(); link.begin = use->begin(); link.end = use->end(); return link; } } return link; } void CPPEditor::jumpToDefinition() { openLink(findLinkAt(textCursor())); } Symbol *CPPEditor::findDefinition(Symbol *symbol, const Snapshot &snapshot) { if (symbol->isFunction()) return 0; // symbol is a function definition. else if (! symbol->type()->isFunctionType()) return 0; // not a function declaration return snapshot.findMatchingDefinition(symbol); } unsigned CPPEditor::editorRevision() const { return document()->revision(); } bool CPPEditor::isOutdated() const { if (m_lastSemanticInfo.revision != editorRevision()) return true; return false; } SemanticInfo CPPEditor::semanticInfo() const { return m_lastSemanticInfo; } CPlusPlus::OverviewModel *CPPEditor::outlineModel() const { return m_outlineModel; } QModelIndex CPPEditor::outlineModelIndex() { if (!m_outlineModelIndex.isValid()) { int line = 0, column = 0; convertPosition(position(), &line, &column); m_outlineModelIndex = indexForPosition(line, column); emit outlineModelIndexChanged(m_outlineModelIndex); } return m_outlineModelIndex; } bool CPPEditor::isElectricCharacter(QChar ch) const { if (ch == QLatin1Char('{') || ch == QLatin1Char('}') || ch == QLatin1Char(':') || ch == QLatin1Char('#')) { return true; } return false; } QString CPPEditor::insertMatchingBrace(const QTextCursor &tc, const QString &text, QChar la, int *skippedChars) const { MatchingText m; return m.insertMatchingBrace(tc, text, la, skippedChars); } QString CPPEditor::insertParagraphSeparator(const QTextCursor &tc) const { MatchingText m; return m.insertParagraphSeparator(tc); } bool CPPEditor::contextAllowsAutoParentheses(const QTextCursor &cursor, const QString &textToInsert) const { QChar ch; if (! textToInsert.isEmpty()) ch = textToInsert.at(0); if (! (MatchingText::shouldInsertMatchingText(cursor) || ch == QLatin1Char('\'') || ch == QLatin1Char('"'))) return false; else if (isInComment(cursor)) return false; return true; } bool CPPEditor::contextAllowsElectricCharacters(const QTextCursor &cursor) const { const Token tk = SimpleLexer::tokenAt(cursor.block().text(), cursor.positionInBlock(), BackwardsScanner::previousBlockState(cursor.block())); // XXX Duplicated from CPPEditor::isInComment to avoid tokenizing twice if (tk.isComment()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos == tk.end()) { if (tk.is(T_CPP_COMMENT) || tk.is(T_CPP_DOXY_COMMENT)) return false; const int state = cursor.block().userState() & 0xFF; if (state > 0) return false; } if (pos < tk.end()) return false; } else if (tk.is(T_STRING_LITERAL) || tk.is(T_WIDE_STRING_LITERAL) || tk.is(T_CHAR_LITERAL) || tk.is(T_WIDE_CHAR_LITERAL)) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos <= tk.end()) return false; } return true; } bool CPPEditor::isInComment(const QTextCursor &cursor) const { const Token tk = SimpleLexer::tokenAt(cursor.block().text(), cursor.positionInBlock(), BackwardsScanner::previousBlockState(cursor.block())); if (tk.isComment()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos == tk.end()) { if (tk.is(T_CPP_COMMENT) || tk.is(T_CPP_DOXY_COMMENT)) return true; const int state = cursor.block().userState() & 0xFF; if (state > 0) return true; } if (pos < tk.end()) return true; } return false; } void CPPEditor::indentBlock(QTextDocument *doc, QTextBlock block, QChar typedChar) { Q_UNUSED(doc) Q_UNUSED(typedChar) const TabSettings &ts = tabSettings(); CppTools::QtStyleCodeFormatter codeFormatter(ts); codeFormatter.updateStateUntil(block); const int depth = codeFormatter.indentFor(block); ts.indentLine(block, depth); } void CPPEditor::indent(QTextDocument *doc, const QTextCursor &cursor, QChar typedChar) { Q_UNUSED(doc) Q_UNUSED(typedChar) maybeClearSomeExtraSelections(cursor); if (cursor.hasSelection()) { QTextBlock block = doc->findBlock(cursor.selectionStart()); const QTextBlock end = doc->findBlock(cursor.selectionEnd()).next(); const TabSettings &ts = tabSettings(); CppTools::QtStyleCodeFormatter codeFormatter(ts); codeFormatter.updateStateUntil(block); QTextCursor tc = textCursor(); tc.beginEditBlock(); do { ts.indentLine(block, codeFormatter.indentFor(block)); codeFormatter.updateLineStateChange(block); block = block.next(); } while (block.isValid() && block != end); tc.endEditBlock(); } else { indentBlock(doc, cursor.block(), typedChar); } } bool CPPEditor::event(QEvent *e) { switch (e->type()) { case QEvent::ShortcutOverride: if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape && m_currentRenameSelection != NoCurrentRenameSelection) { e->accept(); return true; } break; default: break; } return BaseTextEditor::event(e); } void CPPEditor::performQuickFix(int index) { TextEditor::QuickFixOperation::Ptr op = m_quickFixes.at(index); op->perform(); } void CPPEditor::contextMenuEvent(QContextMenuEvent *e) { // ### enable // updateSemanticInfo(m_semanticHighlighter->semanticInfo(currentSource())); QMenu *menu = new QMenu; Core::ActionManager *am = Core::ICore::instance()->actionManager(); Core::ActionContainer *mcontext = am->actionContainer(CppEditor::Constants::M_CONTEXT); QMenu *contextMenu = mcontext->menu(); CppQuickFixCollector *quickFixCollector = CppPlugin::instance()->quickFixCollector(); QSignalMapper mapper; connect(&mapper, SIGNAL(mapped(int)), this, SLOT(performQuickFix(int))); if (! isOutdated()) { if (quickFixCollector->startCompletion(editableInterface()) != -1) { m_quickFixes = quickFixCollector->quickFixes(); for (int index = 0; index < m_quickFixes.size(); ++index) { TextEditor::QuickFixOperation::Ptr op = m_quickFixes.at(index); QAction *action = menu->addAction(op->description()); mapper.setMapping(action, index); connect(action, SIGNAL(triggered()), &mapper, SLOT(map())); } if (! m_quickFixes.isEmpty()) menu->addSeparator(); } } foreach (QAction *action, contextMenu->actions()) menu->addAction(action); appendStandardContextMenuActions(menu); menu->exec(e->globalPos()); quickFixCollector->cleanup(); m_quickFixes.clear(); delete menu; } void CPPEditor::keyPressEvent(QKeyEvent *e) { if (m_currentRenameSelection == NoCurrentRenameSelection) { TextEditor::BaseTextEditor::keyPressEvent(e); return; } QTextCursor cursor = textCursor(); const QTextCursor::MoveMode moveMode = (e->modifiers() & Qt::ShiftModifier) ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Escape: abortRename(); e->accept(); return; case Qt::Key_Home: { // Send home to start of name when within the name and not at the start if (cursor.position() > m_currentRenameSelectionBegin.position() && cursor.position() <= m_currentRenameSelectionEnd.position()) { cursor.setPosition(m_currentRenameSelectionBegin.position(), moveMode); setTextCursor(cursor); e->accept(); return; } break; } case Qt::Key_End: { // Send end to end of name when within the name and not at the end if (cursor.position() >= m_currentRenameSelectionBegin.position() && cursor.position() < m_currentRenameSelectionEnd.position()) { cursor.setPosition(m_currentRenameSelectionEnd.position(), moveMode); setTextCursor(cursor); e->accept(); return; } break; } case Qt::Key_Backspace: { if (cursor.position() == m_currentRenameSelectionBegin.position() && !cursor.hasSelection()) { // Eat backspace at start of name when there is no selection e->accept(); return; } break; } case Qt::Key_Delete: { if (cursor.position() == m_currentRenameSelectionEnd.position() && !cursor.hasSelection()) { // Eat delete at end of name when there is no selection e->accept(); return; } break; } default: { break; } } // switch startRename(); bool wantEditBlock = (cursor.position() >= m_currentRenameSelectionBegin.position() && cursor.position() <= m_currentRenameSelectionEnd.position()); if (wantEditBlock) { // possible change inside rename selection if (m_firstRenameChange) cursor.beginEditBlock(); else cursor.joinPreviousEditBlock(); m_firstRenameChange = false; } TextEditor::BaseTextEditor::keyPressEvent(e); if (wantEditBlock) cursor.endEditBlock(); finishRename(); } Core::Context CPPEditorEditable::context() const { return m_context; } Core::IEditor *CPPEditorEditable::duplicate(QWidget *parent) { CPPEditor *newEditor = new CPPEditor(parent); newEditor->duplicateFrom(editor()); CppPlugin::instance()->initializeEditor(newEditor); return newEditor->editableInterface(); } QString CPPEditorEditable::id() const { return QLatin1String(CppEditor::Constants::CPPEDITOR_ID); } bool CPPEditorEditable::open(const QString & fileName) { bool b = TextEditor::BaseTextEditorEditable::open(fileName); editor()->setMimeType(Core::ICore::instance()->mimeDatabase()->findByFile(QFileInfo(fileName)).type()); return b; } void CPPEditor::setFontSettings(const TextEditor::FontSettings &fs) { TextEditor::BaseTextEditor::setFontSettings(fs); CppHighlighter *highlighter = qobject_cast<CppHighlighter*>(baseTextDocument()->syntaxHighlighter()); if (!highlighter) return; static QVector<QString> categories; if (categories.isEmpty()) { categories << QLatin1String(TextEditor::Constants::C_NUMBER) << QLatin1String(TextEditor::Constants::C_STRING) << QLatin1String(TextEditor::Constants::C_TYPE) << QLatin1String(TextEditor::Constants::C_KEYWORD) << QLatin1String(TextEditor::Constants::C_OPERATOR) << QLatin1String(TextEditor::Constants::C_PREPROCESSOR) << QLatin1String(TextEditor::Constants::C_LABEL) << QLatin1String(TextEditor::Constants::C_COMMENT) << QLatin1String(TextEditor::Constants::C_DOXYGEN_COMMENT) << QLatin1String(TextEditor::Constants::C_DOXYGEN_TAG) << QLatin1String(TextEditor::Constants::C_VISUAL_WHITESPACE); } const QVector<QTextCharFormat> formats = fs.toTextCharFormats(categories); highlighter->setFormats(formats.constBegin(), formats.constEnd()); m_occurrencesFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES)); m_occurrencesUnusedFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES_UNUSED)); m_occurrencesUnusedFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline); m_occurrencesUnusedFormat.setUnderlineColor(m_occurrencesUnusedFormat.foreground().color()); m_occurrencesUnusedFormat.clearForeground(); m_occurrencesUnusedFormat.setToolTip(tr("Unused variable")); m_occurrenceRenameFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES_RENAME)); m_typeFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_TYPE)); m_localFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_LOCAL)); m_fieldFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_FIELD)); m_staticFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_STATIC)); m_virtualMethodFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_VIRTUAL_METHOD)); m_keywordFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_KEYWORD)); // only set the background, we do not want to modify foreground properties set by the syntax highlighter or the link m_occurrencesFormat.clearForeground(); m_occurrenceRenameFormat.clearForeground(); // Clear all additional formats since they may have changed QTextBlock b = document()->firstBlock(); while (b.isValid()) { highlighter->setExtraAdditionalFormats(b, QList<QTextLayout::FormatRange>()); b = b.next(); } // This also triggers an update of the additional formats highlighter->rehighlight(); } void CPPEditor::setTabSettings(const TextEditor::TabSettings &ts) { CppTools::QtStyleCodeFormatter formatter; formatter.invalidateCache(document()); TextEditor::BaseTextEditor::setTabSettings(ts); } void CPPEditor::unCommentSelection() { Utils::unCommentSelection(this); } CPPEditor::Link CPPEditor::linkToSymbol(CPlusPlus::Symbol *symbol) { if (!symbol) return Link(); const QString fileName = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength()); unsigned line = symbol->line(); unsigned column = symbol->column(); if (column) --column; if (symbol->isGenerated()) column = 0; return Link(fileName, line, column); } bool CPPEditor::openCppEditorAt(const Link &link) { if (link.fileName.isEmpty()) return false; if (baseTextDocument()->fileName() == link.fileName) { Core::EditorManager *editorManager = Core::EditorManager::instance(); editorManager->cutForwardNavigationHistory(); editorManager->addCurrentPositionToNavigationHistory(); gotoLine(link.line, link.column); setFocus(); return true; } return TextEditor::BaseTextEditor::openEditorAt(link.fileName, link.line, link.column, Constants::CPPEDITOR_ID); } void CPPEditor::semanticRehighlight() { m_semanticHighlighter->rehighlight(currentSource()); } void CPPEditor::updateSemanticInfo(const SemanticInfo &semanticInfo) { if (semanticInfo.revision != editorRevision()) { // got outdated semantic info semanticRehighlight(); return; } const SemanticInfo previousSemanticInfo = m_lastSemanticInfo; m_lastSemanticInfo = semanticInfo; // update the semantic info int line = 0, column = 0; convertPosition(position(), &line, &column); QList<QTextEdit::ExtraSelection> unusedSelections; m_renameSelections.clear(); m_currentRenameSelection = NoCurrentRenameSelection; SemanticInfo::LocalUseIterator it(semanticInfo.localUses); while (it.hasNext()) { it.next(); const QList<SemanticInfo::Use> &uses = it.value(); bool good = false; foreach (const SemanticInfo::Use &use, uses) { unsigned l = line; unsigned c = column + 1; // convertCursorPosition() returns a 0-based column number. if (l == use.line && c >= use.column && c <= (use.column + use.length)) { good = true; break; } } if (uses.size() == 1) // it's an unused declaration highlightUses(uses, semanticInfo, &unusedSelections); else if (good && m_renameSelections.isEmpty()) highlightUses(uses, semanticInfo, &m_renameSelections); } if (m_lastSemanticInfo.forced || previousSemanticInfo.revision != semanticInfo.revision) { QTextCharFormat diagnosticMessageFormat; diagnosticMessageFormat.setUnderlineColor(Qt::darkYellow); // ### hardcoded diagnosticMessageFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline); // ### hardcoded setExtraSelections(UndefinedSymbolSelection, createSelections(document(), semanticInfo.diagnosticMessages, diagnosticMessageFormat)); m_highlighter.cancel(); if (semanticInfo.doc) { if (Core::EditorManager::instance()->currentEditor() == editableInterface()) { LookupContext context(semanticInfo.doc, semanticInfo.snapshot); CheckSymbols::Future f = CheckSymbols::go(semanticInfo.doc, context); m_highlighter = f; m_highlightRevision = semanticInfo.revision; m_nextHighlightBlockNumber = 0; m_highlightWatcher.setFuture(m_highlighter); } } #if 0 // ### TODO: enable objc semantic highlighting setExtraSelections(ObjCSelection, createSelections(document(), semanticInfo.objcKeywords, m_keywordFormat)); #endif } setExtraSelections(UnusedSymbolSelection, unusedSelections); if (! m_renameSelections.isEmpty()) setExtraSelections(CodeSemanticsSelection, m_renameSelections); // ### else { markSymbols(textCursor(), semanticInfo); } m_lastSemanticInfo.forced = false; // clear the forced flag } namespace { class FindObjCKeywords: public ASTVisitor { public: FindObjCKeywords(TranslationUnit *unit) : ASTVisitor(unit) {} QList<SemanticInfo::Use> operator()() { _keywords.clear(); accept(translationUnit()->ast()); return _keywords; } virtual bool visit(ObjCClassDeclarationAST *ast) { addToken(ast->interface_token); addToken(ast->implementation_token); addToken(ast->end_token); return true; } virtual bool visit(ObjCClassForwardDeclarationAST *ast) { addToken(ast->class_token); return true; } virtual bool visit(ObjCProtocolDeclarationAST *ast) { addToken(ast->protocol_token); addToken(ast->end_token); return true; } virtual bool visit(ObjCProtocolForwardDeclarationAST *ast) { addToken(ast->protocol_token); return true; } virtual bool visit(ObjCProtocolExpressionAST *ast) { addToken(ast->protocol_token); return true; } virtual bool visit(ObjCTypeNameAST *) { return true; } virtual bool visit(ObjCEncodeExpressionAST *ast) { addToken(ast->encode_token); return true; } virtual bool visit(ObjCSelectorExpressionAST *ast) { addToken(ast->selector_token); return true; } virtual bool visit(ObjCVisibilityDeclarationAST *ast) { addToken(ast->visibility_token); return true; } virtual bool visit(ObjCPropertyAttributeAST *ast) { const Identifier *attrId = identifier(ast->attribute_identifier_token); if (attrId == control()->objcAssignId() || attrId == control()->objcCopyId() || attrId == control()->objcGetterId() || attrId == control()->objcNonatomicId() || attrId == control()->objcReadonlyId() || attrId == control()->objcReadwriteId() || attrId == control()->objcRetainId() || attrId == control()->objcSetterId()) addToken(ast->attribute_identifier_token); return true; } virtual bool visit(ObjCPropertyDeclarationAST *ast) { addToken(ast->property_token); return true; } virtual bool visit(ObjCSynthesizedPropertiesDeclarationAST *ast) { addToken(ast->synthesized_token); return true; } virtual bool visit(ObjCDynamicPropertiesDeclarationAST *ast) { addToken(ast->dynamic_token); return true; } virtual bool visit(ObjCFastEnumerationAST *ast) { addToken(ast->for_token); addToken(ast->in_token); return true; } virtual bool visit(ObjCSynchronizedStatementAST *ast) { addToken(ast->synchronized_token); return true; } protected: void addToken(unsigned token) { if (token) { SemanticInfo::Use use; getTokenStartPosition(token, &use.line, &use.column); use.length = tokenAt(token).length(); _keywords.append(use); } } private: QList<SemanticInfo::Use> _keywords; }; } // anonymous namespace SemanticHighlighter::Source CPPEditor::currentSource(bool force) { int line = 0, column = 0; convertPosition(position(), &line, &column); const Snapshot snapshot = m_modelManager->snapshot(); const QString fileName = file()->fileName(); QString code; if (force || m_lastSemanticInfo.revision != editorRevision()) code = toPlainText(); // get the source code only when needed. const unsigned revision = editorRevision(); SemanticHighlighter::Source source(snapshot, fileName, code, line, column, revision); source.force = force; return source; } SemanticHighlighter::SemanticHighlighter(QObject *parent) : QThread(parent), m_done(false) { } SemanticHighlighter::~SemanticHighlighter() { } void SemanticHighlighter::abort() { QMutexLocker locker(&m_mutex); m_done = true; m_condition.wakeOne(); } void SemanticHighlighter::rehighlight(const Source &source) { QMutexLocker locker(&m_mutex); m_source = source; m_condition.wakeOne(); } bool SemanticHighlighter::isOutdated() { QMutexLocker locker(&m_mutex); const bool outdated = ! m_source.fileName.isEmpty() || m_done; return outdated; } void SemanticHighlighter::run() { setPriority(QThread::LowestPriority); forever { m_mutex.lock(); while (! (m_done || ! m_source.fileName.isEmpty())) m_condition.wait(&m_mutex); const bool done = m_done; const Source source = m_source; m_source.clear(); m_mutex.unlock(); if (done) break; const SemanticInfo info = semanticInfo(source); if (! isOutdated()) { m_mutex.lock(); m_lastSemanticInfo = info; m_mutex.unlock(); emit changed(info); } } } SemanticInfo SemanticHighlighter::semanticInfo(const Source &source) { m_mutex.lock(); const int revision = m_lastSemanticInfo.revision; m_mutex.unlock(); Snapshot snapshot; Document::Ptr doc; QList<Document::DiagnosticMessage> diagnosticMessages; QList<SemanticInfo::Use> objcKeywords; if (! source.force && revision == source.revision) { m_mutex.lock(); snapshot = m_lastSemanticInfo.snapshot; // ### TODO: use the new snapshot. doc = m_lastSemanticInfo.doc; diagnosticMessages = m_lastSemanticInfo.diagnosticMessages; objcKeywords = m_lastSemanticInfo.objcKeywords; m_mutex.unlock(); } if (! doc) { snapshot = source.snapshot; const QByteArray preprocessedCode = snapshot.preprocessedCode(source.code, source.fileName); doc = snapshot.documentFromSource(preprocessedCode, source.fileName); doc->check(); #if 0 if (TranslationUnit *unit = doc->translationUnit()) { FindObjCKeywords findObjCKeywords(unit); // ### remove me objcKeywords = findObjCKeywords(); } #endif } TranslationUnit *translationUnit = doc->translationUnit(); AST *ast = translationUnit->ast(); FunctionDefinitionUnderCursor functionDefinitionUnderCursor(translationUnit); DeclarationAST *currentFunctionDefinition = functionDefinitionUnderCursor(ast, source.line, source.column); const LocalSymbols useTable(doc, currentFunctionDefinition); SemanticInfo semanticInfo; semanticInfo.revision = source.revision; semanticInfo.snapshot = snapshot; semanticInfo.doc = doc; semanticInfo.localUses = useTable.uses; semanticInfo.hasQ = useTable.hasQ; semanticInfo.hasD = useTable.hasD; semanticInfo.forced = source.force; semanticInfo.diagnosticMessages = diagnosticMessages; semanticInfo.objcKeywords = objcKeywords; return semanticInfo; } QModelIndex CPPEditor::indexForPosition(int line, int column, const QModelIndex &rootIndex) const { QModelIndex lastIndex = rootIndex; const int rowCount = m_outlineModel->rowCount(rootIndex); for (int row = 0; row < rowCount; ++row) { const QModelIndex index = m_outlineModel->index(row, 0, rootIndex); Symbol *symbol = m_outlineModel->symbolFromIndex(index); if (symbol && symbol->line() > unsigned(line)) break; lastIndex = index; } if (lastIndex != rootIndex) { // recurse lastIndex = indexForPosition(line, column, lastIndex); } return lastIndex; } #include "cppeditor.moc"
//===- FileCheck.cpp - Check that File's Contents match what is expected --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // FileCheck does a line-by line check of a file that validates whether it // contains the expected content. This is useful for regression tests etc. // // This program exits with an error status of 2 on error, exit status of 0 if // the file matched the expected contents, and exit status of 1 if it did not // contain the expected contents. // //===----------------------------------------------------------------------===// #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Regex.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/system_error.h" #include <algorithm> #include <map> #include <string> #include <vector> using namespace llvm; static cl::opt<std::string> CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required); static cl::opt<std::string> InputFilename("input-file", cl::desc("File to check (defaults to stdin)"), cl::init("-"), cl::value_desc("filename")); static cl::opt<std::string> CheckPrefix("check-prefix", cl::init("CHECK"), cl::desc("Prefix to use from check file (defaults to 'CHECK')")); static cl::opt<bool> NoCanonicalizeWhiteSpace("strict-whitespace", cl::desc("Do not treat all horizontal whitespace as equivalent")); //===----------------------------------------------------------------------===// // Pattern Handling Code. //===----------------------------------------------------------------------===// class Pattern { SMLoc PatternLoc; /// MatchEOF - When set, this pattern only matches the end of file. This is /// used for trailing CHECK-NOTs. bool MatchEOF; /// FixedStr - If non-empty, this pattern is a fixed string match with the /// specified fixed string. StringRef FixedStr; /// RegEx - If non-empty, this is a regex pattern. std::string RegExStr; /// \brief Contains the number of line this pattern is in. unsigned LineNumber; /// VariableUses - Entries in this vector map to uses of a variable in the /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain /// "foobaz" and we'll get an entry in this vector that tells us to insert the /// value of bar at offset 3. std::vector<std::pair<StringRef, unsigned> > VariableUses; /// VariableDefs - Maps definitions of variables to their parenthesized /// capture numbers. /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1. std::map<StringRef, unsigned> VariableDefs; public: Pattern(bool matchEOF = false) : MatchEOF(matchEOF) { } /// getLoc - Return the location in source code. SMLoc getLoc() const { return PatternLoc; } /// ParsePattern - Parse the given string into the Pattern. SM provides the /// SourceMgr used for error reports, and LineNumber is the line number in /// the input file from which the pattern string was read. /// Returns true in case of an error, false otherwise. bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber); /// Match - Match the pattern string against the input buffer Buffer. This /// returns the position that is matched or npos if there is no match. If /// there is a match, the size of the matched string is returned in MatchLen. /// /// The VariableTable StringMap provides the current values of filecheck /// variables and is updated if this match defines new values. size_t Match(StringRef Buffer, size_t &MatchLen, StringMap<StringRef> &VariableTable) const; /// PrintFailureInfo - Print additional information about a failure to match /// involving this pattern. void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, const StringMap<StringRef> &VariableTable) const; private: static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr); bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM); void AddBackrefToRegEx(unsigned BackrefNum); /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of /// matching this pattern at the start of \arg Buffer; a distance of zero /// should correspond to a perfect match. unsigned ComputeMatchDistance(StringRef Buffer, const StringMap<StringRef> &VariableTable) const; /// \brief Evaluates expression and stores the result to \p Value. /// \return true on success. false when the expression has invalid syntax. bool EvaluateExpression(StringRef Expr, std::string &Value) const; /// \brief Finds the closing sequence of a regex variable usage or /// definition. Str has to point in the beginning of the definition /// (right after the opening sequence). /// \return offset of the closing sequence within Str, or npos if it was not /// found. size_t FindRegexVarEnd(StringRef Str); }; bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber) { this->LineNumber = LineNumber; PatternLoc = SMLoc::getFromPointer(PatternStr.data()); // Ignore trailing whitespace. while (!PatternStr.empty() && (PatternStr.back() == ' ' || PatternStr.back() == '\t')) PatternStr = PatternStr.substr(0, PatternStr.size()-1); // Check that there is something on the line. if (PatternStr.empty()) { SM.PrintMessage(PatternLoc, SourceMgr::DK_Error, "found empty check string with prefix '" + CheckPrefix+":'"); return true; } // Check to see if this is a fixed string, or if it has regex pieces. if (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos && PatternStr.find("[[") == StringRef::npos)) { FixedStr = PatternStr; return false; } // Paren value #0 is for the fully matched string. Any new parenthesized // values add from there. unsigned CurParen = 1; // Otherwise, there is at least one regex piece. Build up the regex pattern // by escaping scary characters in fixed strings, building up one big regex. while (!PatternStr.empty()) { // RegEx matches. if (PatternStr.startswith("{{")) { // This is the start of a regex match. Scan for the }}. size_t End = PatternStr.find("}}"); if (End == StringRef::npos) { SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()), SourceMgr::DK_Error, "found start of regex string with no end '}}'"); return true; } // Enclose {{}} patterns in parens just like [[]] even though we're not // capturing the result for any purpose. This is required in case the // expression contains an alternation like: CHECK: abc{{x|z}}def. We // want this to turn into: "abc(x|z)def" not "abcx|zdef". RegExStr += '('; ++CurParen; if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM)) return true; RegExStr += ')'; PatternStr = PatternStr.substr(End+2); continue; } // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .* // (or some other regex) and assigns it to the FileCheck variable 'foo'. The // second form is [[foo]] which is a reference to foo. The variable name // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject // it. This is to catch some common errors. if (PatternStr.startswith("[[")) { // Find the closing bracket pair ending the match. End is going to be an // offset relative to the beginning of the match string. size_t End = FindRegexVarEnd(PatternStr.substr(2)); if (End == StringRef::npos) { SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()), SourceMgr::DK_Error, "invalid named regex reference, no ]] found"); return true; } StringRef MatchStr = PatternStr.substr(2, End); PatternStr = PatternStr.substr(End+4); // Get the regex name (e.g. "foo"). size_t NameEnd = MatchStr.find(':'); StringRef Name = MatchStr.substr(0, NameEnd); if (Name.empty()) { SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, "invalid name in named regex: empty name"); return true; } // Verify that the name/expression is well formed. FileCheck currently // supports @LINE, @LINE+number, @LINE-number expressions. The check here // is relaxed, more strict check is performed in \c EvaluateExpression. bool IsExpression = false; for (unsigned i = 0, e = Name.size(); i != e; ++i) { if (i == 0 && Name[i] == '@') { if (NameEnd != StringRef::npos) { SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, "invalid name in named regex definition"); return true; } IsExpression = true; continue; } if (Name[i] != '_' && !isalnum(Name[i]) && (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) { SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i), SourceMgr::DK_Error, "invalid name in named regex"); return true; } } // Name can't start with a digit. if (isdigit(static_cast<unsigned char>(Name[0]))) { SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, "invalid name in named regex"); return true; } // Handle [[foo]]. if (NameEnd == StringRef::npos) { // Handle variables that were defined earlier on the same line by // emitting a backreference. if (VariableDefs.find(Name) != VariableDefs.end()) { unsigned VarParenNum = VariableDefs[Name]; if (VarParenNum < 1 || VarParenNum > 9) { SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, "Can't back-reference more than 9 variables"); return true; } AddBackrefToRegEx(VarParenNum); } else { VariableUses.push_back(std::make_pair(Name, RegExStr.size())); } continue; } // Handle [[foo:.*]]. VariableDefs[Name] = CurParen; RegExStr += '('; ++CurParen; if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM)) return true; RegExStr += ')'; } // Handle fixed string matches. // Find the end, which is the start of the next regex. size_t FixedMatchEnd = PatternStr.find("{{"); FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[[")); AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr); PatternStr = PatternStr.substr(FixedMatchEnd); } return false; } void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) { // Add the characters from FixedStr to the regex, escaping as needed. This // avoids "leaning toothpicks" in common patterns. for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) { switch (FixedStr[i]) { // These are the special characters matched in "p_ere_exp". case '(': case ')': case '^': case '$': case '|': case '*': case '+': case '?': case '.': case '[': case '\\': case '{': TheStr += '\\'; // FALL THROUGH. default: TheStr += FixedStr[i]; break; } } } bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) { Regex R(RS); std::string Error; if (!R.isValid(Error)) { SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error, "invalid regex: " + Error); return true; } RegExStr += RS.str(); CurParen += R.getNumMatches(); return false; } void Pattern::AddBackrefToRegEx(unsigned BackrefNum) { assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number"); std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum); RegExStr += Backref; } bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const { // The only supported expression is @LINE([\+-]\d+)? if (!Expr.startswith("@LINE")) return false; Expr = Expr.substr(StringRef("@LINE").size()); int Offset = 0; if (!Expr.empty()) { if (Expr[0] == '+') Expr = Expr.substr(1); else if (Expr[0] != '-') return false; if (Expr.getAsInteger(10, Offset)) return false; } Value = llvm::itostr(LineNumber + Offset); return true; } /// Match - Match the pattern string against the input buffer Buffer. This /// returns the position that is matched or npos if there is no match. If /// there is a match, the size of the matched string is returned in MatchLen. size_t Pattern::Match(StringRef Buffer, size_t &MatchLen, StringMap<StringRef> &VariableTable) const { // If this is the EOF pattern, match it immediately. if (MatchEOF) { MatchLen = 0; return Buffer.size(); } // If this is a fixed string pattern, just match it now. if (!FixedStr.empty()) { MatchLen = FixedStr.size(); return Buffer.find(FixedStr); } // Regex match. // If there are variable uses, we need to create a temporary string with the // actual value. StringRef RegExToMatch = RegExStr; std::string TmpStr; if (!VariableUses.empty()) { TmpStr = RegExStr; unsigned InsertOffset = 0; for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) { std::string Value; if (VariableUses[i].first[0] == '@') { if (!EvaluateExpression(VariableUses[i].first, Value)) return StringRef::npos; } else { StringMap<StringRef>::iterator it = VariableTable.find(VariableUses[i].first); // If the variable is undefined, return an error. if (it == VariableTable.end()) return StringRef::npos; // Look up the value and escape it so that we can plop it into the regex. AddFixedStringToRegEx(it->second, Value); } // Plop it into the regex at the adjusted offset. TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset, Value.begin(), Value.end()); InsertOffset += Value.size(); } // Match the newly constructed regex. RegExToMatch = TmpStr; } SmallVector<StringRef, 4> MatchInfo; if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo)) return StringRef::npos; // Successful regex match. assert(!MatchInfo.empty() && "Didn't get any match"); StringRef FullMatch = MatchInfo[0]; // If this defines any variables, remember their values. for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(), E = VariableDefs.end(); I != E; ++I) { assert(I->second < MatchInfo.size() && "Internal paren error"); VariableTable[I->first] = MatchInfo[I->second]; } MatchLen = FullMatch.size(); return FullMatch.data()-Buffer.data(); } unsigned Pattern::ComputeMatchDistance(StringRef Buffer, const StringMap<StringRef> &VariableTable) const { // Just compute the number of matching characters. For regular expressions, we // just compare against the regex itself and hope for the best. // // FIXME: One easy improvement here is have the regex lib generate a single // example regular expression which matches, and use that as the example // string. StringRef ExampleString(FixedStr); if (ExampleString.empty()) ExampleString = RegExStr; // Only compare up to the first line in the buffer, or the string size. StringRef BufferPrefix = Buffer.substr(0, ExampleString.size()); BufferPrefix = BufferPrefix.split('\n').first; return BufferPrefix.edit_distance(ExampleString); } void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, const StringMap<StringRef> &VariableTable) const{ // If this was a regular expression using variables, print the current // variable values. if (!VariableUses.empty()) { for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) { SmallString<256> Msg; raw_svector_ostream OS(Msg); StringRef Var = VariableUses[i].first; if (Var[0] == '@') { std::string Value; if (EvaluateExpression(Var, Value)) { OS << "with expression \""; OS.write_escaped(Var) << "\" equal to \""; OS.write_escaped(Value) << "\""; } else { OS << "uses incorrect expression \""; OS.write_escaped(Var) << "\""; } } else { StringMap<StringRef>::const_iterator it = VariableTable.find(Var); // Check for undefined variable references. if (it == VariableTable.end()) { OS << "uses undefined variable \""; OS.write_escaped(Var) << "\""; } else { OS << "with variable \""; OS.write_escaped(Var) << "\" equal to \""; OS.write_escaped(it->second) << "\""; } } SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, OS.str()); } } // Attempt to find the closest/best fuzzy match. Usually an error happens // because some string in the output didn't exactly match. In these cases, we // would like to show the user a best guess at what "should have" matched, to // save them having to actually check the input manually. size_t NumLinesForward = 0; size_t Best = StringRef::npos; double BestQuality = 0; // Use an arbitrary 4k limit on how far we will search. for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) { if (Buffer[i] == '\n') ++NumLinesForward; // Patterns have leading whitespace stripped, so skip whitespace when // looking for something which looks like a pattern. if (Buffer[i] == ' ' || Buffer[i] == '\t') continue; // Compute the "quality" of this match as an arbitrary combination of the // match distance and the number of lines skipped to get to this match. unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable); double Quality = Distance + (NumLinesForward / 100.); if (Quality < BestQuality || Best == StringRef::npos) { Best = i; BestQuality = Quality; } } // Print the "possible intended match here" line if we found something // reasonable and not equal to what we showed in the "scanning from here" // line. if (Best && Best != StringRef::npos && BestQuality < 50) { SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best), SourceMgr::DK_Note, "possible intended match here"); // FIXME: If we wanted to be really friendly we would show why the match // failed, as it can be hard to spot simple one character differences. } } size_t Pattern::FindRegexVarEnd(StringRef Str) { // Offset keeps track of the current offset within the input Str size_t Offset = 0; // [...] Nesting depth size_t BracketDepth = 0; while (!Str.empty()) { if (Str.startswith("]]") && BracketDepth == 0) return Offset; if (Str[0] == '\\') { // Backslash escapes the next char within regexes, so skip them both. Str = Str.substr(2); Offset += 2; } else { switch (Str[0]) { default: break; case '[': BracketDepth++; break; case ']': assert(BracketDepth > 0 && "Invalid regex"); BracketDepth--; break; } Str = Str.substr(1); Offset++; } } return StringRef::npos; } //===----------------------------------------------------------------------===// // Check Strings. //===----------------------------------------------------------------------===// /// CheckString - This is a check that we found in the input file. struct CheckString { /// Pat - The pattern to match. Pattern Pat; /// Loc - The location in the match file that the check string was specified. SMLoc Loc; /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed /// to a CHECK: directive. bool IsCheckNext; /// NotStrings - These are all of the strings that are disallowed from /// occurring between this match string and the previous one (or start of /// file). std::vector<Pattern> NotStrings; CheckString(const Pattern &P, SMLoc L, bool isCheckNext) : Pat(P), Loc(L), IsCheckNext(isCheckNext) {} }; /// Canonicalize whitespaces in the input file. Line endings are replaced /// with UNIX-style '\n'. /// /// \param PreserveHorizontal Don't squash consecutive horizontal whitespace /// characters to a single space. static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB, bool PreserveHorizontal) { SmallString<128> NewFile; NewFile.reserve(MB->getBufferSize()); for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd(); Ptr != End; ++Ptr) { // Eliminate trailing dosish \r. if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') { continue; } // If current char is not a horizontal whitespace or if horizontal // whitespace canonicalization is disabled, dump it to output as is. if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) { NewFile.push_back(*Ptr); continue; } // Otherwise, add one space and advance over neighboring space. NewFile.push_back(' '); while (Ptr+1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t')) ++Ptr; } // Free the old buffer and return a new one. MemoryBuffer *MB2 = MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier()); delete MB; return MB2; } /// ReadCheckFile - Read the check file, which specifies the sequence of /// expected strings. The strings are added to the CheckStrings vector. /// Returns true in case of an error, false otherwise. static bool ReadCheckFile(SourceMgr &SM, std::vector<CheckString> &CheckStrings) { OwningPtr<MemoryBuffer> File; if (error_code ec = MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) { errs() << "Could not open check file '" << CheckFilename << "': " << ec.message() << '\n'; return true; } // If we want to canonicalize whitespace, strip excess whitespace from the // buffer containing the CHECK lines. Remove DOS style line endings. MemoryBuffer *F = CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace); SM.AddNewSourceBuffer(F, SMLoc()); // Find all instances of CheckPrefix followed by : in the file. StringRef Buffer = F->getBuffer(); std::vector<Pattern> NotMatches; // LineNumber keeps track of the line on which CheckPrefix instances are // found. unsigned LineNumber = 1; while (1) { // See if Prefix occurs in the memory buffer. size_t PrefixLoc = Buffer.find(CheckPrefix); // If we didn't find a match, we're done. if (PrefixLoc == StringRef::npos) break; LineNumber += Buffer.substr(0, PrefixLoc).count('\n'); Buffer = Buffer.substr(PrefixLoc); const char *CheckPrefixStart = Buffer.data(); // When we find a check prefix, keep track of whether we find CHECK: or // CHECK-NEXT: bool IsCheckNext = false, IsCheckNot = false; // Verify that the : is present after the prefix. if (Buffer[CheckPrefix.size()] == ':') { Buffer = Buffer.substr(CheckPrefix.size()+1); } else if (Buffer.size() > CheckPrefix.size()+6 && memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) { Buffer = Buffer.substr(CheckPrefix.size()+6); IsCheckNext = true; } else if (Buffer.size() > CheckPrefix.size()+5 && memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) { Buffer = Buffer.substr(CheckPrefix.size()+5); IsCheckNot = true; } else { Buffer = Buffer.substr(1); continue; } // Okay, we found the prefix, yay. Remember the rest of the line, but // ignore leading and trailing whitespace. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t")); // Scan ahead to the end of line. size_t EOL = Buffer.find_first_of("\n\r"); // Remember the location of the start of the pattern, for diagnostics. SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data()); // Parse the pattern. Pattern P; if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber)) return true; Buffer = Buffer.substr(EOL); // Verify that CHECK-NEXT lines have at least one CHECK line before them. if (IsCheckNext && CheckStrings.empty()) { SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart), SourceMgr::DK_Error, "found '"+CheckPrefix+"-NEXT:' without previous '"+ CheckPrefix+ ": line"); return true; } // Handle CHECK-NOT. if (IsCheckNot) { NotMatches.push_back(P); continue; } // Okay, add the string we captured to the output vector and move on. CheckStrings.push_back(CheckString(P, PatternLoc, IsCheckNext)); std::swap(NotMatches, CheckStrings.back().NotStrings); } // Add an EOF pattern for any trailing CHECK-NOTs. if (!NotMatches.empty()) { CheckStrings.push_back(CheckString(Pattern(true), SMLoc::getFromPointer(Buffer.data()), false)); std::swap(NotMatches, CheckStrings.back().NotStrings); } if (CheckStrings.empty()) { errs() << "error: no check strings found with prefix '" << CheckPrefix << ":'\n"; return true; } return false; } static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr, StringRef Buffer, StringMap<StringRef> &VariableTable) { // Otherwise, we have an error, emit an error message. SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, "expected string not found in input"); // Print the "scanning from here" line. If the current position is at the // end of a line, advance to the start of the next line. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r")); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, "scanning from here"); // Allow the pattern to print additional information if desired. CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable); } /// CountNumNewlinesBetween - Count the number of newlines in the specified /// range. static unsigned CountNumNewlinesBetween(StringRef Range) { unsigned NumNewLines = 0; while (1) { // Scan for newline. Range = Range.substr(Range.find_first_of("\n\r")); if (Range.empty()) return NumNewLines; ++NumNewLines; // Handle \n\r and \r\n as a single newline. if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') && (Range[0] != Range[1])) Range = Range.substr(1); Range = Range.substr(1); } } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); SourceMgr SM; // Read the expected strings from the check file. std::vector<CheckString> CheckStrings; if (ReadCheckFile(SM, CheckStrings)) return 2; // Open the file to check and add it to SourceMgr. OwningPtr<MemoryBuffer> File; if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) { errs() << "Could not open input file '" << InputFilename << "': " << ec.message() << '\n'; return 2; } if (File->getBufferSize() == 0) { errs() << "FileCheck error: '" << InputFilename << "' is empty.\n"; return 2; } // Remove duplicate spaces in the input file if requested. // Remove DOS style line endings. MemoryBuffer *F = CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace); SM.AddNewSourceBuffer(F, SMLoc()); /// VariableTable - This holds all the current filecheck variables. StringMap<StringRef> VariableTable; // Check that we have all of the expected strings, in order, in the input // file. StringRef Buffer = F->getBuffer(); const char *LastMatch = Buffer.data(); for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) { const CheckString &CheckStr = CheckStrings[StrNo]; StringRef SearchFrom = Buffer; // Find StrNo in the file. size_t MatchLen = 0; size_t MatchPos = CheckStr.Pat.Match(Buffer, MatchLen, VariableTable); Buffer = Buffer.substr(MatchPos); // If we didn't find a match, reject the input. if (MatchPos == StringRef::npos) { PrintCheckFailed(SM, CheckStr, SearchFrom, VariableTable); return 1; } StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch); // If this check is a "CHECK-NEXT", verify that the previous match was on // the previous line (i.e. that there is one newline between them). if (CheckStr.IsCheckNext) { // Count the number of newlines between the previous match and this one. assert(LastMatch != F->getBufferStart() && "CHECK-NEXT can't be the first check in a file"); unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion); if (NumNewLines == 0) { SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+"-NEXT: is on the same line as previous match"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, "'next' match was here"); SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note, "previous match was here"); return 1; } if (NumNewLines != 1) { SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+ "-NEXT: is not on the line after the previous match"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, "'next' match was here"); SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note, "previous match was here"); return 1; } } // If this match had "not strings", verify that they don't exist in the // skipped region. for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size(); ChunkNo != e; ++ChunkNo) { size_t MatchLen = 0; size_t Pos = CheckStr.NotStrings[ChunkNo].Match(SkippedRegion, MatchLen, VariableTable); if (Pos == StringRef::npos) continue; SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos), SourceMgr::DK_Error, CheckPrefix+"-NOT: string occurred!"); SM.PrintMessage(CheckStr.NotStrings[ChunkNo].getLoc(), SourceMgr::DK_Note, CheckPrefix+"-NOT: pattern specified here"); return 1; } // Otherwise, everything is good. Step over the matched text and remember // the position after the match as the end of the last match. Buffer = Buffer.substr(MatchLen); LastMatch = Buffer.data(); } return 0; } Refactor string checking. No functionality change. git-svn-id: a4a6f32337ebd29ad4763b423022f00f68d1c7b7@181824 91177308-0d34-0410-b5e6-96231b3b80d8 //===- FileCheck.cpp - Check that File's Contents match what is expected --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // FileCheck does a line-by line check of a file that validates whether it // contains the expected content. This is useful for regression tests etc. // // This program exits with an error status of 2 on error, exit status of 0 if // the file matched the expected contents, and exit status of 1 if it did not // contain the expected contents. // //===----------------------------------------------------------------------===// #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Regex.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/system_error.h" #include <algorithm> #include <map> #include <string> #include <vector> using namespace llvm; static cl::opt<std::string> CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required); static cl::opt<std::string> InputFilename("input-file", cl::desc("File to check (defaults to stdin)"), cl::init("-"), cl::value_desc("filename")); static cl::opt<std::string> CheckPrefix("check-prefix", cl::init("CHECK"), cl::desc("Prefix to use from check file (defaults to 'CHECK')")); static cl::opt<bool> NoCanonicalizeWhiteSpace("strict-whitespace", cl::desc("Do not treat all horizontal whitespace as equivalent")); //===----------------------------------------------------------------------===// // Pattern Handling Code. //===----------------------------------------------------------------------===// class Pattern { SMLoc PatternLoc; /// MatchEOF - When set, this pattern only matches the end of file. This is /// used for trailing CHECK-NOTs. bool MatchEOF; /// FixedStr - If non-empty, this pattern is a fixed string match with the /// specified fixed string. StringRef FixedStr; /// RegEx - If non-empty, this is a regex pattern. std::string RegExStr; /// \brief Contains the number of line this pattern is in. unsigned LineNumber; /// VariableUses - Entries in this vector map to uses of a variable in the /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain /// "foobaz" and we'll get an entry in this vector that tells us to insert the /// value of bar at offset 3. std::vector<std::pair<StringRef, unsigned> > VariableUses; /// VariableDefs - Maps definitions of variables to their parenthesized /// capture numbers. /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1. std::map<StringRef, unsigned> VariableDefs; public: Pattern(bool matchEOF = false) : MatchEOF(matchEOF) { } /// getLoc - Return the location in source code. SMLoc getLoc() const { return PatternLoc; } /// ParsePattern - Parse the given string into the Pattern. SM provides the /// SourceMgr used for error reports, and LineNumber is the line number in /// the input file from which the pattern string was read. /// Returns true in case of an error, false otherwise. bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber); /// Match - Match the pattern string against the input buffer Buffer. This /// returns the position that is matched or npos if there is no match. If /// there is a match, the size of the matched string is returned in MatchLen. /// /// The VariableTable StringMap provides the current values of filecheck /// variables and is updated if this match defines new values. size_t Match(StringRef Buffer, size_t &MatchLen, StringMap<StringRef> &VariableTable) const; /// PrintFailureInfo - Print additional information about a failure to match /// involving this pattern. void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, const StringMap<StringRef> &VariableTable) const; private: static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr); bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM); void AddBackrefToRegEx(unsigned BackrefNum); /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of /// matching this pattern at the start of \arg Buffer; a distance of zero /// should correspond to a perfect match. unsigned ComputeMatchDistance(StringRef Buffer, const StringMap<StringRef> &VariableTable) const; /// \brief Evaluates expression and stores the result to \p Value. /// \return true on success. false when the expression has invalid syntax. bool EvaluateExpression(StringRef Expr, std::string &Value) const; /// \brief Finds the closing sequence of a regex variable usage or /// definition. Str has to point in the beginning of the definition /// (right after the opening sequence). /// \return offset of the closing sequence within Str, or npos if it was not /// found. size_t FindRegexVarEnd(StringRef Str); }; bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber) { this->LineNumber = LineNumber; PatternLoc = SMLoc::getFromPointer(PatternStr.data()); // Ignore trailing whitespace. while (!PatternStr.empty() && (PatternStr.back() == ' ' || PatternStr.back() == '\t')) PatternStr = PatternStr.substr(0, PatternStr.size()-1); // Check that there is something on the line. if (PatternStr.empty()) { SM.PrintMessage(PatternLoc, SourceMgr::DK_Error, "found empty check string with prefix '" + CheckPrefix+":'"); return true; } // Check to see if this is a fixed string, or if it has regex pieces. if (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos && PatternStr.find("[[") == StringRef::npos)) { FixedStr = PatternStr; return false; } // Paren value #0 is for the fully matched string. Any new parenthesized // values add from there. unsigned CurParen = 1; // Otherwise, there is at least one regex piece. Build up the regex pattern // by escaping scary characters in fixed strings, building up one big regex. while (!PatternStr.empty()) { // RegEx matches. if (PatternStr.startswith("{{")) { // This is the start of a regex match. Scan for the }}. size_t End = PatternStr.find("}}"); if (End == StringRef::npos) { SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()), SourceMgr::DK_Error, "found start of regex string with no end '}}'"); return true; } // Enclose {{}} patterns in parens just like [[]] even though we're not // capturing the result for any purpose. This is required in case the // expression contains an alternation like: CHECK: abc{{x|z}}def. We // want this to turn into: "abc(x|z)def" not "abcx|zdef". RegExStr += '('; ++CurParen; if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM)) return true; RegExStr += ')'; PatternStr = PatternStr.substr(End+2); continue; } // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .* // (or some other regex) and assigns it to the FileCheck variable 'foo'. The // second form is [[foo]] which is a reference to foo. The variable name // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject // it. This is to catch some common errors. if (PatternStr.startswith("[[")) { // Find the closing bracket pair ending the match. End is going to be an // offset relative to the beginning of the match string. size_t End = FindRegexVarEnd(PatternStr.substr(2)); if (End == StringRef::npos) { SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()), SourceMgr::DK_Error, "invalid named regex reference, no ]] found"); return true; } StringRef MatchStr = PatternStr.substr(2, End); PatternStr = PatternStr.substr(End+4); // Get the regex name (e.g. "foo"). size_t NameEnd = MatchStr.find(':'); StringRef Name = MatchStr.substr(0, NameEnd); if (Name.empty()) { SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, "invalid name in named regex: empty name"); return true; } // Verify that the name/expression is well formed. FileCheck currently // supports @LINE, @LINE+number, @LINE-number expressions. The check here // is relaxed, more strict check is performed in \c EvaluateExpression. bool IsExpression = false; for (unsigned i = 0, e = Name.size(); i != e; ++i) { if (i == 0 && Name[i] == '@') { if (NameEnd != StringRef::npos) { SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, "invalid name in named regex definition"); return true; } IsExpression = true; continue; } if (Name[i] != '_' && !isalnum(Name[i]) && (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) { SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i), SourceMgr::DK_Error, "invalid name in named regex"); return true; } } // Name can't start with a digit. if (isdigit(static_cast<unsigned char>(Name[0]))) { SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, "invalid name in named regex"); return true; } // Handle [[foo]]. if (NameEnd == StringRef::npos) { // Handle variables that were defined earlier on the same line by // emitting a backreference. if (VariableDefs.find(Name) != VariableDefs.end()) { unsigned VarParenNum = VariableDefs[Name]; if (VarParenNum < 1 || VarParenNum > 9) { SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, "Can't back-reference more than 9 variables"); return true; } AddBackrefToRegEx(VarParenNum); } else { VariableUses.push_back(std::make_pair(Name, RegExStr.size())); } continue; } // Handle [[foo:.*]]. VariableDefs[Name] = CurParen; RegExStr += '('; ++CurParen; if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM)) return true; RegExStr += ')'; } // Handle fixed string matches. // Find the end, which is the start of the next regex. size_t FixedMatchEnd = PatternStr.find("{{"); FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[[")); AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr); PatternStr = PatternStr.substr(FixedMatchEnd); } return false; } void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) { // Add the characters from FixedStr to the regex, escaping as needed. This // avoids "leaning toothpicks" in common patterns. for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) { switch (FixedStr[i]) { // These are the special characters matched in "p_ere_exp". case '(': case ')': case '^': case '$': case '|': case '*': case '+': case '?': case '.': case '[': case '\\': case '{': TheStr += '\\'; // FALL THROUGH. default: TheStr += FixedStr[i]; break; } } } bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) { Regex R(RS); std::string Error; if (!R.isValid(Error)) { SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error, "invalid regex: " + Error); return true; } RegExStr += RS.str(); CurParen += R.getNumMatches(); return false; } void Pattern::AddBackrefToRegEx(unsigned BackrefNum) { assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number"); std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum); RegExStr += Backref; } bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const { // The only supported expression is @LINE([\+-]\d+)? if (!Expr.startswith("@LINE")) return false; Expr = Expr.substr(StringRef("@LINE").size()); int Offset = 0; if (!Expr.empty()) { if (Expr[0] == '+') Expr = Expr.substr(1); else if (Expr[0] != '-') return false; if (Expr.getAsInteger(10, Offset)) return false; } Value = llvm::itostr(LineNumber + Offset); return true; } /// Match - Match the pattern string against the input buffer Buffer. This /// returns the position that is matched or npos if there is no match. If /// there is a match, the size of the matched string is returned in MatchLen. size_t Pattern::Match(StringRef Buffer, size_t &MatchLen, StringMap<StringRef> &VariableTable) const { // If this is the EOF pattern, match it immediately. if (MatchEOF) { MatchLen = 0; return Buffer.size(); } // If this is a fixed string pattern, just match it now. if (!FixedStr.empty()) { MatchLen = FixedStr.size(); return Buffer.find(FixedStr); } // Regex match. // If there are variable uses, we need to create a temporary string with the // actual value. StringRef RegExToMatch = RegExStr; std::string TmpStr; if (!VariableUses.empty()) { TmpStr = RegExStr; unsigned InsertOffset = 0; for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) { std::string Value; if (VariableUses[i].first[0] == '@') { if (!EvaluateExpression(VariableUses[i].first, Value)) return StringRef::npos; } else { StringMap<StringRef>::iterator it = VariableTable.find(VariableUses[i].first); // If the variable is undefined, return an error. if (it == VariableTable.end()) return StringRef::npos; // Look up the value and escape it so that we can plop it into the regex. AddFixedStringToRegEx(it->second, Value); } // Plop it into the regex at the adjusted offset. TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset, Value.begin(), Value.end()); InsertOffset += Value.size(); } // Match the newly constructed regex. RegExToMatch = TmpStr; } SmallVector<StringRef, 4> MatchInfo; if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo)) return StringRef::npos; // Successful regex match. assert(!MatchInfo.empty() && "Didn't get any match"); StringRef FullMatch = MatchInfo[0]; // If this defines any variables, remember their values. for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(), E = VariableDefs.end(); I != E; ++I) { assert(I->second < MatchInfo.size() && "Internal paren error"); VariableTable[I->first] = MatchInfo[I->second]; } MatchLen = FullMatch.size(); return FullMatch.data()-Buffer.data(); } unsigned Pattern::ComputeMatchDistance(StringRef Buffer, const StringMap<StringRef> &VariableTable) const { // Just compute the number of matching characters. For regular expressions, we // just compare against the regex itself and hope for the best. // // FIXME: One easy improvement here is have the regex lib generate a single // example regular expression which matches, and use that as the example // string. StringRef ExampleString(FixedStr); if (ExampleString.empty()) ExampleString = RegExStr; // Only compare up to the first line in the buffer, or the string size. StringRef BufferPrefix = Buffer.substr(0, ExampleString.size()); BufferPrefix = BufferPrefix.split('\n').first; return BufferPrefix.edit_distance(ExampleString); } void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, const StringMap<StringRef> &VariableTable) const{ // If this was a regular expression using variables, print the current // variable values. if (!VariableUses.empty()) { for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) { SmallString<256> Msg; raw_svector_ostream OS(Msg); StringRef Var = VariableUses[i].first; if (Var[0] == '@') { std::string Value; if (EvaluateExpression(Var, Value)) { OS << "with expression \""; OS.write_escaped(Var) << "\" equal to \""; OS.write_escaped(Value) << "\""; } else { OS << "uses incorrect expression \""; OS.write_escaped(Var) << "\""; } } else { StringMap<StringRef>::const_iterator it = VariableTable.find(Var); // Check for undefined variable references. if (it == VariableTable.end()) { OS << "uses undefined variable \""; OS.write_escaped(Var) << "\""; } else { OS << "with variable \""; OS.write_escaped(Var) << "\" equal to \""; OS.write_escaped(it->second) << "\""; } } SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, OS.str()); } } // Attempt to find the closest/best fuzzy match. Usually an error happens // because some string in the output didn't exactly match. In these cases, we // would like to show the user a best guess at what "should have" matched, to // save them having to actually check the input manually. size_t NumLinesForward = 0; size_t Best = StringRef::npos; double BestQuality = 0; // Use an arbitrary 4k limit on how far we will search. for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) { if (Buffer[i] == '\n') ++NumLinesForward; // Patterns have leading whitespace stripped, so skip whitespace when // looking for something which looks like a pattern. if (Buffer[i] == ' ' || Buffer[i] == '\t') continue; // Compute the "quality" of this match as an arbitrary combination of the // match distance and the number of lines skipped to get to this match. unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable); double Quality = Distance + (NumLinesForward / 100.); if (Quality < BestQuality || Best == StringRef::npos) { Best = i; BestQuality = Quality; } } // Print the "possible intended match here" line if we found something // reasonable and not equal to what we showed in the "scanning from here" // line. if (Best && Best != StringRef::npos && BestQuality < 50) { SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best), SourceMgr::DK_Note, "possible intended match here"); // FIXME: If we wanted to be really friendly we would show why the match // failed, as it can be hard to spot simple one character differences. } } size_t Pattern::FindRegexVarEnd(StringRef Str) { // Offset keeps track of the current offset within the input Str size_t Offset = 0; // [...] Nesting depth size_t BracketDepth = 0; while (!Str.empty()) { if (Str.startswith("]]") && BracketDepth == 0) return Offset; if (Str[0] == '\\') { // Backslash escapes the next char within regexes, so skip them both. Str = Str.substr(2); Offset += 2; } else { switch (Str[0]) { default: break; case '[': BracketDepth++; break; case ']': assert(BracketDepth > 0 && "Invalid regex"); BracketDepth--; break; } Str = Str.substr(1); Offset++; } } return StringRef::npos; } //===----------------------------------------------------------------------===// // Check Strings. //===----------------------------------------------------------------------===// /// CheckString - This is a check that we found in the input file. struct CheckString { /// Pat - The pattern to match. Pattern Pat; /// Loc - The location in the match file that the check string was specified. SMLoc Loc; /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed /// to a CHECK: directive. bool IsCheckNext; /// NotStrings - These are all of the strings that are disallowed from /// occurring between this match string and the previous one (or start of /// file). std::vector<Pattern> NotStrings; CheckString(const Pattern &P, SMLoc L, bool isCheckNext) : Pat(P), Loc(L), IsCheckNext(isCheckNext) {} /// Check - Match check string and its "not strings". size_t Check(const SourceMgr &SM, StringRef Buffer, size_t &MatchLen, StringMap<StringRef> &VariableTable) const; /// CheckNext - Verify there is a single line in the given buffer. bool CheckNext(const SourceMgr &SM, StringRef Buffer) const; /// CheckNot - Verify there's no "not strings" in the given buffer. bool CheckNot(const SourceMgr &SM, StringRef Buffer, StringMap<StringRef> &VariableTable) const; }; /// Canonicalize whitespaces in the input file. Line endings are replaced /// with UNIX-style '\n'. /// /// \param PreserveHorizontal Don't squash consecutive horizontal whitespace /// characters to a single space. static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB, bool PreserveHorizontal) { SmallString<128> NewFile; NewFile.reserve(MB->getBufferSize()); for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd(); Ptr != End; ++Ptr) { // Eliminate trailing dosish \r. if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') { continue; } // If current char is not a horizontal whitespace or if horizontal // whitespace canonicalization is disabled, dump it to output as is. if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) { NewFile.push_back(*Ptr); continue; } // Otherwise, add one space and advance over neighboring space. NewFile.push_back(' '); while (Ptr+1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t')) ++Ptr; } // Free the old buffer and return a new one. MemoryBuffer *MB2 = MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier()); delete MB; return MB2; } /// ReadCheckFile - Read the check file, which specifies the sequence of /// expected strings. The strings are added to the CheckStrings vector. /// Returns true in case of an error, false otherwise. static bool ReadCheckFile(SourceMgr &SM, std::vector<CheckString> &CheckStrings) { OwningPtr<MemoryBuffer> File; if (error_code ec = MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) { errs() << "Could not open check file '" << CheckFilename << "': " << ec.message() << '\n'; return true; } // If we want to canonicalize whitespace, strip excess whitespace from the // buffer containing the CHECK lines. Remove DOS style line endings. MemoryBuffer *F = CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace); SM.AddNewSourceBuffer(F, SMLoc()); // Find all instances of CheckPrefix followed by : in the file. StringRef Buffer = F->getBuffer(); std::vector<Pattern> NotMatches; // LineNumber keeps track of the line on which CheckPrefix instances are // found. unsigned LineNumber = 1; while (1) { // See if Prefix occurs in the memory buffer. size_t PrefixLoc = Buffer.find(CheckPrefix); // If we didn't find a match, we're done. if (PrefixLoc == StringRef::npos) break; LineNumber += Buffer.substr(0, PrefixLoc).count('\n'); Buffer = Buffer.substr(PrefixLoc); const char *CheckPrefixStart = Buffer.data(); // When we find a check prefix, keep track of whether we find CHECK: or // CHECK-NEXT: bool IsCheckNext = false, IsCheckNot = false; // Verify that the : is present after the prefix. if (Buffer[CheckPrefix.size()] == ':') { Buffer = Buffer.substr(CheckPrefix.size()+1); } else if (Buffer.size() > CheckPrefix.size()+6 && memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) { Buffer = Buffer.substr(CheckPrefix.size()+6); IsCheckNext = true; } else if (Buffer.size() > CheckPrefix.size()+5 && memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) { Buffer = Buffer.substr(CheckPrefix.size()+5); IsCheckNot = true; } else { Buffer = Buffer.substr(1); continue; } // Okay, we found the prefix, yay. Remember the rest of the line, but // ignore leading and trailing whitespace. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t")); // Scan ahead to the end of line. size_t EOL = Buffer.find_first_of("\n\r"); // Remember the location of the start of the pattern, for diagnostics. SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data()); // Parse the pattern. Pattern P; if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber)) return true; Buffer = Buffer.substr(EOL); // Verify that CHECK-NEXT lines have at least one CHECK line before them. if (IsCheckNext && CheckStrings.empty()) { SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart), SourceMgr::DK_Error, "found '"+CheckPrefix+"-NEXT:' without previous '"+ CheckPrefix+ ": line"); return true; } // Handle CHECK-NOT. if (IsCheckNot) { NotMatches.push_back(P); continue; } // Okay, add the string we captured to the output vector and move on. CheckStrings.push_back(CheckString(P, PatternLoc, IsCheckNext)); std::swap(NotMatches, CheckStrings.back().NotStrings); } // Add an EOF pattern for any trailing CHECK-NOTs. if (!NotMatches.empty()) { CheckStrings.push_back(CheckString(Pattern(true), SMLoc::getFromPointer(Buffer.data()), false)); std::swap(NotMatches, CheckStrings.back().NotStrings); } if (CheckStrings.empty()) { errs() << "error: no check strings found with prefix '" << CheckPrefix << ":'\n"; return true; } return false; } static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr, StringRef Buffer, StringMap<StringRef> &VariableTable) { // Otherwise, we have an error, emit an error message. SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, "expected string not found in input"); // Print the "scanning from here" line. If the current position is at the // end of a line, advance to the start of the next line. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r")); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, "scanning from here"); // Allow the pattern to print additional information if desired. CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable); } /// CountNumNewlinesBetween - Count the number of newlines in the specified /// range. static unsigned CountNumNewlinesBetween(StringRef Range) { unsigned NumNewLines = 0; while (1) { // Scan for newline. Range = Range.substr(Range.find_first_of("\n\r")); if (Range.empty()) return NumNewLines; ++NumNewLines; // Handle \n\r and \r\n as a single newline. if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') && (Range[0] != Range[1])) Range = Range.substr(1); Range = Range.substr(1); } } size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer, size_t &MatchLen, StringMap<StringRef> &VariableTable) const { size_t MatchPos = Pat.Match(Buffer, MatchLen, VariableTable); if (MatchPos == StringRef::npos) { PrintCheckFailed(SM, *this, Buffer, VariableTable); return StringRef::npos; } StringRef SkippedRegion = Buffer.substr(0, MatchPos); // If this check is a "CHECK-NEXT", verify that the previous match was on // the previous line (i.e. that there is one newline between them). if (CheckNext(SM, SkippedRegion)) return StringRef::npos; // If this match had "not strings", verify that they don't exist in the // skipped region. if (CheckNot(SM, SkippedRegion, VariableTable)) return StringRef::npos; return MatchPos; } bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const { if (!IsCheckNext) return false; // Count the number of newlines between the previous match and this one. assert(Buffer.data() != SM.getMemoryBuffer( SM.FindBufferContainingLoc( SMLoc::getFromPointer(Buffer.data())))->getBufferStart() && "CHECK-NEXT can't be the first check in a file"); unsigned NumNewLines = CountNumNewlinesBetween(Buffer); if (NumNewLines == 0) { SM.PrintMessage(Loc, SourceMgr::DK_Error, CheckPrefix+ "-NEXT: is on the same line as previous match"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note, "'next' match was here"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, "previous match ended here"); return true; } if (NumNewLines != 1) { SM.PrintMessage(Loc, SourceMgr::DK_Error, CheckPrefix+ "-NEXT: is not on the line after the previous match"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note, "'next' match was here"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, "previous match ended here"); return true; } return false; } bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer, StringMap<StringRef> &VariableTable) const { for (unsigned ChunkNo = 0, e = NotStrings.size(); ChunkNo != e; ++ChunkNo) { size_t MatchLen = 0; size_t Pos = NotStrings[ChunkNo].Match(Buffer, MatchLen, VariableTable); if (Pos == StringRef::npos) continue; SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos), SourceMgr::DK_Error, CheckPrefix+"-NOT: string occurred!"); SM.PrintMessage(NotStrings[ChunkNo].getLoc(), SourceMgr::DK_Note, CheckPrefix+"-NOT: pattern specified here"); return true; } return false; } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); SourceMgr SM; // Read the expected strings from the check file. std::vector<CheckString> CheckStrings; if (ReadCheckFile(SM, CheckStrings)) return 2; // Open the file to check and add it to SourceMgr. OwningPtr<MemoryBuffer> File; if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) { errs() << "Could not open input file '" << InputFilename << "': " << ec.message() << '\n'; return 2; } if (File->getBufferSize() == 0) { errs() << "FileCheck error: '" << InputFilename << "' is empty.\n"; return 2; } // Remove duplicate spaces in the input file if requested. // Remove DOS style line endings. MemoryBuffer *F = CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace); SM.AddNewSourceBuffer(F, SMLoc()); /// VariableTable - This holds all the current filecheck variables. StringMap<StringRef> VariableTable; // Check that we have all of the expected strings, in order, in the input // file. StringRef Buffer = F->getBuffer(); for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) { const CheckString &CheckStr = CheckStrings[StrNo]; // Find StrNo in the file. size_t MatchLen = 0; size_t MatchPos = CheckStr.Check(SM, Buffer, MatchLen, VariableTable); if (MatchPos == StringRef::npos) return 1; Buffer = Buffer.substr(MatchPos + MatchLen); } return 0; }
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "branchadddialog.h" #include "ui_branchadddialog.h" #include <utils/hostosinfo.h> #include <QPushButton> #include <QValidator> namespace Git { namespace Internal { /*! * \brief The BranchNameValidator class validates the corresponding string as * a valid Git branch name. * * The class does this by a couple of rules that are applied on the string. * */ class BranchNameValidator : public QValidator { public: BranchNameValidator(const QStringList &localBranches, QObject *parent = 0) : QValidator(parent), m_invalidChars(QLatin1String( "\\s" // no whitespace "|~" // no "~" "|\\^" // no "^" "|\\[" // no "[" "|\\.\\." // no ".." "|/\\." // no slashdot "|:" // no ":" "|@\\{" // no "@{" sequence "|\\\\" // no backslash "|//" // no double slash "|^[/-]" // no leading slash or dash )), m_localBranches(localBranches) { } ~BranchNameValidator() {} State validate(QString &input, int &pos) const { Q_UNUSED(pos) // NoGos if (input.contains(m_invalidChars)) return Invalid; // "Intermediate" patterns, may change to Acceptable when user edits further: if (input.endsWith(QLatin1String(".lock"))) //..may not end with ".lock" return Intermediate; if (input.endsWith(QLatin1Char('.'))) // no dot at the end (but allowed in the middle) return Intermediate; if (input.endsWith(QLatin1Char('/'))) // no slash at the end (but allowed in the middle) return Intermediate; if (m_localBranches.contains(input, Utils::HostOsInfo::isWindowsHost() ? Qt::CaseInsensitive : Qt::CaseSensitive)) { return Intermediate; } // is a valid branch name return Acceptable; } private: const QRegExp m_invalidChars; QStringList m_localBranches; }; BranchAddDialog::BranchAddDialog(const QStringList &localBranches, bool addBranch, QWidget *parent) : QDialog(parent), m_ui(new Ui::BranchAddDialog) { m_ui->setupUi(this); setWindowTitle(addBranch ? tr("Add Branch") : tr("Rename Branch")); m_ui->branchNameEdit->setValidator(new BranchNameValidator(localBranches, this)); connect(m_ui->branchNameEdit, SIGNAL(textChanged(QString)), this, SLOT(updateButtonStatus())); } BranchAddDialog::~BranchAddDialog() { delete m_ui; } void BranchAddDialog::setBranchName(const QString &n) { m_ui->branchNameEdit->setText(n); m_ui->branchNameEdit->selectAll(); } QString BranchAddDialog::branchName() const { return m_ui->branchNameEdit->text(); } void BranchAddDialog::setTrackedBranchName(const QString &name, bool remote) { m_ui->trackingCheckBox->setVisible(true); if (!name.isEmpty()) { m_ui->trackingCheckBox->setText(remote ? tr("Track remote branch \'%1\'").arg(name) : tr("Track local branch \'%1\'").arg(name)); m_ui->trackingCheckBox->setChecked(remote); } else { m_ui->trackingCheckBox->setVisible(false); m_ui->trackingCheckBox->setChecked(false); } } bool BranchAddDialog::track() { return m_ui->trackingCheckBox->isChecked(); } /*! Updates the ok button enabled state of the dialog according to the validity of the branch name. */ void BranchAddDialog::updateButtonStatus() { m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(m_ui->branchNameEdit->hasAcceptableInput()); } } // namespace Internal } // namespace Git Git: Fix comment indentation in BranchAddDialog Change-Id: Ia1cd72b598555681e62444f6843a746049c5c04d Reviewed-by: Orgad Shaneh <2b010cbad792a0c0a8175f752f93f83941fc6bc1@gmail.com> /**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "branchadddialog.h" #include "ui_branchadddialog.h" #include <utils/hostosinfo.h> #include <QPushButton> #include <QValidator> namespace Git { namespace Internal { /*! * \brief The BranchNameValidator class validates the corresponding string as * a valid Git branch name. * * The class does this by a couple of rules that are applied on the string. * */ class BranchNameValidator : public QValidator { public: BranchNameValidator(const QStringList &localBranches, QObject *parent = 0) : QValidator(parent), m_invalidChars(QLatin1String( "\\s" // no whitespace "|~" // no "~" "|\\^" // no "^" "|\\[" // no "[" "|\\.\\." // no ".." "|/\\." // no slashdot "|:" // no ":" "|@\\{" // no "@{" sequence "|\\\\" // no backslash "|//" // no double slash "|^[/-]" // no leading slash or dash )), m_localBranches(localBranches) { } ~BranchNameValidator() {} State validate(QString &input, int &pos) const { Q_UNUSED(pos) // NoGos if (input.contains(m_invalidChars)) return Invalid; // "Intermediate" patterns, may change to Acceptable when user edits further: if (input.endsWith(QLatin1String(".lock"))) //..may not end with ".lock" return Intermediate; if (input.endsWith(QLatin1Char('.'))) // no dot at the end (but allowed in the middle) return Intermediate; if (input.endsWith(QLatin1Char('/'))) // no slash at the end (but allowed in the middle) return Intermediate; if (m_localBranches.contains(input, Utils::HostOsInfo::isWindowsHost() ? Qt::CaseInsensitive : Qt::CaseSensitive)) { return Intermediate; } // is a valid branch name return Acceptable; } private: const QRegExp m_invalidChars; QStringList m_localBranches; }; BranchAddDialog::BranchAddDialog(const QStringList &localBranches, bool addBranch, QWidget *parent) : QDialog(parent), m_ui(new Ui::BranchAddDialog) { m_ui->setupUi(this); setWindowTitle(addBranch ? tr("Add Branch") : tr("Rename Branch")); m_ui->branchNameEdit->setValidator(new BranchNameValidator(localBranches, this)); connect(m_ui->branchNameEdit, SIGNAL(textChanged(QString)), this, SLOT(updateButtonStatus())); } BranchAddDialog::~BranchAddDialog() { delete m_ui; } void BranchAddDialog::setBranchName(const QString &n) { m_ui->branchNameEdit->setText(n); m_ui->branchNameEdit->selectAll(); } QString BranchAddDialog::branchName() const { return m_ui->branchNameEdit->text(); } void BranchAddDialog::setTrackedBranchName(const QString &name, bool remote) { m_ui->trackingCheckBox->setVisible(true); if (!name.isEmpty()) { m_ui->trackingCheckBox->setText(remote ? tr("Track remote branch \'%1\'").arg(name) : tr("Track local branch \'%1\'").arg(name)); m_ui->trackingCheckBox->setChecked(remote); } else { m_ui->trackingCheckBox->setVisible(false); m_ui->trackingCheckBox->setChecked(false); } } bool BranchAddDialog::track() { return m_ui->trackingCheckBox->isChecked(); } /*! Updates the ok button enabled state of the dialog according to the validity of the branch name. */ void BranchAddDialog::updateButtonStatus() { m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(m_ui->branchNameEdit->hasAcceptableInput()); } } // namespace Internal } // namespace Git
#include "xbl_manager.h" #include "halley/support/logger.h" #include "halley/text/halleystring.h" #include <winrt/Windows.UI.Core.h> #include <winrt/Windows.Gaming.XboxLive.Storage.h> #include "xsapi/services.h" #include "halley/concurrency/concurrent.h" #include <winrt/Windows.System.UserProfile.h> using namespace Halley; template <typename T> T from_cx(Platform::Object^ from) { T to{ nullptr }; winrt::check_hresult(reinterpret_cast<::IUnknown*>(from) ->QueryInterface(winrt::guid_of<T>(), reinterpret_cast<void**>(winrt::put_abi(to)))); return to; } template <typename T> T^ to_cx(winrt::Windows::Foundation::IUnknown const& from) { return safe_cast<T^>(reinterpret_cast<Platform::Object^>(winrt::get_abi(from))); } XBLManager::XBLManager() { } XBLManager::~XBLManager() { deInit(); } void XBLManager::init() { signIn(); } void XBLManager::deInit() { } void XBLManager::signIn() { using namespace xbox::services::system; xboxUser = std::make_shared<xbox_live_user>(nullptr); auto dispatcher = to_cx<Platform::Object>(winrt::Windows::UI::Core::CoreWindow::GetForCurrentThread().Dispatcher()); xboxUser->signin_silently(dispatcher).then([=] (xbox::services::xbox_live_result<sign_in_result> result) -> winrt::Windows::Foundation::IAsyncAction { if (result.err()) { Logger::logError(String("Error signing in to Xbox Live: ") + result.err_message()); } else { bool loggedIn = false; switch (result.payload().status()) { case success: loggedIn = true; break; case user_interaction_required: xboxUser->signin(dispatcher).then([&](xbox::services::xbox_live_result<sign_in_result> loudResult) { if (!loudResult.err()) { auto resPayload = loudResult.payload(); switch (resPayload.status()) { case success: loggedIn = true; break; case user_cancel: break; } } }, concurrency::task_continuation_context::use_current()); break; } if (loggedIn) { xboxLiveContext = std::make_shared<xbox::services::xbox_live_context>(xboxUser); xbox_live_user::add_sign_out_completed_handler([this](const sign_out_completed_event_args&) { xboxUser.reset(); xboxLiveContext.reset(); }); } } co_await getConnectedStorage(); Logger::logInfo("Storage thread done."); }); } winrt::Windows::Foundation::IAsyncAction XBLManager::getConnectedStorage() { using namespace winrt::Windows::Gaming::XboxLive::Storage; auto windowsUser = co_await winrt::Windows::System::User::FindAllAsync(); //auto user = from_cx<winrt::Windows::System::User>(windowsUser.First()); GameSaveProviderGetResult result = co_await GameSaveProvider::GetForUserAsync(*windowsUser.First(), xboxLiveContext->application_config()->scid()); if (result.Status() == GameSaveErrorStatus::Ok) { gameSaveProvider = result.Value(); Logger::logInfo("Got game save provider"); } } aaaaaaaaahhh #include "xbl_manager.h" #include "halley/support/logger.h" #include "halley/text/halleystring.h" #include <winrt/Windows.UI.Core.h> #include <winrt/Windows.Gaming.XboxLive.Storage.h> #include "xsapi/services.h" #include "halley/concurrency/concurrent.h" #include <winrt/Windows.System.UserProfile.h> using namespace Halley; template <typename T> T from_cx(Platform::Object^ from) { T to{ nullptr }; winrt::check_hresult(reinterpret_cast<::IUnknown*>(from) ->QueryInterface(winrt::guid_of<T>(), reinterpret_cast<void**>(winrt::put_abi(to)))); return to; } template <typename T> T^ to_cx(winrt::Windows::Foundation::IUnknown const& from) { return safe_cast<T^>(reinterpret_cast<Platform::Object^>(winrt::get_abi(from))); } XBLManager::XBLManager() { } XBLManager::~XBLManager() { deInit(); } void XBLManager::init() { signIn(); } void XBLManager::deInit() { } void XBLManager::signIn() { using namespace xbox::services::system; xboxUser = std::make_shared<xbox_live_user>(nullptr); auto dispatcher = to_cx<Platform::Object>(winrt::Windows::UI::Core::CoreWindow::GetForCurrentThread().Dispatcher()); xboxUser->signin_silently(dispatcher).then([=] (xbox::services::xbox_live_result<sign_in_result> result) -> winrt::Windows::Foundation::IAsyncAction { if (result.err()) { Logger::logError(String("Error signing in to Xbox Live: ") + result.err_message()); } else { bool loggedIn = false; switch (result.payload().status()) { case success: loggedIn = true; break; case user_interaction_required: xboxUser->signin(dispatcher).then([&](xbox::services::xbox_live_result<sign_in_result> loudResult) { if (!loudResult.err()) { auto resPayload = loudResult.payload(); switch (resPayload.status()) { case success: loggedIn = true; break; case user_cancel: break; } } }, concurrency::task_continuation_context::use_current()); break; } if (loggedIn) { xboxLiveContext = std::make_shared<xbox::services::xbox_live_context>(xboxUser); xbox_live_user::add_sign_out_completed_handler([this](const sign_out_completed_event_args&) { xboxUser.reset(); xboxLiveContext.reset(); }); } } co_await getConnectedStorage(); Logger::logInfo("Storage thread done."); }); } winrt::Windows::Foundation::IAsyncAction XBLManager::getConnectedStorage() { using namespace winrt::Windows::Gaming::XboxLive::Storage; auto windowsUser = co_await winrt::Windows::System::User::FindAllAsync(); //auto user = from_cx<winrt::Windows::System::User>(windowsUser.First()); GameSaveProviderGetResult result = co_await GameSaveProvider::GetForUserAsync(*windowsUser.First(), xboxLiveContext->application_config()->scid()); if (result.Status() == GameSaveErrorStatus::Ok) { gameSaveProvider = result.Value(); Logger::logInfo("Got game save provider"); auto container = gameSaveProvider.get().CreateContainer(L"save"); auto dataWriter = winrt::Windows::Storage::Streams::DataWriter(); //dataWriter.WriteBytes() auto buffer = dataWriter.DetachBuffer(); auto updates = std::map<winrt::hstring, winrt::Windows::Storage::Streams::IBuffer>(); //auto view = winrt::param::async_map_view<winrt::hstring, winrt::Windows::Storage::Streams::IBuffer>(updates); //container.SubmitUpdatesAsync(view); } }
/** * @file * * @brief Source for yamlsmith plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ // -- Imports ------------------------------------------------------------------------------------------------------------------------------ #include <fstream> #include <iostream> #include "yamlsmith.hpp" #include <kdb.hpp> #include <kdbease.h> #include <kdberrors.h> using std::endl; using std::ofstream; using std::string; using ckdb::Key; using ckdb::KeySet; using ckdb::elektraKeyGetRelativeName; using ckdb::keyNew; using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; using NameIterator = kdb::NameIterator; // -- Functions ---------------------------------------------------------------------------------------------------------------------------- namespace { /** * @brief This function returns a key set containing the contract of the plugin. * * @return A contract describing the functionality of this plugin */ CppKeySet contractYamlsmith () { return CppKeySet (30, keyNew ("system/elektra/modules/yamlsmith", KEY_VALUE, "yamlsmith plugin waits for your orders", KEY_END), keyNew ("system/elektra/modules/yamlsmith/exports", KEY_END), keyNew ("system/elektra/modules/yamlsmith/exports/get", KEY_FUNC, elektraYamlsmithGet, KEY_END), keyNew ("system/elektra/modules/yamlsmith/exports/set", KEY_FUNC, elektraYamlsmithSet, KEY_END), #include ELEKTRA_README (yamlsmith) keyNew ("system/elektra/modules/yamlsmith/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END); } /** * @brief This class provides additional functionality for the keys. */ class CppKeyPlus : public CppKey { public: /** * @copydoc Key::Key(Key &) */ CppKeyPlus (kdb::Key const & other) : CppKey (other) { } /** * @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`. * * @pre This key must be a child of `parent`. * * @param parent This key specifies the part of the name iterator that will not be part of the return value of this function. * * @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`. */ NameIterator relativeKeyIterator (Key const & parent) { auto parentIterator = parent.begin (); auto keyIterator = this->begin (); while (parentIterator != parent.end () && keyIterator != this->end ()) { parentIterator++; keyIterator++; } return keyIterator; } }; /** * @brief This class provides additional functionality for the key set class. */ class CppKeySetPlus : public CppKeySet { public: /** * @copydoc KeySet::KeySet(ckdb::KeySet) */ CppKeySetPlus (ckdb::KeySet * keys) : CppKeySet (keys) { } /** * @brief Collect leaf keys (keys without any key below) for this key set. * * @return A key set containing all leaf keys */ CppKeySet leaves () { CppKeySet leaves; auto current = this->begin (); if (current == this->end ()) return leaves; CppKey previous = *current; while (++current != this->end ()) { bool isLeaf = !current->isBelow (previous); if (isLeaf) { leaves.append (previous); } previous = *current; } // The last key is always a leaf leaves.append (previous); return leaves; } }; } // end namespace extern "C" { // ==================== // = Plugin Interface = // ==================== /** @see elektraDocGet */ int elektraYamlsmithGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey) { CppKey parent{ parentKey }; CppKeySet keys{ returned }; if (parent.getName () == "system/elektra/modules/yamlsmith") { keys.append (contractYamlsmith ()); parent.release (); keys.release (); return ELEKTRA_PLUGIN_STATUS_SUCCESS; } parent.release (); return ELEKTRA_PLUGIN_STATUS_NO_UPDATE; } /** @see elektraDocSet */ int elektraYamlsmithSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey) { CppKey parent{ parentKey }; CppKeySetPlus keys{ returned }; ofstream file{ parent.getString () }; if (file.is_open ()) { for (auto key : keys.leaves ()) { string indent; CppKeyPlus plus{ *key }; auto relative = plus.relativeKeyIterator (parent); while (relative != plus.end ()) { file << indent << *relative << ":" << endl; relative++; indent += " "; } file << indent << plus.getString () << endl; } } else { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, parent.getKey (), "Unable to open file “%s”", parent.getString ().c_str ()); } parent.release (); keys.release (); return ELEKTRA_PLUGIN_STATUS_SUCCESS; } Plugin * ELEKTRA_PLUGIN_EXPORT (yamlsmith) { return elektraPluginExport ("yamlsmith", ELEKTRA_PLUGIN_GET, &elektraYamlsmithGet, ELEKTRA_PLUGIN_SET, &elektraYamlsmithSet, ELEKTRA_PLUGIN_END); } } // end extern "C" YAML Smith: Use function for relative iterator /** * @file * * @brief Source for yamlsmith plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ // -- Imports ------------------------------------------------------------------------------------------------------------------------------ #include <fstream> #include <iostream> #include "yamlsmith.hpp" #include <kdb.hpp> #include <kdbease.h> #include <kdberrors.h> using std::endl; using std::ofstream; using std::string; using ckdb::Key; using ckdb::KeySet; using ckdb::elektraKeyGetRelativeName; using ckdb::keyNew; using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; using NameIterator = kdb::NameIterator; // -- Functions ---------------------------------------------------------------------------------------------------------------------------- namespace { /** * @brief This function returns a key set containing the contract of the plugin. * * @return A contract describing the functionality of this plugin */ CppKeySet contractYamlsmith () { return CppKeySet (30, keyNew ("system/elektra/modules/yamlsmith", KEY_VALUE, "yamlsmith plugin waits for your orders", KEY_END), keyNew ("system/elektra/modules/yamlsmith/exports", KEY_END), keyNew ("system/elektra/modules/yamlsmith/exports/get", KEY_FUNC, elektraYamlsmithGet, KEY_END), keyNew ("system/elektra/modules/yamlsmith/exports/set", KEY_FUNC, elektraYamlsmithSet, KEY_END), #include ELEKTRA_README (yamlsmith) keyNew ("system/elektra/modules/yamlsmith/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END); } /** * @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`. * * @pre The parameter `key` must be a child of `parent`. * * @param key This is the key for which this function returns a relative iterator. * @param parent This key specifies the part of the name iterator that will not be part of the return value of this function. * * @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`. */ NameIterator relativeKeyIterator (CppKey const & key, CppKey const & parent) { auto parentIterator = parent.begin (); auto keyIterator = key.begin (); while (parentIterator != parent.end () && keyIterator != key.end ()) { parentIterator++; keyIterator++; } return keyIterator; } /** * @brief This class provides additional functionality for the key set class. */ class CppKeySetPlus : public CppKeySet { public: /** * @copydoc KeySet::KeySet(ckdb::KeySet) */ CppKeySetPlus (ckdb::KeySet * keys) : CppKeySet (keys) { } /** * @brief Collect leaf keys (keys without any key below) for this key set. * * @return A key set containing all leaf keys */ CppKeySet leaves () { CppKeySet leaves; auto current = this->begin (); if (current == this->end ()) return leaves; CppKey previous = *current; while (++current != this->end ()) { bool isLeaf = !current->isBelow (previous); if (isLeaf) { leaves.append (previous); } previous = *current; } // The last key is always a leaf leaves.append (previous); return leaves; } }; } // end namespace extern "C" { // ==================== // = Plugin Interface = // ==================== /** @see elektraDocGet */ int elektraYamlsmithGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey) { CppKey parent{ parentKey }; CppKeySet keys{ returned }; if (parent.getName () == "system/elektra/modules/yamlsmith") { keys.append (contractYamlsmith ()); parent.release (); keys.release (); return ELEKTRA_PLUGIN_STATUS_SUCCESS; } parent.release (); return ELEKTRA_PLUGIN_STATUS_NO_UPDATE; } /** @see elektraDocSet */ int elektraYamlsmithSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey) { CppKey parent{ parentKey }; CppKeySetPlus keys{ returned }; ofstream file{ parent.getString () }; if (file.is_open ()) { for (auto key : keys.leaves ()) { string indent; auto relative = relativeKeyIterator (*key, parent); while (relative != key.end ()) { file << indent << *relative << ":" << endl; relative++; indent += " "; } file << indent << key.getString () << endl; } } else { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, parent.getKey (), "Unable to open file “%s”", parent.getString ().c_str ()); } parent.release (); keys.release (); return ELEKTRA_PLUGIN_STATUS_SUCCESS; } Plugin * ELEKTRA_PLUGIN_EXPORT (yamlsmith) { return elektraPluginExport ("yamlsmith", ELEKTRA_PLUGIN_GET, &elektraYamlsmithGet, ELEKTRA_PLUGIN_SET, &elektraYamlsmithSet, ELEKTRA_PLUGIN_END); } } // end extern "C"
/* Copyright 2020 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "legion.h" #include "legion/runtime.h" #include "legion/legion_ops.h" #include "legion/legion_tasks.h" #include "legion/region_tree.h" #include "legion/legion_spy.h" #include "legion/legion_trace.h" #include "legion/legion_profiling.h" #include "legion/legion_instances.h" #include "legion/legion_views.h" #include "legion/legion_analysis.h" #include "legion/legion_context.h" namespace Legion { namespace Internal { LEGION_EXTERN_LOGGER_DECLARATIONS ///////////////////////////////////////////////////////////// // Users and Info ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalUser::LogicalUser(void) : GenericUser(), op(NULL), idx(0), gen(0), timeout(TIMEOUT) #ifdef LEGION_SPY , uid(0) #endif //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalUser::LogicalUser(Operation *o, unsigned id, const RegionUsage &u, const FieldMask &m) : GenericUser(u, m), op(o), idx(id), gen(o->get_generation()), timeout(TIMEOUT) #ifdef LEGION_SPY , uid(o->get_unique_op_id()) #endif //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalUser::LogicalUser(Operation *o, GenerationID g, unsigned id, const RegionUsage &u, const FieldMask &m) : GenericUser(u, m), op(o), idx(id), gen(g), timeout(TIMEOUT) #ifdef LEGION_SPY , uid(o->get_unique_op_id()) #endif //-------------------------------------------------------------------------- { } #ifdef ENABLE_VIEW_REPLICATION //-------------------------------------------------------------------------- PhysicalUser::PhysicalUser(const RegionUsage &u, IndexSpaceExpression *e, UniqueID id, unsigned x, RtEvent collect, bool cpy, bool cov) : usage(u), expr(e), op_id(id), index(x), collect_event(collect), copy_user(cpy), covers(cov) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(expr != NULL); #endif expr->add_expression_reference(); } #else //-------------------------------------------------------------------------- PhysicalUser::PhysicalUser(const RegionUsage &u, IndexSpaceExpression *e, UniqueID id, unsigned x, bool cpy, bool cov) : usage(u), expr(e), op_id(id), index(x), copy_user(cpy), covers(cov) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(expr != NULL); #endif expr->add_expression_reference(); } #endif //-------------------------------------------------------------------------- PhysicalUser::PhysicalUser(const PhysicalUser &rhs) : usage(rhs.usage), expr(rhs.expr), op_id(rhs.op_id), index(rhs.index), #ifdef ENABLE_VIEW_REPLICATION collect_event(rhs.collect_event), #endif copy_user(rhs.copy_user), covers(rhs.covers) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- PhysicalUser::~PhysicalUser(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(expr != NULL); #endif if (expr->remove_expression_reference()) delete expr; } //-------------------------------------------------------------------------- PhysicalUser& PhysicalUser::operator=(const PhysicalUser &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void PhysicalUser::pack_user(Serializer &rez, const AddressSpaceID target) const //-------------------------------------------------------------------------- { RezCheck z(rez); #ifdef ENABLE_VIEW_REPLICATION rez.serialize(collect_event); #endif rez.serialize(usage); expr->pack_expression(rez, target); rez.serialize(op_id); rez.serialize(index); rez.serialize<bool>(copy_user); rez.serialize<bool>(covers); } //-------------------------------------------------------------------------- /*static*/ PhysicalUser* PhysicalUser::unpack_user(Deserializer &derez, RegionTreeForest *forest, const AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); #ifdef ENABLE_VIEW_REPLICATION RtEvent collect_event; derez.deserialize(collect_event); #endif RegionUsage usage; derez.deserialize(usage); IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez, forest, source); UniqueID op_id; derez.deserialize(op_id); unsigned index; derez.deserialize(index); bool copy_user, covers; derez.deserialize<bool>(copy_user); derez.deserialize<bool>(covers); #ifdef ENABLE_VIEW_REPLICATION return new PhysicalUser(usage, expr, op_id, index, collect_event, copy_user, covers); #else return new PhysicalUser(usage, expr, op_id, index, copy_user, covers); #endif } ///////////////////////////////////////////////////////////// // VersionInfo ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- VersionInfo::VersionInfo(void) : owner(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- VersionInfo::VersionInfo(const VersionInfo &rhs) : owner(NULL) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(rhs.owner == NULL); assert(equivalence_sets.empty()); assert(rhs.equivalence_sets.empty()); #endif } //-------------------------------------------------------------------------- VersionInfo::~VersionInfo(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- VersionInfo& VersionInfo::operator=(const VersionInfo &rhs) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(rhs.owner == NULL); assert(equivalence_sets.empty()); assert(rhs.equivalence_sets.empty()); #endif return *this; } //-------------------------------------------------------------------------- void VersionInfo::record_equivalence_set(VersionManager *own, EquivalenceSet *set, const FieldMask &set_mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert((owner == NULL) || (owner == own)); #endif owner = own; equivalence_sets.insert(set, set_mask); } //-------------------------------------------------------------------------- void VersionInfo::clear(void) //-------------------------------------------------------------------------- { owner = NULL; equivalence_sets.clear(); } ///////////////////////////////////////////////////////////// // LogicalTraceInfo ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalTraceInfo::LogicalTraceInfo(bool already_tr, LegionTrace *tr, unsigned idx, const RegionRequirement &r) : already_traced(already_tr), trace(tr), req_idx(idx), req(r) //-------------------------------------------------------------------------- { // If we have a trace but it doesn't handle the region tree then // we should mark that this is not part of a trace if ((trace != NULL) && !trace->handles_region_tree(req.parent.get_tree_id())) { already_traced = false; trace = NULL; } } ///////////////////////////////////////////////////////////// // Remote Trace Recorder ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- RemoteTraceRecorder::RemoteTraceRecorder(Runtime *rt, AddressSpaceID origin, AddressSpaceID local, Memoizable *memo, PhysicalTemplate *tpl, RtUserEvent applied, RtEvent collect) : runtime(rt), origin_space(origin), local_space(local), memoizable(memo), remote_tpl(tpl), applied_event(applied), collect_event(collect) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(remote_tpl != NULL); #endif } //-------------------------------------------------------------------------- RemoteTraceRecorder::RemoteTraceRecorder(const RemoteTraceRecorder &rhs) : runtime(rhs.runtime), origin_space(rhs.origin_space), local_space(rhs.local_space), memoizable(rhs.memoizable), remote_tpl(rhs.remote_tpl), applied_event(rhs.applied_event), collect_event(rhs.collect_event) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- RemoteTraceRecorder::~RemoteTraceRecorder(void) //-------------------------------------------------------------------------- { if (!applied_events.empty()) Runtime::trigger_event(applied_event, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied_event); // Clean up our memoizable object if necessary if ((memoizable != NULL) && (memoizable->get_origin_space() != local_space)) delete memoizable; } //-------------------------------------------------------------------------- RemoteTraceRecorder& RemoteTraceRecorder::operator=( const RemoteTraceRecorder &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void RemoteTraceRecorder::add_recorder_reference(void) //-------------------------------------------------------------------------- { add_reference(); } //-------------------------------------------------------------------------- bool RemoteTraceRecorder::remove_recorder_reference(void) //-------------------------------------------------------------------------- { return remove_reference(); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::pack_recorder(Serializer &rez, std::set<RtEvent> &external_applied, const AddressSpaceID target) //-------------------------------------------------------------------------- { rez.serialize(origin_space); rez.serialize(target); rez.serialize(remote_tpl); RtUserEvent remote_applied = Runtime::create_rt_user_event(); rez.serialize(remote_applied); rez.serialize(collect_event); // Only need to store this one locally since we already hooked our whole // chain of events into the operations applied set on the origin node // See PhysicalTemplate::pack_recorder AutoLock a_lock(applied_lock); applied_events.insert(remote_applied); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_get_term_event(Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_RECORD_GET_TERM); rez.serialize(applied); memo->pack_remote_memoizable(rez, origin_space); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_get_term_event(memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_create_ap_user_event( ApUserEvent lhs, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_CREATE_USER_EVENT); rez.serialize(applied); rez.serialize(lhs); memo->pack_remote_memoizable(rez, origin_space); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_create_ap_user_event(lhs, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_trigger_event(ApUserEvent lhs, ApEvent rhs) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_TRIGGER_EVENT); rez.serialize(applied); rez.serialize(lhs); rez.serialize(rhs); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_trigger_event(lhs, rhs); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_merge_events(ApEvent &lhs, ApEvent rhs, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { std::set<ApEvent> rhs_events; rhs_events.insert(rhs); record_merge_events(lhs, rhs_events, memo); } else remote_tpl->record_merge_events(lhs, rhs, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_merge_events(ApEvent &lhs, ApEvent e1, ApEvent e2, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { std::set<ApEvent> rhs_events; rhs_events.insert(e1); rhs_events.insert(e2); record_merge_events(lhs, rhs_events, memo); } else remote_tpl->record_merge_events(lhs, e1, e2, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_merge_events(ApEvent &lhs, ApEvent e1, ApEvent e2, ApEvent e3, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { std::set<ApEvent> rhs_events; rhs_events.insert(e1); rhs_events.insert(e2); rhs_events.insert(e3); record_merge_events(lhs, rhs_events, memo); } else remote_tpl->record_merge_events(lhs, e1, e2, e3, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_merge_events(ApEvent &lhs, const std::set<ApEvent>& rhs, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent done = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_MERGE_EVENTS); rez.serialize(done); rez.serialize(&lhs); rez.serialize(lhs); memo->pack_remote_memoizable(rez, origin_space); rez.serialize<size_t>(rhs.size()); for (std::set<ApEvent>::const_iterator it = rhs.begin(); it != rhs.end(); it++) rez.serialize(*it); } runtime->send_remote_trace_update(origin_space, rez); // Wait to see if lhs changes done.wait(); } else remote_tpl->record_merge_events(lhs, rhs, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_issue_copy(Memoizable *memo, unsigned src_idx, unsigned dst_idx, ApEvent &lhs, IndexSpaceExpression *expr, const std::vector<CopySrcDstField>& src_fields, const std::vector<CopySrcDstField>& dst_fields, #ifdef LEGION_SPY RegionTreeID src_tree_id, RegionTreeID dst_tree_id, #endif ApEvent precondition, ReductionOpID redop, bool reduction_fold, const FieldMaskSet<InstanceView> &tracing_srcs, const FieldMaskSet<InstanceView> &tracing_dsts) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent done = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_ISSUE_COPY); rez.serialize(done); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(src_idx); rez.serialize(dst_idx); rez.serialize(&lhs); rez.serialize(lhs); expr->pack_expression(rez, origin_space); #ifdef DEBUG_LEGION assert(src_fields.size() == dst_fields.size()); #endif rez.serialize<size_t>(src_fields.size()); for (unsigned idx = 0; idx < src_fields.size(); idx++) { pack_src_dst_field(rez, src_fields[idx]); pack_src_dst_field(rez, dst_fields[idx]); } #ifdef LEGION_SPY rez.serialize(src_tree_id); rez.serialize(dst_tree_id); #endif rez.serialize(precondition); rez.serialize(redop); rez.serialize<bool>(reduction_fold); rez.serialize<size_t>(tracing_srcs.size()); for (FieldMaskSet<InstanceView>::const_iterator it = tracing_srcs.begin(); it != tracing_srcs.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<size_t>(tracing_dsts.size()); for (FieldMaskSet<InstanceView>::const_iterator it = tracing_dsts.begin(); it != tracing_dsts.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } } runtime->send_remote_trace_update(origin_space, rez); // Wait to see if lhs changes done.wait(); } else remote_tpl->record_issue_copy(memo, src_idx, dst_idx, lhs, expr, src_fields, dst_fields, #ifdef LEGION_SPY src_tree_id, dst_tree_id, #endif precondition, redop, reduction_fold, tracing_srcs, tracing_dsts); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_issue_indirect(Memoizable *memo, ApEvent &lhs, IndexSpaceExpression *expr, const std::vector<CopySrcDstField>& src_fields, const std::vector<CopySrcDstField>& dst_fields, const std::vector<void*> &indirections, ApEvent precondition) //-------------------------------------------------------------------------- { if (local_space != origin_space) { // TODO assert(false); } else remote_tpl->record_issue_indirect(memo, lhs, expr,src_fields,dst_fields, indirections, precondition); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_issue_fill(Memoizable *memo, unsigned idx, ApEvent &lhs, IndexSpaceExpression *expr, const std::vector<CopySrcDstField> &fields, const void *fill_value, size_t fill_size, #ifdef LEGION_SPY FieldSpace handle, RegionTreeID tree_id, #endif ApEvent precondition, const FieldMaskSet<FillView> &tracing_srcs, const FieldMaskSet<InstanceView> &tracing_dsts) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent done = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_ISSUE_FILL); rez.serialize(done); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(idx); rez.serialize(&lhs); rez.serialize(lhs); expr->pack_expression(rez, origin_space); rez.serialize<size_t>(fields.size()); for (unsigned idx = 0; idx < fields.size(); idx++) pack_src_dst_field(rez, fields[idx]); rez.serialize(fill_size); rez.serialize(fill_value, fill_size); #ifdef LEGION_SPY rez.serialize(handle); rez.serialize(tree_id); #endif rez.serialize(precondition); rez.serialize<size_t>(tracing_srcs.size()); for (FieldMaskSet<FillView>::const_iterator it = tracing_srcs.begin(); it != tracing_srcs.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<size_t>(tracing_dsts.size()); for (FieldMaskSet<InstanceView>::const_iterator it = tracing_dsts.begin(); it != tracing_dsts.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } } runtime->send_remote_trace_update(origin_space, rez); // Wait to see if lhs changes done.wait(); } else remote_tpl->record_issue_fill(memo, idx, lhs, expr, fields, fill_value, fill_size, #ifdef LEGION_SPY handle, tree_id, #endif precondition, tracing_srcs, tracing_dsts); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_fill_view(FillView *view, const FieldMask &user_mask) //-------------------------------------------------------------------------- { // this should never be called on remote nodes assert(false); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_op_view(Memoizable *memo, unsigned idx, InstanceView *view, const RegionUsage &usage, const FieldMask &user_mask, bool update_validity) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_RECORD_OP_VIEW); rez.serialize(applied); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(idx); rez.serialize(view->did); rez.serialize(usage); rez.serialize(user_mask); rez.serialize<bool>(update_validity); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_op_view(memo, idx, view, usage, user_mask, update_validity); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_set_op_sync_event(ApEvent &lhs, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent done = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_SET_OP_SYNC); rez.serialize(done); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(&lhs); rez.serialize(lhs); } runtime->send_remote_trace_update(origin_space, rez); // wait to see if lhs changes done.wait(); } else remote_tpl->record_set_op_sync_event(lhs, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_mapper_output(Memoizable *memo, const Mapper::MapTaskOutput &output, const std::deque<InstanceSet> &physical_instances, std::set<RtEvent> &external_applied) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_RECORD_MAPPER_OUTPUT); rez.serialize(applied); memo->pack_remote_memoizable(rez, origin_space); // We actually only need a few things here rez.serialize<size_t>(output.target_procs.size()); for (unsigned idx = 0; idx < output.target_procs.size(); idx++) rez.serialize(output.target_procs[idx]); rez.serialize(output.chosen_variant); rez.serialize(output.task_priority); rez.serialize<bool>(output.postmap_task); rez.serialize<size_t>(physical_instances.size()); for (std::deque<InstanceSet>::const_iterator it = physical_instances.begin(); it != physical_instances.end(); it++) it->pack_references(rez); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_mapper_output(memo, output, physical_instances, external_applied); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::get_reduction_ready_events(Memoizable *memo, std::set<ApEvent> &ready_events) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent done_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_GET_REDUCTION_EVENTS); rez.serialize(done_event); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(&ready_events); } runtime->send_remote_trace_update(origin_space, rez); // Wait for the result to be ready done_event.wait(); } else remote_tpl->get_reduction_ready_events(memo, ready_events); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_set_effects(Memoizable *memo, ApEvent &rhs) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_SET_EFFECTS); rez.serialize(applied); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(rhs); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_set_effects(memo, rhs); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_complete_replay(Memoizable *memo, ApEvent rhs) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_COMPLETE_REPLAY); rez.serialize(applied); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(rhs); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_complete_replay(memo, rhs); } //-------------------------------------------------------------------------- /*static*/ RemoteTraceRecorder* RemoteTraceRecorder::unpack_remote_recorder( Deserializer &derez, Runtime *runtime, Memoizable *memo) //-------------------------------------------------------------------------- { AddressSpaceID origin_space, local_space; derez.deserialize(origin_space); derez.deserialize(local_space); PhysicalTemplate *remote_tpl; derez.deserialize(remote_tpl); RtUserEvent applied_event; derez.deserialize(applied_event); RtEvent collect_event; derez.deserialize(collect_event); return new RemoteTraceRecorder(runtime, origin_space, local_space, memo, remote_tpl, applied_event, collect_event); } //-------------------------------------------------------------------------- /*static*/ void RemoteTraceRecorder::handle_remote_update( Deserializer &derez, Runtime *runtime, AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); PhysicalTemplate *tpl; derez.deserialize(tpl); RemoteTraceKind kind; derez.deserialize(kind); switch (kind) { case REMOTE_TRACE_RECORD_GET_TERM: { RtUserEvent applied; derez.deserialize(applied); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); tpl->record_get_term_event(memo); Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_CREATE_USER_EVENT: { RtUserEvent applied; derez.deserialize(applied); ApUserEvent lhs; derez.deserialize(lhs); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); tpl->record_create_ap_user_event(lhs, memo); Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_TRIGGER_EVENT: { RtUserEvent applied; derez.deserialize(applied); ApUserEvent lhs; derez.deserialize(lhs); ApEvent rhs; derez.deserialize(rhs); tpl->record_trigger_event(lhs, rhs); Runtime::trigger_event(applied); break; } case REMOTE_TRACE_MERGE_EVENTS: { RtUserEvent done; derez.deserialize(done); ApUserEvent *event_ptr; derez.deserialize(event_ptr); ApUserEvent lhs; derez.deserialize(lhs); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); size_t num_rhs; derez.deserialize(num_rhs); const ApUserEvent lhs_copy = lhs; if (num_rhs == 2) { ApEvent e1, e2; derez.deserialize(e1); derez.deserialize(e2); tpl->record_merge_events(lhs, e1, e2, memo); } else if (num_rhs == 3) { ApEvent e1, e2, e3; derez.deserialize(e1); derez.deserialize(e2); derez.deserialize(e3); tpl->record_merge_events(lhs, e1, e2, e3, memo); } else { std::set<ApEvent> rhs_events; for (unsigned idx = 0; idx < num_rhs; idx++) { ApEvent event; derez.deserialize(event); rhs_events.insert(event); } tpl->record_merge_events(lhs, rhs_events, memo); } if (lhs != lhs_copy) { Serializer rez; { RezCheck z2(rez); rez.serialize(REMOTE_TRACE_MERGE_EVENTS); rez.serialize(event_ptr); rez.serialize(lhs); rez.serialize(done); } runtime->send_remote_trace_response(source, rez); } else // didn't change so just trigger Runtime::trigger_event(done); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_ISSUE_COPY: { RtUserEvent done; derez.deserialize(done); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); unsigned src_idx, dst_idx; derez.deserialize(src_idx); derez.deserialize(dst_idx); ApUserEvent *lhs_ptr; derez.deserialize(lhs_ptr); ApUserEvent lhs; derez.deserialize(lhs); RegionTreeForest *forest = runtime->forest; IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez, forest, source); size_t num_fields; derez.deserialize(num_fields); std::vector<CopySrcDstField> src_fields(num_fields); std::vector<CopySrcDstField> dst_fields(num_fields); for (unsigned idx = 0; idx < num_fields; idx++) { unpack_src_dst_field(derez, src_fields[idx]); unpack_src_dst_field(derez, dst_fields[idx]); } #ifdef LEGION_SPY RegionTreeID src_tree_id, dst_tree_id; derez.deserialize(src_tree_id); derez.deserialize(dst_tree_id); #endif ApEvent precondition; derez.deserialize(precondition); ReductionOpID redop; derez.deserialize(redop); bool reduction_fold; derez.deserialize<bool>(reduction_fold); FieldMaskSet<InstanceView> tracing_srcs, tracing_dsts; std::set<RtEvent> ready_events; size_t num_srcs; derez.deserialize(num_srcs); for (unsigned idx = 0; idx < num_srcs; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; InstanceView *view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(did, ready)); if (ready.exists() && !ready.has_triggered()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); tracing_srcs.insert(view, mask); } size_t num_dsts; derez.deserialize(num_dsts); for (unsigned idx = 0; idx < num_dsts; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; InstanceView *view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(did, ready)); if (ready.exists() && !ready.has_triggered()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); tracing_dsts.insert(view, mask); } // Use this to track if lhs changes const ApUserEvent lhs_copy = lhs; if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); } // Do the base call tpl->record_issue_copy(memo, src_idx, dst_idx, lhs, expr, src_fields, dst_fields, #ifdef LEGION_SPY src_tree_id, dst_tree_id, #endif precondition, redop, reduction_fold, tracing_srcs, tracing_dsts); if (lhs != lhs_copy) { Serializer rez; { RezCheck z2(rez); rez.serialize(REMOTE_TRACE_ISSUE_COPY); rez.serialize(lhs_ptr); rez.serialize(lhs); rez.serialize(done); } runtime->send_remote_trace_response(source, rez); } else // lhs was unchanged Runtime::trigger_event(done); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_ISSUE_FILL: { RtUserEvent done; derez.deserialize(done); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); unsigned index; derez.deserialize(index); ApUserEvent *lhs_ptr; derez.deserialize(lhs_ptr); ApUserEvent lhs; derez.deserialize(lhs); RegionTreeForest *forest = runtime->forest; IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez, forest, source); size_t num_fields; derez.deserialize(num_fields); std::vector<CopySrcDstField> fields(num_fields); for (unsigned idx = 0; idx < num_fields; idx++) unpack_src_dst_field(derez, fields[idx]); size_t fill_size; derez.deserialize(fill_size); const void *fill_value = derez.get_current_pointer(); derez.advance_pointer(fill_size); #ifdef LEGION_SPY FieldSpace handle; derez.deserialize(handle); RegionTreeID tree_id; derez.deserialize(tree_id); #endif ApEvent precondition; derez.deserialize(precondition); FieldMaskSet<FillView> tracing_srcs; std::set<RtEvent> ready_events; size_t num_srcs; derez.deserialize(num_srcs); for (unsigned idx = 0; idx < num_srcs; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; FillView *view = static_cast<FillView*>( runtime->find_or_request_logical_view(did, ready)); if (ready.exists() && !ready.has_triggered()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); tracing_srcs.insert(view, mask); } FieldMaskSet<InstanceView> tracing_dsts; size_t num_dsts; derez.deserialize(num_dsts); for (unsigned idx = 0; idx < num_dsts; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; InstanceView *view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(did, ready)); if (ready.exists() && !ready.has_triggered()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); tracing_dsts.insert(view, mask); } // Use this to track if lhs changes const ApUserEvent lhs_copy = lhs; if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); } // Do the base call tpl->record_issue_fill(memo, index, lhs, expr, fields, fill_value, fill_size, #ifdef LEGION_SPY handle, tree_id, #endif precondition, tracing_srcs, tracing_dsts); if (lhs != lhs_copy) { Serializer rez; { RezCheck z2(rez); rez.serialize(REMOTE_TRACE_ISSUE_FILL); rez.serialize(lhs_ptr); rez.serialize(lhs); rez.serialize(done); } runtime->send_remote_trace_response(source, rez); } else // lhs was unchanged Runtime::trigger_event(done); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_RECORD_OP_VIEW: { RtUserEvent applied; derez.deserialize(applied); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); unsigned index; derez.deserialize(index); DistributedID did; derez.deserialize(did); RtEvent ready; InstanceView *view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(did, ready)); RegionUsage usage; derez.deserialize(usage); FieldMask user_mask; derez.deserialize(user_mask); bool update_validity; derez.deserialize<bool>(update_validity); if (ready.exists() && !ready.has_triggered()) ready.wait(); tpl->record_op_view(memo, index, view, usage, user_mask, update_validity); Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_SET_OP_SYNC: { RtUserEvent done; derez.deserialize(done); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); ApUserEvent *lhs_ptr; derez.deserialize(lhs_ptr); ApUserEvent lhs; derez.deserialize(lhs); const ApUserEvent lhs_copy = lhs; tpl->record_set_op_sync_event(lhs, memo); if (lhs != lhs_copy) { Serializer rez; { RezCheck z2(rez); rez.serialize(REMOTE_TRACE_SET_OP_SYNC); rez.serialize(lhs_ptr); rez.serialize(lhs); rez.serialize(done); } runtime->send_remote_trace_response(source, rez); } else // lhs didn't change Runtime::trigger_event(done); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_RECORD_MAPPER_OUTPUT: { RtUserEvent applied; derez.deserialize(applied); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); size_t num_target_processors; derez.deserialize(num_target_processors); Mapper::MapTaskOutput output; output.target_procs.resize(num_target_processors); for (unsigned idx = 0; idx < num_target_processors; idx++) derez.deserialize(output.target_procs[idx]); derez.deserialize(output.chosen_variant); derez.deserialize(output.task_priority); derez.deserialize<bool>(output.postmap_task); size_t num_phy_instances; derez.deserialize(num_phy_instances); std::deque<InstanceSet> physical_instances(num_phy_instances); std::set<RtEvent> ready_events; for (unsigned idx = 0; idx < num_phy_instances; idx++) physical_instances[idx].unpack_references(runtime, derez, ready_events); if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); } std::set<RtEvent> applied_events; tpl->record_mapper_output(memo, output, physical_instances, applied_events); if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_GET_REDUCTION_EVENTS: { RtUserEvent done; derez.deserialize(done); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); std::set<ApEvent> *target; derez.deserialize(target); std::set<ApEvent> result; tpl->get_reduction_ready_events(memo, result); if (!result.empty()) { Serializer rez; { RezCheck z2(rez); rez.serialize(REMOTE_TRACE_GET_REDUCTION_EVENTS); rez.serialize(target); rez.serialize<size_t>(result.size()); for (std::set<ApEvent>::const_iterator it = result.begin(); it != result.end(); it++) rez.serialize(*it); rez.serialize(done); } runtime->send_remote_trace_response(source, rez); } else Runtime::trigger_event(done); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_SET_EFFECTS: { RtUserEvent applied; derez.deserialize(applied); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); ApEvent postcondition; derez.deserialize(postcondition); tpl->record_set_effects(memo, postcondition); Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_COMPLETE_REPLAY: { RtUserEvent applied; derez.deserialize(applied); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); ApEvent ready_event; derez.deserialize(ready_event); tpl->record_complete_replay(memo, ready_event); Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } default: assert(false); } } //-------------------------------------------------------------------------- /*static*/ void RemoteTraceRecorder::handle_remote_response( Deserializer &derez) //-------------------------------------------------------------------------- { DerezCheck z(derez); RemoteTraceKind kind; derez.deserialize(kind); switch (kind) { case REMOTE_TRACE_MERGE_EVENTS: case REMOTE_TRACE_ISSUE_COPY: case REMOTE_TRACE_ISSUE_FILL: case REMOTE_TRACE_SET_OP_SYNC: { ApUserEvent *event_ptr; derez.deserialize(event_ptr); derez.deserialize(*event_ptr); RtUserEvent done; derez.deserialize(done); Runtime::trigger_event(done); break; } case REMOTE_TRACE_GET_REDUCTION_EVENTS: { std::set<ApEvent> *target; derez.deserialize(target); size_t num_events; derez.deserialize(num_events); for (unsigned idx = 0; idx < num_events; idx++) { ApEvent event; derez.deserialize(event); target->insert(event); } RtUserEvent done; derez.deserialize(done); Runtime::trigger_event(done); break; } default: assert(false); } } //-------------------------------------------------------------------------- /*static*/ void RemoteTraceRecorder::pack_src_dst_field( Serializer &rez, const CopySrcDstField &field) //-------------------------------------------------------------------------- { RezCheck z(rez); rez.serialize(field.inst); rez.serialize(field.field_id); rez.serialize(field.size); rez.serialize(field.redop_id); rez.serialize<bool>(field.red_fold); rez.serialize(field.serdez_id); rez.serialize(field.subfield_offset); rez.serialize(field.indirect_index); rez.serialize(field.fill_data.indirect); #ifdef LEGION_SPY rez.serialize(field.inst_event); #endif } //-------------------------------------------------------------------------- /*static*/ void RemoteTraceRecorder::unpack_src_dst_field( Deserializer &derez, CopySrcDstField &field) //-------------------------------------------------------------------------- { DerezCheck z(derez); derez.deserialize(field.inst); derez.deserialize(field.field_id); derez.deserialize(field.size); derez.deserialize(field.redop_id); derez.deserialize<bool>(field.red_fold); derez.deserialize(field.serdez_id); derez.deserialize(field.subfield_offset); derez.deserialize(field.indirect_index); derez.deserialize(field.fill_data.indirect); #ifdef LEGION_SPY derez.deserialize(field.inst_event); #endif } ///////////////////////////////////////////////////////////// // TraceInfo ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- TraceInfo::TraceInfo(Operation *o, bool init) : op(o), memo((op == NULL) ? NULL : op->get_memoizable()), rec((memo == NULL) ? NULL : memo->get_template()), recording((rec == NULL) ? false : rec->is_recording()) //-------------------------------------------------------------------------- { if (recording && init) record_get_term_event(); if (rec != NULL) rec->add_recorder_reference(); } //-------------------------------------------------------------------------- TraceInfo::TraceInfo(const TraceInfo &rhs) : op(rhs.op), memo(rhs.memo), rec(rhs.rec), recording(rhs.recording) //-------------------------------------------------------------------------- { if (rec != NULL) rec->add_recorder_reference(); } //-------------------------------------------------------------------------- TraceInfo::TraceInfo(const TraceInfo &rhs, Operation *o) : op(o), memo(o->get_memoizable()), rec(rhs.rec), recording(rhs.recording) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(memo != NULL); #endif if (rec != NULL) rec->add_recorder_reference(); } //-------------------------------------------------------------------------- TraceInfo::~TraceInfo(void) //-------------------------------------------------------------------------- { if ((rec != NULL) && rec->remove_recorder_reference()) delete rec; } //-------------------------------------------------------------------------- TraceInfo::TraceInfo(Operation *o, Memoizable *m, PhysicalTraceRecorder *r, const bool record) : op(o), memo(m), rec(r), recording(record) //-------------------------------------------------------------------------- { if (rec != NULL) rec->add_recorder_reference(); } //-------------------------------------------------------------------------- void TraceInfo::pack_remote_trace_info(Serializer &rez, AddressSpaceID target, std::set<RtEvent> &applied) const //-------------------------------------------------------------------------- { rez.serialize<bool>(recording); if (recording) { // Only need to pack these if we're recording memo->pack_remote_memoizable(rez, target); rec->pack_recorder(rez, applied, target); } } //-------------------------------------------------------------------------- /*static*/ TraceInfo* TraceInfo::unpack_remote_trace_info( Deserializer &derez, Operation *op, Runtime *runtime) //-------------------------------------------------------------------------- { bool recording; derez.deserialize<bool>(recording); if (recording) { Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, op, runtime); // PhysicalTraceRecord takes possible ownership of memoizable PhysicalTraceRecorder *rec = RemoteTraceRecorder::unpack_remote_recorder(derez, runtime, memo); return new TraceInfo(op, memo, rec, true/*recording*/); } else return new TraceInfo(op, NULL, NULL, false/*recording*/); } ///////////////////////////////////////////////////////////// // PhysicalTraceInfo ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- PhysicalTraceInfo::PhysicalTraceInfo(Operation *o, unsigned idx, bool init) : TraceInfo(o, init), index(idx), dst_index(idx), update_validity(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalTraceInfo::PhysicalTraceInfo(const TraceInfo &info, unsigned idx, bool update/*=true*/) : TraceInfo(info), index(idx), dst_index(idx), update_validity(update) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalTraceInfo::PhysicalTraceInfo(unsigned src_idx, const TraceInfo &info,unsigned dst_idx) : TraceInfo(info), index(src_idx), dst_index(dst_idx), update_validity(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalTraceInfo::PhysicalTraceInfo(const PhysicalTraceInfo &rhs) : TraceInfo(rhs), index(rhs.index), dst_index(rhs.dst_index), update_validity(rhs.update_validity) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalTraceInfo::PhysicalTraceInfo(Operation *o, Memoizable *m, unsigned src_idx,unsigned dst_idx,bool update,PhysicalTraceRecorder *r) : TraceInfo(o, m, r, (m != NULL)), index(src_idx), dst_index(dst_idx), update_validity(update) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<> void PhysicalTraceInfo::pack_trace_info<true>(Serializer &rez, std::set<RtEvent> &applied, const AddressSpaceID target) const //-------------------------------------------------------------------------- { rez.serialize<bool>(recording); if (recording) { #ifdef DEBUG_LEGION assert(op != NULL); assert(memo != NULL); assert(rec != NULL); #endif op->pack_remote_operation(rez, target, applied); memo->pack_remote_memoizable(rez, target); rez.serialize(index); rez.serialize(dst_index); rez.serialize<bool>(update_validity); rec->pack_recorder(rez, applied, target); } } //-------------------------------------------------------------------------- template<> void PhysicalTraceInfo::pack_trace_info<false>(Serializer &rez, std::set<RtEvent> &applied, const AddressSpaceID target) const //-------------------------------------------------------------------------- { rez.serialize<bool>(recording); if (recording) { #ifdef DEBUG_LEGION assert(memo != NULL); assert(rec != NULL); #endif memo->pack_remote_memoizable(rez, target); rez.serialize(index); rez.serialize(dst_index); rez.serialize<bool>(update_validity); rec->pack_recorder(rez, applied, target); } } //-------------------------------------------------------------------------- /*static*/ PhysicalTraceInfo PhysicalTraceInfo::unpack_trace_info( Deserializer &derez, Runtime *runtime, std::set<RtEvent> &ready_events) //-------------------------------------------------------------------------- { bool recording; derez.deserialize<bool>(recording); if (recording) { RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, op, runtime); unsigned index, dst_index; derez.deserialize(index); derez.deserialize(dst_index); bool update_validity; derez.deserialize(update_validity); // PhysicalTraceRecord takes possible ownership of memoizable PhysicalTraceRecorder *recorder = RemoteTraceRecorder::unpack_remote_recorder(derez, runtime, memo); return PhysicalTraceInfo(op, memo, index, dst_index, update_validity, recorder); } else return PhysicalTraceInfo(NULL, -1U, false); } //-------------------------------------------------------------------------- /*static*/ PhysicalTraceInfo PhysicalTraceInfo::unpack_trace_info( Deserializer &derez, Runtime *runtime, Operation *op) //-------------------------------------------------------------------------- { bool recording; derez.deserialize<bool>(recording); if (recording) { #ifdef DEBUG_LEGION assert(op != NULL); #endif Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, op, runtime); unsigned index, dst_index; derez.deserialize(index); derez.deserialize(dst_index); bool update_validity; derez.deserialize(update_validity); // PhysicalTraceRecord takes possible ownership of memoizable RemoteTraceRecorder *recorder = RemoteTraceRecorder::unpack_remote_recorder(derez, runtime, memo); return PhysicalTraceInfo(op, memo, index, dst_index, update_validity, recorder); } else return PhysicalTraceInfo(op, -1U, false); } ///////////////////////////////////////////////////////////// // ProjectionInfo ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- ProjectionInfo::ProjectionInfo(Runtime *runtime, const RegionRequirement &req, IndexSpaceNode *launch_space) : projection((req.handle_type != SINGULAR) ? runtime->find_projection_function(req.projection) : NULL), projection_type(req.handle_type), projection_space(launch_space) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // PathTraverser ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- PathTraverser::PathTraverser(RegionTreePath &p) : path(p) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PathTraverser::PathTraverser(const PathTraverser &rhs) : path(rhs.path) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- PathTraverser::~PathTraverser(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PathTraverser& PathTraverser::operator=(const PathTraverser &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool PathTraverser::traverse(RegionTreeNode *node) //-------------------------------------------------------------------------- { // Continue visiting nodes and then finding their children // until we have traversed the entire path. while (true) { #ifdef DEBUG_LEGION assert(node != NULL); #endif depth = node->get_depth(); has_child = path.has_child(depth); if (has_child) next_child = path.get_child(depth); bool continue_traversal = node->visit_node(this); if (!continue_traversal) return false; if (!has_child) break; node = node->get_tree_child(next_child); } return true; } ///////////////////////////////////////////////////////////// // LogicalPathRegistrar ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalPathRegistrar::LogicalPathRegistrar(ContextID c, Operation *o, const FieldMask &m, RegionTreePath &p) : PathTraverser(p), ctx(c), field_mask(m), op(o) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalPathRegistrar::LogicalPathRegistrar(const LogicalPathRegistrar&rhs) : PathTraverser(rhs.path), ctx(0), field_mask(FieldMask()), op(NULL) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- LogicalPathRegistrar::~LogicalPathRegistrar(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalPathRegistrar& LogicalPathRegistrar::operator=( const LogicalPathRegistrar &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool LogicalPathRegistrar::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { node->register_logical_dependences(ctx, op, field_mask,false/*dominate*/); if (!has_child) { // If we're at the bottom, fan out and do all the children LogicalRegistrar registrar(ctx, op, field_mask, false); return node->visit_node(&registrar); } return true; } //-------------------------------------------------------------------------- bool LogicalPathRegistrar::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { node->register_logical_dependences(ctx, op, field_mask,false/*dominate*/); if (!has_child) { // If we're at the bottom, fan out and do all the children LogicalRegistrar registrar(ctx, op, field_mask, false); return node->visit_node(&registrar); } return true; } ///////////////////////////////////////////////////////////// // LogicalRegistrar ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalRegistrar::LogicalRegistrar(ContextID c, Operation *o, const FieldMask &m, bool dom) : ctx(c), field_mask(m), op(o), dominate(dom) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalRegistrar::LogicalRegistrar(const LogicalRegistrar &rhs) : ctx(0), field_mask(FieldMask()), op(NULL), dominate(rhs.dominate) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- LogicalRegistrar::~LogicalRegistrar(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalRegistrar& LogicalRegistrar::operator=(const LogicalRegistrar &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool LogicalRegistrar::visit_only_valid(void) const //-------------------------------------------------------------------------- { return false; } //-------------------------------------------------------------------------- bool LogicalRegistrar::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { node->register_logical_dependences(ctx, op, field_mask, dominate); return true; } //-------------------------------------------------------------------------- bool LogicalRegistrar::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { node->register_logical_dependences(ctx, op, field_mask, dominate); return true; } ///////////////////////////////////////////////////////////// // CurrentInitializer ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- CurrentInitializer::CurrentInitializer(ContextID c) : ctx(c) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CurrentInitializer::CurrentInitializer(const CurrentInitializer &rhs) : ctx(0) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- CurrentInitializer::~CurrentInitializer(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CurrentInitializer& CurrentInitializer::operator=( const CurrentInitializer &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool CurrentInitializer::visit_only_valid(void) const //-------------------------------------------------------------------------- { return false; } //-------------------------------------------------------------------------- bool CurrentInitializer::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { node->initialize_current_state(ctx); return true; } //-------------------------------------------------------------------------- bool CurrentInitializer::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { node->initialize_current_state(ctx); return true; } ///////////////////////////////////////////////////////////// // CurrentInvalidator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- CurrentInvalidator::CurrentInvalidator(ContextID c, bool only) : ctx(c), users_only(only) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CurrentInvalidator::CurrentInvalidator(const CurrentInvalidator &rhs) : ctx(0), users_only(false) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- CurrentInvalidator::~CurrentInvalidator(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CurrentInvalidator& CurrentInvalidator::operator=( const CurrentInvalidator &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool CurrentInvalidator::visit_only_valid(void) const //-------------------------------------------------------------------------- { return false; } //-------------------------------------------------------------------------- bool CurrentInvalidator::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { node->invalidate_current_state(ctx, users_only); return true; } //-------------------------------------------------------------------------- bool CurrentInvalidator::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { node->invalidate_current_state(ctx, users_only); return true; } ///////////////////////////////////////////////////////////// // DeletionInvalidator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- DeletionInvalidator::DeletionInvalidator(ContextID c, const FieldMask &dm) : ctx(c), deletion_mask(dm) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- DeletionInvalidator::DeletionInvalidator(const DeletionInvalidator &rhs) : ctx(0), deletion_mask(rhs.deletion_mask) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- DeletionInvalidator::~DeletionInvalidator(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- DeletionInvalidator& DeletionInvalidator::operator=( const DeletionInvalidator &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool DeletionInvalidator::visit_only_valid(void) const //-------------------------------------------------------------------------- { return false; } //-------------------------------------------------------------------------- bool DeletionInvalidator::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { node->invalidate_deleted_state(ctx, deletion_mask); return true; } //-------------------------------------------------------------------------- bool DeletionInvalidator::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { node->invalidate_deleted_state(ctx, deletion_mask); return true; } ///////////////////////////////////////////////////////////// // Projection Epoch ///////////////////////////////////////////////////////////// // C++ is really dumb const ProjectionEpochID ProjectionEpoch::first_epoch; //-------------------------------------------------------------------------- ProjectionEpoch::ProjectionEpoch(ProjectionEpochID id, const FieldMask &m) : epoch_id(id), valid_fields(m) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ProjectionEpoch::ProjectionEpoch(const ProjectionEpoch &rhs) : epoch_id(rhs.epoch_id), valid_fields(rhs.valid_fields) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- ProjectionEpoch::~ProjectionEpoch(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ProjectionEpoch& ProjectionEpoch::operator=(const ProjectionEpoch &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void ProjectionEpoch::insert(ProjectionFunction *function, IndexSpaceNode* node) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!valid_fields); #endif write_projections[function].insert(node); } ///////////////////////////////////////////////////////////// // LogicalState ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalState::LogicalState(RegionTreeNode *node, ContextID ctx) : owner(node) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalState::LogicalState(const LogicalState &rhs) : owner(NULL) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- LogicalState::~LogicalState(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalState& LogicalState::operator=(const LogicalState&rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void LogicalState::check_init(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(field_states.empty()); assert(curr_epoch_users.empty()); assert(prev_epoch_users.empty()); assert(projection_epochs.empty()); assert(!reduction_fields); #endif } //-------------------------------------------------------------------------- void LogicalState::clear_logical_users(void) //-------------------------------------------------------------------------- { if (!curr_epoch_users.empty()) { for (LegionList<LogicalUser,CURR_LOGICAL_ALLOC>::track_aligned:: const_iterator it = curr_epoch_users.begin(); it != curr_epoch_users.end(); it++) { it->op->remove_mapping_reference(it->gen); } curr_epoch_users.clear(); } if (!prev_epoch_users.empty()) { for (LegionList<LogicalUser,PREV_LOGICAL_ALLOC>::track_aligned:: const_iterator it = prev_epoch_users.begin(); it != prev_epoch_users.end(); it++) { it->op->remove_mapping_reference(it->gen); } prev_epoch_users.clear(); } } //-------------------------------------------------------------------------- void LogicalState::reset(void) //-------------------------------------------------------------------------- { field_states.clear(); clear_logical_users(); reduction_fields.clear(); outstanding_reductions.clear(); for (std::list<ProjectionEpoch*>::const_iterator it = projection_epochs.begin(); it != projection_epochs.end(); it++) delete *it; projection_epochs.clear(); } //-------------------------------------------------------------------------- void LogicalState::clear_deleted_state(const FieldMask &deleted_mask) //-------------------------------------------------------------------------- { for (LegionList<FieldState>::aligned::iterator it = field_states.begin(); it != field_states.end(); /*nothing*/) { if (it->filter(deleted_mask)) it = field_states.erase(it); else it++; } reduction_fields -= deleted_mask; if (!outstanding_reductions.empty()) { std::vector<ReductionOpID> to_delete; for (LegionMap<ReductionOpID,FieldMask>::aligned::iterator it = outstanding_reductions.begin(); it != outstanding_reductions.end(); it++) { it->second -= deleted_mask; if (!it->second) to_delete.push_back(it->first); } for (std::vector<ReductionOpID>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { outstanding_reductions.erase(*it); } } } //-------------------------------------------------------------------------- void LogicalState::advance_projection_epochs(const FieldMask &advance_mask) //-------------------------------------------------------------------------- { // See if we can get some coalescing going on here std::map<ProjectionEpochID,ProjectionEpoch*> to_add; for (std::list<ProjectionEpoch*>::iterator it = projection_epochs.begin(); it != projection_epochs.end(); /*nothing*/) { FieldMask overlap = (*it)->valid_fields & advance_mask; if (!overlap) { it++; continue; } const ProjectionEpochID next_epoch_id = (*it)->epoch_id + 1; std::map<ProjectionEpochID,ProjectionEpoch*>::iterator finder = to_add.find(next_epoch_id); if (finder == to_add.end()) { ProjectionEpoch *next_epoch = new ProjectionEpoch((*it)->epoch_id+1, overlap); to_add[next_epoch_id] = next_epoch; } else finder->second->valid_fields |= overlap; // Filter the fields from our old one (*it)->valid_fields -= overlap; if (!((*it)->valid_fields)) { delete (*it); it = projection_epochs.erase(it); } else it++; } if (!to_add.empty()) { for (std::map<ProjectionEpochID,ProjectionEpoch*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) projection_epochs.push_back(it->second); } } //-------------------------------------------------------------------------- void LogicalState::update_projection_epochs(FieldMask capture_mask, const ProjectionInfo &info) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!capture_mask); #endif for (std::list<ProjectionEpoch*>::const_iterator it = projection_epochs.begin(); it != projection_epochs.end(); it++) { FieldMask overlap = (*it)->valid_fields & capture_mask; if (!overlap) continue; capture_mask -= overlap; if (!capture_mask) return; } // If it didn't already exist, start a new projection epoch ProjectionEpoch *new_epoch = new ProjectionEpoch(ProjectionEpoch::first_epoch, capture_mask); projection_epochs.push_back(new_epoch); } ///////////////////////////////////////////////////////////// // FieldState ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- FieldState::FieldState(void) : open_state(NOT_OPEN), redop(0), projection(NULL), projection_space(NULL), rebuild_timeout(1) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FieldState::FieldState(const GenericUser &user, const FieldMask &m, RegionTreeNode *child, std::set<RtEvent> &applied) : redop(0), projection(NULL), projection_space(NULL), rebuild_timeout(1) //-------------------------------------------------------------------------- { if (IS_READ_ONLY(user.usage)) open_state = OPEN_READ_ONLY; else if (IS_WRITE(user.usage)) open_state = OPEN_READ_WRITE; else if (IS_REDUCE(user.usage)) { open_state = OPEN_SINGLE_REDUCE; redop = user.usage.redop; } if (open_children.insert(child, m)) { WrapperReferenceMutator mutator(applied); child->add_base_valid_ref(FIELD_STATE_REF, &mutator); } } //-------------------------------------------------------------------------- FieldState::FieldState(const RegionUsage &usage, const FieldMask &m, ProjectionFunction *proj, IndexSpaceNode *proj_space, bool disjoint, bool dirty_reduction) : redop(0),projection(proj),projection_space(proj_space),rebuild_timeout(1) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(projection != NULL); #endif open_children.relax_valid_mask(m); if (IS_READ_ONLY(usage)) open_state = OPEN_READ_ONLY_PROJ; else if (IS_REDUCE(usage)) { if (dirty_reduction) open_state = OPEN_REDUCE_PROJ_DIRTY; else open_state = OPEN_REDUCE_PROJ; redop = usage.redop; } else if (disjoint && (projection->depth == 0)) open_state = OPEN_READ_WRITE_PROJ_DISJOINT_SHALLOW; else open_state = OPEN_READ_WRITE_PROJ; } //-------------------------------------------------------------------------- FieldState::FieldState(const FieldState &rhs) : open_state(rhs.open_state), redop(rhs.redop), projection(rhs.projection), projection_space(rhs.projection_space), rebuild_timeout(rhs.rebuild_timeout) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(rhs.open_children.empty()); #endif } //-------------------------------------------------------------------------- FieldState::~FieldState(void) //-------------------------------------------------------------------------- { for (FieldMaskSet<RegionTreeNode>::const_iterator it = open_children.begin(); it != open_children.end(); it++) if (it->first->remove_base_valid_ref(FIELD_STATE_REF)) delete it->first; } //-------------------------------------------------------------------------- FieldState& FieldState::operator=(const FieldState &rhs) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(open_children.empty()); assert(rhs.open_children.empty()); #endif open_state = rhs.open_state; redop = rhs.redop; projection = rhs.projection; projection_space = rhs.projection_space; rebuild_timeout = rhs.rebuild_timeout; return *this; } //-------------------------------------------------------------------------- bool FieldState::overlaps(const FieldState &rhs) const //-------------------------------------------------------------------------- { if (redop != rhs.redop) return false; if (projection != rhs.projection) return false; // Only do this test if they are both projections if ((projection != NULL) && (projection_space != rhs.projection_space)) return false; if (redop == 0) return (open_state == rhs.open_state); else { #ifdef DEBUG_LEGION assert((open_state == OPEN_SINGLE_REDUCE) || (open_state == OPEN_MULTI_REDUCE) || (open_state == OPEN_REDUCE_PROJ) || (open_state == OPEN_REDUCE_PROJ_DIRTY)); assert((rhs.open_state == OPEN_SINGLE_REDUCE) || (rhs.open_state == OPEN_MULTI_REDUCE) || (rhs.open_state == OPEN_REDUCE_PROJ) || (rhs.open_state == OPEN_REDUCE_PROJ_DIRTY)); #endif // Only support merging reduction fields with exactly the // same mask which should be single fields for reductions return (valid_fields() == rhs.valid_fields()); } } //-------------------------------------------------------------------------- void FieldState::merge(FieldState &rhs, RegionTreeNode *node) //-------------------------------------------------------------------------- { for (FieldMaskSet<RegionTreeNode>::const_iterator it = rhs.open_children.begin(); it != rhs.open_children.end(); it++) // Remove duplicate references if we already had it if (!open_children.insert(it->first, it->second)) it->first->remove_base_valid_ref(FIELD_STATE_REF); rhs.open_children.clear(); #ifdef DEBUG_LEGION assert(redop == rhs.redop); assert(projection == rhs.projection); #endif if (redop > 0) { #ifdef DEBUG_LEGION assert(!open_children.empty()); #endif // For the reductions, handle the case where we need to merge // reduction modes, if they are all disjoint, we don't need // to distinguish between single and multi reduce if (node->are_all_children_disjoint()) { open_state = OPEN_READ_WRITE; redop = 0; } else { if (open_children.size() == 1) open_state = OPEN_SINGLE_REDUCE; else open_state = OPEN_MULTI_REDUCE; } } } //-------------------------------------------------------------------------- bool FieldState::filter(const FieldMask &mask) //-------------------------------------------------------------------------- { if (is_projection_state()) { #ifdef DEBUG_LEGION assert(projection != NULL); assert(open_children.empty()); #endif open_children.filter_valid_mask(mask); return !open_children.get_valid_mask(); } else { std::vector<RegionTreeNode*> to_delete; for (FieldMaskSet<RegionTreeNode>::iterator it = open_children.begin(); it != open_children.end(); it++) { it.filter(mask); if (!it->second) to_delete.push_back(it->first); } if (to_delete.size() < open_children.size()) { for (std::vector<RegionTreeNode*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { open_children.erase(*it); if ((*it)->remove_base_valid_ref(FIELD_STATE_REF)) delete (*it); } } else { open_children.clear(); for (std::vector<RegionTreeNode*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) if ((*it)->remove_base_valid_ref(FIELD_STATE_REF)) delete (*it); } open_children.tighten_valid_mask(); return open_children.empty(); } } //-------------------------------------------------------------------------- void FieldState::add_child(RegionTreeNode *child, const FieldMask &mask, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { if (open_children.insert(child, mask)) { WrapperReferenceMutator mutator(applied_events); child->add_base_valid_ref(FIELD_STATE_REF, &mutator); } } //-------------------------------------------------------------------------- void FieldState::remove_child(RegionTreeNode *child) //-------------------------------------------------------------------------- { FieldMaskSet<RegionTreeNode>::iterator finder = open_children.find(child); #ifdef DEBUG_LEGION assert(finder != open_children.end()); assert(!finder->second); #endif open_children.erase(finder); if (child->remove_base_valid_ref(FIELD_STATE_REF)) delete child; } //-------------------------------------------------------------------------- bool FieldState::projection_domain_dominates( IndexSpaceNode *next_space) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(projection_space != NULL); #endif if (projection_space == next_space) return true; // If the domains do not have the same type, the answer must be no if (projection_space->handle.get_type_tag() != next_space->handle.get_type_tag()) return false; return projection_space->dominates(next_space); } //-------------------------------------------------------------------------- void FieldState::print_state(TreeStateLogger *logger, const FieldMask &capture_mask, RegionNode *node) const //-------------------------------------------------------------------------- { switch (open_state) { case NOT_OPEN: { logger->log("Field State: NOT OPEN (%ld)", open_children.size()); break; } case OPEN_READ_WRITE: { logger->log("Field State: OPEN READ WRITE (%ld)", open_children.size()); break; } case OPEN_READ_ONLY: { logger->log("Field State: OPEN READ-ONLY (%ld)", open_children.size()); break; } case OPEN_SINGLE_REDUCE: { logger->log("Field State: OPEN SINGLE REDUCE Mode %d (%ld)", redop, open_children.size()); break; } case OPEN_MULTI_REDUCE: { logger->log("Field State: OPEN MULTI REDUCE Mode %d (%ld)", redop, open_children.size()); break; } case OPEN_READ_ONLY_PROJ: { logger->log("Field State: OPEN READ-ONLY PROJECTION %d", projection->projection_id); break; } case OPEN_READ_WRITE_PROJ: { logger->log("Field State: OPEN READ WRITE PROJECTION %d", projection->projection_id); break; } case OPEN_READ_WRITE_PROJ_DISJOINT_SHALLOW: { logger->log("Field State: OPEN READ WRITE PROJECTION (Disjoint Shallow) %d", projection->projection_id); break; } case OPEN_REDUCE_PROJ: { logger->log("Field State: OPEN REDUCE PROJECTION %d Mode %d", projection->projection_id, redop); break; } case OPEN_REDUCE_PROJ_DIRTY: { logger->log("Field State: OPEN REDUCE PROJECTION (Dirty) %d Mode %d", projection->projection_id, redop); break; } default: assert(false); } logger->down(); for (FieldMaskSet<RegionTreeNode>::const_iterator it = open_children.begin(); it != open_children.end(); it++) { FieldMask overlap = it->second & capture_mask; if (!overlap) continue; char *mask_buffer = overlap.to_string(); logger->log("Color %d Mask %s", it->first->get_color(), mask_buffer); free(mask_buffer); } logger->up(); } //-------------------------------------------------------------------------- void FieldState::print_state(TreeStateLogger *logger, const FieldMask &capture_mask, PartitionNode *node) const //-------------------------------------------------------------------------- { switch (open_state) { case NOT_OPEN: { logger->log("Field State: NOT OPEN (%ld)", open_children.size()); break; } case OPEN_READ_WRITE: { logger->log("Field State: OPEN READ WRITE (%ld)", open_children.size()); break; } case OPEN_READ_ONLY: { logger->log("Field State: OPEN READ-ONLY (%ld)", open_children.size()); break; } case OPEN_SINGLE_REDUCE: { logger->log("Field State: OPEN SINGLE REDUCE Mode %d (%ld)", redop, open_children.size()); break; } case OPEN_MULTI_REDUCE: { logger->log("Field State: OPEN MULTI REDUCE Mode %d (%ld)", redop, open_children.size()); break; } case OPEN_READ_ONLY_PROJ: { logger->log("Field State: OPEN READ-ONLY PROJECTION %d", projection->projection_id); break; } case OPEN_READ_WRITE_PROJ: { logger->log("Field State: OPEN READ WRITE PROJECTION %d", projection->projection_id); break; } case OPEN_READ_WRITE_PROJ_DISJOINT_SHALLOW: { logger->log("Field State: OPEN READ WRITE PROJECTION (Disjoint Shallow) %d", projection->projection_id); break; } case OPEN_REDUCE_PROJ: { logger->log("Field State: OPEN REDUCE PROJECTION %d Mode %d", projection->projection_id, redop); break; } case OPEN_REDUCE_PROJ_DIRTY: { logger->log("Field State: OPEN REDUCE PROJECTION (Dirty) %d Mode %d", projection->projection_id, redop); break; } default: assert(false); } logger->down(); for (FieldMaskSet<RegionTreeNode>::const_iterator it = open_children.begin(); it != open_children.end(); it++) { IndexSpaceNode *color_space = node->row_source->color_space; DomainPoint color = color_space->delinearize_color_to_point(it->first->get_color()); FieldMask overlap = it->second & capture_mask; if (!overlap) continue; char *mask_buffer = overlap.to_string(); switch (color.get_dim()) { case 1: { logger->log("Color %d Mask %s", color[0], mask_buffer); break; } #if LEGION_MAX_DIM >= 2 case 2: { logger->log("Color (%d,%d) Mask %s", color[0], color[1], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 3 case 3: { logger->log("Color (%d,%d,%d) Mask %s", color[0], color[1], color[2], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 4 case 4: { logger->log("Color (%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 5 case 5: { logger->log("Color (%d,%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], color[4], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 6 case 6: { logger->log("Color (%d,%d,%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], color[4], color[5], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 7 case 7: { logger->log("Color (%d,%d,%d,%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], color[4], color[5], color[6], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 8 case 8: { logger->log("Color (%d,%d,%d,%d,%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], color[4], color[5], color[6], color[7], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 9 case 9: { logger->log("Color (%d,%d,%d,%d,%d,%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], color[4], color[5], color[6], color[7], color[8], mask_buffer); break; } #endif default: assert(false); // implemenent more dimensions } free(mask_buffer); } logger->up(); } ///////////////////////////////////////////////////////////// // Logical Closer ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalCloser::LogicalCloser(ContextID c, const LogicalUser &u, RegionTreeNode *r, bool val) : ctx(c), user(u), root_node(r), validates(val), close_op(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalCloser::LogicalCloser(const LogicalCloser &rhs) : user(rhs.user), root_node(rhs.root_node), validates(rhs.validates) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- LogicalCloser::~LogicalCloser(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalCloser& LogicalCloser::operator=(const LogicalCloser &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void LogicalCloser::record_close_operation(const FieldMask &mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!mask); #endif close_mask |= mask; } //-------------------------------------------------------------------------- void LogicalCloser::record_closed_user(const LogicalUser &user, const FieldMask &mask) //-------------------------------------------------------------------------- { closed_users.push_back(user); LogicalUser &closed_user = closed_users.back(); closed_user.field_mask = mask; } #ifndef LEGION_SPY //-------------------------------------------------------------------------- void LogicalCloser::pop_closed_user(void) //-------------------------------------------------------------------------- { closed_users.pop_back(); } #endif //-------------------------------------------------------------------------- void LogicalCloser::initialize_close_operations(LogicalState &state, Operation *creator, const LogicalTraceInfo &trace_info) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION // These sets of fields better be disjoint assert(!!close_mask); assert(close_op == NULL); #endif // Construct a reigon requirement for this operation // All privileges are based on the parent logical region RegionRequirement req; if (root_node->is_region()) req = RegionRequirement(root_node->as_region_node()->handle, READ_WRITE, EXCLUSIVE, trace_info.req.parent); else req = RegionRequirement(root_node->as_partition_node()->handle, 0, READ_WRITE, EXCLUSIVE, trace_info.req.parent); close_op = creator->runtime->get_available_merge_close_op(); merge_close_gen = close_op->get_generation(); req.privilege_fields.clear(); root_node->column_source->get_field_set(close_mask, trace_info.req.privilege_fields, req.privilege_fields); close_op->initialize(creator->get_context(), req, trace_info, trace_info.req_idx, close_mask, creator); } //-------------------------------------------------------------------------- void LogicalCloser::perform_dependence_analysis(const LogicalUser &current, const FieldMask &open_below, LegionList<LogicalUser,CURR_LOGICAL_ALLOC>::track_aligned &cusers, LegionList<LogicalUser,PREV_LOGICAL_ALLOC>::track_aligned &pusers) //-------------------------------------------------------------------------- { // We also need to do dependence analysis against all the other operations // that this operation recorded dependences on above in the tree so we // don't run too early. LegionList<LogicalUser,LOGICAL_REC_ALLOC>::track_aligned &above_users = current.op->get_logical_records(); const LogicalUser merge_close_user(close_op, 0/*idx*/, RegionUsage(READ_WRITE, EXCLUSIVE, 0/*redop*/), close_mask); register_dependences(close_op, merge_close_user, current, open_below, closed_users, above_users, cusers, pusers); // Now we can remove our references on our local users for (LegionList<LogicalUser>::aligned::const_iterator it = closed_users.begin(); it != closed_users.end(); it++) { it->op->remove_mapping_reference(it->gen); } } // If you are looking for LogicalCloser::register_dependences it can // be found in region_tree.cc to make sure that templates are instantiated //-------------------------------------------------------------------------- void LogicalCloser::update_state(LogicalState &state) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(state.owner == root_node); #endif root_node->filter_prev_epoch_users(state, close_mask); root_node->filter_curr_epoch_users(state, close_mask); } //-------------------------------------------------------------------------- void LogicalCloser::register_close_operations( LegionList<LogicalUser,CURR_LOGICAL_ALLOC>::track_aligned &users) //-------------------------------------------------------------------------- { // No need to add mapping references, we did that in // Note we also use the cached generation IDs since the close // operations have already been kicked off and might be done // LogicalCloser::register_dependences const LogicalUser close_user(close_op, merge_close_gen,0/*idx*/, RegionUsage(READ_WRITE, EXCLUSIVE, 0/*redop*/), close_mask); users.push_back(close_user); } ///////////////////////////////////////////////////////////// // KDNode ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- template<int DIM> KDNode<DIM>::KDNode(IndexSpaceExpression *expr, Runtime *rt, int ref_dim, int last) : runtime(rt), bounds(get_bounds(expr)), refinement_dim(ref_dim), last_changed_dim(last) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(ref_dim < DIM); #endif } //-------------------------------------------------------------------------- template<int DIM> KDNode<DIM>::KDNode(const Rect<DIM> &rect, Runtime *rt, int ref_dim, int last_dim) : runtime(rt), bounds(rect), refinement_dim(ref_dim), last_changed_dim(last_dim) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(ref_dim < DIM); #endif } //-------------------------------------------------------------------------- template<int DIM> KDNode<DIM>::KDNode(const KDNode<DIM> &rhs) : runtime(rhs.runtime), bounds(rhs.bounds), refinement_dim(rhs.refinement_dim), last_changed_dim(rhs.last_changed_dim) //-------------------------------------------------------------------------- { // Should never be called assert(false); } //-------------------------------------------------------------------------- template<int DIM> KDNode<DIM>::~KDNode(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM> KDNode<DIM>& KDNode<DIM>::operator=(const KDNode<DIM> &rhs) //-------------------------------------------------------------------------- { // Should never be called assert(false); return *this; } //-------------------------------------------------------------------------- template<int DIM> /*static*/ Rect<DIM> KDNode<DIM>::get_bounds(IndexSpaceExpression *expr) //-------------------------------------------------------------------------- { ApEvent wait_on; const Domain d = expr->get_domain(wait_on, true/*tight*/); if (wait_on.exists()) wait_on.wait(); return d.bounds<DIM,coord_t>(); } //-------------------------------------------------------------------------- template<int DIM> bool KDNode<DIM>::refine(std::vector<EquivalenceSet*> &subsets, const FieldMask &refinement_mask, unsigned max_depth) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(subsets.size() > LEGION_MAX_BVH_FANOUT); #endif std::vector<Rect<DIM> > subset_bounds(subsets.size()); for (unsigned idx = 0; idx < subsets.size(); idx++) subset_bounds[idx] = get_bounds(subsets[idx]->set_expr); // Compute a splitting plane coord_t split = 0; { // Sort the start and end of each equivalence set bounding rectangle // along the splitting dimension std::set<KDLine> lines; for (unsigned idx = 0; idx < subsets.size(); idx++) { lines.insert(KDLine(subset_bounds[idx].lo[refinement_dim],idx,true)); lines.insert(KDLine(subset_bounds[idx].hi[refinement_dim],idx,false)); } // Construct two lists by scanning from left-to-right and // from right-to-left of the number of rectangles that would // be inlcuded on the left or right side by each splitting plane std::map<coord_t,unsigned> left_inclusive, right_inclusive; unsigned count = 0; for (typename std::set<KDLine>::const_iterator it = lines.begin(); it != lines.end(); it++) { // Only increment for new rectangles if (it->start) count++; // Always record the count for all splits left_inclusive[it->value] = count; } count = 0; for (typename std::set<KDLine>::const_reverse_iterator it = lines.rbegin(); it != lines.rend(); it++) { // End of rectangles are the beginning in this direction if (!it->start) count++; // Always record the count for all splits right_inclusive[it->value] = count; } #ifdef DEBUG_LEGION assert(left_inclusive.size() == right_inclusive.size()); #endif // We want to take the mini-max of the two numbers in order // to try to balance the splitting plane across the two sets unsigned split_max = subsets.size(); for (std::map<coord_t,unsigned>::const_iterator it = left_inclusive.begin(); it != left_inclusive.end(); it++) { const unsigned left = it->second; const unsigned right = right_inclusive[it->first]; const unsigned max = (left > right) ? left : right; if (max < split_max) { split_max = max; split = it->first; } } } // Sort the subsets into left and right Rect<DIM> left_bounds, right_bounds; left_bounds = bounds; right_bounds = bounds; left_bounds.hi[refinement_dim] = split; right_bounds.lo[refinement_dim] = split+1; std::vector<EquivalenceSet*> left_set, right_set; for (unsigned idx = 0; idx < subsets.size(); idx++) { const Rect<DIM> &sub_bounds = subset_bounds[idx]; if (left_bounds.overlaps(sub_bounds)) left_set.push_back(subsets[idx]); if (right_bounds.overlaps(sub_bounds)) right_set.push_back(subsets[idx]); } // Check for the non-convex case where we can't refine anymore if ((refinement_dim == last_changed_dim) && ((left_set.size() == subsets.size()) || (right_set.size() == subsets.size()))) return false; // Recurse down the tree const int next_dim = (refinement_dim + 1) % DIM; bool left_changed = false; if ((left_set.size() > LEGION_MAX_BVH_FANOUT) && (max_depth > 0)) { // If all the subsets span our splitting plane then we need // to either start tracking the last changed dimension or // continue propagating the current one const int left_last_dim = (left_set.size() == subsets.size()) ? ((last_changed_dim != -1) ? last_changed_dim : refinement_dim) : -1; KDNode<DIM> left(left_bounds, runtime, next_dim, left_last_dim); left_changed = left.refine(left_set, refinement_mask, max_depth - 1); } bool right_changed = false; if ((right_set.size() > LEGION_MAX_BVH_FANOUT) && (max_depth > 0)) { // If all the subsets span our splitting plane then we need // to either start tracking the last changed dimension or // continue propagating the current one const int right_last_dim = (right_set.size() == subsets.size()) ? ((last_changed_dim != -1) ? last_changed_dim : refinement_dim) : -1; KDNode<DIM> right(right_bounds, runtime, next_dim, right_last_dim); right_changed = right.refine(right_set, refinement_mask, max_depth - 1); } // If the sum of the left and right equivalence sets // are too big then build intermediate nodes for each one if (((left_set.size() + right_set.size()) > LEGION_MAX_BVH_FANOUT) && (left_set.size() < subsets.size()) && (right_set.size() < subsets.size())) { // Make a new equivalence class and record all the subsets const AddressSpaceID local_space = runtime->address_space; std::set<IndexSpaceExpression*> left_exprs, right_exprs; for (std::vector<EquivalenceSet*>::const_iterator it = left_set.begin(); it != left_set.end(); it++) left_exprs.insert((*it)->set_expr); IndexSpaceExpression *left_union_expr = runtime->forest->union_index_spaces(left_exprs); for (std::vector<EquivalenceSet*>::const_iterator it = right_set.begin(); it != right_set.end(); it++) right_exprs.insert((*it)->set_expr); IndexSpaceExpression *right_union_expr = runtime->forest->union_index_spaces(right_exprs); EquivalenceSet *left_temp = new EquivalenceSet(runtime, runtime->get_available_distributed_id(), local_space, local_space, left_union_expr, NULL/*index space*/, true/*register now*/); EquivalenceSet *right_temp = new EquivalenceSet(runtime, runtime->get_available_distributed_id(), local_space, local_space, right_union_expr, NULL/*index space*/, true/*register now*/); for (std::vector<EquivalenceSet*>::const_iterator it = left_set.begin(); it != left_set.end(); it++) left_temp->record_subset(*it, refinement_mask); for (std::vector<EquivalenceSet*>::const_iterator it = right_set.begin(); it != right_set.end(); it++) right_temp->record_subset(*it, refinement_mask); subsets.clear(); subsets.push_back(left_temp); subsets.push_back(right_temp); return true; } else if (left_changed || right_changed) { // If either right or left changed, then we need to recombine // and deduplicate the equivalence sets before we can return std::set<EquivalenceSet*> children; children.insert(left_set.begin(), left_set.end()); children.insert(right_set.begin(), right_set.end()); subsets.clear(); subsets.insert(subsets.end(), children.begin(), children.end()); return true; } else // No changes were made return false; } ///////////////////////////////////////////////////////////// // Copy Fill Guard ///////////////////////////////////////////////////////////// #ifndef NON_AGGRESSIVE_AGGREGATORS //-------------------------------------------------------------------------- CopyFillGuard::CopyFillGuard(RtUserEvent post, RtUserEvent applied) : guard_postcondition(post), effects_applied(applied), releasing_guards(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyFillGuard::CopyFillGuard(const CopyFillGuard &rhs) : guard_postcondition(rhs.guard_postcondition), effects_applied(rhs.effects_applied) //-------------------------------------------------------------------------- { // Should never be called assert(false); } #else //-------------------------------------------------------------------------- CopyFillGuard::CopyFillGuard(RtUserEvent applied) : effects_applied(applied), releasing_guards(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyFillGuard::CopyFillGuard(const CopyFillGuard &rhs) : effects_applied(rhs.effects_applied) //-------------------------------------------------------------------------- { // Should never be called assert(false); } #endif //-------------------------------------------------------------------------- CopyFillGuard::~CopyFillGuard(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(releasing_guards); // should have done a release assert(guarded_sets.empty()); assert(remote_release_events.empty()); #endif } //-------------------------------------------------------------------------- CopyFillGuard& CopyFillGuard::operator=(const CopyFillGuard &rhs) //-------------------------------------------------------------------------- { // Should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void CopyFillGuard::pack_guard(Serializer &rez) //-------------------------------------------------------------------------- { AutoLock g_lock(guard_lock); // If we're already releasing a guard then there is no point in sending it if (releasing_guards) { rez.serialize(RtUserEvent::NO_RT_USER_EVENT); return; } #ifdef DEBUG_LEGION assert(effects_applied.exists()); #endif // We only ever pack the effects applied event here because once a // guard is on a remote node then the guard postcondition is no longer // useful since all remote copy fill operations will need to key off // the effects applied event to be correct rez.serialize(effects_applied); // Make an event for recording when all the remote events are applied RtUserEvent remote_release = Runtime::create_rt_user_event(); rez.serialize(remote_release); remote_release_events.push_back(remote_release); } //-------------------------------------------------------------------------- /*static*/ CopyFillGuard* CopyFillGuard::unpack_guard(Deserializer &derez, Runtime *runtime, EquivalenceSet *set) //-------------------------------------------------------------------------- { RtUserEvent effects_applied; derez.deserialize(effects_applied); if (!effects_applied.exists()) return NULL; #ifndef NON_AGGRESSIVE_AGGREGATORS // Note we use the effects applied event here twice because all // copy-fill aggregators on this node will need to wait for the // full effects to be applied of any guards on a remote node CopyFillGuard *result = new CopyFillGuard(effects_applied, effects_applied); #else CopyFillGuard *result = new CopyFillGuard(effects_applied); #endif #ifdef DEBUG_LEGION if (!result->record_guard_set(set)) assert(false); #else result->record_guard_set(set); #endif RtUserEvent remote_release; derez.deserialize(remote_release); std::set<RtEvent> release_preconditions; result->release_guards(runtime, release_preconditions, true/*defer*/); if (!release_preconditions.empty()) Runtime::trigger_event(remote_release, Runtime::merge_events(release_preconditions)); else Runtime::trigger_event(remote_release); return result; } //-------------------------------------------------------------------------- bool CopyFillGuard::record_guard_set(EquivalenceSet *set) //-------------------------------------------------------------------------- { if (releasing_guards) return false; AutoLock g_lock(guard_lock); // Check again after getting the lock to avoid the race if (releasing_guards) return false; guarded_sets.insert(set); return true; } //-------------------------------------------------------------------------- bool CopyFillGuard::release_guards(Runtime *rt, std::set<RtEvent> &applied, bool force_deferral /*=false*/) //-------------------------------------------------------------------------- { if (force_deferral || !effects_applied.has_triggered()) { RtUserEvent released = Runtime::create_rt_user_event(); // Meta-task will take responsibility for deletion CopyFillDeletion args(this, implicit_provenance, released); rt->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, effects_applied); applied.insert(released); return false; } else release_guarded_sets(applied); return true; } //-------------------------------------------------------------------------- /*static*/ void CopyFillGuard::handle_deletion(const void *args) //-------------------------------------------------------------------------- { const CopyFillDeletion *dargs = (const CopyFillDeletion*)args; std::set<RtEvent> released_preconditions; dargs->guard->release_guarded_sets(released_preconditions); if (!released_preconditions.empty()) Runtime::trigger_event(dargs->released, Runtime::merge_events(released_preconditions)); else Runtime::trigger_event(dargs->released); delete dargs->guard; } //-------------------------------------------------------------------------- void CopyFillGuard::release_guarded_sets(std::set<RtEvent> &released) //-------------------------------------------------------------------------- { std::set<EquivalenceSet*> to_remove; { AutoLock g_lock(guard_lock); #ifdef DEBUG_LEGION assert(!releasing_guards); #endif releasing_guards = true; to_remove.swap(guarded_sets); if (!remote_release_events.empty()) { released.insert(remote_release_events.begin(), remote_release_events.end()); remote_release_events.clear(); } } if (!to_remove.empty()) { for (std::set<EquivalenceSet*>::const_iterator it = to_remove.begin(); it != to_remove.end(); it++) (*it)->remove_update_guard(this); } } ///////////////////////////////////////////////////////////// // Copy Fill Aggregator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- CopyFillAggregator::CopyFillAggregator(RegionTreeForest *f, Operation *o, unsigned idx, RtEvent g, bool t, PredEvent p) : WrapperReferenceMutator(effects), #ifndef NON_AGGRESSIVE_AGGREGATORS CopyFillGuard(Runtime::create_rt_user_event(), Runtime::create_rt_user_event()), #else CopyFillGuard(Runtime::create_rt_user_event()), #endif forest(f), local_space(f->runtime->address_space), op(o), src_index(idx), dst_index(idx), guard_precondition(g), predicate_guard(p), track_events(t), tracing_src_fills(NULL), tracing_srcs(NULL), tracing_dsts(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyFillAggregator::CopyFillAggregator(RegionTreeForest *f, Operation *o, unsigned src_idx, unsigned dst_idx, RtEvent g, bool t, PredEvent p) : WrapperReferenceMutator(effects), #ifndef NON_AGGRESSIVE_AGGREGATORS CopyFillGuard(Runtime::create_rt_user_event(), Runtime::create_rt_user_event()), #else CopyFillGuard(Runtime::create_rt_user_event()), #endif forest(f), local_space(f->runtime->address_space), op(o), src_index(src_idx), dst_index(dst_idx), guard_precondition(g), predicate_guard(p), track_events(t), tracing_src_fills(NULL), tracing_srcs(NULL), tracing_dsts(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyFillAggregator::CopyFillAggregator(const CopyFillAggregator &rhs) : WrapperReferenceMutator(effects), CopyFillGuard(rhs), forest(rhs.forest), local_space(rhs.local_space), op(rhs.op), src_index(rhs.src_index), dst_index(rhs.dst_index), guard_precondition(rhs.guard_precondition), predicate_guard(rhs.predicate_guard), track_events(rhs.track_events) //-------------------------------------------------------------------------- { // Should never be called assert(false); } //-------------------------------------------------------------------------- CopyFillAggregator::~CopyFillAggregator(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION #ifndef NON_AGGRESSIVE_AGGREGATORS assert(guard_postcondition.has_triggered()); #endif assert(effects_applied.has_triggered()); #endif // Remove references from any views that we have for (std::set<LogicalView*>::const_iterator it = all_views.begin(); it != all_views.end(); it++) if ((*it)->remove_base_valid_ref(AGGREGATORE_REF)) delete (*it); // Delete all our copy updates for (LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned:: const_iterator mit = sources.begin(); mit != sources.end(); mit++) { for (FieldMaskSet<Update>::const_iterator it = mit->second.begin(); it != mit->second.end(); it++) delete it->first; } for (std::vector<LegionMap<InstanceView*, FieldMaskSet<Update> >::aligned>::const_iterator rit = reductions.begin(); rit != reductions.end(); rit++) { for (LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned:: const_iterator mit = rit->begin(); mit != rit->end(); mit++) { for (FieldMaskSet<Update>::const_iterator it = mit->second.begin(); it != mit->second.end(); it++) delete it->first; } } // Clean up any data structures that we made for tracing if (tracing_src_fills != NULL) delete tracing_src_fills; if (tracing_srcs != NULL) delete tracing_srcs; if (tracing_dsts != NULL) delete tracing_dsts; } //-------------------------------------------------------------------------- CopyFillAggregator& CopyFillAggregator::operator=( const CopyFillAggregator &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void CopyFillAggregator::CopyUpdate::record_source_expressions( InstanceFieldExprs &src_exprs) const //-------------------------------------------------------------------------- { FieldMaskSet<IndexSpaceExpression> &exprs = src_exprs[source]; FieldMaskSet<IndexSpaceExpression>::iterator finder = exprs.find(expr); if (finder == exprs.end()) exprs.insert(expr, src_mask); else finder.merge(src_mask); } //-------------------------------------------------------------------------- void CopyFillAggregator::CopyUpdate::compute_source_preconditions( RegionTreeForest *forest, #ifdef DEBUG_LEGION const bool copy_across, #endif const std::map<InstanceView*,EventFieldExprs> &src_pre, LegionMap<ApEvent,FieldMask>::aligned &preconditions) const //-------------------------------------------------------------------------- { std::map<InstanceView*,EventFieldExprs>::const_iterator finder = src_pre.find(source); if (finder == src_pre.end()) return; for (EventFieldExprs::const_iterator eit = finder->second.begin(); eit != finder->second.end(); eit++) { FieldMask set_overlap = src_mask & eit->second.get_valid_mask(); if (!set_overlap) continue; for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = eit->second.begin(); it != eit->second.end(); it++) { const FieldMask overlap = set_overlap & it->second; if (!overlap) continue; IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(expr, it->first); if (expr_overlap->is_empty()) continue; #ifdef DEBUG_LEGION // Since this is an equivalence set update there should be no users // that are using just a part of it, should be all or nothing, with // the exception of copy across operations in which case it doesn't // matter because we don't need precise preconditions there if (copy_across) assert(expr_overlap->get_volume() == expr->get_volume()); #endif // Overlap in both so record it LegionMap<ApEvent,FieldMask>::aligned::iterator event_finder = preconditions.find(eit->first); if (event_finder == preconditions.end()) preconditions[eit->first] = overlap; else event_finder->second |= overlap; set_overlap -= overlap; if (!set_overlap) break; } } } //-------------------------------------------------------------------------- void CopyFillAggregator::CopyUpdate::sort_updates( std::map<InstanceView*, std::vector<CopyUpdate*> > &copies, std::vector<FillUpdate*> &fills) //-------------------------------------------------------------------------- { copies[source].push_back(this); } //-------------------------------------------------------------------------- void CopyFillAggregator::FillUpdate::record_source_expressions( InstanceFieldExprs &src_exprs) const //-------------------------------------------------------------------------- { // Do nothing, we have no source expressions } //-------------------------------------------------------------------------- void CopyFillAggregator::FillUpdate::compute_source_preconditions( RegionTreeForest *forest, #ifdef DEBUG_LEGION const bool copy_across, #endif const std::map<InstanceView*,EventFieldExprs> &src_pre, LegionMap<ApEvent,FieldMask>::aligned &preconditions) const //-------------------------------------------------------------------------- { // Do nothing, we have no source preconditions to worry about } //-------------------------------------------------------------------------- void CopyFillAggregator::FillUpdate::sort_updates( std::map<InstanceView*, std::vector<CopyUpdate*> > &copies, std::vector<FillUpdate*> &fills) //-------------------------------------------------------------------------- { fills.push_back(this); } //-------------------------------------------------------------------------- void CopyFillAggregator::record_updates(InstanceView *dst_view, const FieldMaskSet<LogicalView> &src_views, const FieldMask &src_mask, IndexSpaceExpression *expr, ReductionOpID redop /*=0*/, CopyAcrossHelper *helper /*=NULL*/) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!src_mask); assert(!src_views.empty()); assert(!expr->is_empty()); #endif update_fields |= src_mask; FieldMaskSet<Update> &updates = sources[dst_view]; record_view(dst_view); if (src_views.size() == 1) { const LogicalView *view = src_views.begin()->first; const FieldMask record_mask = src_views.get_valid_mask() & src_mask; if (!!record_mask) { if (view->is_instance_view()) { InstanceView *inst = view->as_instance_view(); record_view(inst); CopyUpdate *update = new CopyUpdate(inst, record_mask, expr, redop, helper); if (helper == NULL) updates.insert(update, record_mask); else updates.insert(update, helper->convert_src_to_dst(record_mask)); } else { DeferredView *def = view->as_deferred_view(); def->flatten(*this, dst_view, record_mask, expr, helper); } } } else { // We have multiple views, so let's sort them LegionList<FieldSet<LogicalView*> >::aligned view_sets; src_views.compute_field_sets(src_mask, view_sets); for (LegionList<FieldSet<LogicalView*> >::aligned::const_iterator vit = view_sets.begin(); vit != view_sets.end(); vit++) { if (vit->elements.empty()) continue; if (vit->elements.size() == 1) { // Easy case, just one view so do it const LogicalView *view = *(vit->elements.begin()); const FieldMask &record_mask = vit->set_mask; if (view->is_instance_view()) { InstanceView *inst = view->as_instance_view(); record_view(inst); CopyUpdate *update = new CopyUpdate(inst, record_mask, expr, redop, helper); if (helper == NULL) updates.insert(update, record_mask); else updates.insert(update, helper->convert_src_to_dst(record_mask)); } else { DeferredView *def = view->as_deferred_view(); def->flatten(*this, dst_view, record_mask, expr, helper); } } else { // Sort the views, prefer fills, then instances, then deferred FillView *fill = NULL; DeferredView *deferred = NULL; std::vector<InstanceView*> instances; for (std::set<LogicalView*>::const_iterator it = vit->elements.begin(); it != vit->elements.end(); it++) { if (!(*it)->is_instance_view()) { DeferredView *def = (*it)->as_deferred_view(); if (!def->is_fill_view()) { if (deferred == NULL) deferred = def; } else { fill = def->as_fill_view(); // Break out since we found what we're looking for break; } } else instances.push_back((*it)->as_instance_view()); } if (fill != NULL) record_fill(dst_view, fill, vit->set_mask, expr, helper); else if (!instances.empty()) { if (instances.size() == 1) { // Easy, just one instance to use InstanceView *inst = instances.back(); record_view(inst); CopyUpdate *update = new CopyUpdate(inst, vit->set_mask, expr, redop, helper); if (helper == NULL) updates.insert(update, vit->set_mask); else updates.insert(update, helper->convert_src_to_dst(vit->set_mask)); } else { // Hard, multiple potential sources, // ask the mapper which one to use // First though check to see if we've already asked it bool found = false; const std::set<InstanceView*> instances_set(instances.begin(), instances.end()); std::map<InstanceView*,LegionVector<SourceQuery>::aligned>:: const_iterator finder = mapper_queries.find(dst_view); if (finder != mapper_queries.end()) { for (LegionVector<SourceQuery>::aligned::const_iterator qit = finder->second.begin(); qit != finder->second.end(); qit++) { if ((qit->query_mask == vit->set_mask) && (qit->sources == instances_set)) { found = true; record_view(qit->result); CopyUpdate *update = new CopyUpdate(qit->result, qit->query_mask, expr, redop, helper); if (helper == NULL) updates.insert(update, qit->query_mask); else updates.insert(update, helper->convert_src_to_dst(qit->query_mask)); break; } } } if (!found) { // If we didn't find the query result we need to do // it for ourself, start by constructing the inputs InstanceRef dst(dst_view->get_manager(), helper == NULL ? vit->set_mask : helper->convert_src_to_dst(vit->set_mask)); InstanceSet sources(instances.size()); unsigned src_idx = 0; for (std::vector<InstanceView*>::const_iterator it = instances.begin(); it != instances.end(); it++) sources[src_idx++] = InstanceRef((*it)->get_manager(), vit->set_mask); std::vector<unsigned> ranking; // Always use the source index for selecting sources op->select_sources(src_index, dst, sources, ranking); // We know that which ever one was chosen first is // the one that satisfies all our fields since all // these instances are valid for all fields InstanceView *result = ranking.empty() ? instances.front() : instances[ranking[0]]; // Record the update record_view(result); CopyUpdate *update = new CopyUpdate(result, vit->set_mask, expr, redop, helper); if (helper == NULL) updates.insert(update, vit->set_mask); else updates.insert(update, helper->convert_src_to_dst(vit->set_mask)); // Save the result for the future mapper_queries[dst_view].push_back( SourceQuery(instances_set, vit->set_mask, result)); } } } else { #ifdef DEBUG_LEGION assert(deferred != NULL); #endif deferred->flatten(*this, dst_view, vit->set_mask, expr, helper); } } } } } //-------------------------------------------------------------------------- void CopyFillAggregator::record_fill(InstanceView *dst_view, FillView *src_view, const FieldMask &fill_mask, IndexSpaceExpression *expr, CopyAcrossHelper *helper /*=NULL*/) //-------------------------------------------------------------------------- { // No need to record the destination as we already did that the first // time through on our way to finding this fill view #ifdef DEBUG_LEGION assert(all_views.find(dst_view) != all_views.end()); assert(!!fill_mask); assert(!expr->is_empty()); #endif update_fields |= fill_mask; record_view(src_view); FillUpdate *update = new FillUpdate(src_view, fill_mask, expr, helper); if (helper == NULL) sources[dst_view].insert(update, fill_mask); else sources[dst_view].insert(update, helper->convert_src_to_dst(fill_mask)); } //-------------------------------------------------------------------------- void CopyFillAggregator::record_reductions(InstanceView *dst_view, const std::vector<ReductionView*> &src_views, const unsigned src_fidx, const unsigned dst_fidx, IndexSpaceExpression *expr, CopyAcrossHelper *across_helper) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!src_views.empty()); assert(!expr->is_empty()); #endif update_fields.set_bit(src_fidx); record_view(dst_view); for (std::vector<ReductionView*>::const_iterator it = src_views.begin(); it != src_views.end(); it++) record_view(*it); const std::pair<InstanceView*,unsigned> dst_key(dst_view, dst_fidx); std::vector<ReductionOpID> &redop_epochs = reduction_epochs[dst_key]; FieldMask src_mask, dst_mask; src_mask.set_bit(src_fidx); dst_mask.set_bit(dst_fidx); // Always start scanning from the first redop index unsigned redop_index = 0; for (std::vector<ReductionView*>::const_iterator it = src_views.begin(); it != src_views.end(); it++) { const ReductionOpID redop = (*it)->get_redop(); CopyUpdate *update = new CopyUpdate(*it, src_mask, expr, redop, across_helper); // Scan along looking for a reduction op epoch that matches while ((redop_index < redop_epochs.size()) && (redop_epochs[redop_index] != redop)) redop_index++; if (redop_index == redop_epochs.size()) { #ifdef DEBUG_LEGION assert(redop_index <= reductions.size()); #endif // Start a new redop epoch if necessary redop_epochs.push_back(redop); if (reductions.size() == redop_index) reductions.resize(redop_index + 1); } reductions[redop_index][dst_view].insert(update, dst_mask); } } //-------------------------------------------------------------------------- void CopyFillAggregator::record_preconditions(InstanceView *view, bool reading, EventFieldExprs &preconditions) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!preconditions.empty()); #endif AutoLock p_lock(pre_lock); EventFieldExprs &pre = reading ? src_pre[view] : dst_pre[view]; for (EventFieldExprs::iterator eit = preconditions.begin(); eit != preconditions.end(); eit++) { EventFieldExprs::iterator event_finder = pre.find(eit->first); if (event_finder != pre.end()) { // Need to do the merge manually for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = eit->second.begin(); it != eit->second.end(); it++) { FieldMaskSet<IndexSpaceExpression>::iterator finder = event_finder->second.find(it->first); if (finder == event_finder->second.end()) event_finder->second.insert(it->first, it->second); else finder.merge(it->second); } } else // We can just swap this over pre[eit->first].swap(eit->second); } } //-------------------------------------------------------------------------- void CopyFillAggregator::record_precondition(InstanceView *view, bool reading, ApEvent event, const FieldMask &mask, IndexSpaceExpression *expr) //-------------------------------------------------------------------------- { AutoLock p_lock(pre_lock); FieldMaskSet<IndexSpaceExpression> &event_pre = reading ? src_pre[view][event] : dst_pre[view][event]; FieldMaskSet<IndexSpaceExpression>::iterator finder = event_pre.find(expr); if (finder == event_pre.end()) event_pre.insert(expr, mask); else finder.merge(mask); } //-------------------------------------------------------------------------- void CopyFillAggregator::issue_updates(const PhysicalTraceInfo &trace_info, ApEvent precondition, const bool has_src_preconditions, const bool has_dst_preconditions, const bool need_deferral, unsigned pass, bool need_pass_preconditions) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!sources.empty() || !reductions.empty()); #endif if (need_deferral || (guard_precondition.exists() && !guard_precondition.has_triggered())) { CopyFillAggregation args(this, trace_info, precondition, has_src_preconditions, has_dst_preconditions, op->get_unique_op_id(), pass, need_pass_preconditions); op->runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, guard_precondition); return; } #ifdef DEBUG_LEGION assert(!guard_precondition.exists() || guard_precondition.has_triggered()); #endif if (pass == 0) { // Perform updates from any sources first if (!sources.empty()) { const RtEvent deferral_event = perform_updates(sources, trace_info, precondition, has_src_preconditions, has_dst_preconditions, need_pass_preconditions); if (deferral_event.exists()) { CopyFillAggregation args(this, trace_info, precondition, has_src_preconditions, has_dst_preconditions, op->get_unique_op_id(), pass, false/*need pre*/); op->runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, deferral_event); return; } } // We made it through the first pass pass++; need_pass_preconditions = true; } // Then apply any reductions that we might have if (!reductions.empty()) { #ifdef DEBUG_LEGION assert(pass > 0); #endif // Skip any passes that we might have already done for (unsigned idx = pass-1; idx < reductions.size(); idx++) { const RtEvent deferral_event = perform_updates(reductions[idx], trace_info, precondition, has_src_preconditions, has_dst_preconditions, need_pass_preconditions); if (deferral_event.exists()) { CopyFillAggregation args(this, trace_info, precondition, has_src_preconditions, has_dst_preconditions, op->get_unique_op_id(), pass, false/*need pre*/); op->runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, deferral_event); return; } // Made it through this pass pass++; need_pass_preconditions = true; } } #ifndef NON_AGGRESSIVE_AGGREGATORS Runtime::trigger_event(guard_postcondition); #endif // We can also trigger our guard event once the effects are applied if (!effects.empty()) Runtime::trigger_event(effects_applied, Runtime::merge_events(effects)); else Runtime::trigger_event(effects_applied); } //-------------------------------------------------------------------------- ApEvent CopyFillAggregator::summarize(const PhysicalTraceInfo &info) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(track_events); #endif if (!events.empty()) return Runtime::merge_events(&info, events); else return ApEvent::NO_AP_EVENT; } //-------------------------------------------------------------------------- void CopyFillAggregator::record_view(LogicalView *new_view) //-------------------------------------------------------------------------- { std::pair<std::set<LogicalView*>::iterator,bool> result = all_views.insert(new_view); if (result.second) new_view->add_base_valid_ref(AGGREGATORE_REF, this); } //-------------------------------------------------------------------------- RtEvent CopyFillAggregator::perform_updates( const LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned &updates, const PhysicalTraceInfo &trace_info, const ApEvent all_precondition, const bool has_src_preconditions, const bool has_dst_preconditions, const bool needs_preconditions) //-------------------------------------------------------------------------- { if (needs_preconditions && (!has_src_preconditions || !has_dst_preconditions)) { // First compute the access expressions for all the copies InstanceFieldExprs dst_exprs, src_exprs; for (LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned:: const_iterator uit = updates.begin(); uit != updates.end(); uit++) { FieldMaskSet<IndexSpaceExpression> &dst_expr = dst_exprs[uit->first]; for (FieldMaskSet<Update>::const_iterator it = uit->second.begin(); it != uit->second.end(); it++) { // Update the destinations first if (!has_dst_preconditions) { #ifdef DEBUG_LEGION // We should not have an across helper in this case assert(it->first->across_helper == NULL); #endif FieldMaskSet<IndexSpaceExpression>::iterator finder = dst_expr.find(it->first->expr); if (finder == dst_expr.end()) dst_expr.insert(it->first->expr, it->second); else finder.merge(it->second); } // Now record the source expressions if (!has_src_preconditions) it->first->record_source_expressions(src_exprs); } } // Next compute the event preconditions for these accesses std::set<RtEvent> preconditions_ready; const UniqueID op_id = op->get_unique_op_id(); if (!has_dst_preconditions) { dst_pre.clear(); for (InstanceFieldExprs::const_iterator dit = dst_exprs.begin(); dit != dst_exprs.end(); dit++) { if (dit->second.size() == 1) { // No need to do any kind of sorts here IndexSpaceExpression *copy_expr = dit->second.begin()->first; const FieldMask &copy_mask = dit->second.get_valid_mask(); RtEvent pre_ready = dit->first->find_copy_preconditions( false/*reading*/, copy_mask, copy_expr, op_id, dst_index,*this,trace_info.recording,local_space); if (pre_ready.exists()) preconditions_ready.insert(pre_ready); } else { // Sort into field sets and merge expressions LegionList<FieldSet<IndexSpaceExpression*> >::aligned sorted_exprs; dit->second.compute_field_sets(FieldMask(), sorted_exprs); for (LegionList<FieldSet<IndexSpaceExpression*> >::aligned:: const_iterator it = sorted_exprs.begin(); it != sorted_exprs.end(); it++) { const FieldMask &copy_mask = it->set_mask; IndexSpaceExpression *copy_expr = (it->elements.size() == 1) ? *(it->elements.begin()) : forest->union_index_spaces(it->elements); RtEvent pre_ready = dit->first->find_copy_preconditions( false/*reading*/, copy_mask, copy_expr, op_id, dst_index, *this, trace_info.recording, local_space); if (pre_ready.exists()) preconditions_ready.insert(pre_ready); } } } } if (!has_src_preconditions) { src_pre.clear(); for (InstanceFieldExprs::const_iterator sit = src_exprs.begin(); sit != src_exprs.end(); sit++) { if (sit->second.size() == 1) { // No need to do any kind of sorts here IndexSpaceExpression *copy_expr = sit->second.begin()->first; const FieldMask &copy_mask = sit->second.get_valid_mask(); RtEvent pre_ready = sit->first->find_copy_preconditions( true/*reading*/, copy_mask, copy_expr, op_id, src_index, *this, trace_info.recording,local_space); if (pre_ready.exists()) preconditions_ready.insert(pre_ready); } else { // Sort into field sets and merge expressions LegionList<FieldSet<IndexSpaceExpression*> >::aligned sorted_exprs; sit->second.compute_field_sets(FieldMask(), sorted_exprs); for (LegionList<FieldSet<IndexSpaceExpression*> >::aligned:: const_iterator it = sorted_exprs.begin(); it != sorted_exprs.end(); it++) { const FieldMask &copy_mask = it->set_mask; IndexSpaceExpression *copy_expr = (it->elements.size() == 1) ? *(it->elements.begin()) : forest->union_index_spaces(it->elements); RtEvent pre_ready = sit->first->find_copy_preconditions( true/*reading*/, copy_mask, copy_expr, op_id, src_index, *this, trace_info.recording, local_space); if (pre_ready.exists()) preconditions_ready.insert(pre_ready); } } } } // If necessary wait until all we have all the preconditions if (!preconditions_ready.empty()) { const RtEvent wait_on = Runtime::merge_events(preconditions_ready); if (wait_on.exists()) return wait_on; } } #ifndef UNSAFE_AGGREGATION // Iterate over the destinations and compute updates that have the // same preconditions on different fields std::map<std::set<ApEvent>,ApEvent> merge_cache; for (LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned:: const_iterator uit = updates.begin(); uit != updates.end(); uit++) { EventFieldUpdates update_groups; const EventFieldExprs &dst_preconditions = dst_pre[uit->first]; for (FieldMaskSet<Update>::const_iterator it = uit->second.begin(); it != uit->second.end(); it++) { // Compute the preconditions for this update // This is a little tricky for across copies because we need // to make sure that all the fields are in same field space // which will be the source field space, so we need to convert // some field masks back to that space if necessary LegionMap<ApEvent,FieldMask>::aligned preconditions; // Compute the destination preconditions first if (!dst_preconditions.empty()) { for (EventFieldExprs::const_iterator pit = dst_preconditions.begin(); pit != dst_preconditions.end(); pit++) { FieldMask set_overlap = it->second & pit->second.get_valid_mask(); if (!set_overlap) continue; for (FieldMaskSet<IndexSpaceExpression>::const_iterator eit = pit->second.begin(); eit != pit->second.end(); eit++) { const FieldMask overlap = set_overlap & eit->second; if (!overlap) continue; IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(eit->first, it->first->expr); if (expr_overlap->is_empty()) continue; #ifdef DEBUG_LEGION // Since this is an equivalence set update there should // be no users that are using just a part of it, should // be all or nothing, unless this is a copy across in // which case it doesn't matter if (src_index != dst_index) assert(expr_overlap->get_volume() == it->first->expr->get_volume()); #endif // Overlap on both so add it to the set LegionMap<ApEvent,FieldMask>::aligned::iterator finder = preconditions.find(pit->first); // Make sure to convert back to the source field space // in the case of across copies if necessary if (finder == preconditions.end()) { if (it->first->across_helper == NULL) preconditions[pit->first] = overlap; else preconditions[pit->first] = it->first->across_helper->convert_dst_to_src(overlap); } else { if (it->first->across_helper == NULL) finder->second |= overlap; else finder->second |= it->first->across_helper->convert_dst_to_src(overlap); } set_overlap -= overlap; // If we found preconditions on all our fields then we're done if (!set_overlap) break; } } } // The compute the source preconditions for this update it->first->compute_source_preconditions(forest, #ifdef DEBUG_LEGION (src_index != dst_index), #endif src_pre, preconditions); if (preconditions.empty()) // NO precondition so enter it with a no event update_groups[ApEvent::NO_AP_EVENT].insert(it->first, it->first->src_mask); else if (preconditions.size() == 1) { LegionMap<ApEvent,FieldMask>::aligned::const_iterator first = preconditions.begin(); update_groups[first->first].insert(it->first, first->second); const FieldMask remainder = it->first->src_mask - first->second; if (!!remainder) update_groups[ApEvent::NO_AP_EVENT].insert(it->first, remainder); } else { // Group event preconditions by fields LegionList<FieldSet<ApEvent> >::aligned grouped_events; compute_field_sets<ApEvent>(it->first->src_mask, preconditions, grouped_events); for (LegionList<FieldSet<ApEvent> >::aligned::const_iterator ait = grouped_events.begin(); ait != grouped_events.end(); ait++) { ApEvent key; if (ait->elements.size() > 1) { // See if the set is in the cache or we need to compute it std::map<std::set<ApEvent>,ApEvent>::const_iterator finder = merge_cache.find(ait->elements); if (finder == merge_cache.end()) { key = Runtime::merge_events(&trace_info, ait->elements); merge_cache[ait->elements] = key; } else key = finder->second; } else if (ait->elements.size() == 1) key = *(ait->elements.begin()); FieldMaskSet<Update> &group = update_groups[key]; FieldMaskSet<Update>::iterator finder = group.find(it->first); if (finder != group.end()) finder.merge(ait->set_mask); else group.insert(it->first, ait->set_mask); } } } // Now iterate over events and group by fields for (EventFieldUpdates::const_iterator eit = update_groups.begin(); eit != update_groups.end(); eit++) { // Merge in the over-arching precondition if necessary const ApEvent group_precondition = all_precondition.exists() ? Runtime::merge_events(&trace_info, all_precondition, eit->first) : eit->first; const FieldMaskSet<Update> &group = eit->second; #ifdef DEBUG_LEGION assert(!group.empty()); #endif if (group.size() == 1) { // Only one update so no need to try to group or merge std::vector<FillUpdate*> fills; std::map<InstanceView* /*src*/,std::vector<CopyUpdate*> > copies; Update *update = group.begin()->first; update->sort_updates(copies, fills); const FieldMask &update_mask = group.get_valid_mask(); if (!fills.empty()) issue_fills(uit->first, fills, group_precondition, update_mask, trace_info, has_dst_preconditions); if (!copies.empty()) issue_copies(uit->first, copies, group_precondition, update_mask, trace_info, has_dst_preconditions); } else { // Group by fields LegionList<FieldSet<Update*> >::aligned field_groups; group.compute_field_sets(FieldMask(), field_groups); for (LegionList<FieldSet<Update*> >::aligned::const_iterator fit = field_groups.begin(); fit != field_groups.end(); fit++) { std::vector<FillUpdate*> fills; std::map<InstanceView* /*src*/, std::vector<CopyUpdate*> > copies; for (std::set<Update*>::const_iterator it = fit->elements.begin(); it != fit->elements.end(); it++) (*it)->sort_updates(copies, fills); if (!fills.empty()) issue_fills(uit->first, fills, group_precondition, fit->set_mask, trace_info, has_dst_preconditions); if (!copies.empty()) issue_copies(uit->first, copies, group_precondition, fit->set_mask, trace_info, has_dst_preconditions); } } } } // iterate over dst instances #else // This is the unsafe aggregation routine that just looks at fields // and expressions and doesn't consider event preconditions for (LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned:: const_iterator uit = updates.begin(); uit != updates.end(); uit++) { const EventFieldExprs &dst_preconditions = dst_pre[uit->first]; // Group by fields first LegionList<FieldSet<Update*> >::aligned field_groups; uit->second.compute_field_sets(FieldMask(), field_groups); for (LegionList<FieldSet<Update*> >::aligned::const_iterator fit = field_groups.begin(); fit != field_groups.end(); fit++) { const FieldMask &dst_mask = fit->set_mask; // Now that we have the src mask for these operations group // them into fills and copies and then do their event analysis std::vector<FillUpdate*> fills; std::map<InstanceView* /*src*/,std::vector<CopyUpdate*> > copies; for (std::set<Update*>::const_iterator it = fit->elements.begin(); it != fit->elements.end(); it++) (*it)->sort_updates(copies, fills); // Issue the copies and fills if (!fills.empty()) { std::set<ApEvent> preconditions; if (all_precondition.exists()) preconditions.insert(all_precondition); std::set<IndexSpaceExpression*> fill_exprs; for (std::vector<FillUpdate*>::const_iterator it = fills.begin(); it != fills.end(); it++) fill_exprs.insert((*it)->expr); IndexSpaceExpression *fill_expr = (fill_exprs.size() == 1) ? *(fill_exprs.begin()) : forest->union_index_spaces(fill_exprs); for (EventFieldExprs::const_iterator eit = dst_preconditions.begin(); eit != dst_preconditions.end(); eit++) { // If there are no overlapping fields we can skip it if (dst_mask * eit->second.get_valid_mask()) continue; for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = eit->second.begin(); it != eit->second.end(); it++) { if (it->second * dst_mask) continue; IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(it->first, fill_expr); if (!expr_overlap->is_empty()) { preconditions.insert(eit->first); break; } } } CopyAcrossHelper *across_helper = fills[0]->across_helper; const FieldMask src_mask = (across_helper == NULL) ? dst_mask : across_helper->convert_dst_to_src(dst_mask); if (!preconditions.empty()) { const ApEvent fill_precondition = Runtime::merge_events(&trace_info, preconditions); issue_fills(uit->first, fills, fill_precondition, src_mask, trace_info, has_dst_preconditions); } else issue_fills(uit->first, fills, ApEvent::NO_AP_EVENT, src_mask, trace_info, has_dst_preconditions); } if (!copies.empty()) { std::set<ApEvent> preconditions; if (all_precondition.exists()) preconditions.insert(all_precondition); std::set<IndexSpaceExpression*> copy_exprs; for (std::map<InstanceView*,std::vector<CopyUpdate*> >:: const_iterator cit = copies.begin(); cit != copies.end(); cit++) for (std::vector<CopyUpdate*>::const_iterator it = cit->second.begin(); it != cit->second.end(); it++) copy_exprs.insert((*it)->expr); IndexSpaceExpression *copy_expr = (copy_exprs.size() == 1) ? *(copy_exprs.begin()) : forest->union_index_spaces(copy_exprs); // Destination preconditions first for (EventFieldExprs::const_iterator eit = dst_preconditions.begin(); eit != dst_preconditions.end(); eit++) { // If there are no overlapping fields we can skip it if (dst_mask * eit->second.get_valid_mask()) continue; for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = eit->second.begin(); it != eit->second.end(); it++) { if (it->second * dst_mask) continue; IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(it->first, copy_expr); if (!expr_overlap->is_empty()) { preconditions.insert(eit->first); break; } } } // Then do the source preconditions // Be careful that we get the destination fields right in the // case that this is an across copy CopyAcrossHelper *across_helper = copies.begin()->second[0]->across_helper; const FieldMask src_mask = (across_helper == NULL) ? dst_mask : across_helper->convert_dst_to_src(dst_mask); LegionMap<ApEvent,FieldMask>::aligned src_preconds; for (std::map<InstanceView*,std::vector<CopyUpdate*> >:: const_iterator cit = copies.begin(); cit != copies.end(); cit++) { for (std::vector<CopyUpdate*>::const_iterator it = cit->second.begin(); it != cit->second.end(); it++) { (*it)->compute_source_preconditions(forest, #ifdef DEBUG_LEGION (src_index != dst_index), #endif src_pre, src_preconds); } } for (LegionMap<ApEvent,FieldMask>::aligned::const_iterator it = src_preconds.begin(); it != src_preconds.end(); it++) { if (it->second * dst_mask) continue; preconditions.insert(it->first); } if (!preconditions.empty()) { const ApEvent copy_precondition = Runtime::merge_events(&trace_info, preconditions); issue_copies(uit->first, copies, copy_precondition, src_mask, trace_info, has_dst_preconditions); } else issue_copies(uit->first, copies, ApEvent::NO_AP_EVENT, src_mask, trace_info, has_dst_preconditions); } } } #endif return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- void CopyFillAggregator::issue_fills(InstanceView *target, const std::vector<FillUpdate*> &fills, ApEvent precondition, const FieldMask &fill_mask, const PhysicalTraceInfo &trace_info, const bool has_dst_preconditions) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!fills.empty()); assert(!!fill_mask); #endif const UniqueID op_id = op->get_unique_op_id(); PhysicalManager *manager = target->get_manager(); if (fills.size() == 1) { FillUpdate *update = fills[0]; #ifdef DEBUG_LEGION // Should cover all the fields assert(!(fill_mask - update->src_mask)); #endif IndexSpaceExpression *fill_expr = update->expr; FillView *fill_view = update->source; // Check to see if we need to do any work for tracing if (trace_info.recording) { if (tracing_src_fills == NULL) tracing_src_fills = new FieldMaskSet<FillView>(); else tracing_src_fills->clear(); // Record the source view tracing_src_fills->insert(fill_view, fill_mask); if (tracing_dsts == NULL) tracing_dsts = new FieldMaskSet<InstanceView>(); else tracing_dsts->clear(); // Record the destination view, convert field mask if necessary if (update->across_helper != NULL) { const FieldMask dst_mask = update->across_helper->convert_src_to_dst(fill_mask); tracing_dsts->insert(target, dst_mask); } else tracing_dsts->insert(target, fill_mask); } const ApEvent result = manager->fill_from(fill_view, precondition, predicate_guard, fill_expr, fill_mask, trace_info, fills[0]->across_helper, tracing_src_fills, tracing_dsts); // Record the fill result in the destination if (result.exists()) { const RtEvent collect_event = trace_info.get_collect_event(); if (update->across_helper != NULL) { const FieldMask dst_mask = update->across_helper->convert_src_to_dst(fill_mask); target->add_copy_user(false/*reading*/, result, collect_event, dst_mask, fill_expr, op_id, dst_index, effects, trace_info.recording, local_space); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, dst_mask, fill_expr); } else { target->add_copy_user(false/*reading*/, result, collect_event, fill_mask, fill_expr, op_id,dst_index, effects, trace_info.recording, local_space); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, fill_mask, fill_expr); } if (track_events) events.insert(result); } } else { #ifdef DEBUG_LEGION #ifndef NDEBUG // These should all have had the same across helper for (unsigned idx = 1; idx < fills.size(); idx++) assert(fills[idx]->across_helper == fills[0]->across_helper); #endif #endif std::map<FillView*,std::set<IndexSpaceExpression*> > exprs; for (std::vector<FillUpdate*>::const_iterator it = fills.begin(); it != fills.end(); it++) { #ifdef DEBUG_LEGION // Should cover all the fields assert(!(fill_mask - (*it)->src_mask)); // Should also have the same across helper as the first one assert(fills[0]->across_helper == (*it)->across_helper); #endif exprs[(*it)->source].insert((*it)->expr); } const FieldMask dst_mask = (fills[0]->across_helper == NULL) ? fill_mask : fills[0]->across_helper->convert_src_to_dst(fill_mask); // See if we have any work to do for tracing if (trace_info.recording) { // Destination is the same for all the fills if (tracing_dsts == NULL) tracing_dsts = new FieldMaskSet<InstanceView>(); else tracing_dsts->clear(); tracing_dsts->insert(target, dst_mask); } for (std::map<FillView*,std::set<IndexSpaceExpression*> >:: const_iterator it = exprs.begin(); it != exprs.end(); it++) { IndexSpaceExpression *fill_expr = (it->second.size() == 1) ? *(it->second.begin()) : forest->union_index_spaces(it->second); if (trace_info.recording) { if (tracing_src_fills == NULL) tracing_src_fills = new FieldMaskSet<FillView>(); else tracing_src_fills->clear(); // Record the source view tracing_src_fills->insert(it->first, fill_mask); } // See if we have any work to do for tracing const ApEvent result = manager->fill_from(it->first, precondition, predicate_guard, fill_expr, fill_mask, trace_info, fills[0]->across_helper, tracing_src_fills, tracing_dsts); const RtEvent collect_event = trace_info.get_collect_event(); if (result.exists()) { target->add_copy_user(false/*reading*/, result, collect_event, dst_mask, fill_expr, op_id, dst_index, effects, trace_info.recording, local_space); if (track_events) events.insert(result); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, dst_mask, fill_expr); } } } } //-------------------------------------------------------------------------- void CopyFillAggregator::issue_copies(InstanceView *target, const std::map<InstanceView*, std::vector<CopyUpdate*> > &copies, ApEvent precondition, const FieldMask &copy_mask, const PhysicalTraceInfo &trace_info, const bool has_dst_preconditions) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!copies.empty()); assert(!!copy_mask); #endif const UniqueID op_id = op->get_unique_op_id(); PhysicalManager *target_manager = target->get_manager(); for (std::map<InstanceView*,std::vector<CopyUpdate*> >::const_iterator cit = copies.begin(); cit != copies.end(); cit++) { #ifdef DEBUG_LEGION assert(!cit->second.empty()); #endif if (cit->second.size() == 1) { // Easy case of a single update copy CopyUpdate *update = cit->second[0]; #ifdef DEBUG_LEGION // Should cover all the fields assert(!(copy_mask - update->src_mask)); #endif InstanceView *source = update->source; IndexSpaceExpression *copy_expr = update->expr; // See if we have any work to do for tracing if (trace_info.recording) { if (tracing_srcs == NULL) tracing_srcs = new FieldMaskSet<InstanceView>(); else tracing_srcs->clear(); tracing_srcs->insert(source, copy_mask); if (tracing_dsts == NULL) tracing_dsts = new FieldMaskSet<InstanceView>(); else tracing_dsts->clear(); // Handle the across case properly here if (update->across_helper != NULL) { const FieldMask dst_mask = update->across_helper->convert_src_to_dst(copy_mask); tracing_dsts->insert(target, dst_mask); } else tracing_dsts->insert(target, copy_mask); } const ApEvent result = target_manager->copy_from( source->get_manager(), precondition, predicate_guard, update->redop, copy_expr, copy_mask, trace_info, cit->second[0]->across_helper, tracing_srcs, tracing_dsts); if (result.exists()) { const RtEvent collect_event = trace_info.get_collect_event(); source->add_copy_user(true/*reading*/, result, collect_event, copy_mask, copy_expr, op_id,src_index, effects, trace_info.recording, local_space); if (update->across_helper != NULL) { const FieldMask dst_mask = update->across_helper->convert_src_to_dst(copy_mask); target->add_copy_user(false/*reading*/, result, collect_event, dst_mask, copy_expr, op_id, dst_index, effects, trace_info.recording, local_space); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, dst_mask, copy_expr); } else { target->add_copy_user(false/*reading*/, result, collect_event, copy_mask, copy_expr, op_id,dst_index, effects, trace_info.recording, local_space); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, copy_mask, copy_expr); } if (track_events) events.insert(result); } } else { // Have to group by source instances in order to merge together // different index space expressions for the same copy std::map<InstanceView*,std::set<IndexSpaceExpression*> > src_exprs; const ReductionOpID redop = cit->second[0]->redop; for (std::vector<CopyUpdate*>::const_iterator it = cit->second.begin(); it != cit->second.end(); it++) { #ifdef DEBUG_LEGION // Should cover all the fields assert(!(copy_mask - (*it)->src_mask)); // Should have the same redop assert(redop == (*it)->redop); // Should also have the same across helper as the first one assert(cit->second[0]->across_helper == (*it)->across_helper); #endif src_exprs[(*it)->source].insert((*it)->expr); } const FieldMask dst_mask = (cit->second[0]->across_helper == NULL) ? copy_mask : cit->second[0]->across_helper->convert_src_to_dst(copy_mask); // If we're tracing we can get the destination now if (trace_info.recording) { if (tracing_dsts == NULL) tracing_dsts = new FieldMaskSet<InstanceView>(); else tracing_dsts->clear(); tracing_dsts->insert(target, dst_mask); } for (std::map<InstanceView*,std::set<IndexSpaceExpression*> >:: const_iterator it = src_exprs.begin(); it != src_exprs.end(); it++) { IndexSpaceExpression *copy_expr = (it->second.size() == 1) ? *(it->second.begin()) : forest->union_index_spaces(it->second); // If we're tracing then get the source information if (trace_info.recording) { if (tracing_srcs == NULL) tracing_srcs = new FieldMaskSet<InstanceView>(); else tracing_srcs->clear(); tracing_srcs->insert(it->first, copy_mask); } const ApEvent result = target_manager->copy_from( it->first->get_manager(), precondition, predicate_guard, redop, copy_expr, copy_mask, trace_info, cit->second[0]->across_helper, tracing_srcs, tracing_dsts); const RtEvent collect_event = trace_info.get_collect_event(); if (result.exists()) { it->first->add_copy_user(true/*reading*/, result, collect_event, copy_mask, copy_expr, op_id,src_index, effects, trace_info.recording, local_space); target->add_copy_user(false/*reading*/, result, collect_event, dst_mask, copy_expr, op_id, dst_index, effects, trace_info.recording, local_space); if (track_events) events.insert(result); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, dst_mask, copy_expr); } } } } } //-------------------------------------------------------------------------- /*static*/ void CopyFillAggregator::handle_aggregation(const void *args) //-------------------------------------------------------------------------- { const CopyFillAggregation *cfargs = (const CopyFillAggregation*)args; cfargs->aggregator->issue_updates(*cfargs, cfargs->pre, cfargs->has_src, cfargs->has_dst, false/*needs deferral*/, cfargs->pass, cfargs->need_pass_preconditions); cfargs->remove_recorder_reference(); } ///////////////////////////////////////////////////////////// // Physical Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- PhysicalAnalysis::PhysicalAnalysis(Runtime *rt, Operation *o, unsigned idx, const VersionInfo &info, bool h) : previous(rt->address_space), original_source(rt->address_space), runtime(rt), op(o), index(idx), version_manager(info.get_manager()), owns_op(false), on_heap(h), remote_instances(NULL), restricted(false), parallel_traversals(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalAnalysis::PhysicalAnalysis(Runtime *rt, AddressSpaceID source, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, bool h) : previous(prev), original_source(source), runtime(rt), op(o), index(idx), version_manager(man), owns_op(true), on_heap(h), remote_instances(NULL), restricted(false), parallel_traversals(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalAnalysis::PhysicalAnalysis(const PhysicalAnalysis &rhs) : previous(0), original_source(0), runtime(NULL), op(NULL), index(0), version_manager(NULL), owns_op(false), on_heap(false) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- PhysicalAnalysis::~PhysicalAnalysis(void) //-------------------------------------------------------------------------- { if (remote_instances != NULL) delete remote_instances; if (owns_op && (op != NULL)) delete op; } //-------------------------------------------------------------------------- void PhysicalAnalysis::traverse(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, const bool cached_set, RtEvent precondition/*= NO_EVENT*/, const bool already_deferred /* = false*/) //-------------------------------------------------------------------------- { if (precondition.exists() && !precondition.has_triggered()) { // This has to be the first time through and isn't really // a deferral of an the traversal since we haven't even // started the traversal yet defer_traversal(precondition, set, mask, deferral_events,applied_events, cached_set, RtUserEvent::NO_RT_USER_EVENT, already_deferred); } else { if (cached_set) { FieldMask stale_mask; perform_traversal(set, mask, deferral_events, applied_events, &stale_mask, cached_set, already_deferred); if (!!stale_mask) stale_sets.insert(set, stale_mask); } else perform_traversal(set, mask, deferral_events, applied_events, NULL/*remove*/, cached_set, already_deferred); } } //-------------------------------------------------------------------------- void PhysicalAnalysis::defer_traversal(RtEvent precondition, EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, const bool cached_set, RtUserEvent deferral_event, const bool already_deferred) //-------------------------------------------------------------------------- { // Make sure that we record that this has parallel traversals const DeferPerformTraversalArgs args(this, set, mask, deferral_event, cached_set, already_deferred); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, precondition); deferral_events.insert(args.done_event); applied_events.insert(args.applied_event); } //-------------------------------------------------------------------------- void PhysicalAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { // only called by derived classes assert(false); } //-------------------------------------------------------------------------- RtEvent PhysicalAnalysis::perform_remote(RtEvent precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { // only called by derived classes assert(false); return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- RtEvent PhysicalAnalysis::perform_updates(RtEvent precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { // only called by derived classes assert(false); return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- ApEvent PhysicalAnalysis::perform_output(RtEvent precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { // only called by derived classes assert(false); return ApEvent::NO_AP_EVENT; } //-------------------------------------------------------------------------- void PhysicalAnalysis::process_remote_instances(Deserializer &derez, std::set<RtEvent> &ready_events) //-------------------------------------------------------------------------- { size_t num_views; derez.deserialize(num_views); AutoLock a_lock(*this); if (remote_instances == NULL) remote_instances = new FieldMaskSet<InstanceView>(); for (unsigned idx = 0; idx < num_views; idx++) { DistributedID view_did; derez.deserialize(view_did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(view_did, ready); if (ready.exists()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); remote_instances->insert(static_cast<InstanceView*>(view), mask); } bool remote_restrict; derez.deserialize(remote_restrict); if (remote_restrict) restricted = true; } //-------------------------------------------------------------------------- void PhysicalAnalysis::process_local_instances( const FieldMaskSet<InstanceView> &views, const bool local_restricted) //-------------------------------------------------------------------------- { AutoLock a_lock(*this); if (remote_instances == NULL) remote_instances = new FieldMaskSet<InstanceView>(); for (FieldMaskSet<InstanceView>::const_iterator it = views.begin(); it != views.end(); it++) if (it->first->is_instance_view()) remote_instances->insert(it->first, it->second); if (local_restricted) restricted = true; } //-------------------------------------------------------------------------- void PhysicalAnalysis::filter_remote_expressions( FieldMaskSet<IndexSpaceExpression> &exprs) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!remote_sets.empty()); #endif FieldMaskSet<IndexSpaceExpression> remote_exprs; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) remote_exprs.insert(it->first->set_expr, it->second); FieldMaskSet<IndexSpaceExpression> to_add; std::vector<IndexSpaceExpression*> to_remove; if (remote_exprs.size() > 1) { LegionList<FieldSet<IndexSpaceExpression*> >::aligned field_sets; remote_exprs.compute_field_sets(FieldMask(), field_sets); for (LegionList<FieldSet<IndexSpaceExpression*> >::aligned:: const_iterator fit = field_sets.begin(); fit != field_sets.end(); fit++) { IndexSpaceExpression *remote_expr = (fit->elements.size() == 1) ? *(fit->elements.begin()) : runtime->forest->union_index_spaces(fit->elements); for (FieldMaskSet<IndexSpaceExpression>::iterator it = exprs.begin(); it != exprs.end(); it++) { const FieldMask overlap = it->second & fit->set_mask; if (!overlap) continue; IndexSpaceExpression *diff = runtime->forest->subtract_index_spaces(it->first, remote_expr); if (!diff->is_empty()) to_add.insert(diff, overlap); it.filter(overlap); if (!it->second) to_remove.push_back(it->first); } } } else { FieldMaskSet<IndexSpaceExpression>::const_iterator first = remote_exprs.begin(); for (FieldMaskSet<IndexSpaceExpression>::iterator it = exprs.begin(); it != exprs.end(); it++) { const FieldMask overlap = it->second & first->second; if (!overlap) continue; IndexSpaceExpression *diff = runtime->forest->subtract_index_spaces(it->first, first->first); if (!diff->is_empty()) to_add.insert(diff, overlap); it.filter(overlap); if (!it->second) to_remove.push_back(it->first); } } if (!to_remove.empty()) { for (std::vector<IndexSpaceExpression*>::const_iterator it = to_remove.begin(); it != to_remove.end(); it++) exprs.erase(*it); } if (!to_add.empty()) { for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = to_add.begin(); it != to_add.end(); it++) exprs.insert(it->first, it->second); } } //-------------------------------------------------------------------------- bool PhysicalAnalysis::report_instances(FieldMaskSet<InstanceView> &insts) //-------------------------------------------------------------------------- { // No need for the lock since we shouldn't be mutating anything at // this point anyway if (remote_instances != NULL) remote_instances->swap(insts); return restricted; } //-------------------------------------------------------------------------- bool PhysicalAnalysis::update_alt_sets(EquivalenceSet *set, FieldMask &mask) //-------------------------------------------------------------------------- { if (parallel_traversals) { // Need the lock in this case AutoLock a_lock(*this); FieldMaskSet<EquivalenceSet>::iterator finder = alt_sets.find(set); // Remove any fields we already traversed if (finder != alt_sets.end()) { mask -= finder->second; // If we already traversed it then we don't need to do it again if (!mask) return true; // early out finder.merge(mask); } else alt_sets.insert(set, mask); } else { // No parallel traversals means we're the only thread FieldMaskSet<EquivalenceSet>::iterator finder = alt_sets.find(set); // Remove any fields we already traversed if (finder != alt_sets.end()) { mask -= finder->second; // If we already traversed it then we don't need to do it again if (!mask) return true; // early out finder.merge(mask); } else alt_sets.insert(set, mask); } return false; } //-------------------------------------------------------------------------- void PhysicalAnalysis::filter_alt_sets(EquivalenceSet *set, const FieldMask &mask) //-------------------------------------------------------------------------- { if (parallel_traversals) { // Need the lock if there are parallel traversals AutoLock a_lock(*this); FieldMaskSet<EquivalenceSet>::iterator finder = alt_sets.find(set); if (finder != alt_sets.end()) { finder.filter(mask); if (!finder->second) alt_sets.erase(finder); } } else { // No parallel traversals means no lock needed FieldMaskSet<EquivalenceSet>::iterator finder = alt_sets.find(set); if (finder != alt_sets.end()) { finder.filter(mask); if (!finder->second) alt_sets.erase(finder); } } } //-------------------------------------------------------------------------- void PhysicalAnalysis::record_stale_set(EquivalenceSet *set, const FieldMask &mask) //-------------------------------------------------------------------------- { if (parallel_traversals) { // Lock needed if we're doing parallel traversals AutoLock a_lock(*this); stale_sets.insert(set, mask); } else // No lock needed if we're the only one stale_sets.insert(set, mask); } //-------------------------------------------------------------------------- void PhysicalAnalysis::record_remote(EquivalenceSet *set, const FieldMask &mask, const AddressSpaceID owner, const bool cached_set) //-------------------------------------------------------------------------- { const std::pair<AddressSpaceID,bool> key(owner, cached_set); if (parallel_traversals) { AutoLock a_lock(*this); remote_sets[key].insert(set, mask); } else // No lock needed if we're the only one remote_sets[key].insert(set, mask); } //-------------------------------------------------------------------------- void PhysicalAnalysis::update_stale_equivalence_sets( std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { // No need for the lock here since we know there are no // races because there are no more traversals being performed #ifdef DEBUG_LEGION assert(!stale_sets.empty()); #endif // Check to see if we are on the local node for the version manager // or whether we need to send a message to record the stale sets if (original_source != runtime->address_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize<size_t>(stale_sets.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = stale_sets.begin(); it != stale_sets.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize(version_manager); rez.serialize(applied); } runtime->send_equivalence_set_stale_update(original_source, rez); applied_events.insert(applied); } else // the local node case { const RtEvent done = version_manager->record_stale_sets(stale_sets); if (done.exists()) applied_events.insert(done); } } //-------------------------------------------------------------------------- void PhysicalAnalysis::record_instance(InstanceView *view, const FieldMask &mask) //-------------------------------------------------------------------------- { // Lock held from caller if (remote_instances == NULL) remote_instances = new FieldMaskSet<InstanceView>(); remote_instances->insert(view, mask); } //-------------------------------------------------------------------------- /*static*/ void PhysicalAnalysis::handle_remote_instances( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); PhysicalAnalysis *target; derez.deserialize(target); RtUserEvent done_event; derez.deserialize(done_event); std::set<RtEvent> ready_events; target->process_remote_instances(derez, ready_events); if (!ready_events.empty()) Runtime::trigger_event(done_event, Runtime::merge_events(ready_events)); else Runtime::trigger_event(done_event); } //-------------------------------------------------------------------------- PhysicalAnalysis::DeferPerformTraversalArgs::DeferPerformTraversalArgs( PhysicalAnalysis *ana, EquivalenceSet *s, const FieldMask &m, RtUserEvent done, bool cached, bool def) : LgTaskArgs<DeferPerformTraversalArgs>(ana->op->get_unique_op_id()), analysis(ana), set(s), mask(new FieldMask(m)), applied_event(Runtime::create_rt_user_event()), done_event(done.exists() ? done : Runtime::create_rt_user_event()), cached_set(cached), already_deferred(def) //-------------------------------------------------------------------------- { analysis->record_parallel_traversals(); if (analysis->on_heap) analysis->add_reference(); } //-------------------------------------------------------------------------- /*static*/void PhysicalAnalysis::handle_deferred_traversal(const void *args) //-------------------------------------------------------------------------- { const DeferPerformTraversalArgs *dargs = (const DeferPerformTraversalArgs*)args; // Get this before doing anything const bool on_heap = dargs->analysis->on_heap; std::set<RtEvent> deferral_events, applied_events; dargs->analysis->traverse(dargs->set, *(dargs->mask), deferral_events, applied_events, dargs->cached_set, RtEvent::NO_RT_EVENT, dargs->already_deferred); if (!deferral_events.empty()) Runtime::trigger_event(dargs->done_event, Runtime::merge_events(deferral_events)); else Runtime::trigger_event(dargs->done_event); if (!applied_events.empty()) Runtime::trigger_event(dargs->applied_event, Runtime::merge_events(applied_events)); else Runtime::trigger_event(dargs->applied_event); if (on_heap && dargs->analysis->remove_reference()) delete dargs->analysis; delete dargs->mask; } //-------------------------------------------------------------------------- PhysicalAnalysis::DeferPerformRemoteArgs::DeferPerformRemoteArgs( PhysicalAnalysis *ana) : LgTaskArgs<DeferPerformRemoteArgs>(ana->op->get_unique_op_id()), analysis(ana), applied_event(Runtime::create_rt_user_event()), done_event(Runtime::create_rt_user_event()) //-------------------------------------------------------------------------- { if (analysis->on_heap) analysis->add_reference(); } //-------------------------------------------------------------------------- /*static*/ void PhysicalAnalysis::handle_deferred_remote(const void *args) //-------------------------------------------------------------------------- { const DeferPerformRemoteArgs *dargs = (const DeferPerformRemoteArgs*)args; std::set<RtEvent> applied_events; // Get this before doing anything const bool on_heap = dargs->analysis->on_heap; const RtEvent done = dargs->analysis->perform_remote(RtEvent::NO_RT_EVENT, applied_events, true/*already deferred*/); Runtime::trigger_event(dargs->done_event, done); if (!applied_events.empty()) Runtime::trigger_event(dargs->applied_event, Runtime::merge_events(applied_events)); else Runtime::trigger_event(dargs->applied_event); if (on_heap && dargs->analysis->remove_reference()) delete dargs->analysis; } //-------------------------------------------------------------------------- PhysicalAnalysis::DeferPerformUpdateArgs::DeferPerformUpdateArgs( PhysicalAnalysis *ana) : LgTaskArgs<DeferPerformUpdateArgs>(ana->op->get_unique_op_id()), analysis(ana), applied_event(Runtime::create_rt_user_event()), done_event(Runtime::create_rt_user_event()) //-------------------------------------------------------------------------- { if (analysis->on_heap) analysis->add_reference(); } //-------------------------------------------------------------------------- /*static*/ void PhysicalAnalysis::handle_deferred_update(const void *args) //-------------------------------------------------------------------------- { const DeferPerformUpdateArgs *dargs = (const DeferPerformUpdateArgs*)args; std::set<RtEvent> applied_events; // Get this before doing anything const bool on_heap = dargs->analysis->on_heap; const RtEvent done =dargs->analysis->perform_updates(RtEvent::NO_RT_EVENT, applied_events, true/*already deferred*/); Runtime::trigger_event(dargs->done_event, done); if (!applied_events.empty()) Runtime::trigger_event(dargs->applied_event, Runtime::merge_events(applied_events)); else Runtime::trigger_event(dargs->applied_event); if (on_heap && dargs->analysis->remove_reference()) delete dargs->analysis; } //-------------------------------------------------------------------------- PhysicalAnalysis::DeferPerformOutputArgs::DeferPerformOutputArgs( PhysicalAnalysis *ana) : LgTaskArgs<DeferPerformOutputArgs>(ana->op->get_unique_op_id()), analysis(ana), applied_event(Runtime::create_rt_user_event()), effects_event(Runtime::create_ap_user_event()) //-------------------------------------------------------------------------- { if (analysis->on_heap) analysis->add_reference(); } //-------------------------------------------------------------------------- /*static*/ void PhysicalAnalysis::handle_deferred_output(const void *args) //-------------------------------------------------------------------------- { const DeferPerformOutputArgs *dargs = (const DeferPerformOutputArgs*)args; std::set<RtEvent> applied_events; const bool on_heap = dargs->analysis->on_heap; const ApEvent effects = dargs->analysis->perform_output( RtEvent::NO_RT_EVENT, applied_events, true/*already deferred*/); // Get this before doing anything Runtime::trigger_event(dargs->effects_event, effects); if (!applied_events.empty()) Runtime::trigger_event(dargs->applied_event, Runtime::merge_events(applied_events)); else Runtime::trigger_event(dargs->applied_event); if (on_heap && dargs->analysis->remove_reference()) delete dargs->analysis; } ///////////////////////////////////////////////////////////// // Valid Inst Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- ValidInstAnalysis::ValidInstAnalysis(Runtime *rt, Operation *o,unsigned idx, const VersionInfo &info, ReductionOpID red) : PhysicalAnalysis(rt, o, idx, info, false/*on heap*/), redop(red), target_analysis(this) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ValidInstAnalysis::ValidInstAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, ValidInstAnalysis *t, ReductionOpID red) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), redop(red), target_analysis(t) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ValidInstAnalysis::ValidInstAnalysis(const ValidInstAnalysis &rhs) : PhysicalAnalysis(rhs), redop(0), target_analysis(NULL) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- ValidInstAnalysis::~ValidInstAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ValidInstAnalysis& ValidInstAnalysis::operator=(const ValidInstAnalysis &rs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void ValidInstAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->find_valid_instances(*this, mask, deferral_events, applied_events, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent ValidInstAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Easy out if we don't have remote sets if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; std::set<RtEvent> ready_events; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent ready = Runtime::create_rt_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize(redop); rez.serialize(target_analysis); rez.serialize(ready); rez.serialize(applied); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_request_instances(target, rez); ready_events.insert(ready); applied_events.insert(applied); } return Runtime::merge_events(ready_events); } //-------------------------------------------------------------------------- RtEvent ValidInstAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (remote_instances != NULL) { if (original_source != runtime->address_space) { const RtUserEvent response_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(target_analysis); rez.serialize(response_event); rez.serialize<size_t>(remote_instances->size()); for (FieldMaskSet<InstanceView>::const_iterator it = remote_instances->begin(); it != remote_instances->end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<bool>(restricted); } runtime->send_equivalence_set_remote_instances(original_source, rez); return response_event; } else target_analysis->process_local_instances(*remote_instances, restricted); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- /*static*/ void ValidInstAnalysis::handle_remote_request_instances( Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); ReductionOpID redop; derez.deserialize(redop); ValidInstAnalysis *target; derez.deserialize(target); RtUserEvent ready; derez.deserialize(ready); RtUserEvent applied; derez.deserialize(applied); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); ValidInstAnalysis *analysis = new ValidInstAnalysis(runtime, original_source, previous, op, index, version_manager, target, redop); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Wait for the equivalence sets to be ready if necessary RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); if (traversal_done.exists() || analysis->has_remote_sets()) { const RtEvent remote_ready = analysis->perform_remote(traversal_done, applied_events); if (remote_ready.exists()) ready_events.insert(remote_ready); } // Defer sending the updates until we're ready const RtEvent local_ready = analysis->perform_updates(traversal_done, applied_events); if (local_ready.exists()) ready_events.insert(local_ready); if (!ready_events.empty()) Runtime::trigger_event(ready, Runtime::merge_events(ready_events)); else Runtime::trigger_event(ready); if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Invalid Inst Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- InvalidInstAnalysis::InvalidInstAnalysis(Runtime *rt, Operation *o, unsigned idx, const VersionInfo &info, const FieldMaskSet<InstanceView> &valid_insts) : PhysicalAnalysis(rt, o, idx, info, false/*on heap*/), valid_instances(valid_insts), target_analysis(this) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InvalidInstAnalysis::InvalidInstAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, InvalidInstAnalysis *t, const FieldMaskSet<InstanceView> &valid_insts) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), valid_instances(valid_insts), target_analysis(t) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InvalidInstAnalysis::InvalidInstAnalysis(const InvalidInstAnalysis &rhs) : PhysicalAnalysis(rhs), valid_instances(rhs.valid_instances), target_analysis(NULL) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- InvalidInstAnalysis::~InvalidInstAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InvalidInstAnalysis& InvalidInstAnalysis::operator=( const InvalidInstAnalysis &rs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void InvalidInstAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->find_invalid_instances(*this, mask, deferral_events, applied_events, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent InvalidInstAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Easy out if we don't have remote sets if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; std::set<RtEvent> ready_events; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent ready = Runtime::create_rt_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize<size_t>(valid_instances.size()); for (FieldMaskSet<InstanceView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize(target_analysis); rez.serialize(ready); rez.serialize(applied); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_request_invalid(target, rez); ready_events.insert(ready); applied_events.insert(applied); } return Runtime::merge_events(ready_events); } //-------------------------------------------------------------------------- RtEvent InvalidInstAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (remote_instances != NULL) { if (original_source != runtime->address_space) { const RtUserEvent response_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(target_analysis); rez.serialize(response_event); rez.serialize<size_t>(remote_instances->size()); for (FieldMaskSet<InstanceView>::const_iterator it = remote_instances->begin(); it != remote_instances->end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<bool>(restricted); } runtime->send_equivalence_set_remote_instances(original_source, rez); return response_event; } else target_analysis->process_local_instances(*remote_instances, restricted); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- /*static*/ void InvalidInstAnalysis::handle_remote_request_invalid( Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); FieldMaskSet<InstanceView> valid_instances; size_t num_valid_instances; derez.deserialize<size_t>(num_valid_instances); for (unsigned idx = 0; idx < num_valid_instances; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; InstanceView *view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(did, ready)); if (ready.exists()) ready_events.insert(ready); FieldMask view_mask; derez.deserialize(view_mask); valid_instances.insert(view, view_mask); } InvalidInstAnalysis *target; derez.deserialize(target); RtUserEvent ready; derez.deserialize(ready); RtUserEvent applied; derez.deserialize(applied); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); InvalidInstAnalysis *analysis = new InvalidInstAnalysis(runtime, original_source, previous, op, index, version_manager, target, valid_instances); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Wait for the equivalence sets to be ready if necessary RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); if (traversal_done.exists() || analysis->has_remote_sets()) { const RtEvent remote_ready = analysis->perform_remote(traversal_done, applied_events); if (remote_ready.exists()) ready_events.insert(remote_ready); } // Defer sending the updates until we're ready const RtEvent local_ready = analysis->perform_updates(traversal_done, applied_events); if (local_ready.exists()) ready_events.insert(local_ready); if (!ready_events.empty()) Runtime::trigger_event(ready, Runtime::merge_events(ready_events)); else Runtime::trigger_event(ready); if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Update Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- UpdateAnalysis::UpdateAnalysis(Runtime *rt, Operation *o, unsigned idx, const VersionInfo &info, const RegionRequirement &req, RegionNode *rn, const InstanceSet &target_insts, std::vector<InstanceView*> &target_vws, const PhysicalTraceInfo &t_info, const ApEvent pre, const ApEvent term, const bool track, const bool check, const bool record) : PhysicalAnalysis(rt, o, idx, info, true/*on heap*/), usage(req), node(rn), target_instances(target_insts), target_views(target_vws), trace_info(t_info), precondition(pre), term_event(term), track_effects(track), check_initialized(check && !IS_DISCARD(usage) && !IS_SIMULT(usage)), record_valid(record), output_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- UpdateAnalysis::UpdateAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, const RegionUsage &use, RegionNode *rn, InstanceSet &target_insts, std::vector<InstanceView*> &target_vws, const PhysicalTraceInfo &info, const RtEvent user_reg, const ApEvent pre, const ApEvent term, const bool track, const bool check, const bool record) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), usage(use), node(rn), target_instances(target_insts), target_views(target_vws), trace_info(info), precondition(pre), term_event(term), track_effects(track), check_initialized(check), record_valid(record), output_aggregator(NULL), remote_user_registered(user_reg) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- UpdateAnalysis::UpdateAnalysis(const UpdateAnalysis &rhs) : PhysicalAnalysis(rhs), usage(rhs.usage), node(rhs.node), target_instances(rhs.target_instances), target_views(rhs.target_views), trace_info(rhs.trace_info), precondition(rhs.precondition), term_event(rhs.term_event), track_effects(rhs.track_effects), check_initialized(rhs.check_initialized), record_valid(rhs.record_valid) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- UpdateAnalysis::~UpdateAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- UpdateAnalysis& UpdateAnalysis::operator=(const UpdateAnalysis &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- void UpdateAnalysis::record_uninitialized(const FieldMask &uninit, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { if (!uninitialized) { #ifdef DEBUG_LEGION assert(!uninitialized_reported.exists()); #endif uninitialized_reported = Runtime::create_rt_user_event(); applied_events.insert(uninitialized_reported); } uninitialized |= uninit; } //-------------------------------------------------------------------------- void UpdateAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->update_set(*this, mask, deferral_events, applied_events, stale_mask, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent UpdateAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Easy out if we don't have any remote sets if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; #ifdef DEBUG_LEGION assert(!target_instances.empty()); assert(target_instances.size() == target_views.size()); #endif if (!remote_user_registered.exists()) { #ifdef DEBUG_LEGION assert(original_source == runtime->address_space); assert(!user_registered.exists()); #endif user_registered = Runtime::create_rt_user_event(); remote_user_registered = user_registered; } std::set<RtEvent> remote_events; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent updated = Runtime::create_rt_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); const ApUserEvent effects = track_effects ? Runtime::create_ap_user_event() : ApUserEvent::NO_AP_USER_EVENT; Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize(node->handle); rez.serialize(usage); rez.serialize<size_t>(target_instances.size()); for (unsigned idx = 0; idx < target_instances.size(); idx++) { const InstanceRef &ref = target_instances[idx]; rez.serialize(ref.get_manager()->did); rez.serialize(target_views[idx]->did); rez.serialize(ref.get_valid_fields()); } trace_info.pack_trace_info<false>(rez, applied_events, target); rez.serialize(precondition); rez.serialize(term_event); rez.serialize(updated); rez.serialize(remote_user_registered); rez.serialize(applied); rez.serialize(effects); rez.serialize(version_manager); rez.serialize<bool>(check_initialized); rez.serialize<bool>(record_valid); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_updates(target, rez); remote_events.insert(updated); applied_events.insert(applied); if (track_effects) effects_events.insert(effects); } return Runtime::merge_events(remote_events); } //-------------------------------------------------------------------------- RtEvent UpdateAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Report any uninitialized data now that we know the traversal is done if (!!uninitialized) { #ifdef DEBUG_LEGION assert(check_initialized); assert(uninitialized_reported.exists()); #endif node->report_uninitialized_usage(op, index, usage, uninitialized, uninitialized_reported); } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (!input_aggregators.empty()) { const bool needs_deferral = !already_deferred || (input_aggregators.size() > 1); for (std::map<RtEvent,CopyFillAggregator*>::const_iterator it = input_aggregators.begin(); it != input_aggregators.end(); it++) { it->second->issue_updates(trace_info, precondition, false/*has src*/, false/*has dst*/, needs_deferral); #ifdef NON_AGGRESSIVE_AGGREGATORS if (!it->second->effects_applied.has_triggered()) guard_events.insert(it->second->effects_applied); #else if (!it->second->guard_postcondition.has_triggered()) guard_events.insert(it->second->guard_postcondition); #endif if (it->second->release_guards(op->runtime, applied_events)) delete it->second; } } if (!guard_events.empty()) return Runtime::merge_events(guard_events); else return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- ApEvent UpdateAnalysis::perform_output(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformOutputArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.effects_event; } ApEvent result; if (output_aggregator != NULL) { output_aggregator->issue_updates(trace_info, term_event); // We need to wait for the aggregator updates to be applied // here before we can summarize the output #ifdef NON_AGGRESSIVE_AGGREGATORS if (!output_aggregator->effects_applied.has_triggered()) output_aggregator->effects_applied.wait(); #else if (!output_aggregator->guard_postcondition.has_triggered()) output_aggregator->guard_postcondition.wait(); #endif result = output_aggregator->summarize(trace_info); if (output_aggregator->release_guards(op->runtime, applied_events)) delete output_aggregator; } return result; } //-------------------------------------------------------------------------- /*static*/ void UpdateAnalysis::handle_remote_updates(Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); FieldMask user_mask; for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); user_mask |= eq_masks[idx]; } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); LogicalRegion handle; derez.deserialize(handle); RegionUsage usage; derez.deserialize(usage); size_t num_targets; derez.deserialize(num_targets); InstanceSet targets(num_targets); std::vector<InstanceView*> target_views(num_targets, NULL); for (unsigned idx = 0; idx < num_targets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; PhysicalManager *manager = runtime->find_or_request_physical_manager(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(did); LogicalView *view = runtime->find_or_request_logical_view(did, ready); target_views[idx] = static_cast<InstanceView*>(view); if (ready.exists()) ready_events.insert(ready); FieldMask valid_fields; derez.deserialize(valid_fields); targets[idx] = InstanceRef(manager, valid_fields); } PhysicalTraceInfo trace_info = PhysicalTraceInfo::unpack_trace_info(derez, runtime, op); ApEvent precondition; derez.deserialize(precondition); ApEvent term_event; derez.deserialize(term_event); RtUserEvent updated; derez.deserialize(updated); RtEvent remote_user_registered; derez.deserialize(remote_user_registered); RtUserEvent applied; derez.deserialize(applied); ApUserEvent effects_done; derez.deserialize(effects_done); const bool track_effects = effects_done.exists(); VersionManager *version_manager; derez.deserialize(version_manager); bool check_initialized; derez.deserialize(check_initialized); bool record_valid; derez.deserialize(record_valid); bool cached_sets; derez.deserialize(cached_sets); RegionNode *node = runtime->forest->get_node(handle); // This takes ownership of the remote operation UpdateAnalysis *analysis = new UpdateAnalysis(runtime, original_source, previous, op, index, version_manager, usage, node, targets, target_views, trace_info, remote_user_registered, precondition, term_event, track_effects, check_initialized, record_valid); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Make sure that all our pointers are ready RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); std::set<RtEvent> update_events; // If we have remote messages to send do that now if (traversal_done.exists() || analysis->has_remote_sets()) { const RtEvent remote_ready = analysis->perform_remote(traversal_done, applied_events); if (remote_ready.exists()) update_events.insert(remote_ready); } // Then perform the updates // Note that we need to capture all the effects of these updates // before we can consider them applied, so we can't use the // applied_events data structure here const RtEvent updates_ready = analysis->perform_updates(traversal_done, update_events); if (updates_ready.exists()) update_events.insert(updates_ready); // We can trigger our updated event done when all the guards are done if (!update_events.empty()) Runtime::trigger_event(updated, Runtime::merge_events(update_events)); else Runtime::trigger_event(updated); // If we have outputs we need for the user to be registered // before we can apply the output copies const ApEvent result = analysis->perform_output(remote_user_registered, applied_events); if (effects_done.exists()) Runtime::trigger_event(effects_done, result); // Do the rest of the triggers if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Acquire Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- AcquireAnalysis::AcquireAnalysis(Runtime *rt, Operation *o, unsigned idx, const VersionInfo &info) : PhysicalAnalysis(rt, o, idx, info, false/*on heap*/), target_analysis(this) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- AcquireAnalysis::AcquireAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, AcquireAnalysis *t) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), target_analysis(t) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- AcquireAnalysis::AcquireAnalysis(const AcquireAnalysis &rhs) : PhysicalAnalysis(rhs), target_analysis(rhs.target_analysis) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- AcquireAnalysis::~AcquireAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- AcquireAnalysis& AcquireAnalysis::operator=(const AcquireAnalysis &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void AcquireAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->acquire_restrictions(*this, mask, deferral_events, applied_events, stale_mask, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent AcquireAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Easy out if there is nothing to do if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; std::set<RtEvent> remote_events; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent returned = Runtime::create_rt_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize(returned); rez.serialize(applied); rez.serialize(target_analysis); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_acquires(target, rez); applied_events.insert(applied); remote_events.insert(returned); } return Runtime::merge_events(remote_events); } //-------------------------------------------------------------------------- RtEvent AcquireAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (remote_instances != NULL) { if (original_source != runtime->address_space) { const RtUserEvent response_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(target_analysis); rez.serialize(response_event); rez.serialize<size_t>(remote_instances->size()); for (FieldMaskSet<InstanceView>::const_iterator it = remote_instances->begin(); it != remote_instances->end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<bool>(restricted); } runtime->send_equivalence_set_remote_instances(original_source, rez); return response_event; } else target_analysis->process_local_instances(*remote_instances, restricted); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- /*static*/ void AcquireAnalysis::handle_remote_acquires(Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); RtUserEvent returned; derez.deserialize(returned); RtUserEvent applied; derez.deserialize(applied); AcquireAnalysis *target; derez.deserialize(target); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); // This takes ownership of the operation AcquireAnalysis *analysis = new AcquireAnalysis(runtime, original_source, previous, op, index, version_manager, target); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Make sure that all our pointers are ready RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); if (traversal_done.exists() || analysis->has_remote_sets()) { const RtEvent remote_ready = analysis->perform_remote(traversal_done, applied_events); if (remote_ready.exists()) ready_events.insert(remote_ready); } // Defer sending the updates until we're ready const RtEvent local_ready = analysis->perform_updates(traversal_done, applied_events); if (local_ready.exists()) ready_events.insert(local_ready); if (!ready_events.empty()) Runtime::trigger_event(returned, Runtime::merge_events(ready_events)); else Runtime::trigger_event(returned); if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Release Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- ReleaseAnalysis::ReleaseAnalysis(Runtime *rt, Operation *o, unsigned idx, ApEvent pre, const VersionInfo &info, const PhysicalTraceInfo &t_info) : PhysicalAnalysis(rt, o, idx, info, false/*on heap*/), precondition(pre), target_analysis(this), trace_info(t_info), release_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ReleaseAnalysis::ReleaseAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx,VersionManager *man, ApEvent pre, ReleaseAnalysis *t, const PhysicalTraceInfo &info) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), precondition(pre), target_analysis(t), trace_info(info), release_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ReleaseAnalysis::ReleaseAnalysis(const ReleaseAnalysis &rhs) : PhysicalAnalysis(rhs), target_analysis(rhs.target_analysis), trace_info(rhs.trace_info) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- ReleaseAnalysis::~ReleaseAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ReleaseAnalysis& ReleaseAnalysis::operator=(const ReleaseAnalysis &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void ReleaseAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->release_restrictions(*this, mask, deferral_events, applied_events, stale_mask, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent ReleaseAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Easy out if there is nothing to do if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; std::set<RtEvent> remote_events; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent returned = Runtime::create_rt_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize(precondition); rez.serialize(returned); rez.serialize(applied); rez.serialize(target_analysis); trace_info.pack_trace_info<false>(rez, applied_events, target); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_releases(target, rez); applied_events.insert(applied); remote_events.insert(returned); } return Runtime::merge_events(remote_events); } //-------------------------------------------------------------------------- RtEvent ReleaseAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { // Defer this if necessary if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); // See if we have any instance names to send back if ((target_analysis != this) && (remote_instances != NULL)) { if (original_source != runtime->address_space) { const RtUserEvent response_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(target_analysis); rez.serialize(response_event); rez.serialize<size_t>(remote_instances->size()); for (FieldMaskSet<InstanceView>::const_iterator it = remote_instances->begin(); it != remote_instances->end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<bool>(restricted); } runtime->send_equivalence_set_remote_instances(original_source, rez); applied_events.insert(response_event); } else target_analysis->process_local_instances(*remote_instances, restricted); } if (release_aggregator != NULL) { std::set<RtEvent> guard_events; release_aggregator->issue_updates(trace_info, precondition); #ifdef NON_AGGRESSIVE_AGGREGATORS if (release_aggregator->effects_applied.has_triggered()) guard_events.insert(release_aggregator->effects_applied); #else if (!release_aggregator->guard_postcondition.has_triggered()) guard_events.insert(release_aggregator->guard_postcondition); #endif if (release_aggregator->release_guards(op->runtime, applied_events)) delete release_aggregator; if (!guard_events.empty()) return Runtime::merge_events(guard_events); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- /*static*/ void ReleaseAnalysis::handle_remote_releases(Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); ApEvent precondition; derez.deserialize(precondition); RtUserEvent returned; derez.deserialize(returned); RtUserEvent applied; derez.deserialize(applied); ReleaseAnalysis *target; derez.deserialize(target); const PhysicalTraceInfo trace_info = PhysicalTraceInfo::unpack_trace_info(derez, runtime, op); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); ReleaseAnalysis *analysis = new ReleaseAnalysis(runtime, original_source, previous, op, index, version_manager, precondition, target, trace_info); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; RtEvent ready_event; // Make sure that all our pointers are ready if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); if (traversal_done.exists() || analysis->has_remote_sets()) { const RtEvent remote_ready = analysis->perform_remote(traversal_done, applied_events); if (remote_ready.exists()) ready_events.insert(remote_ready); } // Note that we use the ready events here for applied so that // we can know that all our updates are done before we tell // the original source node that we've returned const RtEvent local_ready = analysis->perform_updates(traversal_done, (original_source == runtime->address_space) ? applied_events : ready_events); if (local_ready.exists()) ready_events.insert(local_ready); if (!ready_events.empty()) Runtime::trigger_event(returned, Runtime::merge_events(ready_events)); else Runtime::trigger_event(returned); if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Copy Across Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- CopyAcrossAnalysis::CopyAcrossAnalysis(Runtime *rt, Operation *o, unsigned src_idx, unsigned dst_idx, const VersionInfo &info, const RegionRequirement &src_req, const RegionRequirement &dst_req, const InstanceSet &target_insts, const std::vector<InstanceView*> &target_vws, const ApEvent pre, const PredEvent pred, const ReductionOpID red, const std::vector<unsigned> &src_idxes, const std::vector<unsigned> &dst_idxes, const PhysicalTraceInfo &t_info, const bool perf) : PhysicalAnalysis(rt, o, dst_idx, info, true/*on heap*/), src_mask(perf ? FieldMask() : initialize_mask(src_idxes)), dst_mask(perf ? FieldMask() : initialize_mask(dst_idxes)), src_index(src_idx), dst_index(dst_idx), src_usage(src_req), dst_usage(dst_req), src_region(src_req.region), dst_region(dst_req.region), target_instances(target_insts), target_views(target_vws), precondition(pre),pred_guard(pred),redop(red), src_indexes(src_idxes), dst_indexes(dst_idxes), across_helpers(perf ? std::vector<CopyAcrossHelper*>() : create_across_helpers(src_mask, dst_mask, target_instances, src_indexes, dst_indexes)), trace_info(t_info), perfect(perf), across_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyAcrossAnalysis::CopyAcrossAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned src_idx, unsigned dst_idx, const RegionUsage &src_use, const RegionUsage &dst_use, const LogicalRegion src_reg, const LogicalRegion dst_reg, const InstanceSet &target_insts, const std::vector<InstanceView*> &target_vws, const ApEvent pre, const PredEvent pred, const ReductionOpID red, const std::vector<unsigned> &src_idxes, const std::vector<unsigned> &dst_idxes, const PhysicalTraceInfo &t_info, const bool perf) : PhysicalAnalysis(rt, src, prev, o, dst_idx,NULL/*man*/,true/*on heap*/), src_mask(perf ? FieldMask() : initialize_mask(src_idxes)), dst_mask(perf ? FieldMask() : initialize_mask(dst_idxes)), src_index(src_idx), dst_index(dst_idx), src_usage(src_use), dst_usage(dst_use), src_region(src_reg), dst_region(dst_reg), target_instances(target_insts), target_views(target_vws), precondition(pre),pred_guard(pred),redop(red), src_indexes(src_idxes), dst_indexes(dst_idxes), across_helpers(perf ? std::vector<CopyAcrossHelper*>() : create_across_helpers(src_mask, dst_mask, target_instances, src_indexes, dst_indexes)), trace_info(t_info), perfect(perf), across_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyAcrossAnalysis::CopyAcrossAnalysis(const CopyAcrossAnalysis &rhs) : PhysicalAnalysis(rhs), dst_mask(rhs.dst_mask), src_index(rhs.src_index), dst_index(rhs.dst_index), src_usage(rhs.src_usage), dst_usage(rhs.dst_usage), src_region(rhs.src_region), dst_region(rhs.dst_region), target_instances(rhs.target_instances), target_views(rhs.target_views), precondition(rhs.precondition), pred_guard(rhs.pred_guard), redop(rhs.redop), src_indexes(rhs.src_indexes), dst_indexes(rhs.dst_indexes), across_helpers(rhs.across_helpers), trace_info(rhs.trace_info), perfect(rhs.perfect) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- CopyAcrossAnalysis::~CopyAcrossAnalysis(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!aggregator_guard.exists() || aggregator_guard.has_triggered()); #endif for (std::vector<CopyAcrossHelper*>::const_iterator it = across_helpers.begin(); it != across_helpers.end(); it++) delete (*it); } //-------------------------------------------------------------------------- CopyAcrossAnalysis& CopyAcrossAnalysis::operator=( const CopyAcrossAnalysis &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void CopyAcrossAnalysis::record_uninitialized(const FieldMask &uninit, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { if (!uninitialized) { #ifdef DEBUG_LEGION assert(!uninitialized_reported.exists()); #endif uninitialized_reported = Runtime::create_rt_user_event(); applied_events.insert(uninitialized_reported); } uninitialized |= uninit; } //-------------------------------------------------------------------------- CopyFillAggregator* CopyAcrossAnalysis::get_across_aggregator(void) //-------------------------------------------------------------------------- { if (across_aggregator == NULL) { #ifdef DEBUG_LEGION assert(!aggregator_guard.exists()); #endif aggregator_guard = Runtime::create_rt_user_event(); across_aggregator = new CopyFillAggregator(runtime->forest, op, src_index, dst_index, aggregator_guard, true/*track*/, pred_guard); } return across_aggregator; } //-------------------------------------------------------------------------- RtEvent CopyAcrossAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; #ifdef DEBUG_LEGION assert(target_instances.size() == target_views.size()); assert(src_indexes.size() == dst_indexes.size()); #endif for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->first.second); // should not be a cached set here assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const ApUserEvent copy = Runtime::create_ap_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(src_index); rez.serialize(dst_index); rez.serialize(src_usage); rez.serialize(dst_usage); rez.serialize<size_t>(target_instances.size()); for (unsigned idx = 0; idx < target_instances.size(); idx++) { target_instances[idx].pack_reference(rez); rez.serialize(target_views[idx]->did); } rez.serialize(src_region); rez.serialize(dst_region); rez.serialize(pred_guard); rez.serialize(precondition); rez.serialize(redop); rez.serialize<bool>(perfect); if (!perfect) { rez.serialize<size_t>(src_indexes.size()); for (unsigned idx = 0; idx < src_indexes.size(); idx++) { rez.serialize(src_indexes[idx]); rez.serialize(dst_indexes[idx]); } } rez.serialize(applied); rez.serialize(copy); trace_info.pack_trace_info<false>(rez, applied_events, target); } runtime->send_equivalence_set_remote_copies_across(target, rez); applied_events.insert(applied); copy_events.insert(copy); } // Filter all the remote expressions from the local ones here filter_remote_expressions(local_exprs); return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- RtEvent CopyAcrossAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Report any uninitialized data now that we know the traversal is done if (!!uninitialized) { #ifdef DEBUG_LEGION assert(uninitialized_reported.exists()); #endif RegionNode *src_node = runtime->forest->get_node(src_region); src_node->report_uninitialized_usage(op, src_index, src_usage, uninitialized, uninitialized_reported); } #ifdef DEBUG_LEGION // CopyAcrossAnalysis should have no alt-set tracking because // individual equivalence sets may need to be traversed multiple times assert(alt_sets.empty()); assert(stale_sets.empty()); #endif if (across_aggregator != NULL) { #ifdef DEBUG_LEGION assert(aggregator_guard.exists()); #endif // Trigger the guard event for the aggregator once all the // actual guard events are done. Note that this is safe for // copy across aggregators because unlike other aggregators // they are moving data from one field to another so it is // safe to create entanglements between fields since they are // all going to be subsumed by the same completion event for // the copy-across operation anyway if (!guard_events.empty()) Runtime::trigger_event(aggregator_guard, Runtime::merge_events(guard_events)); else Runtime::trigger_event(aggregator_guard); // Record the event field preconditions for each view // Use the destination expr since we know we we're only actually // issuing copies for that particular expression if (local_exprs.size() > 1) { LegionList<FieldSet<IndexSpaceExpression*> >::aligned field_sets; local_exprs.compute_field_sets(FieldMask(), field_sets); for (LegionList<FieldSet<IndexSpaceExpression*> >::aligned:: const_iterator it = field_sets.begin(); it != field_sets.end(); it++) { IndexSpaceExpression *expr = (it->elements.size() == 1) ? *(it->elements.begin()) : runtime->forest->union_index_spaces(it->elements); if (expr->is_empty()) continue; for (unsigned idx = 0; idx < target_instances.size(); idx++) { const InstanceRef &ref = target_instances[idx]; const ApEvent event = ref.get_ready_event(); if (!event.exists()) continue; const FieldMask &mask = ref.get_valid_fields(); // Convert these to destination fields if necessary const FieldMask overlap = mask & (perfect ? it->set_mask : across_helpers[idx]->convert_src_to_dst(it->set_mask)); if (!overlap) continue; InstanceView *view = target_views[idx]; across_aggregator->record_precondition(view, false/*reading*/, event, overlap, expr); } } } else { FieldMaskSet<IndexSpaceExpression>::const_iterator first = local_exprs.begin(); if (!first->first->is_empty()) { for (unsigned idx = 0; idx < target_instances.size(); idx++) { const InstanceRef &ref = target_instances[idx]; const ApEvent event = ref.get_ready_event(); if (!event.exists()) continue; const FieldMask &mask = ref.get_valid_fields(); // Convert these to destination fields if necessary const FieldMask overlap = mask & (perfect ? first->second : across_helpers[idx]->convert_src_to_dst(first->second)); if (!overlap) continue; InstanceView *view = target_views[idx]; across_aggregator->record_precondition(view, false/*reading*/, event, overlap, first->first); } } } across_aggregator->issue_updates(trace_info, precondition, false/*has src preconditions*/, true/*has dst preconditions*/); // Need to wait before we can get the summary #ifdef NON_AGGRESSIVE_AGGREGATORS if (!across_aggregator->effects_applied.has_triggered()) return across_aggregator->effects_applied; #else if (!across_aggregator->guard_postcondition.has_triggered()) return across_aggregator->guard_postcondition; #endif } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- ApEvent CopyAcrossAnalysis::perform_output(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformOutputArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.effects_event; } if (across_aggregator != NULL) { const ApEvent result = across_aggregator->summarize(trace_info); if (result.exists()) copy_events.insert(result); if (across_aggregator->release_guards(op->runtime, applied_events)) delete across_aggregator; } if (!copy_events.empty()) return Runtime::merge_events(&trace_info, copy_events); else return ApEvent::NO_AP_EVENT; } //-------------------------------------------------------------------------- /*static*/ void CopyAcrossAnalysis::handle_remote_copies_across( Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); FieldMask src_mask; for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); src_mask |= eq_masks[idx]; } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned src_index, dst_index; derez.deserialize(src_index); derez.deserialize(dst_index); RegionUsage src_usage, dst_usage; derez.deserialize(src_usage); derez.deserialize(dst_usage); size_t num_dsts; derez.deserialize(num_dsts); InstanceSet dst_instances(num_dsts); std::vector<InstanceView*> dst_views(num_dsts, NULL); for (unsigned idx = 0; idx < num_dsts; idx++) { RtEvent ready; dst_instances[idx].unpack_reference(runtime, derez, ready); if (ready.exists()) ready_events.insert(ready); DistributedID did; derez.deserialize(did); LogicalView *view = runtime->find_or_request_logical_view(did, ready); dst_views[idx] = static_cast<InstanceView*>(view); if (ready.exists()) ready_events.insert(ready); } LogicalRegion src_handle, dst_handle; derez.deserialize(src_handle); derez.deserialize(dst_handle); PredEvent pred_guard; derez.deserialize(pred_guard); ApEvent precondition; derez.deserialize(precondition); ReductionOpID redop; derez.deserialize(redop); bool perfect; derez.deserialize(perfect); std::vector<unsigned> src_indexes, dst_indexes; if (!perfect) { size_t num_indexes; derez.deserialize(num_indexes); src_indexes.resize(num_indexes); dst_indexes.resize(num_indexes); for (unsigned idx = 0; idx < num_indexes; idx++) { derez.deserialize(src_indexes[idx]); derez.deserialize(dst_indexes[idx]); } } RtUserEvent applied; derez.deserialize(applied); ApUserEvent copy; derez.deserialize(copy); const PhysicalTraceInfo trace_info = PhysicalTraceInfo::unpack_trace_info(derez, runtime, op); std::vector<CopyAcrossHelper*> across_helpers; std::set<RtEvent> deferral_events, applied_events; RegionNode *dst_node = runtime->forest->get_node(dst_handle); IndexSpaceExpression *dst_expr = dst_node->get_index_space_expression(); // Make sure that all our pointers are ready if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); } // This takes ownership of the op and the across helpers CopyAcrossAnalysis *analysis = new CopyAcrossAnalysis(runtime, original_source, previous, op, src_index, dst_index, src_usage, dst_usage, src_handle, dst_handle, dst_instances, dst_views, precondition, pred_guard, redop, src_indexes, dst_indexes, trace_info, perfect); analysis->add_reference(); for (unsigned idx = 0; idx < eq_sets.size(); idx++) { EquivalenceSet *set = eq_sets[idx]; // Check that the index spaces intersect IndexSpaceExpression *overlap = runtime->forest->intersect_index_spaces(set->set_expr, dst_expr); if (overlap->is_empty()) continue; set->issue_across_copies(*analysis, eq_masks[idx], overlap, deferral_events, applied_events); } const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); // Start with the source mask here in case we need to filter which // is all done on the source fields analysis->local_exprs.insert(dst_expr, src_mask); RtEvent remote_ready; if (traversal_done.exists() || analysis->has_remote_sets()) remote_ready = analysis->perform_remote(traversal_done, applied_events); RtEvent updates_ready; // Chain these so we get the local_exprs set correct if (remote_ready.exists() || analysis->has_across_updates()) updates_ready = analysis->perform_updates(remote_ready, applied_events); const ApEvent result = analysis->perform_output(updates_ready, applied_events); Runtime::trigger_event(copy, result); // Now we can trigger our applied event if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); // Clean up our analysis if (analysis->remove_reference()) delete analysis; } //-------------------------------------------------------------------------- /*static*/ std::vector<CopyAcrossHelper*> CopyAcrossAnalysis::create_across_helpers( const FieldMask &src_mask, const FieldMask &dst_mask, const InstanceSet &dst_instances, const std::vector<unsigned> &src_indexes, const std::vector<unsigned> &dst_indexes) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!dst_instances.empty()); #endif std::vector<CopyAcrossHelper*> result(dst_instances.size()); for (unsigned idx = 0; idx < dst_instances.size(); idx++) { result[idx] = new CopyAcrossHelper(src_mask, src_indexes, dst_indexes); InstanceManager *manager = dst_instances[idx].get_manager()->as_instance_manager(); manager->initialize_across_helper(result[idx], dst_mask, src_indexes, dst_indexes); } return result; } ///////////////////////////////////////////////////////////// // Overwrite Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- static inline std::set<LogicalView*> overwrite_insert_helper(LogicalView *v) //-------------------------------------------------------------------------- { std::set<LogicalView*> result; if (v != NULL) result.insert(v); return result; } //-------------------------------------------------------------------------- OverwriteAnalysis::OverwriteAnalysis(Runtime *rt, Operation *o, unsigned idx, const RegionUsage &use, const VersionInfo &info, LogicalView *view, const PhysicalTraceInfo &t_info, const ApEvent pre, const RtEvent guard, const PredEvent pred, const bool track, const bool restriction) : PhysicalAnalysis(rt, o, idx, info, true/*on heap*/), usage(use), views(overwrite_insert_helper(view)), trace_info(t_info), precondition(pre), guard_event(guard), pred_guard(pred), track_effects(track), add_restriction(restriction), output_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- OverwriteAnalysis::OverwriteAnalysis(Runtime *rt, Operation *o, unsigned idx, const RegionUsage &use, const VersionInfo &info,const std::set<LogicalView*> &v, const PhysicalTraceInfo &t_info, const ApEvent pre, const RtEvent guard, const PredEvent pred, const bool track, const bool restriction) : PhysicalAnalysis(rt, o, idx, info, true/*on heap*/), usage(use), views(v), trace_info(t_info), precondition(pre), guard_event(guard), pred_guard(pred), track_effects(track), add_restriction(restriction), output_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- OverwriteAnalysis::OverwriteAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, const RegionUsage &use, const std::set<LogicalView*> &v, const PhysicalTraceInfo &info, const ApEvent pre, const RtEvent guard, const PredEvent pred, const bool track, const bool restriction) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), usage(use), views(v), trace_info(info), precondition(pre), guard_event(guard), pred_guard(pred), track_effects(track), add_restriction(restriction), output_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- OverwriteAnalysis::OverwriteAnalysis(const OverwriteAnalysis &rhs) : PhysicalAnalysis(rhs), usage(rhs.usage), views(rhs.views), trace_info(rhs.trace_info), precondition(rhs.precondition), guard_event(rhs.guard_event), pred_guard(rhs.pred_guard), track_effects(rhs.track_effects), add_restriction(rhs.add_restriction) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- OverwriteAnalysis::~OverwriteAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- OverwriteAnalysis& OverwriteAnalysis::operator=(const OverwriteAnalysis &rs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void OverwriteAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->overwrite_set(*this, mask, deferral_events, applied_events, stale_mask, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent OverwriteAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // If there are no sets we're done if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; WrapperReferenceMutator mutator(applied_events); for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpace target = rit->first.first; const RtUserEvent applied = Runtime::create_rt_user_event(); const ApUserEvent effects = track_effects ? Runtime::create_ap_user_event() : ApUserEvent::NO_AP_USER_EVENT; Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize(usage); rez.serialize<size_t>(views.size()); if (!views.empty()) { for (std::set<LogicalView*>::const_iterator it = views.begin(); it != views.end(); it++) { (*it)->add_base_valid_ref(REMOTE_DID_REF, &mutator); rez.serialize((*it)->did); } } trace_info.pack_trace_info<false>(rez, applied_events, target); rez.serialize(pred_guard); rez.serialize(precondition); rez.serialize(guard_event); rez.serialize<bool>(add_restriction); rez.serialize(applied); rez.serialize(effects); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_overwrites(target, rez); applied_events.insert(applied); if (track_effects) effects_events.insert(effects); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- RtEvent OverwriteAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (output_aggregator != NULL) { output_aggregator->issue_updates(trace_info, precondition); // Need to wait before we can get the summary #ifdef NON_AGGRESSIVE_AGGREGATORS if (!output_aggregator->effects_applied.has_triggered()) return output_aggregator->effects_applied; #else if (!output_aggregator->guard_postcondition.has_triggered()) return output_aggregator->guard_postcondition; #endif } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- ApEvent OverwriteAnalysis::perform_output(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformOutputArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.effects_event; } if (output_aggregator != NULL) { const ApEvent result = output_aggregator->summarize(trace_info); if (result.exists() && track_effects) effects_events.insert(result); if (output_aggregator->release_guards(op->runtime, applied_events)) delete output_aggregator; } if (!effects_events.empty()) return Runtime::merge_events(&trace_info, effects_events); else return ApEvent::NO_AP_EVENT; } //-------------------------------------------------------------------------- /*static*/ void OverwriteAnalysis::handle_remote_overwrites( Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); RegionUsage usage; derez.deserialize(usage); std::set<LogicalView*> views; size_t num_views; derez.deserialize(num_views); for (unsigned idx = 0; idx < num_views; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(did, ready); if (ready.exists()) ready_events.insert(ready); views.insert(view); } const PhysicalTraceInfo trace_info = PhysicalTraceInfo::unpack_trace_info(derez, runtime, op); PredEvent pred_guard; derez.deserialize(pred_guard); ApEvent precondition; derez.deserialize(precondition); RtEvent guard_event; derez.deserialize(guard_event); bool add_restriction; derez.deserialize(add_restriction); RtUserEvent applied; derez.deserialize(applied); ApUserEvent effects; derez.deserialize(effects); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); // This takes ownership of the operation OverwriteAnalysis *analysis = new OverwriteAnalysis(runtime, original_source, previous, op, index, version_manager, usage, views, trace_info, precondition, guard_event, pred_guard, effects.exists(), add_restriction); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Make sure that all our pointers are ready RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); RtEvent remote_ready; if (traversal_done.exists() || analysis->has_remote_sets()) remote_ready = analysis->perform_remote(traversal_done, applied_events); RtEvent output_ready; if (traversal_done.exists() || analysis->has_output_updates()) output_ready = analysis->perform_updates(traversal_done, applied_events); const ApEvent result = analysis->perform_output( Runtime::merge_events(remote_ready, output_ready), applied_events); if (effects.exists()) Runtime::trigger_event(effects, result); // Now we can trigger our applied event if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Filter Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- FilterAnalysis::FilterAnalysis(Runtime *rt, Operation *o, unsigned idx, const VersionInfo &info, InstanceView *view, LogicalView *reg_view, const bool remove_restrict) : PhysicalAnalysis(rt, o, idx, info, true/*on heap*/), inst_view(view), registration_view(reg_view), remove_restriction(remove_restrict) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FilterAnalysis::FilterAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, InstanceView *view, LogicalView *reg_view, const bool remove_restrict) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), inst_view(view), registration_view(reg_view), remove_restriction(remove_restrict) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FilterAnalysis::FilterAnalysis(const FilterAnalysis &rhs) : PhysicalAnalysis(rhs), inst_view(rhs.inst_view), registration_view(rhs.registration_view), remove_restriction(rhs.remove_restriction) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- FilterAnalysis::~FilterAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FilterAnalysis& FilterAnalysis::operator=(const FilterAnalysis &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void FilterAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->filter_set(*this, mask, deferral_events, applied_events, stale_mask, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent FilterAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Filter has no perform_updates call so we apply this here if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; WrapperReferenceMutator mutator(applied_events); for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); if (inst_view != NULL) { inst_view->add_base_valid_ref(REMOTE_DID_REF, &mutator); rez.serialize(inst_view->did); } else rez.serialize<DistributedID>(0); if (registration_view != NULL) { registration_view->add_base_valid_ref(REMOTE_DID_REF, &mutator); rez.serialize(registration_view->did); } else rez.serialize<DistributedID>(0); rez.serialize(remove_restriction); rez.serialize(applied); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_filters(target, rez); applied_events.insert(applied); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- /*static*/ void FilterAnalysis::handle_remote_filters(Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); DistributedID view_did; derez.deserialize(view_did); InstanceView *inst_view = NULL; if (view_did != 0) { RtEvent view_ready; inst_view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(view_did, view_ready)); if (view_ready.exists()) ready_events.insert(view_ready); } derez.deserialize(view_did); LogicalView *registration_view = NULL; if (view_did != 0) { RtEvent view_ready; registration_view = runtime->find_or_request_logical_view(view_did, view_ready); if (view_ready.exists()) ready_events.insert(view_ready); } bool remove_restriction; derez.deserialize(remove_restriction); RtUserEvent applied; derez.deserialize(applied); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); // This takes ownership of the remote operation FilterAnalysis *analysis = new FilterAnalysis(runtime, original_source, previous, op, index, version_manager, inst_view, registration_view, remove_restriction); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Make sure that all our pointers are ready RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); RtEvent remote_ready; if (traversal_done.exists() || analysis->has_remote_sets()) analysis->perform_remote(traversal_done, applied_events); // Now we can trigger our applied event if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; // Nasty race here: make sure the ready has triggered before // removing the references here because the views are not valid if (ready_event.exists() && !ready_event.has_triggered()) ready_event.wait(); if (inst_view != NULL) inst_view->send_remote_valid_decrement(previous, NULL, applied); if (registration_view != NULL) registration_view->send_remote_valid_decrement(previous, NULL, applied); } ///////////////////////////////////////////////////////////// // Equivalence Set ///////////////////////////////////////////////////////////// // C++ is dumb const VersionID EquivalenceSet::init_version; //-------------------------------------------------------------------------- EquivalenceSet::DisjointPartitionRefinement::DisjointPartitionRefinement( EquivalenceSet *owner, IndexPartNode *p, std::set<RtEvent> &applied_events) : owner_did(owner->did), partition(p), total_child_volume(0), partition_volume(partition->get_union_expression()->get_volume()) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(partition->is_disjoint()); #endif WrapperReferenceMutator mutator(applied_events); partition->add_nested_valid_ref(owner_did, &mutator); } //-------------------------------------------------------------------------- EquivalenceSet::DisjointPartitionRefinement::DisjointPartitionRefinement( const DisjointPartitionRefinement &rhs, std::set<RtEvent> &applied_events) : owner_did(rhs.owner_did), partition(rhs.partition), children(rhs.get_children()), total_child_volume(children.size()), partition_volume(rhs.get_volume()) //-------------------------------------------------------------------------- { WrapperReferenceMutator mutator(applied_events); partition->add_nested_valid_ref(owner_did, &mutator); } //-------------------------------------------------------------------------- EquivalenceSet::DisjointPartitionRefinement::~DisjointPartitionRefinement( void) //-------------------------------------------------------------------------- { if (partition->remove_nested_valid_ref(owner_did)) delete partition; } //-------------------------------------------------------------------------- void EquivalenceSet::DisjointPartitionRefinement::add_child( IndexSpaceNode *node, EquivalenceSet *child) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(children.find(node) == children.end()); #endif children[node] = child; total_child_volume += node->get_volume(); } //-------------------------------------------------------------------------- EquivalenceSet* EquivalenceSet::DisjointPartitionRefinement::find_child( IndexSpaceNode *node) const //-------------------------------------------------------------------------- { std::map<IndexSpaceNode*,EquivalenceSet*>::const_iterator finder = children.find(node); if (finder == children.end()) return NULL; return finder->second; } //-------------------------------------------------------------------------- EquivalenceSet::EquivalenceSet(Runtime *rt, DistributedID did, AddressSpaceID owner, AddressSpace logical, IndexSpaceExpression *expr, IndexSpaceNode *node, bool reg_now) : DistributedCollectable(rt, LEGION_DISTRIBUTED_HELP_ENCODE(did, EQUIVALENCE_SET_DC), owner, reg_now), set_expr(expr), index_space_node(node), logical_owner_space(logical), eq_state(is_logical_owner() ? MAPPING_STATE : INVALID_STATE), subset_exprs(NULL), migration_index(0), sample_count(0), pending_analyses(0) //-------------------------------------------------------------------------- { set_expr->add_expression_reference(); if (index_space_node != NULL) { #ifdef DEBUG_LEGION // These two index space expressions should be equivalent // Although they don't have to be the same // These assertions are pretty expensive so we'll comment them // out for now, but put them back in if you think this invariant // is being violated //assert(runtime->forest->subtract_index_spaces(index_space_node, // set_expr)->is_empty()); //assert(runtime->forest->subtract_index_spaces(set_expr, // index_space_node)->is_empty()); #endif index_space_node->add_nested_resource_ref(did); } #ifdef LEGION_GC log_garbage.info("GC Equivalence Set %lld %d", did, local_space); #endif } //-------------------------------------------------------------------------- EquivalenceSet::EquivalenceSet(const EquivalenceSet &rhs) : DistributedCollectable(rhs), set_expr(NULL), index_space_node(NULL), logical_owner_space(rhs.logical_owner_space) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- EquivalenceSet::~EquivalenceSet(void) //-------------------------------------------------------------------------- { if (set_expr->remove_expression_reference()) delete set_expr; if ((index_space_node != NULL) && index_space_node->remove_nested_resource_ref(did)) delete index_space_node; if (!subsets.empty()) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) if (it->first->remove_nested_resource_ref(did)) delete it->first; subsets.clear(); } if (!valid_instances.empty()) { for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) if (it->first->remove_nested_valid_ref(did)) delete it->first; } if (!reduction_instances.empty()) { for (std::map<unsigned,std::vector<ReductionView*> >::const_iterator rit = reduction_instances.begin(); rit != reduction_instances.end(); rit++) { for (std::vector<ReductionView*>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) if ((*it)->remove_nested_valid_ref(did)) delete (*it); } } if (!restricted_instances.empty()) { for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end(); it++) if (it->first->remove_nested_valid_ref(did)) delete it->first; } if (!disjoint_partition_refinements.empty()) { for (FieldMaskSet<DisjointPartitionRefinement>::const_iterator it = disjoint_partition_refinements.begin(); it != disjoint_partition_refinements.end(); it++) delete it->first; } if (!unrefined_remainders.empty()) { for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = unrefined_remainders.begin(); it != unrefined_remainders.end(); it++) if (it->first->remove_expression_reference()) delete it->first; } if (subset_exprs != NULL) delete subset_exprs; } //-------------------------------------------------------------------------- EquivalenceSet& EquivalenceSet::operator=(const EquivalenceSet &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void EquivalenceSet::trigger_pending_analysis_event(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif Runtime::trigger_event(waiting_event); waiting_event = RtUserEvent::NO_RT_USER_EVENT; } //-------------------------------------------------------------------------- void EquivalenceSet::notify_active(ReferenceMutator *mutator) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- void EquivalenceSet::notify_inactive(ReferenceMutator *mutator) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- void EquivalenceSet::notify_valid(ReferenceMutator *mutator) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- void EquivalenceSet::notify_invalid(ReferenceMutator *mutator) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- AddressSpaceID EquivalenceSet::clone_from(const EquivalenceSet *parent, const FieldMask &clone_mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION // Should be cloning from the parent on it's owner space assert(parent->logical_owner_space == this->local_space); #endif // Take our lock in exclusive mode since we're going to be updating // our data structures AutoLock eq(eq_lock); // Check to see if we're the logical owner, if not then tell // the refinement task where it should send the data if (!is_logical_owner()) return logical_owner_space; // We are the logical owner so clone the meta data // No need for a mutator here since all the views already // have valid references being held by the parent equivalence set if (!parent->valid_instances.empty() && !(clone_mask * parent->valid_instances.get_valid_mask())) { for (FieldMaskSet<LogicalView>::const_iterator it = parent->valid_instances.begin(); it != parent->valid_instances.end(); it++) { const FieldMask overlap = it->second & clone_mask; if (!overlap) continue; if (this->valid_instances.insert(it->first, overlap)) it->first->add_nested_valid_ref(did); } } if (!!parent->reduction_fields) { const FieldMask reduc_overlap = parent->reduction_fields & clone_mask; if (!!reduc_overlap) { this->reduction_fields |= reduc_overlap; int fidx = reduc_overlap.find_first_set(); while (fidx >= 0) { std::vector<ReductionView*> &reduc_insts = this->reduction_instances[fidx]; #ifdef DEBUG_LEGION assert(reduc_insts.empty()); #endif std::map<unsigned,std::vector<ReductionView*> >::const_iterator finder = parent->reduction_instances.find(fidx); #ifdef DEBUG_LEGION assert(finder != parent->reduction_instances.end()); #endif reduc_insts = finder->second; for (unsigned idx = 0; idx < reduc_insts.size(); idx++) reduc_insts[idx]->add_nested_valid_ref(did); fidx = reduc_overlap.find_next_set(fidx+1); } } } if (!parent->restricted_instances.empty() && !(clone_mask * parent->restricted_instances.get_valid_mask())) { this->restricted_fields |= (clone_mask & parent->restricted_fields); for (FieldMaskSet<InstanceView>::const_iterator it = parent->restricted_instances.begin(); it != parent->restricted_instances.end(); it++) { const FieldMask overlap = it->second & clone_mask; if (!overlap) continue; if (this->restricted_instances.insert(it->first, overlap)) it->first->add_nested_valid_ref(did); } } if (!parent->update_guards.empty() && !(clone_mask * parent->update_guards.get_valid_mask())) { for (FieldMaskSet<CopyFillGuard>::const_iterator it = parent->update_guards.begin(); it != parent->update_guards.end(); it++) { const FieldMask overlap = it->second & clone_mask; if (!overlap) continue; // Only want to record this if it isn't in the process of // being pruned out. The record_guard_set method will check // for this return true if it is not being pruned out if (it->first->record_guard_set(this)) update_guards.insert(it->first, overlap); } } // Return our space since we stored the data here return local_space; } //-------------------------------------------------------------------------- void EquivalenceSet::remove_update_guard(CopyFillGuard *guard) //-------------------------------------------------------------------------- { AutoLock eq(eq_lock); // If we're no longer the logical owner then it's because we were // migrated and there should be no guards so we're done if (!is_logical_owner() && update_guards.empty()) return; // We could get here when we're not the logical owner if we've unpacked // ourselves but haven't become the owner yet, in which case we still // need to prune ourselves out of the list FieldMaskSet<CopyFillGuard>::iterator finder = update_guards.find(guard); // It's also possible that the equivalence set is migrated away and // then migrated back before this guard is removed in which case we // won't find it in the update guards and can safely ignore it if (finder == update_guards.end()) return; const bool should_tighten = !!finder->second; update_guards.erase(finder); if (should_tighten) update_guards.tighten_valid_mask(); } //-------------------------------------------------------------------------- void EquivalenceSet::check_for_unrefined_remainder(AutoLock &eq, const FieldMask &mask, AddressSpaceID source) //-------------------------------------------------------------------------- { if (!is_logical_owner()) return; bool first_pass = true; do { // If this isn't the first pass then we need to wait if (!first_pass) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif const RtEvent wait_on = waiting_event; eq.release(); if (!wait_on.has_triggered()) wait_on.wait(); eq.reacquire(); // When we wake up we have to do all the checks again // in case there were fields that weren't refined before // but are (partially or being) refined now #ifdef DEBUG_LEGION // Should never be migrated while we are waiting here assert(is_logical_owner()); #endif } else first_pass = false; // Check for any disjoint pieces if (!disjoint_partition_refinements.empty()) { FieldMask disjoint_overlap = disjoint_partition_refinements.get_valid_mask() & mask; if (!!disjoint_overlap) { std::vector<DisjointPartitionRefinement*> to_delete; for (FieldMaskSet<DisjointPartitionRefinement>::iterator it = disjoint_partition_refinements.begin(); it != disjoint_partition_refinements.end(); it++) { const FieldMask overlap = it->second & disjoint_overlap; if (!overlap) continue; finalize_disjoint_refinement(it->first, overlap); it.filter(overlap); if (!it->second) to_delete.push_back(it->first); disjoint_overlap -= overlap; if (!disjoint_overlap) break; } if (!to_delete.empty()) { for (std::vector<DisjointPartitionRefinement*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { disjoint_partition_refinements.erase(*it); delete (*it); } disjoint_partition_refinements.tighten_valid_mask(); } } } // Check for unrefined remainder pieces too if (!unrefined_remainders.empty()) { FieldMask unrefined_overlap = unrefined_remainders.get_valid_mask() & mask; if (!!unrefined_overlap) { std::vector<IndexSpaceExpression*> to_delete; for (FieldMaskSet<IndexSpaceExpression>::iterator it = unrefined_remainders.begin(); it != unrefined_remainders.end(); it++) { const FieldMask overlap = it->second & unrefined_overlap; if (!overlap) continue; add_pending_refinement(it->first, overlap, NULL/*node*/, source); it.filter(overlap); if (!it->second) to_delete.push_back(it->first); unrefined_overlap -= overlap; if (!unrefined_overlap) break; } if (!to_delete.empty()) { for (std::vector<IndexSpaceExpression*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { unrefined_remainders.erase(*it); if ((*it)->remove_expression_reference()) delete (*it); } unrefined_remainders.tighten_valid_mask(); } } } } // See if we need to wait for any refinements to finish while (!(mask * pending_refinements.get_valid_mask()) || !(mask * refining_fields)); } //-------------------------------------------------------------------------- void EquivalenceSet::refresh_refinement(RayTracer *target, const FieldMask &mask, RtUserEvent refresh_done) //-------------------------------------------------------------------------- { ray_trace_equivalence_sets(target, set_expr, mask, (index_space_node == NULL) ? IndexSpace::NO_SPACE : index_space_node->handle, runtime->address_space, refresh_done); } //-------------------------------------------------------------------------- void EquivalenceSet::ray_trace_equivalence_sets(RayTracer *target, IndexSpaceExpression *expr, FieldMask ray_mask, IndexSpace handle, AddressSpaceID source, RtUserEvent trace_done, RtUserEvent deferral_event) //-------------------------------------------------------------------------- { RegionTreeForest *forest = runtime->forest; #ifdef DEBUG_LEGION assert(expr != NULL); // An expensive sanity check if you want to turn it on //assert(forest->subtract_index_spaces(expr, set_expr)->is_empty()); #endif RtEvent refinement_done; std::set<RtEvent> done_events; FieldMaskSet<EquivalenceSet> to_traverse, pending_to_traverse; std::map<EquivalenceSet*,IndexSpaceExpression*> to_traverse_exprs; { // Try to get the lock, if we don't get it build a continuation AutoTryLock eq(eq_lock); if (!eq.has_lock()) { // We didn't get the lock so build a continuation // We need a name for our completion event that we can use for // the atomic compare and swap below if (!deferral_event.exists()) { // If we haven't already been deferred then we need to // add ourselves to the back of the list of deferrals deferral_event = Runtime::create_rt_user_event(); const RtEvent continuation_pre = chain_deferral_events(deferral_event); DeferRayTraceArgs args(this, target, expr, handle, source, trace_done, deferral_event, ray_mask); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, continuation_pre); } else { // We've already been deferred and our precondition has already // triggered so just launch ourselves again whenever the lock // should be ready to try again DeferRayTraceArgs args(this, target, expr, handle, source, trace_done, deferral_event, ray_mask); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, eq.try_next()); } return; } else if (!is_logical_owner()) { // If we're not the owner node then send the request there Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(target); expr->pack_expression(rez, logical_owner_space); rez.serialize(ray_mask); rez.serialize(handle); rez.serialize(source); rez.serialize(trace_done); } runtime->send_equivalence_set_ray_trace_request(logical_owner_space, rez); // Trigger our deferral event if we had one if (deferral_event.exists()) Runtime::trigger_event(deferral_event); return; } else if ((eq_state == REFINING_STATE) && !(ray_mask * refining_fields)) { if (!transition_event.exists()) transition_event = Runtime::create_rt_user_event(); // If we're refining then we also need to defer this until // the refinements that interfere with us are done DeferRayTraceArgs args(this, target, expr, handle, source, trace_done, deferral_event, ray_mask); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, transition_event); return; } // Handle the special case where we are exactly representing the // index space and we have not been refined yet. This a performance // optimization only and is not required for correctness if (handle.exists() && (index_space_node != NULL) && (index_space_node->handle == handle) && (subsets.empty() || (ray_mask * subsets.get_valid_mask()))) { // Just record this as one of the results if (source != runtime->address_space) { // Not local so we need to send a message Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(ray_mask); rez.serialize(target); rez.serialize(trace_done); } runtime->send_equivalence_set_ray_trace_response(source, rez); } else // Local so we can update this directly { target->record_equivalence_set(this, ray_mask); Runtime::trigger_event(trace_done); } // We're done with our traversal so trigger the deferral event if (deferral_event.exists()) Runtime::trigger_event(deferral_event); return; } // First check to see which fields are in a disjoint refinement // and whether we can continue doing the disjoint refinement if (!disjoint_partition_refinements.empty()) { #ifdef DEBUG_LEGION assert(index_space_node != NULL); #endif FieldMask disjoint_overlap = ray_mask & disjoint_partition_refinements.get_valid_mask(); if (!!disjoint_overlap) { FieldMaskSet<DisjointPartitionRefinement> to_add; std::vector<DisjointPartitionRefinement*> to_delete; // Iterate over the disjoint partition refinements and see // which ones we overlap with for (FieldMaskSet<DisjointPartitionRefinement>::iterator it = disjoint_partition_refinements.begin(); it != disjoint_partition_refinements.end(); it++) { FieldMask overlap = it->second & disjoint_overlap; if (!overlap) continue; // Remove this from the disjoint overlap now in case // we end up removing overlap fields later disjoint_overlap -= overlap; // This is the special case where we are refining // a disjoint partition and all the refinements so far // have been specific instances of a subregion of the // disjoint partition, check to see if that is still true if (handle.exists()) { IndexSpaceNode *node = runtime->forest->get_node(handle); if (node->parent == it->first->partition) { // Record that we're handling all these ray fields // before we go about filtering the fields out of overlap ray_mask -= overlap; // Another sub-region of the disjoint partition // See if we already made the refinement or not EquivalenceSet *child = it->first->find_child(node); // If child is NULL then we haven't made it yet if (child == NULL) { // We want to maintain the invariant that a disjoint // partition refinement represents all the children // being refined for all the same fields, so we need // to split this disjoint partition refinement into // two if there is a difference in fields const FieldMask non_overlap = it->second - overlap; if (!!non_overlap) { // Make a new disjoint partition refinement that is // a copy of the old one up to this point DisjointPartitionRefinement *copy_refinement = new DisjointPartitionRefinement(*(it->first), done_events); to_add.insert(copy_refinement, non_overlap); // Filter the fields down to just the overlap it.filter(non_overlap); } #ifdef DEBUG_LEGION assert(it->second == overlap); #endif // Refine this for all the fields in the disjoint // partition refinement to maintain the invariant that // all these chidren have been refined for all fields child = add_pending_refinement(expr, overlap, node, source); pending_to_traverse.insert(child, overlap); to_traverse_exprs[child] = expr; // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } // Record this child for the future it->first->add_child(node, child); // Check to see if we've finished this disjoint partition if (it->first->is_refined()) { // If we're done with this disjoint pending partition // then we can remove it from the set to_delete.push_back(it->first); // If this wasn't a complete partition then we need to // add the difference into the remainder if (!it->first->partition->is_complete()) { IndexSpaceExpression *diff_expr = runtime->forest->subtract_index_spaces(set_expr, it->first->partition->get_union_expression()); #ifdef DEBUG_LEGION assert((diff_expr != NULL) && !diff_expr->is_empty()); assert(unrefined_remainders.get_valid_mask() * overlap); #endif if (unrefined_remainders.insert(diff_expr, overlap)) diff_expr->add_expression_reference(); } } // Remove these fields from the overlap indicating // that we handled them overlap.clear(); } else { // Figure out which fields have already been refined // and which ones are still pending, issue refinements // for any fields that haven't been refined yet FieldMaskSet<EquivalenceSet>::iterator finder = subsets.find(child); if (finder != subsets.end()) { const FieldMask eq_valid = overlap & finder->second; if (!!eq_valid) { to_traverse.insert(child, eq_valid); to_traverse_exprs[child] = expr; overlap -= eq_valid; } } // If we couldn't find it in the already valid set, check // also in the pending refinements if (!!overlap) { finder = pending_refinements.find(child); if (finder != pending_refinements.end()) { #ifdef DEBUG_LEGION // All overlap fields should be dominated assert(!(overlap - finder->second)); #endif pending_to_traverse.insert(child, overlap); to_traverse_exprs[child] = expr; overlap.clear(); // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } } } #ifdef DEBUG_LEGION // Should have handled all the fields at this point assert(!overlap); #endif } } } // If we get here and we still haven't done a disjoint // refinement then we can no longer allow it to continue if (!!overlap) { finalize_disjoint_refinement(it->first, overlap); it.filter(overlap); if (!it->second) to_delete.push_back(it->first); } // If we handled our disjoint overlap fields then we're done if (!disjoint_overlap) break; } if (!to_delete.empty()) { for (std::vector<DisjointPartitionRefinement*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { disjoint_partition_refinements.erase(*it); delete (*it); } disjoint_partition_refinements.tighten_valid_mask(); } if (!to_add.empty()) { if (!disjoint_partition_refinements.empty()) for (FieldMaskSet<DisjointPartitionRefinement>::const_iterator it = to_add.begin(); it != to_add.end(); it++) disjoint_partition_refinements.insert(it->first, it->second); else disjoint_partition_refinements.swap(to_add); } } } // Next handle any fields which are refined or pending refined if (!!ray_mask) { FieldMaskSet<IndexSpaceExpression> intersections; if (!pending_refinements.empty() && !(ray_mask * pending_refinements.get_valid_mask())) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = pending_refinements.begin(); it != pending_refinements.end(); it++) { const FieldMask overlap = it->second & ray_mask; if (!overlap) continue; // Next check for expression overlap IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(expr, it->first->set_expr); if (expr_overlap->is_empty()) continue; pending_to_traverse.insert(it->first, overlap); to_traverse_exprs[it->first] = expr_overlap; intersections.insert(expr_overlap, overlap); // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } } } if (!subsets.empty() && !(ray_mask * subsets.get_valid_mask())) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & ray_mask; if (!overlap) continue; // Next check for expression overlap IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(expr, it->first->set_expr); if (expr_overlap->is_empty()) continue; to_traverse.insert(it->first, overlap); to_traverse_exprs[it->first] = expr_overlap; intersections.insert(expr_overlap, overlap); } } // For all our intersections, compute the remainders after the // overlap and if they exist then perform refinements for them if (!intersections.empty()) { if (intersections.size() > 1) { // Sort these into field mask sets LegionList<FieldSet<IndexSpaceExpression*> >::aligned field_sets; intersections.compute_field_sets(FieldMask(), field_sets); for (LegionList<FieldSet<IndexSpaceExpression*> >::aligned:: iterator it = field_sets.begin(); it != field_sets.end(); it++) { IndexSpaceExpression *diff = forest->subtract_index_spaces(expr, forest->union_index_spaces(it->elements)); if (!diff->is_empty()) { EquivalenceSet *child = add_pending_refinement(diff, it->set_mask, NULL, source); pending_to_traverse.insert(child, it->set_mask); to_traverse_exprs[child] = diff; // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } // We need to subtract this off any unrefined remainders // or add the difference of it with the original set // to the set of unrefined remainders filter_unrefined_remainders(it->set_mask, diff); if (!!it->set_mask) { IndexSpaceExpression *remainder = forest->subtract_index_spaces(set_expr, diff); if (!remainder->is_empty()) { #ifdef DEBUG_LEGION assert(disjoint_partition_refinements.get_valid_mask() * it->set_mask); assert(unrefined_remainders.get_valid_mask() * it->set_mask); #endif if (unrefined_remainders.insert(remainder, it->set_mask)) remainder->add_expression_reference(); } } } } } else { // Easy case with just one intersection FieldMaskSet<IndexSpaceExpression>::const_iterator first = intersections.begin(); IndexSpaceExpression *diff = forest->subtract_index_spaces(expr, first->first); if (!diff->is_empty()) { EquivalenceSet *child = add_pending_refinement(diff, first->second, NULL, source); pending_to_traverse.insert(child, first->second); to_traverse_exprs[child] = diff; // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } // Subtract from any unrefined remainders FieldMask to_filter = first->second; filter_unrefined_remainders(to_filter, diff); if (!!to_filter) { IndexSpaceExpression *remainder = forest->subtract_index_spaces(set_expr, diff); if (!remainder->is_empty()) { #ifdef DEBUG_LEGION assert(disjoint_partition_refinements.get_valid_mask() * to_filter); assert(unrefined_remainders.get_valid_mask() * to_filter); #endif if (unrefined_remainders.insert(remainder, to_filter)) remainder->add_expression_reference(); } } } } // These fields are all remove from the ray mask // since they have now been handled ray_mask -= intersections.get_valid_mask(); } } // If we still have fields left, see if we need a refinement if (!!ray_mask && (set_expr->expr_id != expr->expr_id) && (expr->get_volume() < set_expr->get_volume())) { #ifdef DEBUG_LEGION IndexSpaceExpression *diff = forest->subtract_index_spaces(set_expr, expr); assert(!diff->is_empty()); #endif // We're doing a refinement for the first time, see if // we can make this a disjoint partition refeinement if ((index_space_node != NULL) && handle.exists()) { FieldMask disjoint_mask = ray_mask; // We can't start a new disjoint mask for anything that // has already been partially refined if (!unrefined_remainders.empty()) disjoint_mask -= unrefined_remainders.get_valid_mask(); if (!!disjoint_mask) { IndexSpaceNode *node = runtime->forest->get_node(handle); // We can start a disjoint complete partition if there // is exactly one partition between the parent index // space for the equivalence class and the child index // space for the subset and the partition is disjoint if ((node->parent != NULL) && (node->parent->parent == index_space_node) && node->parent->is_disjoint()) { DisjointPartitionRefinement *dis = new DisjointPartitionRefinement(this, node->parent, done_events); EquivalenceSet *child = add_pending_refinement(expr, disjoint_mask, node, source); pending_to_traverse.insert(child, disjoint_mask); to_traverse_exprs[child] = expr; // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } // Save this for the future dis->add_child(node, child); #ifdef DEBUG_LEGION assert(disjoint_mask * unrefined_remainders.get_valid_mask()); #endif disjoint_partition_refinements.insert(dis, disjoint_mask); ray_mask -= disjoint_mask; } } } // If we didn't make a disjoint partition refeinement // then we need to do the normal kind of refinement if (!!ray_mask) { // Time to refine this since we only need a subset of it EquivalenceSet *child = add_pending_refinement(expr, ray_mask, NULL, source); pending_to_traverse.insert(child, ray_mask); to_traverse_exprs[child] = expr; // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } // Subtract from any unrefined remainders filter_unrefined_remainders(ray_mask, expr); if (!!ray_mask) { #ifdef DEBUG_LEGION assert(disjoint_partition_refinements.get_valid_mask() * ray_mask); assert(unrefined_remainders.get_valid_mask() * ray_mask); #else IndexSpaceExpression *diff = forest->subtract_index_spaces(set_expr, expr); #endif if (unrefined_remainders.insert(diff, ray_mask)) diff->add_expression_reference(); ray_mask.clear(); } } } // Otherwise we can fall through because this means the // expressions are equivalent } // We've done our traversal, so if we had a deferral even we can // trigger it now to signal to the next user that they can start if (deferral_event.exists()) Runtime::trigger_event(deferral_event); // Any fields which are still valid should be recorded if (!!ray_mask) { // Not local so we need to send a message if (source != runtime->address_space) { // If there's nothing to do after this we can use // the trace_done event directly if (to_traverse.empty() && pending_to_traverse.empty()) { Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(ray_mask); rez.serialize(target); rez.serialize(trace_done); } runtime->send_equivalence_set_ray_trace_response(source, rez); return; } else { RtUserEvent done = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(ray_mask); rez.serialize(target); rez.serialize(done); } runtime->send_equivalence_set_ray_trace_response(source, rez); done_events.insert(done); } } else target->record_equivalence_set(this, ray_mask); } // Traverse anything we can now before we have to wait if (!to_traverse.empty()) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) { RtUserEvent done = Runtime::create_rt_user_event(); std::map<EquivalenceSet*,IndexSpaceExpression*>::const_iterator finder = to_traverse_exprs.find(it->first); #ifdef DEBUG_LEGION assert(finder != to_traverse_exprs.end()); #endif const IndexSpace subset_handle = (handle.exists() && (finder->second->get_volume() == expr->get_volume())) ? handle : IndexSpace::NO_SPACE; it->first->ray_trace_equivalence_sets(target, finder->second, it->second, subset_handle, source, done); done_events.insert(done); } // Clear these since we are done doing them to_traverse.clear(); } // Get the actual equivalence sets for any refinements we needed to // wait for because they weren't ready earlier if (!pending_to_traverse.empty()) { // If we have a refinement to do then we need to wait for that // to be done before we continue our traversal if (refinement_done.exists() && !refinement_done.has_triggered()) { // Defer this until the refinements are done FieldMaskSet<EquivalenceSet> *copy_traverse = new FieldMaskSet<EquivalenceSet>(); copy_traverse->swap(pending_to_traverse); std::map<EquivalenceSet*,IndexSpaceExpression*> *copy_exprs = new std::map<EquivalenceSet*,IndexSpaceExpression*>(); copy_exprs->swap(to_traverse_exprs); const RtUserEvent done = Runtime::create_rt_user_event(); DeferRayTraceFinishArgs args(target, source, copy_traverse, copy_exprs, expr->get_volume(), handle, done); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, refinement_done); done_events.insert(done); } else { for (FieldMaskSet<EquivalenceSet>::const_iterator it = pending_to_traverse.begin(); it != pending_to_traverse.end(); it++) { RtUserEvent done = Runtime::create_rt_user_event(); std::map<EquivalenceSet*,IndexSpaceExpression*>::const_iterator finder = to_traverse_exprs.find(it->first); #ifdef DEBUG_LEGION assert(finder != to_traverse_exprs.end()); #endif const IndexSpace subset_handle = (handle.exists() && (finder->second->get_volume() == expr->get_volume())) ? handle : IndexSpace::NO_SPACE; it->first->ray_trace_equivalence_sets(target, finder->second, it->second, subset_handle, source, done); done_events.insert(done); } } } if (!done_events.empty()) Runtime::trigger_event(trace_done, Runtime::merge_events(done_events)); else Runtime::trigger_event(trace_done); } //-------------------------------------------------------------------------- void EquivalenceSet::pack_state(Serializer &rez, const FieldMask &pack_mask) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(is_logical_owner()); #endif // Pack the valid instances rez.serialize<size_t>(valid_instances.size()); if (!valid_instances.empty()) { for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask overlap = it->second & pack_mask; if (!!overlap) { rez.serialize(it->first->did); rez.serialize(overlap); } else rez.serialize<DistributedID>(0); } } // Pack the reduction instances if (!!reduction_fields) { const FieldMask reduc_mask = reduction_fields & pack_mask; if (!!reduc_mask) { rez.serialize<size_t>(reduc_mask.pop_count()); int fidx = reduc_mask.find_first_set(); while (fidx >= 0) { rez.serialize<unsigned>(fidx); std::map<unsigned,std::vector<ReductionView*> >::const_iterator finder = reduction_instances.find(fidx); #ifdef DEBUG_LEGION assert(finder != reduction_instances.end()); #endif rez.serialize<size_t>(finder->second.size()); for (std::vector<ReductionView*>::const_iterator it = finder->second.begin(); it != finder->second.end(); it++) rez.serialize((*it)->did); fidx = reduc_mask.find_next_set(fidx+1); } } else rez.serialize<size_t>(0); } else rez.serialize<size_t>(0); // Pack the restricted instances if (!!restricted_fields) { const FieldMask restr_mask = restricted_fields & pack_mask; if (!!restr_mask) { rez.serialize<size_t>(restricted_instances.size()); for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end(); it++) { const FieldMask overlap = pack_mask & it->second; if (!!overlap) { rez.serialize(it->first->did); rez.serialize(overlap); } else rez.serialize<DistributedID>(0); } } else rez.serialize<size_t>(0); } else rez.serialize<size_t>(0); // Pack the version numbers rez.serialize<size_t>(version_numbers.size()); if (!version_numbers.empty()) { for (LegionMap<VersionID,FieldMask>::aligned::const_iterator it = version_numbers.begin(); it != version_numbers.end(); it++) { const FieldMask overlap = pack_mask & it->second; if (!!overlap) { rez.serialize(it->first); rez.serialize(overlap); } else rez.serialize<VersionID>(0); } } // Pack the update guards if (!update_guards.empty() && !(pack_mask * update_guards.get_valid_mask())) { FieldMaskSet<CopyFillGuard> remote_guards; for (FieldMaskSet<CopyFillGuard>::const_iterator it = update_guards.begin(); it != update_guards.end(); it++) { const FieldMask overlap = pack_mask & it->second; if (!overlap) continue; remote_guards.insert(it->first, overlap); } rez.serialize<size_t>(remote_guards.size()); for (FieldMaskSet<CopyFillGuard>::const_iterator it = remote_guards.begin(); it != remote_guards.end(); it++) { it->first->pack_guard(rez); rez.serialize(it->second); } } else rez.serialize<size_t>(0); } //-------------------------------------------------------------------------- void EquivalenceSet::unpack_state(Deserializer &derez) //-------------------------------------------------------------------------- { RtUserEvent done_event; derez.deserialize(done_event); bool initial_refinement; derez.deserialize(initial_refinement); // Do a quick test to see if we're still the owner, if not // then we can just forward this on immediately { AutoLock eq(eq_lock,1,false/*exlcusive*/); // Check to see if we're the initial refinement, if not // then we need to keep forwarding this on to wherever the // owner is, otherwise we can handle it now and make ourselves // the owner once we are ready if (!is_logical_owner() && !initial_refinement) { Serializer rez; // No RezCheck because of forwarding rez.serialize(did); rez.serialize(done_event); rez.serialize<bool>(false); // initial refinement // Just move the bytes over to the serializer and return const size_t bytes = derez.get_remaining_bytes(); rez.serialize(derez.get_current_pointer(), bytes); runtime->send_equivalence_set_remote_refinement( logical_owner_space, rez); // Keep the deserializer happy derez.advance_pointer(bytes); return; } } // Keep track of ready events std::set<RtEvent> ready_events; // Unpack into local data structures which we'll update later FieldMaskSet<LogicalView> new_valid; size_t num_valid_insts; derez.deserialize(num_valid_insts); for (unsigned idx = 0; idx < num_valid_insts; idx++) { DistributedID valid_did; derez.deserialize(valid_did); if (valid_did == 0) continue; RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(valid_did, ready); if (ready.exists()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); new_valid.insert(view, mask); } size_t num_reduc_fields; derez.deserialize(num_reduc_fields); std::map<unsigned,std::vector<ReductionView*> > new_reductions; for (unsigned idx1 = 0; idx1 < num_reduc_fields; idx1++) { unsigned fidx; derez.deserialize(fidx); std::vector<ReductionView*> &new_views = new_reductions[fidx]; size_t num_reduc_insts; derez.deserialize(num_reduc_insts); new_views.resize(num_reduc_insts); for (unsigned idx2 = 0; idx2 < num_reduc_insts; idx2++) { DistributedID reduc_did; derez.deserialize(reduc_did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(reduc_did, ready); new_views[idx2] = static_cast<ReductionView*>(view); if (ready.exists()) ready_events.insert(ready); } } size_t num_restrict_insts; derez.deserialize(num_restrict_insts); FieldMaskSet<InstanceView> new_restrictions; if (num_restrict_insts > 0) { for (unsigned idx = 0; idx < num_restrict_insts; idx++) { DistributedID valid_did; derez.deserialize(valid_did); if (valid_did == 0) continue; RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(valid_did, ready); if (ready.exists()) ready_events.insert(ready); InstanceView *inst_view = static_cast<InstanceView*>(view); FieldMask mask; derez.deserialize(mask); new_restrictions.insert(inst_view, mask); } } size_t num_versions; derez.deserialize(num_versions); LegionMap<VersionID,FieldMask>::aligned new_versions; for (unsigned idx = 0; idx < num_versions; idx++) { VersionID vid; derez.deserialize(vid); if (vid == 0) continue; derez.deserialize(new_versions[vid]); } size_t num_guards; derez.deserialize(num_guards); if (num_guards > 0) { // Need to hold the lock here to prevent copy fill guard // deletions from removing this before we've registered it AutoLock eq(eq_lock); for (unsigned idx = 0; idx < num_guards; idx++) { CopyFillGuard *guard = CopyFillGuard::unpack_guard(derez, runtime, this); FieldMask guard_mask; derez.deserialize(guard_mask); if (guard != NULL) update_guards.insert(guard, guard_mask); } } // If we have events to wait for then we need to defer this if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) { // Defer the merge or forward until the views are ready FieldMaskSet<LogicalView> *view_copy = new FieldMaskSet<LogicalView>(); view_copy->swap(new_valid); std::map<unsigned,std::vector<ReductionView*> > *reduc_copy = new std::map<unsigned,std::vector<ReductionView*> >(); reduc_copy->swap(new_reductions); FieldMaskSet<InstanceView> *restrict_copy = new FieldMaskSet<InstanceView>(); restrict_copy->swap(new_restrictions); LegionMap<VersionID,FieldMask>::aligned *version_copy = new LegionMap<VersionID,FieldMask>::aligned(); version_copy->swap(new_versions); DeferMergeOrForwardArgs args(this, initial_refinement, view_copy, reduc_copy, restrict_copy, version_copy, done_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, wait_on); return; } // Otherwise fall through to do the merge or forward now } // Either merge or forward the update merge_or_forward(done_event, initial_refinement, new_valid, new_reductions, new_restrictions, new_versions); } //-------------------------------------------------------------------------- void EquivalenceSet::merge_or_forward(const RtUserEvent done_event, bool initial_refinement, const FieldMaskSet<LogicalView> &new_views, const std::map<unsigned,std::vector<ReductionView*> > &new_reductions, const FieldMaskSet<InstanceView> &new_restrictions, const LegionMap<VersionID,FieldMask>::aligned &new_versions) //-------------------------------------------------------------------------- { AutoLock eq(eq_lock); if (is_logical_owner() || initial_refinement) { // We're the owner so we can do the merge LocalReferenceMutator mutator; for (FieldMaskSet<LogicalView>::const_iterator it = new_views.begin(); it != new_views.end(); it++) if (valid_instances.insert(it->first, it->second)) it->first->add_nested_valid_ref(did, &mutator); for (std::map<unsigned,std::vector<ReductionView*> >::const_iterator rit = new_reductions.begin(); rit != new_reductions.end(); rit++) { reduction_fields.set_bit(rit->first); std::vector<ReductionView*> &reduc_insts = reduction_instances[rit->first]; #ifdef DEBUG_LEGION assert(reduc_insts.empty()); #endif for (std::vector<ReductionView*>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { reduc_insts.push_back(*it); (*it)->add_nested_valid_ref(did, &mutator); } } for (FieldMaskSet<InstanceView>::const_iterator it = new_restrictions.begin(); it != new_restrictions.end(); it++) { restricted_fields |= it->second; if (restricted_instances.insert(it->first, it->second)) it->first->add_nested_valid_ref(did, &mutator); } for (LegionMap<VersionID,FieldMask>::aligned::const_iterator it = new_versions.begin(); it != new_versions.end(); it++) { LegionMap<VersionID,FieldMask>::aligned::iterator finder = version_numbers.find(it->first); if (finder == version_numbers.end()) version_numbers.insert(*it); else finder->second |= it->second; } Runtime::trigger_event(done_event, mutator.get_done_event()); // See if we need to make this the owner now if (!is_logical_owner()) { logical_owner_space = local_space; eq_state = MAPPING_STATE; } } else { // We're not the owner so we need to forward this on Serializer rez; // No RezCheck in case of forwarding rez.serialize(did); rez.serialize(done_event); rez.serialize<bool>(false); // initial refinement rez.serialize(new_views.size()); for (FieldMaskSet<LogicalView>::const_iterator it = new_views.begin(); it != new_views.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<size_t>(new_reductions.size()); for (std::map<unsigned,std::vector<ReductionView*> >::const_iterator rit = new_reductions.begin(); rit != new_reductions.end(); rit++) { rez.serialize(rit->first); rez.serialize(rit->second.size()); for (std::vector<ReductionView*>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) rez.serialize((*it)->did); } rez.serialize(new_restrictions.size()); for (FieldMaskSet<InstanceView>::const_iterator it = new_restrictions.begin(); it != new_restrictions.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize(new_versions.size()); for (LegionMap<VersionID,FieldMask>::aligned::const_iterator it = new_versions.begin(); it != new_versions.end(); it++) { rez.serialize(it->first); rez.serialize(it->second); } runtime->send_equivalence_set_remote_refinement( logical_owner_space, rez); } } //-------------------------------------------------------------------------- void EquivalenceSet::pack_migration(Serializer &rez, RtEvent done_migration) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(pending_refinements.empty()); #endif std::map<LogicalView*,unsigned> *late_references = NULL; // Pack the valid instances rez.serialize<size_t>(valid_instances.size()); if (!valid_instances.empty()) { for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); if (late_references == NULL) late_references = new std::map<LogicalView*,unsigned>(); (*late_references)[it->first] = 1; } valid_instances.clear(); } // Pack the reduction instances rez.serialize<size_t>(reduction_instances.size()); if (!reduction_instances.empty()) { for (std::map<unsigned,std::vector<ReductionView*> >::const_iterator rit = reduction_instances.begin(); rit != reduction_instances.end(); rit++) { rez.serialize(rit->first); rez.serialize<size_t>(rit->second.size()); for (std::vector<ReductionView*>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize((*it)->did); if (late_references == NULL) late_references = new std::map<LogicalView*,unsigned>(); (*late_references)[*it] = 1; } } reduction_instances.clear(); reduction_fields.clear(); } // Pack the restricted instances rez.serialize<size_t>(restricted_instances.size()); if (!restricted_instances.empty()) { rez.serialize(restricted_fields); for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); if (late_references == NULL) late_references = new std::map<LogicalView*,unsigned>(); std::map<LogicalView*,unsigned>::iterator finder = late_references->find(it->first); if (finder == late_references->end()) (*late_references)[it->first] = 1; else finder->second += 1; } restricted_instances.clear(); restricted_fields.clear(); } // Pack the version numbers rez.serialize<size_t>(version_numbers.size()); if (!version_numbers.empty()) { for (LegionMap<VersionID,FieldMask>::aligned::const_iterator it = version_numbers.begin(); it != version_numbers.end(); it++) { rez.serialize(it->first); rez.serialize(it->second); } version_numbers.clear(); } // Pack the update guards rez.serialize<size_t>(update_guards.size()); if (!update_guards.empty()) { for (FieldMaskSet<CopyFillGuard>::const_iterator it = update_guards.begin(); it != update_guards.end(); it++) { it->first->pack_guard(rez); rez.serialize(it->second); } update_guards.clear(); } // Pack subsets // We're only allowed to keep the complete subsets on this node // so we need to filter anything that isn't fully refined // We still keep references to the equivalence sets though // so that they aren't deleted FieldMask incomplete_refinements; if (!unrefined_remainders.empty()) incomplete_refinements = unrefined_remainders.get_valid_mask(); if (!disjoint_partition_refinements.empty()) incomplete_refinements |= disjoint_partition_refinements.get_valid_mask(); rez.serialize<size_t>(subsets.size()); for (FieldMaskSet<EquivalenceSet>::iterator it = subsets.begin(); it != subsets.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); if (!!incomplete_refinements) it.filter(incomplete_refinements); } // Tighten the valid mask for future analyses if (!!incomplete_refinements) subsets.tighten_valid_mask(); // No need to clear subsets since we can still maintain a copy of it // Pack remote subsets rez.serialize<size_t>(remote_subsets.size()); if (!remote_subsets.empty()) { for (std::set<AddressSpaceID>::const_iterator it = remote_subsets.begin(); it != remote_subsets.end(); it++) rez.serialize(*it); remote_subsets.clear(); } // Pack unrefined remainders rez.serialize<size_t>(unrefined_remainders.size()); if (!unrefined_remainders.empty()) { std::vector<IndexSpaceExpression*> *references = new std::vector<IndexSpaceExpression*>(); references->reserve(unrefined_remainders.size()); for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = unrefined_remainders.begin(); it != unrefined_remainders.end(); it++) { it->first->pack_expression(rez, logical_owner_space); rez.serialize(it->second); references->push_back(it->first); } unrefined_remainders.clear(); // Defer removing the references on these expressions until // the migration has been done DeferRemoveRefArgs args(references); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_WORK_PRIORITY, done_migration); } // Pack disjoint partition refinements rez.serialize<size_t>(disjoint_partition_refinements.size()); if (!disjoint_partition_refinements.empty()) { for (FieldMaskSet<DisjointPartitionRefinement>::const_iterator it = disjoint_partition_refinements.begin(); it != disjoint_partition_refinements.end(); it++) { rez.serialize(it->first->partition->handle); const std::map<IndexSpaceNode*,EquivalenceSet*> &children = it->first->get_children(); rez.serialize<size_t>(children.size()); for (std::map<IndexSpaceNode*,EquivalenceSet*>::const_iterator cit = children.begin(); cit != children.end(); cit++) { rez.serialize(cit->first->handle); rez.serialize(cit->second->did); } rez.serialize(it->second); delete it->first; } disjoint_partition_refinements.clear(); } // Pack the user samples and counts rez.serialize(migration_index); for (unsigned idx = 0; idx < MIGRATION_EPOCHS; idx++) { std::vector<std::pair<AddressSpaceID,unsigned> > &samples = user_samples[idx]; rez.serialize<size_t>(samples.size()); for (std::vector<std::pair<AddressSpaceID,unsigned> >::const_iterator it = samples.begin(); it != samples.end(); it++) { rez.serialize(it->first); rez.serialize(it->second); } samples.clear(); } if (late_references != NULL) { // Launch a task to remove the references once the migration is done RemoteRefTaskArgs args(this->did, RtUserEvent::NO_RT_USER_EVENT, false/*add*/, late_references); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_WORK_PRIORITY, done_migration); } } //-------------------------------------------------------------------------- void EquivalenceSet::unpack_migration(Deserializer &derez, AddressSpaceID source, RtUserEvent done_event) //-------------------------------------------------------------------------- { // All the preconditions before we can make this the owner std::set<RtEvent> owner_preconditions; AutoLock eq(eq_lock); #ifdef DEBUG_LEGION assert(!is_logical_owner()); assert(valid_instances.empty()); assert(reduction_instances.empty()); assert(restricted_instances.empty()); assert(version_numbers.empty()); assert(update_guards.empty()); assert(pending_refinements.empty()); assert(remote_subsets.empty()); assert(unrefined_remainders.empty()); assert(disjoint_partition_refinements.empty()); #endif size_t num_valid_insts; derez.deserialize(num_valid_insts); for (unsigned idx = 0; idx < num_valid_insts; idx++) { DistributedID valid_did; derez.deserialize(valid_did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(valid_did, ready); FieldMask mask; derez.deserialize(mask); valid_instances.insert(view, mask); if (ready.exists()) owner_preconditions.insert(ready); } size_t num_reduc_fields; derez.deserialize(num_reduc_fields); for (unsigned idx1 = 0; idx1 < num_reduc_fields; idx1++) { unsigned fidx; derez.deserialize(fidx); reduction_fields.set_bit(fidx); size_t num_reduc_insts; derez.deserialize(num_reduc_insts); std::vector<ReductionView*> &reduc_views = reduction_instances[fidx]; for (unsigned idx2 = 0; idx2 < num_reduc_insts; idx2++) { DistributedID reduc_did; derez.deserialize(reduc_did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(reduc_did, ready); ReductionView *reduc_view = static_cast<ReductionView*>(view); reduc_views.push_back(reduc_view); if (ready.exists()) owner_preconditions.insert(ready); } } size_t num_restrict_insts; derez.deserialize(num_restrict_insts); if (num_restrict_insts > 0) { derez.deserialize(restricted_fields); for (unsigned idx = 0; idx < num_restrict_insts; idx++) { DistributedID valid_did; derez.deserialize(valid_did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(valid_did, ready); InstanceView *inst_view = static_cast<InstanceView*>(view); FieldMask mask; derez.deserialize(mask); restricted_instances.insert(inst_view, mask); if (ready.exists()) owner_preconditions.insert(ready); } } size_t num_versions; derez.deserialize(num_versions); for (unsigned idx = 0; idx < num_versions; idx++) { VersionID vid; derez.deserialize(vid); derez.deserialize(version_numbers[vid]); } size_t num_guards; derez.deserialize(num_guards); for (unsigned idx = 0; idx < num_guards; idx++) { CopyFillGuard *guard = CopyFillGuard::unpack_guard(derez, runtime,this); FieldMask guard_mask; derez.deserialize(guard_mask); if (guard != NULL) update_guards.insert(guard, guard_mask); } FieldMaskSet<EquivalenceSet> new_subsets; size_t num_subsets; derez.deserialize(num_subsets); for (unsigned idx = 0; idx < num_subsets; idx++) { DistributedID subset_did; derez.deserialize(subset_did); RtEvent ready; EquivalenceSet *subset = runtime->find_or_request_equivalence_set(subset_did, ready); if (ready.exists()) owner_preconditions.insert(ready); FieldMask subset_mask; derez.deserialize(subset_mask); new_subsets.insert(subset, subset_mask); } size_t num_remote_subsets; derez.deserialize(num_remote_subsets); for (unsigned idx = 0; idx < num_remote_subsets; idx++) { AddressSpaceID remote; derez.deserialize(remote); remote_subsets.insert(remote); } size_t num_unrefined_remainders; derez.deserialize(num_unrefined_remainders); for (unsigned idx = 0; idx < num_unrefined_remainders; idx++) { IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez,runtime->forest,source); FieldMask mask; derez.deserialize(mask); if (unrefined_remainders.insert(expr, mask)) expr->add_expression_reference(); } size_t num_disjoint_refinements; derez.deserialize(num_disjoint_refinements); for (unsigned idx1 = 0; idx1 < num_disjoint_refinements; idx1++) { IndexPartition handle; derez.deserialize(handle); IndexPartNode *part = runtime->forest->get_node(handle); DisjointPartitionRefinement *dis = new DisjointPartitionRefinement(this, part, owner_preconditions); size_t num_children; derez.deserialize(num_children); for (unsigned idx2 = 0; idx2 < num_children; idx2++) { IndexSpace child; derez.deserialize(child); IndexSpaceNode *node = runtime->forest->get_node(child); DistributedID child_did; derez.deserialize(child_did); RtEvent ready; dis->add_child(node, runtime->find_or_request_equivalence_set(child_did, ready)); if (ready.exists()) owner_preconditions.insert(ready); } FieldMask mask; derez.deserialize(mask); disjoint_partition_refinements.insert(dis, mask); } derez.deserialize(migration_index); for (unsigned idx1 = 0; idx1 < MIGRATION_EPOCHS; idx1++) { size_t num_samples; derez.deserialize(num_samples); if (num_samples > 0) { std::vector<std::pair<AddressSpaceID,unsigned> > &samples = user_samples[idx1]; samples.resize(num_samples); for (unsigned idx2 = 0; idx2 < num_samples; idx2++) { derez.deserialize(samples[idx2].first); derez.deserialize(samples[idx2].second); } } } // If there are any pending anayses we need to wait for them to finish if (pending_analyses > 0) { #ifdef DEBUG_LEGION assert(!waiting_event.exists()); #endif waiting_event = Runtime::create_rt_user_event(); owner_preconditions.insert(waiting_event); } if (!owner_preconditions.empty()) { const RtEvent pre = Runtime::merge_events(owner_preconditions); if (pre.exists() && !pre.has_triggered()) { // We need to defer this until later FieldMaskSet<EquivalenceSet> *owner_subsets = new FieldMaskSet<EquivalenceSet>(); owner_subsets->swap(new_subsets); // Defer the call to make this the owner until the event triggers DeferMakeOwnerArgs args(this, owner_subsets, done_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, pre); return; } } // If we fall through then we get to do the add now make_owner(&new_subsets, done_event, false/*need lock*/); } //-------------------------------------------------------------------------- bool EquivalenceSet::make_owner(FieldMaskSet<EquivalenceSet> *new_subsets, RtUserEvent done_event, bool need_lock) //-------------------------------------------------------------------------- { if (need_lock) { AutoLock eq(eq_lock); return make_owner(new_subsets, done_event, false/*need lock*/); } #ifdef DEBUG_LEGION assert(!is_logical_owner()); #endif // See if we need to defer this because there are outstanding analyses if (pending_analyses > 0) { #ifdef DEBUG_LEGION assert(!waiting_event.exists()); #endif waiting_event = Runtime::create_rt_user_event(); DeferMakeOwnerArgs args(this, new_subsets, done_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, waiting_event); return false; } // Now we can mark that we are the logical owner logical_owner_space = local_space; // If we were waiting for a valid copy of the subsets we now have it if (eq_state == PENDING_VALID_STATE) { #ifdef DEBUG_LEGION assert(transition_event.exists()); #endif // We can trigger this transition event now that we have a valid // copy of the subsets (we are the logical owner) Runtime::trigger_event(transition_event); transition_event = RtUserEvent::NO_RT_USER_EVENT; } eq_state = MAPPING_STATE; LocalReferenceMutator mutator; // Add references to all the views that we've loaded for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) it->first->add_nested_valid_ref(did, &mutator); for (std::map<unsigned,std::vector<ReductionView*> >::const_iterator it1 = reduction_instances.begin(); it1 != reduction_instances.end(); it1++) for (std::vector<ReductionView*>::const_iterator it2 = it1->second.begin(); it2 != it1->second.end(); it2++) (*it2)->add_nested_valid_ref(did, &mutator); for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end(); it++) it->first->add_nested_valid_ref(did, &mutator); // Update the subsets now that we are officially the owner for (FieldMaskSet<EquivalenceSet>::const_iterator it = new_subsets->begin(); it != new_subsets->end(); it++) if (subsets.insert(it->first, it->second)) it->first->add_nested_resource_ref(did); Runtime::trigger_event(done_event, mutator.get_done_event()); return true; } //-------------------------------------------------------------------------- void EquivalenceSet::update_owner(const AddressSpaceID new_logical_owner) //-------------------------------------------------------------------------- { AutoLock eq(eq_lock); #ifdef DEBUG_LEGION // We should never be told that we're the new owner this way assert(new_logical_owner != local_space); #endif // If we are the owner then we know this update is stale so ignore it if (!is_logical_owner()) logical_owner_space = new_logical_owner; } //-------------------------------------------------------------------------- FieldMask EquivalenceSet::is_restricted(InstanceView *view) //-------------------------------------------------------------------------- { AutoLock eq(eq_lock,1,false/*exclusive*/); FieldMask mask; FieldMaskSet<InstanceView>::const_iterator finder = restricted_instances.find(view); if (finder != restricted_instances.end()) mask = finder->second; return mask; } //-------------------------------------------------------------------------- void EquivalenceSet::initialize_set(const RegionUsage &usage, const FieldMask &user_mask, const bool restricted, const InstanceSet &sources, const std::vector<InstanceView*> &corresponding, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(is_logical_owner()); assert(sources.size() == corresponding.size()); #endif WrapperReferenceMutator mutator(applied_events); AutoLock eq(eq_lock); if (IS_REDUCE(usage)) { #ifdef DEBUG_LEGION // Reduction-only should always be restricted for now // Could change if we started issuing reduction close // operations at the end of a context assert(restricted); #endif // Since these are restricted, we'll make these the actual // target logical instances and record them as restricted // instead of recording them as reduction instances for (unsigned idx = 0; idx < sources.size(); idx++) { const FieldMask &view_mask = sources[idx].get_valid_fields(); InstanceView *view = corresponding[idx]; FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(view); if (finder == valid_instances.end()) { valid_instances.insert(view, view_mask); view->add_nested_valid_ref(did, &mutator); } else finder.merge(view_mask); // Always restrict reduction-only users since we know the data // is going to need to be flushed anyway FieldMaskSet<InstanceView>::iterator restricted_finder = restricted_instances.find(view); if (restricted_finder == restricted_instances.end()) { restricted_instances.insert(view, view_mask); view->add_nested_valid_ref(did, &mutator); } else restricted_finder.merge(view_mask); } } else { for (unsigned idx = 0; idx < sources.size(); idx++) { const FieldMask &view_mask = sources[idx].get_valid_fields(); InstanceView *view = corresponding[idx]; #ifdef DEBUG_LEGION assert(!view->is_reduction_view()); #endif FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(view); if (finder == valid_instances.end()) { valid_instances.insert(view, view_mask); view->add_nested_valid_ref(did, &mutator); } else finder.merge(view_mask); // If this is restricted then record it if (restricted) { FieldMaskSet<InstanceView>::iterator restricted_finder = restricted_instances.find(view); if (restricted_finder == restricted_instances.end()) { restricted_instances.insert(view, view_mask); view->add_nested_valid_ref(did, &mutator); } else restricted_finder.merge(view_mask); } } } // Update any restricted fields if (restricted) restricted_fields |= user_mask; // Set the version numbers too version_numbers[init_version] |= user_mask; } //-------------------------------------------------------------------------- void EquivalenceSet::find_valid_instances(ValidInstAnalysis &analysis, FieldMask user_mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, user_mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, user_mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = user_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); user_mask -= non_subset; if (!user_mask) return; } } // Otherwise we fall through and record our subsets } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(user_mask)) { check_for_unrefined_remainder(eq, user_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & user_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Update the user mask and the stale_mask if there is one user_mask -= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->find_valid_instances(analysis, it->second, deferral_events, applied_events, false/*original*/); eq.reacquire(); // Return if our user mask is empty if (!user_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif // Lock the analysis so we can perform updates here AutoLock a_lock(analysis); if (analysis.redop != 0) { // Iterate over all the fields int fidx = user_mask.find_first_set(); while (fidx >= 0) { std::map<unsigned,std::vector<ReductionView*> >::const_iterator current = reduction_instances.find(fidx); if (current != reduction_instances.end()) { FieldMask local_mask; local_mask.set_bit(fidx); for (std::vector<ReductionView*>::const_reverse_iterator it = current->second.rbegin(); it != current->second.rend(); it++) { ReductionManager *manager = (*it)->get_manager()->as_reduction_manager(); if (manager->redop != analysis.redop) break; analysis.record_instance(*it, local_mask); } } fidx = user_mask.find_next_set(fidx+1); } } else { for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { if (!it->first->is_instance_view()) continue; const FieldMask overlap = it->second & user_mask; if (!overlap) continue; analysis.record_instance(it->first->as_instance_view(), overlap); } } if (has_restrictions(user_mask)) analysis.record_restriction(); } //-------------------------------------------------------------------------- void EquivalenceSet::find_invalid_instances(InvalidInstAnalysis &analysis, FieldMask user_mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, user_mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, user_mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = user_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); user_mask -= non_subset; if (!user_mask) return; } } // Otherwise we fall through and record our subsets } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(user_mask)) { check_for_unrefined_remainder(eq, user_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & user_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Update the user mask and the stale_mask if there is one user_mask -= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->find_invalid_instances(analysis, it->second, deferral_events, applied_events, false/*original*/); eq.reacquire(); // Return if our user mask is empty if (!user_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif // Lock the analysis so we can perform updates here AutoLock a_lock(analysis); // See if our instances are valid for any fields we're traversing // and if not record them for (FieldMaskSet<InstanceView>::const_iterator it = analysis.valid_instances.begin(); it != analysis.valid_instances.end(); it++) { FieldMask invalid_mask = it->second & user_mask; if (!invalid_mask) continue; FieldMaskSet<LogicalView>::const_iterator finder = valid_instances.find(it->first); if (finder != valid_instances.end()) { invalid_mask -= finder->second; if (!!invalid_mask) analysis.record_instance(it->first, invalid_mask); } else // Not valid for any of them so record it analysis.record_instance(it->first, invalid_mask); } } //-------------------------------------------------------------------------- void EquivalenceSet::defer_traversal(AutoTryLock &eq, PhysicalAnalysis &analysis, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, const bool already_deferred, const bool cached_set) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!eq.has_lock()); #endif // See if we've already deferred this or not if (!already_deferred) { const RtUserEvent deferral_event = Runtime::create_rt_user_event(); const RtEvent precondition = chain_deferral_events(deferral_event); analysis.defer_traversal(precondition, this, mask, deferral_events, applied_events, cached_set, deferral_event); } else analysis.defer_traversal(eq.try_next(), this, mask, deferral_events, applied_events, cached_set); } //-------------------------------------------------------------------------- void EquivalenceSet::update_set(UpdateAnalysis &analysis, FieldMask user_mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *remove_mask, // can be NULL const bool cached_set/*=true*/, const bool already_deferred/*=false*/) //-------------------------------------------------------------------------- { // Try to get the lock, if we don't defer the traversal AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, user_mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!cached_set && analysis.update_alt_sets(this, user_mask)) return; if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, user_mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = user_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); user_mask -= non_subset; if (!user_mask) return; } } // Otherwise we fall through and record our subsets } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(user_mask)) { check_for_unrefined_remainder(eq, user_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & user_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Remove ourselves if we recursed if (!cached_set) analysis.filter_alt_sets(this, to_traverse.get_valid_mask()); // Update the user mask and the remove_mask if there is one user_mask -= to_traverse.get_valid_mask(); if (remove_mask != NULL) *remove_mask |= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->update_set(analysis, it->second, deferral_events, applied_events, NULL/*remove mask*/, false/*original set*/); eq.reacquire(); // Return if our user mask is empty if (!user_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif WrapperReferenceMutator mutator(applied_events); // Now that we're ready to perform the analysis // we need to lock the analysis AutoLock a_lock(analysis); // Check for any uninitialized data // Don't report uninitialized warnings for empty equivalence classes if (analysis.check_initialized && !set_expr->is_empty()) { const FieldMask uninit = user_mask - valid_instances.get_valid_mask(); if (!!uninit) analysis.record_uninitialized(uninit, applied_events); } if (analysis.output_aggregator != NULL) analysis.output_aggregator->clear_update_fields(); if (IS_REDUCE(analysis.usage)) { // Reduction-only // We only record reductions if the set expression is not empty // as we can't guarantee the reductions will ever be read for // empty equivalence sets which can lead to leaked instances if (!set_expr->is_empty()) { // Record the reduction instances for (unsigned idx = 0; idx < analysis.target_views.size(); idx++) { ReductionView *red_view = analysis.target_views[idx]->as_reduction_view(); #ifdef DEBUG_LEGION assert(red_view->get_redop() == analysis.usage.redop); #endif const FieldMask &update_fields = analysis.target_instances[idx].get_valid_fields(); int fidx = update_fields.find_first_set(); while (fidx >= 0) { std::vector<ReductionView*> &field_views = reduction_instances[fidx]; red_view->add_nested_valid_ref(did, &mutator); field_views.push_back(red_view); fidx = update_fields.find_next_set(fidx+1); } } // Flush any restricted fields if (!!restricted_fields) { const FieldMask reduce_mask = user_mask & restricted_fields; if (!!reduce_mask) apply_reductions(reduce_mask, analysis.output_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.index, true/*track events*/); // No need to record that we applied the reductions, we'll // discover that when we collapse the single/multi-reduce state reduction_fields |= (user_mask - restricted_fields); } else reduction_fields |= user_mask; } } else if (IS_WRITE(analysis.usage) && IS_DISCARD(analysis.usage)) { // Write-only // Filter any reductions that we no longer need const FieldMask reduce_filter = reduction_fields & user_mask; if (!!reduce_filter) filter_reduction_instances(reduce_filter); // Filter any normal instances that will be overwritten const FieldMask non_restricted = user_mask - restricted_fields; if (!!non_restricted) { filter_valid_instances(non_restricted); // Record any non-restricted instances record_instances(non_restricted, analysis.target_instances, analysis.target_views, mutator); } // Issue copy-out copies for any restricted fields if (!!restricted_fields) { const FieldMask restricted_mask = user_mask & restricted_fields; if (!!restricted_mask) copy_out(restricted_mask, analysis.target_instances, analysis.target_views, analysis.op, analysis.index, analysis.output_aggregator); } // Advance our version numbers advance_version_numbers(user_mask); } else if (IS_READ_ONLY(analysis.usage) && !update_guards.empty() && !(user_mask * update_guards.get_valid_mask())) { // If we're doing read-only mode, get the set of events that // we need to wait for before we can do our registration, this // ensures that we serialize read-only operations correctly // In order to avoid deadlock we have to make different copy fill // aggregators for each of the different fields of prior updates FieldMask remainder_mask = user_mask; LegionVector<std::pair<CopyFillAggregator*,FieldMask> >::aligned to_add; for (FieldMaskSet<CopyFillGuard>::iterator it = update_guards.begin(); it != update_guards.end(); it++) { const FieldMask guard_mask = remainder_mask & it->second; if (!guard_mask) continue; // No matter what record our dependences on the prior guards #ifdef NON_AGGRESSIVE_AGGREGATORS const RtEvent guard_event = it->first->effects_applied; #else const RtEvent guard_event = (analysis.original_source == local_space) ? it->first->guard_postcondition : it->first->effects_applied; #endif analysis.guard_events.insert(guard_event); CopyFillAggregator *input_aggregator = NULL; // See if we have an input aggregator that we can use now std::map<RtEvent,CopyFillAggregator*>::const_iterator finder = analysis.input_aggregators.find(guard_event); if (finder != analysis.input_aggregators.end()) { input_aggregator = finder->second; if (input_aggregator != NULL) input_aggregator->clear_update_fields(); } // Use this to see if any new updates are recorded update_set_internal(input_aggregator, guard_event, analysis.op, analysis.index, analysis.usage, guard_mask, analysis.target_instances, analysis.target_views, applied_events, analysis.record_valid); // If we did any updates record ourselves as the new guard here if ((input_aggregator != NULL) && ((finder == analysis.input_aggregators.end()) || input_aggregator->has_update_fields())) { #ifndef NON_AGGRESSIVE_AGGREGATORS // We also have to chain effects in this case input_aggregator->record_reference_mutation_effect( it->first->effects_applied); #endif if (finder == analysis.input_aggregators.end()) analysis.input_aggregators[guard_event] = input_aggregator; // Record this as a guard for later operations to_add.resize(to_add.size() + 1); std::pair<CopyFillAggregator*,FieldMask> &back = to_add.back(); const FieldMask &update_mask = input_aggregator->get_update_fields(); back.first = input_aggregator; back.second = update_mask; #ifdef DEBUG_LEGION if (!input_aggregator->record_guard_set(this)) assert(false); #else input_aggregator->record_guard_set(this); #endif // Remove the current guard since it doesn't matter anymore it.filter(update_mask); } remainder_mask -= guard_mask; if (!remainder_mask) break; } if (!to_add.empty()) { for (LegionVector<std::pair<CopyFillAggregator*,FieldMask> >:: aligned::const_iterator it = to_add.begin(); it != to_add.end(); it++) { #ifdef DEBUG_LEGION assert(it->second * refining_fields); #endif update_guards.insert(it->first, it->second); } } // If we have unguarded fields we can easily do thos if (!!remainder_mask) { CopyFillAggregator *input_aggregator = NULL; // See if we have an input aggregator that we can use now std::map<RtEvent,CopyFillAggregator*>::const_iterator finder = analysis.input_aggregators.find(RtEvent::NO_RT_EVENT); if (finder != analysis.input_aggregators.end()) { input_aggregator = finder->second; if (input_aggregator != NULL) input_aggregator->clear_update_fields(); } update_set_internal(input_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.index, analysis.usage, remainder_mask, analysis.target_instances, analysis.target_views, applied_events, analysis.record_valid); // If we made the input aggregator then store it if ((input_aggregator != NULL) && ((finder == analysis.input_aggregators.end()) || input_aggregator->has_update_fields())) { analysis.input_aggregators[RtEvent::NO_RT_EVENT] = input_aggregator; #ifdef DEBUG_LEGION assert(input_aggregator->get_update_fields() * refining_fields); #endif // Record this as a guard for later operations update_guards.insert(input_aggregator, input_aggregator->get_update_fields()); #ifdef DEBUG_LEGION if (!input_aggregator->record_guard_set(this)) assert(false); #else input_aggregator->record_guard_set(this); #endif } } } else { // Read-write or read-only case // Read-only case if there are no guards CopyFillAggregator *input_aggregator = NULL; // See if we have an input aggregator that we can use now std::map<RtEvent,CopyFillAggregator*>::const_iterator finder = analysis.input_aggregators.find(RtEvent::NO_RT_EVENT); if (finder != analysis.input_aggregators.end()) { input_aggregator = finder->second; if (input_aggregator != NULL) input_aggregator->clear_update_fields(); } update_set_internal(input_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.index, analysis.usage, user_mask, analysis.target_instances, analysis.target_views, applied_events, analysis.record_valid); if (IS_WRITE(analysis.usage)) { advance_version_numbers(user_mask); // Issue copy-out copies for any restricted fields if we wrote stuff const FieldMask restricted_mask = restricted_fields & user_mask; if (!!restricted_mask) copy_out(restricted_mask, analysis.target_instances, analysis.target_views, analysis.op, analysis.index, analysis.output_aggregator); } // If we made the input aggregator then store it if ((input_aggregator != NULL) && ((finder == analysis.input_aggregators.end()) || input_aggregator->has_update_fields())) { analysis.input_aggregators[RtEvent::NO_RT_EVENT] = input_aggregator; #ifdef DEBUG_LEGION assert(input_aggregator->get_update_fields() * refining_fields); #endif // Record this as a guard for later operations update_guards.insert(input_aggregator, input_aggregator->get_update_fields()); #ifdef DEBUG_LEGION if (!input_aggregator->record_guard_set(this)) assert(false); #else input_aggregator->record_guard_set(this); #endif } } if ((analysis.output_aggregator != NULL) && analysis.output_aggregator->has_update_fields()) { #ifdef DEBUG_LEGION assert(analysis.output_aggregator->get_update_fields() * refining_fields); #endif update_guards.insert(analysis.output_aggregator, analysis.output_aggregator->get_update_fields()); #ifdef DEBUG_LEGION if (!analysis.output_aggregator->record_guard_set(this)) assert(false); #else analysis.output_aggregator->record_guard_set(this); #endif } check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::update_set_internal( CopyFillAggregator *&input_aggregator, const RtEvent guard_event, Operation *op, const unsigned index, const RegionUsage &usage, const FieldMask &user_mask, const InstanceSet &target_instances, const std::vector<InstanceView*> &target_views, std::set<RtEvent> &applied_events, const bool record_valid) //-------------------------------------------------------------------------- { // Read-write or read-only // Check for any copies from normal instances first issue_update_copies_and_fills(input_aggregator, guard_event, op, index, false/*track*/, user_mask, target_instances, target_views, set_expr); // Get the set of fields to filter, any for which we're about // to apply pending reductions or overwite, except those that // are restricted const FieldMask reduce_mask = reduction_fields & user_mask; const FieldMask restricted_mask = restricted_fields & user_mask; const bool is_write = IS_WRITE(usage); FieldMask filter_mask = is_write ? user_mask : reduce_mask; if (!!restricted_mask) filter_mask -= restricted_mask; if (!!filter_mask) filter_valid_instances(filter_mask); WrapperReferenceMutator mutator(applied_events); // Save the instances if they are not restricted // Otherwise if they are restricted then the restricted instances // are already listed as the valid views so there's nothing more // for us to have to do if (!!restricted_mask) { const FieldMask non_restricted = user_mask - restricted_fields; if (!!non_restricted) record_instances(non_restricted, target_instances, target_views, mutator); } else if (record_valid) record_instances(user_mask, target_instances, target_views, mutator); // Read-only instances that perform reductions still need to be // tracked for these fields because it is where the reductions // are to be applied else if (!!reduce_mask) record_instances(reduce_mask, target_instances, target_views, mutator); // Next check for any reductions that need to be applied if (!!reduce_mask) apply_reductions(reduce_mask, input_aggregator, guard_event, op, index, false/*track events*/); } //-------------------------------------------------------------------------- void EquivalenceSet::check_for_migration(PhysicalAnalysis &analysis, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { #ifndef DISABLE_EQUIVALENCE_SET_MIGRATION #ifdef DEBUG_LEGION assert(is_logical_owner()); #endif const AddressSpaceID eq_source = analysis.original_source; // Record our user in the set of previous users bool found = false; std::vector<std::pair<AddressSpaceID,unsigned> > &current_samples = user_samples[migration_index]; for (std::vector<std::pair<AddressSpaceID,unsigned> >::iterator it = current_samples.begin(); it != current_samples.end(); it++) { if (it->first != eq_source) continue; found = true; it->second++; break; } if (!found) current_samples.push_back( std::pair<AddressSpaceID,unsigned>(eq_source,1)); // Increase the sample count and if we haven't done enough // for a test then we can return and keep going if (++sample_count < SAMPLES_PER_MIGRATION_TEST) { // Check to see if the request bounced off a stale owner // and we should send the update message if ((eq_source != analysis.previous) && (eq_source != local_space) && (eq_source != logical_owner_space)) { RtUserEvent notification_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(logical_owner_space); rez.serialize(notification_event); } runtime->send_equivalence_set_owner_update(eq_source, rez); applied_events.insert(notification_event); } return; } // Issue a warning and don't migrate if we hit this case if (current_samples.size() == SAMPLES_PER_MIGRATION_TEST) { REPORT_LEGION_WARNING(LEGION_WARNING_LARGE_EQUIVALENCE_SET_NODE_USAGE, "Internal runtime performance warning: equivalence set %lld has " "%zd different users which is the same as the sampling rate of " "%d. Please report this application use case to the Legion " "developers mailing list.", did, current_samples.size(), SAMPLES_PER_MIGRATION_TEST) // Reset the data structures for the next run current_samples.clear(); sample_count = 0; return; } // Sort the current samples so that they are in order for // single epoch cases, for multi-epoch cases they will be // sorted by the summary computation below if ((MIGRATION_EPOCHS == 1) && (current_samples.size() > 1)) std::sort(current_samples.begin(), current_samples.end()); // Increment this for the next pass migration_index = (migration_index + 1) % MIGRATION_EPOCHS; // Don't do any migrations if we have any pending refinements // or we have outstanding analyses that prevent it for now if (!pending_refinements.empty() || !!refining_fields || (pending_analyses > 0)) { // Reset the data structures for the next run sample_count = 0; user_samples[migration_index].clear(); return; } std::vector<std::pair<AddressSpaceID,unsigned> > &next_samples = user_samples[migration_index]; if (MIGRATION_EPOCHS > 1) { // Compute the summary from all the epochs into the epoch // that we are about to clear std::map<AddressSpaceID,unsigned> summary( next_samples.begin(), next_samples.end()); for (unsigned idx = 1; idx < MIGRATION_EPOCHS; idx++) { const std::vector<std::pair<AddressSpaceID,unsigned> > &other_samples = user_samples[(migration_index + idx) % MIGRATION_EPOCHS]; for (std::vector<std::pair<AddressSpaceID,unsigned> >::const_iterator it = other_samples.begin(); it != other_samples.end(); it++) { std::map<AddressSpaceID,unsigned>::iterator finder = summary.find(it->first); if (finder == summary.end()) summary.insert(*it); else finder->second += it->second; } } next_samples.clear(); next_samples.insert(next_samples.begin(),summary.begin(),summary.end()); } AddressSpaceID new_logical_owner = logical_owner_space; #ifdef DEBUG_LEGION assert(!next_samples.empty()); #endif if (next_samples.size() > 1) { int logical_owner_count = -1; // Figure out which node(s) has/have the most uses // Make sure that the current owner node is sticky // if it is tied for the most uses unsigned max_count = next_samples[0].second; AddressSpaceID max_user = next_samples[0].first; for (unsigned idx = 1; idx < next_samples.size(); idx++) { const AddressSpaceID user = next_samples[idx].first; const unsigned user_count = next_samples[idx].second; if (user == logical_owner_space) logical_owner_count = user_count; if (user_count < max_count) continue; // This is the part where we guarantee stickiness if ((user_count == max_count) && (user != logical_owner_space)) continue; max_count = user_count; max_user = user; } if (logical_owner_count > 0) { if (logical_owner_space != max_user) { // If the logical owner is one of the current users then // we really better have a good reason to move this // equivalence set to a new node. For now the difference // between max_count and the current owner count has to // be greater than the number of nodes that we see participating // on this equivalence set. This heuristic should avoid // the ping-pong case even when our sampling rate does not // naturally align with the number of nodes participating if ((max_count - unsigned(logical_owner_count)) > next_samples.size()) new_logical_owner = max_user; } } else // If we didn't have the current logical owner then // just pick the maximum one new_logical_owner = max_user; } else // If all the requests came from the same node, send it there new_logical_owner = next_samples[0].first; // This always get reset here sample_count = 0; // Reset this for the next iteration next_samples.clear(); // See if we are actually going to do the migration if (logical_owner_space == new_logical_owner) { // No need to do the migration in this case // Check to see if the request bounced off a stale owner // and we should send the update message if ((eq_source != analysis.previous) && (eq_source != local_space) && (eq_source != logical_owner_space)) { RtUserEvent notification_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(logical_owner_space); rez.serialize(notification_event); } runtime->send_equivalence_set_owner_update(eq_source, rez); applied_events.insert(notification_event); } return; } // At this point we've decided to do the migration log_migration.info("Migrating Equivalence Set %llx from %d to %d", did, local_space, new_logical_owner); logical_owner_space = new_logical_owner; // Add ourselves and remove the new owner from remote subsets remote_subsets.insert(local_space); remote_subsets.erase(logical_owner_space); // We can switch our eq_state to being remote valid eq_state = VALID_STATE; RtUserEvent done_migration = Runtime::create_rt_user_event(); // Do the migration Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(done_migration); pack_migration(rez, done_migration); } runtime->send_equivalence_set_migration(logical_owner_space, rez); applied_events.insert(done_migration); #endif // DISABLE_EQUIVALENCE_SET MIGRATION } //-------------------------------------------------------------------------- void EquivalenceSet::acquire_restrictions(AcquireAnalysis &analysis, FieldMask acquire_mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *remove_mask, const bool cached_set/*=true*/, const bool already_deferred/*=false*/) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, acquire_mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!cached_set && analysis.update_alt_sets(this, acquire_mask)) return; if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, acquire_mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = acquire_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); acquire_mask -= non_subset; if (!acquire_mask) return; } } } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(acquire_mask)) { check_for_unrefined_remainder(eq, acquire_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & acquire_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Remove ourselves if we recursed if (!cached_set) analysis.filter_alt_sets(this, to_traverse.get_valid_mask()); // Update the acquire mask and the remove_mask if there is one acquire_mask -= to_traverse.get_valid_mask(); if (remove_mask != NULL) *remove_mask |= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->acquire_restrictions(analysis, it->second, deferral_events, applied_events, NULL/*remove mask*/, false/*original set*/); eq.reacquire(); // Return if our acquire user mask is empty if (!acquire_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif acquire_mask &= restricted_fields; if (!acquire_mask) return; // Now we need to lock the analysis if we're going to do this traversal AutoLock a_lock(analysis); for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end();it++) { const FieldMask overlap = acquire_mask & it->second; if (!overlap) continue; InstanceView *view = it->first->as_instance_view(); analysis.record_instance(view, overlap); } restricted_fields -= acquire_mask; check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::release_restrictions(ReleaseAnalysis &analysis, FieldMask release_mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *remove_mask, const bool cached_set/*=true*/, const bool already_deferred/*=false*/) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, release_mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!cached_set && analysis.update_alt_sets(this, release_mask)) return; if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, release_mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = release_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); release_mask -= non_subset; if (!release_mask) return; } } } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(release_mask)) { check_for_unrefined_remainder(eq, release_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & release_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Remove ourselves if we recursed if (!cached_set) analysis.filter_alt_sets(this, to_traverse.get_valid_mask()); // Update the release mask and the remove_mask if there is one release_mask -= to_traverse.get_valid_mask(); if (remove_mask != NULL) *remove_mask |= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->release_restrictions(analysis, it->second, deferral_events, applied_events, NULL/*remove mask*/, false/*original set*/); eq.reacquire(); // Return if ourt release mask is empty if (!release_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif // At this point we need to lock the analysis AutoLock a_lock(analysis); // Find our local restricted instances and views and record them InstanceSet local_instances; std::vector<InstanceView*> local_views; for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end();it++) { const FieldMask overlap = it->second & release_mask; if (!overlap) continue; InstanceView *view = it->first->as_instance_view(); local_instances.add_instance(InstanceRef(view->get_manager(), overlap)); local_views.push_back(view); analysis.record_instance(view, overlap); } if (analysis.release_aggregator != NULL) analysis.release_aggregator->clear_update_fields(); // Issue the updates issue_update_copies_and_fills(analysis.release_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.index, false/*track*/, release_mask, local_instances, local_views, set_expr); // Filter the valid views filter_valid_instances(release_mask); // Update with just the restricted instances WrapperReferenceMutator mutator(applied_events); record_instances(release_mask, local_instances, local_views, mutator); // See if we have any reductions to apply as well const FieldMask reduce_mask = release_mask & reduction_fields; if (!!reduce_mask) apply_reductions(reduce_mask, analysis.release_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.index, false/*track*/); // Add the fields back to the restricted ones restricted_fields |= release_mask; if ((analysis.release_aggregator != NULL) && analysis.release_aggregator->has_update_fields()) { #ifdef DEBUG_LEGION assert(analysis.release_aggregator->get_update_fields() * refining_fields); #endif update_guards.insert(analysis.release_aggregator, analysis.release_aggregator->get_update_fields()); #ifdef DEBUG_LEGION if (!analysis.release_aggregator->record_guard_set(this)) assert(false); #else analysis.release_aggregator->record_guard_set(this); #endif } check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::issue_across_copies(CopyAcrossAnalysis &analysis, FieldMask src_mask, IndexSpaceExpression *overlap, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { // No try lock since we can't defer this because of the overlap // Also, while you might think this could a read-only lock since // we're just reading meta-data, that's not quite right because // we need exclusive access to data structures in check_for_migration AutoLock eq(eq_lock); // No alt-set tracking here for copy across because we might // need to to traverse this multiple times with different expressions if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, src_mask, logical_owner_space, false/*cached set*/); return; } else { const FieldMask non_subset = src_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, false/*cached set*/); src_mask -= non_subset; if (!src_mask) return; } } } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(src_mask)) { check_for_unrefined_remainder(eq, src_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & src_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // No alt-set tracking here, see comment above // Update the release mask and the remove_mask if there is one src_mask -= to_traverse.get_valid_mask(); // No alt-set tracking here, see comment above for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) { IndexSpaceExpression *subset_overlap = runtime->forest-> intersect_index_spaces(it->first->set_expr, overlap); if (subset_overlap->is_empty()) continue; it->first->issue_across_copies(analysis, it->second, subset_overlap, deferral_events, applied_events); } eq.reacquire(); // Return if ourt source mask is empty if (!src_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); assert(IS_READ_ONLY(analysis.src_usage)); #endif // We need to lock the analysis at this point AutoLock a_lock(analysis); // Check for any uninitialized fields const FieldMask uninit = src_mask - valid_instances.get_valid_mask(); if (!!uninit) analysis.record_uninitialized(uninit, applied_events); // TODO: Handle the case where we are predicated if (analysis.pred_guard.exists()) assert(false); // See if there are any other predicate guard fields that we need // to have as preconditions before applying our owner updates if (!update_guards.empty() && !(src_mask * update_guards.get_valid_mask())) { for (FieldMaskSet<CopyFillGuard>::iterator it = update_guards.begin(); it != update_guards.end(); it++) { if (src_mask * it->second) continue; // No matter what record our dependences on the prior guards #ifdef NON_AGGRESSIVE_AGGREGATORS const RtEvent guard_event = it->first->effects_applied; #else const RtEvent guard_event = (analysis.original_source == local_space) ? it->first->guard_postcondition : it->first->effects_applied; #endif analysis.guard_events.insert(guard_event); } } // At this point we know we're going to need an aggregator since // this is an across copy and we have to be doing updates CopyFillAggregator *across_aggregator = analysis.get_across_aggregator(); if (!analysis.perfect) { // The general case where fields don't align regardless of // whether we are doing a reduction across or not #ifdef DEBUG_LEGION assert(!analysis.src_indexes.empty()); assert(!analysis.dst_indexes.empty()); assert(analysis.src_indexes.size() == analysis.dst_indexes.size()); assert(analysis.across_helpers.size() == analysis.target_instances.size()); #endif // We need to figure out how to issue these copies ourself since // we need to map from one field to another // First construct a map from dst indexes to src indexes std::map<unsigned,unsigned> dst_to_src; for (unsigned idx = 0; idx < analysis.src_indexes.size(); idx++) dst_to_src[analysis.dst_indexes[idx]] = analysis.src_indexes[idx]; // Iterate over the target instances for (unsigned idx = 0; idx < analysis.target_views.size(); idx++) { const FieldMask &dst_mask = analysis.target_instances[idx].get_valid_fields(); // Compute a tmp mask based on the dst mask FieldMask source_mask; int fidx = dst_mask.find_first_set(); while (fidx >= 0) { std::map<unsigned,unsigned>::const_iterator finder = dst_to_src.find(fidx); #ifdef DEBUG_LEGION assert(finder != dst_to_src.end()); #endif source_mask.set_bit(finder->second); fidx = dst_mask.find_next_set(fidx+1); } // Now find all the source instances for this destination FieldMaskSet<LogicalView> src_views; for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask field_overlap = it->second & source_mask; if (!field_overlap) continue; src_views.insert(it->first, field_overlap); } #ifdef DEBUG_LEGION if (src_views.empty()) // will only happen in error case continue; #endif across_aggregator->record_updates(analysis.target_views[idx], src_views, source_mask, overlap, analysis.redop, analysis.across_helpers[idx]); } // Now check for any reductions that need to be applied FieldMask reduce_mask = reduction_fields & src_mask; if (!!reduce_mask) { #ifdef DEBUG_LEGION assert(analysis.redop == 0); // can't have reductions of reductions #endif std::map<unsigned,unsigned> src_to_dst; for (unsigned idx = 0; idx < analysis.src_indexes.size(); idx++) src_to_dst[analysis.src_indexes[idx]] = analysis.dst_indexes[idx]; int src_fidx = reduce_mask.find_first_set(); while (src_fidx >= 0) { std::map<unsigned,std::vector<ReductionView*> >::const_iterator finder = reduction_instances.find(src_fidx); #ifdef DEBUG_LEGION assert(finder != reduction_instances.end()); assert(src_to_dst.find(src_fidx) != src_to_dst.end()); #endif const unsigned dst_fidx = src_to_dst[src_fidx]; // Find the target targets and record them for (unsigned idx = 0; idx < analysis.target_views.size(); idx++) { const FieldMask target_mask = analysis.target_instances[idx].get_valid_fields(); if (!target_mask.is_set(dst_fidx)) continue; across_aggregator->record_reductions(analysis.target_views[idx], finder->second, src_fidx, dst_fidx, overlap, analysis.across_helpers[idx]); } src_fidx = reduce_mask.find_next_set(src_fidx+1); } } } else if (analysis.redop == 0) { // Fields align and we're not doing a reduction so we can just // do a normal update copy analysis to figure out what to do issue_update_copies_and_fills(across_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.src_index, true/*track effects*/, src_mask, analysis.target_instances, analysis.target_views, overlap, true/*skip check*/, analysis.dst_index); // We also need to check for any reductions that need to be applied const FieldMask reduce_mask = reduction_fields & src_mask; if (!!reduce_mask) { int fidx = reduce_mask.find_first_set(); while (fidx >= 0) { std::map<unsigned,std::vector<ReductionView*> >::const_iterator finder = reduction_instances.find(fidx); #ifdef DEBUG_LEGION assert(finder != reduction_instances.end()); #endif // Find the target targets and record them for (unsigned idx = 0; idx < analysis.target_views.size(); idx++) { const FieldMask target_mask = analysis.target_instances[idx].get_valid_fields(); if (!target_mask.is_set(fidx)) continue; across_aggregator->record_reductions(analysis.target_views[idx], finder->second, fidx, fidx, overlap); } fidx = reduce_mask.find_next_set(fidx+1); } } } else { // Fields align but we're doing a reduction across // Find the valid views that we need for issuing the updates FieldMaskSet<LogicalView> src_views; for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask overlap = it->second & src_mask; if (!overlap) continue; src_views.insert(it->first, overlap); } for (unsigned idx = 0; idx < analysis.target_views.size(); idx++) { const FieldMask &mask = analysis.target_instances[idx].get_valid_fields(); #ifdef DEBUG_LEGION if (src_views.empty()) // will only happen in error case continue; #endif across_aggregator->record_updates(analysis.target_views[idx], src_views, mask, overlap, analysis.redop, NULL/*across*/); } // There shouldn't be any reduction instances to worry about here #ifdef DEBUG_LEGION assert(reduction_fields * src_mask); #endif } check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::overwrite_set(OverwriteAnalysis &analysis, FieldMask mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *remove_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!cached_set && analysis.update_alt_sets(this, mask)) return; if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); mask -= non_subset; if (!mask) return; } } } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(mask)) { check_for_unrefined_remainder(eq, mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Remove ourselves if we recursed if (!cached_set) analysis.filter_alt_sets(this, to_traverse.get_valid_mask()); // Update the mask and the remove_mask if there is one mask -= to_traverse.get_valid_mask(); if (remove_mask != NULL) *remove_mask |= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->overwrite_set(analysis, it->second, deferral_events, applied_events, NULL/*remove mask*/, false/*cachd set*/); eq.reacquire(); // Return if ourt mask is empty if (!mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif // At this point we need to lock the analysis AutoLock a_lock(analysis); if (analysis.output_aggregator != NULL) analysis.output_aggregator->clear_update_fields(); // Two different cases here depending on whether we have a precidate if (analysis.pred_guard.exists()) { #ifdef DEBUG_LEGION assert(!analysis.add_restriction); // shouldn't be doing this #endif // We have a predicate so collapse everything to all the valid // instances and then do predicate fills to all those instances assert(false); } else { if (analysis.add_restriction || !restricted_fields || (restricted_fields * mask)) { // Easy case, just filter everything and add the new view const FieldMask reduce_filter = mask & reduction_fields; if (!!reduce_filter) filter_reduction_instances(reduce_filter); filter_valid_instances(mask); if (!analysis.views.empty()) { for (std::set<LogicalView*>::const_iterator it = analysis.views.begin(); it != analysis.views.end(); it++) { FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(*it); if (finder == valid_instances.end()) { WrapperReferenceMutator mutator(applied_events); (*it)->add_nested_valid_ref(did, &mutator); valid_instances.insert(*it, mask); } else finder.merge(mask); } } } else { // We overlap with some restricted fields so we can't filter // or update any restricted fields const FieldMask update_mask = mask - restricted_fields; if (!!update_mask) { const FieldMask reduce_filter = update_mask & reduction_fields; if (!!reduce_filter) filter_reduction_instances(reduce_filter); filter_valid_instances(update_mask); if (!analysis.views.empty()) { for (std::set<LogicalView*>::const_iterator it = analysis.views.begin(); it != analysis.views.end(); it++) { FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(*it); if (finder == valid_instances.end()) { WrapperReferenceMutator mutator(applied_events); (*it)->add_nested_valid_ref(did, &mutator); valid_instances.insert(*it, mask); } else finder.merge(mask); } } } } // Advance the version numbers advance_version_numbers(mask); if (analysis.add_restriction) { #ifdef DEBUG_LEGION assert(analysis.views.size() == 1); LogicalView *log_view = *(analysis.views.begin()); assert(log_view->is_instance_view()); #else LogicalView *log_view = *(analysis.views.begin()); #endif InstanceView *inst_view = log_view->as_instance_view(); FieldMaskSet<InstanceView>::iterator restricted_finder = restricted_instances.find(inst_view); if (restricted_finder == restricted_instances.end()) { WrapperReferenceMutator mutator(applied_events); inst_view->add_nested_valid_ref(did, &mutator); restricted_instances.insert(inst_view, mask); } else restricted_finder.merge(mask); restricted_fields |= mask; } else if (!!restricted_fields && !analysis.views.empty()) { // Check to see if we have any restricted outputs to write const FieldMask restricted_overlap = mask & restricted_fields; if (!!restricted_overlap) { // Pick a random view and copy from it LogicalView *log_view = *(analysis.views.begin()); copy_out(restricted_overlap, log_view, analysis.op, analysis.index, analysis.output_aggregator); } } } if ((analysis.output_aggregator != NULL) && analysis.output_aggregator->has_update_fields()) { #ifdef DEBUG_LEGION assert(analysis.output_aggregator->get_update_fields() * refining_fields); #endif update_guards.insert(analysis.output_aggregator, analysis.output_aggregator->get_update_fields()); #ifdef DEBUG_LEGION if (!analysis.output_aggregator->record_guard_set(this)) assert(false); #else analysis.output_aggregator->record_guard_set(this); #endif } check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::filter_set(FilterAnalysis &analysis, FieldMask mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *remove_mask, const bool cached_set/*=true*/, const bool already_deferred/*=false*/) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!cached_set && analysis.update_alt_sets(this, mask)) return; if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); mask -= non_subset; if (!mask) return; } } } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(mask)) { check_for_unrefined_remainder(eq, mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Remove ourselves if we recursed if (!cached_set) analysis.filter_alt_sets(this, to_traverse.get_valid_mask()); // Update the mask and the remove_mask if there is one mask -= to_traverse.get_valid_mask(); if (remove_mask != NULL) *remove_mask |= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->filter_set(analysis, it->second, deferral_events, applied_events, NULL/*remove mask*/, false/*original set*/); eq.reacquire(); // Return if ourt mask is empty if (!mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif // No need to lock the analysis here since we're not going to change it FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(analysis.inst_view); if (finder != valid_instances.end()) { finder.filter(mask); if (!finder->second) { if (analysis.inst_view->remove_nested_valid_ref(did)) delete analysis.inst_view; valid_instances.erase(finder); } } if ((analysis.registration_view != NULL) && (analysis.registration_view != analysis.inst_view)) { finder = valid_instances.find(analysis.registration_view); if (finder != valid_instances.end()) { finder.filter(mask); if (!finder->second) { if (analysis.registration_view->remove_nested_valid_ref(did)) delete analysis.registration_view; valid_instances.erase(finder); } } } if (analysis.remove_restriction) { restricted_fields -= mask; #ifdef DEBUG_LEGION assert(analysis.inst_view != NULL); #endif FieldMaskSet<InstanceView>::iterator restricted_finder = restricted_instances.find(analysis.inst_view); if (restricted_finder != restricted_instances.end()) { restricted_finder.filter(mask); if (!restricted_finder->second) { if (analysis.inst_view->remove_nested_valid_ref(did)) delete analysis.inst_view; restricted_instances.erase(restricted_finder); } } } check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::request_remote_subsets(std::set<RtEvent> &applied) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!is_logical_owner()); assert(eq_state == INVALID_STATE); assert(!transition_event.exists()); #endif // It's not actually ok to block here or we risk a hang so if we're // not already valid and haven't requested a valid copy yet then // go ahead and do that and record the event as an applied event // to ensure we get the update for the next user transition_event = Runtime::create_rt_user_event(); eq_state = PENDING_VALID_STATE; Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(local_space); } runtime->send_equivalence_set_subset_request(logical_owner_space, rez); applied.insert(transition_event); } //-------------------------------------------------------------------------- void EquivalenceSet::record_instances(const FieldMask &record_mask, const InstanceSet &target_instances, const std::vector<InstanceView*> &target_views, ReferenceMutator &mutator) //-------------------------------------------------------------------------- { for (unsigned idx = 0; idx < target_views.size(); idx++) { const FieldMask valid_mask = target_instances[idx].get_valid_fields() & record_mask; if (!valid_mask) continue; InstanceView *target = target_views[idx]; // Add it to the set FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(target); if (finder == valid_instances.end()) { target->add_nested_valid_ref(did, &mutator); valid_instances.insert(target, valid_mask); } else finder.merge(valid_mask); } } //-------------------------------------------------------------------------- void EquivalenceSet::issue_update_copies_and_fills( CopyFillAggregator *&aggregator, const RtEvent guard_event, Operation *op, const unsigned index, const bool track_events, FieldMask update_mask, const InstanceSet &target_instances, const std::vector<InstanceView*> &target_views, IndexSpaceExpression *update_expr, const bool skip_check, const int dst_index /*= -1*/) const //-------------------------------------------------------------------------- { if (update_expr->is_empty()) return; if (!skip_check) { // Scan through and figure out which fields are already valid for (unsigned idx = 0; idx < target_views.size(); idx++) { FieldMaskSet<LogicalView>::const_iterator finder = valid_instances.find(target_views[idx]); if (finder == valid_instances.end()) continue; const FieldMask &needed_mask = target_instances[idx].get_valid_fields(); const FieldMask already_valid = needed_mask & finder->second; if (!already_valid) continue; update_mask -= already_valid; // If we're already valid for all the fields then we're done if (!update_mask) return; } } #ifdef DEBUG_LEGION assert(!!update_mask); #endif // Find the valid views that we need for issuing the updates FieldMaskSet<LogicalView> valid_views; for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask overlap = it->second & update_mask; if (!overlap) continue; valid_views.insert(it->first, overlap); } // Can happen with uninitialized data, we handle this case // before calling this method if (valid_views.empty()) return; if (target_instances.size() == 1) { if (aggregator == NULL) aggregator = (dst_index >= 0) ? new CopyFillAggregator(runtime->forest, op, index, dst_index, guard_event, track_events) : new CopyFillAggregator(runtime->forest, op, index, guard_event, track_events); aggregator->record_updates(target_views[0], valid_views, update_mask, update_expr); } else if (valid_views.size() == 1) { for (unsigned idx = 0; idx < target_views.size(); idx++) { const FieldMask dst_mask = update_mask & target_instances[idx].get_valid_fields(); if (!dst_mask) continue; if (aggregator == NULL) aggregator = (dst_index >= 0) ? new CopyFillAggregator(runtime->forest, op, index, dst_index, guard_event, track_events) : new CopyFillAggregator(runtime->forest, op, index, guard_event, track_events); aggregator->record_updates(target_views[idx], valid_views, dst_mask, update_expr); } } else { for (unsigned idx = 0; idx < target_views.size(); idx++) { const FieldMask dst_mask = update_mask & target_instances[idx].get_valid_fields(); // Can happen in cases with uninitialized data if (!dst_mask) continue; FieldMaskSet<LogicalView> src_views; for (FieldMaskSet<LogicalView>::const_iterator it = valid_views.begin(); it != valid_views.end(); it++) { const FieldMask overlap = dst_mask & it->second; if (!overlap) continue; src_views.insert(it->first, overlap); } if (aggregator == NULL) aggregator = (dst_index >= 0) ? new CopyFillAggregator(runtime->forest, op, index, dst_index, guard_event, track_events) : new CopyFillAggregator(runtime->forest, op, index, guard_event, track_events); aggregator->record_updates(target_views[idx], src_views, dst_mask, update_expr); } } } //-------------------------------------------------------------------------- void EquivalenceSet::filter_valid_instances(const FieldMask &filter_mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!filter_mask); #endif std::vector<LogicalView*> to_erase; for (FieldMaskSet<LogicalView>::iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask overlap = it->second & filter_mask; if (!overlap) continue; it.filter(overlap); if (!it->second) to_erase.push_back(it->first); } if (!to_erase.empty()) { for (std::vector<LogicalView*>::const_iterator it = to_erase.begin(); it != to_erase.end(); it++) { valid_instances.erase(*it); if ((*it)->remove_nested_valid_ref(did)) delete (*it); } } } //-------------------------------------------------------------------------- void EquivalenceSet::filter_reduction_instances(const FieldMask &to_filter) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!to_filter); #endif int fidx = to_filter.find_first_set(); while (fidx >= 0) { std::map<unsigned,std::vector<ReductionView*> >::iterator finder = reduction_instances.find(fidx); #ifdef DEBUG_LEGION assert(finder != reduction_instances.end()); #endif for (std::vector<ReductionView*>::const_iterator it = finder->second.begin(); it != finder->second.end(); it++) if ((*it)->remove_nested_valid_ref(did)) delete (*it); reduction_instances.erase(finder); fidx = to_filter.find_next_set(fidx+1); } reduction_fields -= to_filter; } //-------------------------------------------------------------------------- void EquivalenceSet::apply_reductions(const FieldMask &reduce_mask, CopyFillAggregator *&aggregator, const RtEvent guard_event, Operation *op, const unsigned index, const bool trace_events) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!reduce_mask); assert(!set_expr->is_empty()); #endif int fidx = reduce_mask.find_first_set(); while (fidx >= 0) { std::map<unsigned,std::vector<ReductionView*> >::iterator finder = reduction_instances.find(fidx); #ifdef DEBUG_LEGION assert(finder != reduction_instances.end()); #endif // Find the target targets and record them for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { if (!it->second.is_set(fidx)) continue; // Shouldn't have any deferred views here InstanceView *dst_view = it->first->as_instance_view(); if (aggregator == NULL) aggregator = new CopyFillAggregator(runtime->forest, op, index, guard_event, trace_events); aggregator->record_reductions(dst_view, finder->second, fidx, fidx, set_expr); } // Remove the reduction views from those available for (std::vector<ReductionView*>::const_iterator it = finder->second.begin(); it != finder->second.end(); it++) if ((*it)->remove_nested_valid_ref(did)) delete (*it); reduction_instances.erase(finder); fidx = reduce_mask.find_next_set(fidx+1); } // Record that we advanced the version number in this case advance_version_numbers(reduce_mask); // These reductions have been applied so we are done reduction_fields -= reduce_mask; } //-------------------------------------------------------------------------- void EquivalenceSet::copy_out(const FieldMask &restricted_mask, const InstanceSet &src_instances, const std::vector<InstanceView*> &src_views, Operation *op, const unsigned index, CopyFillAggregator *&aggregator) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!restricted_mask); #endif if (set_expr->is_empty()) return; if (valid_instances.size() == 1) { // Only 1 destination FieldMaskSet<LogicalView>::const_iterator first = valid_instances.begin(); #ifdef DEBUG_LEGION assert(!(restricted_mask - first->second)); #endif InstanceView *dst_view = first->first->as_instance_view(); FieldMaskSet<LogicalView> srcs; for (unsigned idx = 0; idx < src_views.size(); idx++) { if (first->first == src_views[idx]) continue; const FieldMask overlap = src_instances[idx].get_valid_fields() & restricted_mask; if (!overlap) continue; srcs.insert(src_views[idx], overlap); } if (!srcs.empty()) { if (aggregator == NULL) aggregator = new CopyFillAggregator(runtime->forest, op, index, RtEvent::NO_RT_EVENT, true/*track*/); aggregator->record_updates(dst_view, srcs, restricted_mask, set_expr); } } else if (src_instances.size() == 1) { // Only 1 source #ifdef DEBUG_LEGION assert(!(restricted_mask - src_instances[0].get_valid_fields())); #endif FieldMaskSet<LogicalView> srcs; srcs.insert(src_views[0], restricted_mask); for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { if (it->first == src_views[0]) continue; const FieldMask overlap = it->second & restricted_mask; if (!overlap) continue; InstanceView *dst_view = it->first->as_instance_view(); if (aggregator == NULL) aggregator = new CopyFillAggregator(runtime->forest, op, index, RtEvent::NO_RT_EVENT, true/*track*/); aggregator->record_updates(dst_view, srcs, overlap, set_expr); } } else { // General case for cross-products for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask dst_overlap = it->second & restricted_mask; if (!dst_overlap) continue; InstanceView *dst_view = it->first->as_instance_view(); FieldMaskSet<LogicalView> srcs; for (unsigned idx = 0; idx < src_views.size(); idx++) { if (dst_view == src_views[idx]) continue; const FieldMask src_overlap = src_instances[idx].get_valid_fields() & dst_overlap; if (!src_overlap) continue; srcs.insert(src_views[idx], src_overlap); } if (!srcs.empty()) { if (aggregator == NULL) aggregator = new CopyFillAggregator(runtime->forest, op, index, RtEvent::NO_RT_EVENT, true/*track*/); aggregator->record_updates(dst_view, srcs, dst_overlap, set_expr); } } } } //-------------------------------------------------------------------------- void EquivalenceSet::copy_out(const FieldMask &restricted_mask, LogicalView *src_view, Operation *op, const unsigned index, CopyFillAggregator *&aggregator) const //-------------------------------------------------------------------------- { if (set_expr->is_empty()) return; FieldMaskSet<LogicalView> srcs; srcs.insert(src_view, restricted_mask); for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { if (it->first == src_view) continue; const FieldMask overlap = it->second & restricted_mask; if (!overlap) continue; InstanceView *dst_view = it->first->as_instance_view(); if (aggregator == NULL) aggregator = new CopyFillAggregator(runtime->forest, op, index, RtEvent::NO_RT_EVENT, true/*track*/); aggregator->record_updates(dst_view, srcs, overlap, set_expr); } } //-------------------------------------------------------------------------- void EquivalenceSet::advance_version_numbers(FieldMask advance_mask) //-------------------------------------------------------------------------- { std::vector<VersionID> to_remove; for (LegionMap<VersionID,FieldMask>::aligned::iterator it = version_numbers.begin(); it != version_numbers.end(); it++) { const FieldMask overlap = it->second & advance_mask; if (!overlap) continue; LegionMap<VersionID,FieldMask>::aligned::iterator finder = version_numbers.find(it->first + 1); if (finder == version_numbers.end()) version_numbers[it->first + 1] = overlap; else finder->second |= overlap; it->second -= overlap; if (!it->second) to_remove.push_back(it->first); advance_mask -= overlap; if (!advance_mask) break; } if (!to_remove.empty()) { for (std::vector<VersionID>::const_iterator it = to_remove.begin(); it != to_remove.end(); it++) version_numbers.erase(*it); } if (!!advance_mask) version_numbers[init_version] = advance_mask; } //-------------------------------------------------------------------------- void EquivalenceSet::perform_refinements(void) //-------------------------------------------------------------------------- { RtUserEvent to_trigger; FieldMaskSet<EquivalenceSet> to_perform; std::set<EquivalenceSet*> remote_first_refs; std::set<RtEvent> remote_subsets_informed; do { std::set<RtEvent> refinements_done; for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_perform.begin(); it != to_perform.end(); it++) { // Need the lock in read-only mode when doing the clone AutoLock eq(eq_lock,1,false/*exclusive*/); AddressSpaceID alt_space = it->first->clone_from(this, it->second); // If the user asked us to send it to a different node then do that if (alt_space != local_space) { RtUserEvent done_event = Runtime::create_rt_user_event(); Serializer rez; // No RezCheck here because we might need to forward it rez.serialize(it->first->did); rez.serialize(done_event); // Determine whether this is the inital refinement or not // VERY IMPORTANT! You cannot use the subsets data structure // to test this for the case where we constructed a KD-tree // to build intermediate nodes into the refinement tree to // avoid exceeding our maximum fanout. Instead we use the // remote_first_refs data structure to test this if (remote_first_refs.find(it->first) != remote_first_refs.end()) rez.serialize<bool>(true); // initial refinement else rez.serialize<bool>(false); // not initial refinement pack_state(rez, it->second); runtime->send_equivalence_set_remote_refinement( it->first->logical_owner_space, rez); refinements_done.insert(done_event); } } if (!refinements_done.empty()) { const RtEvent wait_on = Runtime::merge_events(refinements_done); wait_on.wait(); } AutoLock eq(eq_lock); #ifdef DEBUG_LEGION assert(is_logical_owner()); assert(waiting_event.exists()); assert(eq_state == REFINING_STATE); #endif // Add any new refinements to our set and record any // potentially complete fields FieldMask complete_mask; if (!to_perform.empty()) { #ifdef DEBUG_LEGION // These masks should be identical assert(refining_fields == to_perform.get_valid_mask()); #endif complete_mask = refining_fields; refining_fields.clear(); // References were added to these sets when they were added // to the pending refinement queue, if they are already here // then we can remove the duplicate reference, no need to // check for deletion since we know we hold another reference for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_perform.begin(); it != to_perform.end(); it++) if (!subsets.insert(it->first, it->second)) it->first->remove_nested_resource_ref(did); to_perform.clear(); remote_first_refs.clear(); // See if there was anyone waiting for us to be done if (transition_event.exists()) { Runtime::trigger_event(transition_event); transition_event = RtUserEvent::NO_RT_USER_EVENT; } } #ifdef DEBUG_LEGION assert(!refining_fields); assert(!transition_event.exists()); #endif // Fields which are still being refined are not complete while (!!complete_mask) { if (!pending_refinements.empty()) { complete_mask -= pending_refinements.get_valid_mask(); if (!complete_mask) break; } if (!unrefined_remainders.empty()) { complete_mask -= unrefined_remainders.get_valid_mask(); if (!complete_mask) break; } if (!disjoint_partition_refinements.empty()) { // Make sure this is tight before we remove them disjoint_partition_refinements.tighten_valid_mask(); complete_mask -= disjoint_partition_refinements.get_valid_mask(); } // Only need one iteration of this loop break; } if (!!complete_mask) { FieldMaskSet<EquivalenceSet> complete_subsets; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = complete_mask & it->second; if (!overlap) continue; complete_subsets.insert(it->first, overlap); } if (complete_subsets.size() > LEGION_MAX_BVH_FANOUT) { // Sort these info field mask sets LegionList<FieldSet<EquivalenceSet*> >::aligned field_sets; complete_subsets.compute_field_sets(complete_mask, field_sets); for (LegionList<FieldSet<EquivalenceSet*> >::aligned::const_iterator fit = field_sets.begin(); fit != field_sets.end(); fit++) { if (fit->elements.size() <= LEGION_MAX_BVH_FANOUT) continue; KDTree *tree = NULL; switch (set_expr->get_num_dims()) { #define KDDIM(DIM) \ case DIM: \ { \ tree = new KDNode<DIM>(set_expr, runtime, 0/*dim*/); \ break; \ } LEGION_FOREACH_N(KDDIM) #undef KDDIM default: assert(false); } // Refine the tree to make the new subsets std::vector<EquivalenceSet*> new_subsets( fit->elements.begin(), fit->elements.end()); #ifdef LEGION_MAX_BVH_DEPTH unsigned max_depth = 0; size_t bvh_ratio = new_subsets.size() / LEGION_MAX_BVH_FANOUT; while (bvh_ratio >>= 1) max_depth++; #else unsigned max_depth = new_subsets.size(); #endif if (tree->refine(new_subsets, fit->set_mask, max_depth)) { // Remove old references for (std::set<EquivalenceSet*>::const_iterator it = fit->elements.begin(); it != fit->elements.end(); it++) { bool found = false; for (std::vector<EquivalenceSet*>::const_iterator nit = new_subsets.begin(); nit != new_subsets.end(); nit++) { if ((*nit) != (*it)) continue; found = true; break; } // If the eq set is in the new set then there is nothing to do if (found) continue; // If it's not in the new set, then we need to remove its // fields from the existing subsets FieldMaskSet<EquivalenceSet>::iterator finder = subsets.find(*it); #ifdef DEBUG_LEGION assert(finder != subsets.end()); #endif finder.filter(fit->set_mask); if (!finder->second) { if (finder->first->remove_nested_resource_ref(did)) delete finder->first; subsets.erase(finder); } // Also remove it from the complete subsets finder = complete_subsets.find(*it); #ifdef DEBUG_LEGION assert(finder != complete_subsets.end()); #endif finder.filter(fit->set_mask); if (!finder->second) complete_subsets.erase(finder); } // Add new references for (std::vector<EquivalenceSet*>::const_iterator it = new_subsets.begin(); it != new_subsets.end(); it++) { if (subsets.insert(*it, fit->set_mask)) (*it)->add_nested_resource_ref(did); // Also add it to the complete subsets complete_subsets.insert(*it, fit->set_mask); } } // Clean up the tree delete tree; } } // If we're done refining then send updates to any // remote sets informing them of the complete set of subsets if (!remote_subsets.empty() && !complete_subsets.empty()) { for (std::set<AddressSpaceID>::const_iterator rit = remote_subsets.begin(); rit != remote_subsets.end(); rit++) { const RtUserEvent informed = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(informed); rez.serialize<size_t>(complete_subsets.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = complete_subsets.begin(); it != complete_subsets.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } } runtime->send_equivalence_set_subset_update(*rit, rez); remote_subsets_informed.insert(informed); } } // Clean out these entries from our data structures if (!valid_instances.empty()) { std::vector<LogicalView*> to_delete; for (FieldMaskSet<LogicalView>::iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { it.filter(complete_mask); if (!it->second) to_delete.push_back(it->first); } if (!to_delete.empty()) { for (std::vector<LogicalView*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { valid_instances.erase(*it); if ((*it)->remove_nested_valid_ref(did)) delete (*it); } valid_instances.tighten_valid_mask(); } } if (!reduction_instances.empty() && !(reduction_fields * complete_mask)) { for (std::map<unsigned,std::vector<ReductionView*> >:: iterator rit = reduction_instances.begin(); rit != reduction_instances.end(); /*nothing*/) { if (complete_mask.is_set(rit->first)) { for (std::vector<ReductionView*>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) if ((*it)->remove_nested_valid_ref(did)) delete (*it); std::map<unsigned,std::vector<ReductionView*> >::iterator to_delete = rit++; reduction_instances.erase(to_delete); } else rit++; } reduction_fields -= complete_mask; } if (!restricted_instances.empty() && !(restricted_fields * complete_mask)) { std::vector<InstanceView*> to_delete; for (FieldMaskSet<InstanceView>::iterator it = restricted_instances.begin(); it != restricted_instances.end(); it++) { it.filter(complete_mask); if (!it->second) to_delete.push_back(it->first); } if (!to_delete.empty()) { for (std::vector<InstanceView*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { restricted_instances.erase(*it); if ((*it)->remove_nested_valid_ref(did)) delete (*it); } restricted_instances.tighten_valid_mask(); } restricted_fields -= complete_mask; } for (LegionMap<VersionID,FieldMask>::aligned::iterator it = version_numbers.begin(); it != version_numbers.end();/*nothing*/) { it->second -= complete_mask; if (!it->second) { LegionMap<VersionID,FieldMask>::aligned::iterator to_delete = it++; version_numbers.erase(to_delete); } else it++; } } // See if we have more refinements to do if (pending_refinements.empty()) { // Go back to the mapping state and trigger our done event eq_state = MAPPING_STATE; to_trigger = waiting_event; waiting_event = RtUserEvent::NO_RT_USER_EVENT; } else // there are more refinements to do so we go around again { #ifdef DEBUG_LEGION assert(!refining_fields); // should be empty prior to this #endif refining_fields = pending_refinements.get_valid_mask(); to_perform.swap(pending_refinements); remote_first_refs.swap(remote_first_refinements); } } while (!to_perform.empty()); #ifdef DEBUG_LEGION assert(to_trigger.exists()); #endif // Make sure that everyone is informed before we return if (!remote_subsets_informed.empty()) Runtime::trigger_event(to_trigger, Runtime::merge_events(remote_subsets_informed)); else Runtime::trigger_event(to_trigger); } //-------------------------------------------------------------------------- void EquivalenceSet::record_subset(EquivalenceSet *set, const FieldMask &set_mask) //-------------------------------------------------------------------------- { // This method is only called when adding extra levels to the // equivalence set BVH data structure in order to reduce large // fanout. We don't need the lock and we shouldn't have any // remote copies of this equivalence set #ifdef DEBUG_LEGION assert(is_logical_owner()); assert(!has_remote_instances()); #endif if (subsets.insert(set, set_mask)) set->add_nested_resource_ref(did); } //-------------------------------------------------------------------------- void EquivalenceSet::finalize_disjoint_refinement( DisjointPartitionRefinement *dis, const FieldMask &finalize_mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(unrefined_remainders.get_valid_mask() * finalize_mask); #endif // We're not going to be able to finish up this disjoint // partition refinement so restore this to the state // for normal traversal // Figure out if we finished refining or whether there // is still an unrefined remainder IndexPartNode *partition = dis->partition; if (!dis->is_refined()) { std::set<LegionColor> current_colors; const std::map<IndexSpaceNode*,EquivalenceSet*> &children = dis->get_children(); for (std::map<IndexSpaceNode*,EquivalenceSet*>::const_iterator it = children.begin(); it != children.end(); it++) current_colors.insert(it->first->color); // No matter what finish making all the children since making // disjoint partitions is a good thing if (partition->total_children == partition->max_linearized_color) { for (LegionColor color = 0; color < partition->total_children; color++) { if (current_colors.find(color) != current_colors.end()) continue; IndexSpaceNode *child = partition->get_child(color); if (child->is_empty()) continue; add_pending_refinement(child, finalize_mask, child, runtime->address_space); // Don't add this to the refinement as we might only be // finalizing for a subset of fields and the // DisjointPartitionRefinement should only store entries // for children that have been refined for all fields } } else { ColorSpaceIterator *itr = partition->color_space->create_color_space_iterator(); while (itr->is_valid()) { const LegionColor color = itr->yield_color(); if (current_colors.find(color) != current_colors.end()) continue; if (!partition->color_space->contains_color(color)) continue; IndexSpaceNode *child = partition->get_child(color); if (child->is_empty()) continue; add_pending_refinement(child, finalize_mask, child, runtime->address_space); // Don't add this to the refinement as we might only be // finalizing for a subset of fields and the // DisjointPartitionRefinement should only store entries // for children that have been refined for all fields } delete itr; } } if (!partition->is_complete()) { // We had all the children, but the partition is not // complete so we actually need to do the subtraction IndexSpaceExpression *diff_expr = runtime->forest->subtract_index_spaces(set_expr, partition->get_union_expression()); #ifdef DEBUG_LEGION assert((diff_expr != NULL) && !diff_expr->is_empty()); assert(unrefined_remainders.get_valid_mask() * finalize_mask); #endif if (unrefined_remainders.insert(diff_expr, finalize_mask)) diff_expr->add_expression_reference(); } } //-------------------------------------------------------------------------- void EquivalenceSet::filter_unrefined_remainders(FieldMask &to_filter, IndexSpaceExpression *expr) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!to_filter); assert(!expr->is_empty()); #endif if (unrefined_remainders.empty()) return; if (to_filter * unrefined_remainders.get_valid_mask()) return; FieldMaskSet<IndexSpaceExpression> to_add; std::vector<IndexSpaceExpression*> to_delete; for (FieldMaskSet<IndexSpaceExpression>::iterator it = unrefined_remainders.begin(); it != unrefined_remainders.end(); it++) { const FieldMask overlap = to_filter & it->second; if (!overlap) continue; IndexSpaceExpression *remainder = runtime->forest->subtract_index_spaces(it->first, expr); if (!remainder->is_empty()) to_add.insert(remainder, overlap); it.filter(overlap); if (!it->second) to_delete.push_back(it->first); to_filter -= overlap; if (!to_filter) break; } if (!to_delete.empty()) { for (std::vector<IndexSpaceExpression*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { unrefined_remainders.erase(*it); if ((*it)->remove_expression_reference()) delete (*it); } } if (!to_add.empty()) { for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = to_add.begin(); it != to_add.end(); it++) if (unrefined_remainders.insert(it->first, it->second)) it->first->add_expression_reference(); } } //-------------------------------------------------------------------------- void EquivalenceSet::send_equivalence_set(AddressSpaceID target) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(is_owner()); // We should have had a request for this already assert(!has_remote_instance(target)); #endif update_remote_instances(target); Serializer rez; { RezCheck z(rez); rez.serialize(did); // There be dragons here! // In the case where we first make a new equivalence set on a // remote node that is about to be the owner, we can't mark it // as the owner until it receives all an unpack_state or // unpack_migration message which provides it valid meta-data // Therefore we'll tell it that we're the owner which will // create a cycle in the forwarding graph. This won't matter for // unpack_migration as it's going to overwrite the data in the // equivalence set anyway, but for upack_state, we'll need to // recognize when to break the cycle. Effectively whenever we // send an update to a remote node that we can tell has never // been the owner before (and therefore can't have migrated) // we know that we should just do the unpack there. This will // break the cycle and allow forward progress. Analysis messages // may go round and round a few times, but they have lower // priority and therefore shouldn't create an livelock. { AutoLock eq(eq_lock,1,false/*exclusive*/); if (target == logical_owner_space) rez.serialize(local_space); else rez.serialize(logical_owner_space); } set_expr->pack_expression(rez, target); if (index_space_node != NULL) rez.serialize(index_space_node->handle); else rez.serialize(IndexSpace::NO_SPACE); } runtime->send_equivalence_set_response(target, rez); } //-------------------------------------------------------------------------- EquivalenceSet* EquivalenceSet::add_pending_refinement( IndexSpaceExpression *expr, const FieldMask &mask, IndexSpaceNode *node, AddressSpaceID source) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(is_logical_owner()); #endif // See if we already have a subset with this expression EquivalenceSet *subset = NULL; if ((subset_exprs == NULL) && !subsets.empty()) { // Fill in the data structure if it hasn't already been done // e.g. due to migration subset_exprs = new std::map<IndexSpaceExpression*,EquivalenceSet*>(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) (*subset_exprs)[it->first->set_expr] = it->first; } if (subset_exprs != NULL) { std::map<IndexSpaceExpression*,EquivalenceSet*>::const_iterator finder = subset_exprs->find(expr); if (finder != subset_exprs->end()) subset = finder->second; } if (subset == NULL) { // Make a new subset subset = new EquivalenceSet(runtime, runtime->get_available_distributed_id(), local_space, source, expr, node, true/*register*/); if (subset_exprs == NULL) subset_exprs = new std::map<IndexSpaceExpression*,EquivalenceSet*>(); // Save it in the set (*subset_exprs)[expr] = subset; if (pending_refinements.insert(subset, mask)) subset->add_nested_resource_ref(did); // If this is going to be a remote first refinement record it if (source != local_space) remote_first_refinements.insert(subset); } else { // We already have a subset, see which fields it's already // been refined for (maybe none if it is still pending) FieldMaskSet<EquivalenceSet>::const_iterator finder = subsets.find(subset); if (finder != subsets.end()) { const FieldMask diff_mask = mask - finder->second; if (!!diff_mask) { if (pending_refinements.insert(subset, diff_mask)) subset->add_nested_resource_ref(did); } else // It's already refined for all of them, so just return return subset; } else { // Do the normal insert if we couldn't find it if (pending_refinements.insert(subset, mask)) subset->add_nested_resource_ref(did); } } // Launch the refinement task if there isn't one already running if (eq_state == MAPPING_STATE) { #ifdef DEBUG_LEGION assert(!transition_event.exists()); assert(!waiting_event.exists()); assert(!refining_fields); // should be empty #endif waiting_event = Runtime::create_rt_user_event(); eq_state = REFINING_STATE; // Launch the refinement task to be performed RefinementTaskArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY); } return subset; } //-------------------------------------------------------------------------- void EquivalenceSet::process_subset_request(AddressSpaceID source, RtUserEvent deferral_event) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { // We didn't get the lock so build a continuation // We need a name for our completion event that we can use for // the atomic compare and swap below if (!deferral_event.exists()) { // If we haven't already been deferred then we need to // add ourselves to the back of the list of deferrals deferral_event = Runtime::create_rt_user_event(); const RtEvent continuation_pre = chain_deferral_events(deferral_event); DeferSubsetRequestArgs args(this, source, deferral_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, continuation_pre); } else { // We've already been deferred and our precondition has already // triggered so just launch ourselves again whenever the lock // should be ready to try again DeferSubsetRequestArgs args(this, source, deferral_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, eq.try_next()); } return; } if (!is_logical_owner()) { // If we're not the owner anymore then forward on the request Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(source); } runtime->send_equivalence_set_subset_request(logical_owner_space, rez); if (deferral_event.exists()) Runtime::trigger_event(deferral_event); return; } // If we arrived back at ourself after we were made the owner // then there is nothing for us to do, similarly if this is a // duplicate then there is nothing for us to do if ((source == local_space) || (remote_subsets.find(source) != remote_subsets.end())) { if (deferral_event.exists()) Runtime::trigger_event(deferral_event); return; } // If we're in the process of doing a refinement, wait for // that to be done before we do anything else if (eq_state == REFINING_STATE) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif DeferSubsetRequestArgs args(this, source, deferral_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, waiting_event); return; } // Record the remote subsets remote_subsets.insert(source); // Remote copies of the subsets either have to be empty or a // full copy of the subsets with no partial refinements if (!subsets.empty()) { FieldMask complete_mask = subsets.get_valid_mask(); // Any fields for which we have partial refinements cannot be sent yet if (!pending_refinements.empty()) complete_mask -= pending_refinements.get_valid_mask(); if (!!refining_fields) complete_mask -= refining_fields; if (!unrefined_remainders.empty()) complete_mask -= unrefined_remainders.get_valid_mask(); if (!!disjoint_partition_refinements.empty()) complete_mask -= disjoint_partition_refinements.get_valid_mask(); if (!!complete_mask) { Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize<size_t>(subsets.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & complete_mask; if (!!overlap) { rez.serialize(it->first->did); rez.serialize(overlap); } else rez.serialize<DistributedID>(0); } } runtime->send_equivalence_set_subset_response(source, rez); if (deferral_event.exists()) Runtime::trigger_event(deferral_event); return; } } // If we make it here then we just send a message with an // empty set of subsets to allow forward progress to be made Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize<size_t>(0); } runtime->send_equivalence_set_subset_response(source, rez); if (deferral_event.exists()) Runtime::trigger_event(deferral_event); } //-------------------------------------------------------------------------- void EquivalenceSet::process_subset_response(Deserializer &derez) //-------------------------------------------------------------------------- { size_t num_subsets; derez.deserialize(num_subsets); FieldMaskSet<EquivalenceSet> new_subsets; if (num_subsets > 0) { std::set<RtEvent> ready_events; for (unsigned idx = 0; idx < num_subsets; idx++) { DistributedID subdid; derez.deserialize(subdid); if (subdid == 0) continue; RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(subdid, ready); if (ready.exists()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); new_subsets.insert(set, mask); } if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists()) wait_on.wait(); } } AutoLock eq(eq_lock); if (is_logical_owner()) { // If we've since been made the logical owner then there // should be nothing else for us to do #ifdef DEBUG_LEGION assert(new_subsets.empty()); #endif return; } else if (eq_state == PENDING_VALID_STATE) { #ifdef DEBUG_LEGION assert(subsets.empty()); assert(transition_event.exists()); assert(!transition_event.has_triggered()); #endif if (!new_subsets.empty()) { subsets.swap(new_subsets); // Add the references for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) it->first->add_nested_resource_ref(did); } // Update the state eq_state = VALID_STATE; // Trigger the transition state to wake up any waiters Runtime::trigger_event(transition_event); transition_event = RtUserEvent::NO_RT_USER_EVENT; } } //-------------------------------------------------------------------------- void EquivalenceSet::process_subset_update(Deserializer &derez) //-------------------------------------------------------------------------- { size_t num_subsets; derez.deserialize(num_subsets); if (num_subsets == 0) return; std::vector<EquivalenceSet*> new_subsets(num_subsets); LegionVector<FieldMask>::aligned new_masks(num_subsets); std::set<RtEvent> wait_for; for (unsigned idx = 0; idx < num_subsets; idx++) { DistributedID subdid; derez.deserialize(subdid); RtEvent ready; new_subsets[idx] = runtime->find_or_request_equivalence_set(subdid, ready); if (ready.exists()) wait_for.insert(ready); derez.deserialize(new_masks[idx]); } if (!wait_for.empty()) { const RtEvent wait_on = Runtime::merge_events(wait_for); wait_on.wait(); } AutoLock eq(eq_lock); if (is_logical_owner()) // If we've become the logical owner there is nothing to do return; #ifdef DEBUG_LEGION assert(eq_state == VALID_STATE); assert(!transition_event.exists()); #endif for (unsigned idx = 0; idx < num_subsets; idx++) if (subsets.insert(new_subsets[idx], new_masks[idx])) new_subsets[idx]->add_nested_resource_ref(did); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_refinement(const void *args) //-------------------------------------------------------------------------- { const RefinementTaskArgs *rargs = (const RefinementTaskArgs*)args; rargs->target->perform_refinements(); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_remote_references(const void *args) //-------------------------------------------------------------------------- { const RemoteRefTaskArgs *rargs = (const RemoteRefTaskArgs*)args; if (rargs->done_event.exists()) { LocalReferenceMutator mutator; if (rargs->add_references) { for (std::map<LogicalView*,unsigned>::const_iterator it = rargs->refs->begin(); it != rargs->refs->end(); it++) it->first->add_nested_valid_ref(rargs->did, &mutator, it->second); } else { for (std::map<LogicalView*,unsigned>::const_iterator it = rargs->refs->begin(); it != rargs->refs->end(); it++) it->first->remove_nested_valid_ref(rargs->did, &mutator,it->second); } const RtEvent done_pre = mutator.get_done_event(); Runtime::trigger_event(rargs->done_event, done_pre); } else { if (rargs->add_references) { for (std::map<LogicalView*,unsigned>::const_iterator it = rargs->refs->begin(); it != rargs->refs->end(); it++) it->first->add_nested_valid_ref(rargs->did, NULL, it->second); } else { for (std::map<LogicalView*,unsigned>::const_iterator it = rargs->refs->begin(); it != rargs->refs->end(); it++) it->first->remove_nested_valid_ref(rargs->did, NULL, it->second); } } delete rargs->refs; } //-------------------------------------------------------------------------- EquivalenceSet::DeferRayTraceArgs::DeferRayTraceArgs(EquivalenceSet *s, RayTracer *t, IndexSpaceExpression *e, IndexSpace h, AddressSpaceID o, RtUserEvent d, RtUserEvent def, const FieldMask &m, bool local, bool is_expr_s, IndexSpace expr_h, IndexSpaceExprID expr_i) : LgTaskArgs<DeferRayTraceArgs>(implicit_provenance), set(s), target(t), expr(local ? e : NULL), handle(h), origin(o), done(d), deferral(def), ray_mask(new FieldMask(m)), expr_handle(expr_h), expr_id(expr_i), is_local(local), is_expr_space(is_expr_s) //-------------------------------------------------------------------------- { if (local) expr->add_expression_reference(); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_ray_trace(const void *args, Runtime *runtime) //-------------------------------------------------------------------------- { const DeferRayTraceArgs *dargs = (const DeferRayTraceArgs*)args; // See if we need to load the expression or not IndexSpaceExpression *expr = (dargs->is_local) ? dargs->expr : (dargs->is_expr_space) ? runtime->forest->get_node(dargs->expr_handle) : runtime->forest->find_remote_expression(dargs->expr_id); dargs->set->ray_trace_equivalence_sets(dargs->target, expr, *(dargs->ray_mask), dargs->handle, dargs->origin, dargs->done, dargs->deferral); // Clean up our ray mask delete dargs->ray_mask; // Remove our expression reference too if (dargs->is_local && dargs->expr->remove_expression_reference()) delete dargs->expr; } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_ray_trace_finish(const void *args) //-------------------------------------------------------------------------- { const DeferRayTraceFinishArgs *dargs = (const DeferRayTraceFinishArgs*)args; std::set<RtEvent> done_events; for (FieldMaskSet<EquivalenceSet>::const_iterator it = dargs->to_traverse->begin(); it != dargs->to_traverse->end(); it++) { RtUserEvent done = Runtime::create_rt_user_event(); std::map<EquivalenceSet*,IndexSpaceExpression*>::const_iterator finder = dargs->exprs->find(it->first); #ifdef DEBUG_LEGION assert(finder != dargs->exprs->end()); #endif const IndexSpace subset_handle = (dargs->handle.exists() && (finder->second->get_volume() == dargs->volume)) ? dargs->handle : IndexSpace::NO_SPACE; it->first->ray_trace_equivalence_sets(dargs->target, finder->second, it->second, subset_handle, dargs->source, done); done_events.insert(done); } if (!done_events.empty()) Runtime::trigger_event(dargs->done, Runtime::merge_events(done_events)); else Runtime::trigger_event(dargs->done); delete dargs->to_traverse; delete dargs->exprs; } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_subset_request(const void *args) //-------------------------------------------------------------------------- { const DeferSubsetRequestArgs *dargs = (const DeferSubsetRequestArgs*)args; dargs->set->process_subset_request(dargs->source, dargs->deferral); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_make_owner(const void *args) //-------------------------------------------------------------------------- { const DeferMakeOwnerArgs *dargs = (const DeferMakeOwnerArgs*)args; if (dargs->set->make_owner(dargs->new_subsets, dargs->done, true/*need lock*/)) delete dargs->new_subsets; } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_merge_or_forward(const void *args) //-------------------------------------------------------------------------- { const DeferMergeOrForwardArgs *dargs = (const DeferMergeOrForwardArgs*)args; dargs->set->merge_or_forward(dargs->done, dargs->initial, *(dargs->views), *(dargs->reductions), *(dargs->restricted), *(dargs->versions)); delete dargs->views; delete dargs->reductions; delete dargs->restricted; delete dargs->versions; } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_equivalence_set_request( Deserializer &derez, Runtime *runtime, AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); DistributedCollectable *dc = runtime->find_distributed_collectable(did); #ifdef DEBUG_LEGION EquivalenceSet *set = dynamic_cast<EquivalenceSet*>(dc); assert(set != NULL); #else EquivalenceSet *set = static_cast<EquivalenceSet*>(dc); #endif set->send_equivalence_set(source); } //-------------------------------------------------------------------------- EquivalenceSet::DeferResponseArgs::DeferResponseArgs(DistributedID id, AddressSpaceID src, AddressSpaceID log, IndexSpaceExpression *ex, bool local, bool is_space, IndexSpace expr_h, IndexSpaceExprID xid, IndexSpace h) : LgTaskArgs<DeferResponseArgs>(implicit_provenance), did(id), source(src), logical_owner(log), expr(ex), is_local(local), is_index_space(is_space), expr_handle(expr_h), expr_id(xid), handle(h) //-------------------------------------------------------------------------- { if (is_local) expr->add_expression_reference(); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_equivalence_set_response( Deserializer &derez, Runtime *runtime, AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); AddressSpaceID logical_owner; derez.deserialize(logical_owner); bool is_local, is_index_space; IndexSpace expr_handle; IndexSpaceExprID expr_id; RtEvent wait_for; IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez, runtime->forest, source, is_local, is_index_space, expr_handle, expr_id, wait_for); IndexSpace handle; derez.deserialize(handle); // We only actually need the index space node on the owner and the // logical owner otherwise we can skip it IndexSpaceNode *node = NULL; RtEvent wait_on; if (handle.exists() && (logical_owner == runtime->address_space)) node = runtime->forest->get_node(handle, &wait_on); // Defer this if the index space expression isn't ready yet if (wait_for.exists() || wait_on.exists()) { RtEvent precondition; if (wait_for.exists()) { if (wait_on.exists()) precondition = Runtime::merge_events(wait_for, wait_on); else precondition = wait_for; } else precondition = wait_on; if (precondition.exists() && !precondition.has_triggered()) { DeferResponseArgs args(did, source, logical_owner, expr, is_local, is_index_space, expr_handle, expr_id, handle); runtime->issue_runtime_meta_task(args, LG_LATENCY_MESSAGE_PRIORITY, precondition); return; } // If we fall through we need to refetch things that we didn't get if (expr == NULL) expr = is_index_space ? runtime->forest->get_node(expr_handle) : runtime->forest->find_remote_expression(expr_id); if ((node == NULL) && handle.exists() && (logical_owner == runtime->address_space)) node = runtime->forest->get_node(handle); } void *location; EquivalenceSet *set = NULL; if (runtime->find_pending_collectable_location(did, location)) set = new(location) EquivalenceSet(runtime, did, source, logical_owner, expr, node, false/*register now*/); else set = new EquivalenceSet(runtime, did, source, logical_owner, expr, node, false/*register now*/); // Once construction is complete then we do the registration set->register_with_runtime(NULL/*no remote registration needed*/); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_deferred_response(const void *args, Runtime *runtime) //-------------------------------------------------------------------------- { const DeferResponseArgs *dargs = (const DeferResponseArgs*)args; IndexSpaceExpression *expr = (dargs->is_local) ? dargs->expr : (dargs->is_index_space) ? runtime->forest->get_node(dargs->expr_handle) : runtime->forest->find_remote_expression(dargs->expr_id); IndexSpaceNode *node = NULL; if (dargs->handle.exists() && (dargs->logical_owner == runtime->address_space)) node = runtime->forest->get_node(dargs->handle); void *location; EquivalenceSet *set = NULL; if (runtime->find_pending_collectable_location(dargs->did, location)) set = new(location) EquivalenceSet(runtime, dargs->did, dargs->source, dargs->logical_owner, expr, node, false/*register now*/); else set = new EquivalenceSet(runtime, dargs->did, dargs->source, dargs->logical_owner, expr, node, false/*register now*/); // Once construction is complete then we do the registration set->register_with_runtime(NULL/*no remote registration needed*/); // Remove our expression reference too if (dargs->is_local && dargs->expr->remove_expression_reference()) delete dargs->expr; } //-------------------------------------------------------------------------- /*static*/void EquivalenceSet::handle_deferred_remove_refs(const void *args) //-------------------------------------------------------------------------- { const DeferRemoveRefArgs *dargs = (const DeferRemoveRefArgs*)args; for (std::vector<IndexSpaceExpression*>::const_iterator it = dargs->references->begin(); it != dargs->references->end(); it++) if ((*it)->remove_expression_reference()) delete (*it); delete dargs->references; } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_subset_request( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); AddressSpaceID source; derez.deserialize(source); if (ready.exists() && !ready.has_triggered()) ready.wait(); set->process_subset_request(source, RtUserEvent::NO_RT_USER_EVENT); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_subset_response( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); DistributedCollectable *dc = runtime->find_distributed_collectable(did); #ifdef DEBUG_LEGION EquivalenceSet *set = dynamic_cast<EquivalenceSet*>(dc); assert(set != NULL); #else EquivalenceSet *set = static_cast<EquivalenceSet*>(dc); #endif set->process_subset_response(derez); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_subset_update( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); RtUserEvent to_trigger; derez.deserialize(to_trigger); DistributedCollectable *dc = runtime->find_distributed_collectable(did); #ifdef DEBUG_LEGION EquivalenceSet *set = dynamic_cast<EquivalenceSet*>(dc); assert(set != NULL); #else EquivalenceSet *set = static_cast<EquivalenceSet*>(dc); #endif set->process_subset_update(derez); Runtime::trigger_event(to_trigger); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_ray_trace_request( Deserializer &derez, Runtime *runtime, AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); RayTracer *target; derez.deserialize(target); bool is_local, is_expr_space; IndexSpace expr_handle; IndexSpaceExprID expr_id; RtEvent expr_ready; IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez, runtime->forest, source, is_local, is_expr_space, expr_handle, expr_id, expr_ready); FieldMask ray_mask; derez.deserialize(ray_mask); IndexSpace handle; derez.deserialize(handle); AddressSpaceID origin; derez.deserialize(origin); RtUserEvent done_event; derez.deserialize(done_event); if (ready.exists() || expr_ready.exists()) { const RtEvent defer = Runtime::merge_events(ready, expr_ready); if (defer.exists() && !defer.has_triggered()) { // We need to defer this until things are ready DeferRayTraceArgs args(set, target, expr, handle, origin, done_event, RtUserEvent::NO_RT_USER_EVENT, ray_mask, is_local, is_expr_space, expr_handle, expr_id); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, defer); return; } if (expr_ready.exists()) expr = (is_expr_space) ? runtime->forest->get_node(expr_handle) : runtime->forest->find_remote_expression(expr_id); // Fall through and actually do the operation now } set->ray_trace_equivalence_sets(target, expr, ray_mask, handle, origin, done_event); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_ray_trace_response( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); FieldMask eq_mask; derez.deserialize(eq_mask); RayTracer *target; derez.deserialize(target); RtUserEvent done_event; derez.deserialize(done_event); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); if (ready.exists() && !ready.has_triggered()) { target->record_pending_equivalence_set(set, eq_mask); Runtime::trigger_event(done_event, ready); } else { target->record_equivalence_set(set, eq_mask); Runtime::trigger_event(done_event); } } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_migration(Deserializer &derez, Runtime *runtime, AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); RtUserEvent done; derez.deserialize(done); LocalReferenceMutator mutator; if (ready.exists() && !ready.has_triggered()) ready.wait(); set->unpack_migration(derez, source, done); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_owner_update(Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); AddressSpaceID new_owner; derez.deserialize(new_owner); RtUserEvent done; derez.deserialize(done); if (ready.exists() && !ready.has_triggered()) ready.wait(); set->update_owner(new_owner); Runtime::trigger_event(done); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_remote_refinement( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); if (ready.exists() && !ready.has_triggered()) ready.wait(); set->unpack_state(derez); } ///////////////////////////////////////////////////////////// // Version Manager ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- VersionManager::VersionManager(RegionTreeNode *n, ContextID c) : ctx(c), node(n), runtime(n->context->runtime) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- VersionManager::VersionManager(const VersionManager &rhs) : ctx(rhs.ctx), node(rhs.node), runtime(rhs.runtime) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- VersionManager::~VersionManager(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- VersionManager& VersionManager::operator=(const VersionManager &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void VersionManager::reset(void) //-------------------------------------------------------------------------- { AutoLock m_lock(manager_lock); if (!equivalence_sets.empty()) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = equivalence_sets.begin(); it != equivalence_sets.end(); it++) { if (it->first->remove_base_resource_ref(VERSION_MANAGER_REF)) delete it->first; } equivalence_sets.clear(); } #ifdef DEBUG_LEGION assert(waiting_infos.empty()); assert(equivalence_sets_ready.empty()); #endif } //-------------------------------------------------------------------------- RtEvent VersionManager::perform_versioning_analysis(InnerContext *context, VersionInfo *version_info, RegionNode *region_node, const FieldMask &version_mask, Operation *op) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(node == region_node); #endif // If we don't have equivalence classes for this region yet we // either need to compute them or request them from the owner FieldMask remaining_mask(version_mask); bool has_waiter = false; { AutoLock m_lock(manager_lock,1,false/*exclusive*/); // Check to see if any computations of equivalence sets are in progress // If so we'll skip out early and go down the slow path which should // be a fairly rare thing to do if (!equivalence_sets_ready.empty()) { for (LegionMap<RtUserEvent,FieldMask>::aligned::const_iterator it = equivalence_sets_ready.begin(); it != equivalence_sets_ready.end(); it++) { if (remaining_mask * it->second) continue; // Skip out earlier if we have at least one thing to wait // for since we're going to have to go down the slow path has_waiter = true; break; } } // If we have a waiter, then don't bother doing this if (!has_waiter) { // Get any fields that are already ready if (version_info != NULL) { if (!(version_mask * equivalence_sets.get_valid_mask())) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = equivalence_sets.begin(); it != equivalence_sets.end(); it++) { const FieldMask overlap = it->second & version_mask; if (!overlap) continue; version_info->record_equivalence_set(this, it->first, overlap); } } } remaining_mask -= equivalence_sets.get_valid_mask(); // If we got all our fields then we are done if (!remaining_mask) return RtEvent::NO_RT_EVENT; } } // Retake the lock in exclusive mode and make sure we don't lose the race RtUserEvent compute_event; std::set<RtEvent> wait_on; { FieldMask waiting_mask; AutoLock m_lock(manager_lock); if (!equivalence_sets_ready.empty()) { for (LegionMap<RtUserEvent,FieldMask>::aligned::const_iterator it = equivalence_sets_ready.begin(); it != equivalence_sets_ready.end(); it++) { const FieldMask overlap = remaining_mask & it->second; if (!overlap) continue; wait_on.insert(it->first); waiting_mask |= overlap; } if (!!waiting_mask) remaining_mask -= waiting_mask; } // Get any fields that are already ready // Have to do this after looking for pending equivalence sets // to make sure we don't have pending outstanding requests if (!(remaining_mask * equivalence_sets.get_valid_mask())) { if (version_info != NULL) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = equivalence_sets.begin(); it != equivalence_sets.end(); it++) { const FieldMask overlap = it->second & remaining_mask; if (!overlap) continue; version_info->record_equivalence_set(this, it->first, overlap); } } remaining_mask -= equivalence_sets.get_valid_mask(); // If we got all our fields here and we're not waiting // on any other computations then we're done if (!remaining_mask && wait_on.empty()) return RtEvent::NO_RT_EVENT; } // If we still have remaining fields then we need to // do this computation ourselves if (!!remaining_mask) { compute_event = Runtime::create_rt_user_event(); equivalence_sets_ready[compute_event] = remaining_mask; wait_on.insert(compute_event); waiting_mask |= remaining_mask; } #ifdef DEBUG_LEGION assert(!!waiting_mask); #endif // Record that our version info is waiting for these fields if (version_info != NULL) waiting_infos.insert(version_info, waiting_mask); } if (compute_event.exists()) { IndexSpaceExpression *expr = region_node->row_source; IndexSpace handle = region_node->row_source->handle; RtEvent ready = context->compute_equivalence_sets(this, region_node->get_tree_id(), handle, expr, remaining_mask, runtime->address_space); if (ready.exists() && !ready.has_triggered()) { // Launch task to finalize the sets once they are ready LgFinalizeEqSetsArgs args(this, compute_event, op->get_unique_op_id()); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, ready); } else finalize_equivalence_sets(compute_event); } return Runtime::merge_events(wait_on); } //-------------------------------------------------------------------------- void VersionManager::record_equivalence_set(EquivalenceSet *set, const FieldMask &mask) //-------------------------------------------------------------------------- { AutoLock m_lock(manager_lock); if (equivalence_sets.insert(set, mask)) set->add_base_resource_ref(VERSION_MANAGER_REF); } //-------------------------------------------------------------------------- void VersionManager::record_pending_equivalence_set(EquivalenceSet *set, const FieldMask &mask) //-------------------------------------------------------------------------- { AutoLock m_lock(manager_lock); pending_equivalence_sets.insert(set, mask); } //-------------------------------------------------------------------------- void VersionManager::finalize_equivalence_sets(RtUserEvent done_event) //-------------------------------------------------------------------------- { std::set<RtEvent> done_preconditions; { AutoLock m_lock(manager_lock); LegionMap<RtUserEvent,FieldMask>::aligned::iterator finder = equivalence_sets_ready.find(done_event); #ifdef DEBUG_LEGION assert(finder != equivalence_sets_ready.end()); #endif // See if there are any other events with overlapping fields, // if there are then we can't actually move over any pending // equivalence sets for those fields yet since we don't know // which are ours, just record dependences on those events if (equivalence_sets_ready.size() > 1) { FieldMask aliased; for (LegionMap<RtUserEvent,FieldMask>::aligned::const_iterator it = equivalence_sets_ready.begin(); it != equivalence_sets_ready.end(); it++) { if (it->first == done_event) continue; const FieldMask overlap = it->second & finder->second; if (!overlap) continue; done_preconditions.insert(it->first); aliased |= overlap; } if (!!aliased) finder->second -= aliased; } // If there are any pending equivalence sets, move them into // the actual equivalence sets if (!pending_equivalence_sets.empty() && !(finder->second * pending_equivalence_sets.get_valid_mask())) { std::vector<EquivalenceSet*> to_delete; for (FieldMaskSet<EquivalenceSet>::iterator it = pending_equivalence_sets.begin(); it != pending_equivalence_sets.end(); it++) { // Once it's valid for any field then it's valid for all of them if (it->second * finder->second) continue; if (equivalence_sets.insert(it->first, it->second)) it->first->add_base_resource_ref(VERSION_MANAGER_REF); to_delete.push_back(it->first); } if (!to_delete.empty()) { if (to_delete.size() < pending_equivalence_sets.size()) { for (std::vector<EquivalenceSet*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) pending_equivalence_sets.erase(*it); pending_equivalence_sets.tighten_valid_mask(); } else pending_equivalence_sets.clear(); } } if (!waiting_infos.empty() && !(waiting_infos.get_valid_mask() * finder->second)) { std::vector<VersionInfo*> to_delete; for (FieldMaskSet<VersionInfo>::iterator vit = waiting_infos.begin(); vit != waiting_infos.end(); vit++) { const FieldMask info_overlap = vit->second & finder->second; if (!info_overlap) continue; for (FieldMaskSet<EquivalenceSet>::const_iterator it = equivalence_sets.begin(); it != equivalence_sets.end(); it++) { const FieldMask overlap = info_overlap & it->second; if (!overlap) continue; vit->first->record_equivalence_set(this, it->first, overlap); } vit.filter(info_overlap); if (!vit->second) to_delete.push_back(vit->first); } if (!to_delete.empty()) { for (std::vector<VersionInfo*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) waiting_infos.erase(*it); } } equivalence_sets_ready.erase(finder); } if (!done_preconditions.empty()) Runtime::trigger_event(done_event, Runtime::merge_events(done_preconditions)); else Runtime::trigger_event(done_event); } //-------------------------------------------------------------------------- RtEvent VersionManager::record_stale_sets( FieldMaskSet<EquivalenceSet> &stale_sets) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!stale_sets.empty()); #endif RtUserEvent compute_event; { FieldMask update_mask; AutoLock m_lock(manager_lock); // See which of our stale sets are still in the valid set, if they // are then remove their fields, otherwise record that we don't need // to update them for (FieldMaskSet<EquivalenceSet>::iterator it = stale_sets.begin(); it != stale_sets.end(); it++) { FieldMaskSet<EquivalenceSet>::iterator finder = equivalence_sets.find(it->first); if (finder != equivalence_sets.end()) { const FieldMask need_refinement = it->second & finder->second; if (!!need_refinement) { update_mask |= need_refinement; finder.filter(need_refinement); if (!finder->second) // Reference flows back with stale sets equivalence_sets.erase(finder); else // Add a reference to keep the eq set live until we're done it->first->add_base_resource_ref(VERSION_MANAGER_REF); it.filter(~need_refinement); #ifdef DEBUG_LEGION assert(!!it->second); #endif continue; } } it.clear(); } if (!update_mask) return RtEvent::NO_RT_EVENT; compute_event = Runtime::create_rt_user_event(); equivalence_sets_ready[compute_event] = update_mask; } // For these equivalence sets we need to perform additional ray // traces to get the new refineemnts of the sets std::set<RtEvent> preconditions; for (FieldMaskSet<EquivalenceSet>::iterator it = stale_sets.begin(); it != stale_sets.end(); it++) { // Skip any sets which didn't have valid fields if (!it->second) continue; RtUserEvent refresh_done = Runtime::create_rt_user_event(); it->first->refresh_refinement(this, it->second, refresh_done); preconditions.insert(refresh_done); // Remove the reference that we are holding if (it->first->remove_base_resource_ref(VERSION_MANAGER_REF)) delete it->first; } // Now launch a finalize task to complete the update if (!preconditions.empty()) { const RtEvent precondition = Runtime::merge_events(preconditions); if (precondition.exists() && !precondition.has_triggered()) { LgFinalizeEqSetsArgs args(this, compute_event, implicit_provenance); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, precondition); return compute_event; } } // If we make it here we can do the finalize call now finalize_equivalence_sets(compute_event); return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- void VersionManager::print_physical_state(RegionTreeNode *node, const FieldMask &capture_mask, TreeStateLogger *logger) //-------------------------------------------------------------------------- { logger->log("Equivalence Sets:"); logger->down(); // TODO: log equivalence sets assert(false); logger->up(); } //-------------------------------------------------------------------------- /*static*/ void VersionManager::handle_finalize_eq_sets(const void *args) //-------------------------------------------------------------------------- { const LgFinalizeEqSetsArgs *fargs = (const LgFinalizeEqSetsArgs*)args; fargs->manager->finalize_equivalence_sets(fargs->compute); } //-------------------------------------------------------------------------- /*static*/ void VersionManager::handle_stale_update(Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); size_t num_sets; derez.deserialize(num_sets); FieldMaskSet<EquivalenceSet> stale_sets; std::set<RtEvent> ready_events; for (unsigned idx = 0; idx < num_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did, ready); FieldMask mask; derez.deserialize(mask); stale_sets.insert(set, mask); if (ready.exists() && !ready.has_triggered()) ready_events.insert(ready); } VersionManager *manager; derez.deserialize(manager); RtUserEvent done_event; derez.deserialize(done_event); if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); } const RtEvent done = manager->record_stale_sets(stale_sets); Runtime::trigger_event(done_event, done); } ///////////////////////////////////////////////////////////// // RegionTreePath ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- RegionTreePath::RegionTreePath(void) : min_depth(0), max_depth(0) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- void RegionTreePath::initialize(unsigned min, unsigned max) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(min <= max); #endif min_depth = min; max_depth = max; path.resize(max_depth+1, INVALID_COLOR); } //-------------------------------------------------------------------------- void RegionTreePath::register_child(unsigned depth, const LegionColor color) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(min_depth <= depth); assert(depth <= max_depth); #endif path[depth] = color; } //-------------------------------------------------------------------------- void RegionTreePath::record_aliased_children(unsigned depth, const FieldMask &mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(min_depth <= depth); assert(depth <= max_depth); #endif LegionMap<unsigned,FieldMask>::aligned::iterator finder = interfering_children.find(depth); if (finder == interfering_children.end()) interfering_children[depth] = mask; else finder->second |= mask; } //-------------------------------------------------------------------------- void RegionTreePath::clear(void) //-------------------------------------------------------------------------- { path.clear(); min_depth = 0; max_depth = 0; } #ifdef DEBUG_LEGION //-------------------------------------------------------------------------- bool RegionTreePath::has_child(unsigned depth) const //-------------------------------------------------------------------------- { assert(min_depth <= depth); assert(depth <= max_depth); return (path[depth] != INVALID_COLOR); } //-------------------------------------------------------------------------- LegionColor RegionTreePath::get_child(unsigned depth) const //-------------------------------------------------------------------------- { assert(min_depth <= depth); assert(depth <= max_depth); assert(has_child(depth)); return path[depth]; } #endif //-------------------------------------------------------------------------- const FieldMask* RegionTreePath::get_aliased_children(unsigned depth) const //-------------------------------------------------------------------------- { if (interfering_children.empty()) return NULL; LegionMap<unsigned,FieldMask>::aligned::const_iterator finder = interfering_children.find(depth); if (finder == interfering_children.end()) return NULL; return &(finder->second); } ///////////////////////////////////////////////////////////// // InstanceRef ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- InstanceRef::InstanceRef(bool comp) : ready_event(ApEvent::NO_AP_EVENT), manager(NULL), local(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InstanceRef::InstanceRef(const InstanceRef &rhs) : valid_fields(rhs.valid_fields), ready_event(rhs.ready_event), manager(rhs.manager), local(rhs.local) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InstanceRef::InstanceRef(PhysicalManager *man, const FieldMask &m,ApEvent r) : valid_fields(m), ready_event(r), manager(man), local(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InstanceRef::~InstanceRef(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InstanceRef& InstanceRef::operator=(const InstanceRef &rhs) //-------------------------------------------------------------------------- { valid_fields = rhs.valid_fields; ready_event = rhs.ready_event; local = rhs.local; manager = rhs.manager; return *this; } //-------------------------------------------------------------------------- bool InstanceRef::operator==(const InstanceRef &rhs) const //-------------------------------------------------------------------------- { if (valid_fields != rhs.valid_fields) return false; if (ready_event != rhs.ready_event) return false; if (manager != rhs.manager) return false; return true; } //-------------------------------------------------------------------------- bool InstanceRef::operator!=(const InstanceRef &rhs) const //-------------------------------------------------------------------------- { return !(*this == rhs); } //-------------------------------------------------------------------------- MappingInstance InstanceRef::get_mapping_instance(void) const //-------------------------------------------------------------------------- { return MappingInstance(manager); } //-------------------------------------------------------------------------- bool InstanceRef::is_virtual_ref(void) const //-------------------------------------------------------------------------- { if (manager == NULL) return true; return manager->is_virtual_manager(); } //-------------------------------------------------------------------------- void InstanceRef::add_resource_reference(ReferenceSource source) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif manager->add_base_resource_ref(source); } //-------------------------------------------------------------------------- void InstanceRef::remove_resource_reference(ReferenceSource source) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif if (manager->remove_base_resource_ref(source)) delete manager; } //-------------------------------------------------------------------------- void InstanceRef::add_valid_reference(ReferenceSource source, ReferenceMutator *mutator) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif manager->add_base_valid_ref(source, mutator); } //-------------------------------------------------------------------------- void InstanceRef::remove_valid_reference(ReferenceSource source, ReferenceMutator *mutator) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif if (manager->remove_base_valid_ref(source, mutator)) delete manager; } //-------------------------------------------------------------------------- Memory InstanceRef::get_memory(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif return manager->get_memory(); } //-------------------------------------------------------------------------- bool InstanceRef::is_field_set(FieldID fid) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif unsigned index = manager->field_space_node->get_field_index(fid); return valid_fields.is_set(index); } //-------------------------------------------------------------------------- LegionRuntime::Accessor::RegionAccessor< LegionRuntime::Accessor::AccessorType::Generic> InstanceRef::get_accessor(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif return manager->get_accessor(); } //-------------------------------------------------------------------------- LegionRuntime::Accessor::RegionAccessor< LegionRuntime::Accessor::AccessorType::Generic> InstanceRef::get_field_accessor(FieldID fid) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif return manager->get_field_accessor(fid); } //-------------------------------------------------------------------------- void InstanceRef::pack_reference(Serializer &rez) const //-------------------------------------------------------------------------- { rez.serialize(valid_fields); rez.serialize(ready_event); if (manager != NULL) rez.serialize(manager->did); else rez.serialize<DistributedID>(0); } //-------------------------------------------------------------------------- void InstanceRef::unpack_reference(Runtime *runtime, Deserializer &derez, RtEvent &ready) //-------------------------------------------------------------------------- { derez.deserialize(valid_fields); derez.deserialize(ready_event); DistributedID did; derez.deserialize(did); if (did == 0) return; manager = runtime->find_or_request_physical_manager(did, ready); local = false; } ///////////////////////////////////////////////////////////// // InstanceSet ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- InstanceSet::CollectableRef& InstanceSet::CollectableRef::operator=( const InstanceSet::CollectableRef &rhs) //-------------------------------------------------------------------------- { valid_fields = rhs.valid_fields; ready_event = rhs.ready_event; local = rhs.local; manager = rhs.manager; return *this; } //-------------------------------------------------------------------------- InstanceSet::InstanceSet(size_t init_size /*=0*/) : single((init_size <= 1)), shared(false) //-------------------------------------------------------------------------- { if (init_size == 0) refs.single = NULL; else if (init_size == 1) { refs.single = new CollectableRef(); refs.single->add_reference(); } else { refs.multi = new InternalSet(init_size); refs.multi->add_reference(); } } //-------------------------------------------------------------------------- InstanceSet::InstanceSet(const InstanceSet &rhs) : single(rhs.single) //-------------------------------------------------------------------------- { // Mark that the other one is sharing too if (single) { refs.single = rhs.refs.single; if (refs.single == NULL) { shared = false; return; } shared = true; rhs.shared = true; refs.single->add_reference(); } else { refs.multi = rhs.refs.multi; shared = true; rhs.shared = true; refs.multi->add_reference(); } } //-------------------------------------------------------------------------- InstanceSet::~InstanceSet(void) //-------------------------------------------------------------------------- { if (single) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); } else { if (refs.multi->remove_reference()) delete refs.multi; } } //-------------------------------------------------------------------------- InstanceSet& InstanceSet::operator=(const InstanceSet &rhs) //-------------------------------------------------------------------------- { // See if we need to delete our current one if (single) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); } else { if (refs.multi->remove_reference()) delete refs.multi; } // Now copy over the other one single = rhs.single; if (single) { refs.single = rhs.refs.single; if (refs.single != NULL) { shared = true; rhs.shared = true; refs.single->add_reference(); } else shared = false; } else { refs.multi = rhs.refs.multi; shared = true; rhs.shared = true; refs.multi->add_reference(); } return *this; } //-------------------------------------------------------------------------- void InstanceSet::make_copy(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(shared); #endif if (single) { if (refs.single != NULL) { CollectableRef *next = new CollectableRef(*refs.single); next->add_reference(); if (refs.single->remove_reference()) delete (refs.single); refs.single = next; } } else { InternalSet *next = new InternalSet(*refs.multi); next->add_reference(); if (refs.multi->remove_reference()) delete refs.multi; refs.multi = next; } shared = false; } //-------------------------------------------------------------------------- bool InstanceSet::operator==(const InstanceSet &rhs) const //-------------------------------------------------------------------------- { if (single != rhs.single) return false; if (single) { if (refs.single == rhs.refs.single) return true; if (((refs.single == NULL) && (rhs.refs.single != NULL)) || ((refs.single != NULL) && (rhs.refs.single == NULL))) return false; return ((*refs.single) == (*rhs.refs.single)); } else { if (refs.multi->vector.size() != rhs.refs.multi->vector.size()) return false; for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) { if (refs.multi->vector[idx] != rhs.refs.multi->vector[idx]) return false; } return true; } } //-------------------------------------------------------------------------- bool InstanceSet::operator!=(const InstanceSet &rhs) const //-------------------------------------------------------------------------- { return !((*this) == rhs); } //-------------------------------------------------------------------------- InstanceRef& InstanceSet::operator[](unsigned idx) //-------------------------------------------------------------------------- { if (shared) make_copy(); if (single) { #ifdef DEBUG_LEGION assert(idx == 0); assert(refs.single != NULL); #endif return *(refs.single); } #ifdef DEBUG_LEGION assert(idx < refs.multi->vector.size()); #endif return refs.multi->vector[idx]; } //-------------------------------------------------------------------------- const InstanceRef& InstanceSet::operator[](unsigned idx) const //-------------------------------------------------------------------------- { // No need to make a copy if shared here since this is read-only if (single) { #ifdef DEBUG_LEGION assert(idx == 0); assert(refs.single != NULL); #endif return *(refs.single); } #ifdef DEBUG_LEGION assert(idx < refs.multi->vector.size()); #endif return refs.multi->vector[idx]; } //-------------------------------------------------------------------------- bool InstanceSet::empty(void) const //-------------------------------------------------------------------------- { if (single && (refs.single == NULL)) return true; else if (!single && refs.multi->empty()) return true; return false; } //-------------------------------------------------------------------------- size_t InstanceSet::size(void) const //-------------------------------------------------------------------------- { if (single) { if (refs.single == NULL) return 0; return 1; } if (refs.multi == NULL) return 0; return refs.multi->vector.size(); } //-------------------------------------------------------------------------- void InstanceSet::resize(size_t new_size) //-------------------------------------------------------------------------- { if (single) { if (new_size == 0) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); refs.single = NULL; shared = false; } else if (new_size > 1) { // Switch to multi InternalSet *next = new InternalSet(new_size); if (refs.single != NULL) { next->vector[0] = *(refs.single); if (refs.single->remove_reference()) delete (refs.single); } next->add_reference(); refs.multi = next; single = false; shared = false; } else if (refs.single == NULL) { // New size is 1 but we were empty before CollectableRef *next = new CollectableRef(); next->add_reference(); refs.single = next; single = true; shared = false; } } else { if (new_size == 0) { if (refs.multi->remove_reference()) delete refs.multi; refs.single = NULL; single = true; shared = false; } else if (new_size == 1) { CollectableRef *next = new CollectableRef(refs.multi->vector[0]); if (refs.multi->remove_reference()) delete (refs.multi); next->add_reference(); refs.single = next; single = true; shared = false; } else { size_t current_size = refs.multi->vector.size(); if (current_size != new_size) { if (shared) { // Make a copy InternalSet *next = new InternalSet(new_size); // Copy over the elements for (unsigned idx = 0; idx < ((current_size < new_size) ? current_size : new_size); idx++) next->vector[idx] = refs.multi->vector[idx]; if (refs.multi->remove_reference()) delete refs.multi; next->add_reference(); refs.multi = next; shared = false; } else { // Resize our existing vector refs.multi->vector.resize(new_size); } } // Size is the same so there is no need to do anything } } } //-------------------------------------------------------------------------- void InstanceSet::clear(void) //-------------------------------------------------------------------------- { // No need to copy since we are removing our references and not mutating if (single) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); refs.single = NULL; } else { if (shared) { // Small optimization here, if we're told to delete it, we know // that means we were the last user so we can re-use it if (refs.multi->remove_reference()) { // Put a reference back on it since we're reusing it refs.multi->add_reference(); refs.multi->vector.clear(); } else { // Go back to single refs.multi = NULL; single = true; } } else refs.multi->vector.clear(); } shared = false; } //-------------------------------------------------------------------------- void InstanceSet::swap(InstanceSet &rhs) //-------------------------------------------------------------------------- { // Swap references { InternalSet *other = rhs.refs.multi; rhs.refs.multi = refs.multi; refs.multi = other; } // Swap single { bool other = rhs.single; rhs.single = single; single = other; } // Swap shared { bool other = rhs.shared; rhs.shared = shared; shared = other; } } //-------------------------------------------------------------------------- void InstanceSet::add_instance(const InstanceRef &ref) //-------------------------------------------------------------------------- { if (single) { // No need to check for shared, we're going to make new things anyway if (refs.single != NULL) { // Make the new multi version InternalSet *next = new InternalSet(2); next->vector[0] = *(refs.single); next->vector[1] = ref; if (refs.single->remove_reference()) delete (refs.single); next->add_reference(); refs.multi = next; single = false; shared = false; } else { refs.single = new CollectableRef(ref); refs.single->add_reference(); } } else { if (shared) make_copy(); refs.multi->vector.push_back(ref); } } //-------------------------------------------------------------------------- bool InstanceSet::is_virtual_mapping(void) const //-------------------------------------------------------------------------- { if (empty()) return true; if (size() > 1) return false; return refs.single->is_virtual_ref(); } //-------------------------------------------------------------------------- void InstanceSet::pack_references(Serializer &rez) const //-------------------------------------------------------------------------- { if (single) { if (refs.single == NULL) { rez.serialize<size_t>(0); return; } rez.serialize<size_t>(1); refs.single->pack_reference(rez); } else { rez.serialize<size_t>(refs.multi->vector.size()); for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) refs.multi->vector[idx].pack_reference(rez); } } //-------------------------------------------------------------------------- void InstanceSet::unpack_references(Runtime *runtime, Deserializer &derez, std::set<RtEvent> &ready_events) //-------------------------------------------------------------------------- { size_t num_refs; derez.deserialize(num_refs); if (num_refs == 0) { // No matter what, we can just clear out any references we have if (single) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); refs.single = NULL; } else { if (refs.multi->remove_reference()) delete refs.multi; single = true; } } else if (num_refs == 1) { // If we're in multi, go back to single if (!single) { if (refs.multi->remove_reference()) delete refs.multi; refs.multi = NULL; single = true; } // Now we can unpack our reference, see if we need to make one if (refs.single == NULL) { refs.single = new CollectableRef(); refs.single->add_reference(); } RtEvent ready; refs.single->unpack_reference(runtime, derez, ready); if (ready.exists()) ready_events.insert(ready); } else { // If we're in single, go to multi // otherwise resize our multi for the appropriate number of references if (single) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); refs.multi = new InternalSet(num_refs); refs.multi->add_reference(); single = false; } else refs.multi->vector.resize(num_refs); // Now do the unpacking for (unsigned idx = 0; idx < num_refs; idx++) { RtEvent ready; refs.multi->vector[idx].unpack_reference(runtime, derez, ready); if (ready.exists()) ready_events.insert(ready); } } // We are always not shared when we are done shared = false; } //-------------------------------------------------------------------------- void InstanceSet::add_resource_references(ReferenceSource source) const //-------------------------------------------------------------------------- { if (single) { if (refs.single != NULL) refs.single->add_resource_reference(source); } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) refs.multi->vector[idx].add_resource_reference(source); } } //-------------------------------------------------------------------------- void InstanceSet::remove_resource_references(ReferenceSource source) const //-------------------------------------------------------------------------- { if (single) { if (refs.single != NULL) refs.single->remove_resource_reference(source); } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) refs.multi->vector[idx].remove_resource_reference(source); } } //-------------------------------------------------------------------------- void InstanceSet::add_valid_references(ReferenceSource source, ReferenceMutator *mutator) const //-------------------------------------------------------------------------- { if (single) { if (refs.single != NULL) refs.single->add_valid_reference(source, mutator); } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) refs.multi->vector[idx].add_valid_reference(source, mutator); } } //-------------------------------------------------------------------------- void InstanceSet::remove_valid_references(ReferenceSource source, ReferenceMutator *mutator) const //-------------------------------------------------------------------------- { if (single) { if (refs.single != NULL) refs.single->remove_valid_reference(source, mutator); } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) refs.multi->vector[idx].remove_valid_reference(source, mutator); } } //-------------------------------------------------------------------------- void InstanceSet::update_wait_on_events(std::set<ApEvent> &wait_on) const //-------------------------------------------------------------------------- { if (single) { if (refs.single != NULL) { ApEvent ready = refs.single->get_ready_event(); if (ready.exists()) wait_on.insert(ready); } } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) { ApEvent ready = refs.multi->vector[idx].get_ready_event(); if (ready.exists()) wait_on.insert(ready); } } } //-------------------------------------------------------------------------- LegionRuntime::Accessor::RegionAccessor< LegionRuntime::Accessor::AccessorType::Generic> InstanceSet:: get_field_accessor(FieldID fid) const //-------------------------------------------------------------------------- { if (single) { #ifdef DEBUG_LEGION assert(refs.single != NULL); #endif return refs.single->get_field_accessor(fid); } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) { const InstanceRef &ref = refs.multi->vector[idx]; if (ref.is_field_set(fid)) return ref.get_field_accessor(fid); } assert(false); return refs.multi->vector[0].get_field_accessor(fid); } } ///////////////////////////////////////////////////////////// // VersioningInvalidator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- VersioningInvalidator::VersioningInvalidator(void) : ctx(0), invalidate_all(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- VersioningInvalidator::VersioningInvalidator(RegionTreeContext c) : ctx(c.get_id()), invalidate_all(!c.exists()) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- bool VersioningInvalidator::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { if (invalidate_all) node->invalidate_version_managers(); else node->invalidate_version_state(ctx); return true; } //-------------------------------------------------------------------------- bool VersioningInvalidator::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { // There is no version information on partitions return true; } }; // namespace Internal }; // namespace Legion legion: more small updates to equivalence sets /* Copyright 2020 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "legion.h" #include "legion/runtime.h" #include "legion/legion_ops.h" #include "legion/legion_tasks.h" #include "legion/region_tree.h" #include "legion/legion_spy.h" #include "legion/legion_trace.h" #include "legion/legion_profiling.h" #include "legion/legion_instances.h" #include "legion/legion_views.h" #include "legion/legion_analysis.h" #include "legion/legion_context.h" namespace Legion { namespace Internal { LEGION_EXTERN_LOGGER_DECLARATIONS ///////////////////////////////////////////////////////////// // Users and Info ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalUser::LogicalUser(void) : GenericUser(), op(NULL), idx(0), gen(0), timeout(TIMEOUT) #ifdef LEGION_SPY , uid(0) #endif //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalUser::LogicalUser(Operation *o, unsigned id, const RegionUsage &u, const FieldMask &m) : GenericUser(u, m), op(o), idx(id), gen(o->get_generation()), timeout(TIMEOUT) #ifdef LEGION_SPY , uid(o->get_unique_op_id()) #endif //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalUser::LogicalUser(Operation *o, GenerationID g, unsigned id, const RegionUsage &u, const FieldMask &m) : GenericUser(u, m), op(o), idx(id), gen(g), timeout(TIMEOUT) #ifdef LEGION_SPY , uid(o->get_unique_op_id()) #endif //-------------------------------------------------------------------------- { } #ifdef ENABLE_VIEW_REPLICATION //-------------------------------------------------------------------------- PhysicalUser::PhysicalUser(const RegionUsage &u, IndexSpaceExpression *e, UniqueID id, unsigned x, RtEvent collect, bool cpy, bool cov) : usage(u), expr(e), op_id(id), index(x), collect_event(collect), copy_user(cpy), covers(cov) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(expr != NULL); #endif expr->add_expression_reference(); } #else //-------------------------------------------------------------------------- PhysicalUser::PhysicalUser(const RegionUsage &u, IndexSpaceExpression *e, UniqueID id, unsigned x, bool cpy, bool cov) : usage(u), expr(e), op_id(id), index(x), copy_user(cpy), covers(cov) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(expr != NULL); #endif expr->add_expression_reference(); } #endif //-------------------------------------------------------------------------- PhysicalUser::PhysicalUser(const PhysicalUser &rhs) : usage(rhs.usage), expr(rhs.expr), op_id(rhs.op_id), index(rhs.index), #ifdef ENABLE_VIEW_REPLICATION collect_event(rhs.collect_event), #endif copy_user(rhs.copy_user), covers(rhs.covers) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- PhysicalUser::~PhysicalUser(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(expr != NULL); #endif if (expr->remove_expression_reference()) delete expr; } //-------------------------------------------------------------------------- PhysicalUser& PhysicalUser::operator=(const PhysicalUser &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void PhysicalUser::pack_user(Serializer &rez, const AddressSpaceID target) const //-------------------------------------------------------------------------- { RezCheck z(rez); #ifdef ENABLE_VIEW_REPLICATION rez.serialize(collect_event); #endif rez.serialize(usage); expr->pack_expression(rez, target); rez.serialize(op_id); rez.serialize(index); rez.serialize<bool>(copy_user); rez.serialize<bool>(covers); } //-------------------------------------------------------------------------- /*static*/ PhysicalUser* PhysicalUser::unpack_user(Deserializer &derez, RegionTreeForest *forest, const AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); #ifdef ENABLE_VIEW_REPLICATION RtEvent collect_event; derez.deserialize(collect_event); #endif RegionUsage usage; derez.deserialize(usage); IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez, forest, source); UniqueID op_id; derez.deserialize(op_id); unsigned index; derez.deserialize(index); bool copy_user, covers; derez.deserialize<bool>(copy_user); derez.deserialize<bool>(covers); #ifdef ENABLE_VIEW_REPLICATION return new PhysicalUser(usage, expr, op_id, index, collect_event, copy_user, covers); #else return new PhysicalUser(usage, expr, op_id, index, copy_user, covers); #endif } ///////////////////////////////////////////////////////////// // VersionInfo ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- VersionInfo::VersionInfo(void) : owner(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- VersionInfo::VersionInfo(const VersionInfo &rhs) : owner(NULL) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(rhs.owner == NULL); assert(equivalence_sets.empty()); assert(rhs.equivalence_sets.empty()); #endif } //-------------------------------------------------------------------------- VersionInfo::~VersionInfo(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- VersionInfo& VersionInfo::operator=(const VersionInfo &rhs) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(rhs.owner == NULL); assert(equivalence_sets.empty()); assert(rhs.equivalence_sets.empty()); #endif return *this; } //-------------------------------------------------------------------------- void VersionInfo::record_equivalence_set(VersionManager *own, EquivalenceSet *set, const FieldMask &set_mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert((owner == NULL) || (owner == own)); #endif owner = own; equivalence_sets.insert(set, set_mask); } //-------------------------------------------------------------------------- void VersionInfo::clear(void) //-------------------------------------------------------------------------- { owner = NULL; equivalence_sets.clear(); } ///////////////////////////////////////////////////////////// // LogicalTraceInfo ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalTraceInfo::LogicalTraceInfo(bool already_tr, LegionTrace *tr, unsigned idx, const RegionRequirement &r) : already_traced(already_tr), trace(tr), req_idx(idx), req(r) //-------------------------------------------------------------------------- { // If we have a trace but it doesn't handle the region tree then // we should mark that this is not part of a trace if ((trace != NULL) && !trace->handles_region_tree(req.parent.get_tree_id())) { already_traced = false; trace = NULL; } } ///////////////////////////////////////////////////////////// // Remote Trace Recorder ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- RemoteTraceRecorder::RemoteTraceRecorder(Runtime *rt, AddressSpaceID origin, AddressSpaceID local, Memoizable *memo, PhysicalTemplate *tpl, RtUserEvent applied, RtEvent collect) : runtime(rt), origin_space(origin), local_space(local), memoizable(memo), remote_tpl(tpl), applied_event(applied), collect_event(collect) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(remote_tpl != NULL); #endif } //-------------------------------------------------------------------------- RemoteTraceRecorder::RemoteTraceRecorder(const RemoteTraceRecorder &rhs) : runtime(rhs.runtime), origin_space(rhs.origin_space), local_space(rhs.local_space), memoizable(rhs.memoizable), remote_tpl(rhs.remote_tpl), applied_event(rhs.applied_event), collect_event(rhs.collect_event) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- RemoteTraceRecorder::~RemoteTraceRecorder(void) //-------------------------------------------------------------------------- { if (!applied_events.empty()) Runtime::trigger_event(applied_event, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied_event); // Clean up our memoizable object if necessary if ((memoizable != NULL) && (memoizable->get_origin_space() != local_space)) delete memoizable; } //-------------------------------------------------------------------------- RemoteTraceRecorder& RemoteTraceRecorder::operator=( const RemoteTraceRecorder &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void RemoteTraceRecorder::add_recorder_reference(void) //-------------------------------------------------------------------------- { add_reference(); } //-------------------------------------------------------------------------- bool RemoteTraceRecorder::remove_recorder_reference(void) //-------------------------------------------------------------------------- { return remove_reference(); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::pack_recorder(Serializer &rez, std::set<RtEvent> &external_applied, const AddressSpaceID target) //-------------------------------------------------------------------------- { rez.serialize(origin_space); rez.serialize(target); rez.serialize(remote_tpl); RtUserEvent remote_applied = Runtime::create_rt_user_event(); rez.serialize(remote_applied); rez.serialize(collect_event); // Only need to store this one locally since we already hooked our whole // chain of events into the operations applied set on the origin node // See PhysicalTemplate::pack_recorder AutoLock a_lock(applied_lock); applied_events.insert(remote_applied); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_get_term_event(Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_RECORD_GET_TERM); rez.serialize(applied); memo->pack_remote_memoizable(rez, origin_space); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_get_term_event(memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_create_ap_user_event( ApUserEvent lhs, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_CREATE_USER_EVENT); rez.serialize(applied); rez.serialize(lhs); memo->pack_remote_memoizable(rez, origin_space); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_create_ap_user_event(lhs, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_trigger_event(ApUserEvent lhs, ApEvent rhs) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_TRIGGER_EVENT); rez.serialize(applied); rez.serialize(lhs); rez.serialize(rhs); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_trigger_event(lhs, rhs); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_merge_events(ApEvent &lhs, ApEvent rhs, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { std::set<ApEvent> rhs_events; rhs_events.insert(rhs); record_merge_events(lhs, rhs_events, memo); } else remote_tpl->record_merge_events(lhs, rhs, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_merge_events(ApEvent &lhs, ApEvent e1, ApEvent e2, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { std::set<ApEvent> rhs_events; rhs_events.insert(e1); rhs_events.insert(e2); record_merge_events(lhs, rhs_events, memo); } else remote_tpl->record_merge_events(lhs, e1, e2, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_merge_events(ApEvent &lhs, ApEvent e1, ApEvent e2, ApEvent e3, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { std::set<ApEvent> rhs_events; rhs_events.insert(e1); rhs_events.insert(e2); rhs_events.insert(e3); record_merge_events(lhs, rhs_events, memo); } else remote_tpl->record_merge_events(lhs, e1, e2, e3, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_merge_events(ApEvent &lhs, const std::set<ApEvent>& rhs, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent done = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_MERGE_EVENTS); rez.serialize(done); rez.serialize(&lhs); rez.serialize(lhs); memo->pack_remote_memoizable(rez, origin_space); rez.serialize<size_t>(rhs.size()); for (std::set<ApEvent>::const_iterator it = rhs.begin(); it != rhs.end(); it++) rez.serialize(*it); } runtime->send_remote_trace_update(origin_space, rez); // Wait to see if lhs changes done.wait(); } else remote_tpl->record_merge_events(lhs, rhs, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_issue_copy(Memoizable *memo, unsigned src_idx, unsigned dst_idx, ApEvent &lhs, IndexSpaceExpression *expr, const std::vector<CopySrcDstField>& src_fields, const std::vector<CopySrcDstField>& dst_fields, #ifdef LEGION_SPY RegionTreeID src_tree_id, RegionTreeID dst_tree_id, #endif ApEvent precondition, ReductionOpID redop, bool reduction_fold, const FieldMaskSet<InstanceView> &tracing_srcs, const FieldMaskSet<InstanceView> &tracing_dsts) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent done = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_ISSUE_COPY); rez.serialize(done); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(src_idx); rez.serialize(dst_idx); rez.serialize(&lhs); rez.serialize(lhs); expr->pack_expression(rez, origin_space); #ifdef DEBUG_LEGION assert(src_fields.size() == dst_fields.size()); #endif rez.serialize<size_t>(src_fields.size()); for (unsigned idx = 0; idx < src_fields.size(); idx++) { pack_src_dst_field(rez, src_fields[idx]); pack_src_dst_field(rez, dst_fields[idx]); } #ifdef LEGION_SPY rez.serialize(src_tree_id); rez.serialize(dst_tree_id); #endif rez.serialize(precondition); rez.serialize(redop); rez.serialize<bool>(reduction_fold); rez.serialize<size_t>(tracing_srcs.size()); for (FieldMaskSet<InstanceView>::const_iterator it = tracing_srcs.begin(); it != tracing_srcs.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<size_t>(tracing_dsts.size()); for (FieldMaskSet<InstanceView>::const_iterator it = tracing_dsts.begin(); it != tracing_dsts.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } } runtime->send_remote_trace_update(origin_space, rez); // Wait to see if lhs changes done.wait(); } else remote_tpl->record_issue_copy(memo, src_idx, dst_idx, lhs, expr, src_fields, dst_fields, #ifdef LEGION_SPY src_tree_id, dst_tree_id, #endif precondition, redop, reduction_fold, tracing_srcs, tracing_dsts); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_issue_indirect(Memoizable *memo, ApEvent &lhs, IndexSpaceExpression *expr, const std::vector<CopySrcDstField>& src_fields, const std::vector<CopySrcDstField>& dst_fields, const std::vector<void*> &indirections, ApEvent precondition) //-------------------------------------------------------------------------- { if (local_space != origin_space) { // TODO assert(false); } else remote_tpl->record_issue_indirect(memo, lhs, expr,src_fields,dst_fields, indirections, precondition); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_issue_fill(Memoizable *memo, unsigned idx, ApEvent &lhs, IndexSpaceExpression *expr, const std::vector<CopySrcDstField> &fields, const void *fill_value, size_t fill_size, #ifdef LEGION_SPY FieldSpace handle, RegionTreeID tree_id, #endif ApEvent precondition, const FieldMaskSet<FillView> &tracing_srcs, const FieldMaskSet<InstanceView> &tracing_dsts) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent done = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_ISSUE_FILL); rez.serialize(done); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(idx); rez.serialize(&lhs); rez.serialize(lhs); expr->pack_expression(rez, origin_space); rez.serialize<size_t>(fields.size()); for (unsigned idx = 0; idx < fields.size(); idx++) pack_src_dst_field(rez, fields[idx]); rez.serialize(fill_size); rez.serialize(fill_value, fill_size); #ifdef LEGION_SPY rez.serialize(handle); rez.serialize(tree_id); #endif rez.serialize(precondition); rez.serialize<size_t>(tracing_srcs.size()); for (FieldMaskSet<FillView>::const_iterator it = tracing_srcs.begin(); it != tracing_srcs.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<size_t>(tracing_dsts.size()); for (FieldMaskSet<InstanceView>::const_iterator it = tracing_dsts.begin(); it != tracing_dsts.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } } runtime->send_remote_trace_update(origin_space, rez); // Wait to see if lhs changes done.wait(); } else remote_tpl->record_issue_fill(memo, idx, lhs, expr, fields, fill_value, fill_size, #ifdef LEGION_SPY handle, tree_id, #endif precondition, tracing_srcs, tracing_dsts); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_fill_view(FillView *view, const FieldMask &user_mask) //-------------------------------------------------------------------------- { // this should never be called on remote nodes assert(false); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_op_view(Memoizable *memo, unsigned idx, InstanceView *view, const RegionUsage &usage, const FieldMask &user_mask, bool update_validity) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_RECORD_OP_VIEW); rez.serialize(applied); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(idx); rez.serialize(view->did); rez.serialize(usage); rez.serialize(user_mask); rez.serialize<bool>(update_validity); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_op_view(memo, idx, view, usage, user_mask, update_validity); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_set_op_sync_event(ApEvent &lhs, Memoizable *memo) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent done = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_SET_OP_SYNC); rez.serialize(done); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(&lhs); rez.serialize(lhs); } runtime->send_remote_trace_update(origin_space, rez); // wait to see if lhs changes done.wait(); } else remote_tpl->record_set_op_sync_event(lhs, memo); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_mapper_output(Memoizable *memo, const Mapper::MapTaskOutput &output, const std::deque<InstanceSet> &physical_instances, std::set<RtEvent> &external_applied) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_RECORD_MAPPER_OUTPUT); rez.serialize(applied); memo->pack_remote_memoizable(rez, origin_space); // We actually only need a few things here rez.serialize<size_t>(output.target_procs.size()); for (unsigned idx = 0; idx < output.target_procs.size(); idx++) rez.serialize(output.target_procs[idx]); rez.serialize(output.chosen_variant); rez.serialize(output.task_priority); rez.serialize<bool>(output.postmap_task); rez.serialize<size_t>(physical_instances.size()); for (std::deque<InstanceSet>::const_iterator it = physical_instances.begin(); it != physical_instances.end(); it++) it->pack_references(rez); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_mapper_output(memo, output, physical_instances, external_applied); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::get_reduction_ready_events(Memoizable *memo, std::set<ApEvent> &ready_events) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent done_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_GET_REDUCTION_EVENTS); rez.serialize(done_event); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(&ready_events); } runtime->send_remote_trace_update(origin_space, rez); // Wait for the result to be ready done_event.wait(); } else remote_tpl->get_reduction_ready_events(memo, ready_events); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_set_effects(Memoizable *memo, ApEvent &rhs) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_SET_EFFECTS); rez.serialize(applied); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(rhs); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_set_effects(memo, rhs); } //-------------------------------------------------------------------------- void RemoteTraceRecorder::record_complete_replay(Memoizable *memo, ApEvent rhs) //-------------------------------------------------------------------------- { if (local_space != origin_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(remote_tpl); rez.serialize(REMOTE_TRACE_COMPLETE_REPLAY); rez.serialize(applied); memo->pack_remote_memoizable(rez, origin_space); rez.serialize(rhs); } runtime->send_remote_trace_update(origin_space, rez); AutoLock a_lock(applied_lock); applied_events.insert(applied); } else remote_tpl->record_complete_replay(memo, rhs); } //-------------------------------------------------------------------------- /*static*/ RemoteTraceRecorder* RemoteTraceRecorder::unpack_remote_recorder( Deserializer &derez, Runtime *runtime, Memoizable *memo) //-------------------------------------------------------------------------- { AddressSpaceID origin_space, local_space; derez.deserialize(origin_space); derez.deserialize(local_space); PhysicalTemplate *remote_tpl; derez.deserialize(remote_tpl); RtUserEvent applied_event; derez.deserialize(applied_event); RtEvent collect_event; derez.deserialize(collect_event); return new RemoteTraceRecorder(runtime, origin_space, local_space, memo, remote_tpl, applied_event, collect_event); } //-------------------------------------------------------------------------- /*static*/ void RemoteTraceRecorder::handle_remote_update( Deserializer &derez, Runtime *runtime, AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); PhysicalTemplate *tpl; derez.deserialize(tpl); RemoteTraceKind kind; derez.deserialize(kind); switch (kind) { case REMOTE_TRACE_RECORD_GET_TERM: { RtUserEvent applied; derez.deserialize(applied); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); tpl->record_get_term_event(memo); Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_CREATE_USER_EVENT: { RtUserEvent applied; derez.deserialize(applied); ApUserEvent lhs; derez.deserialize(lhs); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); tpl->record_create_ap_user_event(lhs, memo); Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_TRIGGER_EVENT: { RtUserEvent applied; derez.deserialize(applied); ApUserEvent lhs; derez.deserialize(lhs); ApEvent rhs; derez.deserialize(rhs); tpl->record_trigger_event(lhs, rhs); Runtime::trigger_event(applied); break; } case REMOTE_TRACE_MERGE_EVENTS: { RtUserEvent done; derez.deserialize(done); ApUserEvent *event_ptr; derez.deserialize(event_ptr); ApUserEvent lhs; derez.deserialize(lhs); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); size_t num_rhs; derez.deserialize(num_rhs); const ApUserEvent lhs_copy = lhs; if (num_rhs == 2) { ApEvent e1, e2; derez.deserialize(e1); derez.deserialize(e2); tpl->record_merge_events(lhs, e1, e2, memo); } else if (num_rhs == 3) { ApEvent e1, e2, e3; derez.deserialize(e1); derez.deserialize(e2); derez.deserialize(e3); tpl->record_merge_events(lhs, e1, e2, e3, memo); } else { std::set<ApEvent> rhs_events; for (unsigned idx = 0; idx < num_rhs; idx++) { ApEvent event; derez.deserialize(event); rhs_events.insert(event); } tpl->record_merge_events(lhs, rhs_events, memo); } if (lhs != lhs_copy) { Serializer rez; { RezCheck z2(rez); rez.serialize(REMOTE_TRACE_MERGE_EVENTS); rez.serialize(event_ptr); rez.serialize(lhs); rez.serialize(done); } runtime->send_remote_trace_response(source, rez); } else // didn't change so just trigger Runtime::trigger_event(done); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_ISSUE_COPY: { RtUserEvent done; derez.deserialize(done); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); unsigned src_idx, dst_idx; derez.deserialize(src_idx); derez.deserialize(dst_idx); ApUserEvent *lhs_ptr; derez.deserialize(lhs_ptr); ApUserEvent lhs; derez.deserialize(lhs); RegionTreeForest *forest = runtime->forest; IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez, forest, source); size_t num_fields; derez.deserialize(num_fields); std::vector<CopySrcDstField> src_fields(num_fields); std::vector<CopySrcDstField> dst_fields(num_fields); for (unsigned idx = 0; idx < num_fields; idx++) { unpack_src_dst_field(derez, src_fields[idx]); unpack_src_dst_field(derez, dst_fields[idx]); } #ifdef LEGION_SPY RegionTreeID src_tree_id, dst_tree_id; derez.deserialize(src_tree_id); derez.deserialize(dst_tree_id); #endif ApEvent precondition; derez.deserialize(precondition); ReductionOpID redop; derez.deserialize(redop); bool reduction_fold; derez.deserialize<bool>(reduction_fold); FieldMaskSet<InstanceView> tracing_srcs, tracing_dsts; std::set<RtEvent> ready_events; size_t num_srcs; derez.deserialize(num_srcs); for (unsigned idx = 0; idx < num_srcs; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; InstanceView *view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(did, ready)); if (ready.exists() && !ready.has_triggered()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); tracing_srcs.insert(view, mask); } size_t num_dsts; derez.deserialize(num_dsts); for (unsigned idx = 0; idx < num_dsts; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; InstanceView *view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(did, ready)); if (ready.exists() && !ready.has_triggered()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); tracing_dsts.insert(view, mask); } // Use this to track if lhs changes const ApUserEvent lhs_copy = lhs; if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); } // Do the base call tpl->record_issue_copy(memo, src_idx, dst_idx, lhs, expr, src_fields, dst_fields, #ifdef LEGION_SPY src_tree_id, dst_tree_id, #endif precondition, redop, reduction_fold, tracing_srcs, tracing_dsts); if (lhs != lhs_copy) { Serializer rez; { RezCheck z2(rez); rez.serialize(REMOTE_TRACE_ISSUE_COPY); rez.serialize(lhs_ptr); rez.serialize(lhs); rez.serialize(done); } runtime->send_remote_trace_response(source, rez); } else // lhs was unchanged Runtime::trigger_event(done); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_ISSUE_FILL: { RtUserEvent done; derez.deserialize(done); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); unsigned index; derez.deserialize(index); ApUserEvent *lhs_ptr; derez.deserialize(lhs_ptr); ApUserEvent lhs; derez.deserialize(lhs); RegionTreeForest *forest = runtime->forest; IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez, forest, source); size_t num_fields; derez.deserialize(num_fields); std::vector<CopySrcDstField> fields(num_fields); for (unsigned idx = 0; idx < num_fields; idx++) unpack_src_dst_field(derez, fields[idx]); size_t fill_size; derez.deserialize(fill_size); const void *fill_value = derez.get_current_pointer(); derez.advance_pointer(fill_size); #ifdef LEGION_SPY FieldSpace handle; derez.deserialize(handle); RegionTreeID tree_id; derez.deserialize(tree_id); #endif ApEvent precondition; derez.deserialize(precondition); FieldMaskSet<FillView> tracing_srcs; std::set<RtEvent> ready_events; size_t num_srcs; derez.deserialize(num_srcs); for (unsigned idx = 0; idx < num_srcs; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; FillView *view = static_cast<FillView*>( runtime->find_or_request_logical_view(did, ready)); if (ready.exists() && !ready.has_triggered()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); tracing_srcs.insert(view, mask); } FieldMaskSet<InstanceView> tracing_dsts; size_t num_dsts; derez.deserialize(num_dsts); for (unsigned idx = 0; idx < num_dsts; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; InstanceView *view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(did, ready)); if (ready.exists() && !ready.has_triggered()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); tracing_dsts.insert(view, mask); } // Use this to track if lhs changes const ApUserEvent lhs_copy = lhs; if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); } // Do the base call tpl->record_issue_fill(memo, index, lhs, expr, fields, fill_value, fill_size, #ifdef LEGION_SPY handle, tree_id, #endif precondition, tracing_srcs, tracing_dsts); if (lhs != lhs_copy) { Serializer rez; { RezCheck z2(rez); rez.serialize(REMOTE_TRACE_ISSUE_FILL); rez.serialize(lhs_ptr); rez.serialize(lhs); rez.serialize(done); } runtime->send_remote_trace_response(source, rez); } else // lhs was unchanged Runtime::trigger_event(done); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_RECORD_OP_VIEW: { RtUserEvent applied; derez.deserialize(applied); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); unsigned index; derez.deserialize(index); DistributedID did; derez.deserialize(did); RtEvent ready; InstanceView *view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(did, ready)); RegionUsage usage; derez.deserialize(usage); FieldMask user_mask; derez.deserialize(user_mask); bool update_validity; derez.deserialize<bool>(update_validity); if (ready.exists() && !ready.has_triggered()) ready.wait(); tpl->record_op_view(memo, index, view, usage, user_mask, update_validity); Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_SET_OP_SYNC: { RtUserEvent done; derez.deserialize(done); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); ApUserEvent *lhs_ptr; derez.deserialize(lhs_ptr); ApUserEvent lhs; derez.deserialize(lhs); const ApUserEvent lhs_copy = lhs; tpl->record_set_op_sync_event(lhs, memo); if (lhs != lhs_copy) { Serializer rez; { RezCheck z2(rez); rez.serialize(REMOTE_TRACE_SET_OP_SYNC); rez.serialize(lhs_ptr); rez.serialize(lhs); rez.serialize(done); } runtime->send_remote_trace_response(source, rez); } else // lhs didn't change Runtime::trigger_event(done); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_RECORD_MAPPER_OUTPUT: { RtUserEvent applied; derez.deserialize(applied); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); size_t num_target_processors; derez.deserialize(num_target_processors); Mapper::MapTaskOutput output; output.target_procs.resize(num_target_processors); for (unsigned idx = 0; idx < num_target_processors; idx++) derez.deserialize(output.target_procs[idx]); derez.deserialize(output.chosen_variant); derez.deserialize(output.task_priority); derez.deserialize<bool>(output.postmap_task); size_t num_phy_instances; derez.deserialize(num_phy_instances); std::deque<InstanceSet> physical_instances(num_phy_instances); std::set<RtEvent> ready_events; for (unsigned idx = 0; idx < num_phy_instances; idx++) physical_instances[idx].unpack_references(runtime, derez, ready_events); if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); } std::set<RtEvent> applied_events; tpl->record_mapper_output(memo, output, physical_instances, applied_events); if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_GET_REDUCTION_EVENTS: { RtUserEvent done; derez.deserialize(done); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); std::set<ApEvent> *target; derez.deserialize(target); std::set<ApEvent> result; tpl->get_reduction_ready_events(memo, result); if (!result.empty()) { Serializer rez; { RezCheck z2(rez); rez.serialize(REMOTE_TRACE_GET_REDUCTION_EVENTS); rez.serialize(target); rez.serialize<size_t>(result.size()); for (std::set<ApEvent>::const_iterator it = result.begin(); it != result.end(); it++) rez.serialize(*it); rez.serialize(done); } runtime->send_remote_trace_response(source, rez); } else Runtime::trigger_event(done); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_SET_EFFECTS: { RtUserEvent applied; derez.deserialize(applied); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); ApEvent postcondition; derez.deserialize(postcondition); tpl->record_set_effects(memo, postcondition); Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } case REMOTE_TRACE_COMPLETE_REPLAY: { RtUserEvent applied; derez.deserialize(applied); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, NULL/*op*/, runtime); ApEvent ready_event; derez.deserialize(ready_event); tpl->record_complete_replay(memo, ready_event); Runtime::trigger_event(applied); if (memo->get_origin_space() != runtime->address_space) delete memo; break; } default: assert(false); } } //-------------------------------------------------------------------------- /*static*/ void RemoteTraceRecorder::handle_remote_response( Deserializer &derez) //-------------------------------------------------------------------------- { DerezCheck z(derez); RemoteTraceKind kind; derez.deserialize(kind); switch (kind) { case REMOTE_TRACE_MERGE_EVENTS: case REMOTE_TRACE_ISSUE_COPY: case REMOTE_TRACE_ISSUE_FILL: case REMOTE_TRACE_SET_OP_SYNC: { ApUserEvent *event_ptr; derez.deserialize(event_ptr); derez.deserialize(*event_ptr); RtUserEvent done; derez.deserialize(done); Runtime::trigger_event(done); break; } case REMOTE_TRACE_GET_REDUCTION_EVENTS: { std::set<ApEvent> *target; derez.deserialize(target); size_t num_events; derez.deserialize(num_events); for (unsigned idx = 0; idx < num_events; idx++) { ApEvent event; derez.deserialize(event); target->insert(event); } RtUserEvent done; derez.deserialize(done); Runtime::trigger_event(done); break; } default: assert(false); } } //-------------------------------------------------------------------------- /*static*/ void RemoteTraceRecorder::pack_src_dst_field( Serializer &rez, const CopySrcDstField &field) //-------------------------------------------------------------------------- { RezCheck z(rez); rez.serialize(field.inst); rez.serialize(field.field_id); rez.serialize(field.size); rez.serialize(field.redop_id); rez.serialize<bool>(field.red_fold); rez.serialize(field.serdez_id); rez.serialize(field.subfield_offset); rez.serialize(field.indirect_index); rez.serialize(field.fill_data.indirect); #ifdef LEGION_SPY rez.serialize(field.inst_event); #endif } //-------------------------------------------------------------------------- /*static*/ void RemoteTraceRecorder::unpack_src_dst_field( Deserializer &derez, CopySrcDstField &field) //-------------------------------------------------------------------------- { DerezCheck z(derez); derez.deserialize(field.inst); derez.deserialize(field.field_id); derez.deserialize(field.size); derez.deserialize(field.redop_id); derez.deserialize<bool>(field.red_fold); derez.deserialize(field.serdez_id); derez.deserialize(field.subfield_offset); derez.deserialize(field.indirect_index); derez.deserialize(field.fill_data.indirect); #ifdef LEGION_SPY derez.deserialize(field.inst_event); #endif } ///////////////////////////////////////////////////////////// // TraceInfo ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- TraceInfo::TraceInfo(Operation *o, bool init) : op(o), memo((op == NULL) ? NULL : op->get_memoizable()), rec((memo == NULL) ? NULL : memo->get_template()), recording((rec == NULL) ? false : rec->is_recording()) //-------------------------------------------------------------------------- { if (recording && init) record_get_term_event(); if (rec != NULL) rec->add_recorder_reference(); } //-------------------------------------------------------------------------- TraceInfo::TraceInfo(const TraceInfo &rhs) : op(rhs.op), memo(rhs.memo), rec(rhs.rec), recording(rhs.recording) //-------------------------------------------------------------------------- { if (rec != NULL) rec->add_recorder_reference(); } //-------------------------------------------------------------------------- TraceInfo::TraceInfo(const TraceInfo &rhs, Operation *o) : op(o), memo(o->get_memoizable()), rec(rhs.rec), recording(rhs.recording) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(memo != NULL); #endif if (rec != NULL) rec->add_recorder_reference(); } //-------------------------------------------------------------------------- TraceInfo::~TraceInfo(void) //-------------------------------------------------------------------------- { if ((rec != NULL) && rec->remove_recorder_reference()) delete rec; } //-------------------------------------------------------------------------- TraceInfo::TraceInfo(Operation *o, Memoizable *m, PhysicalTraceRecorder *r, const bool record) : op(o), memo(m), rec(r), recording(record) //-------------------------------------------------------------------------- { if (rec != NULL) rec->add_recorder_reference(); } //-------------------------------------------------------------------------- void TraceInfo::pack_remote_trace_info(Serializer &rez, AddressSpaceID target, std::set<RtEvent> &applied) const //-------------------------------------------------------------------------- { rez.serialize<bool>(recording); if (recording) { // Only need to pack these if we're recording memo->pack_remote_memoizable(rez, target); rec->pack_recorder(rez, applied, target); } } //-------------------------------------------------------------------------- /*static*/ TraceInfo* TraceInfo::unpack_remote_trace_info( Deserializer &derez, Operation *op, Runtime *runtime) //-------------------------------------------------------------------------- { bool recording; derez.deserialize<bool>(recording); if (recording) { Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, op, runtime); // PhysicalTraceRecord takes possible ownership of memoizable PhysicalTraceRecorder *rec = RemoteTraceRecorder::unpack_remote_recorder(derez, runtime, memo); return new TraceInfo(op, memo, rec, true/*recording*/); } else return new TraceInfo(op, NULL, NULL, false/*recording*/); } ///////////////////////////////////////////////////////////// // PhysicalTraceInfo ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- PhysicalTraceInfo::PhysicalTraceInfo(Operation *o, unsigned idx, bool init) : TraceInfo(o, init), index(idx), dst_index(idx), update_validity(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalTraceInfo::PhysicalTraceInfo(const TraceInfo &info, unsigned idx, bool update/*=true*/) : TraceInfo(info), index(idx), dst_index(idx), update_validity(update) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalTraceInfo::PhysicalTraceInfo(unsigned src_idx, const TraceInfo &info,unsigned dst_idx) : TraceInfo(info), index(src_idx), dst_index(dst_idx), update_validity(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalTraceInfo::PhysicalTraceInfo(const PhysicalTraceInfo &rhs) : TraceInfo(rhs), index(rhs.index), dst_index(rhs.dst_index), update_validity(rhs.update_validity) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalTraceInfo::PhysicalTraceInfo(Operation *o, Memoizable *m, unsigned src_idx,unsigned dst_idx,bool update,PhysicalTraceRecorder *r) : TraceInfo(o, m, r, (m != NULL)), index(src_idx), dst_index(dst_idx), update_validity(update) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<> void PhysicalTraceInfo::pack_trace_info<true>(Serializer &rez, std::set<RtEvent> &applied, const AddressSpaceID target) const //-------------------------------------------------------------------------- { rez.serialize<bool>(recording); if (recording) { #ifdef DEBUG_LEGION assert(op != NULL); assert(memo != NULL); assert(rec != NULL); #endif op->pack_remote_operation(rez, target, applied); memo->pack_remote_memoizable(rez, target); rez.serialize(index); rez.serialize(dst_index); rez.serialize<bool>(update_validity); rec->pack_recorder(rez, applied, target); } } //-------------------------------------------------------------------------- template<> void PhysicalTraceInfo::pack_trace_info<false>(Serializer &rez, std::set<RtEvent> &applied, const AddressSpaceID target) const //-------------------------------------------------------------------------- { rez.serialize<bool>(recording); if (recording) { #ifdef DEBUG_LEGION assert(memo != NULL); assert(rec != NULL); #endif memo->pack_remote_memoizable(rez, target); rez.serialize(index); rez.serialize(dst_index); rez.serialize<bool>(update_validity); rec->pack_recorder(rez, applied, target); } } //-------------------------------------------------------------------------- /*static*/ PhysicalTraceInfo PhysicalTraceInfo::unpack_trace_info( Deserializer &derez, Runtime *runtime, std::set<RtEvent> &ready_events) //-------------------------------------------------------------------------- { bool recording; derez.deserialize<bool>(recording); if (recording) { RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, op, runtime); unsigned index, dst_index; derez.deserialize(index); derez.deserialize(dst_index); bool update_validity; derez.deserialize(update_validity); // PhysicalTraceRecord takes possible ownership of memoizable PhysicalTraceRecorder *recorder = RemoteTraceRecorder::unpack_remote_recorder(derez, runtime, memo); return PhysicalTraceInfo(op, memo, index, dst_index, update_validity, recorder); } else return PhysicalTraceInfo(NULL, -1U, false); } //-------------------------------------------------------------------------- /*static*/ PhysicalTraceInfo PhysicalTraceInfo::unpack_trace_info( Deserializer &derez, Runtime *runtime, Operation *op) //-------------------------------------------------------------------------- { bool recording; derez.deserialize<bool>(recording); if (recording) { #ifdef DEBUG_LEGION assert(op != NULL); #endif Memoizable *memo = RemoteMemoizable::unpack_remote_memoizable(derez, op, runtime); unsigned index, dst_index; derez.deserialize(index); derez.deserialize(dst_index); bool update_validity; derez.deserialize(update_validity); // PhysicalTraceRecord takes possible ownership of memoizable RemoteTraceRecorder *recorder = RemoteTraceRecorder::unpack_remote_recorder(derez, runtime, memo); return PhysicalTraceInfo(op, memo, index, dst_index, update_validity, recorder); } else return PhysicalTraceInfo(op, -1U, false); } ///////////////////////////////////////////////////////////// // ProjectionInfo ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- ProjectionInfo::ProjectionInfo(Runtime *runtime, const RegionRequirement &req, IndexSpaceNode *launch_space) : projection((req.handle_type != SINGULAR) ? runtime->find_projection_function(req.projection) : NULL), projection_type(req.handle_type), projection_space(launch_space) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // PathTraverser ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- PathTraverser::PathTraverser(RegionTreePath &p) : path(p) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PathTraverser::PathTraverser(const PathTraverser &rhs) : path(rhs.path) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- PathTraverser::~PathTraverser(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PathTraverser& PathTraverser::operator=(const PathTraverser &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool PathTraverser::traverse(RegionTreeNode *node) //-------------------------------------------------------------------------- { // Continue visiting nodes and then finding their children // until we have traversed the entire path. while (true) { #ifdef DEBUG_LEGION assert(node != NULL); #endif depth = node->get_depth(); has_child = path.has_child(depth); if (has_child) next_child = path.get_child(depth); bool continue_traversal = node->visit_node(this); if (!continue_traversal) return false; if (!has_child) break; node = node->get_tree_child(next_child); } return true; } ///////////////////////////////////////////////////////////// // LogicalPathRegistrar ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalPathRegistrar::LogicalPathRegistrar(ContextID c, Operation *o, const FieldMask &m, RegionTreePath &p) : PathTraverser(p), ctx(c), field_mask(m), op(o) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalPathRegistrar::LogicalPathRegistrar(const LogicalPathRegistrar&rhs) : PathTraverser(rhs.path), ctx(0), field_mask(FieldMask()), op(NULL) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- LogicalPathRegistrar::~LogicalPathRegistrar(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalPathRegistrar& LogicalPathRegistrar::operator=( const LogicalPathRegistrar &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool LogicalPathRegistrar::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { node->register_logical_dependences(ctx, op, field_mask,false/*dominate*/); if (!has_child) { // If we're at the bottom, fan out and do all the children LogicalRegistrar registrar(ctx, op, field_mask, false); return node->visit_node(&registrar); } return true; } //-------------------------------------------------------------------------- bool LogicalPathRegistrar::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { node->register_logical_dependences(ctx, op, field_mask,false/*dominate*/); if (!has_child) { // If we're at the bottom, fan out and do all the children LogicalRegistrar registrar(ctx, op, field_mask, false); return node->visit_node(&registrar); } return true; } ///////////////////////////////////////////////////////////// // LogicalRegistrar ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalRegistrar::LogicalRegistrar(ContextID c, Operation *o, const FieldMask &m, bool dom) : ctx(c), field_mask(m), op(o), dominate(dom) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalRegistrar::LogicalRegistrar(const LogicalRegistrar &rhs) : ctx(0), field_mask(FieldMask()), op(NULL), dominate(rhs.dominate) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- LogicalRegistrar::~LogicalRegistrar(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalRegistrar& LogicalRegistrar::operator=(const LogicalRegistrar &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool LogicalRegistrar::visit_only_valid(void) const //-------------------------------------------------------------------------- { return false; } //-------------------------------------------------------------------------- bool LogicalRegistrar::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { node->register_logical_dependences(ctx, op, field_mask, dominate); return true; } //-------------------------------------------------------------------------- bool LogicalRegistrar::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { node->register_logical_dependences(ctx, op, field_mask, dominate); return true; } ///////////////////////////////////////////////////////////// // CurrentInitializer ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- CurrentInitializer::CurrentInitializer(ContextID c) : ctx(c) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CurrentInitializer::CurrentInitializer(const CurrentInitializer &rhs) : ctx(0) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- CurrentInitializer::~CurrentInitializer(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CurrentInitializer& CurrentInitializer::operator=( const CurrentInitializer &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool CurrentInitializer::visit_only_valid(void) const //-------------------------------------------------------------------------- { return false; } //-------------------------------------------------------------------------- bool CurrentInitializer::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { node->initialize_current_state(ctx); return true; } //-------------------------------------------------------------------------- bool CurrentInitializer::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { node->initialize_current_state(ctx); return true; } ///////////////////////////////////////////////////////////// // CurrentInvalidator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- CurrentInvalidator::CurrentInvalidator(ContextID c, bool only) : ctx(c), users_only(only) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CurrentInvalidator::CurrentInvalidator(const CurrentInvalidator &rhs) : ctx(0), users_only(false) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- CurrentInvalidator::~CurrentInvalidator(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CurrentInvalidator& CurrentInvalidator::operator=( const CurrentInvalidator &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool CurrentInvalidator::visit_only_valid(void) const //-------------------------------------------------------------------------- { return false; } //-------------------------------------------------------------------------- bool CurrentInvalidator::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { node->invalidate_current_state(ctx, users_only); return true; } //-------------------------------------------------------------------------- bool CurrentInvalidator::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { node->invalidate_current_state(ctx, users_only); return true; } ///////////////////////////////////////////////////////////// // DeletionInvalidator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- DeletionInvalidator::DeletionInvalidator(ContextID c, const FieldMask &dm) : ctx(c), deletion_mask(dm) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- DeletionInvalidator::DeletionInvalidator(const DeletionInvalidator &rhs) : ctx(0), deletion_mask(rhs.deletion_mask) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- DeletionInvalidator::~DeletionInvalidator(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- DeletionInvalidator& DeletionInvalidator::operator=( const DeletionInvalidator &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- bool DeletionInvalidator::visit_only_valid(void) const //-------------------------------------------------------------------------- { return false; } //-------------------------------------------------------------------------- bool DeletionInvalidator::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { node->invalidate_deleted_state(ctx, deletion_mask); return true; } //-------------------------------------------------------------------------- bool DeletionInvalidator::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { node->invalidate_deleted_state(ctx, deletion_mask); return true; } ///////////////////////////////////////////////////////////// // Projection Epoch ///////////////////////////////////////////////////////////// // C++ is really dumb const ProjectionEpochID ProjectionEpoch::first_epoch; //-------------------------------------------------------------------------- ProjectionEpoch::ProjectionEpoch(ProjectionEpochID id, const FieldMask &m) : epoch_id(id), valid_fields(m) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ProjectionEpoch::ProjectionEpoch(const ProjectionEpoch &rhs) : epoch_id(rhs.epoch_id), valid_fields(rhs.valid_fields) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- ProjectionEpoch::~ProjectionEpoch(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ProjectionEpoch& ProjectionEpoch::operator=(const ProjectionEpoch &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void ProjectionEpoch::insert(ProjectionFunction *function, IndexSpaceNode* node) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!valid_fields); #endif write_projections[function].insert(node); } ///////////////////////////////////////////////////////////// // LogicalState ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalState::LogicalState(RegionTreeNode *node, ContextID ctx) : owner(node) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalState::LogicalState(const LogicalState &rhs) : owner(NULL) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- LogicalState::~LogicalState(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalState& LogicalState::operator=(const LogicalState&rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void LogicalState::check_init(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(field_states.empty()); assert(curr_epoch_users.empty()); assert(prev_epoch_users.empty()); assert(projection_epochs.empty()); assert(!reduction_fields); #endif } //-------------------------------------------------------------------------- void LogicalState::clear_logical_users(void) //-------------------------------------------------------------------------- { if (!curr_epoch_users.empty()) { for (LegionList<LogicalUser,CURR_LOGICAL_ALLOC>::track_aligned:: const_iterator it = curr_epoch_users.begin(); it != curr_epoch_users.end(); it++) { it->op->remove_mapping_reference(it->gen); } curr_epoch_users.clear(); } if (!prev_epoch_users.empty()) { for (LegionList<LogicalUser,PREV_LOGICAL_ALLOC>::track_aligned:: const_iterator it = prev_epoch_users.begin(); it != prev_epoch_users.end(); it++) { it->op->remove_mapping_reference(it->gen); } prev_epoch_users.clear(); } } //-------------------------------------------------------------------------- void LogicalState::reset(void) //-------------------------------------------------------------------------- { field_states.clear(); clear_logical_users(); reduction_fields.clear(); outstanding_reductions.clear(); for (std::list<ProjectionEpoch*>::const_iterator it = projection_epochs.begin(); it != projection_epochs.end(); it++) delete *it; projection_epochs.clear(); } //-------------------------------------------------------------------------- void LogicalState::clear_deleted_state(const FieldMask &deleted_mask) //-------------------------------------------------------------------------- { for (LegionList<FieldState>::aligned::iterator it = field_states.begin(); it != field_states.end(); /*nothing*/) { if (it->filter(deleted_mask)) it = field_states.erase(it); else it++; } reduction_fields -= deleted_mask; if (!outstanding_reductions.empty()) { std::vector<ReductionOpID> to_delete; for (LegionMap<ReductionOpID,FieldMask>::aligned::iterator it = outstanding_reductions.begin(); it != outstanding_reductions.end(); it++) { it->second -= deleted_mask; if (!it->second) to_delete.push_back(it->first); } for (std::vector<ReductionOpID>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { outstanding_reductions.erase(*it); } } } //-------------------------------------------------------------------------- void LogicalState::advance_projection_epochs(const FieldMask &advance_mask) //-------------------------------------------------------------------------- { // See if we can get some coalescing going on here std::map<ProjectionEpochID,ProjectionEpoch*> to_add; for (std::list<ProjectionEpoch*>::iterator it = projection_epochs.begin(); it != projection_epochs.end(); /*nothing*/) { FieldMask overlap = (*it)->valid_fields & advance_mask; if (!overlap) { it++; continue; } const ProjectionEpochID next_epoch_id = (*it)->epoch_id + 1; std::map<ProjectionEpochID,ProjectionEpoch*>::iterator finder = to_add.find(next_epoch_id); if (finder == to_add.end()) { ProjectionEpoch *next_epoch = new ProjectionEpoch((*it)->epoch_id+1, overlap); to_add[next_epoch_id] = next_epoch; } else finder->second->valid_fields |= overlap; // Filter the fields from our old one (*it)->valid_fields -= overlap; if (!((*it)->valid_fields)) { delete (*it); it = projection_epochs.erase(it); } else it++; } if (!to_add.empty()) { for (std::map<ProjectionEpochID,ProjectionEpoch*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) projection_epochs.push_back(it->second); } } //-------------------------------------------------------------------------- void LogicalState::update_projection_epochs(FieldMask capture_mask, const ProjectionInfo &info) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!capture_mask); #endif for (std::list<ProjectionEpoch*>::const_iterator it = projection_epochs.begin(); it != projection_epochs.end(); it++) { FieldMask overlap = (*it)->valid_fields & capture_mask; if (!overlap) continue; capture_mask -= overlap; if (!capture_mask) return; } // If it didn't already exist, start a new projection epoch ProjectionEpoch *new_epoch = new ProjectionEpoch(ProjectionEpoch::first_epoch, capture_mask); projection_epochs.push_back(new_epoch); } ///////////////////////////////////////////////////////////// // FieldState ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- FieldState::FieldState(void) : open_state(NOT_OPEN), redop(0), projection(NULL), projection_space(NULL), rebuild_timeout(1) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FieldState::FieldState(const GenericUser &user, const FieldMask &m, RegionTreeNode *child, std::set<RtEvent> &applied) : redop(0), projection(NULL), projection_space(NULL), rebuild_timeout(1) //-------------------------------------------------------------------------- { if (IS_READ_ONLY(user.usage)) open_state = OPEN_READ_ONLY; else if (IS_WRITE(user.usage)) open_state = OPEN_READ_WRITE; else if (IS_REDUCE(user.usage)) { open_state = OPEN_SINGLE_REDUCE; redop = user.usage.redop; } if (open_children.insert(child, m)) { WrapperReferenceMutator mutator(applied); child->add_base_valid_ref(FIELD_STATE_REF, &mutator); } } //-------------------------------------------------------------------------- FieldState::FieldState(const RegionUsage &usage, const FieldMask &m, ProjectionFunction *proj, IndexSpaceNode *proj_space, bool disjoint, bool dirty_reduction) : redop(0),projection(proj),projection_space(proj_space),rebuild_timeout(1) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(projection != NULL); #endif open_children.relax_valid_mask(m); if (IS_READ_ONLY(usage)) open_state = OPEN_READ_ONLY_PROJ; else if (IS_REDUCE(usage)) { if (dirty_reduction) open_state = OPEN_REDUCE_PROJ_DIRTY; else open_state = OPEN_REDUCE_PROJ; redop = usage.redop; } else if (disjoint && (projection->depth == 0)) open_state = OPEN_READ_WRITE_PROJ_DISJOINT_SHALLOW; else open_state = OPEN_READ_WRITE_PROJ; } //-------------------------------------------------------------------------- FieldState::FieldState(const FieldState &rhs) : open_state(rhs.open_state), redop(rhs.redop), projection(rhs.projection), projection_space(rhs.projection_space), rebuild_timeout(rhs.rebuild_timeout) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(rhs.open_children.empty()); #endif } //-------------------------------------------------------------------------- FieldState::~FieldState(void) //-------------------------------------------------------------------------- { for (FieldMaskSet<RegionTreeNode>::const_iterator it = open_children.begin(); it != open_children.end(); it++) if (it->first->remove_base_valid_ref(FIELD_STATE_REF)) delete it->first; } //-------------------------------------------------------------------------- FieldState& FieldState::operator=(const FieldState &rhs) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(open_children.empty()); assert(rhs.open_children.empty()); #endif open_state = rhs.open_state; redop = rhs.redop; projection = rhs.projection; projection_space = rhs.projection_space; rebuild_timeout = rhs.rebuild_timeout; return *this; } //-------------------------------------------------------------------------- bool FieldState::overlaps(const FieldState &rhs) const //-------------------------------------------------------------------------- { if (redop != rhs.redop) return false; if (projection != rhs.projection) return false; // Only do this test if they are both projections if ((projection != NULL) && (projection_space != rhs.projection_space)) return false; if (redop == 0) return (open_state == rhs.open_state); else { #ifdef DEBUG_LEGION assert((open_state == OPEN_SINGLE_REDUCE) || (open_state == OPEN_MULTI_REDUCE) || (open_state == OPEN_REDUCE_PROJ) || (open_state == OPEN_REDUCE_PROJ_DIRTY)); assert((rhs.open_state == OPEN_SINGLE_REDUCE) || (rhs.open_state == OPEN_MULTI_REDUCE) || (rhs.open_state == OPEN_REDUCE_PROJ) || (rhs.open_state == OPEN_REDUCE_PROJ_DIRTY)); #endif // Only support merging reduction fields with exactly the // same mask which should be single fields for reductions return (valid_fields() == rhs.valid_fields()); } } //-------------------------------------------------------------------------- void FieldState::merge(FieldState &rhs, RegionTreeNode *node) //-------------------------------------------------------------------------- { for (FieldMaskSet<RegionTreeNode>::const_iterator it = rhs.open_children.begin(); it != rhs.open_children.end(); it++) // Remove duplicate references if we already had it if (!open_children.insert(it->first, it->second)) it->first->remove_base_valid_ref(FIELD_STATE_REF); rhs.open_children.clear(); #ifdef DEBUG_LEGION assert(redop == rhs.redop); assert(projection == rhs.projection); #endif if (redop > 0) { #ifdef DEBUG_LEGION assert(!open_children.empty()); #endif // For the reductions, handle the case where we need to merge // reduction modes, if they are all disjoint, we don't need // to distinguish between single and multi reduce if (node->are_all_children_disjoint()) { open_state = OPEN_READ_WRITE; redop = 0; } else { if (open_children.size() == 1) open_state = OPEN_SINGLE_REDUCE; else open_state = OPEN_MULTI_REDUCE; } } } //-------------------------------------------------------------------------- bool FieldState::filter(const FieldMask &mask) //-------------------------------------------------------------------------- { if (is_projection_state()) { #ifdef DEBUG_LEGION assert(projection != NULL); assert(open_children.empty()); #endif open_children.filter_valid_mask(mask); return !open_children.get_valid_mask(); } else { std::vector<RegionTreeNode*> to_delete; for (FieldMaskSet<RegionTreeNode>::iterator it = open_children.begin(); it != open_children.end(); it++) { it.filter(mask); if (!it->second) to_delete.push_back(it->first); } if (to_delete.size() < open_children.size()) { for (std::vector<RegionTreeNode*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { open_children.erase(*it); if ((*it)->remove_base_valid_ref(FIELD_STATE_REF)) delete (*it); } } else { open_children.clear(); for (std::vector<RegionTreeNode*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) if ((*it)->remove_base_valid_ref(FIELD_STATE_REF)) delete (*it); } open_children.tighten_valid_mask(); return open_children.empty(); } } //-------------------------------------------------------------------------- void FieldState::add_child(RegionTreeNode *child, const FieldMask &mask, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { if (open_children.insert(child, mask)) { WrapperReferenceMutator mutator(applied_events); child->add_base_valid_ref(FIELD_STATE_REF, &mutator); } } //-------------------------------------------------------------------------- void FieldState::remove_child(RegionTreeNode *child) //-------------------------------------------------------------------------- { FieldMaskSet<RegionTreeNode>::iterator finder = open_children.find(child); #ifdef DEBUG_LEGION assert(finder != open_children.end()); assert(!finder->second); #endif open_children.erase(finder); if (child->remove_base_valid_ref(FIELD_STATE_REF)) delete child; } //-------------------------------------------------------------------------- bool FieldState::projection_domain_dominates( IndexSpaceNode *next_space) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(projection_space != NULL); #endif if (projection_space == next_space) return true; // If the domains do not have the same type, the answer must be no if (projection_space->handle.get_type_tag() != next_space->handle.get_type_tag()) return false; return projection_space->dominates(next_space); } //-------------------------------------------------------------------------- void FieldState::print_state(TreeStateLogger *logger, const FieldMask &capture_mask, RegionNode *node) const //-------------------------------------------------------------------------- { switch (open_state) { case NOT_OPEN: { logger->log("Field State: NOT OPEN (%ld)", open_children.size()); break; } case OPEN_READ_WRITE: { logger->log("Field State: OPEN READ WRITE (%ld)", open_children.size()); break; } case OPEN_READ_ONLY: { logger->log("Field State: OPEN READ-ONLY (%ld)", open_children.size()); break; } case OPEN_SINGLE_REDUCE: { logger->log("Field State: OPEN SINGLE REDUCE Mode %d (%ld)", redop, open_children.size()); break; } case OPEN_MULTI_REDUCE: { logger->log("Field State: OPEN MULTI REDUCE Mode %d (%ld)", redop, open_children.size()); break; } case OPEN_READ_ONLY_PROJ: { logger->log("Field State: OPEN READ-ONLY PROJECTION %d", projection->projection_id); break; } case OPEN_READ_WRITE_PROJ: { logger->log("Field State: OPEN READ WRITE PROJECTION %d", projection->projection_id); break; } case OPEN_READ_WRITE_PROJ_DISJOINT_SHALLOW: { logger->log("Field State: OPEN READ WRITE PROJECTION (Disjoint Shallow) %d", projection->projection_id); break; } case OPEN_REDUCE_PROJ: { logger->log("Field State: OPEN REDUCE PROJECTION %d Mode %d", projection->projection_id, redop); break; } case OPEN_REDUCE_PROJ_DIRTY: { logger->log("Field State: OPEN REDUCE PROJECTION (Dirty) %d Mode %d", projection->projection_id, redop); break; } default: assert(false); } logger->down(); for (FieldMaskSet<RegionTreeNode>::const_iterator it = open_children.begin(); it != open_children.end(); it++) { FieldMask overlap = it->second & capture_mask; if (!overlap) continue; char *mask_buffer = overlap.to_string(); logger->log("Color %d Mask %s", it->first->get_color(), mask_buffer); free(mask_buffer); } logger->up(); } //-------------------------------------------------------------------------- void FieldState::print_state(TreeStateLogger *logger, const FieldMask &capture_mask, PartitionNode *node) const //-------------------------------------------------------------------------- { switch (open_state) { case NOT_OPEN: { logger->log("Field State: NOT OPEN (%ld)", open_children.size()); break; } case OPEN_READ_WRITE: { logger->log("Field State: OPEN READ WRITE (%ld)", open_children.size()); break; } case OPEN_READ_ONLY: { logger->log("Field State: OPEN READ-ONLY (%ld)", open_children.size()); break; } case OPEN_SINGLE_REDUCE: { logger->log("Field State: OPEN SINGLE REDUCE Mode %d (%ld)", redop, open_children.size()); break; } case OPEN_MULTI_REDUCE: { logger->log("Field State: OPEN MULTI REDUCE Mode %d (%ld)", redop, open_children.size()); break; } case OPEN_READ_ONLY_PROJ: { logger->log("Field State: OPEN READ-ONLY PROJECTION %d", projection->projection_id); break; } case OPEN_READ_WRITE_PROJ: { logger->log("Field State: OPEN READ WRITE PROJECTION %d", projection->projection_id); break; } case OPEN_READ_WRITE_PROJ_DISJOINT_SHALLOW: { logger->log("Field State: OPEN READ WRITE PROJECTION (Disjoint Shallow) %d", projection->projection_id); break; } case OPEN_REDUCE_PROJ: { logger->log("Field State: OPEN REDUCE PROJECTION %d Mode %d", projection->projection_id, redop); break; } case OPEN_REDUCE_PROJ_DIRTY: { logger->log("Field State: OPEN REDUCE PROJECTION (Dirty) %d Mode %d", projection->projection_id, redop); break; } default: assert(false); } logger->down(); for (FieldMaskSet<RegionTreeNode>::const_iterator it = open_children.begin(); it != open_children.end(); it++) { IndexSpaceNode *color_space = node->row_source->color_space; DomainPoint color = color_space->delinearize_color_to_point(it->first->get_color()); FieldMask overlap = it->second & capture_mask; if (!overlap) continue; char *mask_buffer = overlap.to_string(); switch (color.get_dim()) { case 1: { logger->log("Color %d Mask %s", color[0], mask_buffer); break; } #if LEGION_MAX_DIM >= 2 case 2: { logger->log("Color (%d,%d) Mask %s", color[0], color[1], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 3 case 3: { logger->log("Color (%d,%d,%d) Mask %s", color[0], color[1], color[2], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 4 case 4: { logger->log("Color (%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 5 case 5: { logger->log("Color (%d,%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], color[4], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 6 case 6: { logger->log("Color (%d,%d,%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], color[4], color[5], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 7 case 7: { logger->log("Color (%d,%d,%d,%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], color[4], color[5], color[6], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 8 case 8: { logger->log("Color (%d,%d,%d,%d,%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], color[4], color[5], color[6], color[7], mask_buffer); break; } #endif #if LEGION_MAX_DIM >= 9 case 9: { logger->log("Color (%d,%d,%d,%d,%d,%d,%d,%d,%d) Mask %s", color[0], color[1], color[2], color[3], color[4], color[5], color[6], color[7], color[8], mask_buffer); break; } #endif default: assert(false); // implemenent more dimensions } free(mask_buffer); } logger->up(); } ///////////////////////////////////////////////////////////// // Logical Closer ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalCloser::LogicalCloser(ContextID c, const LogicalUser &u, RegionTreeNode *r, bool val) : ctx(c), user(u), root_node(r), validates(val), close_op(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalCloser::LogicalCloser(const LogicalCloser &rhs) : user(rhs.user), root_node(rhs.root_node), validates(rhs.validates) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- LogicalCloser::~LogicalCloser(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalCloser& LogicalCloser::operator=(const LogicalCloser &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void LogicalCloser::record_close_operation(const FieldMask &mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!mask); #endif close_mask |= mask; } //-------------------------------------------------------------------------- void LogicalCloser::record_closed_user(const LogicalUser &user, const FieldMask &mask) //-------------------------------------------------------------------------- { closed_users.push_back(user); LogicalUser &closed_user = closed_users.back(); closed_user.field_mask = mask; } #ifndef LEGION_SPY //-------------------------------------------------------------------------- void LogicalCloser::pop_closed_user(void) //-------------------------------------------------------------------------- { closed_users.pop_back(); } #endif //-------------------------------------------------------------------------- void LogicalCloser::initialize_close_operations(LogicalState &state, Operation *creator, const LogicalTraceInfo &trace_info) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION // These sets of fields better be disjoint assert(!!close_mask); assert(close_op == NULL); #endif // Construct a reigon requirement for this operation // All privileges are based on the parent logical region RegionRequirement req; if (root_node->is_region()) req = RegionRequirement(root_node->as_region_node()->handle, READ_WRITE, EXCLUSIVE, trace_info.req.parent); else req = RegionRequirement(root_node->as_partition_node()->handle, 0, READ_WRITE, EXCLUSIVE, trace_info.req.parent); close_op = creator->runtime->get_available_merge_close_op(); merge_close_gen = close_op->get_generation(); req.privilege_fields.clear(); root_node->column_source->get_field_set(close_mask, trace_info.req.privilege_fields, req.privilege_fields); close_op->initialize(creator->get_context(), req, trace_info, trace_info.req_idx, close_mask, creator); } //-------------------------------------------------------------------------- void LogicalCloser::perform_dependence_analysis(const LogicalUser &current, const FieldMask &open_below, LegionList<LogicalUser,CURR_LOGICAL_ALLOC>::track_aligned &cusers, LegionList<LogicalUser,PREV_LOGICAL_ALLOC>::track_aligned &pusers) //-------------------------------------------------------------------------- { // We also need to do dependence analysis against all the other operations // that this operation recorded dependences on above in the tree so we // don't run too early. LegionList<LogicalUser,LOGICAL_REC_ALLOC>::track_aligned &above_users = current.op->get_logical_records(); const LogicalUser merge_close_user(close_op, 0/*idx*/, RegionUsage(READ_WRITE, EXCLUSIVE, 0/*redop*/), close_mask); register_dependences(close_op, merge_close_user, current, open_below, closed_users, above_users, cusers, pusers); // Now we can remove our references on our local users for (LegionList<LogicalUser>::aligned::const_iterator it = closed_users.begin(); it != closed_users.end(); it++) { it->op->remove_mapping_reference(it->gen); } } // If you are looking for LogicalCloser::register_dependences it can // be found in region_tree.cc to make sure that templates are instantiated //-------------------------------------------------------------------------- void LogicalCloser::update_state(LogicalState &state) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(state.owner == root_node); #endif root_node->filter_prev_epoch_users(state, close_mask); root_node->filter_curr_epoch_users(state, close_mask); } //-------------------------------------------------------------------------- void LogicalCloser::register_close_operations( LegionList<LogicalUser,CURR_LOGICAL_ALLOC>::track_aligned &users) //-------------------------------------------------------------------------- { // No need to add mapping references, we did that in // Note we also use the cached generation IDs since the close // operations have already been kicked off and might be done // LogicalCloser::register_dependences const LogicalUser close_user(close_op, merge_close_gen,0/*idx*/, RegionUsage(READ_WRITE, EXCLUSIVE, 0/*redop*/), close_mask); users.push_back(close_user); } ///////////////////////////////////////////////////////////// // KDNode ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- template<int DIM> KDNode<DIM>::KDNode(IndexSpaceExpression *expr, Runtime *rt, int ref_dim, int last) : runtime(rt), bounds(get_bounds(expr)), refinement_dim(ref_dim), last_changed_dim(last) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(ref_dim < DIM); #endif } //-------------------------------------------------------------------------- template<int DIM> KDNode<DIM>::KDNode(const Rect<DIM> &rect, Runtime *rt, int ref_dim, int last_dim) : runtime(rt), bounds(rect), refinement_dim(ref_dim), last_changed_dim(last_dim) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(ref_dim < DIM); #endif } //-------------------------------------------------------------------------- template<int DIM> KDNode<DIM>::KDNode(const KDNode<DIM> &rhs) : runtime(rhs.runtime), bounds(rhs.bounds), refinement_dim(rhs.refinement_dim), last_changed_dim(rhs.last_changed_dim) //-------------------------------------------------------------------------- { // Should never be called assert(false); } //-------------------------------------------------------------------------- template<int DIM> KDNode<DIM>::~KDNode(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM> KDNode<DIM>& KDNode<DIM>::operator=(const KDNode<DIM> &rhs) //-------------------------------------------------------------------------- { // Should never be called assert(false); return *this; } //-------------------------------------------------------------------------- template<int DIM> /*static*/ Rect<DIM> KDNode<DIM>::get_bounds(IndexSpaceExpression *expr) //-------------------------------------------------------------------------- { ApEvent wait_on; const Domain d = expr->get_domain(wait_on, true/*tight*/); if (wait_on.exists()) wait_on.wait(); return d.bounds<DIM,coord_t>(); } //-------------------------------------------------------------------------- template<int DIM> bool KDNode<DIM>::refine(std::vector<EquivalenceSet*> &subsets, const FieldMask &refinement_mask, unsigned max_depth) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(subsets.size() > LEGION_MAX_BVH_FANOUT); #endif std::vector<Rect<DIM> > subset_bounds(subsets.size()); for (unsigned idx = 0; idx < subsets.size(); idx++) subset_bounds[idx] = get_bounds(subsets[idx]->set_expr); // Compute a splitting plane coord_t split = 0; { // Sort the start and end of each equivalence set bounding rectangle // along the splitting dimension std::set<KDLine> lines; for (unsigned idx = 0; idx < subsets.size(); idx++) { lines.insert(KDLine(subset_bounds[idx].lo[refinement_dim],idx,true)); lines.insert(KDLine(subset_bounds[idx].hi[refinement_dim],idx,false)); } // Construct two lists by scanning from left-to-right and // from right-to-left of the number of rectangles that would // be inlcuded on the left or right side by each splitting plane std::map<coord_t,unsigned> left_inclusive, right_inclusive; unsigned count = 0; for (typename std::set<KDLine>::const_iterator it = lines.begin(); it != lines.end(); it++) { // Only increment for new rectangles if (it->start) count++; // Always record the count for all splits left_inclusive[it->value] = count; } count = 0; for (typename std::set<KDLine>::const_reverse_iterator it = lines.rbegin(); it != lines.rend(); it++) { // End of rectangles are the beginning in this direction if (!it->start) count++; // Always record the count for all splits right_inclusive[it->value] = count; } #ifdef DEBUG_LEGION assert(left_inclusive.size() == right_inclusive.size()); #endif // We want to take the mini-max of the two numbers in order // to try to balance the splitting plane across the two sets unsigned split_max = subsets.size(); for (std::map<coord_t,unsigned>::const_iterator it = left_inclusive.begin(); it != left_inclusive.end(); it++) { const unsigned left = it->second; const unsigned right = right_inclusive[it->first]; const unsigned max = (left > right) ? left : right; if (max < split_max) { split_max = max; split = it->first; } } } // Sort the subsets into left and right Rect<DIM> left_bounds, right_bounds; left_bounds = bounds; right_bounds = bounds; left_bounds.hi[refinement_dim] = split; right_bounds.lo[refinement_dim] = split+1; std::vector<EquivalenceSet*> left_set, right_set; for (unsigned idx = 0; idx < subsets.size(); idx++) { const Rect<DIM> &sub_bounds = subset_bounds[idx]; if (left_bounds.overlaps(sub_bounds)) left_set.push_back(subsets[idx]); if (right_bounds.overlaps(sub_bounds)) right_set.push_back(subsets[idx]); } // Check for the non-convex case where we can't refine anymore if ((refinement_dim == last_changed_dim) && ((left_set.size() == subsets.size()) || (right_set.size() == subsets.size()))) return false; // Recurse down the tree const int next_dim = (refinement_dim + 1) % DIM; bool left_changed = false; if ((left_set.size() > LEGION_MAX_BVH_FANOUT) && (max_depth > 0)) { // If all the subsets span our splitting plane then we need // to either start tracking the last changed dimension or // continue propagating the current one const int left_last_dim = (left_set.size() == subsets.size()) ? ((last_changed_dim != -1) ? last_changed_dim : refinement_dim) : -1; KDNode<DIM> left(left_bounds, runtime, next_dim, left_last_dim); left_changed = left.refine(left_set, refinement_mask, max_depth - 1); } bool right_changed = false; if ((right_set.size() > LEGION_MAX_BVH_FANOUT) && (max_depth > 0)) { // If all the subsets span our splitting plane then we need // to either start tracking the last changed dimension or // continue propagating the current one const int right_last_dim = (right_set.size() == subsets.size()) ? ((last_changed_dim != -1) ? last_changed_dim : refinement_dim) : -1; KDNode<DIM> right(right_bounds, runtime, next_dim, right_last_dim); right_changed = right.refine(right_set, refinement_mask, max_depth - 1); } // If the sum of the left and right equivalence sets // are too big then build intermediate nodes for each one if (((left_set.size() + right_set.size()) > LEGION_MAX_BVH_FANOUT) && (left_set.size() < subsets.size()) && !left_set.empty() && (right_set.size() < subsets.size()) && !right_set.empty()) { // Make a new equivalence class and record all the subsets const AddressSpaceID local_space = runtime->address_space; std::set<IndexSpaceExpression*> left_exprs, right_exprs; for (std::vector<EquivalenceSet*>::const_iterator it = left_set.begin(); it != left_set.end(); it++) left_exprs.insert((*it)->set_expr); IndexSpaceExpression *left_union_expr = runtime->forest->union_index_spaces(left_exprs); for (std::vector<EquivalenceSet*>::const_iterator it = right_set.begin(); it != right_set.end(); it++) right_exprs.insert((*it)->set_expr); IndexSpaceExpression *right_union_expr = runtime->forest->union_index_spaces(right_exprs); EquivalenceSet *left_temp = new EquivalenceSet(runtime, runtime->get_available_distributed_id(), local_space, local_space, left_union_expr, NULL/*index space*/, true/*register now*/); EquivalenceSet *right_temp = new EquivalenceSet(runtime, runtime->get_available_distributed_id(), local_space, local_space, right_union_expr, NULL/*index space*/, true/*register now*/); for (std::vector<EquivalenceSet*>::const_iterator it = left_set.begin(); it != left_set.end(); it++) left_temp->record_subset(*it, refinement_mask); for (std::vector<EquivalenceSet*>::const_iterator it = right_set.begin(); it != right_set.end(); it++) right_temp->record_subset(*it, refinement_mask); subsets.clear(); subsets.push_back(left_temp); subsets.push_back(right_temp); return true; } else if (left_changed || right_changed) { // If either right or left changed, then we need to recombine // and deduplicate the equivalence sets before we can return if (!left_set.empty() && !right_set.empty()) { std::set<EquivalenceSet*> children; children.insert(left_set.begin(), left_set.end()); children.insert(right_set.begin(), right_set.end()); subsets.clear(); subsets.insert(subsets.end(), children.begin(), children.end()); } else if (!left_set.empty()) { subsets.clear(); subsets.insert(subsets.end(), left_set.begin(), left_set.end()); } else { subsets.clear(); subsets.insert(subsets.end(), right_set.begin(), right_set.end()); } return true; } else // No changes were made return false; } ///////////////////////////////////////////////////////////// // Copy Fill Guard ///////////////////////////////////////////////////////////// #ifndef NON_AGGRESSIVE_AGGREGATORS //-------------------------------------------------------------------------- CopyFillGuard::CopyFillGuard(RtUserEvent post, RtUserEvent applied) : guard_postcondition(post), effects_applied(applied), releasing_guards(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyFillGuard::CopyFillGuard(const CopyFillGuard &rhs) : guard_postcondition(rhs.guard_postcondition), effects_applied(rhs.effects_applied) //-------------------------------------------------------------------------- { // Should never be called assert(false); } #else //-------------------------------------------------------------------------- CopyFillGuard::CopyFillGuard(RtUserEvent applied) : effects_applied(applied), releasing_guards(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyFillGuard::CopyFillGuard(const CopyFillGuard &rhs) : effects_applied(rhs.effects_applied) //-------------------------------------------------------------------------- { // Should never be called assert(false); } #endif //-------------------------------------------------------------------------- CopyFillGuard::~CopyFillGuard(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(releasing_guards); // should have done a release assert(guarded_sets.empty()); assert(remote_release_events.empty()); #endif } //-------------------------------------------------------------------------- CopyFillGuard& CopyFillGuard::operator=(const CopyFillGuard &rhs) //-------------------------------------------------------------------------- { // Should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void CopyFillGuard::pack_guard(Serializer &rez) //-------------------------------------------------------------------------- { AutoLock g_lock(guard_lock); // If we're already releasing a guard then there is no point in sending it if (releasing_guards) { rez.serialize(RtUserEvent::NO_RT_USER_EVENT); return; } #ifdef DEBUG_LEGION assert(effects_applied.exists()); #endif // We only ever pack the effects applied event here because once a // guard is on a remote node then the guard postcondition is no longer // useful since all remote copy fill operations will need to key off // the effects applied event to be correct rez.serialize(effects_applied); // Make an event for recording when all the remote events are applied RtUserEvent remote_release = Runtime::create_rt_user_event(); rez.serialize(remote_release); remote_release_events.push_back(remote_release); } //-------------------------------------------------------------------------- /*static*/ CopyFillGuard* CopyFillGuard::unpack_guard(Deserializer &derez, Runtime *runtime, EquivalenceSet *set) //-------------------------------------------------------------------------- { RtUserEvent effects_applied; derez.deserialize(effects_applied); if (!effects_applied.exists()) return NULL; #ifndef NON_AGGRESSIVE_AGGREGATORS // Note we use the effects applied event here twice because all // copy-fill aggregators on this node will need to wait for the // full effects to be applied of any guards on a remote node CopyFillGuard *result = new CopyFillGuard(effects_applied, effects_applied); #else CopyFillGuard *result = new CopyFillGuard(effects_applied); #endif #ifdef DEBUG_LEGION if (!result->record_guard_set(set)) assert(false); #else result->record_guard_set(set); #endif RtUserEvent remote_release; derez.deserialize(remote_release); std::set<RtEvent> release_preconditions; result->release_guards(runtime, release_preconditions, true/*defer*/); if (!release_preconditions.empty()) Runtime::trigger_event(remote_release, Runtime::merge_events(release_preconditions)); else Runtime::trigger_event(remote_release); return result; } //-------------------------------------------------------------------------- bool CopyFillGuard::record_guard_set(EquivalenceSet *set) //-------------------------------------------------------------------------- { if (releasing_guards) return false; AutoLock g_lock(guard_lock); // Check again after getting the lock to avoid the race if (releasing_guards) return false; guarded_sets.insert(set); return true; } //-------------------------------------------------------------------------- bool CopyFillGuard::release_guards(Runtime *rt, std::set<RtEvent> &applied, bool force_deferral /*=false*/) //-------------------------------------------------------------------------- { if (force_deferral || !effects_applied.has_triggered()) { RtUserEvent released = Runtime::create_rt_user_event(); // Meta-task will take responsibility for deletion CopyFillDeletion args(this, implicit_provenance, released); rt->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, effects_applied); applied.insert(released); return false; } else release_guarded_sets(applied); return true; } //-------------------------------------------------------------------------- /*static*/ void CopyFillGuard::handle_deletion(const void *args) //-------------------------------------------------------------------------- { const CopyFillDeletion *dargs = (const CopyFillDeletion*)args; std::set<RtEvent> released_preconditions; dargs->guard->release_guarded_sets(released_preconditions); if (!released_preconditions.empty()) Runtime::trigger_event(dargs->released, Runtime::merge_events(released_preconditions)); else Runtime::trigger_event(dargs->released); delete dargs->guard; } //-------------------------------------------------------------------------- void CopyFillGuard::release_guarded_sets(std::set<RtEvent> &released) //-------------------------------------------------------------------------- { std::set<EquivalenceSet*> to_remove; { AutoLock g_lock(guard_lock); #ifdef DEBUG_LEGION assert(!releasing_guards); #endif releasing_guards = true; to_remove.swap(guarded_sets); if (!remote_release_events.empty()) { released.insert(remote_release_events.begin(), remote_release_events.end()); remote_release_events.clear(); } } if (!to_remove.empty()) { for (std::set<EquivalenceSet*>::const_iterator it = to_remove.begin(); it != to_remove.end(); it++) (*it)->remove_update_guard(this); } } ///////////////////////////////////////////////////////////// // Copy Fill Aggregator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- CopyFillAggregator::CopyFillAggregator(RegionTreeForest *f, Operation *o, unsigned idx, RtEvent g, bool t, PredEvent p) : WrapperReferenceMutator(effects), #ifndef NON_AGGRESSIVE_AGGREGATORS CopyFillGuard(Runtime::create_rt_user_event(), Runtime::create_rt_user_event()), #else CopyFillGuard(Runtime::create_rt_user_event()), #endif forest(f), local_space(f->runtime->address_space), op(o), src_index(idx), dst_index(idx), guard_precondition(g), predicate_guard(p), track_events(t), tracing_src_fills(NULL), tracing_srcs(NULL), tracing_dsts(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyFillAggregator::CopyFillAggregator(RegionTreeForest *f, Operation *o, unsigned src_idx, unsigned dst_idx, RtEvent g, bool t, PredEvent p) : WrapperReferenceMutator(effects), #ifndef NON_AGGRESSIVE_AGGREGATORS CopyFillGuard(Runtime::create_rt_user_event(), Runtime::create_rt_user_event()), #else CopyFillGuard(Runtime::create_rt_user_event()), #endif forest(f), local_space(f->runtime->address_space), op(o), src_index(src_idx), dst_index(dst_idx), guard_precondition(g), predicate_guard(p), track_events(t), tracing_src_fills(NULL), tracing_srcs(NULL), tracing_dsts(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyFillAggregator::CopyFillAggregator(const CopyFillAggregator &rhs) : WrapperReferenceMutator(effects), CopyFillGuard(rhs), forest(rhs.forest), local_space(rhs.local_space), op(rhs.op), src_index(rhs.src_index), dst_index(rhs.dst_index), guard_precondition(rhs.guard_precondition), predicate_guard(rhs.predicate_guard), track_events(rhs.track_events) //-------------------------------------------------------------------------- { // Should never be called assert(false); } //-------------------------------------------------------------------------- CopyFillAggregator::~CopyFillAggregator(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION #ifndef NON_AGGRESSIVE_AGGREGATORS assert(guard_postcondition.has_triggered()); #endif assert(effects_applied.has_triggered()); #endif // Remove references from any views that we have for (std::set<LogicalView*>::const_iterator it = all_views.begin(); it != all_views.end(); it++) if ((*it)->remove_base_valid_ref(AGGREGATORE_REF)) delete (*it); // Delete all our copy updates for (LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned:: const_iterator mit = sources.begin(); mit != sources.end(); mit++) { for (FieldMaskSet<Update>::const_iterator it = mit->second.begin(); it != mit->second.end(); it++) delete it->first; } for (std::vector<LegionMap<InstanceView*, FieldMaskSet<Update> >::aligned>::const_iterator rit = reductions.begin(); rit != reductions.end(); rit++) { for (LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned:: const_iterator mit = rit->begin(); mit != rit->end(); mit++) { for (FieldMaskSet<Update>::const_iterator it = mit->second.begin(); it != mit->second.end(); it++) delete it->first; } } // Clean up any data structures that we made for tracing if (tracing_src_fills != NULL) delete tracing_src_fills; if (tracing_srcs != NULL) delete tracing_srcs; if (tracing_dsts != NULL) delete tracing_dsts; } //-------------------------------------------------------------------------- CopyFillAggregator& CopyFillAggregator::operator=( const CopyFillAggregator &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void CopyFillAggregator::CopyUpdate::record_source_expressions( InstanceFieldExprs &src_exprs) const //-------------------------------------------------------------------------- { FieldMaskSet<IndexSpaceExpression> &exprs = src_exprs[source]; FieldMaskSet<IndexSpaceExpression>::iterator finder = exprs.find(expr); if (finder == exprs.end()) exprs.insert(expr, src_mask); else finder.merge(src_mask); } //-------------------------------------------------------------------------- void CopyFillAggregator::CopyUpdate::compute_source_preconditions( RegionTreeForest *forest, #ifdef DEBUG_LEGION const bool copy_across, #endif const std::map<InstanceView*,EventFieldExprs> &src_pre, LegionMap<ApEvent,FieldMask>::aligned &preconditions) const //-------------------------------------------------------------------------- { std::map<InstanceView*,EventFieldExprs>::const_iterator finder = src_pre.find(source); if (finder == src_pre.end()) return; for (EventFieldExprs::const_iterator eit = finder->second.begin(); eit != finder->second.end(); eit++) { FieldMask set_overlap = src_mask & eit->second.get_valid_mask(); if (!set_overlap) continue; for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = eit->second.begin(); it != eit->second.end(); it++) { const FieldMask overlap = set_overlap & it->second; if (!overlap) continue; IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(expr, it->first); if (expr_overlap->is_empty()) continue; #ifdef DEBUG_LEGION // Since this is an equivalence set update there should be no users // that are using just a part of it, should be all or nothing, with // the exception of copy across operations in which case it doesn't // matter because we don't need precise preconditions there if (copy_across) assert(expr_overlap->get_volume() == expr->get_volume()); #endif // Overlap in both so record it LegionMap<ApEvent,FieldMask>::aligned::iterator event_finder = preconditions.find(eit->first); if (event_finder == preconditions.end()) preconditions[eit->first] = overlap; else event_finder->second |= overlap; set_overlap -= overlap; if (!set_overlap) break; } } } //-------------------------------------------------------------------------- void CopyFillAggregator::CopyUpdate::sort_updates( std::map<InstanceView*, std::vector<CopyUpdate*> > &copies, std::vector<FillUpdate*> &fills) //-------------------------------------------------------------------------- { copies[source].push_back(this); } //-------------------------------------------------------------------------- void CopyFillAggregator::FillUpdate::record_source_expressions( InstanceFieldExprs &src_exprs) const //-------------------------------------------------------------------------- { // Do nothing, we have no source expressions } //-------------------------------------------------------------------------- void CopyFillAggregator::FillUpdate::compute_source_preconditions( RegionTreeForest *forest, #ifdef DEBUG_LEGION const bool copy_across, #endif const std::map<InstanceView*,EventFieldExprs> &src_pre, LegionMap<ApEvent,FieldMask>::aligned &preconditions) const //-------------------------------------------------------------------------- { // Do nothing, we have no source preconditions to worry about } //-------------------------------------------------------------------------- void CopyFillAggregator::FillUpdate::sort_updates( std::map<InstanceView*, std::vector<CopyUpdate*> > &copies, std::vector<FillUpdate*> &fills) //-------------------------------------------------------------------------- { fills.push_back(this); } //-------------------------------------------------------------------------- void CopyFillAggregator::record_updates(InstanceView *dst_view, const FieldMaskSet<LogicalView> &src_views, const FieldMask &src_mask, IndexSpaceExpression *expr, ReductionOpID redop /*=0*/, CopyAcrossHelper *helper /*=NULL*/) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!src_mask); assert(!src_views.empty()); assert(!expr->is_empty()); #endif update_fields |= src_mask; FieldMaskSet<Update> &updates = sources[dst_view]; record_view(dst_view); if (src_views.size() == 1) { const LogicalView *view = src_views.begin()->first; const FieldMask record_mask = src_views.get_valid_mask() & src_mask; if (!!record_mask) { if (view->is_instance_view()) { InstanceView *inst = view->as_instance_view(); record_view(inst); CopyUpdate *update = new CopyUpdate(inst, record_mask, expr, redop, helper); if (helper == NULL) updates.insert(update, record_mask); else updates.insert(update, helper->convert_src_to_dst(record_mask)); } else { DeferredView *def = view->as_deferred_view(); def->flatten(*this, dst_view, record_mask, expr, helper); } } } else { // We have multiple views, so let's sort them LegionList<FieldSet<LogicalView*> >::aligned view_sets; src_views.compute_field_sets(src_mask, view_sets); for (LegionList<FieldSet<LogicalView*> >::aligned::const_iterator vit = view_sets.begin(); vit != view_sets.end(); vit++) { if (vit->elements.empty()) continue; if (vit->elements.size() == 1) { // Easy case, just one view so do it const LogicalView *view = *(vit->elements.begin()); const FieldMask &record_mask = vit->set_mask; if (view->is_instance_view()) { InstanceView *inst = view->as_instance_view(); record_view(inst); CopyUpdate *update = new CopyUpdate(inst, record_mask, expr, redop, helper); if (helper == NULL) updates.insert(update, record_mask); else updates.insert(update, helper->convert_src_to_dst(record_mask)); } else { DeferredView *def = view->as_deferred_view(); def->flatten(*this, dst_view, record_mask, expr, helper); } } else { // Sort the views, prefer fills, then instances, then deferred FillView *fill = NULL; DeferredView *deferred = NULL; std::vector<InstanceView*> instances; for (std::set<LogicalView*>::const_iterator it = vit->elements.begin(); it != vit->elements.end(); it++) { if (!(*it)->is_instance_view()) { DeferredView *def = (*it)->as_deferred_view(); if (!def->is_fill_view()) { if (deferred == NULL) deferred = def; } else { fill = def->as_fill_view(); // Break out since we found what we're looking for break; } } else instances.push_back((*it)->as_instance_view()); } if (fill != NULL) record_fill(dst_view, fill, vit->set_mask, expr, helper); else if (!instances.empty()) { if (instances.size() == 1) { // Easy, just one instance to use InstanceView *inst = instances.back(); record_view(inst); CopyUpdate *update = new CopyUpdate(inst, vit->set_mask, expr, redop, helper); if (helper == NULL) updates.insert(update, vit->set_mask); else updates.insert(update, helper->convert_src_to_dst(vit->set_mask)); } else { // Hard, multiple potential sources, // ask the mapper which one to use // First though check to see if we've already asked it bool found = false; const std::set<InstanceView*> instances_set(instances.begin(), instances.end()); std::map<InstanceView*,LegionVector<SourceQuery>::aligned>:: const_iterator finder = mapper_queries.find(dst_view); if (finder != mapper_queries.end()) { for (LegionVector<SourceQuery>::aligned::const_iterator qit = finder->second.begin(); qit != finder->second.end(); qit++) { if ((qit->query_mask == vit->set_mask) && (qit->sources == instances_set)) { found = true; record_view(qit->result); CopyUpdate *update = new CopyUpdate(qit->result, qit->query_mask, expr, redop, helper); if (helper == NULL) updates.insert(update, qit->query_mask); else updates.insert(update, helper->convert_src_to_dst(qit->query_mask)); break; } } } if (!found) { // If we didn't find the query result we need to do // it for ourself, start by constructing the inputs InstanceRef dst(dst_view->get_manager(), helper == NULL ? vit->set_mask : helper->convert_src_to_dst(vit->set_mask)); InstanceSet sources(instances.size()); unsigned src_idx = 0; for (std::vector<InstanceView*>::const_iterator it = instances.begin(); it != instances.end(); it++) sources[src_idx++] = InstanceRef((*it)->get_manager(), vit->set_mask); std::vector<unsigned> ranking; // Always use the source index for selecting sources op->select_sources(src_index, dst, sources, ranking); // We know that which ever one was chosen first is // the one that satisfies all our fields since all // these instances are valid for all fields InstanceView *result = ranking.empty() ? instances.front() : instances[ranking[0]]; // Record the update record_view(result); CopyUpdate *update = new CopyUpdate(result, vit->set_mask, expr, redop, helper); if (helper == NULL) updates.insert(update, vit->set_mask); else updates.insert(update, helper->convert_src_to_dst(vit->set_mask)); // Save the result for the future mapper_queries[dst_view].push_back( SourceQuery(instances_set, vit->set_mask, result)); } } } else { #ifdef DEBUG_LEGION assert(deferred != NULL); #endif deferred->flatten(*this, dst_view, vit->set_mask, expr, helper); } } } } } //-------------------------------------------------------------------------- void CopyFillAggregator::record_fill(InstanceView *dst_view, FillView *src_view, const FieldMask &fill_mask, IndexSpaceExpression *expr, CopyAcrossHelper *helper /*=NULL*/) //-------------------------------------------------------------------------- { // No need to record the destination as we already did that the first // time through on our way to finding this fill view #ifdef DEBUG_LEGION assert(all_views.find(dst_view) != all_views.end()); assert(!!fill_mask); assert(!expr->is_empty()); #endif update_fields |= fill_mask; record_view(src_view); FillUpdate *update = new FillUpdate(src_view, fill_mask, expr, helper); if (helper == NULL) sources[dst_view].insert(update, fill_mask); else sources[dst_view].insert(update, helper->convert_src_to_dst(fill_mask)); } //-------------------------------------------------------------------------- void CopyFillAggregator::record_reductions(InstanceView *dst_view, const std::vector<ReductionView*> &src_views, const unsigned src_fidx, const unsigned dst_fidx, IndexSpaceExpression *expr, CopyAcrossHelper *across_helper) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!src_views.empty()); assert(!expr->is_empty()); #endif update_fields.set_bit(src_fidx); record_view(dst_view); for (std::vector<ReductionView*>::const_iterator it = src_views.begin(); it != src_views.end(); it++) record_view(*it); const std::pair<InstanceView*,unsigned> dst_key(dst_view, dst_fidx); std::vector<ReductionOpID> &redop_epochs = reduction_epochs[dst_key]; FieldMask src_mask, dst_mask; src_mask.set_bit(src_fidx); dst_mask.set_bit(dst_fidx); // Always start scanning from the first redop index unsigned redop_index = 0; for (std::vector<ReductionView*>::const_iterator it = src_views.begin(); it != src_views.end(); it++) { const ReductionOpID redop = (*it)->get_redop(); CopyUpdate *update = new CopyUpdate(*it, src_mask, expr, redop, across_helper); // Scan along looking for a reduction op epoch that matches while ((redop_index < redop_epochs.size()) && (redop_epochs[redop_index] != redop)) redop_index++; if (redop_index == redop_epochs.size()) { #ifdef DEBUG_LEGION assert(redop_index <= reductions.size()); #endif // Start a new redop epoch if necessary redop_epochs.push_back(redop); if (reductions.size() == redop_index) reductions.resize(redop_index + 1); } reductions[redop_index][dst_view].insert(update, dst_mask); } } //-------------------------------------------------------------------------- void CopyFillAggregator::record_preconditions(InstanceView *view, bool reading, EventFieldExprs &preconditions) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!preconditions.empty()); #endif AutoLock p_lock(pre_lock); EventFieldExprs &pre = reading ? src_pre[view] : dst_pre[view]; for (EventFieldExprs::iterator eit = preconditions.begin(); eit != preconditions.end(); eit++) { EventFieldExprs::iterator event_finder = pre.find(eit->first); if (event_finder != pre.end()) { // Need to do the merge manually for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = eit->second.begin(); it != eit->second.end(); it++) { FieldMaskSet<IndexSpaceExpression>::iterator finder = event_finder->second.find(it->first); if (finder == event_finder->second.end()) event_finder->second.insert(it->first, it->second); else finder.merge(it->second); } } else // We can just swap this over pre[eit->first].swap(eit->second); } } //-------------------------------------------------------------------------- void CopyFillAggregator::record_precondition(InstanceView *view, bool reading, ApEvent event, const FieldMask &mask, IndexSpaceExpression *expr) //-------------------------------------------------------------------------- { AutoLock p_lock(pre_lock); FieldMaskSet<IndexSpaceExpression> &event_pre = reading ? src_pre[view][event] : dst_pre[view][event]; FieldMaskSet<IndexSpaceExpression>::iterator finder = event_pre.find(expr); if (finder == event_pre.end()) event_pre.insert(expr, mask); else finder.merge(mask); } //-------------------------------------------------------------------------- void CopyFillAggregator::issue_updates(const PhysicalTraceInfo &trace_info, ApEvent precondition, const bool has_src_preconditions, const bool has_dst_preconditions, const bool need_deferral, unsigned pass, bool need_pass_preconditions) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!sources.empty() || !reductions.empty()); #endif if (need_deferral || (guard_precondition.exists() && !guard_precondition.has_triggered())) { CopyFillAggregation args(this, trace_info, precondition, has_src_preconditions, has_dst_preconditions, op->get_unique_op_id(), pass, need_pass_preconditions); op->runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, guard_precondition); return; } #ifdef DEBUG_LEGION assert(!guard_precondition.exists() || guard_precondition.has_triggered()); #endif if (pass == 0) { // Perform updates from any sources first if (!sources.empty()) { const RtEvent deferral_event = perform_updates(sources, trace_info, precondition, has_src_preconditions, has_dst_preconditions, need_pass_preconditions); if (deferral_event.exists()) { CopyFillAggregation args(this, trace_info, precondition, has_src_preconditions, has_dst_preconditions, op->get_unique_op_id(), pass, false/*need pre*/); op->runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, deferral_event); return; } } // We made it through the first pass pass++; need_pass_preconditions = true; } // Then apply any reductions that we might have if (!reductions.empty()) { #ifdef DEBUG_LEGION assert(pass > 0); #endif // Skip any passes that we might have already done for (unsigned idx = pass-1; idx < reductions.size(); idx++) { const RtEvent deferral_event = perform_updates(reductions[idx], trace_info, precondition, has_src_preconditions, has_dst_preconditions, need_pass_preconditions); if (deferral_event.exists()) { CopyFillAggregation args(this, trace_info, precondition, has_src_preconditions, has_dst_preconditions, op->get_unique_op_id(), pass, false/*need pre*/); op->runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, deferral_event); return; } // Made it through this pass pass++; need_pass_preconditions = true; } } #ifndef NON_AGGRESSIVE_AGGREGATORS Runtime::trigger_event(guard_postcondition); #endif // We can also trigger our guard event once the effects are applied if (!effects.empty()) Runtime::trigger_event(effects_applied, Runtime::merge_events(effects)); else Runtime::trigger_event(effects_applied); } //-------------------------------------------------------------------------- ApEvent CopyFillAggregator::summarize(const PhysicalTraceInfo &info) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(track_events); #endif if (!events.empty()) return Runtime::merge_events(&info, events); else return ApEvent::NO_AP_EVENT; } //-------------------------------------------------------------------------- void CopyFillAggregator::record_view(LogicalView *new_view) //-------------------------------------------------------------------------- { std::pair<std::set<LogicalView*>::iterator,bool> result = all_views.insert(new_view); if (result.second) new_view->add_base_valid_ref(AGGREGATORE_REF, this); } //-------------------------------------------------------------------------- RtEvent CopyFillAggregator::perform_updates( const LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned &updates, const PhysicalTraceInfo &trace_info, const ApEvent all_precondition, const bool has_src_preconditions, const bool has_dst_preconditions, const bool needs_preconditions) //-------------------------------------------------------------------------- { if (needs_preconditions && (!has_src_preconditions || !has_dst_preconditions)) { // First compute the access expressions for all the copies InstanceFieldExprs dst_exprs, src_exprs; for (LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned:: const_iterator uit = updates.begin(); uit != updates.end(); uit++) { FieldMaskSet<IndexSpaceExpression> &dst_expr = dst_exprs[uit->first]; for (FieldMaskSet<Update>::const_iterator it = uit->second.begin(); it != uit->second.end(); it++) { // Update the destinations first if (!has_dst_preconditions) { #ifdef DEBUG_LEGION // We should not have an across helper in this case assert(it->first->across_helper == NULL); #endif FieldMaskSet<IndexSpaceExpression>::iterator finder = dst_expr.find(it->first->expr); if (finder == dst_expr.end()) dst_expr.insert(it->first->expr, it->second); else finder.merge(it->second); } // Now record the source expressions if (!has_src_preconditions) it->first->record_source_expressions(src_exprs); } } // Next compute the event preconditions for these accesses std::set<RtEvent> preconditions_ready; const UniqueID op_id = op->get_unique_op_id(); if (!has_dst_preconditions) { dst_pre.clear(); for (InstanceFieldExprs::const_iterator dit = dst_exprs.begin(); dit != dst_exprs.end(); dit++) { if (dit->second.size() == 1) { // No need to do any kind of sorts here IndexSpaceExpression *copy_expr = dit->second.begin()->first; const FieldMask &copy_mask = dit->second.get_valid_mask(); RtEvent pre_ready = dit->first->find_copy_preconditions( false/*reading*/, copy_mask, copy_expr, op_id, dst_index,*this,trace_info.recording,local_space); if (pre_ready.exists()) preconditions_ready.insert(pre_ready); } else { // Sort into field sets and merge expressions LegionList<FieldSet<IndexSpaceExpression*> >::aligned sorted_exprs; dit->second.compute_field_sets(FieldMask(), sorted_exprs); for (LegionList<FieldSet<IndexSpaceExpression*> >::aligned:: const_iterator it = sorted_exprs.begin(); it != sorted_exprs.end(); it++) { const FieldMask &copy_mask = it->set_mask; IndexSpaceExpression *copy_expr = (it->elements.size() == 1) ? *(it->elements.begin()) : forest->union_index_spaces(it->elements); RtEvent pre_ready = dit->first->find_copy_preconditions( false/*reading*/, copy_mask, copy_expr, op_id, dst_index, *this, trace_info.recording, local_space); if (pre_ready.exists()) preconditions_ready.insert(pre_ready); } } } } if (!has_src_preconditions) { src_pre.clear(); for (InstanceFieldExprs::const_iterator sit = src_exprs.begin(); sit != src_exprs.end(); sit++) { if (sit->second.size() == 1) { // No need to do any kind of sorts here IndexSpaceExpression *copy_expr = sit->second.begin()->first; const FieldMask &copy_mask = sit->second.get_valid_mask(); RtEvent pre_ready = sit->first->find_copy_preconditions( true/*reading*/, copy_mask, copy_expr, op_id, src_index, *this, trace_info.recording,local_space); if (pre_ready.exists()) preconditions_ready.insert(pre_ready); } else { // Sort into field sets and merge expressions LegionList<FieldSet<IndexSpaceExpression*> >::aligned sorted_exprs; sit->second.compute_field_sets(FieldMask(), sorted_exprs); for (LegionList<FieldSet<IndexSpaceExpression*> >::aligned:: const_iterator it = sorted_exprs.begin(); it != sorted_exprs.end(); it++) { const FieldMask &copy_mask = it->set_mask; IndexSpaceExpression *copy_expr = (it->elements.size() == 1) ? *(it->elements.begin()) : forest->union_index_spaces(it->elements); RtEvent pre_ready = sit->first->find_copy_preconditions( true/*reading*/, copy_mask, copy_expr, op_id, src_index, *this, trace_info.recording, local_space); if (pre_ready.exists()) preconditions_ready.insert(pre_ready); } } } } // If necessary wait until all we have all the preconditions if (!preconditions_ready.empty()) { const RtEvent wait_on = Runtime::merge_events(preconditions_ready); if (wait_on.exists()) return wait_on; } } #ifndef UNSAFE_AGGREGATION // Iterate over the destinations and compute updates that have the // same preconditions on different fields std::map<std::set<ApEvent>,ApEvent> merge_cache; for (LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned:: const_iterator uit = updates.begin(); uit != updates.end(); uit++) { EventFieldUpdates update_groups; const EventFieldExprs &dst_preconditions = dst_pre[uit->first]; for (FieldMaskSet<Update>::const_iterator it = uit->second.begin(); it != uit->second.end(); it++) { // Compute the preconditions for this update // This is a little tricky for across copies because we need // to make sure that all the fields are in same field space // which will be the source field space, so we need to convert // some field masks back to that space if necessary LegionMap<ApEvent,FieldMask>::aligned preconditions; // Compute the destination preconditions first if (!dst_preconditions.empty()) { for (EventFieldExprs::const_iterator pit = dst_preconditions.begin(); pit != dst_preconditions.end(); pit++) { FieldMask set_overlap = it->second & pit->second.get_valid_mask(); if (!set_overlap) continue; for (FieldMaskSet<IndexSpaceExpression>::const_iterator eit = pit->second.begin(); eit != pit->second.end(); eit++) { const FieldMask overlap = set_overlap & eit->second; if (!overlap) continue; IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(eit->first, it->first->expr); if (expr_overlap->is_empty()) continue; #ifdef DEBUG_LEGION // Since this is an equivalence set update there should // be no users that are using just a part of it, should // be all or nothing, unless this is a copy across in // which case it doesn't matter if (src_index != dst_index) assert(expr_overlap->get_volume() == it->first->expr->get_volume()); #endif // Overlap on both so add it to the set LegionMap<ApEvent,FieldMask>::aligned::iterator finder = preconditions.find(pit->first); // Make sure to convert back to the source field space // in the case of across copies if necessary if (finder == preconditions.end()) { if (it->first->across_helper == NULL) preconditions[pit->first] = overlap; else preconditions[pit->first] = it->first->across_helper->convert_dst_to_src(overlap); } else { if (it->first->across_helper == NULL) finder->second |= overlap; else finder->second |= it->first->across_helper->convert_dst_to_src(overlap); } set_overlap -= overlap; // If we found preconditions on all our fields then we're done if (!set_overlap) break; } } } // The compute the source preconditions for this update it->first->compute_source_preconditions(forest, #ifdef DEBUG_LEGION (src_index != dst_index), #endif src_pre, preconditions); if (preconditions.empty()) // NO precondition so enter it with a no event update_groups[ApEvent::NO_AP_EVENT].insert(it->first, it->first->src_mask); else if (preconditions.size() == 1) { LegionMap<ApEvent,FieldMask>::aligned::const_iterator first = preconditions.begin(); update_groups[first->first].insert(it->first, first->second); const FieldMask remainder = it->first->src_mask - first->second; if (!!remainder) update_groups[ApEvent::NO_AP_EVENT].insert(it->first, remainder); } else { // Group event preconditions by fields LegionList<FieldSet<ApEvent> >::aligned grouped_events; compute_field_sets<ApEvent>(it->first->src_mask, preconditions, grouped_events); for (LegionList<FieldSet<ApEvent> >::aligned::const_iterator ait = grouped_events.begin(); ait != grouped_events.end(); ait++) { ApEvent key; if (ait->elements.size() > 1) { // See if the set is in the cache or we need to compute it std::map<std::set<ApEvent>,ApEvent>::const_iterator finder = merge_cache.find(ait->elements); if (finder == merge_cache.end()) { key = Runtime::merge_events(&trace_info, ait->elements); merge_cache[ait->elements] = key; } else key = finder->second; } else if (ait->elements.size() == 1) key = *(ait->elements.begin()); FieldMaskSet<Update> &group = update_groups[key]; FieldMaskSet<Update>::iterator finder = group.find(it->first); if (finder != group.end()) finder.merge(ait->set_mask); else group.insert(it->first, ait->set_mask); } } } // Now iterate over events and group by fields for (EventFieldUpdates::const_iterator eit = update_groups.begin(); eit != update_groups.end(); eit++) { // Merge in the over-arching precondition if necessary const ApEvent group_precondition = all_precondition.exists() ? Runtime::merge_events(&trace_info, all_precondition, eit->first) : eit->first; const FieldMaskSet<Update> &group = eit->second; #ifdef DEBUG_LEGION assert(!group.empty()); #endif if (group.size() == 1) { // Only one update so no need to try to group or merge std::vector<FillUpdate*> fills; std::map<InstanceView* /*src*/,std::vector<CopyUpdate*> > copies; Update *update = group.begin()->first; update->sort_updates(copies, fills); const FieldMask &update_mask = group.get_valid_mask(); if (!fills.empty()) issue_fills(uit->first, fills, group_precondition, update_mask, trace_info, has_dst_preconditions); if (!copies.empty()) issue_copies(uit->first, copies, group_precondition, update_mask, trace_info, has_dst_preconditions); } else { // Group by fields LegionList<FieldSet<Update*> >::aligned field_groups; group.compute_field_sets(FieldMask(), field_groups); for (LegionList<FieldSet<Update*> >::aligned::const_iterator fit = field_groups.begin(); fit != field_groups.end(); fit++) { std::vector<FillUpdate*> fills; std::map<InstanceView* /*src*/, std::vector<CopyUpdate*> > copies; for (std::set<Update*>::const_iterator it = fit->elements.begin(); it != fit->elements.end(); it++) (*it)->sort_updates(copies, fills); if (!fills.empty()) issue_fills(uit->first, fills, group_precondition, fit->set_mask, trace_info, has_dst_preconditions); if (!copies.empty()) issue_copies(uit->first, copies, group_precondition, fit->set_mask, trace_info, has_dst_preconditions); } } } } // iterate over dst instances #else // This is the unsafe aggregation routine that just looks at fields // and expressions and doesn't consider event preconditions for (LegionMap<InstanceView*,FieldMaskSet<Update> >::aligned:: const_iterator uit = updates.begin(); uit != updates.end(); uit++) { const EventFieldExprs &dst_preconditions = dst_pre[uit->first]; // Group by fields first LegionList<FieldSet<Update*> >::aligned field_groups; uit->second.compute_field_sets(FieldMask(), field_groups); for (LegionList<FieldSet<Update*> >::aligned::const_iterator fit = field_groups.begin(); fit != field_groups.end(); fit++) { const FieldMask &dst_mask = fit->set_mask; // Now that we have the src mask for these operations group // them into fills and copies and then do their event analysis std::vector<FillUpdate*> fills; std::map<InstanceView* /*src*/,std::vector<CopyUpdate*> > copies; for (std::set<Update*>::const_iterator it = fit->elements.begin(); it != fit->elements.end(); it++) (*it)->sort_updates(copies, fills); // Issue the copies and fills if (!fills.empty()) { std::set<ApEvent> preconditions; if (all_precondition.exists()) preconditions.insert(all_precondition); std::set<IndexSpaceExpression*> fill_exprs; for (std::vector<FillUpdate*>::const_iterator it = fills.begin(); it != fills.end(); it++) fill_exprs.insert((*it)->expr); IndexSpaceExpression *fill_expr = (fill_exprs.size() == 1) ? *(fill_exprs.begin()) : forest->union_index_spaces(fill_exprs); for (EventFieldExprs::const_iterator eit = dst_preconditions.begin(); eit != dst_preconditions.end(); eit++) { // If there are no overlapping fields we can skip it if (dst_mask * eit->second.get_valid_mask()) continue; for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = eit->second.begin(); it != eit->second.end(); it++) { if (it->second * dst_mask) continue; IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(it->first, fill_expr); if (!expr_overlap->is_empty()) { preconditions.insert(eit->first); break; } } } CopyAcrossHelper *across_helper = fills[0]->across_helper; const FieldMask src_mask = (across_helper == NULL) ? dst_mask : across_helper->convert_dst_to_src(dst_mask); if (!preconditions.empty()) { const ApEvent fill_precondition = Runtime::merge_events(&trace_info, preconditions); issue_fills(uit->first, fills, fill_precondition, src_mask, trace_info, has_dst_preconditions); } else issue_fills(uit->first, fills, ApEvent::NO_AP_EVENT, src_mask, trace_info, has_dst_preconditions); } if (!copies.empty()) { std::set<ApEvent> preconditions; if (all_precondition.exists()) preconditions.insert(all_precondition); std::set<IndexSpaceExpression*> copy_exprs; for (std::map<InstanceView*,std::vector<CopyUpdate*> >:: const_iterator cit = copies.begin(); cit != copies.end(); cit++) for (std::vector<CopyUpdate*>::const_iterator it = cit->second.begin(); it != cit->second.end(); it++) copy_exprs.insert((*it)->expr); IndexSpaceExpression *copy_expr = (copy_exprs.size() == 1) ? *(copy_exprs.begin()) : forest->union_index_spaces(copy_exprs); // Destination preconditions first for (EventFieldExprs::const_iterator eit = dst_preconditions.begin(); eit != dst_preconditions.end(); eit++) { // If there are no overlapping fields we can skip it if (dst_mask * eit->second.get_valid_mask()) continue; for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = eit->second.begin(); it != eit->second.end(); it++) { if (it->second * dst_mask) continue; IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(it->first, copy_expr); if (!expr_overlap->is_empty()) { preconditions.insert(eit->first); break; } } } // Then do the source preconditions // Be careful that we get the destination fields right in the // case that this is an across copy CopyAcrossHelper *across_helper = copies.begin()->second[0]->across_helper; const FieldMask src_mask = (across_helper == NULL) ? dst_mask : across_helper->convert_dst_to_src(dst_mask); LegionMap<ApEvent,FieldMask>::aligned src_preconds; for (std::map<InstanceView*,std::vector<CopyUpdate*> >:: const_iterator cit = copies.begin(); cit != copies.end(); cit++) { for (std::vector<CopyUpdate*>::const_iterator it = cit->second.begin(); it != cit->second.end(); it++) { (*it)->compute_source_preconditions(forest, #ifdef DEBUG_LEGION (src_index != dst_index), #endif src_pre, src_preconds); } } for (LegionMap<ApEvent,FieldMask>::aligned::const_iterator it = src_preconds.begin(); it != src_preconds.end(); it++) { if (it->second * dst_mask) continue; preconditions.insert(it->first); } if (!preconditions.empty()) { const ApEvent copy_precondition = Runtime::merge_events(&trace_info, preconditions); issue_copies(uit->first, copies, copy_precondition, src_mask, trace_info, has_dst_preconditions); } else issue_copies(uit->first, copies, ApEvent::NO_AP_EVENT, src_mask, trace_info, has_dst_preconditions); } } } #endif return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- void CopyFillAggregator::issue_fills(InstanceView *target, const std::vector<FillUpdate*> &fills, ApEvent precondition, const FieldMask &fill_mask, const PhysicalTraceInfo &trace_info, const bool has_dst_preconditions) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!fills.empty()); assert(!!fill_mask); #endif const UniqueID op_id = op->get_unique_op_id(); PhysicalManager *manager = target->get_manager(); if (fills.size() == 1) { FillUpdate *update = fills[0]; #ifdef DEBUG_LEGION // Should cover all the fields assert(!(fill_mask - update->src_mask)); #endif IndexSpaceExpression *fill_expr = update->expr; FillView *fill_view = update->source; // Check to see if we need to do any work for tracing if (trace_info.recording) { if (tracing_src_fills == NULL) tracing_src_fills = new FieldMaskSet<FillView>(); else tracing_src_fills->clear(); // Record the source view tracing_src_fills->insert(fill_view, fill_mask); if (tracing_dsts == NULL) tracing_dsts = new FieldMaskSet<InstanceView>(); else tracing_dsts->clear(); // Record the destination view, convert field mask if necessary if (update->across_helper != NULL) { const FieldMask dst_mask = update->across_helper->convert_src_to_dst(fill_mask); tracing_dsts->insert(target, dst_mask); } else tracing_dsts->insert(target, fill_mask); } const ApEvent result = manager->fill_from(fill_view, precondition, predicate_guard, fill_expr, fill_mask, trace_info, fills[0]->across_helper, tracing_src_fills, tracing_dsts); // Record the fill result in the destination if (result.exists()) { const RtEvent collect_event = trace_info.get_collect_event(); if (update->across_helper != NULL) { const FieldMask dst_mask = update->across_helper->convert_src_to_dst(fill_mask); target->add_copy_user(false/*reading*/, result, collect_event, dst_mask, fill_expr, op_id, dst_index, effects, trace_info.recording, local_space); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, dst_mask, fill_expr); } else { target->add_copy_user(false/*reading*/, result, collect_event, fill_mask, fill_expr, op_id,dst_index, effects, trace_info.recording, local_space); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, fill_mask, fill_expr); } if (track_events) events.insert(result); } } else { #ifdef DEBUG_LEGION #ifndef NDEBUG // These should all have had the same across helper for (unsigned idx = 1; idx < fills.size(); idx++) assert(fills[idx]->across_helper == fills[0]->across_helper); #endif #endif std::map<FillView*,std::set<IndexSpaceExpression*> > exprs; for (std::vector<FillUpdate*>::const_iterator it = fills.begin(); it != fills.end(); it++) { #ifdef DEBUG_LEGION // Should cover all the fields assert(!(fill_mask - (*it)->src_mask)); // Should also have the same across helper as the first one assert(fills[0]->across_helper == (*it)->across_helper); #endif exprs[(*it)->source].insert((*it)->expr); } const FieldMask dst_mask = (fills[0]->across_helper == NULL) ? fill_mask : fills[0]->across_helper->convert_src_to_dst(fill_mask); // See if we have any work to do for tracing if (trace_info.recording) { // Destination is the same for all the fills if (tracing_dsts == NULL) tracing_dsts = new FieldMaskSet<InstanceView>(); else tracing_dsts->clear(); tracing_dsts->insert(target, dst_mask); } for (std::map<FillView*,std::set<IndexSpaceExpression*> >:: const_iterator it = exprs.begin(); it != exprs.end(); it++) { IndexSpaceExpression *fill_expr = (it->second.size() == 1) ? *(it->second.begin()) : forest->union_index_spaces(it->second); if (trace_info.recording) { if (tracing_src_fills == NULL) tracing_src_fills = new FieldMaskSet<FillView>(); else tracing_src_fills->clear(); // Record the source view tracing_src_fills->insert(it->first, fill_mask); } // See if we have any work to do for tracing const ApEvent result = manager->fill_from(it->first, precondition, predicate_guard, fill_expr, fill_mask, trace_info, fills[0]->across_helper, tracing_src_fills, tracing_dsts); const RtEvent collect_event = trace_info.get_collect_event(); if (result.exists()) { target->add_copy_user(false/*reading*/, result, collect_event, dst_mask, fill_expr, op_id, dst_index, effects, trace_info.recording, local_space); if (track_events) events.insert(result); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, dst_mask, fill_expr); } } } } //-------------------------------------------------------------------------- void CopyFillAggregator::issue_copies(InstanceView *target, const std::map<InstanceView*, std::vector<CopyUpdate*> > &copies, ApEvent precondition, const FieldMask &copy_mask, const PhysicalTraceInfo &trace_info, const bool has_dst_preconditions) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!copies.empty()); assert(!!copy_mask); #endif const UniqueID op_id = op->get_unique_op_id(); PhysicalManager *target_manager = target->get_manager(); for (std::map<InstanceView*,std::vector<CopyUpdate*> >::const_iterator cit = copies.begin(); cit != copies.end(); cit++) { #ifdef DEBUG_LEGION assert(!cit->second.empty()); #endif if (cit->second.size() == 1) { // Easy case of a single update copy CopyUpdate *update = cit->second[0]; #ifdef DEBUG_LEGION // Should cover all the fields assert(!(copy_mask - update->src_mask)); #endif InstanceView *source = update->source; IndexSpaceExpression *copy_expr = update->expr; // See if we have any work to do for tracing if (trace_info.recording) { if (tracing_srcs == NULL) tracing_srcs = new FieldMaskSet<InstanceView>(); else tracing_srcs->clear(); tracing_srcs->insert(source, copy_mask); if (tracing_dsts == NULL) tracing_dsts = new FieldMaskSet<InstanceView>(); else tracing_dsts->clear(); // Handle the across case properly here if (update->across_helper != NULL) { const FieldMask dst_mask = update->across_helper->convert_src_to_dst(copy_mask); tracing_dsts->insert(target, dst_mask); } else tracing_dsts->insert(target, copy_mask); } const ApEvent result = target_manager->copy_from( source->get_manager(), precondition, predicate_guard, update->redop, copy_expr, copy_mask, trace_info, cit->second[0]->across_helper, tracing_srcs, tracing_dsts); if (result.exists()) { const RtEvent collect_event = trace_info.get_collect_event(); source->add_copy_user(true/*reading*/, result, collect_event, copy_mask, copy_expr, op_id,src_index, effects, trace_info.recording, local_space); if (update->across_helper != NULL) { const FieldMask dst_mask = update->across_helper->convert_src_to_dst(copy_mask); target->add_copy_user(false/*reading*/, result, collect_event, dst_mask, copy_expr, op_id, dst_index, effects, trace_info.recording, local_space); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, dst_mask, copy_expr); } else { target->add_copy_user(false/*reading*/, result, collect_event, copy_mask, copy_expr, op_id,dst_index, effects, trace_info.recording, local_space); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, copy_mask, copy_expr); } if (track_events) events.insert(result); } } else { // Have to group by source instances in order to merge together // different index space expressions for the same copy std::map<InstanceView*,std::set<IndexSpaceExpression*> > src_exprs; const ReductionOpID redop = cit->second[0]->redop; for (std::vector<CopyUpdate*>::const_iterator it = cit->second.begin(); it != cit->second.end(); it++) { #ifdef DEBUG_LEGION // Should cover all the fields assert(!(copy_mask - (*it)->src_mask)); // Should have the same redop assert(redop == (*it)->redop); // Should also have the same across helper as the first one assert(cit->second[0]->across_helper == (*it)->across_helper); #endif src_exprs[(*it)->source].insert((*it)->expr); } const FieldMask dst_mask = (cit->second[0]->across_helper == NULL) ? copy_mask : cit->second[0]->across_helper->convert_src_to_dst(copy_mask); // If we're tracing we can get the destination now if (trace_info.recording) { if (tracing_dsts == NULL) tracing_dsts = new FieldMaskSet<InstanceView>(); else tracing_dsts->clear(); tracing_dsts->insert(target, dst_mask); } for (std::map<InstanceView*,std::set<IndexSpaceExpression*> >:: const_iterator it = src_exprs.begin(); it != src_exprs.end(); it++) { IndexSpaceExpression *copy_expr = (it->second.size() == 1) ? *(it->second.begin()) : forest->union_index_spaces(it->second); // If we're tracing then get the source information if (trace_info.recording) { if (tracing_srcs == NULL) tracing_srcs = new FieldMaskSet<InstanceView>(); else tracing_srcs->clear(); tracing_srcs->insert(it->first, copy_mask); } const ApEvent result = target_manager->copy_from( it->first->get_manager(), precondition, predicate_guard, redop, copy_expr, copy_mask, trace_info, cit->second[0]->across_helper, tracing_srcs, tracing_dsts); const RtEvent collect_event = trace_info.get_collect_event(); if (result.exists()) { it->first->add_copy_user(true/*reading*/, result, collect_event, copy_mask, copy_expr, op_id,src_index, effects, trace_info.recording, local_space); target->add_copy_user(false/*reading*/, result, collect_event, dst_mask, copy_expr, op_id, dst_index, effects, trace_info.recording, local_space); if (track_events) events.insert(result); // Record this for the next iteration if necessary if (has_dst_preconditions) record_precondition(target, false/*reading*/, result, dst_mask, copy_expr); } } } } } //-------------------------------------------------------------------------- /*static*/ void CopyFillAggregator::handle_aggregation(const void *args) //-------------------------------------------------------------------------- { const CopyFillAggregation *cfargs = (const CopyFillAggregation*)args; cfargs->aggregator->issue_updates(*cfargs, cfargs->pre, cfargs->has_src, cfargs->has_dst, false/*needs deferral*/, cfargs->pass, cfargs->need_pass_preconditions); cfargs->remove_recorder_reference(); } ///////////////////////////////////////////////////////////// // Physical Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- PhysicalAnalysis::PhysicalAnalysis(Runtime *rt, Operation *o, unsigned idx, const VersionInfo &info, bool h) : previous(rt->address_space), original_source(rt->address_space), runtime(rt), op(o), index(idx), version_manager(info.get_manager()), owns_op(false), on_heap(h), remote_instances(NULL), restricted(false), parallel_traversals(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalAnalysis::PhysicalAnalysis(Runtime *rt, AddressSpaceID source, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, bool h) : previous(prev), original_source(source), runtime(rt), op(o), index(idx), version_manager(man), owns_op(true), on_heap(h), remote_instances(NULL), restricted(false), parallel_traversals(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalAnalysis::PhysicalAnalysis(const PhysicalAnalysis &rhs) : previous(0), original_source(0), runtime(NULL), op(NULL), index(0), version_manager(NULL), owns_op(false), on_heap(false) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- PhysicalAnalysis::~PhysicalAnalysis(void) //-------------------------------------------------------------------------- { if (remote_instances != NULL) delete remote_instances; if (owns_op && (op != NULL)) delete op; } //-------------------------------------------------------------------------- void PhysicalAnalysis::traverse(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, const bool cached_set, RtEvent precondition/*= NO_EVENT*/, const bool already_deferred /* = false*/) //-------------------------------------------------------------------------- { if (precondition.exists() && !precondition.has_triggered()) { // This has to be the first time through and isn't really // a deferral of an the traversal since we haven't even // started the traversal yet defer_traversal(precondition, set, mask, deferral_events,applied_events, cached_set, RtUserEvent::NO_RT_USER_EVENT, already_deferred); } else { if (cached_set) { FieldMask stale_mask; perform_traversal(set, mask, deferral_events, applied_events, &stale_mask, cached_set, already_deferred); if (!!stale_mask) stale_sets.insert(set, stale_mask); } else perform_traversal(set, mask, deferral_events, applied_events, NULL/*remove*/, cached_set, already_deferred); } } //-------------------------------------------------------------------------- void PhysicalAnalysis::defer_traversal(RtEvent precondition, EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, const bool cached_set, RtUserEvent deferral_event, const bool already_deferred) //-------------------------------------------------------------------------- { // Make sure that we record that this has parallel traversals const DeferPerformTraversalArgs args(this, set, mask, deferral_event, cached_set, already_deferred); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, precondition); deferral_events.insert(args.done_event); applied_events.insert(args.applied_event); } //-------------------------------------------------------------------------- void PhysicalAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { // only called by derived classes assert(false); } //-------------------------------------------------------------------------- RtEvent PhysicalAnalysis::perform_remote(RtEvent precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { // only called by derived classes assert(false); return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- RtEvent PhysicalAnalysis::perform_updates(RtEvent precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { // only called by derived classes assert(false); return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- ApEvent PhysicalAnalysis::perform_output(RtEvent precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { // only called by derived classes assert(false); return ApEvent::NO_AP_EVENT; } //-------------------------------------------------------------------------- void PhysicalAnalysis::process_remote_instances(Deserializer &derez, std::set<RtEvent> &ready_events) //-------------------------------------------------------------------------- { size_t num_views; derez.deserialize(num_views); AutoLock a_lock(*this); if (remote_instances == NULL) remote_instances = new FieldMaskSet<InstanceView>(); for (unsigned idx = 0; idx < num_views; idx++) { DistributedID view_did; derez.deserialize(view_did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(view_did, ready); if (ready.exists()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); remote_instances->insert(static_cast<InstanceView*>(view), mask); } bool remote_restrict; derez.deserialize(remote_restrict); if (remote_restrict) restricted = true; } //-------------------------------------------------------------------------- void PhysicalAnalysis::process_local_instances( const FieldMaskSet<InstanceView> &views, const bool local_restricted) //-------------------------------------------------------------------------- { AutoLock a_lock(*this); if (remote_instances == NULL) remote_instances = new FieldMaskSet<InstanceView>(); for (FieldMaskSet<InstanceView>::const_iterator it = views.begin(); it != views.end(); it++) if (it->first->is_instance_view()) remote_instances->insert(it->first, it->second); if (local_restricted) restricted = true; } //-------------------------------------------------------------------------- void PhysicalAnalysis::filter_remote_expressions( FieldMaskSet<IndexSpaceExpression> &exprs) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!remote_sets.empty()); #endif FieldMaskSet<IndexSpaceExpression> remote_exprs; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) remote_exprs.insert(it->first->set_expr, it->second); FieldMaskSet<IndexSpaceExpression> to_add; std::vector<IndexSpaceExpression*> to_remove; if (remote_exprs.size() > 1) { LegionList<FieldSet<IndexSpaceExpression*> >::aligned field_sets; remote_exprs.compute_field_sets(FieldMask(), field_sets); for (LegionList<FieldSet<IndexSpaceExpression*> >::aligned:: const_iterator fit = field_sets.begin(); fit != field_sets.end(); fit++) { IndexSpaceExpression *remote_expr = (fit->elements.size() == 1) ? *(fit->elements.begin()) : runtime->forest->union_index_spaces(fit->elements); for (FieldMaskSet<IndexSpaceExpression>::iterator it = exprs.begin(); it != exprs.end(); it++) { const FieldMask overlap = it->second & fit->set_mask; if (!overlap) continue; IndexSpaceExpression *diff = runtime->forest->subtract_index_spaces(it->first, remote_expr); if (!diff->is_empty()) to_add.insert(diff, overlap); it.filter(overlap); if (!it->second) to_remove.push_back(it->first); } } } else { FieldMaskSet<IndexSpaceExpression>::const_iterator first = remote_exprs.begin(); for (FieldMaskSet<IndexSpaceExpression>::iterator it = exprs.begin(); it != exprs.end(); it++) { const FieldMask overlap = it->second & first->second; if (!overlap) continue; IndexSpaceExpression *diff = runtime->forest->subtract_index_spaces(it->first, first->first); if (!diff->is_empty()) to_add.insert(diff, overlap); it.filter(overlap); if (!it->second) to_remove.push_back(it->first); } } if (!to_remove.empty()) { for (std::vector<IndexSpaceExpression*>::const_iterator it = to_remove.begin(); it != to_remove.end(); it++) exprs.erase(*it); } if (!to_add.empty()) { for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = to_add.begin(); it != to_add.end(); it++) exprs.insert(it->first, it->second); } } //-------------------------------------------------------------------------- bool PhysicalAnalysis::report_instances(FieldMaskSet<InstanceView> &insts) //-------------------------------------------------------------------------- { // No need for the lock since we shouldn't be mutating anything at // this point anyway if (remote_instances != NULL) remote_instances->swap(insts); return restricted; } //-------------------------------------------------------------------------- bool PhysicalAnalysis::update_alt_sets(EquivalenceSet *set, FieldMask &mask) //-------------------------------------------------------------------------- { if (parallel_traversals) { // Need the lock in this case AutoLock a_lock(*this); FieldMaskSet<EquivalenceSet>::iterator finder = alt_sets.find(set); // Remove any fields we already traversed if (finder != alt_sets.end()) { mask -= finder->second; // If we already traversed it then we don't need to do it again if (!mask) return true; // early out finder.merge(mask); } else alt_sets.insert(set, mask); } else { // No parallel traversals means we're the only thread FieldMaskSet<EquivalenceSet>::iterator finder = alt_sets.find(set); // Remove any fields we already traversed if (finder != alt_sets.end()) { mask -= finder->second; // If we already traversed it then we don't need to do it again if (!mask) return true; // early out finder.merge(mask); } else alt_sets.insert(set, mask); } return false; } //-------------------------------------------------------------------------- void PhysicalAnalysis::filter_alt_sets(EquivalenceSet *set, const FieldMask &mask) //-------------------------------------------------------------------------- { if (parallel_traversals) { // Need the lock if there are parallel traversals AutoLock a_lock(*this); FieldMaskSet<EquivalenceSet>::iterator finder = alt_sets.find(set); if (finder != alt_sets.end()) { finder.filter(mask); if (!finder->second) alt_sets.erase(finder); } } else { // No parallel traversals means no lock needed FieldMaskSet<EquivalenceSet>::iterator finder = alt_sets.find(set); if (finder != alt_sets.end()) { finder.filter(mask); if (!finder->second) alt_sets.erase(finder); } } } //-------------------------------------------------------------------------- void PhysicalAnalysis::record_stale_set(EquivalenceSet *set, const FieldMask &mask) //-------------------------------------------------------------------------- { if (parallel_traversals) { // Lock needed if we're doing parallel traversals AutoLock a_lock(*this); stale_sets.insert(set, mask); } else // No lock needed if we're the only one stale_sets.insert(set, mask); } //-------------------------------------------------------------------------- void PhysicalAnalysis::record_remote(EquivalenceSet *set, const FieldMask &mask, const AddressSpaceID owner, const bool cached_set) //-------------------------------------------------------------------------- { const std::pair<AddressSpaceID,bool> key(owner, cached_set); if (parallel_traversals) { AutoLock a_lock(*this); remote_sets[key].insert(set, mask); } else // No lock needed if we're the only one remote_sets[key].insert(set, mask); } //-------------------------------------------------------------------------- void PhysicalAnalysis::update_stale_equivalence_sets( std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { // No need for the lock here since we know there are no // races because there are no more traversals being performed #ifdef DEBUG_LEGION assert(!stale_sets.empty()); #endif // Check to see if we are on the local node for the version manager // or whether we need to send a message to record the stale sets if (original_source != runtime->address_space) { RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize<size_t>(stale_sets.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = stale_sets.begin(); it != stale_sets.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize(version_manager); rez.serialize(applied); } runtime->send_equivalence_set_stale_update(original_source, rez); applied_events.insert(applied); } else // the local node case { const RtEvent done = version_manager->record_stale_sets(stale_sets); if (done.exists()) applied_events.insert(done); } } //-------------------------------------------------------------------------- void PhysicalAnalysis::record_instance(InstanceView *view, const FieldMask &mask) //-------------------------------------------------------------------------- { // Lock held from caller if (remote_instances == NULL) remote_instances = new FieldMaskSet<InstanceView>(); remote_instances->insert(view, mask); } //-------------------------------------------------------------------------- /*static*/ void PhysicalAnalysis::handle_remote_instances( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); PhysicalAnalysis *target; derez.deserialize(target); RtUserEvent done_event; derez.deserialize(done_event); std::set<RtEvent> ready_events; target->process_remote_instances(derez, ready_events); if (!ready_events.empty()) Runtime::trigger_event(done_event, Runtime::merge_events(ready_events)); else Runtime::trigger_event(done_event); } //-------------------------------------------------------------------------- PhysicalAnalysis::DeferPerformTraversalArgs::DeferPerformTraversalArgs( PhysicalAnalysis *ana, EquivalenceSet *s, const FieldMask &m, RtUserEvent done, bool cached, bool def) : LgTaskArgs<DeferPerformTraversalArgs>(ana->op->get_unique_op_id()), analysis(ana), set(s), mask(new FieldMask(m)), applied_event(Runtime::create_rt_user_event()), done_event(done.exists() ? done : Runtime::create_rt_user_event()), cached_set(cached), already_deferred(def) //-------------------------------------------------------------------------- { analysis->record_parallel_traversals(); if (analysis->on_heap) analysis->add_reference(); } //-------------------------------------------------------------------------- /*static*/void PhysicalAnalysis::handle_deferred_traversal(const void *args) //-------------------------------------------------------------------------- { const DeferPerformTraversalArgs *dargs = (const DeferPerformTraversalArgs*)args; // Get this before doing anything const bool on_heap = dargs->analysis->on_heap; std::set<RtEvent> deferral_events, applied_events; dargs->analysis->traverse(dargs->set, *(dargs->mask), deferral_events, applied_events, dargs->cached_set, RtEvent::NO_RT_EVENT, dargs->already_deferred); if (!deferral_events.empty()) Runtime::trigger_event(dargs->done_event, Runtime::merge_events(deferral_events)); else Runtime::trigger_event(dargs->done_event); if (!applied_events.empty()) Runtime::trigger_event(dargs->applied_event, Runtime::merge_events(applied_events)); else Runtime::trigger_event(dargs->applied_event); if (on_heap && dargs->analysis->remove_reference()) delete dargs->analysis; delete dargs->mask; } //-------------------------------------------------------------------------- PhysicalAnalysis::DeferPerformRemoteArgs::DeferPerformRemoteArgs( PhysicalAnalysis *ana) : LgTaskArgs<DeferPerformRemoteArgs>(ana->op->get_unique_op_id()), analysis(ana), applied_event(Runtime::create_rt_user_event()), done_event(Runtime::create_rt_user_event()) //-------------------------------------------------------------------------- { if (analysis->on_heap) analysis->add_reference(); } //-------------------------------------------------------------------------- /*static*/ void PhysicalAnalysis::handle_deferred_remote(const void *args) //-------------------------------------------------------------------------- { const DeferPerformRemoteArgs *dargs = (const DeferPerformRemoteArgs*)args; std::set<RtEvent> applied_events; // Get this before doing anything const bool on_heap = dargs->analysis->on_heap; const RtEvent done = dargs->analysis->perform_remote(RtEvent::NO_RT_EVENT, applied_events, true/*already deferred*/); Runtime::trigger_event(dargs->done_event, done); if (!applied_events.empty()) Runtime::trigger_event(dargs->applied_event, Runtime::merge_events(applied_events)); else Runtime::trigger_event(dargs->applied_event); if (on_heap && dargs->analysis->remove_reference()) delete dargs->analysis; } //-------------------------------------------------------------------------- PhysicalAnalysis::DeferPerformUpdateArgs::DeferPerformUpdateArgs( PhysicalAnalysis *ana) : LgTaskArgs<DeferPerformUpdateArgs>(ana->op->get_unique_op_id()), analysis(ana), applied_event(Runtime::create_rt_user_event()), done_event(Runtime::create_rt_user_event()) //-------------------------------------------------------------------------- { if (analysis->on_heap) analysis->add_reference(); } //-------------------------------------------------------------------------- /*static*/ void PhysicalAnalysis::handle_deferred_update(const void *args) //-------------------------------------------------------------------------- { const DeferPerformUpdateArgs *dargs = (const DeferPerformUpdateArgs*)args; std::set<RtEvent> applied_events; // Get this before doing anything const bool on_heap = dargs->analysis->on_heap; const RtEvent done =dargs->analysis->perform_updates(RtEvent::NO_RT_EVENT, applied_events, true/*already deferred*/); Runtime::trigger_event(dargs->done_event, done); if (!applied_events.empty()) Runtime::trigger_event(dargs->applied_event, Runtime::merge_events(applied_events)); else Runtime::trigger_event(dargs->applied_event); if (on_heap && dargs->analysis->remove_reference()) delete dargs->analysis; } //-------------------------------------------------------------------------- PhysicalAnalysis::DeferPerformOutputArgs::DeferPerformOutputArgs( PhysicalAnalysis *ana) : LgTaskArgs<DeferPerformOutputArgs>(ana->op->get_unique_op_id()), analysis(ana), applied_event(Runtime::create_rt_user_event()), effects_event(Runtime::create_ap_user_event()) //-------------------------------------------------------------------------- { if (analysis->on_heap) analysis->add_reference(); } //-------------------------------------------------------------------------- /*static*/ void PhysicalAnalysis::handle_deferred_output(const void *args) //-------------------------------------------------------------------------- { const DeferPerformOutputArgs *dargs = (const DeferPerformOutputArgs*)args; std::set<RtEvent> applied_events; const bool on_heap = dargs->analysis->on_heap; const ApEvent effects = dargs->analysis->perform_output( RtEvent::NO_RT_EVENT, applied_events, true/*already deferred*/); // Get this before doing anything Runtime::trigger_event(dargs->effects_event, effects); if (!applied_events.empty()) Runtime::trigger_event(dargs->applied_event, Runtime::merge_events(applied_events)); else Runtime::trigger_event(dargs->applied_event); if (on_heap && dargs->analysis->remove_reference()) delete dargs->analysis; } ///////////////////////////////////////////////////////////// // Valid Inst Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- ValidInstAnalysis::ValidInstAnalysis(Runtime *rt, Operation *o,unsigned idx, const VersionInfo &info, ReductionOpID red) : PhysicalAnalysis(rt, o, idx, info, false/*on heap*/), redop(red), target_analysis(this) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ValidInstAnalysis::ValidInstAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, ValidInstAnalysis *t, ReductionOpID red) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), redop(red), target_analysis(t) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ValidInstAnalysis::ValidInstAnalysis(const ValidInstAnalysis &rhs) : PhysicalAnalysis(rhs), redop(0), target_analysis(NULL) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- ValidInstAnalysis::~ValidInstAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ValidInstAnalysis& ValidInstAnalysis::operator=(const ValidInstAnalysis &rs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void ValidInstAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->find_valid_instances(*this, mask, deferral_events, applied_events, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent ValidInstAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Easy out if we don't have remote sets if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; std::set<RtEvent> ready_events; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent ready = Runtime::create_rt_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize(redop); rez.serialize(target_analysis); rez.serialize(ready); rez.serialize(applied); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_request_instances(target, rez); ready_events.insert(ready); applied_events.insert(applied); } return Runtime::merge_events(ready_events); } //-------------------------------------------------------------------------- RtEvent ValidInstAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (remote_instances != NULL) { if (original_source != runtime->address_space) { const RtUserEvent response_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(target_analysis); rez.serialize(response_event); rez.serialize<size_t>(remote_instances->size()); for (FieldMaskSet<InstanceView>::const_iterator it = remote_instances->begin(); it != remote_instances->end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<bool>(restricted); } runtime->send_equivalence_set_remote_instances(original_source, rez); return response_event; } else target_analysis->process_local_instances(*remote_instances, restricted); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- /*static*/ void ValidInstAnalysis::handle_remote_request_instances( Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); ReductionOpID redop; derez.deserialize(redop); ValidInstAnalysis *target; derez.deserialize(target); RtUserEvent ready; derez.deserialize(ready); RtUserEvent applied; derez.deserialize(applied); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); ValidInstAnalysis *analysis = new ValidInstAnalysis(runtime, original_source, previous, op, index, version_manager, target, redop); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Wait for the equivalence sets to be ready if necessary RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); if (traversal_done.exists() || analysis->has_remote_sets()) { const RtEvent remote_ready = analysis->perform_remote(traversal_done, applied_events); if (remote_ready.exists()) ready_events.insert(remote_ready); } // Defer sending the updates until we're ready const RtEvent local_ready = analysis->perform_updates(traversal_done, applied_events); if (local_ready.exists()) ready_events.insert(local_ready); if (!ready_events.empty()) Runtime::trigger_event(ready, Runtime::merge_events(ready_events)); else Runtime::trigger_event(ready); if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Invalid Inst Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- InvalidInstAnalysis::InvalidInstAnalysis(Runtime *rt, Operation *o, unsigned idx, const VersionInfo &info, const FieldMaskSet<InstanceView> &valid_insts) : PhysicalAnalysis(rt, o, idx, info, false/*on heap*/), valid_instances(valid_insts), target_analysis(this) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InvalidInstAnalysis::InvalidInstAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, InvalidInstAnalysis *t, const FieldMaskSet<InstanceView> &valid_insts) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), valid_instances(valid_insts), target_analysis(t) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InvalidInstAnalysis::InvalidInstAnalysis(const InvalidInstAnalysis &rhs) : PhysicalAnalysis(rhs), valid_instances(rhs.valid_instances), target_analysis(NULL) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- InvalidInstAnalysis::~InvalidInstAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InvalidInstAnalysis& InvalidInstAnalysis::operator=( const InvalidInstAnalysis &rs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void InvalidInstAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->find_invalid_instances(*this, mask, deferral_events, applied_events, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent InvalidInstAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Easy out if we don't have remote sets if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; std::set<RtEvent> ready_events; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent ready = Runtime::create_rt_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize<size_t>(valid_instances.size()); for (FieldMaskSet<InstanceView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize(target_analysis); rez.serialize(ready); rez.serialize(applied); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_request_invalid(target, rez); ready_events.insert(ready); applied_events.insert(applied); } return Runtime::merge_events(ready_events); } //-------------------------------------------------------------------------- RtEvent InvalidInstAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (remote_instances != NULL) { if (original_source != runtime->address_space) { const RtUserEvent response_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(target_analysis); rez.serialize(response_event); rez.serialize<size_t>(remote_instances->size()); for (FieldMaskSet<InstanceView>::const_iterator it = remote_instances->begin(); it != remote_instances->end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<bool>(restricted); } runtime->send_equivalence_set_remote_instances(original_source, rez); return response_event; } else target_analysis->process_local_instances(*remote_instances, restricted); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- /*static*/ void InvalidInstAnalysis::handle_remote_request_invalid( Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); FieldMaskSet<InstanceView> valid_instances; size_t num_valid_instances; derez.deserialize<size_t>(num_valid_instances); for (unsigned idx = 0; idx < num_valid_instances; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; InstanceView *view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(did, ready)); if (ready.exists()) ready_events.insert(ready); FieldMask view_mask; derez.deserialize(view_mask); valid_instances.insert(view, view_mask); } InvalidInstAnalysis *target; derez.deserialize(target); RtUserEvent ready; derez.deserialize(ready); RtUserEvent applied; derez.deserialize(applied); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); InvalidInstAnalysis *analysis = new InvalidInstAnalysis(runtime, original_source, previous, op, index, version_manager, target, valid_instances); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Wait for the equivalence sets to be ready if necessary RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); if (traversal_done.exists() || analysis->has_remote_sets()) { const RtEvent remote_ready = analysis->perform_remote(traversal_done, applied_events); if (remote_ready.exists()) ready_events.insert(remote_ready); } // Defer sending the updates until we're ready const RtEvent local_ready = analysis->perform_updates(traversal_done, applied_events); if (local_ready.exists()) ready_events.insert(local_ready); if (!ready_events.empty()) Runtime::trigger_event(ready, Runtime::merge_events(ready_events)); else Runtime::trigger_event(ready); if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Update Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- UpdateAnalysis::UpdateAnalysis(Runtime *rt, Operation *o, unsigned idx, const VersionInfo &info, const RegionRequirement &req, RegionNode *rn, const InstanceSet &target_insts, std::vector<InstanceView*> &target_vws, const PhysicalTraceInfo &t_info, const ApEvent pre, const ApEvent term, const bool track, const bool check, const bool record) : PhysicalAnalysis(rt, o, idx, info, true/*on heap*/), usage(req), node(rn), target_instances(target_insts), target_views(target_vws), trace_info(t_info), precondition(pre), term_event(term), track_effects(track), check_initialized(check && !IS_DISCARD(usage) && !IS_SIMULT(usage)), record_valid(record), output_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- UpdateAnalysis::UpdateAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, const RegionUsage &use, RegionNode *rn, InstanceSet &target_insts, std::vector<InstanceView*> &target_vws, const PhysicalTraceInfo &info, const RtEvent user_reg, const ApEvent pre, const ApEvent term, const bool track, const bool check, const bool record) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), usage(use), node(rn), target_instances(target_insts), target_views(target_vws), trace_info(info), precondition(pre), term_event(term), track_effects(track), check_initialized(check), record_valid(record), output_aggregator(NULL), remote_user_registered(user_reg) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- UpdateAnalysis::UpdateAnalysis(const UpdateAnalysis &rhs) : PhysicalAnalysis(rhs), usage(rhs.usage), node(rhs.node), target_instances(rhs.target_instances), target_views(rhs.target_views), trace_info(rhs.trace_info), precondition(rhs.precondition), term_event(rhs.term_event), track_effects(rhs.track_effects), check_initialized(rhs.check_initialized), record_valid(rhs.record_valid) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- UpdateAnalysis::~UpdateAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- UpdateAnalysis& UpdateAnalysis::operator=(const UpdateAnalysis &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- void UpdateAnalysis::record_uninitialized(const FieldMask &uninit, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { if (!uninitialized) { #ifdef DEBUG_LEGION assert(!uninitialized_reported.exists()); #endif uninitialized_reported = Runtime::create_rt_user_event(); applied_events.insert(uninitialized_reported); } uninitialized |= uninit; } //-------------------------------------------------------------------------- void UpdateAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->update_set(*this, mask, deferral_events, applied_events, stale_mask, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent UpdateAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Easy out if we don't have any remote sets if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; #ifdef DEBUG_LEGION assert(!target_instances.empty()); assert(target_instances.size() == target_views.size()); #endif if (!remote_user_registered.exists()) { #ifdef DEBUG_LEGION assert(original_source == runtime->address_space); assert(!user_registered.exists()); #endif user_registered = Runtime::create_rt_user_event(); remote_user_registered = user_registered; } std::set<RtEvent> remote_events; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent updated = Runtime::create_rt_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); const ApUserEvent effects = track_effects ? Runtime::create_ap_user_event() : ApUserEvent::NO_AP_USER_EVENT; Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize(node->handle); rez.serialize(usage); rez.serialize<size_t>(target_instances.size()); for (unsigned idx = 0; idx < target_instances.size(); idx++) { const InstanceRef &ref = target_instances[idx]; rez.serialize(ref.get_manager()->did); rez.serialize(target_views[idx]->did); rez.serialize(ref.get_valid_fields()); } trace_info.pack_trace_info<false>(rez, applied_events, target); rez.serialize(precondition); rez.serialize(term_event); rez.serialize(updated); rez.serialize(remote_user_registered); rez.serialize(applied); rez.serialize(effects); rez.serialize(version_manager); rez.serialize<bool>(check_initialized); rez.serialize<bool>(record_valid); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_updates(target, rez); remote_events.insert(updated); applied_events.insert(applied); if (track_effects) effects_events.insert(effects); } return Runtime::merge_events(remote_events); } //-------------------------------------------------------------------------- RtEvent UpdateAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Report any uninitialized data now that we know the traversal is done if (!!uninitialized) { #ifdef DEBUG_LEGION assert(check_initialized); assert(uninitialized_reported.exists()); #endif node->report_uninitialized_usage(op, index, usage, uninitialized, uninitialized_reported); } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (!input_aggregators.empty()) { const bool needs_deferral = !already_deferred || (input_aggregators.size() > 1); for (std::map<RtEvent,CopyFillAggregator*>::const_iterator it = input_aggregators.begin(); it != input_aggregators.end(); it++) { it->second->issue_updates(trace_info, precondition, false/*has src*/, false/*has dst*/, needs_deferral); #ifdef NON_AGGRESSIVE_AGGREGATORS if (!it->second->effects_applied.has_triggered()) guard_events.insert(it->second->effects_applied); #else if (!it->second->guard_postcondition.has_triggered()) guard_events.insert(it->second->guard_postcondition); #endif if (it->second->release_guards(op->runtime, applied_events)) delete it->second; } } if (!guard_events.empty()) return Runtime::merge_events(guard_events); else return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- ApEvent UpdateAnalysis::perform_output(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformOutputArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.effects_event; } ApEvent result; if (output_aggregator != NULL) { output_aggregator->issue_updates(trace_info, term_event); // We need to wait for the aggregator updates to be applied // here before we can summarize the output #ifdef NON_AGGRESSIVE_AGGREGATORS if (!output_aggregator->effects_applied.has_triggered()) output_aggregator->effects_applied.wait(); #else if (!output_aggregator->guard_postcondition.has_triggered()) output_aggregator->guard_postcondition.wait(); #endif result = output_aggregator->summarize(trace_info); if (output_aggregator->release_guards(op->runtime, applied_events)) delete output_aggregator; } return result; } //-------------------------------------------------------------------------- /*static*/ void UpdateAnalysis::handle_remote_updates(Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); FieldMask user_mask; for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); user_mask |= eq_masks[idx]; } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); LogicalRegion handle; derez.deserialize(handle); RegionUsage usage; derez.deserialize(usage); size_t num_targets; derez.deserialize(num_targets); InstanceSet targets(num_targets); std::vector<InstanceView*> target_views(num_targets, NULL); for (unsigned idx = 0; idx < num_targets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; PhysicalManager *manager = runtime->find_or_request_physical_manager(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(did); LogicalView *view = runtime->find_or_request_logical_view(did, ready); target_views[idx] = static_cast<InstanceView*>(view); if (ready.exists()) ready_events.insert(ready); FieldMask valid_fields; derez.deserialize(valid_fields); targets[idx] = InstanceRef(manager, valid_fields); } PhysicalTraceInfo trace_info = PhysicalTraceInfo::unpack_trace_info(derez, runtime, op); ApEvent precondition; derez.deserialize(precondition); ApEvent term_event; derez.deserialize(term_event); RtUserEvent updated; derez.deserialize(updated); RtEvent remote_user_registered; derez.deserialize(remote_user_registered); RtUserEvent applied; derez.deserialize(applied); ApUserEvent effects_done; derez.deserialize(effects_done); const bool track_effects = effects_done.exists(); VersionManager *version_manager; derez.deserialize(version_manager); bool check_initialized; derez.deserialize(check_initialized); bool record_valid; derez.deserialize(record_valid); bool cached_sets; derez.deserialize(cached_sets); RegionNode *node = runtime->forest->get_node(handle); // This takes ownership of the remote operation UpdateAnalysis *analysis = new UpdateAnalysis(runtime, original_source, previous, op, index, version_manager, usage, node, targets, target_views, trace_info, remote_user_registered, precondition, term_event, track_effects, check_initialized, record_valid); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Make sure that all our pointers are ready RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); std::set<RtEvent> update_events; // If we have remote messages to send do that now if (traversal_done.exists() || analysis->has_remote_sets()) { const RtEvent remote_ready = analysis->perform_remote(traversal_done, applied_events); if (remote_ready.exists()) update_events.insert(remote_ready); } // Then perform the updates // Note that we need to capture all the effects of these updates // before we can consider them applied, so we can't use the // applied_events data structure here const RtEvent updates_ready = analysis->perform_updates(traversal_done, update_events); if (updates_ready.exists()) update_events.insert(updates_ready); // We can trigger our updated event done when all the guards are done if (!update_events.empty()) Runtime::trigger_event(updated, Runtime::merge_events(update_events)); else Runtime::trigger_event(updated); // If we have outputs we need for the user to be registered // before we can apply the output copies const ApEvent result = analysis->perform_output(remote_user_registered, applied_events); if (effects_done.exists()) Runtime::trigger_event(effects_done, result); // Do the rest of the triggers if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Acquire Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- AcquireAnalysis::AcquireAnalysis(Runtime *rt, Operation *o, unsigned idx, const VersionInfo &info) : PhysicalAnalysis(rt, o, idx, info, false/*on heap*/), target_analysis(this) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- AcquireAnalysis::AcquireAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, AcquireAnalysis *t) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), target_analysis(t) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- AcquireAnalysis::AcquireAnalysis(const AcquireAnalysis &rhs) : PhysicalAnalysis(rhs), target_analysis(rhs.target_analysis) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- AcquireAnalysis::~AcquireAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- AcquireAnalysis& AcquireAnalysis::operator=(const AcquireAnalysis &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void AcquireAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->acquire_restrictions(*this, mask, deferral_events, applied_events, stale_mask, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent AcquireAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Easy out if there is nothing to do if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; std::set<RtEvent> remote_events; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent returned = Runtime::create_rt_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize(returned); rez.serialize(applied); rez.serialize(target_analysis); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_acquires(target, rez); applied_events.insert(applied); remote_events.insert(returned); } return Runtime::merge_events(remote_events); } //-------------------------------------------------------------------------- RtEvent AcquireAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (remote_instances != NULL) { if (original_source != runtime->address_space) { const RtUserEvent response_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(target_analysis); rez.serialize(response_event); rez.serialize<size_t>(remote_instances->size()); for (FieldMaskSet<InstanceView>::const_iterator it = remote_instances->begin(); it != remote_instances->end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<bool>(restricted); } runtime->send_equivalence_set_remote_instances(original_source, rez); return response_event; } else target_analysis->process_local_instances(*remote_instances, restricted); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- /*static*/ void AcquireAnalysis::handle_remote_acquires(Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); RtUserEvent returned; derez.deserialize(returned); RtUserEvent applied; derez.deserialize(applied); AcquireAnalysis *target; derez.deserialize(target); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); // This takes ownership of the operation AcquireAnalysis *analysis = new AcquireAnalysis(runtime, original_source, previous, op, index, version_manager, target); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Make sure that all our pointers are ready RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); if (traversal_done.exists() || analysis->has_remote_sets()) { const RtEvent remote_ready = analysis->perform_remote(traversal_done, applied_events); if (remote_ready.exists()) ready_events.insert(remote_ready); } // Defer sending the updates until we're ready const RtEvent local_ready = analysis->perform_updates(traversal_done, applied_events); if (local_ready.exists()) ready_events.insert(local_ready); if (!ready_events.empty()) Runtime::trigger_event(returned, Runtime::merge_events(ready_events)); else Runtime::trigger_event(returned); if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Release Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- ReleaseAnalysis::ReleaseAnalysis(Runtime *rt, Operation *o, unsigned idx, ApEvent pre, const VersionInfo &info, const PhysicalTraceInfo &t_info) : PhysicalAnalysis(rt, o, idx, info, false/*on heap*/), precondition(pre), target_analysis(this), trace_info(t_info), release_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ReleaseAnalysis::ReleaseAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx,VersionManager *man, ApEvent pre, ReleaseAnalysis *t, const PhysicalTraceInfo &info) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), precondition(pre), target_analysis(t), trace_info(info), release_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ReleaseAnalysis::ReleaseAnalysis(const ReleaseAnalysis &rhs) : PhysicalAnalysis(rhs), target_analysis(rhs.target_analysis), trace_info(rhs.trace_info) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- ReleaseAnalysis::~ReleaseAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ReleaseAnalysis& ReleaseAnalysis::operator=(const ReleaseAnalysis &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void ReleaseAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->release_restrictions(*this, mask, deferral_events, applied_events, stale_mask, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent ReleaseAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Easy out if there is nothing to do if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; std::set<RtEvent> remote_events; for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent returned = Runtime::create_rt_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize(precondition); rez.serialize(returned); rez.serialize(applied); rez.serialize(target_analysis); trace_info.pack_trace_info<false>(rez, applied_events, target); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_releases(target, rez); applied_events.insert(applied); remote_events.insert(returned); } return Runtime::merge_events(remote_events); } //-------------------------------------------------------------------------- RtEvent ReleaseAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { // Defer this if necessary if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); // See if we have any instance names to send back if ((target_analysis != this) && (remote_instances != NULL)) { if (original_source != runtime->address_space) { const RtUserEvent response_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(target_analysis); rez.serialize(response_event); rez.serialize<size_t>(remote_instances->size()); for (FieldMaskSet<InstanceView>::const_iterator it = remote_instances->begin(); it != remote_instances->end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<bool>(restricted); } runtime->send_equivalence_set_remote_instances(original_source, rez); applied_events.insert(response_event); } else target_analysis->process_local_instances(*remote_instances, restricted); } if (release_aggregator != NULL) { std::set<RtEvent> guard_events; release_aggregator->issue_updates(trace_info, precondition); #ifdef NON_AGGRESSIVE_AGGREGATORS if (release_aggregator->effects_applied.has_triggered()) guard_events.insert(release_aggregator->effects_applied); #else if (!release_aggregator->guard_postcondition.has_triggered()) guard_events.insert(release_aggregator->guard_postcondition); #endif if (release_aggregator->release_guards(op->runtime, applied_events)) delete release_aggregator; if (!guard_events.empty()) return Runtime::merge_events(guard_events); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- /*static*/ void ReleaseAnalysis::handle_remote_releases(Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); ApEvent precondition; derez.deserialize(precondition); RtUserEvent returned; derez.deserialize(returned); RtUserEvent applied; derez.deserialize(applied); ReleaseAnalysis *target; derez.deserialize(target); const PhysicalTraceInfo trace_info = PhysicalTraceInfo::unpack_trace_info(derez, runtime, op); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); ReleaseAnalysis *analysis = new ReleaseAnalysis(runtime, original_source, previous, op, index, version_manager, precondition, target, trace_info); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; RtEvent ready_event; // Make sure that all our pointers are ready if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); if (traversal_done.exists() || analysis->has_remote_sets()) { const RtEvent remote_ready = analysis->perform_remote(traversal_done, applied_events); if (remote_ready.exists()) ready_events.insert(remote_ready); } // Note that we use the ready events here for applied so that // we can know that all our updates are done before we tell // the original source node that we've returned const RtEvent local_ready = analysis->perform_updates(traversal_done, (original_source == runtime->address_space) ? applied_events : ready_events); if (local_ready.exists()) ready_events.insert(local_ready); if (!ready_events.empty()) Runtime::trigger_event(returned, Runtime::merge_events(ready_events)); else Runtime::trigger_event(returned); if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Copy Across Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- CopyAcrossAnalysis::CopyAcrossAnalysis(Runtime *rt, Operation *o, unsigned src_idx, unsigned dst_idx, const VersionInfo &info, const RegionRequirement &src_req, const RegionRequirement &dst_req, const InstanceSet &target_insts, const std::vector<InstanceView*> &target_vws, const ApEvent pre, const PredEvent pred, const ReductionOpID red, const std::vector<unsigned> &src_idxes, const std::vector<unsigned> &dst_idxes, const PhysicalTraceInfo &t_info, const bool perf) : PhysicalAnalysis(rt, o, dst_idx, info, true/*on heap*/), src_mask(perf ? FieldMask() : initialize_mask(src_idxes)), dst_mask(perf ? FieldMask() : initialize_mask(dst_idxes)), src_index(src_idx), dst_index(dst_idx), src_usage(src_req), dst_usage(dst_req), src_region(src_req.region), dst_region(dst_req.region), target_instances(target_insts), target_views(target_vws), precondition(pre),pred_guard(pred),redop(red), src_indexes(src_idxes), dst_indexes(dst_idxes), across_helpers(perf ? std::vector<CopyAcrossHelper*>() : create_across_helpers(src_mask, dst_mask, target_instances, src_indexes, dst_indexes)), trace_info(t_info), perfect(perf), across_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyAcrossAnalysis::CopyAcrossAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned src_idx, unsigned dst_idx, const RegionUsage &src_use, const RegionUsage &dst_use, const LogicalRegion src_reg, const LogicalRegion dst_reg, const InstanceSet &target_insts, const std::vector<InstanceView*> &target_vws, const ApEvent pre, const PredEvent pred, const ReductionOpID red, const std::vector<unsigned> &src_idxes, const std::vector<unsigned> &dst_idxes, const PhysicalTraceInfo &t_info, const bool perf) : PhysicalAnalysis(rt, src, prev, o, dst_idx,NULL/*man*/,true/*on heap*/), src_mask(perf ? FieldMask() : initialize_mask(src_idxes)), dst_mask(perf ? FieldMask() : initialize_mask(dst_idxes)), src_index(src_idx), dst_index(dst_idx), src_usage(src_use), dst_usage(dst_use), src_region(src_reg), dst_region(dst_reg), target_instances(target_insts), target_views(target_vws), precondition(pre),pred_guard(pred),redop(red), src_indexes(src_idxes), dst_indexes(dst_idxes), across_helpers(perf ? std::vector<CopyAcrossHelper*>() : create_across_helpers(src_mask, dst_mask, target_instances, src_indexes, dst_indexes)), trace_info(t_info), perfect(perf), across_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- CopyAcrossAnalysis::CopyAcrossAnalysis(const CopyAcrossAnalysis &rhs) : PhysicalAnalysis(rhs), dst_mask(rhs.dst_mask), src_index(rhs.src_index), dst_index(rhs.dst_index), src_usage(rhs.src_usage), dst_usage(rhs.dst_usage), src_region(rhs.src_region), dst_region(rhs.dst_region), target_instances(rhs.target_instances), target_views(rhs.target_views), precondition(rhs.precondition), pred_guard(rhs.pred_guard), redop(rhs.redop), src_indexes(rhs.src_indexes), dst_indexes(rhs.dst_indexes), across_helpers(rhs.across_helpers), trace_info(rhs.trace_info), perfect(rhs.perfect) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- CopyAcrossAnalysis::~CopyAcrossAnalysis(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!aggregator_guard.exists() || aggregator_guard.has_triggered()); #endif for (std::vector<CopyAcrossHelper*>::const_iterator it = across_helpers.begin(); it != across_helpers.end(); it++) delete (*it); } //-------------------------------------------------------------------------- CopyAcrossAnalysis& CopyAcrossAnalysis::operator=( const CopyAcrossAnalysis &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void CopyAcrossAnalysis::record_uninitialized(const FieldMask &uninit, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { if (!uninitialized) { #ifdef DEBUG_LEGION assert(!uninitialized_reported.exists()); #endif uninitialized_reported = Runtime::create_rt_user_event(); applied_events.insert(uninitialized_reported); } uninitialized |= uninit; } //-------------------------------------------------------------------------- CopyFillAggregator* CopyAcrossAnalysis::get_across_aggregator(void) //-------------------------------------------------------------------------- { if (across_aggregator == NULL) { #ifdef DEBUG_LEGION assert(!aggregator_guard.exists()); #endif aggregator_guard = Runtime::create_rt_user_event(); across_aggregator = new CopyFillAggregator(runtime->forest, op, src_index, dst_index, aggregator_guard, true/*track*/, pred_guard); } return across_aggregator; } //-------------------------------------------------------------------------- RtEvent CopyAcrossAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; #ifdef DEBUG_LEGION assert(target_instances.size() == target_views.size()); assert(src_indexes.size() == dst_indexes.size()); #endif for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->first.second); // should not be a cached set here assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const ApUserEvent copy = Runtime::create_ap_user_event(); const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(src_index); rez.serialize(dst_index); rez.serialize(src_usage); rez.serialize(dst_usage); rez.serialize<size_t>(target_instances.size()); for (unsigned idx = 0; idx < target_instances.size(); idx++) { target_instances[idx].pack_reference(rez); rez.serialize(target_views[idx]->did); } rez.serialize(src_region); rez.serialize(dst_region); rez.serialize(pred_guard); rez.serialize(precondition); rez.serialize(redop); rez.serialize<bool>(perfect); if (!perfect) { rez.serialize<size_t>(src_indexes.size()); for (unsigned idx = 0; idx < src_indexes.size(); idx++) { rez.serialize(src_indexes[idx]); rez.serialize(dst_indexes[idx]); } } rez.serialize(applied); rez.serialize(copy); trace_info.pack_trace_info<false>(rez, applied_events, target); } runtime->send_equivalence_set_remote_copies_across(target, rez); applied_events.insert(applied); copy_events.insert(copy); } // Filter all the remote expressions from the local ones here filter_remote_expressions(local_exprs); return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- RtEvent CopyAcrossAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Report any uninitialized data now that we know the traversal is done if (!!uninitialized) { #ifdef DEBUG_LEGION assert(uninitialized_reported.exists()); #endif RegionNode *src_node = runtime->forest->get_node(src_region); src_node->report_uninitialized_usage(op, src_index, src_usage, uninitialized, uninitialized_reported); } #ifdef DEBUG_LEGION // CopyAcrossAnalysis should have no alt-set tracking because // individual equivalence sets may need to be traversed multiple times assert(alt_sets.empty()); assert(stale_sets.empty()); #endif if (across_aggregator != NULL) { #ifdef DEBUG_LEGION assert(aggregator_guard.exists()); #endif // Trigger the guard event for the aggregator once all the // actual guard events are done. Note that this is safe for // copy across aggregators because unlike other aggregators // they are moving data from one field to another so it is // safe to create entanglements between fields since they are // all going to be subsumed by the same completion event for // the copy-across operation anyway if (!guard_events.empty()) Runtime::trigger_event(aggregator_guard, Runtime::merge_events(guard_events)); else Runtime::trigger_event(aggregator_guard); // Record the event field preconditions for each view // Use the destination expr since we know we we're only actually // issuing copies for that particular expression if (local_exprs.size() > 1) { LegionList<FieldSet<IndexSpaceExpression*> >::aligned field_sets; local_exprs.compute_field_sets(FieldMask(), field_sets); for (LegionList<FieldSet<IndexSpaceExpression*> >::aligned:: const_iterator it = field_sets.begin(); it != field_sets.end(); it++) { IndexSpaceExpression *expr = (it->elements.size() == 1) ? *(it->elements.begin()) : runtime->forest->union_index_spaces(it->elements); if (expr->is_empty()) continue; for (unsigned idx = 0; idx < target_instances.size(); idx++) { const InstanceRef &ref = target_instances[idx]; const ApEvent event = ref.get_ready_event(); if (!event.exists()) continue; const FieldMask &mask = ref.get_valid_fields(); // Convert these to destination fields if necessary const FieldMask overlap = mask & (perfect ? it->set_mask : across_helpers[idx]->convert_src_to_dst(it->set_mask)); if (!overlap) continue; InstanceView *view = target_views[idx]; across_aggregator->record_precondition(view, false/*reading*/, event, overlap, expr); } } } else { FieldMaskSet<IndexSpaceExpression>::const_iterator first = local_exprs.begin(); if (!first->first->is_empty()) { for (unsigned idx = 0; idx < target_instances.size(); idx++) { const InstanceRef &ref = target_instances[idx]; const ApEvent event = ref.get_ready_event(); if (!event.exists()) continue; const FieldMask &mask = ref.get_valid_fields(); // Convert these to destination fields if necessary const FieldMask overlap = mask & (perfect ? first->second : across_helpers[idx]->convert_src_to_dst(first->second)); if (!overlap) continue; InstanceView *view = target_views[idx]; across_aggregator->record_precondition(view, false/*reading*/, event, overlap, first->first); } } } across_aggregator->issue_updates(trace_info, precondition, false/*has src preconditions*/, true/*has dst preconditions*/); // Need to wait before we can get the summary #ifdef NON_AGGRESSIVE_AGGREGATORS if (!across_aggregator->effects_applied.has_triggered()) return across_aggregator->effects_applied; #else if (!across_aggregator->guard_postcondition.has_triggered()) return across_aggregator->guard_postcondition; #endif } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- ApEvent CopyAcrossAnalysis::perform_output(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformOutputArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.effects_event; } if (across_aggregator != NULL) { const ApEvent result = across_aggregator->summarize(trace_info); if (result.exists()) copy_events.insert(result); if (across_aggregator->release_guards(op->runtime, applied_events)) delete across_aggregator; } if (!copy_events.empty()) return Runtime::merge_events(&trace_info, copy_events); else return ApEvent::NO_AP_EVENT; } //-------------------------------------------------------------------------- /*static*/ void CopyAcrossAnalysis::handle_remote_copies_across( Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); FieldMask src_mask; for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); src_mask |= eq_masks[idx]; } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned src_index, dst_index; derez.deserialize(src_index); derez.deserialize(dst_index); RegionUsage src_usage, dst_usage; derez.deserialize(src_usage); derez.deserialize(dst_usage); size_t num_dsts; derez.deserialize(num_dsts); InstanceSet dst_instances(num_dsts); std::vector<InstanceView*> dst_views(num_dsts, NULL); for (unsigned idx = 0; idx < num_dsts; idx++) { RtEvent ready; dst_instances[idx].unpack_reference(runtime, derez, ready); if (ready.exists()) ready_events.insert(ready); DistributedID did; derez.deserialize(did); LogicalView *view = runtime->find_or_request_logical_view(did, ready); dst_views[idx] = static_cast<InstanceView*>(view); if (ready.exists()) ready_events.insert(ready); } LogicalRegion src_handle, dst_handle; derez.deserialize(src_handle); derez.deserialize(dst_handle); PredEvent pred_guard; derez.deserialize(pred_guard); ApEvent precondition; derez.deserialize(precondition); ReductionOpID redop; derez.deserialize(redop); bool perfect; derez.deserialize(perfect); std::vector<unsigned> src_indexes, dst_indexes; if (!perfect) { size_t num_indexes; derez.deserialize(num_indexes); src_indexes.resize(num_indexes); dst_indexes.resize(num_indexes); for (unsigned idx = 0; idx < num_indexes; idx++) { derez.deserialize(src_indexes[idx]); derez.deserialize(dst_indexes[idx]); } } RtUserEvent applied; derez.deserialize(applied); ApUserEvent copy; derez.deserialize(copy); const PhysicalTraceInfo trace_info = PhysicalTraceInfo::unpack_trace_info(derez, runtime, op); std::vector<CopyAcrossHelper*> across_helpers; std::set<RtEvent> deferral_events, applied_events; RegionNode *dst_node = runtime->forest->get_node(dst_handle); IndexSpaceExpression *dst_expr = dst_node->get_index_space_expression(); // Make sure that all our pointers are ready if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); } // This takes ownership of the op and the across helpers CopyAcrossAnalysis *analysis = new CopyAcrossAnalysis(runtime, original_source, previous, op, src_index, dst_index, src_usage, dst_usage, src_handle, dst_handle, dst_instances, dst_views, precondition, pred_guard, redop, src_indexes, dst_indexes, trace_info, perfect); analysis->add_reference(); for (unsigned idx = 0; idx < eq_sets.size(); idx++) { EquivalenceSet *set = eq_sets[idx]; // Check that the index spaces intersect IndexSpaceExpression *overlap = runtime->forest->intersect_index_spaces(set->set_expr, dst_expr); if (overlap->is_empty()) continue; set->issue_across_copies(*analysis, eq_masks[idx], overlap, deferral_events, applied_events); } const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); // Start with the source mask here in case we need to filter which // is all done on the source fields analysis->local_exprs.insert(dst_expr, src_mask); RtEvent remote_ready; if (traversal_done.exists() || analysis->has_remote_sets()) remote_ready = analysis->perform_remote(traversal_done, applied_events); RtEvent updates_ready; // Chain these so we get the local_exprs set correct if (remote_ready.exists() || analysis->has_across_updates()) updates_ready = analysis->perform_updates(remote_ready, applied_events); const ApEvent result = analysis->perform_output(updates_ready, applied_events); Runtime::trigger_event(copy, result); // Now we can trigger our applied event if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); // Clean up our analysis if (analysis->remove_reference()) delete analysis; } //-------------------------------------------------------------------------- /*static*/ std::vector<CopyAcrossHelper*> CopyAcrossAnalysis::create_across_helpers( const FieldMask &src_mask, const FieldMask &dst_mask, const InstanceSet &dst_instances, const std::vector<unsigned> &src_indexes, const std::vector<unsigned> &dst_indexes) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!dst_instances.empty()); #endif std::vector<CopyAcrossHelper*> result(dst_instances.size()); for (unsigned idx = 0; idx < dst_instances.size(); idx++) { result[idx] = new CopyAcrossHelper(src_mask, src_indexes, dst_indexes); InstanceManager *manager = dst_instances[idx].get_manager()->as_instance_manager(); manager->initialize_across_helper(result[idx], dst_mask, src_indexes, dst_indexes); } return result; } ///////////////////////////////////////////////////////////// // Overwrite Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- static inline std::set<LogicalView*> overwrite_insert_helper(LogicalView *v) //-------------------------------------------------------------------------- { std::set<LogicalView*> result; if (v != NULL) result.insert(v); return result; } //-------------------------------------------------------------------------- OverwriteAnalysis::OverwriteAnalysis(Runtime *rt, Operation *o, unsigned idx, const RegionUsage &use, const VersionInfo &info, LogicalView *view, const PhysicalTraceInfo &t_info, const ApEvent pre, const RtEvent guard, const PredEvent pred, const bool track, const bool restriction) : PhysicalAnalysis(rt, o, idx, info, true/*on heap*/), usage(use), views(overwrite_insert_helper(view)), trace_info(t_info), precondition(pre), guard_event(guard), pred_guard(pred), track_effects(track), add_restriction(restriction), output_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- OverwriteAnalysis::OverwriteAnalysis(Runtime *rt, Operation *o, unsigned idx, const RegionUsage &use, const VersionInfo &info,const std::set<LogicalView*> &v, const PhysicalTraceInfo &t_info, const ApEvent pre, const RtEvent guard, const PredEvent pred, const bool track, const bool restriction) : PhysicalAnalysis(rt, o, idx, info, true/*on heap*/), usage(use), views(v), trace_info(t_info), precondition(pre), guard_event(guard), pred_guard(pred), track_effects(track), add_restriction(restriction), output_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- OverwriteAnalysis::OverwriteAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, const RegionUsage &use, const std::set<LogicalView*> &v, const PhysicalTraceInfo &info, const ApEvent pre, const RtEvent guard, const PredEvent pred, const bool track, const bool restriction) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), usage(use), views(v), trace_info(info), precondition(pre), guard_event(guard), pred_guard(pred), track_effects(track), add_restriction(restriction), output_aggregator(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- OverwriteAnalysis::OverwriteAnalysis(const OverwriteAnalysis &rhs) : PhysicalAnalysis(rhs), usage(rhs.usage), views(rhs.views), trace_info(rhs.trace_info), precondition(rhs.precondition), guard_event(rhs.guard_event), pred_guard(rhs.pred_guard), track_effects(rhs.track_effects), add_restriction(rhs.add_restriction) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- OverwriteAnalysis::~OverwriteAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- OverwriteAnalysis& OverwriteAnalysis::operator=(const OverwriteAnalysis &rs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void OverwriteAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->overwrite_set(*this, mask, deferral_events, applied_events, stale_mask, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent OverwriteAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // If there are no sets we're done if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; WrapperReferenceMutator mutator(applied_events); for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpace target = rit->first.first; const RtUserEvent applied = Runtime::create_rt_user_event(); const ApUserEvent effects = track_effects ? Runtime::create_ap_user_event() : ApUserEvent::NO_AP_USER_EVENT; Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); rez.serialize(usage); rez.serialize<size_t>(views.size()); if (!views.empty()) { for (std::set<LogicalView*>::const_iterator it = views.begin(); it != views.end(); it++) { (*it)->add_base_valid_ref(REMOTE_DID_REF, &mutator); rez.serialize((*it)->did); } } trace_info.pack_trace_info<false>(rez, applied_events, target); rez.serialize(pred_guard); rez.serialize(precondition); rez.serialize(guard_event); rez.serialize<bool>(add_restriction); rez.serialize(applied); rez.serialize(effects); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_overwrites(target, rez); applied_events.insert(applied); if (track_effects) effects_events.insert(effects); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- RtEvent OverwriteAnalysis::perform_updates(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformUpdateArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (output_aggregator != NULL) { output_aggregator->issue_updates(trace_info, precondition); // Need to wait before we can get the summary #ifdef NON_AGGRESSIVE_AGGREGATORS if (!output_aggregator->effects_applied.has_triggered()) return output_aggregator->effects_applied; #else if (!output_aggregator->guard_postcondition.has_triggered()) return output_aggregator->guard_postcondition; #endif } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- ApEvent OverwriteAnalysis::perform_output(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformOutputArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.effects_event; } if (output_aggregator != NULL) { const ApEvent result = output_aggregator->summarize(trace_info); if (result.exists() && track_effects) effects_events.insert(result); if (output_aggregator->release_guards(op->runtime, applied_events)) delete output_aggregator; } if (!effects_events.empty()) return Runtime::merge_events(&trace_info, effects_events); else return ApEvent::NO_AP_EVENT; } //-------------------------------------------------------------------------- /*static*/ void OverwriteAnalysis::handle_remote_overwrites( Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); RegionUsage usage; derez.deserialize(usage); std::set<LogicalView*> views; size_t num_views; derez.deserialize(num_views); for (unsigned idx = 0; idx < num_views; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(did, ready); if (ready.exists()) ready_events.insert(ready); views.insert(view); } const PhysicalTraceInfo trace_info = PhysicalTraceInfo::unpack_trace_info(derez, runtime, op); PredEvent pred_guard; derez.deserialize(pred_guard); ApEvent precondition; derez.deserialize(precondition); RtEvent guard_event; derez.deserialize(guard_event); bool add_restriction; derez.deserialize(add_restriction); RtUserEvent applied; derez.deserialize(applied); ApUserEvent effects; derez.deserialize(effects); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); // This takes ownership of the operation OverwriteAnalysis *analysis = new OverwriteAnalysis(runtime, original_source, previous, op, index, version_manager, usage, views, trace_info, precondition, guard_event, pred_guard, effects.exists(), add_restriction); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Make sure that all our pointers are ready RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); RtEvent remote_ready; if (traversal_done.exists() || analysis->has_remote_sets()) remote_ready = analysis->perform_remote(traversal_done, applied_events); RtEvent output_ready; if (traversal_done.exists() || analysis->has_output_updates()) output_ready = analysis->perform_updates(traversal_done, applied_events); const ApEvent result = analysis->perform_output( Runtime::merge_events(remote_ready, output_ready), applied_events); if (effects.exists()) Runtime::trigger_event(effects, result); // Now we can trigger our applied event if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; } ///////////////////////////////////////////////////////////// // Filter Analysis ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- FilterAnalysis::FilterAnalysis(Runtime *rt, Operation *o, unsigned idx, const VersionInfo &info, InstanceView *view, LogicalView *reg_view, const bool remove_restrict) : PhysicalAnalysis(rt, o, idx, info, true/*on heap*/), inst_view(view), registration_view(reg_view), remove_restriction(remove_restrict) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FilterAnalysis::FilterAnalysis(Runtime *rt, AddressSpaceID src, AddressSpaceID prev, Operation *o, unsigned idx, VersionManager *man, InstanceView *view, LogicalView *reg_view, const bool remove_restrict) : PhysicalAnalysis(rt, src, prev, o, idx, man, true/*on heap*/), inst_view(view), registration_view(reg_view), remove_restriction(remove_restrict) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FilterAnalysis::FilterAnalysis(const FilterAnalysis &rhs) : PhysicalAnalysis(rhs), inst_view(rhs.inst_view), registration_view(rhs.registration_view), remove_restriction(rhs.remove_restriction) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- FilterAnalysis::~FilterAnalysis(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FilterAnalysis& FilterAnalysis::operator=(const FilterAnalysis &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void FilterAnalysis::perform_traversal(EquivalenceSet *set, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *stale_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { set->filter_set(*this, mask, deferral_events, applied_events, stale_mask, cached_set, already_deferred); } //-------------------------------------------------------------------------- RtEvent FilterAnalysis::perform_remote(RtEvent perform_precondition, std::set<RtEvent> &applied_events, const bool already_deferred) //-------------------------------------------------------------------------- { if (perform_precondition.exists() && !perform_precondition.has_triggered()) { // Defer this until the precondition is met DeferPerformRemoteArgs args(this); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, perform_precondition); applied_events.insert(args.applied_event); return args.done_event; } // Filter has no perform_updates call so we apply this here if (!stale_sets.empty()) update_stale_equivalence_sets(applied_events); if (remote_sets.empty()) return RtEvent::NO_RT_EVENT; WrapperReferenceMutator mutator(applied_events); for (LegionMap<std::pair<AddressSpaceID,bool>, FieldMaskSet<EquivalenceSet> >::aligned::const_iterator rit = remote_sets.begin(); rit != remote_sets.end(); rit++) { #ifdef DEBUG_LEGION assert(!rit->second.empty()); #endif const AddressSpaceID target = rit->first.first; const RtUserEvent applied = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(original_source); rez.serialize<size_t>(rit->second.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } op->pack_remote_operation(rez, target, applied_events); rez.serialize(index); if (inst_view != NULL) { inst_view->add_base_valid_ref(REMOTE_DID_REF, &mutator); rez.serialize(inst_view->did); } else rez.serialize<DistributedID>(0); if (registration_view != NULL) { registration_view->add_base_valid_ref(REMOTE_DID_REF, &mutator); rez.serialize(registration_view->did); } else rez.serialize<DistributedID>(0); rez.serialize(remove_restriction); rez.serialize(applied); rez.serialize(version_manager); rez.serialize<bool>(rit->first.second); } runtime->send_equivalence_set_remote_filters(target, rez); applied_events.insert(applied); } return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- /*static*/ void FilterAnalysis::handle_remote_filters(Deserializer &derez, Runtime *runtime, AddressSpaceID previous) //-------------------------------------------------------------------------- { DerezCheck z(derez); AddressSpaceID original_source; derez.deserialize(original_source); size_t num_eq_sets; derez.deserialize(num_eq_sets); std::set<RtEvent> ready_events; std::vector<EquivalenceSet*> eq_sets(num_eq_sets, NULL); LegionVector<FieldMask>::aligned eq_masks(num_eq_sets); for (unsigned idx = 0; idx < num_eq_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; eq_sets[idx] = runtime->find_or_request_equivalence_set(did, ready); if (ready.exists()) ready_events.insert(ready); derez.deserialize(eq_masks[idx]); } RemoteOp *op = RemoteOp::unpack_remote_operation(derez, runtime, ready_events); unsigned index; derez.deserialize(index); DistributedID view_did; derez.deserialize(view_did); InstanceView *inst_view = NULL; if (view_did != 0) { RtEvent view_ready; inst_view = static_cast<InstanceView*>( runtime->find_or_request_logical_view(view_did, view_ready)); if (view_ready.exists()) ready_events.insert(view_ready); } derez.deserialize(view_did); LogicalView *registration_view = NULL; if (view_did != 0) { RtEvent view_ready; registration_view = runtime->find_or_request_logical_view(view_did, view_ready); if (view_ready.exists()) ready_events.insert(view_ready); } bool remove_restriction; derez.deserialize(remove_restriction); RtUserEvent applied; derez.deserialize(applied); VersionManager *version_manager; derez.deserialize(version_manager); bool cached_sets; derez.deserialize(cached_sets); // This takes ownership of the remote operation FilterAnalysis *analysis = new FilterAnalysis(runtime, original_source, previous, op, index, version_manager, inst_view, registration_view, remove_restriction); analysis->add_reference(); std::set<RtEvent> deferral_events, applied_events; // Make sure that all our pointers are ready RtEvent ready_event; if (!ready_events.empty()) ready_event = Runtime::merge_events(ready_events); for (unsigned idx = 0; idx < eq_sets.size(); idx++) analysis->traverse(eq_sets[idx], eq_masks[idx], deferral_events, applied_events, cached_sets, ready_event); const RtEvent traversal_done = deferral_events.empty() ? RtEvent::NO_RT_EVENT : Runtime::merge_events(deferral_events); RtEvent remote_ready; if (traversal_done.exists() || analysis->has_remote_sets()) analysis->perform_remote(traversal_done, applied_events); // Now we can trigger our applied event if (!applied_events.empty()) Runtime::trigger_event(applied, Runtime::merge_events(applied_events)); else Runtime::trigger_event(applied); if (analysis->remove_reference()) delete analysis; // Nasty race here: make sure the ready has triggered before // removing the references here because the views are not valid if (ready_event.exists() && !ready_event.has_triggered()) ready_event.wait(); if (inst_view != NULL) inst_view->send_remote_valid_decrement(previous, NULL, applied); if (registration_view != NULL) registration_view->send_remote_valid_decrement(previous, NULL, applied); } ///////////////////////////////////////////////////////////// // Equivalence Set ///////////////////////////////////////////////////////////// // C++ is dumb const VersionID EquivalenceSet::init_version; //-------------------------------------------------------------------------- EquivalenceSet::DisjointPartitionRefinement::DisjointPartitionRefinement( EquivalenceSet *owner, IndexPartNode *p, std::set<RtEvent> &applied_events) : owner_did(owner->did), partition(p), total_child_volume(0), partition_volume(partition->get_union_expression()->get_volume()) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(partition->is_disjoint()); #endif WrapperReferenceMutator mutator(applied_events); partition->add_nested_valid_ref(owner_did, &mutator); } //-------------------------------------------------------------------------- EquivalenceSet::DisjointPartitionRefinement::DisjointPartitionRefinement( const DisjointPartitionRefinement &rhs, std::set<RtEvent> &applied_events) : owner_did(rhs.owner_did), partition(rhs.partition), children(rhs.get_children()), total_child_volume(children.size()), partition_volume(rhs.get_volume()) //-------------------------------------------------------------------------- { WrapperReferenceMutator mutator(applied_events); partition->add_nested_valid_ref(owner_did, &mutator); } //-------------------------------------------------------------------------- EquivalenceSet::DisjointPartitionRefinement::~DisjointPartitionRefinement( void) //-------------------------------------------------------------------------- { if (partition->remove_nested_valid_ref(owner_did)) delete partition; } //-------------------------------------------------------------------------- void EquivalenceSet::DisjointPartitionRefinement::add_child( IndexSpaceNode *node, EquivalenceSet *child) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(children.find(node) == children.end()); #endif children[node] = child; total_child_volume += node->get_volume(); } //-------------------------------------------------------------------------- EquivalenceSet* EquivalenceSet::DisjointPartitionRefinement::find_child( IndexSpaceNode *node) const //-------------------------------------------------------------------------- { std::map<IndexSpaceNode*,EquivalenceSet*>::const_iterator finder = children.find(node); if (finder == children.end()) return NULL; return finder->second; } //-------------------------------------------------------------------------- EquivalenceSet::EquivalenceSet(Runtime *rt, DistributedID did, AddressSpaceID owner, AddressSpace logical, IndexSpaceExpression *expr, IndexSpaceNode *node, bool reg_now) : DistributedCollectable(rt, LEGION_DISTRIBUTED_HELP_ENCODE(did, EQUIVALENCE_SET_DC), owner, reg_now), set_expr(expr), index_space_node(node), logical_owner_space(logical), eq_state(is_logical_owner() ? MAPPING_STATE : INVALID_STATE), subset_exprs(NULL), migration_index(0), sample_count(0), pending_analyses(0) //-------------------------------------------------------------------------- { set_expr->add_expression_reference(); if (index_space_node != NULL) { #ifdef DEBUG_LEGION // These two index space expressions should be equivalent // Although they don't have to be the same // These assertions are pretty expensive so we'll comment them // out for now, but put them back in if you think this invariant // is being violated //assert(runtime->forest->subtract_index_spaces(index_space_node, // set_expr)->is_empty()); //assert(runtime->forest->subtract_index_spaces(set_expr, // index_space_node)->is_empty()); #endif index_space_node->add_nested_resource_ref(did); } #ifdef LEGION_GC log_garbage.info("GC Equivalence Set %lld %d", did, local_space); #endif } //-------------------------------------------------------------------------- EquivalenceSet::EquivalenceSet(const EquivalenceSet &rhs) : DistributedCollectable(rhs), set_expr(NULL), index_space_node(NULL), logical_owner_space(rhs.logical_owner_space) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- EquivalenceSet::~EquivalenceSet(void) //-------------------------------------------------------------------------- { if (set_expr->remove_expression_reference()) delete set_expr; if ((index_space_node != NULL) && index_space_node->remove_nested_resource_ref(did)) delete index_space_node; if (!subsets.empty()) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) if (it->first->remove_nested_resource_ref(did)) delete it->first; subsets.clear(); } if (!valid_instances.empty()) { for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) if (it->first->remove_nested_valid_ref(did)) delete it->first; } if (!reduction_instances.empty()) { for (std::map<unsigned,std::vector<ReductionView*> >::const_iterator rit = reduction_instances.begin(); rit != reduction_instances.end(); rit++) { for (std::vector<ReductionView*>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) if ((*it)->remove_nested_valid_ref(did)) delete (*it); } } if (!restricted_instances.empty()) { for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end(); it++) if (it->first->remove_nested_valid_ref(did)) delete it->first; } if (!disjoint_partition_refinements.empty()) { for (FieldMaskSet<DisjointPartitionRefinement>::const_iterator it = disjoint_partition_refinements.begin(); it != disjoint_partition_refinements.end(); it++) delete it->first; } if (!unrefined_remainders.empty()) { for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = unrefined_remainders.begin(); it != unrefined_remainders.end(); it++) if (it->first->remove_expression_reference()) delete it->first; } if (subset_exprs != NULL) delete subset_exprs; } //-------------------------------------------------------------------------- EquivalenceSet& EquivalenceSet::operator=(const EquivalenceSet &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void EquivalenceSet::trigger_pending_analysis_event(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif Runtime::trigger_event(waiting_event); waiting_event = RtUserEvent::NO_RT_USER_EVENT; } //-------------------------------------------------------------------------- void EquivalenceSet::notify_active(ReferenceMutator *mutator) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- void EquivalenceSet::notify_inactive(ReferenceMutator *mutator) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- void EquivalenceSet::notify_valid(ReferenceMutator *mutator) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- void EquivalenceSet::notify_invalid(ReferenceMutator *mutator) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- AddressSpaceID EquivalenceSet::clone_from(const EquivalenceSet *parent, const FieldMask &clone_mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION // Should be cloning from the parent on it's owner space assert(parent->logical_owner_space == this->local_space); #endif // Take our lock in exclusive mode since we're going to be updating // our data structures AutoLock eq(eq_lock); // Check to see if we're the logical owner, if not then tell // the refinement task where it should send the data if (!is_logical_owner()) return logical_owner_space; // We are the logical owner so clone the meta data // No need for a mutator here since all the views already // have valid references being held by the parent equivalence set if (!parent->valid_instances.empty() && !(clone_mask * parent->valid_instances.get_valid_mask())) { for (FieldMaskSet<LogicalView>::const_iterator it = parent->valid_instances.begin(); it != parent->valid_instances.end(); it++) { const FieldMask overlap = it->second & clone_mask; if (!overlap) continue; if (this->valid_instances.insert(it->first, overlap)) it->first->add_nested_valid_ref(did); } } if (!!parent->reduction_fields) { const FieldMask reduc_overlap = parent->reduction_fields & clone_mask; if (!!reduc_overlap) { this->reduction_fields |= reduc_overlap; int fidx = reduc_overlap.find_first_set(); while (fidx >= 0) { std::vector<ReductionView*> &reduc_insts = this->reduction_instances[fidx]; #ifdef DEBUG_LEGION assert(reduc_insts.empty()); #endif std::map<unsigned,std::vector<ReductionView*> >::const_iterator finder = parent->reduction_instances.find(fidx); #ifdef DEBUG_LEGION assert(finder != parent->reduction_instances.end()); #endif reduc_insts = finder->second; for (unsigned idx = 0; idx < reduc_insts.size(); idx++) reduc_insts[idx]->add_nested_valid_ref(did); fidx = reduc_overlap.find_next_set(fidx+1); } } } if (!parent->restricted_instances.empty() && !(clone_mask * parent->restricted_instances.get_valid_mask())) { this->restricted_fields |= (clone_mask & parent->restricted_fields); for (FieldMaskSet<InstanceView>::const_iterator it = parent->restricted_instances.begin(); it != parent->restricted_instances.end(); it++) { const FieldMask overlap = it->second & clone_mask; if (!overlap) continue; if (this->restricted_instances.insert(it->first, overlap)) it->first->add_nested_valid_ref(did); } } if (!parent->update_guards.empty() && !(clone_mask * parent->update_guards.get_valid_mask())) { for (FieldMaskSet<CopyFillGuard>::const_iterator it = parent->update_guards.begin(); it != parent->update_guards.end(); it++) { const FieldMask overlap = it->second & clone_mask; if (!overlap) continue; // Only want to record this if it isn't in the process of // being pruned out. The record_guard_set method will check // for this return true if it is not being pruned out if (it->first->record_guard_set(this)) update_guards.insert(it->first, overlap); } } // Return our space since we stored the data here return local_space; } //-------------------------------------------------------------------------- void EquivalenceSet::remove_update_guard(CopyFillGuard *guard) //-------------------------------------------------------------------------- { AutoLock eq(eq_lock); // If we're no longer the logical owner then it's because we were // migrated and there should be no guards so we're done if (!is_logical_owner() && update_guards.empty()) return; // We could get here when we're not the logical owner if we've unpacked // ourselves but haven't become the owner yet, in which case we still // need to prune ourselves out of the list FieldMaskSet<CopyFillGuard>::iterator finder = update_guards.find(guard); // It's also possible that the equivalence set is migrated away and // then migrated back before this guard is removed in which case we // won't find it in the update guards and can safely ignore it if (finder == update_guards.end()) return; const bool should_tighten = !!finder->second; update_guards.erase(finder); if (should_tighten) update_guards.tighten_valid_mask(); } //-------------------------------------------------------------------------- void EquivalenceSet::check_for_unrefined_remainder(AutoLock &eq, const FieldMask &mask, AddressSpaceID source) //-------------------------------------------------------------------------- { if (!is_logical_owner()) return; bool first_pass = true; do { // If this isn't the first pass then we need to wait if (!first_pass) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif const RtEvent wait_on = waiting_event; eq.release(); if (!wait_on.has_triggered()) wait_on.wait(); eq.reacquire(); // When we wake up we have to do all the checks again // in case there were fields that weren't refined before // but are (partially or being) refined now #ifdef DEBUG_LEGION // Should never be migrated while we are waiting here assert(is_logical_owner()); #endif } else first_pass = false; // Check for any disjoint pieces if (!disjoint_partition_refinements.empty()) { FieldMask disjoint_overlap = disjoint_partition_refinements.get_valid_mask() & mask; if (!!disjoint_overlap) { std::vector<DisjointPartitionRefinement*> to_delete; for (FieldMaskSet<DisjointPartitionRefinement>::iterator it = disjoint_partition_refinements.begin(); it != disjoint_partition_refinements.end(); it++) { const FieldMask overlap = it->second & disjoint_overlap; if (!overlap) continue; finalize_disjoint_refinement(it->first, overlap); it.filter(overlap); if (!it->second) to_delete.push_back(it->first); disjoint_overlap -= overlap; if (!disjoint_overlap) break; } if (!to_delete.empty()) { for (std::vector<DisjointPartitionRefinement*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { disjoint_partition_refinements.erase(*it); delete (*it); } disjoint_partition_refinements.tighten_valid_mask(); } } } // Check for unrefined remainder pieces too if (!unrefined_remainders.empty()) { FieldMask unrefined_overlap = unrefined_remainders.get_valid_mask() & mask; if (!!unrefined_overlap) { std::vector<IndexSpaceExpression*> to_delete; for (FieldMaskSet<IndexSpaceExpression>::iterator it = unrefined_remainders.begin(); it != unrefined_remainders.end(); it++) { const FieldMask overlap = it->second & unrefined_overlap; if (!overlap) continue; add_pending_refinement(it->first, overlap, NULL/*node*/, source); it.filter(overlap); if (!it->second) to_delete.push_back(it->first); unrefined_overlap -= overlap; if (!unrefined_overlap) break; } if (!to_delete.empty()) { for (std::vector<IndexSpaceExpression*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { unrefined_remainders.erase(*it); if ((*it)->remove_expression_reference()) delete (*it); } unrefined_remainders.tighten_valid_mask(); } } } } // See if we need to wait for any refinements to finish while (!(mask * pending_refinements.get_valid_mask()) || !(mask * refining_fields)); } //-------------------------------------------------------------------------- void EquivalenceSet::refresh_refinement(RayTracer *target, const FieldMask &mask, RtUserEvent refresh_done) //-------------------------------------------------------------------------- { ray_trace_equivalence_sets(target, set_expr, mask, (index_space_node == NULL) ? IndexSpace::NO_SPACE : index_space_node->handle, runtime->address_space, refresh_done); } //-------------------------------------------------------------------------- void EquivalenceSet::ray_trace_equivalence_sets(RayTracer *target, IndexSpaceExpression *expr, FieldMask ray_mask, IndexSpace handle, AddressSpaceID source, RtUserEvent trace_done, RtUserEvent deferral_event) //-------------------------------------------------------------------------- { RegionTreeForest *forest = runtime->forest; #ifdef DEBUG_LEGION assert(expr != NULL); // An expensive sanity check if you want to turn it on //assert(forest->subtract_index_spaces(expr, set_expr)->is_empty()); #endif RtEvent refinement_done; std::set<RtEvent> done_events; FieldMaskSet<EquivalenceSet> to_traverse, pending_to_traverse; std::map<EquivalenceSet*,IndexSpaceExpression*> to_traverse_exprs; { // Try to get the lock, if we don't get it build a continuation AutoTryLock eq(eq_lock); if (!eq.has_lock()) { // We didn't get the lock so build a continuation // We need a name for our completion event that we can use for // the atomic compare and swap below if (!deferral_event.exists()) { // If we haven't already been deferred then we need to // add ourselves to the back of the list of deferrals deferral_event = Runtime::create_rt_user_event(); const RtEvent continuation_pre = chain_deferral_events(deferral_event); DeferRayTraceArgs args(this, target, expr, handle, source, trace_done, deferral_event, ray_mask); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, continuation_pre); } else { // We've already been deferred and our precondition has already // triggered so just launch ourselves again whenever the lock // should be ready to try again DeferRayTraceArgs args(this, target, expr, handle, source, trace_done, deferral_event, ray_mask); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, eq.try_next()); } return; } else if (!is_logical_owner()) { // If we're not the owner node then send the request there Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(target); expr->pack_expression(rez, logical_owner_space); rez.serialize(ray_mask); rez.serialize(handle); rez.serialize(source); rez.serialize(trace_done); } runtime->send_equivalence_set_ray_trace_request(logical_owner_space, rez); // Trigger our deferral event if we had one if (deferral_event.exists()) Runtime::trigger_event(deferral_event); return; } else if ((eq_state == REFINING_STATE) && !(ray_mask * refining_fields)) { if (!transition_event.exists()) transition_event = Runtime::create_rt_user_event(); // If we're refining then we also need to defer this until // the refinements that interfere with us are done DeferRayTraceArgs args(this, target, expr, handle, source, trace_done, deferral_event, ray_mask); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, transition_event); return; } // Handle the special case where we are exactly representing the // index space and we have not been refined yet. This a performance // optimization only and is not required for correctness if (handle.exists() && (index_space_node != NULL) && (index_space_node->handle == handle) && (subsets.empty() || (ray_mask * subsets.get_valid_mask()))) { // Just record this as one of the results if (source != runtime->address_space) { // Not local so we need to send a message Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(ray_mask); rez.serialize(target); rez.serialize(trace_done); } runtime->send_equivalence_set_ray_trace_response(source, rez); } else // Local so we can update this directly { target->record_equivalence_set(this, ray_mask); Runtime::trigger_event(trace_done); } // We're done with our traversal so trigger the deferral event if (deferral_event.exists()) Runtime::trigger_event(deferral_event); return; } // First check to see which fields are in a disjoint refinement // and whether we can continue doing the disjoint refinement if (!disjoint_partition_refinements.empty()) { #ifdef DEBUG_LEGION assert(index_space_node != NULL); #endif FieldMask disjoint_overlap = ray_mask & disjoint_partition_refinements.get_valid_mask(); if (!!disjoint_overlap) { FieldMaskSet<DisjointPartitionRefinement> to_add; std::vector<DisjointPartitionRefinement*> to_delete; // Iterate over the disjoint partition refinements and see // which ones we overlap with for (FieldMaskSet<DisjointPartitionRefinement>::iterator it = disjoint_partition_refinements.begin(); it != disjoint_partition_refinements.end(); it++) { FieldMask overlap = it->second & disjoint_overlap; if (!overlap) continue; // Remove this from the disjoint overlap now in case // we end up removing overlap fields later disjoint_overlap -= overlap; // This is the special case where we are refining // a disjoint partition and all the refinements so far // have been specific instances of a subregion of the // disjoint partition, check to see if that is still true if (handle.exists()) { IndexSpaceNode *node = runtime->forest->get_node(handle); if (node->parent == it->first->partition) { // Record that we're handling all these ray fields // before we go about filtering the fields out of overlap ray_mask -= overlap; // Another sub-region of the disjoint partition // See if we already made the refinement or not EquivalenceSet *child = it->first->find_child(node); // If child is NULL then we haven't made it yet if (child == NULL) { // We want to maintain the invariant that a disjoint // partition refinement represents all the children // being refined for all the same fields, so we need // to split this disjoint partition refinement into // two if there is a difference in fields const FieldMask non_overlap = it->second - overlap; if (!!non_overlap) { // Make a new disjoint partition refinement that is // a copy of the old one up to this point DisjointPartitionRefinement *copy_refinement = new DisjointPartitionRefinement(*(it->first), done_events); to_add.insert(copy_refinement, non_overlap); // Filter the fields down to just the overlap it.filter(non_overlap); } #ifdef DEBUG_LEGION assert(it->second == overlap); #endif // Refine this for all the fields in the disjoint // partition refinement to maintain the invariant that // all these chidren have been refined for all fields child = add_pending_refinement(expr, overlap, node, source); pending_to_traverse.insert(child, overlap); to_traverse_exprs[child] = expr; // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } // Record this child for the future it->first->add_child(node, child); // Check to see if we've finished this disjoint partition if (it->first->is_refined()) { // If we're done with this disjoint pending partition // then we can remove it from the set to_delete.push_back(it->first); // If this wasn't a complete partition then we need to // add the difference into the remainder if (!it->first->partition->is_complete()) { IndexSpaceExpression *diff_expr = runtime->forest->subtract_index_spaces(set_expr, it->first->partition->get_union_expression()); #ifdef DEBUG_LEGION assert((diff_expr != NULL) && !diff_expr->is_empty()); assert(unrefined_remainders.get_valid_mask() * overlap); #endif if (unrefined_remainders.insert(diff_expr, overlap)) diff_expr->add_expression_reference(); } } // Remove these fields from the overlap indicating // that we handled them overlap.clear(); } else { // Figure out which fields have already been refined // and which ones are still pending, issue refinements // for any fields that haven't been refined yet FieldMaskSet<EquivalenceSet>::iterator finder = subsets.find(child); if (finder != subsets.end()) { const FieldMask eq_valid = overlap & finder->second; if (!!eq_valid) { to_traverse.insert(child, eq_valid); to_traverse_exprs[child] = expr; overlap -= eq_valid; } } // If we couldn't find it in the already valid set, check // also in the pending refinements if (!!overlap) { finder = pending_refinements.find(child); if (finder != pending_refinements.end()) { #ifdef DEBUG_LEGION // All overlap fields should be dominated assert(!(overlap - finder->second)); #endif pending_to_traverse.insert(child, overlap); to_traverse_exprs[child] = expr; overlap.clear(); // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } } } #ifdef DEBUG_LEGION // Should have handled all the fields at this point assert(!overlap); #endif } } } // If we get here and we still haven't done a disjoint // refinement then we can no longer allow it to continue if (!!overlap) { finalize_disjoint_refinement(it->first, overlap); it.filter(overlap); if (!it->second) to_delete.push_back(it->first); } // If we handled our disjoint overlap fields then we're done if (!disjoint_overlap) break; } if (!to_delete.empty()) { for (std::vector<DisjointPartitionRefinement*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { disjoint_partition_refinements.erase(*it); delete (*it); } disjoint_partition_refinements.tighten_valid_mask(); } if (!to_add.empty()) { if (!disjoint_partition_refinements.empty()) for (FieldMaskSet<DisjointPartitionRefinement>::const_iterator it = to_add.begin(); it != to_add.end(); it++) disjoint_partition_refinements.insert(it->first, it->second); else disjoint_partition_refinements.swap(to_add); } } } // Next handle any fields which are refined or pending refined if (!!ray_mask) { FieldMaskSet<IndexSpaceExpression> intersections; if (!pending_refinements.empty() && !(ray_mask * pending_refinements.get_valid_mask())) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = pending_refinements.begin(); it != pending_refinements.end(); it++) { const FieldMask overlap = it->second & ray_mask; if (!overlap) continue; // Next check for expression overlap IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(expr, it->first->set_expr); if (expr_overlap->is_empty()) continue; pending_to_traverse.insert(it->first, overlap); to_traverse_exprs[it->first] = expr_overlap; intersections.insert(expr_overlap, overlap); // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } } } if (!subsets.empty() && !(ray_mask * subsets.get_valid_mask())) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & ray_mask; if (!overlap) continue; // Next check for expression overlap IndexSpaceExpression *expr_overlap = forest->intersect_index_spaces(expr, it->first->set_expr); if (expr_overlap->is_empty()) continue; to_traverse.insert(it->first, overlap); to_traverse_exprs[it->first] = expr_overlap; intersections.insert(expr_overlap, overlap); } } // For all our intersections, compute the remainders after the // overlap and if they exist then perform refinements for them if (!intersections.empty()) { if (intersections.size() > 1) { // Sort these into field mask sets LegionList<FieldSet<IndexSpaceExpression*> >::aligned field_sets; intersections.compute_field_sets(FieldMask(), field_sets); for (LegionList<FieldSet<IndexSpaceExpression*> >::aligned:: iterator it = field_sets.begin(); it != field_sets.end(); it++) { IndexSpaceExpression *diff = forest->subtract_index_spaces(expr, forest->union_index_spaces(it->elements)); if (!diff->is_empty()) { EquivalenceSet *child = add_pending_refinement(diff, it->set_mask, NULL, source); pending_to_traverse.insert(child, it->set_mask); to_traverse_exprs[child] = diff; // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } // We need to subtract this off any unrefined remainders // or add the difference of it with the original set // to the set of unrefined remainders filter_unrefined_remainders(it->set_mask, diff); if (!!it->set_mask) { IndexSpaceExpression *remainder = forest->subtract_index_spaces(set_expr, diff); if (!remainder->is_empty()) { #ifdef DEBUG_LEGION assert(disjoint_partition_refinements.get_valid_mask() * it->set_mask); assert(unrefined_remainders.get_valid_mask() * it->set_mask); #endif if (unrefined_remainders.insert(remainder, it->set_mask)) remainder->add_expression_reference(); } } } } } else { // Easy case with just one intersection FieldMaskSet<IndexSpaceExpression>::const_iterator first = intersections.begin(); IndexSpaceExpression *diff = forest->subtract_index_spaces(expr, first->first); if (!diff->is_empty()) { EquivalenceSet *child = add_pending_refinement(diff, first->second, NULL, source); pending_to_traverse.insert(child, first->second); to_traverse_exprs[child] = diff; // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } // Subtract from any unrefined remainders FieldMask to_filter = first->second; filter_unrefined_remainders(to_filter, diff); if (!!to_filter) { IndexSpaceExpression *remainder = forest->subtract_index_spaces(set_expr, diff); if (!remainder->is_empty()) { #ifdef DEBUG_LEGION assert(disjoint_partition_refinements.get_valid_mask() * to_filter); assert(unrefined_remainders.get_valid_mask() * to_filter); #endif if (unrefined_remainders.insert(remainder, to_filter)) remainder->add_expression_reference(); } } } } // These fields are all remove from the ray mask // since they have now been handled ray_mask -= intersections.get_valid_mask(); } } // If we still have fields left, see if we need a refinement if (!!ray_mask && (set_expr->expr_id != expr->expr_id) && (expr->get_volume() < set_expr->get_volume())) { #ifdef DEBUG_LEGION IndexSpaceExpression *diff = forest->subtract_index_spaces(set_expr, expr); assert(!diff->is_empty()); #endif // We're doing a refinement for the first time, see if // we can make this a disjoint partition refeinement if ((index_space_node != NULL) && handle.exists()) { FieldMask disjoint_mask = ray_mask; // We can't start a new disjoint mask for anything that // has already been partially refined if (!unrefined_remainders.empty()) disjoint_mask -= unrefined_remainders.get_valid_mask(); if (!!disjoint_mask) { IndexSpaceNode *node = runtime->forest->get_node(handle); // We can start a disjoint complete partition if there // is exactly one partition between the parent index // space for the equivalence class and the child index // space for the subset and the partition is disjoint if ((node->parent != NULL) && (node->parent->parent == index_space_node) && node->parent->is_disjoint()) { DisjointPartitionRefinement *dis = new DisjointPartitionRefinement(this, node->parent, done_events); EquivalenceSet *child = add_pending_refinement(expr, disjoint_mask, node, source); pending_to_traverse.insert(child, disjoint_mask); to_traverse_exprs[child] = expr; // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } // Save this for the future dis->add_child(node, child); #ifdef DEBUG_LEGION assert(disjoint_mask * unrefined_remainders.get_valid_mask()); #endif disjoint_partition_refinements.insert(dis, disjoint_mask); ray_mask -= disjoint_mask; } } } // If we didn't make a disjoint partition refeinement // then we need to do the normal kind of refinement if (!!ray_mask) { // Time to refine this since we only need a subset of it EquivalenceSet *child = add_pending_refinement(expr, ray_mask, NULL, source); pending_to_traverse.insert(child, ray_mask); to_traverse_exprs[child] = expr; // If this is a pending refinement then we'll need to // wait for it before traversing farther if (!refinement_done.exists()) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif refinement_done = waiting_event; } // Subtract from any unrefined remainders filter_unrefined_remainders(ray_mask, expr); if (!!ray_mask) { #ifdef DEBUG_LEGION assert(disjoint_partition_refinements.get_valid_mask() * ray_mask); assert(unrefined_remainders.get_valid_mask() * ray_mask); #else IndexSpaceExpression *diff = forest->subtract_index_spaces(set_expr, expr); #endif if (unrefined_remainders.insert(diff, ray_mask)) diff->add_expression_reference(); ray_mask.clear(); } } } // Otherwise we can fall through because this means the // expressions are equivalent } // We've done our traversal, so if we had a deferral even we can // trigger it now to signal to the next user that they can start if (deferral_event.exists()) Runtime::trigger_event(deferral_event); // Any fields which are still valid should be recorded if (!!ray_mask) { // Not local so we need to send a message if (source != runtime->address_space) { // If there's nothing to do after this we can use // the trace_done event directly if (to_traverse.empty() && pending_to_traverse.empty()) { Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(ray_mask); rez.serialize(target); rez.serialize(trace_done); } runtime->send_equivalence_set_ray_trace_response(source, rez); return; } else { RtUserEvent done = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(ray_mask); rez.serialize(target); rez.serialize(done); } runtime->send_equivalence_set_ray_trace_response(source, rez); done_events.insert(done); } } else target->record_equivalence_set(this, ray_mask); } // Traverse anything we can now before we have to wait if (!to_traverse.empty()) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) { RtUserEvent done = Runtime::create_rt_user_event(); std::map<EquivalenceSet*,IndexSpaceExpression*>::const_iterator finder = to_traverse_exprs.find(it->first); #ifdef DEBUG_LEGION assert(finder != to_traverse_exprs.end()); #endif const IndexSpace subset_handle = (handle.exists() && (finder->second->get_volume() == expr->get_volume())) ? handle : IndexSpace::NO_SPACE; it->first->ray_trace_equivalence_sets(target, finder->second, it->second, subset_handle, source, done); done_events.insert(done); } // Clear these since we are done doing them to_traverse.clear(); } // Get the actual equivalence sets for any refinements we needed to // wait for because they weren't ready earlier if (!pending_to_traverse.empty()) { // If we have a refinement to do then we need to wait for that // to be done before we continue our traversal if (refinement_done.exists() && !refinement_done.has_triggered()) { // Defer this until the refinements are done FieldMaskSet<EquivalenceSet> *copy_traverse = new FieldMaskSet<EquivalenceSet>(); copy_traverse->swap(pending_to_traverse); std::map<EquivalenceSet*,IndexSpaceExpression*> *copy_exprs = new std::map<EquivalenceSet*,IndexSpaceExpression*>(); copy_exprs->swap(to_traverse_exprs); const RtUserEvent done = Runtime::create_rt_user_event(); DeferRayTraceFinishArgs args(target, source, copy_traverse, copy_exprs, expr->get_volume(), handle, done); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, refinement_done); done_events.insert(done); } else { for (FieldMaskSet<EquivalenceSet>::const_iterator it = pending_to_traverse.begin(); it != pending_to_traverse.end(); it++) { RtUserEvent done = Runtime::create_rt_user_event(); std::map<EquivalenceSet*,IndexSpaceExpression*>::const_iterator finder = to_traverse_exprs.find(it->first); #ifdef DEBUG_LEGION assert(finder != to_traverse_exprs.end()); #endif const IndexSpace subset_handle = (handle.exists() && (finder->second->get_volume() == expr->get_volume())) ? handle : IndexSpace::NO_SPACE; it->first->ray_trace_equivalence_sets(target, finder->second, it->second, subset_handle, source, done); done_events.insert(done); } } } if (!done_events.empty()) Runtime::trigger_event(trace_done, Runtime::merge_events(done_events)); else Runtime::trigger_event(trace_done); } //-------------------------------------------------------------------------- void EquivalenceSet::pack_state(Serializer &rez, const FieldMask &pack_mask) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(is_logical_owner()); #endif // Pack the valid instances rez.serialize<size_t>(valid_instances.size()); if (!valid_instances.empty()) { for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask overlap = it->second & pack_mask; if (!!overlap) { rez.serialize(it->first->did); rez.serialize(overlap); } else rez.serialize<DistributedID>(0); } } // Pack the reduction instances if (!!reduction_fields) { const FieldMask reduc_mask = reduction_fields & pack_mask; if (!!reduc_mask) { rez.serialize<size_t>(reduc_mask.pop_count()); int fidx = reduc_mask.find_first_set(); while (fidx >= 0) { rez.serialize<unsigned>(fidx); std::map<unsigned,std::vector<ReductionView*> >::const_iterator finder = reduction_instances.find(fidx); #ifdef DEBUG_LEGION assert(finder != reduction_instances.end()); #endif rez.serialize<size_t>(finder->second.size()); for (std::vector<ReductionView*>::const_iterator it = finder->second.begin(); it != finder->second.end(); it++) rez.serialize((*it)->did); fidx = reduc_mask.find_next_set(fidx+1); } } else rez.serialize<size_t>(0); } else rez.serialize<size_t>(0); // Pack the restricted instances if (!!restricted_fields) { const FieldMask restr_mask = restricted_fields & pack_mask; if (!!restr_mask) { rez.serialize<size_t>(restricted_instances.size()); for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end(); it++) { const FieldMask overlap = pack_mask & it->second; if (!!overlap) { rez.serialize(it->first->did); rez.serialize(overlap); } else rez.serialize<DistributedID>(0); } } else rez.serialize<size_t>(0); } else rez.serialize<size_t>(0); // Pack the version numbers rez.serialize<size_t>(version_numbers.size()); if (!version_numbers.empty()) { for (LegionMap<VersionID,FieldMask>::aligned::const_iterator it = version_numbers.begin(); it != version_numbers.end(); it++) { const FieldMask overlap = pack_mask & it->second; if (!!overlap) { rez.serialize(it->first); rez.serialize(overlap); } else rez.serialize<VersionID>(0); } } // Pack the update guards if (!update_guards.empty() && !(pack_mask * update_guards.get_valid_mask())) { FieldMaskSet<CopyFillGuard> remote_guards; for (FieldMaskSet<CopyFillGuard>::const_iterator it = update_guards.begin(); it != update_guards.end(); it++) { const FieldMask overlap = pack_mask & it->second; if (!overlap) continue; remote_guards.insert(it->first, overlap); } rez.serialize<size_t>(remote_guards.size()); for (FieldMaskSet<CopyFillGuard>::const_iterator it = remote_guards.begin(); it != remote_guards.end(); it++) { it->first->pack_guard(rez); rez.serialize(it->second); } } else rez.serialize<size_t>(0); } //-------------------------------------------------------------------------- void EquivalenceSet::unpack_state(Deserializer &derez) //-------------------------------------------------------------------------- { RtUserEvent done_event; derez.deserialize(done_event); bool initial_refinement; derez.deserialize(initial_refinement); // Do a quick test to see if we're still the owner, if not // then we can just forward this on immediately { AutoLock eq(eq_lock,1,false/*exlcusive*/); // Check to see if we're the initial refinement, if not // then we need to keep forwarding this on to wherever the // owner is, otherwise we can handle it now and make ourselves // the owner once we are ready if (!is_logical_owner() && !initial_refinement) { Serializer rez; // No RezCheck because of forwarding rez.serialize(did); rez.serialize(done_event); rez.serialize<bool>(false); // initial refinement // Just move the bytes over to the serializer and return const size_t bytes = derez.get_remaining_bytes(); rez.serialize(derez.get_current_pointer(), bytes); runtime->send_equivalence_set_remote_refinement( logical_owner_space, rez); // Keep the deserializer happy derez.advance_pointer(bytes); return; } } // Keep track of ready events std::set<RtEvent> ready_events; // Unpack into local data structures which we'll update later FieldMaskSet<LogicalView> new_valid; size_t num_valid_insts; derez.deserialize(num_valid_insts); for (unsigned idx = 0; idx < num_valid_insts; idx++) { DistributedID valid_did; derez.deserialize(valid_did); if (valid_did == 0) continue; RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(valid_did, ready); if (ready.exists()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); new_valid.insert(view, mask); } size_t num_reduc_fields; derez.deserialize(num_reduc_fields); std::map<unsigned,std::vector<ReductionView*> > new_reductions; for (unsigned idx1 = 0; idx1 < num_reduc_fields; idx1++) { unsigned fidx; derez.deserialize(fidx); std::vector<ReductionView*> &new_views = new_reductions[fidx]; size_t num_reduc_insts; derez.deserialize(num_reduc_insts); new_views.resize(num_reduc_insts); for (unsigned idx2 = 0; idx2 < num_reduc_insts; idx2++) { DistributedID reduc_did; derez.deserialize(reduc_did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(reduc_did, ready); new_views[idx2] = static_cast<ReductionView*>(view); if (ready.exists()) ready_events.insert(ready); } } size_t num_restrict_insts; derez.deserialize(num_restrict_insts); FieldMaskSet<InstanceView> new_restrictions; if (num_restrict_insts > 0) { for (unsigned idx = 0; idx < num_restrict_insts; idx++) { DistributedID valid_did; derez.deserialize(valid_did); if (valid_did == 0) continue; RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(valid_did, ready); if (ready.exists()) ready_events.insert(ready); InstanceView *inst_view = static_cast<InstanceView*>(view); FieldMask mask; derez.deserialize(mask); new_restrictions.insert(inst_view, mask); } } size_t num_versions; derez.deserialize(num_versions); LegionMap<VersionID,FieldMask>::aligned new_versions; for (unsigned idx = 0; idx < num_versions; idx++) { VersionID vid; derez.deserialize(vid); if (vid == 0) continue; derez.deserialize(new_versions[vid]); } size_t num_guards; derez.deserialize(num_guards); if (num_guards > 0) { // Need to hold the lock here to prevent copy fill guard // deletions from removing this before we've registered it AutoLock eq(eq_lock); for (unsigned idx = 0; idx < num_guards; idx++) { CopyFillGuard *guard = CopyFillGuard::unpack_guard(derez, runtime, this); FieldMask guard_mask; derez.deserialize(guard_mask); if (guard != NULL) update_guards.insert(guard, guard_mask); } } // If we have events to wait for then we need to defer this if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) { // Defer the merge or forward until the views are ready FieldMaskSet<LogicalView> *view_copy = new FieldMaskSet<LogicalView>(); view_copy->swap(new_valid); std::map<unsigned,std::vector<ReductionView*> > *reduc_copy = new std::map<unsigned,std::vector<ReductionView*> >(); reduc_copy->swap(new_reductions); FieldMaskSet<InstanceView> *restrict_copy = new FieldMaskSet<InstanceView>(); restrict_copy->swap(new_restrictions); LegionMap<VersionID,FieldMask>::aligned *version_copy = new LegionMap<VersionID,FieldMask>::aligned(); version_copy->swap(new_versions); DeferMergeOrForwardArgs args(this, initial_refinement, view_copy, reduc_copy, restrict_copy, version_copy, done_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, wait_on); return; } // Otherwise fall through to do the merge or forward now } // Either merge or forward the update merge_or_forward(done_event, initial_refinement, new_valid, new_reductions, new_restrictions, new_versions); } //-------------------------------------------------------------------------- void EquivalenceSet::merge_or_forward(const RtUserEvent done_event, bool initial_refinement, const FieldMaskSet<LogicalView> &new_views, const std::map<unsigned,std::vector<ReductionView*> > &new_reductions, const FieldMaskSet<InstanceView> &new_restrictions, const LegionMap<VersionID,FieldMask>::aligned &new_versions) //-------------------------------------------------------------------------- { AutoLock eq(eq_lock); if (is_logical_owner() || initial_refinement) { // We're the owner so we can do the merge LocalReferenceMutator mutator; for (FieldMaskSet<LogicalView>::const_iterator it = new_views.begin(); it != new_views.end(); it++) if (valid_instances.insert(it->first, it->second)) it->first->add_nested_valid_ref(did, &mutator); for (std::map<unsigned,std::vector<ReductionView*> >::const_iterator rit = new_reductions.begin(); rit != new_reductions.end(); rit++) { reduction_fields.set_bit(rit->first); std::vector<ReductionView*> &reduc_insts = reduction_instances[rit->first]; #ifdef DEBUG_LEGION assert(reduc_insts.empty()); #endif for (std::vector<ReductionView*>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { reduc_insts.push_back(*it); (*it)->add_nested_valid_ref(did, &mutator); } } for (FieldMaskSet<InstanceView>::const_iterator it = new_restrictions.begin(); it != new_restrictions.end(); it++) { restricted_fields |= it->second; if (restricted_instances.insert(it->first, it->second)) it->first->add_nested_valid_ref(did, &mutator); } for (LegionMap<VersionID,FieldMask>::aligned::const_iterator it = new_versions.begin(); it != new_versions.end(); it++) { LegionMap<VersionID,FieldMask>::aligned::iterator finder = version_numbers.find(it->first); if (finder == version_numbers.end()) version_numbers.insert(*it); else finder->second |= it->second; } Runtime::trigger_event(done_event, mutator.get_done_event()); // See if we need to make this the owner now if (!is_logical_owner()) { logical_owner_space = local_space; eq_state = MAPPING_STATE; } } else { // We're not the owner so we need to forward this on Serializer rez; // No RezCheck in case of forwarding rez.serialize(did); rez.serialize(done_event); rez.serialize<bool>(false); // initial refinement rez.serialize(new_views.size()); for (FieldMaskSet<LogicalView>::const_iterator it = new_views.begin(); it != new_views.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize<size_t>(new_reductions.size()); for (std::map<unsigned,std::vector<ReductionView*> >::const_iterator rit = new_reductions.begin(); rit != new_reductions.end(); rit++) { rez.serialize(rit->first); rez.serialize(rit->second.size()); for (std::vector<ReductionView*>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) rez.serialize((*it)->did); } rez.serialize(new_restrictions.size()); for (FieldMaskSet<InstanceView>::const_iterator it = new_restrictions.begin(); it != new_restrictions.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } rez.serialize(new_versions.size()); for (LegionMap<VersionID,FieldMask>::aligned::const_iterator it = new_versions.begin(); it != new_versions.end(); it++) { rez.serialize(it->first); rez.serialize(it->second); } runtime->send_equivalence_set_remote_refinement( logical_owner_space, rez); } } //-------------------------------------------------------------------------- void EquivalenceSet::pack_migration(Serializer &rez, RtEvent done_migration) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(pending_refinements.empty()); #endif std::map<LogicalView*,unsigned> *late_references = NULL; // Pack the valid instances rez.serialize<size_t>(valid_instances.size()); if (!valid_instances.empty()) { for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); if (late_references == NULL) late_references = new std::map<LogicalView*,unsigned>(); (*late_references)[it->first] = 1; } valid_instances.clear(); } // Pack the reduction instances rez.serialize<size_t>(reduction_instances.size()); if (!reduction_instances.empty()) { for (std::map<unsigned,std::vector<ReductionView*> >::const_iterator rit = reduction_instances.begin(); rit != reduction_instances.end(); rit++) { rez.serialize(rit->first); rez.serialize<size_t>(rit->second.size()); for (std::vector<ReductionView*>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) { rez.serialize((*it)->did); if (late_references == NULL) late_references = new std::map<LogicalView*,unsigned>(); (*late_references)[*it] = 1; } } reduction_instances.clear(); reduction_fields.clear(); } // Pack the restricted instances rez.serialize<size_t>(restricted_instances.size()); if (!restricted_instances.empty()) { rez.serialize(restricted_fields); for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); if (late_references == NULL) late_references = new std::map<LogicalView*,unsigned>(); std::map<LogicalView*,unsigned>::iterator finder = late_references->find(it->first); if (finder == late_references->end()) (*late_references)[it->first] = 1; else finder->second += 1; } restricted_instances.clear(); restricted_fields.clear(); } // Pack the version numbers rez.serialize<size_t>(version_numbers.size()); if (!version_numbers.empty()) { for (LegionMap<VersionID,FieldMask>::aligned::const_iterator it = version_numbers.begin(); it != version_numbers.end(); it++) { rez.serialize(it->first); rez.serialize(it->second); } version_numbers.clear(); } // Pack the update guards rez.serialize<size_t>(update_guards.size()); if (!update_guards.empty()) { for (FieldMaskSet<CopyFillGuard>::const_iterator it = update_guards.begin(); it != update_guards.end(); it++) { it->first->pack_guard(rez); rez.serialize(it->second); } update_guards.clear(); } // Pack subsets // We're only allowed to keep the complete subsets on this node // so we need to filter anything that isn't fully refined // We still keep references to the equivalence sets though // so that they aren't deleted FieldMask incomplete_refinements; if (!unrefined_remainders.empty()) incomplete_refinements = unrefined_remainders.get_valid_mask(); if (!disjoint_partition_refinements.empty()) incomplete_refinements |= disjoint_partition_refinements.get_valid_mask(); rez.serialize<size_t>(subsets.size()); for (FieldMaskSet<EquivalenceSet>::iterator it = subsets.begin(); it != subsets.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); if (!!incomplete_refinements) it.filter(incomplete_refinements); } // Tighten the valid mask for future analyses if (!!incomplete_refinements) subsets.tighten_valid_mask(); // No need to clear subsets since we can still maintain a copy of it // Pack remote subsets rez.serialize<size_t>(remote_subsets.size()); if (!remote_subsets.empty()) { for (std::set<AddressSpaceID>::const_iterator it = remote_subsets.begin(); it != remote_subsets.end(); it++) rez.serialize(*it); remote_subsets.clear(); } // Pack unrefined remainders rez.serialize<size_t>(unrefined_remainders.size()); if (!unrefined_remainders.empty()) { std::vector<IndexSpaceExpression*> *references = new std::vector<IndexSpaceExpression*>(); references->reserve(unrefined_remainders.size()); for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = unrefined_remainders.begin(); it != unrefined_remainders.end(); it++) { it->first->pack_expression(rez, logical_owner_space); rez.serialize(it->second); references->push_back(it->first); } unrefined_remainders.clear(); // Defer removing the references on these expressions until // the migration has been done DeferRemoveRefArgs args(references); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_WORK_PRIORITY, done_migration); } // Pack disjoint partition refinements rez.serialize<size_t>(disjoint_partition_refinements.size()); if (!disjoint_partition_refinements.empty()) { for (FieldMaskSet<DisjointPartitionRefinement>::const_iterator it = disjoint_partition_refinements.begin(); it != disjoint_partition_refinements.end(); it++) { rez.serialize(it->first->partition->handle); const std::map<IndexSpaceNode*,EquivalenceSet*> &children = it->first->get_children(); rez.serialize<size_t>(children.size()); for (std::map<IndexSpaceNode*,EquivalenceSet*>::const_iterator cit = children.begin(); cit != children.end(); cit++) { rez.serialize(cit->first->handle); rez.serialize(cit->second->did); } rez.serialize(it->second); delete it->first; } disjoint_partition_refinements.clear(); } // Pack the user samples and counts rez.serialize(migration_index); for (unsigned idx = 0; idx < MIGRATION_EPOCHS; idx++) { std::vector<std::pair<AddressSpaceID,unsigned> > &samples = user_samples[idx]; rez.serialize<size_t>(samples.size()); for (std::vector<std::pair<AddressSpaceID,unsigned> >::const_iterator it = samples.begin(); it != samples.end(); it++) { rez.serialize(it->first); rez.serialize(it->second); } samples.clear(); } if (late_references != NULL) { // Launch a task to remove the references once the migration is done RemoteRefTaskArgs args(this->did, RtUserEvent::NO_RT_USER_EVENT, false/*add*/, late_references); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_WORK_PRIORITY, done_migration); } } //-------------------------------------------------------------------------- void EquivalenceSet::unpack_migration(Deserializer &derez, AddressSpaceID source, RtUserEvent done_event) //-------------------------------------------------------------------------- { // All the preconditions before we can make this the owner std::set<RtEvent> owner_preconditions; AutoLock eq(eq_lock); #ifdef DEBUG_LEGION assert(!is_logical_owner()); assert(valid_instances.empty()); assert(reduction_instances.empty()); assert(restricted_instances.empty()); assert(version_numbers.empty()); assert(update_guards.empty()); assert(pending_refinements.empty()); assert(remote_subsets.empty()); assert(unrefined_remainders.empty()); assert(disjoint_partition_refinements.empty()); #endif size_t num_valid_insts; derez.deserialize(num_valid_insts); for (unsigned idx = 0; idx < num_valid_insts; idx++) { DistributedID valid_did; derez.deserialize(valid_did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(valid_did, ready); FieldMask mask; derez.deserialize(mask); valid_instances.insert(view, mask); if (ready.exists()) owner_preconditions.insert(ready); } size_t num_reduc_fields; derez.deserialize(num_reduc_fields); for (unsigned idx1 = 0; idx1 < num_reduc_fields; idx1++) { unsigned fidx; derez.deserialize(fidx); reduction_fields.set_bit(fidx); size_t num_reduc_insts; derez.deserialize(num_reduc_insts); std::vector<ReductionView*> &reduc_views = reduction_instances[fidx]; for (unsigned idx2 = 0; idx2 < num_reduc_insts; idx2++) { DistributedID reduc_did; derez.deserialize(reduc_did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(reduc_did, ready); ReductionView *reduc_view = static_cast<ReductionView*>(view); reduc_views.push_back(reduc_view); if (ready.exists()) owner_preconditions.insert(ready); } } size_t num_restrict_insts; derez.deserialize(num_restrict_insts); if (num_restrict_insts > 0) { derez.deserialize(restricted_fields); for (unsigned idx = 0; idx < num_restrict_insts; idx++) { DistributedID valid_did; derez.deserialize(valid_did); RtEvent ready; LogicalView *view = runtime->find_or_request_logical_view(valid_did, ready); InstanceView *inst_view = static_cast<InstanceView*>(view); FieldMask mask; derez.deserialize(mask); restricted_instances.insert(inst_view, mask); if (ready.exists()) owner_preconditions.insert(ready); } } size_t num_versions; derez.deserialize(num_versions); for (unsigned idx = 0; idx < num_versions; idx++) { VersionID vid; derez.deserialize(vid); derez.deserialize(version_numbers[vid]); } size_t num_guards; derez.deserialize(num_guards); for (unsigned idx = 0; idx < num_guards; idx++) { CopyFillGuard *guard = CopyFillGuard::unpack_guard(derez, runtime,this); FieldMask guard_mask; derez.deserialize(guard_mask); if (guard != NULL) update_guards.insert(guard, guard_mask); } FieldMaskSet<EquivalenceSet> new_subsets; size_t num_subsets; derez.deserialize(num_subsets); for (unsigned idx = 0; idx < num_subsets; idx++) { DistributedID subset_did; derez.deserialize(subset_did); RtEvent ready; EquivalenceSet *subset = runtime->find_or_request_equivalence_set(subset_did, ready); if (ready.exists()) owner_preconditions.insert(ready); FieldMask subset_mask; derez.deserialize(subset_mask); new_subsets.insert(subset, subset_mask); } size_t num_remote_subsets; derez.deserialize(num_remote_subsets); for (unsigned idx = 0; idx < num_remote_subsets; idx++) { AddressSpaceID remote; derez.deserialize(remote); remote_subsets.insert(remote); } size_t num_unrefined_remainders; derez.deserialize(num_unrefined_remainders); for (unsigned idx = 0; idx < num_unrefined_remainders; idx++) { IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez,runtime->forest,source); FieldMask mask; derez.deserialize(mask); if (unrefined_remainders.insert(expr, mask)) expr->add_expression_reference(); } size_t num_disjoint_refinements; derez.deserialize(num_disjoint_refinements); for (unsigned idx1 = 0; idx1 < num_disjoint_refinements; idx1++) { IndexPartition handle; derez.deserialize(handle); IndexPartNode *part = runtime->forest->get_node(handle); DisjointPartitionRefinement *dis = new DisjointPartitionRefinement(this, part, owner_preconditions); size_t num_children; derez.deserialize(num_children); for (unsigned idx2 = 0; idx2 < num_children; idx2++) { IndexSpace child; derez.deserialize(child); IndexSpaceNode *node = runtime->forest->get_node(child); DistributedID child_did; derez.deserialize(child_did); RtEvent ready; dis->add_child(node, runtime->find_or_request_equivalence_set(child_did, ready)); if (ready.exists()) owner_preconditions.insert(ready); } FieldMask mask; derez.deserialize(mask); disjoint_partition_refinements.insert(dis, mask); } derez.deserialize(migration_index); for (unsigned idx1 = 0; idx1 < MIGRATION_EPOCHS; idx1++) { size_t num_samples; derez.deserialize(num_samples); if (num_samples > 0) { std::vector<std::pair<AddressSpaceID,unsigned> > &samples = user_samples[idx1]; samples.resize(num_samples); for (unsigned idx2 = 0; idx2 < num_samples; idx2++) { derez.deserialize(samples[idx2].first); derez.deserialize(samples[idx2].second); } } } // If there are any pending anayses we need to wait for them to finish if (pending_analyses > 0) { #ifdef DEBUG_LEGION assert(!waiting_event.exists()); #endif waiting_event = Runtime::create_rt_user_event(); owner_preconditions.insert(waiting_event); } if (!owner_preconditions.empty()) { const RtEvent pre = Runtime::merge_events(owner_preconditions); if (pre.exists() && !pre.has_triggered()) { // We need to defer this until later FieldMaskSet<EquivalenceSet> *owner_subsets = new FieldMaskSet<EquivalenceSet>(); owner_subsets->swap(new_subsets); // Defer the call to make this the owner until the event triggers DeferMakeOwnerArgs args(this, owner_subsets, done_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, pre); return; } } // If we fall through then we get to do the add now make_owner(&new_subsets, done_event, false/*need lock*/); } //-------------------------------------------------------------------------- bool EquivalenceSet::make_owner(FieldMaskSet<EquivalenceSet> *new_subsets, RtUserEvent done_event, bool need_lock) //-------------------------------------------------------------------------- { if (need_lock) { AutoLock eq(eq_lock); return make_owner(new_subsets, done_event, false/*need lock*/); } #ifdef DEBUG_LEGION assert(!is_logical_owner()); #endif // See if we need to defer this because there are outstanding analyses if (pending_analyses > 0) { #ifdef DEBUG_LEGION assert(!waiting_event.exists()); #endif waiting_event = Runtime::create_rt_user_event(); DeferMakeOwnerArgs args(this, new_subsets, done_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, waiting_event); return false; } // Now we can mark that we are the logical owner logical_owner_space = local_space; // If we were waiting for a valid copy of the subsets we now have it if (eq_state == PENDING_VALID_STATE) { #ifdef DEBUG_LEGION assert(transition_event.exists()); #endif // We can trigger this transition event now that we have a valid // copy of the subsets (we are the logical owner) Runtime::trigger_event(transition_event); transition_event = RtUserEvent::NO_RT_USER_EVENT; } eq_state = MAPPING_STATE; LocalReferenceMutator mutator; // Add references to all the views that we've loaded for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) it->first->add_nested_valid_ref(did, &mutator); for (std::map<unsigned,std::vector<ReductionView*> >::const_iterator it1 = reduction_instances.begin(); it1 != reduction_instances.end(); it1++) for (std::vector<ReductionView*>::const_iterator it2 = it1->second.begin(); it2 != it1->second.end(); it2++) (*it2)->add_nested_valid_ref(did, &mutator); for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end(); it++) it->first->add_nested_valid_ref(did, &mutator); // Update the subsets now that we are officially the owner for (FieldMaskSet<EquivalenceSet>::const_iterator it = new_subsets->begin(); it != new_subsets->end(); it++) if (subsets.insert(it->first, it->second)) it->first->add_nested_resource_ref(did); Runtime::trigger_event(done_event, mutator.get_done_event()); return true; } //-------------------------------------------------------------------------- void EquivalenceSet::update_owner(const AddressSpaceID new_logical_owner) //-------------------------------------------------------------------------- { AutoLock eq(eq_lock); #ifdef DEBUG_LEGION // We should never be told that we're the new owner this way assert(new_logical_owner != local_space); #endif // If we are the owner then we know this update is stale so ignore it if (!is_logical_owner()) logical_owner_space = new_logical_owner; } //-------------------------------------------------------------------------- FieldMask EquivalenceSet::is_restricted(InstanceView *view) //-------------------------------------------------------------------------- { AutoLock eq(eq_lock,1,false/*exclusive*/); FieldMask mask; FieldMaskSet<InstanceView>::const_iterator finder = restricted_instances.find(view); if (finder != restricted_instances.end()) mask = finder->second; return mask; } //-------------------------------------------------------------------------- void EquivalenceSet::initialize_set(const RegionUsage &usage, const FieldMask &user_mask, const bool restricted, const InstanceSet &sources, const std::vector<InstanceView*> &corresponding, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(is_logical_owner()); assert(sources.size() == corresponding.size()); #endif WrapperReferenceMutator mutator(applied_events); AutoLock eq(eq_lock); if (IS_REDUCE(usage)) { #ifdef DEBUG_LEGION // Reduction-only should always be restricted for now // Could change if we started issuing reduction close // operations at the end of a context assert(restricted); #endif // Since these are restricted, we'll make these the actual // target logical instances and record them as restricted // instead of recording them as reduction instances for (unsigned idx = 0; idx < sources.size(); idx++) { const FieldMask &view_mask = sources[idx].get_valid_fields(); InstanceView *view = corresponding[idx]; FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(view); if (finder == valid_instances.end()) { valid_instances.insert(view, view_mask); view->add_nested_valid_ref(did, &mutator); } else finder.merge(view_mask); // Always restrict reduction-only users since we know the data // is going to need to be flushed anyway FieldMaskSet<InstanceView>::iterator restricted_finder = restricted_instances.find(view); if (restricted_finder == restricted_instances.end()) { restricted_instances.insert(view, view_mask); view->add_nested_valid_ref(did, &mutator); } else restricted_finder.merge(view_mask); } } else { for (unsigned idx = 0; idx < sources.size(); idx++) { const FieldMask &view_mask = sources[idx].get_valid_fields(); InstanceView *view = corresponding[idx]; #ifdef DEBUG_LEGION assert(!view->is_reduction_view()); #endif FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(view); if (finder == valid_instances.end()) { valid_instances.insert(view, view_mask); view->add_nested_valid_ref(did, &mutator); } else finder.merge(view_mask); // If this is restricted then record it if (restricted) { FieldMaskSet<InstanceView>::iterator restricted_finder = restricted_instances.find(view); if (restricted_finder == restricted_instances.end()) { restricted_instances.insert(view, view_mask); view->add_nested_valid_ref(did, &mutator); } else restricted_finder.merge(view_mask); } } } // Update any restricted fields if (restricted) restricted_fields |= user_mask; // Set the version numbers too version_numbers[init_version] |= user_mask; } //-------------------------------------------------------------------------- void EquivalenceSet::find_valid_instances(ValidInstAnalysis &analysis, FieldMask user_mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, user_mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, user_mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = user_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); user_mask -= non_subset; if (!user_mask) return; } } // Otherwise we fall through and record our subsets } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(user_mask)) { check_for_unrefined_remainder(eq, user_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & user_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Update the user mask and the stale_mask if there is one user_mask -= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->find_valid_instances(analysis, it->second, deferral_events, applied_events, false/*original*/); eq.reacquire(); // Return if our user mask is empty if (!user_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif // Lock the analysis so we can perform updates here AutoLock a_lock(analysis); if (analysis.redop != 0) { // Iterate over all the fields int fidx = user_mask.find_first_set(); while (fidx >= 0) { std::map<unsigned,std::vector<ReductionView*> >::const_iterator current = reduction_instances.find(fidx); if (current != reduction_instances.end()) { FieldMask local_mask; local_mask.set_bit(fidx); for (std::vector<ReductionView*>::const_reverse_iterator it = current->second.rbegin(); it != current->second.rend(); it++) { ReductionManager *manager = (*it)->get_manager()->as_reduction_manager(); if (manager->redop != analysis.redop) break; analysis.record_instance(*it, local_mask); } } fidx = user_mask.find_next_set(fidx+1); } } else { for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { if (!it->first->is_instance_view()) continue; const FieldMask overlap = it->second & user_mask; if (!overlap) continue; analysis.record_instance(it->first->as_instance_view(), overlap); } } if (has_restrictions(user_mask)) analysis.record_restriction(); } //-------------------------------------------------------------------------- void EquivalenceSet::find_invalid_instances(InvalidInstAnalysis &analysis, FieldMask user_mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, user_mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, user_mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = user_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); user_mask -= non_subset; if (!user_mask) return; } } // Otherwise we fall through and record our subsets } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(user_mask)) { check_for_unrefined_remainder(eq, user_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & user_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Update the user mask and the stale_mask if there is one user_mask -= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->find_invalid_instances(analysis, it->second, deferral_events, applied_events, false/*original*/); eq.reacquire(); // Return if our user mask is empty if (!user_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif // Lock the analysis so we can perform updates here AutoLock a_lock(analysis); // See if our instances are valid for any fields we're traversing // and if not record them for (FieldMaskSet<InstanceView>::const_iterator it = analysis.valid_instances.begin(); it != analysis.valid_instances.end(); it++) { FieldMask invalid_mask = it->second & user_mask; if (!invalid_mask) continue; FieldMaskSet<LogicalView>::const_iterator finder = valid_instances.find(it->first); if (finder != valid_instances.end()) { invalid_mask -= finder->second; if (!!invalid_mask) analysis.record_instance(it->first, invalid_mask); } else // Not valid for any of them so record it analysis.record_instance(it->first, invalid_mask); } } //-------------------------------------------------------------------------- void EquivalenceSet::defer_traversal(AutoTryLock &eq, PhysicalAnalysis &analysis, const FieldMask &mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, const bool already_deferred, const bool cached_set) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!eq.has_lock()); #endif // See if we've already deferred this or not if (!already_deferred) { const RtUserEvent deferral_event = Runtime::create_rt_user_event(); const RtEvent precondition = chain_deferral_events(deferral_event); analysis.defer_traversal(precondition, this, mask, deferral_events, applied_events, cached_set, deferral_event); } else analysis.defer_traversal(eq.try_next(), this, mask, deferral_events, applied_events, cached_set); } //-------------------------------------------------------------------------- void EquivalenceSet::update_set(UpdateAnalysis &analysis, FieldMask user_mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *remove_mask, // can be NULL const bool cached_set/*=true*/, const bool already_deferred/*=false*/) //-------------------------------------------------------------------------- { // Try to get the lock, if we don't defer the traversal AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, user_mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!cached_set && analysis.update_alt_sets(this, user_mask)) return; if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, user_mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = user_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); user_mask -= non_subset; if (!user_mask) return; } } // Otherwise we fall through and record our subsets } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(user_mask)) { check_for_unrefined_remainder(eq, user_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & user_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Remove ourselves if we recursed if (!cached_set) analysis.filter_alt_sets(this, to_traverse.get_valid_mask()); // Update the user mask and the remove_mask if there is one user_mask -= to_traverse.get_valid_mask(); if (remove_mask != NULL) *remove_mask |= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->update_set(analysis, it->second, deferral_events, applied_events, NULL/*remove mask*/, false/*original set*/); eq.reacquire(); // Return if our user mask is empty if (!user_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif WrapperReferenceMutator mutator(applied_events); // Now that we're ready to perform the analysis // we need to lock the analysis AutoLock a_lock(analysis); // Check for any uninitialized data // Don't report uninitialized warnings for empty equivalence classes if (analysis.check_initialized && !set_expr->is_empty()) { const FieldMask uninit = user_mask - valid_instances.get_valid_mask(); if (!!uninit) analysis.record_uninitialized(uninit, applied_events); } if (analysis.output_aggregator != NULL) analysis.output_aggregator->clear_update_fields(); if (IS_REDUCE(analysis.usage)) { // Reduction-only // We only record reductions if the set expression is not empty // as we can't guarantee the reductions will ever be read for // empty equivalence sets which can lead to leaked instances if (!set_expr->is_empty()) { // Record the reduction instances for (unsigned idx = 0; idx < analysis.target_views.size(); idx++) { ReductionView *red_view = analysis.target_views[idx]->as_reduction_view(); #ifdef DEBUG_LEGION assert(red_view->get_redop() == analysis.usage.redop); #endif const FieldMask &update_fields = analysis.target_instances[idx].get_valid_fields(); int fidx = update_fields.find_first_set(); while (fidx >= 0) { std::vector<ReductionView*> &field_views = reduction_instances[fidx]; red_view->add_nested_valid_ref(did, &mutator); field_views.push_back(red_view); fidx = update_fields.find_next_set(fidx+1); } } // Flush any restricted fields if (!!restricted_fields) { const FieldMask reduce_mask = user_mask & restricted_fields; if (!!reduce_mask) apply_reductions(reduce_mask, analysis.output_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.index, true/*track events*/); // No need to record that we applied the reductions, we'll // discover that when we collapse the single/multi-reduce state reduction_fields |= (user_mask - restricted_fields); } else reduction_fields |= user_mask; } } else if (IS_WRITE(analysis.usage) && IS_DISCARD(analysis.usage)) { // Write-only // Filter any reductions that we no longer need const FieldMask reduce_filter = reduction_fields & user_mask; if (!!reduce_filter) filter_reduction_instances(reduce_filter); // Filter any normal instances that will be overwritten const FieldMask non_restricted = user_mask - restricted_fields; if (!!non_restricted) { filter_valid_instances(non_restricted); // Record any non-restricted instances record_instances(non_restricted, analysis.target_instances, analysis.target_views, mutator); } // Issue copy-out copies for any restricted fields if (!!restricted_fields) { const FieldMask restricted_mask = user_mask & restricted_fields; if (!!restricted_mask) copy_out(restricted_mask, analysis.target_instances, analysis.target_views, analysis.op, analysis.index, analysis.output_aggregator); } // Advance our version numbers advance_version_numbers(user_mask); } else if (IS_READ_ONLY(analysis.usage) && !update_guards.empty() && !(user_mask * update_guards.get_valid_mask())) { // If we're doing read-only mode, get the set of events that // we need to wait for before we can do our registration, this // ensures that we serialize read-only operations correctly // In order to avoid deadlock we have to make different copy fill // aggregators for each of the different fields of prior updates FieldMask remainder_mask = user_mask; LegionVector<std::pair<CopyFillAggregator*,FieldMask> >::aligned to_add; for (FieldMaskSet<CopyFillGuard>::iterator it = update_guards.begin(); it != update_guards.end(); it++) { const FieldMask guard_mask = remainder_mask & it->second; if (!guard_mask) continue; // No matter what record our dependences on the prior guards #ifdef NON_AGGRESSIVE_AGGREGATORS const RtEvent guard_event = it->first->effects_applied; #else const RtEvent guard_event = (analysis.original_source == local_space) ? it->first->guard_postcondition : it->first->effects_applied; #endif analysis.guard_events.insert(guard_event); CopyFillAggregator *input_aggregator = NULL; // See if we have an input aggregator that we can use now std::map<RtEvent,CopyFillAggregator*>::const_iterator finder = analysis.input_aggregators.find(guard_event); if (finder != analysis.input_aggregators.end()) { input_aggregator = finder->second; if (input_aggregator != NULL) input_aggregator->clear_update_fields(); } // Use this to see if any new updates are recorded update_set_internal(input_aggregator, guard_event, analysis.op, analysis.index, analysis.usage, guard_mask, analysis.target_instances, analysis.target_views, applied_events, analysis.record_valid); // If we did any updates record ourselves as the new guard here if ((input_aggregator != NULL) && ((finder == analysis.input_aggregators.end()) || input_aggregator->has_update_fields())) { #ifndef NON_AGGRESSIVE_AGGREGATORS // We also have to chain effects in this case input_aggregator->record_reference_mutation_effect( it->first->effects_applied); #endif if (finder == analysis.input_aggregators.end()) analysis.input_aggregators[guard_event] = input_aggregator; // Record this as a guard for later operations to_add.resize(to_add.size() + 1); std::pair<CopyFillAggregator*,FieldMask> &back = to_add.back(); const FieldMask &update_mask = input_aggregator->get_update_fields(); back.first = input_aggregator; back.second = update_mask; #ifdef DEBUG_LEGION if (!input_aggregator->record_guard_set(this)) assert(false); #else input_aggregator->record_guard_set(this); #endif // Remove the current guard since it doesn't matter anymore it.filter(update_mask); } remainder_mask -= guard_mask; if (!remainder_mask) break; } if (!to_add.empty()) { for (LegionVector<std::pair<CopyFillAggregator*,FieldMask> >:: aligned::const_iterator it = to_add.begin(); it != to_add.end(); it++) { #ifdef DEBUG_LEGION assert(it->second * refining_fields); #endif update_guards.insert(it->first, it->second); } } // If we have unguarded fields we can easily do thos if (!!remainder_mask) { CopyFillAggregator *input_aggregator = NULL; // See if we have an input aggregator that we can use now std::map<RtEvent,CopyFillAggregator*>::const_iterator finder = analysis.input_aggregators.find(RtEvent::NO_RT_EVENT); if (finder != analysis.input_aggregators.end()) { input_aggregator = finder->second; if (input_aggregator != NULL) input_aggregator->clear_update_fields(); } update_set_internal(input_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.index, analysis.usage, remainder_mask, analysis.target_instances, analysis.target_views, applied_events, analysis.record_valid); // If we made the input aggregator then store it if ((input_aggregator != NULL) && ((finder == analysis.input_aggregators.end()) || input_aggregator->has_update_fields())) { analysis.input_aggregators[RtEvent::NO_RT_EVENT] = input_aggregator; #ifdef DEBUG_LEGION assert(input_aggregator->get_update_fields() * refining_fields); #endif // Record this as a guard for later operations update_guards.insert(input_aggregator, input_aggregator->get_update_fields()); #ifdef DEBUG_LEGION if (!input_aggregator->record_guard_set(this)) assert(false); #else input_aggregator->record_guard_set(this); #endif } } } else { // Read-write or read-only case // Read-only case if there are no guards CopyFillAggregator *input_aggregator = NULL; // See if we have an input aggregator that we can use now std::map<RtEvent,CopyFillAggregator*>::const_iterator finder = analysis.input_aggregators.find(RtEvent::NO_RT_EVENT); if (finder != analysis.input_aggregators.end()) { input_aggregator = finder->second; if (input_aggregator != NULL) input_aggregator->clear_update_fields(); } update_set_internal(input_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.index, analysis.usage, user_mask, analysis.target_instances, analysis.target_views, applied_events, analysis.record_valid); if (IS_WRITE(analysis.usage)) { advance_version_numbers(user_mask); // Issue copy-out copies for any restricted fields if we wrote stuff const FieldMask restricted_mask = restricted_fields & user_mask; if (!!restricted_mask) copy_out(restricted_mask, analysis.target_instances, analysis.target_views, analysis.op, analysis.index, analysis.output_aggregator); } // If we made the input aggregator then store it if ((input_aggregator != NULL) && ((finder == analysis.input_aggregators.end()) || input_aggregator->has_update_fields())) { analysis.input_aggregators[RtEvent::NO_RT_EVENT] = input_aggregator; #ifdef DEBUG_LEGION assert(input_aggregator->get_update_fields() * refining_fields); #endif // Record this as a guard for later operations update_guards.insert(input_aggregator, input_aggregator->get_update_fields()); #ifdef DEBUG_LEGION if (!input_aggregator->record_guard_set(this)) assert(false); #else input_aggregator->record_guard_set(this); #endif } } if ((analysis.output_aggregator != NULL) && analysis.output_aggregator->has_update_fields()) { #ifdef DEBUG_LEGION assert(analysis.output_aggregator->get_update_fields() * refining_fields); #endif update_guards.insert(analysis.output_aggregator, analysis.output_aggregator->get_update_fields()); #ifdef DEBUG_LEGION if (!analysis.output_aggregator->record_guard_set(this)) assert(false); #else analysis.output_aggregator->record_guard_set(this); #endif } check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::update_set_internal( CopyFillAggregator *&input_aggregator, const RtEvent guard_event, Operation *op, const unsigned index, const RegionUsage &usage, const FieldMask &user_mask, const InstanceSet &target_instances, const std::vector<InstanceView*> &target_views, std::set<RtEvent> &applied_events, const bool record_valid) //-------------------------------------------------------------------------- { // Read-write or read-only // Check for any copies from normal instances first issue_update_copies_and_fills(input_aggregator, guard_event, op, index, false/*track*/, user_mask, target_instances, target_views, set_expr); // Get the set of fields to filter, any for which we're about // to apply pending reductions or overwite, except those that // are restricted const FieldMask reduce_mask = reduction_fields & user_mask; const FieldMask restricted_mask = restricted_fields & user_mask; const bool is_write = IS_WRITE(usage); FieldMask filter_mask = is_write ? user_mask : reduce_mask; if (!!restricted_mask) filter_mask -= restricted_mask; if (!!filter_mask) filter_valid_instances(filter_mask); WrapperReferenceMutator mutator(applied_events); // Save the instances if they are not restricted // Otherwise if they are restricted then the restricted instances // are already listed as the valid views so there's nothing more // for us to have to do if (!!restricted_mask) { const FieldMask non_restricted = user_mask - restricted_fields; if (!!non_restricted) record_instances(non_restricted, target_instances, target_views, mutator); } else if (record_valid) record_instances(user_mask, target_instances, target_views, mutator); // Read-only instances that perform reductions still need to be // tracked for these fields because it is where the reductions // are to be applied else if (!!reduce_mask) record_instances(reduce_mask, target_instances, target_views, mutator); // Next check for any reductions that need to be applied if (!!reduce_mask) apply_reductions(reduce_mask, input_aggregator, guard_event, op, index, false/*track events*/); } //-------------------------------------------------------------------------- void EquivalenceSet::check_for_migration(PhysicalAnalysis &analysis, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { #ifndef DISABLE_EQUIVALENCE_SET_MIGRATION #ifdef DEBUG_LEGION assert(is_logical_owner()); #endif const AddressSpaceID eq_source = analysis.original_source; // Record our user in the set of previous users bool found = false; std::vector<std::pair<AddressSpaceID,unsigned> > &current_samples = user_samples[migration_index]; for (std::vector<std::pair<AddressSpaceID,unsigned> >::iterator it = current_samples.begin(); it != current_samples.end(); it++) { if (it->first != eq_source) continue; found = true; it->second++; break; } if (!found) current_samples.push_back( std::pair<AddressSpaceID,unsigned>(eq_source,1)); // Increase the sample count and if we haven't done enough // for a test then we can return and keep going if (++sample_count < SAMPLES_PER_MIGRATION_TEST) { // Check to see if the request bounced off a stale owner // and we should send the update message if ((eq_source != analysis.previous) && (eq_source != local_space) && (eq_source != logical_owner_space)) { RtUserEvent notification_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(logical_owner_space); rez.serialize(notification_event); } runtime->send_equivalence_set_owner_update(eq_source, rez); applied_events.insert(notification_event); } return; } // Issue a warning and don't migrate if we hit this case if (current_samples.size() == SAMPLES_PER_MIGRATION_TEST) { REPORT_LEGION_WARNING(LEGION_WARNING_LARGE_EQUIVALENCE_SET_NODE_USAGE, "Internal runtime performance warning: equivalence set %lld has " "%zd different users which is the same as the sampling rate of " "%d. Please report this application use case to the Legion " "developers mailing list.", did, current_samples.size(), SAMPLES_PER_MIGRATION_TEST) // Reset the data structures for the next run current_samples.clear(); sample_count = 0; return; } // Sort the current samples so that they are in order for // single epoch cases, for multi-epoch cases they will be // sorted by the summary computation below if ((MIGRATION_EPOCHS == 1) && (current_samples.size() > 1)) std::sort(current_samples.begin(), current_samples.end()); // Increment this for the next pass migration_index = (migration_index + 1) % MIGRATION_EPOCHS; // Don't do any migrations if we have any pending refinements // or we have outstanding analyses that prevent it for now if (!pending_refinements.empty() || !!refining_fields || (pending_analyses > 0)) { // Reset the data structures for the next run sample_count = 0; user_samples[migration_index].clear(); return; } std::vector<std::pair<AddressSpaceID,unsigned> > &next_samples = user_samples[migration_index]; if (MIGRATION_EPOCHS > 1) { // Compute the summary from all the epochs into the epoch // that we are about to clear std::map<AddressSpaceID,unsigned> summary( next_samples.begin(), next_samples.end()); for (unsigned idx = 1; idx < MIGRATION_EPOCHS; idx++) { const std::vector<std::pair<AddressSpaceID,unsigned> > &other_samples = user_samples[(migration_index + idx) % MIGRATION_EPOCHS]; for (std::vector<std::pair<AddressSpaceID,unsigned> >::const_iterator it = other_samples.begin(); it != other_samples.end(); it++) { std::map<AddressSpaceID,unsigned>::iterator finder = summary.find(it->first); if (finder == summary.end()) summary.insert(*it); else finder->second += it->second; } } next_samples.clear(); next_samples.insert(next_samples.begin(),summary.begin(),summary.end()); } AddressSpaceID new_logical_owner = logical_owner_space; #ifdef DEBUG_LEGION assert(!next_samples.empty()); #endif if (next_samples.size() > 1) { int logical_owner_count = -1; // Figure out which node(s) has/have the most uses // Make sure that the current owner node is sticky // if it is tied for the most uses unsigned max_count = next_samples[0].second; AddressSpaceID max_user = next_samples[0].first; for (unsigned idx = 1; idx < next_samples.size(); idx++) { const AddressSpaceID user = next_samples[idx].first; const unsigned user_count = next_samples[idx].second; if (user == logical_owner_space) logical_owner_count = user_count; if (user_count < max_count) continue; // This is the part where we guarantee stickiness if ((user_count == max_count) && (user != logical_owner_space)) continue; max_count = user_count; max_user = user; } if (logical_owner_count > 0) { if (logical_owner_space != max_user) { // If the logical owner is one of the current users then // we really better have a good reason to move this // equivalence set to a new node. For now the difference // between max_count and the current owner count has to // be greater than the number of nodes that we see participating // on this equivalence set. This heuristic should avoid // the ping-pong case even when our sampling rate does not // naturally align with the number of nodes participating if ((max_count - unsigned(logical_owner_count)) > next_samples.size()) new_logical_owner = max_user; } } else // If we didn't have the current logical owner then // just pick the maximum one new_logical_owner = max_user; } else // If all the requests came from the same node, send it there new_logical_owner = next_samples[0].first; // This always get reset here sample_count = 0; // Reset this for the next iteration next_samples.clear(); // See if we are actually going to do the migration if (logical_owner_space == new_logical_owner) { // No need to do the migration in this case // Check to see if the request bounced off a stale owner // and we should send the update message if ((eq_source != analysis.previous) && (eq_source != local_space) && (eq_source != logical_owner_space)) { RtUserEvent notification_event = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(logical_owner_space); rez.serialize(notification_event); } runtime->send_equivalence_set_owner_update(eq_source, rez); applied_events.insert(notification_event); } return; } // At this point we've decided to do the migration log_migration.info("Migrating Equivalence Set %llx from %d to %d", did, local_space, new_logical_owner); logical_owner_space = new_logical_owner; // Add ourselves and remove the new owner from remote subsets remote_subsets.insert(local_space); remote_subsets.erase(logical_owner_space); // We can switch our eq_state to being remote valid eq_state = VALID_STATE; RtUserEvent done_migration = Runtime::create_rt_user_event(); // Do the migration Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(done_migration); pack_migration(rez, done_migration); } runtime->send_equivalence_set_migration(logical_owner_space, rez); applied_events.insert(done_migration); #endif // DISABLE_EQUIVALENCE_SET MIGRATION } //-------------------------------------------------------------------------- void EquivalenceSet::acquire_restrictions(AcquireAnalysis &analysis, FieldMask acquire_mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *remove_mask, const bool cached_set/*=true*/, const bool already_deferred/*=false*/) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, acquire_mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!cached_set && analysis.update_alt_sets(this, acquire_mask)) return; if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, acquire_mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = acquire_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); acquire_mask -= non_subset; if (!acquire_mask) return; } } } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(acquire_mask)) { check_for_unrefined_remainder(eq, acquire_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & acquire_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Remove ourselves if we recursed if (!cached_set) analysis.filter_alt_sets(this, to_traverse.get_valid_mask()); // Update the acquire mask and the remove_mask if there is one acquire_mask -= to_traverse.get_valid_mask(); if (remove_mask != NULL) *remove_mask |= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->acquire_restrictions(analysis, it->second, deferral_events, applied_events, NULL/*remove mask*/, false/*original set*/); eq.reacquire(); // Return if our acquire user mask is empty if (!acquire_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif acquire_mask &= restricted_fields; if (!acquire_mask) return; // Now we need to lock the analysis if we're going to do this traversal AutoLock a_lock(analysis); for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end();it++) { const FieldMask overlap = acquire_mask & it->second; if (!overlap) continue; InstanceView *view = it->first->as_instance_view(); analysis.record_instance(view, overlap); } restricted_fields -= acquire_mask; check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::release_restrictions(ReleaseAnalysis &analysis, FieldMask release_mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *remove_mask, const bool cached_set/*=true*/, const bool already_deferred/*=false*/) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, release_mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!cached_set && analysis.update_alt_sets(this, release_mask)) return; if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, release_mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = release_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); release_mask -= non_subset; if (!release_mask) return; } } } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(release_mask)) { check_for_unrefined_remainder(eq, release_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & release_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Remove ourselves if we recursed if (!cached_set) analysis.filter_alt_sets(this, to_traverse.get_valid_mask()); // Update the release mask and the remove_mask if there is one release_mask -= to_traverse.get_valid_mask(); if (remove_mask != NULL) *remove_mask |= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->release_restrictions(analysis, it->second, deferral_events, applied_events, NULL/*remove mask*/, false/*original set*/); eq.reacquire(); // Return if ourt release mask is empty if (!release_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif // At this point we need to lock the analysis AutoLock a_lock(analysis); // Find our local restricted instances and views and record them InstanceSet local_instances; std::vector<InstanceView*> local_views; for (FieldMaskSet<InstanceView>::const_iterator it = restricted_instances.begin(); it != restricted_instances.end();it++) { const FieldMask overlap = it->second & release_mask; if (!overlap) continue; InstanceView *view = it->first->as_instance_view(); local_instances.add_instance(InstanceRef(view->get_manager(), overlap)); local_views.push_back(view); analysis.record_instance(view, overlap); } if (analysis.release_aggregator != NULL) analysis.release_aggregator->clear_update_fields(); // Issue the updates issue_update_copies_and_fills(analysis.release_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.index, false/*track*/, release_mask, local_instances, local_views, set_expr); // Filter the valid views filter_valid_instances(release_mask); // Update with just the restricted instances WrapperReferenceMutator mutator(applied_events); record_instances(release_mask, local_instances, local_views, mutator); // See if we have any reductions to apply as well const FieldMask reduce_mask = release_mask & reduction_fields; if (!!reduce_mask) apply_reductions(reduce_mask, analysis.release_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.index, false/*track*/); // Add the fields back to the restricted ones restricted_fields |= release_mask; if ((analysis.release_aggregator != NULL) && analysis.release_aggregator->has_update_fields()) { #ifdef DEBUG_LEGION assert(analysis.release_aggregator->get_update_fields() * refining_fields); #endif update_guards.insert(analysis.release_aggregator, analysis.release_aggregator->get_update_fields()); #ifdef DEBUG_LEGION if (!analysis.release_aggregator->record_guard_set(this)) assert(false); #else analysis.release_aggregator->record_guard_set(this); #endif } check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::issue_across_copies(CopyAcrossAnalysis &analysis, FieldMask src_mask, IndexSpaceExpression *overlap, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events) //-------------------------------------------------------------------------- { // No try lock since we can't defer this because of the overlap // Also, while you might think this could a read-only lock since // we're just reading meta-data, that's not quite right because // we need exclusive access to data structures in check_for_migration AutoLock eq(eq_lock); // No alt-set tracking here for copy across because we might // need to to traverse this multiple times with different expressions if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, src_mask, logical_owner_space, false/*cached set*/); return; } else { const FieldMask non_subset = src_mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, false/*cached set*/); src_mask -= non_subset; if (!src_mask) return; } } } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(src_mask)) { check_for_unrefined_remainder(eq, src_mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & src_mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // No alt-set tracking here, see comment above // Update the release mask and the remove_mask if there is one src_mask -= to_traverse.get_valid_mask(); // No alt-set tracking here, see comment above for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) { IndexSpaceExpression *subset_overlap = runtime->forest-> intersect_index_spaces(it->first->set_expr, overlap); if (subset_overlap->is_empty()) continue; it->first->issue_across_copies(analysis, it->second, subset_overlap, deferral_events, applied_events); } eq.reacquire(); // Return if ourt source mask is empty if (!src_mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); assert(IS_READ_ONLY(analysis.src_usage)); #endif // We need to lock the analysis at this point AutoLock a_lock(analysis); // Check for any uninitialized fields const FieldMask uninit = src_mask - valid_instances.get_valid_mask(); if (!!uninit) analysis.record_uninitialized(uninit, applied_events); // TODO: Handle the case where we are predicated if (analysis.pred_guard.exists()) assert(false); // See if there are any other predicate guard fields that we need // to have as preconditions before applying our owner updates if (!update_guards.empty() && !(src_mask * update_guards.get_valid_mask())) { for (FieldMaskSet<CopyFillGuard>::iterator it = update_guards.begin(); it != update_guards.end(); it++) { if (src_mask * it->second) continue; // No matter what record our dependences on the prior guards #ifdef NON_AGGRESSIVE_AGGREGATORS const RtEvent guard_event = it->first->effects_applied; #else const RtEvent guard_event = (analysis.original_source == local_space) ? it->first->guard_postcondition : it->first->effects_applied; #endif analysis.guard_events.insert(guard_event); } } // At this point we know we're going to need an aggregator since // this is an across copy and we have to be doing updates CopyFillAggregator *across_aggregator = analysis.get_across_aggregator(); if (!analysis.perfect) { // The general case where fields don't align regardless of // whether we are doing a reduction across or not #ifdef DEBUG_LEGION assert(!analysis.src_indexes.empty()); assert(!analysis.dst_indexes.empty()); assert(analysis.src_indexes.size() == analysis.dst_indexes.size()); assert(analysis.across_helpers.size() == analysis.target_instances.size()); #endif // We need to figure out how to issue these copies ourself since // we need to map from one field to another // First construct a map from dst indexes to src indexes std::map<unsigned,unsigned> dst_to_src; for (unsigned idx = 0; idx < analysis.src_indexes.size(); idx++) dst_to_src[analysis.dst_indexes[idx]] = analysis.src_indexes[idx]; // Iterate over the target instances for (unsigned idx = 0; idx < analysis.target_views.size(); idx++) { const FieldMask &dst_mask = analysis.target_instances[idx].get_valid_fields(); // Compute a tmp mask based on the dst mask FieldMask source_mask; int fidx = dst_mask.find_first_set(); while (fidx >= 0) { std::map<unsigned,unsigned>::const_iterator finder = dst_to_src.find(fidx); #ifdef DEBUG_LEGION assert(finder != dst_to_src.end()); #endif source_mask.set_bit(finder->second); fidx = dst_mask.find_next_set(fidx+1); } // Now find all the source instances for this destination FieldMaskSet<LogicalView> src_views; for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask field_overlap = it->second & source_mask; if (!field_overlap) continue; src_views.insert(it->first, field_overlap); } #ifdef DEBUG_LEGION if (src_views.empty()) // will only happen in error case continue; #endif across_aggregator->record_updates(analysis.target_views[idx], src_views, source_mask, overlap, analysis.redop, analysis.across_helpers[idx]); } // Now check for any reductions that need to be applied FieldMask reduce_mask = reduction_fields & src_mask; if (!!reduce_mask) { #ifdef DEBUG_LEGION assert(analysis.redop == 0); // can't have reductions of reductions #endif std::map<unsigned,unsigned> src_to_dst; for (unsigned idx = 0; idx < analysis.src_indexes.size(); idx++) src_to_dst[analysis.src_indexes[idx]] = analysis.dst_indexes[idx]; int src_fidx = reduce_mask.find_first_set(); while (src_fidx >= 0) { std::map<unsigned,std::vector<ReductionView*> >::const_iterator finder = reduction_instances.find(src_fidx); #ifdef DEBUG_LEGION assert(finder != reduction_instances.end()); assert(src_to_dst.find(src_fidx) != src_to_dst.end()); #endif const unsigned dst_fidx = src_to_dst[src_fidx]; // Find the target targets and record them for (unsigned idx = 0; idx < analysis.target_views.size(); idx++) { const FieldMask target_mask = analysis.target_instances[idx].get_valid_fields(); if (!target_mask.is_set(dst_fidx)) continue; across_aggregator->record_reductions(analysis.target_views[idx], finder->second, src_fidx, dst_fidx, overlap, analysis.across_helpers[idx]); } src_fidx = reduce_mask.find_next_set(src_fidx+1); } } } else if (analysis.redop == 0) { // Fields align and we're not doing a reduction so we can just // do a normal update copy analysis to figure out what to do issue_update_copies_and_fills(across_aggregator, RtEvent::NO_RT_EVENT, analysis.op, analysis.src_index, true/*track effects*/, src_mask, analysis.target_instances, analysis.target_views, overlap, true/*skip check*/, analysis.dst_index); // We also need to check for any reductions that need to be applied const FieldMask reduce_mask = reduction_fields & src_mask; if (!!reduce_mask) { int fidx = reduce_mask.find_first_set(); while (fidx >= 0) { std::map<unsigned,std::vector<ReductionView*> >::const_iterator finder = reduction_instances.find(fidx); #ifdef DEBUG_LEGION assert(finder != reduction_instances.end()); #endif // Find the target targets and record them for (unsigned idx = 0; idx < analysis.target_views.size(); idx++) { const FieldMask target_mask = analysis.target_instances[idx].get_valid_fields(); if (!target_mask.is_set(fidx)) continue; across_aggregator->record_reductions(analysis.target_views[idx], finder->second, fidx, fidx, overlap); } fidx = reduce_mask.find_next_set(fidx+1); } } } else { // Fields align but we're doing a reduction across // Find the valid views that we need for issuing the updates FieldMaskSet<LogicalView> src_views; for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask overlap = it->second & src_mask; if (!overlap) continue; src_views.insert(it->first, overlap); } for (unsigned idx = 0; idx < analysis.target_views.size(); idx++) { const FieldMask &mask = analysis.target_instances[idx].get_valid_fields(); #ifdef DEBUG_LEGION if (src_views.empty()) // will only happen in error case continue; #endif across_aggregator->record_updates(analysis.target_views[idx], src_views, mask, overlap, analysis.redop, NULL/*across*/); } // There shouldn't be any reduction instances to worry about here #ifdef DEBUG_LEGION assert(reduction_fields * src_mask); #endif } check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::overwrite_set(OverwriteAnalysis &analysis, FieldMask mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *remove_mask, const bool cached_set, const bool already_deferred) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!cached_set && analysis.update_alt_sets(this, mask)) return; if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); mask -= non_subset; if (!mask) return; } } } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(mask)) { check_for_unrefined_remainder(eq, mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Remove ourselves if we recursed if (!cached_set) analysis.filter_alt_sets(this, to_traverse.get_valid_mask()); // Update the mask and the remove_mask if there is one mask -= to_traverse.get_valid_mask(); if (remove_mask != NULL) *remove_mask |= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->overwrite_set(analysis, it->second, deferral_events, applied_events, NULL/*remove mask*/, false/*cachd set*/); eq.reacquire(); // Return if ourt mask is empty if (!mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif // At this point we need to lock the analysis AutoLock a_lock(analysis); if (analysis.output_aggregator != NULL) analysis.output_aggregator->clear_update_fields(); // Two different cases here depending on whether we have a precidate if (analysis.pred_guard.exists()) { #ifdef DEBUG_LEGION assert(!analysis.add_restriction); // shouldn't be doing this #endif // We have a predicate so collapse everything to all the valid // instances and then do predicate fills to all those instances assert(false); } else { if (analysis.add_restriction || !restricted_fields || (restricted_fields * mask)) { // Easy case, just filter everything and add the new view const FieldMask reduce_filter = mask & reduction_fields; if (!!reduce_filter) filter_reduction_instances(reduce_filter); filter_valid_instances(mask); if (!analysis.views.empty()) { for (std::set<LogicalView*>::const_iterator it = analysis.views.begin(); it != analysis.views.end(); it++) { FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(*it); if (finder == valid_instances.end()) { WrapperReferenceMutator mutator(applied_events); (*it)->add_nested_valid_ref(did, &mutator); valid_instances.insert(*it, mask); } else finder.merge(mask); } } } else { // We overlap with some restricted fields so we can't filter // or update any restricted fields const FieldMask update_mask = mask - restricted_fields; if (!!update_mask) { const FieldMask reduce_filter = update_mask & reduction_fields; if (!!reduce_filter) filter_reduction_instances(reduce_filter); filter_valid_instances(update_mask); if (!analysis.views.empty()) { for (std::set<LogicalView*>::const_iterator it = analysis.views.begin(); it != analysis.views.end(); it++) { FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(*it); if (finder == valid_instances.end()) { WrapperReferenceMutator mutator(applied_events); (*it)->add_nested_valid_ref(did, &mutator); valid_instances.insert(*it, mask); } else finder.merge(mask); } } } } // Advance the version numbers advance_version_numbers(mask); if (analysis.add_restriction) { #ifdef DEBUG_LEGION assert(analysis.views.size() == 1); LogicalView *log_view = *(analysis.views.begin()); assert(log_view->is_instance_view()); #else LogicalView *log_view = *(analysis.views.begin()); #endif InstanceView *inst_view = log_view->as_instance_view(); FieldMaskSet<InstanceView>::iterator restricted_finder = restricted_instances.find(inst_view); if (restricted_finder == restricted_instances.end()) { WrapperReferenceMutator mutator(applied_events); inst_view->add_nested_valid_ref(did, &mutator); restricted_instances.insert(inst_view, mask); } else restricted_finder.merge(mask); restricted_fields |= mask; } else if (!!restricted_fields && !analysis.views.empty()) { // Check to see if we have any restricted outputs to write const FieldMask restricted_overlap = mask & restricted_fields; if (!!restricted_overlap) { // Pick a random view and copy from it LogicalView *log_view = *(analysis.views.begin()); copy_out(restricted_overlap, log_view, analysis.op, analysis.index, analysis.output_aggregator); } } } if ((analysis.output_aggregator != NULL) && analysis.output_aggregator->has_update_fields()) { #ifdef DEBUG_LEGION assert(analysis.output_aggregator->get_update_fields() * refining_fields); #endif update_guards.insert(analysis.output_aggregator, analysis.output_aggregator->get_update_fields()); #ifdef DEBUG_LEGION if (!analysis.output_aggregator->record_guard_set(this)) assert(false); #else analysis.output_aggregator->record_guard_set(this); #endif } check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::filter_set(FilterAnalysis &analysis, FieldMask mask, std::set<RtEvent> &deferral_events, std::set<RtEvent> &applied_events, FieldMask *remove_mask, const bool cached_set/*=true*/, const bool already_deferred/*=false*/) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { defer_traversal(eq, analysis, mask, deferral_events, applied_events, already_deferred, cached_set); return; } if (!cached_set && analysis.update_alt_sets(this, mask)) return; if (!is_logical_owner()) { // First check to see if our subsets are up to date if (eq_state == INVALID_STATE) request_remote_subsets(applied_events); if (subsets.empty()) { analysis.record_remote(this, mask, logical_owner_space, cached_set); return; } else { const FieldMask non_subset = mask - subsets.get_valid_mask(); if (!!non_subset) { analysis.record_remote(this, non_subset, logical_owner_space, cached_set); mask -= non_subset; if (!mask) return; } } } // Guard to prevent migration while we may release the lock increment_pending_analyses(); // If we've been refined, we need to get the names of // the sub equivalence sets to try while (is_refined(mask)) { check_for_unrefined_remainder(eq, mask, analysis.original_source); FieldMaskSet<EquivalenceSet> to_traverse; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & mask; if (!overlap) continue; to_traverse.insert(it->first, overlap); } eq.release(); // Remove ourselves if we recursed if (!cached_set) analysis.filter_alt_sets(this, to_traverse.get_valid_mask()); // Update the mask and the remove_mask if there is one mask -= to_traverse.get_valid_mask(); if (remove_mask != NULL) *remove_mask |= to_traverse.get_valid_mask(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_traverse.begin(); it != to_traverse.end(); it++) it->first->filter_set(analysis, it->second, deferral_events, applied_events, NULL/*remove mask*/, false/*original set*/); eq.reacquire(); // Return if ourt mask is empty if (!mask) { decrement_pending_analyses(); return; } } decrement_pending_analyses(); #ifdef DEBUG_LEGION // Should only be here if we're the owner assert(is_logical_owner()); #endif // No need to lock the analysis here since we're not going to change it FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(analysis.inst_view); if (finder != valid_instances.end()) { finder.filter(mask); if (!finder->second) { if (analysis.inst_view->remove_nested_valid_ref(did)) delete analysis.inst_view; valid_instances.erase(finder); } } if ((analysis.registration_view != NULL) && (analysis.registration_view != analysis.inst_view)) { finder = valid_instances.find(analysis.registration_view); if (finder != valid_instances.end()) { finder.filter(mask); if (!finder->second) { if (analysis.registration_view->remove_nested_valid_ref(did)) delete analysis.registration_view; valid_instances.erase(finder); } } } if (analysis.remove_restriction) { restricted_fields -= mask; #ifdef DEBUG_LEGION assert(analysis.inst_view != NULL); #endif FieldMaskSet<InstanceView>::iterator restricted_finder = restricted_instances.find(analysis.inst_view); if (restricted_finder != restricted_instances.end()) { restricted_finder.filter(mask); if (!restricted_finder->second) { if (analysis.inst_view->remove_nested_valid_ref(did)) delete analysis.inst_view; restricted_instances.erase(restricted_finder); } } } check_for_migration(analysis, applied_events); } //-------------------------------------------------------------------------- void EquivalenceSet::request_remote_subsets(std::set<RtEvent> &applied) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!is_logical_owner()); assert(eq_state == INVALID_STATE); assert(!transition_event.exists()); #endif // It's not actually ok to block here or we risk a hang so if we're // not already valid and haven't requested a valid copy yet then // go ahead and do that and record the event as an applied event // to ensure we get the update for the next user transition_event = Runtime::create_rt_user_event(); eq_state = PENDING_VALID_STATE; Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(local_space); } runtime->send_equivalence_set_subset_request(logical_owner_space, rez); applied.insert(transition_event); } //-------------------------------------------------------------------------- void EquivalenceSet::record_instances(const FieldMask &record_mask, const InstanceSet &target_instances, const std::vector<InstanceView*> &target_views, ReferenceMutator &mutator) //-------------------------------------------------------------------------- { for (unsigned idx = 0; idx < target_views.size(); idx++) { const FieldMask valid_mask = target_instances[idx].get_valid_fields() & record_mask; if (!valid_mask) continue; InstanceView *target = target_views[idx]; // Add it to the set FieldMaskSet<LogicalView>::iterator finder = valid_instances.find(target); if (finder == valid_instances.end()) { target->add_nested_valid_ref(did, &mutator); valid_instances.insert(target, valid_mask); } else finder.merge(valid_mask); } } //-------------------------------------------------------------------------- void EquivalenceSet::issue_update_copies_and_fills( CopyFillAggregator *&aggregator, const RtEvent guard_event, Operation *op, const unsigned index, const bool track_events, FieldMask update_mask, const InstanceSet &target_instances, const std::vector<InstanceView*> &target_views, IndexSpaceExpression *update_expr, const bool skip_check, const int dst_index /*= -1*/) const //-------------------------------------------------------------------------- { if (update_expr->is_empty()) return; if (!skip_check) { // Scan through and figure out which fields are already valid for (unsigned idx = 0; idx < target_views.size(); idx++) { FieldMaskSet<LogicalView>::const_iterator finder = valid_instances.find(target_views[idx]); if (finder == valid_instances.end()) continue; const FieldMask &needed_mask = target_instances[idx].get_valid_fields(); const FieldMask already_valid = needed_mask & finder->second; if (!already_valid) continue; update_mask -= already_valid; // If we're already valid for all the fields then we're done if (!update_mask) return; } } #ifdef DEBUG_LEGION assert(!!update_mask); #endif // Find the valid views that we need for issuing the updates FieldMaskSet<LogicalView> valid_views; for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask overlap = it->second & update_mask; if (!overlap) continue; valid_views.insert(it->first, overlap); } // Can happen with uninitialized data, we handle this case // before calling this method if (valid_views.empty()) return; if (target_instances.size() == 1) { if (aggregator == NULL) aggregator = (dst_index >= 0) ? new CopyFillAggregator(runtime->forest, op, index, dst_index, guard_event, track_events) : new CopyFillAggregator(runtime->forest, op, index, guard_event, track_events); aggregator->record_updates(target_views[0], valid_views, update_mask, update_expr); } else if (valid_views.size() == 1) { for (unsigned idx = 0; idx < target_views.size(); idx++) { const FieldMask dst_mask = update_mask & target_instances[idx].get_valid_fields(); if (!dst_mask) continue; if (aggregator == NULL) aggregator = (dst_index >= 0) ? new CopyFillAggregator(runtime->forest, op, index, dst_index, guard_event, track_events) : new CopyFillAggregator(runtime->forest, op, index, guard_event, track_events); aggregator->record_updates(target_views[idx], valid_views, dst_mask, update_expr); } } else { for (unsigned idx = 0; idx < target_views.size(); idx++) { const FieldMask dst_mask = update_mask & target_instances[idx].get_valid_fields(); // Can happen in cases with uninitialized data if (!dst_mask) continue; FieldMaskSet<LogicalView> src_views; for (FieldMaskSet<LogicalView>::const_iterator it = valid_views.begin(); it != valid_views.end(); it++) { const FieldMask overlap = dst_mask & it->second; if (!overlap) continue; src_views.insert(it->first, overlap); } if (aggregator == NULL) aggregator = (dst_index >= 0) ? new CopyFillAggregator(runtime->forest, op, index, dst_index, guard_event, track_events) : new CopyFillAggregator(runtime->forest, op, index, guard_event, track_events); aggregator->record_updates(target_views[idx], src_views, dst_mask, update_expr); } } } //-------------------------------------------------------------------------- void EquivalenceSet::filter_valid_instances(const FieldMask &filter_mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!filter_mask); #endif std::vector<LogicalView*> to_erase; for (FieldMaskSet<LogicalView>::iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask overlap = it->second & filter_mask; if (!overlap) continue; it.filter(overlap); if (!it->second) to_erase.push_back(it->first); } if (!to_erase.empty()) { for (std::vector<LogicalView*>::const_iterator it = to_erase.begin(); it != to_erase.end(); it++) { valid_instances.erase(*it); if ((*it)->remove_nested_valid_ref(did)) delete (*it); } } } //-------------------------------------------------------------------------- void EquivalenceSet::filter_reduction_instances(const FieldMask &to_filter) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!to_filter); #endif int fidx = to_filter.find_first_set(); while (fidx >= 0) { std::map<unsigned,std::vector<ReductionView*> >::iterator finder = reduction_instances.find(fidx); #ifdef DEBUG_LEGION assert(finder != reduction_instances.end()); #endif for (std::vector<ReductionView*>::const_iterator it = finder->second.begin(); it != finder->second.end(); it++) if ((*it)->remove_nested_valid_ref(did)) delete (*it); reduction_instances.erase(finder); fidx = to_filter.find_next_set(fidx+1); } reduction_fields -= to_filter; } //-------------------------------------------------------------------------- void EquivalenceSet::apply_reductions(const FieldMask &reduce_mask, CopyFillAggregator *&aggregator, const RtEvent guard_event, Operation *op, const unsigned index, const bool trace_events) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!reduce_mask); assert(!set_expr->is_empty()); #endif int fidx = reduce_mask.find_first_set(); while (fidx >= 0) { std::map<unsigned,std::vector<ReductionView*> >::iterator finder = reduction_instances.find(fidx); #ifdef DEBUG_LEGION assert(finder != reduction_instances.end()); #endif // Find the target targets and record them for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { if (!it->second.is_set(fidx)) continue; // Shouldn't have any deferred views here InstanceView *dst_view = it->first->as_instance_view(); if (aggregator == NULL) aggregator = new CopyFillAggregator(runtime->forest, op, index, guard_event, trace_events); aggregator->record_reductions(dst_view, finder->second, fidx, fidx, set_expr); } // Remove the reduction views from those available for (std::vector<ReductionView*>::const_iterator it = finder->second.begin(); it != finder->second.end(); it++) if ((*it)->remove_nested_valid_ref(did)) delete (*it); reduction_instances.erase(finder); fidx = reduce_mask.find_next_set(fidx+1); } // Record that we advanced the version number in this case advance_version_numbers(reduce_mask); // These reductions have been applied so we are done reduction_fields -= reduce_mask; } //-------------------------------------------------------------------------- void EquivalenceSet::copy_out(const FieldMask &restricted_mask, const InstanceSet &src_instances, const std::vector<InstanceView*> &src_views, Operation *op, const unsigned index, CopyFillAggregator *&aggregator) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!restricted_mask); #endif if (set_expr->is_empty()) return; if (valid_instances.size() == 1) { // Only 1 destination FieldMaskSet<LogicalView>::const_iterator first = valid_instances.begin(); #ifdef DEBUG_LEGION assert(!(restricted_mask - first->second)); #endif InstanceView *dst_view = first->first->as_instance_view(); FieldMaskSet<LogicalView> srcs; for (unsigned idx = 0; idx < src_views.size(); idx++) { if (first->first == src_views[idx]) continue; const FieldMask overlap = src_instances[idx].get_valid_fields() & restricted_mask; if (!overlap) continue; srcs.insert(src_views[idx], overlap); } if (!srcs.empty()) { if (aggregator == NULL) aggregator = new CopyFillAggregator(runtime->forest, op, index, RtEvent::NO_RT_EVENT, true/*track*/); aggregator->record_updates(dst_view, srcs, restricted_mask, set_expr); } } else if (src_instances.size() == 1) { // Only 1 source #ifdef DEBUG_LEGION assert(!(restricted_mask - src_instances[0].get_valid_fields())); #endif FieldMaskSet<LogicalView> srcs; srcs.insert(src_views[0], restricted_mask); for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { if (it->first == src_views[0]) continue; const FieldMask overlap = it->second & restricted_mask; if (!overlap) continue; InstanceView *dst_view = it->first->as_instance_view(); if (aggregator == NULL) aggregator = new CopyFillAggregator(runtime->forest, op, index, RtEvent::NO_RT_EVENT, true/*track*/); aggregator->record_updates(dst_view, srcs, overlap, set_expr); } } else { // General case for cross-products for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { const FieldMask dst_overlap = it->second & restricted_mask; if (!dst_overlap) continue; InstanceView *dst_view = it->first->as_instance_view(); FieldMaskSet<LogicalView> srcs; for (unsigned idx = 0; idx < src_views.size(); idx++) { if (dst_view == src_views[idx]) continue; const FieldMask src_overlap = src_instances[idx].get_valid_fields() & dst_overlap; if (!src_overlap) continue; srcs.insert(src_views[idx], src_overlap); } if (!srcs.empty()) { if (aggregator == NULL) aggregator = new CopyFillAggregator(runtime->forest, op, index, RtEvent::NO_RT_EVENT, true/*track*/); aggregator->record_updates(dst_view, srcs, dst_overlap, set_expr); } } } } //-------------------------------------------------------------------------- void EquivalenceSet::copy_out(const FieldMask &restricted_mask, LogicalView *src_view, Operation *op, const unsigned index, CopyFillAggregator *&aggregator) const //-------------------------------------------------------------------------- { if (set_expr->is_empty()) return; FieldMaskSet<LogicalView> srcs; srcs.insert(src_view, restricted_mask); for (FieldMaskSet<LogicalView>::const_iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { if (it->first == src_view) continue; const FieldMask overlap = it->second & restricted_mask; if (!overlap) continue; InstanceView *dst_view = it->first->as_instance_view(); if (aggregator == NULL) aggregator = new CopyFillAggregator(runtime->forest, op, index, RtEvent::NO_RT_EVENT, true/*track*/); aggregator->record_updates(dst_view, srcs, overlap, set_expr); } } //-------------------------------------------------------------------------- void EquivalenceSet::advance_version_numbers(FieldMask advance_mask) //-------------------------------------------------------------------------- { std::vector<VersionID> to_remove; for (LegionMap<VersionID,FieldMask>::aligned::iterator it = version_numbers.begin(); it != version_numbers.end(); it++) { const FieldMask overlap = it->second & advance_mask; if (!overlap) continue; LegionMap<VersionID,FieldMask>::aligned::iterator finder = version_numbers.find(it->first + 1); if (finder == version_numbers.end()) version_numbers[it->first + 1] = overlap; else finder->second |= overlap; it->second -= overlap; if (!it->second) to_remove.push_back(it->first); advance_mask -= overlap; if (!advance_mask) break; } if (!to_remove.empty()) { for (std::vector<VersionID>::const_iterator it = to_remove.begin(); it != to_remove.end(); it++) version_numbers.erase(*it); } if (!!advance_mask) version_numbers[init_version] = advance_mask; } //-------------------------------------------------------------------------- void EquivalenceSet::perform_refinements(void) //-------------------------------------------------------------------------- { RtUserEvent to_trigger; FieldMaskSet<EquivalenceSet> to_perform; std::set<EquivalenceSet*> remote_first_refs; std::set<RtEvent> remote_subsets_informed; do { std::set<RtEvent> refinements_done; for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_perform.begin(); it != to_perform.end(); it++) { // Need the lock in read-only mode when doing the clone AutoLock eq(eq_lock,1,false/*exclusive*/); AddressSpaceID alt_space = it->first->clone_from(this, it->second); // If the user asked us to send it to a different node then do that if (alt_space != local_space) { RtUserEvent done_event = Runtime::create_rt_user_event(); Serializer rez; // No RezCheck here because we might need to forward it rez.serialize(it->first->did); rez.serialize(done_event); // Determine whether this is the inital refinement or not // VERY IMPORTANT! You cannot use the subsets data structure // to test this for the case where we constructed a KD-tree // to build intermediate nodes into the refinement tree to // avoid exceeding our maximum fanout. Instead we use the // remote_first_refs data structure to test this if (remote_first_refs.find(it->first) != remote_first_refs.end()) rez.serialize<bool>(true); // initial refinement else rez.serialize<bool>(false); // not initial refinement pack_state(rez, it->second); runtime->send_equivalence_set_remote_refinement( it->first->logical_owner_space, rez); refinements_done.insert(done_event); } } if (!refinements_done.empty()) { const RtEvent wait_on = Runtime::merge_events(refinements_done); wait_on.wait(); } AutoLock eq(eq_lock); #ifdef DEBUG_LEGION assert(is_logical_owner()); assert(waiting_event.exists()); assert(eq_state == REFINING_STATE); #endif // Add any new refinements to our set and record any // potentially complete fields FieldMask complete_mask; if (!to_perform.empty()) { #ifdef DEBUG_LEGION // These masks should be identical assert(refining_fields == to_perform.get_valid_mask()); #endif complete_mask = refining_fields; refining_fields.clear(); // References were added to these sets when they were added // to the pending refinement queue, if they are already here // then we can remove the duplicate reference, no need to // check for deletion since we know we hold another reference for (FieldMaskSet<EquivalenceSet>::const_iterator it = to_perform.begin(); it != to_perform.end(); it++) if (!subsets.insert(it->first, it->second)) it->first->remove_nested_resource_ref(did); to_perform.clear(); remote_first_refs.clear(); // See if there was anyone waiting for us to be done if (transition_event.exists()) { Runtime::trigger_event(transition_event); transition_event = RtUserEvent::NO_RT_USER_EVENT; } } #ifdef DEBUG_LEGION assert(!refining_fields); assert(!transition_event.exists()); #endif // Fields which are still being refined are not complete while (!!complete_mask) { if (!pending_refinements.empty()) { complete_mask -= pending_refinements.get_valid_mask(); if (!complete_mask) break; } if (!unrefined_remainders.empty()) { complete_mask -= unrefined_remainders.get_valid_mask(); if (!complete_mask) break; } if (!disjoint_partition_refinements.empty()) { // Make sure this is tight before we remove them disjoint_partition_refinements.tighten_valid_mask(); complete_mask -= disjoint_partition_refinements.get_valid_mask(); } // Only need one iteration of this loop break; } if (!!complete_mask) { FieldMaskSet<EquivalenceSet> complete_subsets; for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = complete_mask & it->second; if (!overlap) continue; complete_subsets.insert(it->first, overlap); } if (complete_subsets.size() > LEGION_MAX_BVH_FANOUT) { // Sort these info field mask sets LegionList<FieldSet<EquivalenceSet*> >::aligned field_sets; complete_subsets.compute_field_sets(complete_mask, field_sets); for (LegionList<FieldSet<EquivalenceSet*> >::aligned::const_iterator fit = field_sets.begin(); fit != field_sets.end(); fit++) { if (fit->elements.size() <= LEGION_MAX_BVH_FANOUT) continue; KDTree *tree = NULL; switch (set_expr->get_num_dims()) { #define KDDIM(DIM) \ case DIM: \ { \ tree = new KDNode<DIM>(set_expr, runtime, 0/*dim*/); \ break; \ } LEGION_FOREACH_N(KDDIM) #undef KDDIM default: assert(false); } // Refine the tree to make the new subsets std::vector<EquivalenceSet*> new_subsets( fit->elements.begin(), fit->elements.end()); #ifdef LEGION_MAX_BVH_DEPTH unsigned max_depth = 0; size_t bvh_ratio = new_subsets.size() / LEGION_MAX_BVH_FANOUT; while (bvh_ratio >>= 1) max_depth++; #else unsigned max_depth = new_subsets.size(); #endif if (tree->refine(new_subsets, fit->set_mask, max_depth)) { // Remove old references for (std::set<EquivalenceSet*>::const_iterator it = fit->elements.begin(); it != fit->elements.end(); it++) { bool found = false; for (std::vector<EquivalenceSet*>::const_iterator nit = new_subsets.begin(); nit != new_subsets.end(); nit++) { if ((*nit) != (*it)) continue; found = true; break; } // If the eq set is in the new set then there is nothing to do if (found) continue; // If it's not in the new set, then we need to remove its // fields from the existing subsets FieldMaskSet<EquivalenceSet>::iterator finder = subsets.find(*it); #ifdef DEBUG_LEGION assert(finder != subsets.end()); #endif finder.filter(fit->set_mask); if (!finder->second) { if (finder->first->remove_nested_resource_ref(did)) delete finder->first; subsets.erase(finder); } // Also remove it from the complete subsets finder = complete_subsets.find(*it); #ifdef DEBUG_LEGION assert(finder != complete_subsets.end()); #endif finder.filter(fit->set_mask); if (!finder->second) complete_subsets.erase(finder); } // Add new references for (std::vector<EquivalenceSet*>::const_iterator it = new_subsets.begin(); it != new_subsets.end(); it++) { if (subsets.insert(*it, fit->set_mask)) (*it)->add_nested_resource_ref(did); // Also add it to the complete subsets complete_subsets.insert(*it, fit->set_mask); } } // Clean up the tree delete tree; } } // If we're done refining then send updates to any // remote sets informing them of the complete set of subsets if (!remote_subsets.empty() && !complete_subsets.empty()) { for (std::set<AddressSpaceID>::const_iterator rit = remote_subsets.begin(); rit != remote_subsets.end(); rit++) { const RtUserEvent informed = Runtime::create_rt_user_event(); Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(informed); rez.serialize<size_t>(complete_subsets.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = complete_subsets.begin(); it != complete_subsets.end(); it++) { rez.serialize(it->first->did); rez.serialize(it->second); } } runtime->send_equivalence_set_subset_update(*rit, rez); remote_subsets_informed.insert(informed); } } // Clean out these entries from our data structures if (!valid_instances.empty()) { std::vector<LogicalView*> to_delete; for (FieldMaskSet<LogicalView>::iterator it = valid_instances.begin(); it != valid_instances.end(); it++) { it.filter(complete_mask); if (!it->second) to_delete.push_back(it->first); } if (!to_delete.empty()) { for (std::vector<LogicalView*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { valid_instances.erase(*it); if ((*it)->remove_nested_valid_ref(did)) delete (*it); } valid_instances.tighten_valid_mask(); } } if (!reduction_instances.empty() && !(reduction_fields * complete_mask)) { for (std::map<unsigned,std::vector<ReductionView*> >:: iterator rit = reduction_instances.begin(); rit != reduction_instances.end(); /*nothing*/) { if (complete_mask.is_set(rit->first)) { for (std::vector<ReductionView*>::const_iterator it = rit->second.begin(); it != rit->second.end(); it++) if ((*it)->remove_nested_valid_ref(did)) delete (*it); std::map<unsigned,std::vector<ReductionView*> >::iterator to_delete = rit++; reduction_instances.erase(to_delete); } else rit++; } reduction_fields -= complete_mask; } if (!restricted_instances.empty() && !(restricted_fields * complete_mask)) { std::vector<InstanceView*> to_delete; for (FieldMaskSet<InstanceView>::iterator it = restricted_instances.begin(); it != restricted_instances.end(); it++) { it.filter(complete_mask); if (!it->second) to_delete.push_back(it->first); } if (!to_delete.empty()) { for (std::vector<InstanceView*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { restricted_instances.erase(*it); if ((*it)->remove_nested_valid_ref(did)) delete (*it); } restricted_instances.tighten_valid_mask(); } restricted_fields -= complete_mask; } for (LegionMap<VersionID,FieldMask>::aligned::iterator it = version_numbers.begin(); it != version_numbers.end();/*nothing*/) { it->second -= complete_mask; if (!it->second) { LegionMap<VersionID,FieldMask>::aligned::iterator to_delete = it++; version_numbers.erase(to_delete); } else it++; } } // See if we have more refinements to do if (pending_refinements.empty()) { // Go back to the mapping state and trigger our done event eq_state = MAPPING_STATE; to_trigger = waiting_event; waiting_event = RtUserEvent::NO_RT_USER_EVENT; } else // there are more refinements to do so we go around again { #ifdef DEBUG_LEGION assert(!refining_fields); // should be empty prior to this #endif refining_fields = pending_refinements.get_valid_mask(); to_perform.swap(pending_refinements); remote_first_refs.swap(remote_first_refinements); } } while (!to_perform.empty()); #ifdef DEBUG_LEGION assert(to_trigger.exists()); #endif // Make sure that everyone is informed before we return if (!remote_subsets_informed.empty()) Runtime::trigger_event(to_trigger, Runtime::merge_events(remote_subsets_informed)); else Runtime::trigger_event(to_trigger); } //-------------------------------------------------------------------------- void EquivalenceSet::record_subset(EquivalenceSet *set, const FieldMask &set_mask) //-------------------------------------------------------------------------- { // This method is only called when adding extra levels to the // equivalence set BVH data structure in order to reduce large // fanout. We don't need the lock and we shouldn't have any // remote copies of this equivalence set #ifdef DEBUG_LEGION assert(is_logical_owner()); assert(!has_remote_instances()); #endif if (subsets.insert(set, set_mask)) set->add_nested_resource_ref(did); } //-------------------------------------------------------------------------- void EquivalenceSet::finalize_disjoint_refinement( DisjointPartitionRefinement *dis, const FieldMask &finalize_mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(unrefined_remainders.get_valid_mask() * finalize_mask); #endif // We're not going to be able to finish up this disjoint // partition refinement so restore this to the state // for normal traversal // Figure out if we finished refining or whether there // is still an unrefined remainder IndexPartNode *partition = dis->partition; if (!dis->is_refined()) { std::set<LegionColor> current_colors; const std::map<IndexSpaceNode*,EquivalenceSet*> &children = dis->get_children(); for (std::map<IndexSpaceNode*,EquivalenceSet*>::const_iterator it = children.begin(); it != children.end(); it++) current_colors.insert(it->first->color); // No matter what finish making all the children since making // disjoint partitions is a good thing if (partition->total_children == partition->max_linearized_color) { for (LegionColor color = 0; color < partition->total_children; color++) { if (current_colors.find(color) != current_colors.end()) continue; IndexSpaceNode *child = partition->get_child(color); if (child->is_empty()) continue; add_pending_refinement(child, finalize_mask, child, runtime->address_space); // Don't add this to the refinement as we might only be // finalizing for a subset of fields and the // DisjointPartitionRefinement should only store entries // for children that have been refined for all fields } } else { ColorSpaceIterator *itr = partition->color_space->create_color_space_iterator(); while (itr->is_valid()) { const LegionColor color = itr->yield_color(); if (current_colors.find(color) != current_colors.end()) continue; if (!partition->color_space->contains_color(color)) continue; IndexSpaceNode *child = partition->get_child(color); if (child->is_empty()) continue; add_pending_refinement(child, finalize_mask, child, runtime->address_space); // Don't add this to the refinement as we might only be // finalizing for a subset of fields and the // DisjointPartitionRefinement should only store entries // for children that have been refined for all fields } delete itr; } } if (!partition->is_complete()) { // We had all the children, but the partition is not // complete so we actually need to do the subtraction IndexSpaceExpression *diff_expr = runtime->forest->subtract_index_spaces(set_expr, partition->get_union_expression()); #ifdef DEBUG_LEGION assert((diff_expr != NULL) && !diff_expr->is_empty()); assert(unrefined_remainders.get_valid_mask() * finalize_mask); #endif if (unrefined_remainders.insert(diff_expr, finalize_mask)) diff_expr->add_expression_reference(); } } //-------------------------------------------------------------------------- void EquivalenceSet::filter_unrefined_remainders(FieldMask &to_filter, IndexSpaceExpression *expr) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!!to_filter); assert(!expr->is_empty()); #endif if (unrefined_remainders.empty()) return; if (to_filter * unrefined_remainders.get_valid_mask()) return; FieldMaskSet<IndexSpaceExpression> to_add; std::vector<IndexSpaceExpression*> to_delete; for (FieldMaskSet<IndexSpaceExpression>::iterator it = unrefined_remainders.begin(); it != unrefined_remainders.end(); it++) { const FieldMask overlap = to_filter & it->second; if (!overlap) continue; IndexSpaceExpression *remainder = runtime->forest->subtract_index_spaces(it->first, expr); if (!remainder->is_empty()) to_add.insert(remainder, overlap); it.filter(overlap); if (!it->second) to_delete.push_back(it->first); to_filter -= overlap; if (!to_filter) break; } if (!to_delete.empty()) { for (std::vector<IndexSpaceExpression*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) { unrefined_remainders.erase(*it); if ((*it)->remove_expression_reference()) delete (*it); } } if (!to_add.empty()) { for (FieldMaskSet<IndexSpaceExpression>::const_iterator it = to_add.begin(); it != to_add.end(); it++) if (unrefined_remainders.insert(it->first, it->second)) it->first->add_expression_reference(); } } //-------------------------------------------------------------------------- void EquivalenceSet::send_equivalence_set(AddressSpaceID target) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(is_owner()); // We should have had a request for this already assert(!has_remote_instance(target)); #endif update_remote_instances(target); Serializer rez; { RezCheck z(rez); rez.serialize(did); // There be dragons here! // In the case where we first make a new equivalence set on a // remote node that is about to be the owner, we can't mark it // as the owner until it receives all an unpack_state or // unpack_migration message which provides it valid meta-data // Therefore we'll tell it that we're the owner which will // create a cycle in the forwarding graph. This won't matter for // unpack_migration as it's going to overwrite the data in the // equivalence set anyway, but for upack_state, we'll need to // recognize when to break the cycle. Effectively whenever we // send an update to a remote node that we can tell has never // been the owner before (and therefore can't have migrated) // we know that we should just do the unpack there. This will // break the cycle and allow forward progress. Analysis messages // may go round and round a few times, but they have lower // priority and therefore shouldn't create an livelock. { AutoLock eq(eq_lock,1,false/*exclusive*/); if (target == logical_owner_space) rez.serialize(local_space); else rez.serialize(logical_owner_space); } set_expr->pack_expression(rez, target); if (index_space_node != NULL) rez.serialize(index_space_node->handle); else rez.serialize(IndexSpace::NO_SPACE); } runtime->send_equivalence_set_response(target, rez); } //-------------------------------------------------------------------------- EquivalenceSet* EquivalenceSet::add_pending_refinement( IndexSpaceExpression *expr, const FieldMask &mask, IndexSpaceNode *node, AddressSpaceID source) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(is_logical_owner()); #endif // See if we already have a subset with this expression EquivalenceSet *subset = NULL; if ((subset_exprs == NULL) && !subsets.empty()) { // Fill in the data structure if it hasn't already been done // e.g. due to migration subset_exprs = new std::map<IndexSpaceExpression*,EquivalenceSet*>(); for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) (*subset_exprs)[it->first->set_expr] = it->first; } if (subset_exprs != NULL) { std::map<IndexSpaceExpression*,EquivalenceSet*>::const_iterator finder = subset_exprs->find(expr); if (finder != subset_exprs->end()) subset = finder->second; } if (subset == NULL) { // Make a new subset subset = new EquivalenceSet(runtime, runtime->get_available_distributed_id(), local_space, source, expr, node, true/*register*/); if (subset_exprs == NULL) subset_exprs = new std::map<IndexSpaceExpression*,EquivalenceSet*>(); // Save it in the set (*subset_exprs)[expr] = subset; if (pending_refinements.insert(subset, mask)) subset->add_nested_resource_ref(did); // If this is going to be a remote first refinement record it if (source != local_space) remote_first_refinements.insert(subset); } else { // We should not have this subset already for these fields #ifdef DEBUG_LEGION FieldMaskSet<EquivalenceSet>::const_iterator finder = subsets.find(subset); assert((finder == subsets.end()) || (finder->second * mask)); finder = pending_refinements.find(subset); assert((finder == pending_refinements.end()) || (finder->second * mask)); #endif if (pending_refinements.insert(subset, mask)) subset->add_nested_resource_ref(did); } // Launch the refinement task if there isn't one already running if (eq_state == MAPPING_STATE) { #ifdef DEBUG_LEGION assert(!transition_event.exists()); assert(!waiting_event.exists()); assert(!refining_fields); // should be empty #endif waiting_event = Runtime::create_rt_user_event(); eq_state = REFINING_STATE; // Launch the refinement task to be performed RefinementTaskArgs args(this); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY); } return subset; } //-------------------------------------------------------------------------- void EquivalenceSet::process_subset_request(AddressSpaceID source, RtUserEvent deferral_event) //-------------------------------------------------------------------------- { AutoTryLock eq(eq_lock); if (!eq.has_lock()) { // We didn't get the lock so build a continuation // We need a name for our completion event that we can use for // the atomic compare and swap below if (!deferral_event.exists()) { // If we haven't already been deferred then we need to // add ourselves to the back of the list of deferrals deferral_event = Runtime::create_rt_user_event(); const RtEvent continuation_pre = chain_deferral_events(deferral_event); DeferSubsetRequestArgs args(this, source, deferral_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, continuation_pre); } else { // We've already been deferred and our precondition has already // triggered so just launch ourselves again whenever the lock // should be ready to try again DeferSubsetRequestArgs args(this, source, deferral_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, eq.try_next()); } return; } if (!is_logical_owner()) { // If we're not the owner anymore then forward on the request Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize(source); } runtime->send_equivalence_set_subset_request(logical_owner_space, rez); if (deferral_event.exists()) Runtime::trigger_event(deferral_event); return; } // If we arrived back at ourself after we were made the owner // then there is nothing for us to do, similarly if this is a // duplicate then there is nothing for us to do if ((source == local_space) || (remote_subsets.find(source) != remote_subsets.end())) { if (deferral_event.exists()) Runtime::trigger_event(deferral_event); return; } // If we're in the process of doing a refinement, wait for // that to be done before we do anything else if (eq_state == REFINING_STATE) { #ifdef DEBUG_LEGION assert(waiting_event.exists()); #endif DeferSubsetRequestArgs args(this, source, deferral_event); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, waiting_event); return; } // Record the remote subsets remote_subsets.insert(source); // Remote copies of the subsets either have to be empty or a // full copy of the subsets with no partial refinements if (!subsets.empty()) { FieldMask complete_mask = subsets.get_valid_mask(); // Any fields for which we have partial refinements cannot be sent yet if (!pending_refinements.empty()) complete_mask -= pending_refinements.get_valid_mask(); if (!!refining_fields) complete_mask -= refining_fields; if (!unrefined_remainders.empty()) complete_mask -= unrefined_remainders.get_valid_mask(); if (!!disjoint_partition_refinements.empty()) complete_mask -= disjoint_partition_refinements.get_valid_mask(); if (!!complete_mask) { Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize<size_t>(subsets.size()); for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) { const FieldMask overlap = it->second & complete_mask; if (!!overlap) { rez.serialize(it->first->did); rez.serialize(overlap); } else rez.serialize<DistributedID>(0); } } runtime->send_equivalence_set_subset_response(source, rez); if (deferral_event.exists()) Runtime::trigger_event(deferral_event); return; } } // If we make it here then we just send a message with an // empty set of subsets to allow forward progress to be made Serializer rez; { RezCheck z(rez); rez.serialize(did); rez.serialize<size_t>(0); } runtime->send_equivalence_set_subset_response(source, rez); if (deferral_event.exists()) Runtime::trigger_event(deferral_event); } //-------------------------------------------------------------------------- void EquivalenceSet::process_subset_response(Deserializer &derez) //-------------------------------------------------------------------------- { size_t num_subsets; derez.deserialize(num_subsets); FieldMaskSet<EquivalenceSet> new_subsets; if (num_subsets > 0) { std::set<RtEvent> ready_events; for (unsigned idx = 0; idx < num_subsets; idx++) { DistributedID subdid; derez.deserialize(subdid); if (subdid == 0) continue; RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(subdid, ready); if (ready.exists()) ready_events.insert(ready); FieldMask mask; derez.deserialize(mask); new_subsets.insert(set, mask); } if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists()) wait_on.wait(); } } AutoLock eq(eq_lock); if (is_logical_owner()) { // If we've since been made the logical owner then there // should be nothing else for us to do #ifdef DEBUG_LEGION assert(new_subsets.empty()); #endif return; } else if (eq_state == PENDING_VALID_STATE) { #ifdef DEBUG_LEGION assert(subsets.empty()); assert(transition_event.exists()); assert(!transition_event.has_triggered()); #endif if (!new_subsets.empty()) { subsets.swap(new_subsets); // Add the references for (FieldMaskSet<EquivalenceSet>::const_iterator it = subsets.begin(); it != subsets.end(); it++) it->first->add_nested_resource_ref(did); } // Update the state eq_state = VALID_STATE; // Trigger the transition state to wake up any waiters Runtime::trigger_event(transition_event); transition_event = RtUserEvent::NO_RT_USER_EVENT; } } //-------------------------------------------------------------------------- void EquivalenceSet::process_subset_update(Deserializer &derez) //-------------------------------------------------------------------------- { size_t num_subsets; derez.deserialize(num_subsets); if (num_subsets == 0) return; std::vector<EquivalenceSet*> new_subsets(num_subsets); LegionVector<FieldMask>::aligned new_masks(num_subsets); std::set<RtEvent> wait_for; for (unsigned idx = 0; idx < num_subsets; idx++) { DistributedID subdid; derez.deserialize(subdid); RtEvent ready; new_subsets[idx] = runtime->find_or_request_equivalence_set(subdid, ready); if (ready.exists()) wait_for.insert(ready); derez.deserialize(new_masks[idx]); } if (!wait_for.empty()) { const RtEvent wait_on = Runtime::merge_events(wait_for); wait_on.wait(); } AutoLock eq(eq_lock); if (is_logical_owner()) // If we've become the logical owner there is nothing to do return; #ifdef DEBUG_LEGION assert(eq_state == VALID_STATE); assert(!transition_event.exists()); #endif for (unsigned idx = 0; idx < num_subsets; idx++) if (subsets.insert(new_subsets[idx], new_masks[idx])) new_subsets[idx]->add_nested_resource_ref(did); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_refinement(const void *args) //-------------------------------------------------------------------------- { const RefinementTaskArgs *rargs = (const RefinementTaskArgs*)args; rargs->target->perform_refinements(); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_remote_references(const void *args) //-------------------------------------------------------------------------- { const RemoteRefTaskArgs *rargs = (const RemoteRefTaskArgs*)args; if (rargs->done_event.exists()) { LocalReferenceMutator mutator; if (rargs->add_references) { for (std::map<LogicalView*,unsigned>::const_iterator it = rargs->refs->begin(); it != rargs->refs->end(); it++) it->first->add_nested_valid_ref(rargs->did, &mutator, it->second); } else { for (std::map<LogicalView*,unsigned>::const_iterator it = rargs->refs->begin(); it != rargs->refs->end(); it++) it->first->remove_nested_valid_ref(rargs->did, &mutator,it->second); } const RtEvent done_pre = mutator.get_done_event(); Runtime::trigger_event(rargs->done_event, done_pre); } else { if (rargs->add_references) { for (std::map<LogicalView*,unsigned>::const_iterator it = rargs->refs->begin(); it != rargs->refs->end(); it++) it->first->add_nested_valid_ref(rargs->did, NULL, it->second); } else { for (std::map<LogicalView*,unsigned>::const_iterator it = rargs->refs->begin(); it != rargs->refs->end(); it++) it->first->remove_nested_valid_ref(rargs->did, NULL, it->second); } } delete rargs->refs; } //-------------------------------------------------------------------------- EquivalenceSet::DeferRayTraceArgs::DeferRayTraceArgs(EquivalenceSet *s, RayTracer *t, IndexSpaceExpression *e, IndexSpace h, AddressSpaceID o, RtUserEvent d, RtUserEvent def, const FieldMask &m, bool local, bool is_expr_s, IndexSpace expr_h, IndexSpaceExprID expr_i) : LgTaskArgs<DeferRayTraceArgs>(implicit_provenance), set(s), target(t), expr(local ? e : NULL), handle(h), origin(o), done(d), deferral(def), ray_mask(new FieldMask(m)), expr_handle(expr_h), expr_id(expr_i), is_local(local), is_expr_space(is_expr_s) //-------------------------------------------------------------------------- { if (local) expr->add_expression_reference(); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_ray_trace(const void *args, Runtime *runtime) //-------------------------------------------------------------------------- { const DeferRayTraceArgs *dargs = (const DeferRayTraceArgs*)args; // See if we need to load the expression or not IndexSpaceExpression *expr = (dargs->is_local) ? dargs->expr : (dargs->is_expr_space) ? runtime->forest->get_node(dargs->expr_handle) : runtime->forest->find_remote_expression(dargs->expr_id); dargs->set->ray_trace_equivalence_sets(dargs->target, expr, *(dargs->ray_mask), dargs->handle, dargs->origin, dargs->done, dargs->deferral); // Clean up our ray mask delete dargs->ray_mask; // Remove our expression reference too if (dargs->is_local && dargs->expr->remove_expression_reference()) delete dargs->expr; } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_ray_trace_finish(const void *args) //-------------------------------------------------------------------------- { const DeferRayTraceFinishArgs *dargs = (const DeferRayTraceFinishArgs*)args; std::set<RtEvent> done_events; for (FieldMaskSet<EquivalenceSet>::const_iterator it = dargs->to_traverse->begin(); it != dargs->to_traverse->end(); it++) { RtUserEvent done = Runtime::create_rt_user_event(); std::map<EquivalenceSet*,IndexSpaceExpression*>::const_iterator finder = dargs->exprs->find(it->first); #ifdef DEBUG_LEGION assert(finder != dargs->exprs->end()); #endif const IndexSpace subset_handle = (dargs->handle.exists() && (finder->second->get_volume() == dargs->volume)) ? dargs->handle : IndexSpace::NO_SPACE; it->first->ray_trace_equivalence_sets(dargs->target, finder->second, it->second, subset_handle, dargs->source, done); done_events.insert(done); } if (!done_events.empty()) Runtime::trigger_event(dargs->done, Runtime::merge_events(done_events)); else Runtime::trigger_event(dargs->done); delete dargs->to_traverse; delete dargs->exprs; } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_subset_request(const void *args) //-------------------------------------------------------------------------- { const DeferSubsetRequestArgs *dargs = (const DeferSubsetRequestArgs*)args; dargs->set->process_subset_request(dargs->source, dargs->deferral); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_make_owner(const void *args) //-------------------------------------------------------------------------- { const DeferMakeOwnerArgs *dargs = (const DeferMakeOwnerArgs*)args; if (dargs->set->make_owner(dargs->new_subsets, dargs->done, true/*need lock*/)) delete dargs->new_subsets; } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_merge_or_forward(const void *args) //-------------------------------------------------------------------------- { const DeferMergeOrForwardArgs *dargs = (const DeferMergeOrForwardArgs*)args; dargs->set->merge_or_forward(dargs->done, dargs->initial, *(dargs->views), *(dargs->reductions), *(dargs->restricted), *(dargs->versions)); delete dargs->views; delete dargs->reductions; delete dargs->restricted; delete dargs->versions; } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_equivalence_set_request( Deserializer &derez, Runtime *runtime, AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); DistributedCollectable *dc = runtime->find_distributed_collectable(did); #ifdef DEBUG_LEGION EquivalenceSet *set = dynamic_cast<EquivalenceSet*>(dc); assert(set != NULL); #else EquivalenceSet *set = static_cast<EquivalenceSet*>(dc); #endif set->send_equivalence_set(source); } //-------------------------------------------------------------------------- EquivalenceSet::DeferResponseArgs::DeferResponseArgs(DistributedID id, AddressSpaceID src, AddressSpaceID log, IndexSpaceExpression *ex, bool local, bool is_space, IndexSpace expr_h, IndexSpaceExprID xid, IndexSpace h) : LgTaskArgs<DeferResponseArgs>(implicit_provenance), did(id), source(src), logical_owner(log), expr(ex), is_local(local), is_index_space(is_space), expr_handle(expr_h), expr_id(xid), handle(h) //-------------------------------------------------------------------------- { if (is_local) expr->add_expression_reference(); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_equivalence_set_response( Deserializer &derez, Runtime *runtime, AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); AddressSpaceID logical_owner; derez.deserialize(logical_owner); bool is_local, is_index_space; IndexSpace expr_handle; IndexSpaceExprID expr_id; RtEvent wait_for; IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez, runtime->forest, source, is_local, is_index_space, expr_handle, expr_id, wait_for); IndexSpace handle; derez.deserialize(handle); // We only actually need the index space node on the owner and the // logical owner otherwise we can skip it IndexSpaceNode *node = NULL; RtEvent wait_on; if (handle.exists() && (logical_owner == runtime->address_space)) node = runtime->forest->get_node(handle, &wait_on); // Defer this if the index space expression isn't ready yet if (wait_for.exists() || wait_on.exists()) { RtEvent precondition; if (wait_for.exists()) { if (wait_on.exists()) precondition = Runtime::merge_events(wait_for, wait_on); else precondition = wait_for; } else precondition = wait_on; if (precondition.exists() && !precondition.has_triggered()) { DeferResponseArgs args(did, source, logical_owner, expr, is_local, is_index_space, expr_handle, expr_id, handle); runtime->issue_runtime_meta_task(args, LG_LATENCY_MESSAGE_PRIORITY, precondition); return; } // If we fall through we need to refetch things that we didn't get if (expr == NULL) expr = is_index_space ? runtime->forest->get_node(expr_handle) : runtime->forest->find_remote_expression(expr_id); if ((node == NULL) && handle.exists() && (logical_owner == runtime->address_space)) node = runtime->forest->get_node(handle); } void *location; EquivalenceSet *set = NULL; if (runtime->find_pending_collectable_location(did, location)) set = new(location) EquivalenceSet(runtime, did, source, logical_owner, expr, node, false/*register now*/); else set = new EquivalenceSet(runtime, did, source, logical_owner, expr, node, false/*register now*/); // Once construction is complete then we do the registration set->register_with_runtime(NULL/*no remote registration needed*/); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_deferred_response(const void *args, Runtime *runtime) //-------------------------------------------------------------------------- { const DeferResponseArgs *dargs = (const DeferResponseArgs*)args; IndexSpaceExpression *expr = (dargs->is_local) ? dargs->expr : (dargs->is_index_space) ? runtime->forest->get_node(dargs->expr_handle) : runtime->forest->find_remote_expression(dargs->expr_id); IndexSpaceNode *node = NULL; if (dargs->handle.exists() && (dargs->logical_owner == runtime->address_space)) node = runtime->forest->get_node(dargs->handle); void *location; EquivalenceSet *set = NULL; if (runtime->find_pending_collectable_location(dargs->did, location)) set = new(location) EquivalenceSet(runtime, dargs->did, dargs->source, dargs->logical_owner, expr, node, false/*register now*/); else set = new EquivalenceSet(runtime, dargs->did, dargs->source, dargs->logical_owner, expr, node, false/*register now*/); // Once construction is complete then we do the registration set->register_with_runtime(NULL/*no remote registration needed*/); // Remove our expression reference too if (dargs->is_local && dargs->expr->remove_expression_reference()) delete dargs->expr; } //-------------------------------------------------------------------------- /*static*/void EquivalenceSet::handle_deferred_remove_refs(const void *args) //-------------------------------------------------------------------------- { const DeferRemoveRefArgs *dargs = (const DeferRemoveRefArgs*)args; for (std::vector<IndexSpaceExpression*>::const_iterator it = dargs->references->begin(); it != dargs->references->end(); it++) if ((*it)->remove_expression_reference()) delete (*it); delete dargs->references; } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_subset_request( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); AddressSpaceID source; derez.deserialize(source); if (ready.exists() && !ready.has_triggered()) ready.wait(); set->process_subset_request(source, RtUserEvent::NO_RT_USER_EVENT); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_subset_response( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); DistributedCollectable *dc = runtime->find_distributed_collectable(did); #ifdef DEBUG_LEGION EquivalenceSet *set = dynamic_cast<EquivalenceSet*>(dc); assert(set != NULL); #else EquivalenceSet *set = static_cast<EquivalenceSet*>(dc); #endif set->process_subset_response(derez); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_subset_update( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); RtUserEvent to_trigger; derez.deserialize(to_trigger); DistributedCollectable *dc = runtime->find_distributed_collectable(did); #ifdef DEBUG_LEGION EquivalenceSet *set = dynamic_cast<EquivalenceSet*>(dc); assert(set != NULL); #else EquivalenceSet *set = static_cast<EquivalenceSet*>(dc); #endif set->process_subset_update(derez); Runtime::trigger_event(to_trigger); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_ray_trace_request( Deserializer &derez, Runtime *runtime, AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); RayTracer *target; derez.deserialize(target); bool is_local, is_expr_space; IndexSpace expr_handle; IndexSpaceExprID expr_id; RtEvent expr_ready; IndexSpaceExpression *expr = IndexSpaceExpression::unpack_expression(derez, runtime->forest, source, is_local, is_expr_space, expr_handle, expr_id, expr_ready); FieldMask ray_mask; derez.deserialize(ray_mask); IndexSpace handle; derez.deserialize(handle); AddressSpaceID origin; derez.deserialize(origin); RtUserEvent done_event; derez.deserialize(done_event); if (ready.exists() || expr_ready.exists()) { const RtEvent defer = Runtime::merge_events(ready, expr_ready); if (defer.exists() && !defer.has_triggered()) { // We need to defer this until things are ready DeferRayTraceArgs args(set, target, expr, handle, origin, done_event, RtUserEvent::NO_RT_USER_EVENT, ray_mask, is_local, is_expr_space, expr_handle, expr_id); runtime->issue_runtime_meta_task(args, LG_THROUGHPUT_DEFERRED_PRIORITY, defer); return; } if (expr_ready.exists()) expr = (is_expr_space) ? runtime->forest->get_node(expr_handle) : runtime->forest->find_remote_expression(expr_id); // Fall through and actually do the operation now } set->ray_trace_equivalence_sets(target, expr, ray_mask, handle, origin, done_event); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_ray_trace_response( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); FieldMask eq_mask; derez.deserialize(eq_mask); RayTracer *target; derez.deserialize(target); RtUserEvent done_event; derez.deserialize(done_event); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); if (ready.exists() && !ready.has_triggered()) { target->record_pending_equivalence_set(set, eq_mask); Runtime::trigger_event(done_event, ready); } else { target->record_equivalence_set(set, eq_mask); Runtime::trigger_event(done_event); } } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_migration(Deserializer &derez, Runtime *runtime, AddressSpaceID source) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); RtUserEvent done; derez.deserialize(done); LocalReferenceMutator mutator; if (ready.exists() && !ready.has_triggered()) ready.wait(); set->unpack_migration(derez, source, done); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_owner_update(Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); AddressSpaceID new_owner; derez.deserialize(new_owner); RtUserEvent done; derez.deserialize(done); if (ready.exists() && !ready.has_triggered()) ready.wait(); set->update_owner(new_owner); Runtime::trigger_event(done); } //-------------------------------------------------------------------------- /*static*/ void EquivalenceSet::handle_remote_refinement( Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did,ready); if (ready.exists() && !ready.has_triggered()) ready.wait(); set->unpack_state(derez); } ///////////////////////////////////////////////////////////// // Version Manager ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- VersionManager::VersionManager(RegionTreeNode *n, ContextID c) : ctx(c), node(n), runtime(n->context->runtime) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- VersionManager::VersionManager(const VersionManager &rhs) : ctx(rhs.ctx), node(rhs.node), runtime(rhs.runtime) //-------------------------------------------------------------------------- { // should never be called assert(false); } //-------------------------------------------------------------------------- VersionManager::~VersionManager(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- VersionManager& VersionManager::operator=(const VersionManager &rhs) //-------------------------------------------------------------------------- { // should never be called assert(false); return *this; } //-------------------------------------------------------------------------- void VersionManager::reset(void) //-------------------------------------------------------------------------- { AutoLock m_lock(manager_lock); if (!equivalence_sets.empty()) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = equivalence_sets.begin(); it != equivalence_sets.end(); it++) { if (it->first->remove_base_resource_ref(VERSION_MANAGER_REF)) delete it->first; } equivalence_sets.clear(); } #ifdef DEBUG_LEGION assert(waiting_infos.empty()); assert(equivalence_sets_ready.empty()); #endif } //-------------------------------------------------------------------------- RtEvent VersionManager::perform_versioning_analysis(InnerContext *context, VersionInfo *version_info, RegionNode *region_node, const FieldMask &version_mask, Operation *op) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(node == region_node); #endif // If we don't have equivalence classes for this region yet we // either need to compute them or request them from the owner FieldMask remaining_mask(version_mask); bool has_waiter = false; { AutoLock m_lock(manager_lock,1,false/*exclusive*/); // Check to see if any computations of equivalence sets are in progress // If so we'll skip out early and go down the slow path which should // be a fairly rare thing to do if (!equivalence_sets_ready.empty()) { for (LegionMap<RtUserEvent,FieldMask>::aligned::const_iterator it = equivalence_sets_ready.begin(); it != equivalence_sets_ready.end(); it++) { if (remaining_mask * it->second) continue; // Skip out earlier if we have at least one thing to wait // for since we're going to have to go down the slow path has_waiter = true; break; } } // If we have a waiter, then don't bother doing this if (!has_waiter) { // Get any fields that are already ready if (version_info != NULL) { if (!(version_mask * equivalence_sets.get_valid_mask())) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = equivalence_sets.begin(); it != equivalence_sets.end(); it++) { const FieldMask overlap = it->second & version_mask; if (!overlap) continue; version_info->record_equivalence_set(this, it->first, overlap); } } } remaining_mask -= equivalence_sets.get_valid_mask(); // If we got all our fields then we are done if (!remaining_mask) return RtEvent::NO_RT_EVENT; } } // Retake the lock in exclusive mode and make sure we don't lose the race RtUserEvent compute_event; std::set<RtEvent> wait_on; { FieldMask waiting_mask; AutoLock m_lock(manager_lock); if (!equivalence_sets_ready.empty()) { for (LegionMap<RtUserEvent,FieldMask>::aligned::const_iterator it = equivalence_sets_ready.begin(); it != equivalence_sets_ready.end(); it++) { const FieldMask overlap = remaining_mask & it->second; if (!overlap) continue; wait_on.insert(it->first); waiting_mask |= overlap; } if (!!waiting_mask) remaining_mask -= waiting_mask; } // Get any fields that are already ready // Have to do this after looking for pending equivalence sets // to make sure we don't have pending outstanding requests if (!(remaining_mask * equivalence_sets.get_valid_mask())) { if (version_info != NULL) { for (FieldMaskSet<EquivalenceSet>::const_iterator it = equivalence_sets.begin(); it != equivalence_sets.end(); it++) { const FieldMask overlap = it->second & remaining_mask; if (!overlap) continue; version_info->record_equivalence_set(this, it->first, overlap); } } remaining_mask -= equivalence_sets.get_valid_mask(); // If we got all our fields here and we're not waiting // on any other computations then we're done if (!remaining_mask && wait_on.empty()) return RtEvent::NO_RT_EVENT; } // If we still have remaining fields then we need to // do this computation ourselves if (!!remaining_mask) { compute_event = Runtime::create_rt_user_event(); equivalence_sets_ready[compute_event] = remaining_mask; wait_on.insert(compute_event); waiting_mask |= remaining_mask; } #ifdef DEBUG_LEGION assert(!!waiting_mask); #endif // Record that our version info is waiting for these fields if (version_info != NULL) waiting_infos.insert(version_info, waiting_mask); } if (compute_event.exists()) { IndexSpaceExpression *expr = region_node->row_source; IndexSpace handle = region_node->row_source->handle; RtEvent ready = context->compute_equivalence_sets(this, region_node->get_tree_id(), handle, expr, remaining_mask, runtime->address_space); if (ready.exists() && !ready.has_triggered()) { // Launch task to finalize the sets once they are ready LgFinalizeEqSetsArgs args(this, compute_event, op->get_unique_op_id()); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, ready); } else finalize_equivalence_sets(compute_event); } return Runtime::merge_events(wait_on); } //-------------------------------------------------------------------------- void VersionManager::record_equivalence_set(EquivalenceSet *set, const FieldMask &mask) //-------------------------------------------------------------------------- { AutoLock m_lock(manager_lock); if (equivalence_sets.insert(set, mask)) set->add_base_resource_ref(VERSION_MANAGER_REF); } //-------------------------------------------------------------------------- void VersionManager::record_pending_equivalence_set(EquivalenceSet *set, const FieldMask &mask) //-------------------------------------------------------------------------- { AutoLock m_lock(manager_lock); pending_equivalence_sets.insert(set, mask); } //-------------------------------------------------------------------------- void VersionManager::finalize_equivalence_sets(RtUserEvent done_event) //-------------------------------------------------------------------------- { std::set<RtEvent> done_preconditions; { AutoLock m_lock(manager_lock); LegionMap<RtUserEvent,FieldMask>::aligned::iterator finder = equivalence_sets_ready.find(done_event); #ifdef DEBUG_LEGION assert(finder != equivalence_sets_ready.end()); #endif // See if there are any other events with overlapping fields, // if there are then we can't actually move over any pending // equivalence sets for those fields yet since we don't know // which are ours, just record dependences on those events if (equivalence_sets_ready.size() > 1) { FieldMask aliased; for (LegionMap<RtUserEvent,FieldMask>::aligned::const_iterator it = equivalence_sets_ready.begin(); it != equivalence_sets_ready.end(); it++) { if (it->first == done_event) continue; const FieldMask overlap = it->second & finder->second; if (!overlap) continue; done_preconditions.insert(it->first); aliased |= overlap; } if (!!aliased) finder->second -= aliased; } // If there are any pending equivalence sets, move them into // the actual equivalence sets if (!pending_equivalence_sets.empty() && !(finder->second * pending_equivalence_sets.get_valid_mask())) { std::vector<EquivalenceSet*> to_delete; for (FieldMaskSet<EquivalenceSet>::iterator it = pending_equivalence_sets.begin(); it != pending_equivalence_sets.end(); it++) { // Once it's valid for any field then it's valid for all of them if (it->second * finder->second) continue; if (equivalence_sets.insert(it->first, it->second)) it->first->add_base_resource_ref(VERSION_MANAGER_REF); to_delete.push_back(it->first); } if (!to_delete.empty()) { if (to_delete.size() < pending_equivalence_sets.size()) { for (std::vector<EquivalenceSet*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) pending_equivalence_sets.erase(*it); pending_equivalence_sets.tighten_valid_mask(); } else pending_equivalence_sets.clear(); } } if (!waiting_infos.empty() && !(waiting_infos.get_valid_mask() * finder->second)) { std::vector<VersionInfo*> to_delete; for (FieldMaskSet<VersionInfo>::iterator vit = waiting_infos.begin(); vit != waiting_infos.end(); vit++) { const FieldMask info_overlap = vit->second & finder->second; if (!info_overlap) continue; for (FieldMaskSet<EquivalenceSet>::const_iterator it = equivalence_sets.begin(); it != equivalence_sets.end(); it++) { const FieldMask overlap = info_overlap & it->second; if (!overlap) continue; vit->first->record_equivalence_set(this, it->first, overlap); } vit.filter(info_overlap); if (!vit->second) to_delete.push_back(vit->first); } if (!to_delete.empty()) { for (std::vector<VersionInfo*>::const_iterator it = to_delete.begin(); it != to_delete.end(); it++) waiting_infos.erase(*it); } } equivalence_sets_ready.erase(finder); } if (!done_preconditions.empty()) Runtime::trigger_event(done_event, Runtime::merge_events(done_preconditions)); else Runtime::trigger_event(done_event); } //-------------------------------------------------------------------------- RtEvent VersionManager::record_stale_sets( FieldMaskSet<EquivalenceSet> &stale_sets) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(!stale_sets.empty()); #endif RtUserEvent compute_event; { FieldMask update_mask; AutoLock m_lock(manager_lock); // See which of our stale sets are still in the valid set, if they // are then remove their fields, otherwise record that we don't need // to update them for (FieldMaskSet<EquivalenceSet>::iterator it = stale_sets.begin(); it != stale_sets.end(); it++) { FieldMaskSet<EquivalenceSet>::iterator finder = equivalence_sets.find(it->first); if (finder != equivalence_sets.end()) { const FieldMask need_refinement = it->second & finder->second; if (!!need_refinement) { update_mask |= need_refinement; finder.filter(need_refinement); if (!finder->second) // Reference flows back with stale sets equivalence_sets.erase(finder); else // Add a reference to keep the eq set live until we're done it->first->add_base_resource_ref(VERSION_MANAGER_REF); it.filter(~need_refinement); #ifdef DEBUG_LEGION assert(!!it->second); #endif continue; } } it.clear(); } if (!update_mask) return RtEvent::NO_RT_EVENT; compute_event = Runtime::create_rt_user_event(); equivalence_sets_ready[compute_event] = update_mask; } // For these equivalence sets we need to perform additional ray // traces to get the new refineemnts of the sets std::set<RtEvent> preconditions; for (FieldMaskSet<EquivalenceSet>::iterator it = stale_sets.begin(); it != stale_sets.end(); it++) { // Skip any sets which didn't have valid fields if (!it->second) continue; RtUserEvent refresh_done = Runtime::create_rt_user_event(); it->first->refresh_refinement(this, it->second, refresh_done); preconditions.insert(refresh_done); // Remove the reference that we are holding if (it->first->remove_base_resource_ref(VERSION_MANAGER_REF)) delete it->first; } // Now launch a finalize task to complete the update if (!preconditions.empty()) { const RtEvent precondition = Runtime::merge_events(preconditions); if (precondition.exists() && !precondition.has_triggered()) { LgFinalizeEqSetsArgs args(this, compute_event, implicit_provenance); runtime->issue_runtime_meta_task(args, LG_LATENCY_DEFERRED_PRIORITY, precondition); return compute_event; } } // If we make it here we can do the finalize call now finalize_equivalence_sets(compute_event); return RtEvent::NO_RT_EVENT; } //-------------------------------------------------------------------------- void VersionManager::print_physical_state(RegionTreeNode *node, const FieldMask &capture_mask, TreeStateLogger *logger) //-------------------------------------------------------------------------- { logger->log("Equivalence Sets:"); logger->down(); // TODO: log equivalence sets assert(false); logger->up(); } //-------------------------------------------------------------------------- /*static*/ void VersionManager::handle_finalize_eq_sets(const void *args) //-------------------------------------------------------------------------- { const LgFinalizeEqSetsArgs *fargs = (const LgFinalizeEqSetsArgs*)args; fargs->manager->finalize_equivalence_sets(fargs->compute); } //-------------------------------------------------------------------------- /*static*/ void VersionManager::handle_stale_update(Deserializer &derez, Runtime *runtime) //-------------------------------------------------------------------------- { DerezCheck z(derez); size_t num_sets; derez.deserialize(num_sets); FieldMaskSet<EquivalenceSet> stale_sets; std::set<RtEvent> ready_events; for (unsigned idx = 0; idx < num_sets; idx++) { DistributedID did; derez.deserialize(did); RtEvent ready; EquivalenceSet *set = runtime->find_or_request_equivalence_set(did, ready); FieldMask mask; derez.deserialize(mask); stale_sets.insert(set, mask); if (ready.exists() && !ready.has_triggered()) ready_events.insert(ready); } VersionManager *manager; derez.deserialize(manager); RtUserEvent done_event; derez.deserialize(done_event); if (!ready_events.empty()) { const RtEvent wait_on = Runtime::merge_events(ready_events); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); } const RtEvent done = manager->record_stale_sets(stale_sets); Runtime::trigger_event(done_event, done); } ///////////////////////////////////////////////////////////// // RegionTreePath ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- RegionTreePath::RegionTreePath(void) : min_depth(0), max_depth(0) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- void RegionTreePath::initialize(unsigned min, unsigned max) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(min <= max); #endif min_depth = min; max_depth = max; path.resize(max_depth+1, INVALID_COLOR); } //-------------------------------------------------------------------------- void RegionTreePath::register_child(unsigned depth, const LegionColor color) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(min_depth <= depth); assert(depth <= max_depth); #endif path[depth] = color; } //-------------------------------------------------------------------------- void RegionTreePath::record_aliased_children(unsigned depth, const FieldMask &mask) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(min_depth <= depth); assert(depth <= max_depth); #endif LegionMap<unsigned,FieldMask>::aligned::iterator finder = interfering_children.find(depth); if (finder == interfering_children.end()) interfering_children[depth] = mask; else finder->second |= mask; } //-------------------------------------------------------------------------- void RegionTreePath::clear(void) //-------------------------------------------------------------------------- { path.clear(); min_depth = 0; max_depth = 0; } #ifdef DEBUG_LEGION //-------------------------------------------------------------------------- bool RegionTreePath::has_child(unsigned depth) const //-------------------------------------------------------------------------- { assert(min_depth <= depth); assert(depth <= max_depth); return (path[depth] != INVALID_COLOR); } //-------------------------------------------------------------------------- LegionColor RegionTreePath::get_child(unsigned depth) const //-------------------------------------------------------------------------- { assert(min_depth <= depth); assert(depth <= max_depth); assert(has_child(depth)); return path[depth]; } #endif //-------------------------------------------------------------------------- const FieldMask* RegionTreePath::get_aliased_children(unsigned depth) const //-------------------------------------------------------------------------- { if (interfering_children.empty()) return NULL; LegionMap<unsigned,FieldMask>::aligned::const_iterator finder = interfering_children.find(depth); if (finder == interfering_children.end()) return NULL; return &(finder->second); } ///////////////////////////////////////////////////////////// // InstanceRef ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- InstanceRef::InstanceRef(bool comp) : ready_event(ApEvent::NO_AP_EVENT), manager(NULL), local(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InstanceRef::InstanceRef(const InstanceRef &rhs) : valid_fields(rhs.valid_fields), ready_event(rhs.ready_event), manager(rhs.manager), local(rhs.local) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InstanceRef::InstanceRef(PhysicalManager *man, const FieldMask &m,ApEvent r) : valid_fields(m), ready_event(r), manager(man), local(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InstanceRef::~InstanceRef(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InstanceRef& InstanceRef::operator=(const InstanceRef &rhs) //-------------------------------------------------------------------------- { valid_fields = rhs.valid_fields; ready_event = rhs.ready_event; local = rhs.local; manager = rhs.manager; return *this; } //-------------------------------------------------------------------------- bool InstanceRef::operator==(const InstanceRef &rhs) const //-------------------------------------------------------------------------- { if (valid_fields != rhs.valid_fields) return false; if (ready_event != rhs.ready_event) return false; if (manager != rhs.manager) return false; return true; } //-------------------------------------------------------------------------- bool InstanceRef::operator!=(const InstanceRef &rhs) const //-------------------------------------------------------------------------- { return !(*this == rhs); } //-------------------------------------------------------------------------- MappingInstance InstanceRef::get_mapping_instance(void) const //-------------------------------------------------------------------------- { return MappingInstance(manager); } //-------------------------------------------------------------------------- bool InstanceRef::is_virtual_ref(void) const //-------------------------------------------------------------------------- { if (manager == NULL) return true; return manager->is_virtual_manager(); } //-------------------------------------------------------------------------- void InstanceRef::add_resource_reference(ReferenceSource source) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif manager->add_base_resource_ref(source); } //-------------------------------------------------------------------------- void InstanceRef::remove_resource_reference(ReferenceSource source) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif if (manager->remove_base_resource_ref(source)) delete manager; } //-------------------------------------------------------------------------- void InstanceRef::add_valid_reference(ReferenceSource source, ReferenceMutator *mutator) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif manager->add_base_valid_ref(source, mutator); } //-------------------------------------------------------------------------- void InstanceRef::remove_valid_reference(ReferenceSource source, ReferenceMutator *mutator) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif if (manager->remove_base_valid_ref(source, mutator)) delete manager; } //-------------------------------------------------------------------------- Memory InstanceRef::get_memory(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif return manager->get_memory(); } //-------------------------------------------------------------------------- bool InstanceRef::is_field_set(FieldID fid) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif unsigned index = manager->field_space_node->get_field_index(fid); return valid_fields.is_set(index); } //-------------------------------------------------------------------------- LegionRuntime::Accessor::RegionAccessor< LegionRuntime::Accessor::AccessorType::Generic> InstanceRef::get_accessor(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif return manager->get_accessor(); } //-------------------------------------------------------------------------- LegionRuntime::Accessor::RegionAccessor< LegionRuntime::Accessor::AccessorType::Generic> InstanceRef::get_field_accessor(FieldID fid) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(manager != NULL); #endif return manager->get_field_accessor(fid); } //-------------------------------------------------------------------------- void InstanceRef::pack_reference(Serializer &rez) const //-------------------------------------------------------------------------- { rez.serialize(valid_fields); rez.serialize(ready_event); if (manager != NULL) rez.serialize(manager->did); else rez.serialize<DistributedID>(0); } //-------------------------------------------------------------------------- void InstanceRef::unpack_reference(Runtime *runtime, Deserializer &derez, RtEvent &ready) //-------------------------------------------------------------------------- { derez.deserialize(valid_fields); derez.deserialize(ready_event); DistributedID did; derez.deserialize(did); if (did == 0) return; manager = runtime->find_or_request_physical_manager(did, ready); local = false; } ///////////////////////////////////////////////////////////// // InstanceSet ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- InstanceSet::CollectableRef& InstanceSet::CollectableRef::operator=( const InstanceSet::CollectableRef &rhs) //-------------------------------------------------------------------------- { valid_fields = rhs.valid_fields; ready_event = rhs.ready_event; local = rhs.local; manager = rhs.manager; return *this; } //-------------------------------------------------------------------------- InstanceSet::InstanceSet(size_t init_size /*=0*/) : single((init_size <= 1)), shared(false) //-------------------------------------------------------------------------- { if (init_size == 0) refs.single = NULL; else if (init_size == 1) { refs.single = new CollectableRef(); refs.single->add_reference(); } else { refs.multi = new InternalSet(init_size); refs.multi->add_reference(); } } //-------------------------------------------------------------------------- InstanceSet::InstanceSet(const InstanceSet &rhs) : single(rhs.single) //-------------------------------------------------------------------------- { // Mark that the other one is sharing too if (single) { refs.single = rhs.refs.single; if (refs.single == NULL) { shared = false; return; } shared = true; rhs.shared = true; refs.single->add_reference(); } else { refs.multi = rhs.refs.multi; shared = true; rhs.shared = true; refs.multi->add_reference(); } } //-------------------------------------------------------------------------- InstanceSet::~InstanceSet(void) //-------------------------------------------------------------------------- { if (single) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); } else { if (refs.multi->remove_reference()) delete refs.multi; } } //-------------------------------------------------------------------------- InstanceSet& InstanceSet::operator=(const InstanceSet &rhs) //-------------------------------------------------------------------------- { // See if we need to delete our current one if (single) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); } else { if (refs.multi->remove_reference()) delete refs.multi; } // Now copy over the other one single = rhs.single; if (single) { refs.single = rhs.refs.single; if (refs.single != NULL) { shared = true; rhs.shared = true; refs.single->add_reference(); } else shared = false; } else { refs.multi = rhs.refs.multi; shared = true; rhs.shared = true; refs.multi->add_reference(); } return *this; } //-------------------------------------------------------------------------- void InstanceSet::make_copy(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(shared); #endif if (single) { if (refs.single != NULL) { CollectableRef *next = new CollectableRef(*refs.single); next->add_reference(); if (refs.single->remove_reference()) delete (refs.single); refs.single = next; } } else { InternalSet *next = new InternalSet(*refs.multi); next->add_reference(); if (refs.multi->remove_reference()) delete refs.multi; refs.multi = next; } shared = false; } //-------------------------------------------------------------------------- bool InstanceSet::operator==(const InstanceSet &rhs) const //-------------------------------------------------------------------------- { if (single != rhs.single) return false; if (single) { if (refs.single == rhs.refs.single) return true; if (((refs.single == NULL) && (rhs.refs.single != NULL)) || ((refs.single != NULL) && (rhs.refs.single == NULL))) return false; return ((*refs.single) == (*rhs.refs.single)); } else { if (refs.multi->vector.size() != rhs.refs.multi->vector.size()) return false; for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) { if (refs.multi->vector[idx] != rhs.refs.multi->vector[idx]) return false; } return true; } } //-------------------------------------------------------------------------- bool InstanceSet::operator!=(const InstanceSet &rhs) const //-------------------------------------------------------------------------- { return !((*this) == rhs); } //-------------------------------------------------------------------------- InstanceRef& InstanceSet::operator[](unsigned idx) //-------------------------------------------------------------------------- { if (shared) make_copy(); if (single) { #ifdef DEBUG_LEGION assert(idx == 0); assert(refs.single != NULL); #endif return *(refs.single); } #ifdef DEBUG_LEGION assert(idx < refs.multi->vector.size()); #endif return refs.multi->vector[idx]; } //-------------------------------------------------------------------------- const InstanceRef& InstanceSet::operator[](unsigned idx) const //-------------------------------------------------------------------------- { // No need to make a copy if shared here since this is read-only if (single) { #ifdef DEBUG_LEGION assert(idx == 0); assert(refs.single != NULL); #endif return *(refs.single); } #ifdef DEBUG_LEGION assert(idx < refs.multi->vector.size()); #endif return refs.multi->vector[idx]; } //-------------------------------------------------------------------------- bool InstanceSet::empty(void) const //-------------------------------------------------------------------------- { if (single && (refs.single == NULL)) return true; else if (!single && refs.multi->empty()) return true; return false; } //-------------------------------------------------------------------------- size_t InstanceSet::size(void) const //-------------------------------------------------------------------------- { if (single) { if (refs.single == NULL) return 0; return 1; } if (refs.multi == NULL) return 0; return refs.multi->vector.size(); } //-------------------------------------------------------------------------- void InstanceSet::resize(size_t new_size) //-------------------------------------------------------------------------- { if (single) { if (new_size == 0) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); refs.single = NULL; shared = false; } else if (new_size > 1) { // Switch to multi InternalSet *next = new InternalSet(new_size); if (refs.single != NULL) { next->vector[0] = *(refs.single); if (refs.single->remove_reference()) delete (refs.single); } next->add_reference(); refs.multi = next; single = false; shared = false; } else if (refs.single == NULL) { // New size is 1 but we were empty before CollectableRef *next = new CollectableRef(); next->add_reference(); refs.single = next; single = true; shared = false; } } else { if (new_size == 0) { if (refs.multi->remove_reference()) delete refs.multi; refs.single = NULL; single = true; shared = false; } else if (new_size == 1) { CollectableRef *next = new CollectableRef(refs.multi->vector[0]); if (refs.multi->remove_reference()) delete (refs.multi); next->add_reference(); refs.single = next; single = true; shared = false; } else { size_t current_size = refs.multi->vector.size(); if (current_size != new_size) { if (shared) { // Make a copy InternalSet *next = new InternalSet(new_size); // Copy over the elements for (unsigned idx = 0; idx < ((current_size < new_size) ? current_size : new_size); idx++) next->vector[idx] = refs.multi->vector[idx]; if (refs.multi->remove_reference()) delete refs.multi; next->add_reference(); refs.multi = next; shared = false; } else { // Resize our existing vector refs.multi->vector.resize(new_size); } } // Size is the same so there is no need to do anything } } } //-------------------------------------------------------------------------- void InstanceSet::clear(void) //-------------------------------------------------------------------------- { // No need to copy since we are removing our references and not mutating if (single) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); refs.single = NULL; } else { if (shared) { // Small optimization here, if we're told to delete it, we know // that means we were the last user so we can re-use it if (refs.multi->remove_reference()) { // Put a reference back on it since we're reusing it refs.multi->add_reference(); refs.multi->vector.clear(); } else { // Go back to single refs.multi = NULL; single = true; } } else refs.multi->vector.clear(); } shared = false; } //-------------------------------------------------------------------------- void InstanceSet::swap(InstanceSet &rhs) //-------------------------------------------------------------------------- { // Swap references { InternalSet *other = rhs.refs.multi; rhs.refs.multi = refs.multi; refs.multi = other; } // Swap single { bool other = rhs.single; rhs.single = single; single = other; } // Swap shared { bool other = rhs.shared; rhs.shared = shared; shared = other; } } //-------------------------------------------------------------------------- void InstanceSet::add_instance(const InstanceRef &ref) //-------------------------------------------------------------------------- { if (single) { // No need to check for shared, we're going to make new things anyway if (refs.single != NULL) { // Make the new multi version InternalSet *next = new InternalSet(2); next->vector[0] = *(refs.single); next->vector[1] = ref; if (refs.single->remove_reference()) delete (refs.single); next->add_reference(); refs.multi = next; single = false; shared = false; } else { refs.single = new CollectableRef(ref); refs.single->add_reference(); } } else { if (shared) make_copy(); refs.multi->vector.push_back(ref); } } //-------------------------------------------------------------------------- bool InstanceSet::is_virtual_mapping(void) const //-------------------------------------------------------------------------- { if (empty()) return true; if (size() > 1) return false; return refs.single->is_virtual_ref(); } //-------------------------------------------------------------------------- void InstanceSet::pack_references(Serializer &rez) const //-------------------------------------------------------------------------- { if (single) { if (refs.single == NULL) { rez.serialize<size_t>(0); return; } rez.serialize<size_t>(1); refs.single->pack_reference(rez); } else { rez.serialize<size_t>(refs.multi->vector.size()); for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) refs.multi->vector[idx].pack_reference(rez); } } //-------------------------------------------------------------------------- void InstanceSet::unpack_references(Runtime *runtime, Deserializer &derez, std::set<RtEvent> &ready_events) //-------------------------------------------------------------------------- { size_t num_refs; derez.deserialize(num_refs); if (num_refs == 0) { // No matter what, we can just clear out any references we have if (single) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); refs.single = NULL; } else { if (refs.multi->remove_reference()) delete refs.multi; single = true; } } else if (num_refs == 1) { // If we're in multi, go back to single if (!single) { if (refs.multi->remove_reference()) delete refs.multi; refs.multi = NULL; single = true; } // Now we can unpack our reference, see if we need to make one if (refs.single == NULL) { refs.single = new CollectableRef(); refs.single->add_reference(); } RtEvent ready; refs.single->unpack_reference(runtime, derez, ready); if (ready.exists()) ready_events.insert(ready); } else { // If we're in single, go to multi // otherwise resize our multi for the appropriate number of references if (single) { if ((refs.single != NULL) && refs.single->remove_reference()) delete (refs.single); refs.multi = new InternalSet(num_refs); refs.multi->add_reference(); single = false; } else refs.multi->vector.resize(num_refs); // Now do the unpacking for (unsigned idx = 0; idx < num_refs; idx++) { RtEvent ready; refs.multi->vector[idx].unpack_reference(runtime, derez, ready); if (ready.exists()) ready_events.insert(ready); } } // We are always not shared when we are done shared = false; } //-------------------------------------------------------------------------- void InstanceSet::add_resource_references(ReferenceSource source) const //-------------------------------------------------------------------------- { if (single) { if (refs.single != NULL) refs.single->add_resource_reference(source); } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) refs.multi->vector[idx].add_resource_reference(source); } } //-------------------------------------------------------------------------- void InstanceSet::remove_resource_references(ReferenceSource source) const //-------------------------------------------------------------------------- { if (single) { if (refs.single != NULL) refs.single->remove_resource_reference(source); } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) refs.multi->vector[idx].remove_resource_reference(source); } } //-------------------------------------------------------------------------- void InstanceSet::add_valid_references(ReferenceSource source, ReferenceMutator *mutator) const //-------------------------------------------------------------------------- { if (single) { if (refs.single != NULL) refs.single->add_valid_reference(source, mutator); } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) refs.multi->vector[idx].add_valid_reference(source, mutator); } } //-------------------------------------------------------------------------- void InstanceSet::remove_valid_references(ReferenceSource source, ReferenceMutator *mutator) const //-------------------------------------------------------------------------- { if (single) { if (refs.single != NULL) refs.single->remove_valid_reference(source, mutator); } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) refs.multi->vector[idx].remove_valid_reference(source, mutator); } } //-------------------------------------------------------------------------- void InstanceSet::update_wait_on_events(std::set<ApEvent> &wait_on) const //-------------------------------------------------------------------------- { if (single) { if (refs.single != NULL) { ApEvent ready = refs.single->get_ready_event(); if (ready.exists()) wait_on.insert(ready); } } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) { ApEvent ready = refs.multi->vector[idx].get_ready_event(); if (ready.exists()) wait_on.insert(ready); } } } //-------------------------------------------------------------------------- LegionRuntime::Accessor::RegionAccessor< LegionRuntime::Accessor::AccessorType::Generic> InstanceSet:: get_field_accessor(FieldID fid) const //-------------------------------------------------------------------------- { if (single) { #ifdef DEBUG_LEGION assert(refs.single != NULL); #endif return refs.single->get_field_accessor(fid); } else { for (unsigned idx = 0; idx < refs.multi->vector.size(); idx++) { const InstanceRef &ref = refs.multi->vector[idx]; if (ref.is_field_set(fid)) return ref.get_field_accessor(fid); } assert(false); return refs.multi->vector[0].get_field_accessor(fid); } } ///////////////////////////////////////////////////////////// // VersioningInvalidator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- VersioningInvalidator::VersioningInvalidator(void) : ctx(0), invalidate_all(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- VersioningInvalidator::VersioningInvalidator(RegionTreeContext c) : ctx(c.get_id()), invalidate_all(!c.exists()) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- bool VersioningInvalidator::visit_region(RegionNode *node) //-------------------------------------------------------------------------- { if (invalidate_all) node->invalidate_version_managers(); else node->invalidate_version_state(ctx); return true; } //-------------------------------------------------------------------------- bool VersioningInvalidator::visit_partition(PartitionNode *node) //-------------------------------------------------------------------------- { // There is no version information on partitions return true; } }; // namespace Internal }; // namespace Legion
/************************************************************************* * * $RCSfile: PresentationViewShellBase.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-07-13 13:59:19 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_PRESENTATION_VIEW_SHELL_BASE_HXX #define SD_PRESENTATION_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" namespace sd { /** This class exists to be able to register another factory that creates the view shell for the presentation. */ class PresentationViewShellBase : public ViewShellBase { public: TYPEINFO(); SFX_DECL_VIEWFACTORY(PresentationViewShellBase); /** This constructor is used by the view factory of the SFX macros. */ PresentationViewShellBase (SfxViewFrame *pFrame, SfxViewShell* pOldShell); virtual ~PresentationViewShellBase (void); /** We delete the ViewTabBar that is not needed for the presentation. */ virtual void LateInit (void); }; } // end of namespace sd #endif INTEGRATION: CWS ooo19126 (1.3.428); FILE MERGED 2005/09/05 13:22:45 rt 1.3.428.1: #i54170# Change license header: remove SISSL /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PresentationViewShellBase.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:12:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_PRESENTATION_VIEW_SHELL_BASE_HXX #define SD_PRESENTATION_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" namespace sd { /** This class exists to be able to register another factory that creates the view shell for the presentation. */ class PresentationViewShellBase : public ViewShellBase { public: TYPEINFO(); SFX_DECL_VIEWFACTORY(PresentationViewShellBase); /** This constructor is used by the view factory of the SFX macros. */ PresentationViewShellBase (SfxViewFrame *pFrame, SfxViewShell* pOldShell); virtual ~PresentationViewShellBase (void); /** We delete the ViewTabBar that is not needed for the presentation. */ virtual void LateInit (void); }; } // end of namespace sd #endif
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: BResultSetMetaData.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 05:23:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_ADABAS_BRESULTSETMETADATA_HXX_ #include "adabas/BResultSetMetaData.hxx" #endif #ifndef _CONNECTIVITY_ADABAS_CATALOG_HXX_ #include "adabas/BCatalog.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_ #include <com/sun/star/sdbc/DataType.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif using namespace com::sun::star::sdbc; using namespace com::sun::star::uno; using namespace connectivity::adabas; using namespace connectivity; OAdabasResultSetMetaData::OAdabasResultSetMetaData(odbc::OConnection* _pConnection, SQLHANDLE _pStmt,const ::vos::ORef<OSQLColumns>& _rSelectColumns ) : OAdabasResultSetMetaData_BASE(_pConnection,_pStmt) ,m_aSelectColumns(_rSelectColumns) { } // ----------------------------------------------------------------------------- OAdabasResultSetMetaData::OAdabasResultSetMetaData(odbc::OConnection* _pConnection, SQLHANDLE _pStmt ,const ::std::vector<sal_Int32> & _vMapping) : OAdabasResultSetMetaData_BASE(_pConnection,_pStmt,_vMapping) { } // ------------------------------------------------------------------------- OAdabasResultSetMetaData::~OAdabasResultSetMetaData() { } // ----------------------------------------------------------------------------- sal_Int32 SAL_CALL OAdabasResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Int32 nType = OAdabasResultSetMetaData_BASE::getColumnType( column); // special handling for float values which could be doubles ::rtl::OUString sTypeName; OAdabasCatalog::correctColumnProperties(getPrecision(column),nType,sTypeName); return nType; } // ----------------------------------------------------------------------------- sal_Int32 SAL_CALL OAdabasResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Int32 nValue = 0; sal_Bool bFound = sal_False; if ( m_aSelectColumns.isValid() && column > 0 && column <= m_aSelectColumns->size() ) bFound = (*m_aSelectColumns)[column-1]->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)) >>= nValue; if ( !bFound ) nValue = getNumColAttrib(column,SQL_DESC_NULLABLE); return nValue; } // ------------------------------------------------------------------------- INTEGRATION: CWS warnings01 (1.6.30); FILE MERGED 2005/11/07 14:43:02 fs 1.6.30.1: #i57457# warning-free code /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: BResultSetMetaData.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-20 01:10:30 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_ADABAS_BRESULTSETMETADATA_HXX_ #include "adabas/BResultSetMetaData.hxx" #endif #ifndef _CONNECTIVITY_ADABAS_CATALOG_HXX_ #include "adabas/BCatalog.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_ #include <com/sun/star/sdbc/DataType.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif using namespace com::sun::star::sdbc; using namespace com::sun::star::uno; using namespace connectivity::adabas; using namespace connectivity; OAdabasResultSetMetaData::OAdabasResultSetMetaData(odbc::OConnection* _pConnection, SQLHANDLE _pStmt,const ::vos::ORef<OSQLColumns>& _rSelectColumns ) : OAdabasResultSetMetaData_BASE(_pConnection,_pStmt) ,m_aSelectColumns(_rSelectColumns) { } // ----------------------------------------------------------------------------- OAdabasResultSetMetaData::OAdabasResultSetMetaData(odbc::OConnection* _pConnection, SQLHANDLE _pStmt ,const ::std::vector<sal_Int32> & _vMapping) : OAdabasResultSetMetaData_BASE(_pConnection,_pStmt,_vMapping) { } // ------------------------------------------------------------------------- OAdabasResultSetMetaData::~OAdabasResultSetMetaData() { } // ----------------------------------------------------------------------------- sal_Int32 SAL_CALL OAdabasResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Int32 nType = OAdabasResultSetMetaData_BASE::getColumnType( column); // special handling for float values which could be doubles ::rtl::OUString sTypeName; OAdabasCatalog::correctColumnProperties(getPrecision(column),nType,sTypeName); return nType; } // ----------------------------------------------------------------------------- sal_Int32 SAL_CALL OAdabasResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Int32 nValue = 0; sal_Bool bFound = sal_False; if ( m_aSelectColumns.isValid() && column > 0 && column <= (sal_Int32)m_aSelectColumns->size() ) bFound = (*m_aSelectColumns)[column-1]->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)) >>= nValue; if ( !bFound ) nValue = getNumColAttrib(column,SQL_DESC_NULLABLE); return nValue; } // -------------------------------------------------------------------------
/* Copyright 2016 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cuda_module.h" #include "realm/tasks.h" #include "realm/logging.h" #include "realm/cmdline.h" #include "lowlevel_dma.h" #include "channel.h" #include "realm/cuda/cudart_hijack.h" #include "activemsg.h" #include "realm/utils.h" #include <stdio.h> namespace Realm { namespace Cuda { // dma code is still in old namespace typedef LegionRuntime::LowLevel::DmaRequest DmaRequest; typedef LegionRuntime::LowLevel::OASVec OASVec; typedef LegionRuntime::LowLevel::InstPairCopier InstPairCopier; typedef LegionRuntime::LowLevel::MemPairCopier MemPairCopier; typedef LegionRuntime::LowLevel::MemPairCopierFactory MemPairCopierFactory; Logger log_gpu("gpu"); Logger log_gpudma("gpudma"); Logger log_cudart("cudart"); #ifdef EVENT_GRAPH_TRACE extern Logger log_event_graph; #endif Logger log_stream("gpustream"); //////////////////////////////////////////////////////////////////////// // // class GPUStream GPUStream::GPUStream(GPU *_gpu, GPUWorker *_worker) : gpu(_gpu), worker(_worker) { assert(worker != 0); CHECK_CU( cuStreamCreate(&stream, CU_STREAM_NON_BLOCKING) ); log_stream.info() << "CUDA stream " << stream << " created for GPU " << gpu; } GPUStream::~GPUStream(void) { // log_stream.info() << "CUDA stream " << stream << " destroyed - max copies = " // << pending_copies.capacity() << ", max events = " << pending_events.capacity(); CHECK_CU( cuStreamDestroy(stream) ); } GPU *GPUStream::get_gpu(void) const { return gpu; } CUstream GPUStream::get_stream(void) const { return stream; } // may be called by anybody to enqueue a copy or an event void GPUStream::add_copy(GPUMemcpy *copy) { bool add_to_worker = false; { AutoHSLLock al(mutex); // remember to add ourselves to the worker if we didn't already have work add_to_worker = pending_copies.empty(); pending_copies.push_back(copy); } if(add_to_worker) worker->add_stream(this); } void GPUStream::add_fence(GPUWorkFence *fence) { CUevent e = gpu->event_pool.get_event(); CHECK_CU( cuEventRecord(e, stream) ); log_stream.debug() << "CUDA event " << e << " recorded on stream " << stream << " (GPU " << gpu << ")"; add_event(e, fence, 0); } void GPUStream::add_notification(GPUCompletionNotification *notification) { CUevent e = gpu->event_pool.get_event(); CHECK_CU( cuEventRecord(e, stream) ); add_event(e, 0, notification); } void GPUStream::add_event(CUevent event, GPUWorkFence *fence, GPUCompletionNotification *notification) { bool add_to_worker = false; { AutoHSLLock al(mutex); // remember to add ourselves to the worker if we didn't already have work add_to_worker = pending_events.empty(); PendingEvent e; e.event = event; e.fence = fence; e.notification = notification; pending_events.push_back(e); } if(add_to_worker) worker->add_stream(this); } // to be called by a worker (that should already have the GPU context // current) - returns true if any work remains bool GPUStream::issue_copies(void) { while(true) { GPUMemcpy *copy = 0; { AutoHSLLock al(mutex); if(pending_copies.empty()) return false; // no work left copy = pending_copies.front(); pending_copies.pop_front(); } { AutoGPUContext agc(gpu); copy->execute(this); } // no backpressure on copies yet - keep going until list is empty } } bool GPUStream::reap_events(void) { // peek at the first event CUevent event; bool event_valid = false; { AutoHSLLock al(mutex); if(pending_events.empty()) return false; // no work left event = pending_events.front().event; event_valid = true; } // we'll keep looking at events until we find one that hasn't triggered while(event_valid) { CUresult res = cuEventQuery(event); if(res == CUDA_ERROR_NOT_READY) return true; // oldest event hasn't triggered - check again later // no other kind of error is expected assert(res == CUDA_SUCCESS); log_stream.debug() << "CUDA event " << event << " triggered on stream " << stream << " (GPU " << gpu << ")"; // give event back to GPU for reuse gpu->event_pool.return_event(event); // this event has triggered, so figure out the fence/notification to trigger // and also peek at the next event GPUWorkFence *fence = 0; GPUCompletionNotification *notification = 0; { AutoHSLLock al(mutex); const PendingEvent &e = pending_events.front(); assert(e.event == event); fence = e.fence; notification = e.notification; pending_events.pop_front(); if(pending_events.empty()) event_valid = false; else event = pending_events.front().event; } if(fence) fence->mark_finished(true /*successful*/); if(notification) notification->request_completed(); } // if we get all the way to here, we're (temporarily, at least) out of work return false; } //////////////////////////////////////////////////////////////////////// // // class GPUMemcpy GPUMemcpy::GPUMemcpy(GPU *_gpu, GPUMemcpyKind _kind) : gpu(_gpu), kind(_kind) {} //////////////////////////////////////////////////////////////////////// // // class GPUMemcpy1D GPUMemcpy1D::GPUMemcpy1D(GPU *_gpu, void *_dst, const void *_src, size_t _bytes, GPUMemcpyKind _kind, GPUCompletionNotification *_notification) : GPUMemcpy(_gpu, _kind), dst(_dst), src(_src), mask(0), elmt_size(_bytes), notification(_notification) {} GPUMemcpy1D::GPUMemcpy1D(GPU *_gpu, void *_dst, const void *_src, const ElementMask *_mask, size_t _elmt_size, GPUMemcpyKind _kind, GPUCompletionNotification *_notification) : GPUMemcpy(_gpu, _kind), dst(_dst), src(_src), mask(_mask), elmt_size(_elmt_size), notification(_notification) {} GPUMemcpy1D::~GPUMemcpy1D(void) {} void GPUMemcpy1D::do_span(off_t pos, size_t len) { off_t span_start = pos * elmt_size; size_t span_bytes = len * elmt_size; CUstream raw_stream = local_stream->get_stream(); log_stream.debug() << "memcpy added to stream " << raw_stream; switch (kind) { case GPU_MEMCPY_HOST_TO_DEVICE: { CHECK_CU( cuMemcpyHtoDAsync((CUdeviceptr)(((char*)dst)+span_start), (((char*)src)+span_start), span_bytes, raw_stream) ); break; } case GPU_MEMCPY_DEVICE_TO_HOST: { CHECK_CU( cuMemcpyDtoHAsync((((char*)dst)+span_start), (CUdeviceptr)(((char*)src)+span_start), span_bytes, raw_stream) ); break; } case GPU_MEMCPY_DEVICE_TO_DEVICE: { CHECK_CU( cuMemcpyDtoDAsync((CUdeviceptr)(((char*)dst)+span_start), (CUdeviceptr)(((char*)src)+span_start), span_bytes, raw_stream) ); break; } case GPU_MEMCPY_PEER_TO_PEER: { CUcontext src_ctx, dst_ctx; CHECK_CU( cuPointerGetAttribute(&src_ctx, CU_POINTER_ATTRIBUTE_CONTEXT, (CUdeviceptr)src) ); CHECK_CU( cuPointerGetAttribute(&dst_ctx, CU_POINTER_ATTRIBUTE_CONTEXT, (CUdeviceptr)dst) ); CHECK_CU( cuMemcpyPeerAsync((CUdeviceptr)(((char*)dst)+span_start), dst_ctx, (CUdeviceptr)(((char*)src)+span_start), src_ctx, span_bytes, raw_stream) ); break; } default: assert(false); } } void GPUMemcpy1D::execute(GPUStream *stream) { DetailedTimer::ScopedPush sp(TIME_COPY); log_gpudma.info("gpu memcpy: dst=%p src=%p bytes=%zd kind=%d", dst, src, elmt_size, kind); // save stream into local variable for do_spam (which may be called indirectly // by ElementMask::forall_ranges) local_stream = stream; if(mask) { ElementMask::forall_ranges(*this, *mask); } else { do_span(0, 1); } if(notification) stream->add_notification(notification); log_gpudma.info("gpu memcpy complete: dst=%p src=%p bytes=%zd kind=%d", dst, src, elmt_size, kind); } //////////////////////////////////////////////////////////////////////// // // class GPUMemcpy2D GPUMemcpy2D::GPUMemcpy2D(GPU *_gpu, void *_dst, const void *_src, off_t _dst_stride, off_t _src_stride, size_t _bytes, size_t _lines, GPUMemcpyKind _kind, GPUCompletionNotification *_notification) : GPUMemcpy(_gpu, _kind), dst(_dst), src(_src), dst_stride((_dst_stride < (off_t)_bytes) ? _bytes : _dst_stride), src_stride((_src_stride < (off_t)_bytes) ? _bytes : _src_stride), bytes(_bytes), lines(_lines), notification(_notification) {} GPUMemcpy2D::~GPUMemcpy2D(void) {} void GPUMemcpy2D::execute(GPUStream *stream) { log_gpudma.info("gpu memcpy 2d: dst=%p src=%p " "dst_off=%ld src_off=%ld bytes=%ld lines=%ld kind=%d", dst, src, (long)dst_stride, (long)src_stride, bytes, lines, kind); CUDA_MEMCPY2D copy_info; if (kind == GPU_MEMCPY_PEER_TO_PEER) { // If we're doing peer to peer, just let unified memory it deal with it copy_info.srcMemoryType = CU_MEMORYTYPE_UNIFIED; copy_info.dstMemoryType = CU_MEMORYTYPE_UNIFIED; } else { // otherwise we know the answers here copy_info.srcMemoryType = (kind == GPU_MEMCPY_HOST_TO_DEVICE) ? CU_MEMORYTYPE_HOST : CU_MEMORYTYPE_DEVICE; copy_info.dstMemoryType = (kind == GPU_MEMCPY_DEVICE_TO_HOST) ? CU_MEMORYTYPE_HOST : CU_MEMORYTYPE_DEVICE; } copy_info.srcDevice = (CUdeviceptr)src; copy_info.srcHost = src; copy_info.srcPitch = src_stride; copy_info.srcY = 0; copy_info.srcXInBytes = 0; copy_info.dstDevice = (CUdeviceptr)dst; copy_info.dstHost = dst; copy_info.dstPitch = dst_stride; copy_info.dstY = 0; copy_info.dstXInBytes = 0; copy_info.WidthInBytes = bytes; copy_info.Height = lines; CHECK_CU( cuMemcpy2DAsync(&copy_info, stream->get_stream()) ); if(notification) stream->add_notification(notification); log_gpudma.info("gpu memcpy 2d complete: dst=%p src=%p " "dst_off=%ld src_off=%ld bytes=%ld lines=%ld kind=%d", dst, src, (long)dst_stride, (long)src_stride, bytes, lines, kind); } //////////////////////////////////////////////////////////////////////// // // class GPUMemcpy3D GPUMemcpy3D::GPUMemcpy3D(GPU *_gpu, void *_dst, const void *_src, off_t _dst_stride, off_t _src_stride, off_t _dst_height, off_t _src_height, size_t _bytes, size_t _height, size_t _depth, GPUMemcpyKind _kind, GPUCompletionNotification *_notification) : GPUMemcpy(_gpu, _kind), dst(_dst), src(_src), dst_stride((_dst_stride < (off_t)_bytes) ? _bytes : _dst_stride), src_stride((_src_stride < (off_t)_bytes) ? _bytes : _src_stride), dst_height((_dst_height < (off_t)_height) ? _height : _dst_height), src_height((_src_height < (off_t)_height) ? _height : _src_height), bytes(_bytes), height(_height), depth(_depth), notification(_notification) {} GPUMemcpy3D::~GPUMemcpy3D(void) {} void GPUMemcpy3D::execute(GPUStream *stream) { log_gpudma.info("gpu memcpy 3d: dst=%p src=%p" "dst_off=%ld src_off=%ld dst_hei = %ld src_hei = %id" "bytes=%lu height=%lu depth=%lu kind=%d", dst, src, (long)dst_stride, (long)src_stride, (long)dst_height, (long)src_height, bytes, height, depth, kind); CUDA_MEMCPY3D copy_info; if (kind == GPU_MEMCPY_PEER_TO_PEER) { // If we're doing peer to peer, just let unified memory it deal with it copy_info.srcMemoryType = CU_MEMORYTYPE_UNIFIED; copy_info.dstMemoryType = CU_MEMORYTYPE_UNIFIED; } else { // otherwise we know the answers here copy_info.srcMemoryType = (kind == GPU_MEMCPY_HOST_TO_DEVICE) ? CU_MEMORYTYPE_HOST : CU_MEMORYTYPE_DEVICE; copy_info.dstMemoryType = (kind == GPU_MEMCPY_DEVICE_TO_HOST) ? CU_MEMORYTYPE_HOST : CU_MEMORYTYPE_DEVICE; } copy_info.srcDevice = (CUdeviceptr)src; copy_info.srcHost = src; copy_info.srcPitch = src_stride; copy_info.srcHeight = src_height; copy_info.srcY = 0; copy_info.srcZ = 0; copy_info.srcXInBytes = 0; copy_info.srcLOD = 0; copy_info.dstDevice = (CUdeviceptr)dst; copy_info.dstHost = dst; copy_info.dstPitch = dst_stride; copy_info.dstHeight = dst_height; copy_info.dstY = 0; copy_info.dstZ = 0; copy_info.dstXInBytes = 0; copy_info.dstLOD = 0; copy_info.WidthInBytes = bytes; copy_info.Height = height; copy_info.Depth = depth; CHECK_CU( cuMemcpy3DAsync(&copy_info, stream->get_stream()) ); if(notification) stream->add_notification(notification); log_gpudma.info("gpu memcpy 3d complete: dst=%p src=%p" "dst_off=%ld src_off=%ld dst_hei = %ld src_hei = %id" "bytes=%ld height=%ld depth=%ld kind=%d", dst, src, (long)dst_stride, (long)src_stride, (long)dst_height, (long)src_height, bytes, height, depth, kind); } //////////////////////////////////////////////////////////////////////// // // mem pair copiers for DMA channels class GPUtoFBMemPairCopier : public MemPairCopier { public: GPUtoFBMemPairCopier(Memory _src_mem, GPU *_gpu) : gpu(_gpu) { MemoryImpl *src_impl = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_impl->get_direct_ptr(0, src_impl->size)); assert(src_base); } virtual ~GPUtoFBMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new LegionRuntime::LowLevel::SpanBasedInstPairCopier<GPUtoFBMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("gpu write of %zd bytes\n", bytes); gpu->copy_to_fb(dst_offset, src_base + src_offset, bytes); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { gpu->copy_to_fb_2d(dst_offset, src_base + src_offset, dst_stride, src_stride, bytes, lines); record_bytes(bytes * lines); } virtual void flush(DmaRequest *req) { if(total_reqs > 0) gpu->fence_to_fb(req); MemPairCopier::flush(req); } protected: const char *src_base; GPU *gpu; }; class GPUfromFBMemPairCopier : public MemPairCopier { public: GPUfromFBMemPairCopier(GPU *_gpu, Memory _dst_mem) : gpu(_gpu) { MemoryImpl *dst_impl = get_runtime()->get_memory_impl(_dst_mem); dst_base = (char *)(dst_impl->get_direct_ptr(0, dst_impl->size)); assert(dst_base); } virtual ~GPUfromFBMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new LegionRuntime::LowLevel::SpanBasedInstPairCopier<GPUfromFBMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("gpu read of %zd bytes\n", bytes); gpu->copy_from_fb(dst_base + dst_offset, src_offset, bytes); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { gpu->copy_from_fb_2d(dst_base + dst_offset, src_offset, dst_stride, src_stride, bytes, lines); record_bytes(bytes * lines); } virtual void flush(DmaRequest *req) { if(total_reqs > 0) gpu->fence_from_fb(req); MemPairCopier::flush(req); } protected: char *dst_base; GPU *gpu; }; class GPUinFBMemPairCopier : public MemPairCopier { public: GPUinFBMemPairCopier(GPU *_gpu) : gpu(_gpu) { } virtual ~GPUinFBMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new LegionRuntime::LowLevel::SpanBasedInstPairCopier<GPUinFBMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("gpu write of %zd bytes\n", bytes); gpu->copy_within_fb(dst_offset, src_offset, bytes); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { gpu->copy_within_fb_2d(dst_offset, src_offset, dst_stride, src_stride, bytes, lines); record_bytes(bytes * lines); } virtual void flush(DmaRequest *req) { if(total_reqs > 0) gpu->fence_within_fb(req); MemPairCopier::flush(req); } protected: GPU *gpu; }; class GPUPeerMemPairCopier : public MemPairCopier { public: GPUPeerMemPairCopier(GPU *_src, GPU *_dst) : src(_src), dst(_dst) { } virtual ~GPUPeerMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new LegionRuntime::LowLevel::SpanBasedInstPairCopier<GPUPeerMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { src->copy_to_peer(dst, dst_offset, src_offset, bytes); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { src->copy_to_peer_2d(dst, dst_offset, src_offset, dst_stride, src_stride, bytes, lines); record_bytes(bytes * lines); } virtual void flush(DmaRequest *req) { if(total_reqs > 0) src->fence_to_peer(req, dst); MemPairCopier::flush(req); } protected: GPU *src, *dst; }; class GPUDMAChannel_H2D : public MemPairCopierFactory { public: GPUDMAChannel_H2D(GPU *_gpu); virtual bool can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); virtual MemPairCopier *create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); protected: GPU *gpu; }; class GPUDMAChannel_D2H : public MemPairCopierFactory { public: GPUDMAChannel_D2H(GPU *_gpu); virtual bool can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); virtual MemPairCopier *create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); protected: GPU *gpu; }; class GPUDMAChannel_D2D : public MemPairCopierFactory { public: GPUDMAChannel_D2D(GPU *_gpu); virtual bool can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); virtual MemPairCopier *create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); protected: GPU *gpu; }; class GPUDMAChannel_P2P : public MemPairCopierFactory { public: GPUDMAChannel_P2P(GPU *_gpu); virtual bool can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); virtual MemPairCopier *create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); protected: GPU *gpu; }; //////////////////////////////////////////////////////////////////////// // // class GPUDMAChannel_H2D GPUDMAChannel_H2D::GPUDMAChannel_H2D(GPU *_gpu) : MemPairCopierFactory(stringbuilder() << "gpu_h2d (" << _gpu->proc->me << ")") , gpu(_gpu) {} bool GPUDMAChannel_H2D::can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // copies from pinned system memory to _our_ fb, no reduction support if(redop_id != 0) return false; if(gpu->pinned_sysmems.count(src_mem) == 0) return false; if(!(gpu->fbmem) || (dst_mem != gpu->fbmem->me)) return false; return true; } MemPairCopier *GPUDMAChannel_H2D::create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { return new GPUtoFBMemPairCopier(src_mem, gpu); } //////////////////////////////////////////////////////////////////////// // // class GPUDMAChannel_D2H GPUDMAChannel_D2H::GPUDMAChannel_D2H(GPU *_gpu) : MemPairCopierFactory(stringbuilder() << "gpu_d2h (" << _gpu->proc->me << ")") , gpu(_gpu) {} bool GPUDMAChannel_D2H::can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // copies from _our_ fb to pinned system memory, no reduction support if(redop_id != 0) return false; if(!(gpu->fbmem) || (src_mem != gpu->fbmem->me)) return false; if(gpu->pinned_sysmems.count(dst_mem) == 0) return false; return true; } LegionRuntime::LowLevel::MemPairCopier *GPUDMAChannel_D2H::create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { return new GPUfromFBMemPairCopier(gpu, dst_mem); } //////////////////////////////////////////////////////////////////////// // // class GPUDMAChannel_D2D GPUDMAChannel_D2D::GPUDMAChannel_D2D(GPU *_gpu) : MemPairCopierFactory(stringbuilder() << "gpu_d2d (" << _gpu->proc->me << ")") , gpu(_gpu) {} bool GPUDMAChannel_D2D::can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // copies entirely within our fb, no reduction support if(redop_id != 0) return false; if(!gpu->fbmem) return false; Memory our_fb = gpu->fbmem->me; if((src_mem != our_fb) || (dst_mem != our_fb)) return false; // they can't both be our FB return true; } MemPairCopier *GPUDMAChannel_D2D::create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { return new GPUinFBMemPairCopier(gpu); } //////////////////////////////////////////////////////////////////////// // // class GPUDMAChannel_P2P GPUDMAChannel_P2P::GPUDMAChannel_P2P(GPU *_gpu) : MemPairCopierFactory(stringbuilder() << "gpu_p2p (" << _gpu->proc->me << ")") , gpu(_gpu) {} bool GPUDMAChannel_P2P::can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // copies from _our_ fb to a peer's fb, no reduction support if(redop_id != 0) return false; if(!(gpu->fbmem) || (src_mem != gpu->fbmem->me)) return false; if(gpu->peer_fbs.count(dst_mem) == 0) return false; return true; } MemPairCopier *GPUDMAChannel_P2P::create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // TODO: remove this - the p2p copier doesn't actually need it MemoryImpl *dst_impl = get_runtime()->get_memory_impl(dst_mem); GPU *dst_gpu = ((GPUFBMemory *)dst_impl)->gpu; return new GPUPeerMemPairCopier(gpu, dst_gpu); } void GPU::create_dma_channels(Realm::RuntimeImpl *r) { // <NEW_DMA> // Not a good design choice // For now, channel_manager will creates all channels // for GPUs in dma_all_gpus LegionRuntime::LowLevel::register_gpu_in_dma_systems(this); // </NEW_DMA> // if we don't have any framebuffer memory, we can't do any DMAs if(!fbmem) return; if(!pinned_sysmems.empty()) { r->add_dma_channel(new GPUDMAChannel_H2D(this)); r->add_dma_channel(new GPUDMAChannel_D2H(this)); // TODO: move into the dma channels themselves for(std::set<Memory>::const_iterator it = pinned_sysmems.begin(); it != pinned_sysmems.end(); ++it) { Machine::MemoryMemoryAffinity mma; mma.m1 = fbmem->me; mma.m2 = *it; mma.bandwidth = 20; // "medium" mma.latency = 200; // "bad" r->add_mem_mem_affinity(mma); } } else { log_gpu.warning() << "GPU " << proc->me << " has no pinned system memories!?"; } r->add_dma_channel(new GPUDMAChannel_D2D(this)); // only create a p2p channel if we have peers (and an fb) if(!peer_fbs.empty()) { r->add_dma_channel(new GPUDMAChannel_P2P(this)); // TODO: move into the dma channels themselves for(std::set<Memory>::const_iterator it = peer_fbs.begin(); it != peer_fbs.end(); ++it) { Machine::MemoryMemoryAffinity mma; mma.m1 = fbmem->me; mma.m2 = *it; mma.bandwidth = 10; // assuming pcie, this should be ~half the bw and mma.latency = 400; // ~twice the latency as zcmem r->add_mem_mem_affinity(mma); } } } //////////////////////////////////////////////////////////////////////// // // class GPUWorkFence GPUWorkFence::GPUWorkFence(Realm::Operation *op) : Realm::Operation::AsyncWorkItem(op) {} void GPUWorkFence::request_cancellation(void) { // ignored - no way to shoot down CUDA work } void GPUWorkFence::print(std::ostream& os) const { os << "GPUWorkFence"; } void GPUWorkFence::enqueue_on_stream(GPUStream *stream) { if(stream->get_gpu()->module->cfg_fences_use_callbacks) { CHECK_CU( cuStreamAddCallback(stream->get_stream(), &cuda_callback, (void *)this, 0) ); } else { stream->add_fence(this); } } /*static*/ void GPUWorkFence::cuda_callback(CUstream stream, CUresult res, void *data) { GPUWorkFence *me = (GPUWorkFence *)data; assert(res == CUDA_SUCCESS); me->mark_finished(true /*succesful*/); } //////////////////////////////////////////////////////////////////////// // // class GPUMemcpyFence GPUMemcpyFence::GPUMemcpyFence(GPU *_gpu, GPUMemcpyKind _kind, GPUWorkFence *_fence) : GPUMemcpy(_gpu, _kind), fence(_fence) { //log_stream.info() << "gpu memcpy fence " << this << " (fence = " << fence << ") created"; } void GPUMemcpyFence::execute(GPUStream *stream) { //log_stream.info() << "gpu memcpy fence " << this << " (fence = " << fence << ") executed"; fence->enqueue_on_stream(stream); #ifdef FORCE_GPU_STREAM_SYNCHRONIZE CHECK_CU( cuStreamSynchronize(stream->get_stream()) ); #endif } //////////////////////////////////////////////////////////////////////// // // class GPUEventPool GPUEventPool::GPUEventPool(int _batch_size) : batch_size(_batch_size), current_size(0), total_size(0) { // don't immediately fill the pool because we're not managing the context ourselves } // allocating the initial batch of events and cleaning up are done with // these methods instead of constructor/destructor because we don't // manage the GPU context in this helper class void GPUEventPool::init_pool(int init_size /*= 0 -- default == batch size */) { assert(available_events.empty()); if(init_size == 0) init_size = batch_size; available_events.resize(init_size); current_size = init_size; total_size = init_size; // TODO: measure how much benefit is derived from CU_EVENT_DISABLE_TIMING and // consider using them for completion callbacks for(int i = 0; i < init_size; i++) CHECK_CU( cuEventCreate(&available_events[i], CU_EVENT_DEFAULT) ); } void GPUEventPool::empty_pool(void) { // shouldn't be any events running around still assert(current_size == total_size); for(int i = 0; i < current_size; i++) CHECK_CU( cuEventDestroy(available_events[i]) ); current_size = 0; total_size = 0; // free internal vector storage std::vector<CUevent>().swap(available_events); } CUevent GPUEventPool::get_event(void) { AutoHSLLock al(mutex); if(current_size == 0) { // if we need to make an event, make a bunch current_size = batch_size; total_size += batch_size; log_stream.info() << "event pool " << this << " depleted - adding " << batch_size << " events"; // resize the vector (considering all events that might come back) available_events.resize(total_size); for(int i = 0; i < batch_size; i++) CHECK_CU( cuEventCreate(&available_events[i], CU_EVENT_DEFAULT) ); } return available_events[--current_size]; } void GPUEventPool::return_event(CUevent e) { AutoHSLLock al(mutex); assert(current_size < total_size); available_events[current_size++] = e; } //////////////////////////////////////////////////////////////////////// // // class GPUTaskScheduler<T> // we want to subclass the scheduler to replace the execute_task method, but we also want to // allow the use of user or kernel threads, so we apply a bit of template magic (which only works // because the constructors for the KernelThreadTaskScheduler and UserThreadTaskScheduler classes // have the same prototypes) template <typename T> class GPUTaskScheduler : public T { public: GPUTaskScheduler(Processor _proc, Realm::CoreReservation& _core_rsrv, GPUProcessor *_gpu_proc); virtual ~GPUTaskScheduler(void); protected: virtual bool execute_task(Task *task); // might also need to override the thread-switching methods to keep TLS up to date GPUProcessor *gpu_proc; }; template <typename T> GPUTaskScheduler<T>::GPUTaskScheduler(Processor _proc, Realm::CoreReservation& _core_rsrv, GPUProcessor *_gpu_proc) : T(_proc, _core_rsrv), gpu_proc(_gpu_proc) { // nothing else } template <typename T> GPUTaskScheduler<T>::~GPUTaskScheduler(void) { } namespace ThreadLocal { static __thread GPUProcessor *current_gpu_proc = 0; }; // this flag will be set on the first call into any of the hijack code in // cudart_hijack.cc // an application is linked with -lcudart, we will NOT be hijacking the // application's calls, and the cuda module needs to know that) /*extern*/ bool cudart_hijack_active = false; // used in GPUTaskScheduler<T>::execute_task below static bool already_issued_hijack_warning = false; template <typename T> bool GPUTaskScheduler<T>::execute_task(Task *task) { // use TLS to make sure that the task can find the current GPU processor when it makes // CUDA RT calls // TODO: either eliminate these asserts or do TLS swapping when using user threads assert(ThreadLocal::current_gpu_proc == 0); ThreadLocal::current_gpu_proc = gpu_proc; // push the CUDA context for this GPU onto this thread gpu_proc->gpu->push_context(); // bump the current stream // TODO: sanity-check whether this even works right when GPU tasks suspend GPUStream *s = gpu_proc->gpu->switch_to_next_task_stream(); // we'll use a "work fence" to track when the kernels launched by this task actually // finish - this must be added to the task _BEFORE_ we execute GPUWorkFence *fence = new GPUWorkFence(task); task->add_async_work_item(fence); bool ok = T::execute_task(task); // now enqueue the fence on the local stream fence->enqueue_on_stream(s); // A useful debugging macro #ifdef FORCE_GPU_STREAM_SYNCHRONIZE CHECK_CU( cuStreamSynchronize(s->get_stream()) ); #endif // if our hijack code is not active, the application may have put some work for this // task on streams we don't know about, so it takes an expensive device synchronization // to guarantee that any work enqueued on a stream in the future is ordered with respect // to this task's results if(!cudart_hijack_active) { // print a warning if this is the first time and it hasn't been suppressed if(!(gpu_proc->gpu->module->cfg_suppress_hijack_warning || already_issued_hijack_warning)) { already_issued_hijack_warning = true; log_gpu.warning() << "CUDART hijack code not active" << " - device synchronizations required after every GPU task!"; } CHECK_CU( cuCtxSynchronize() ); } // pop the CUDA context for this GPU back off gpu_proc->gpu->pop_context(); assert(ThreadLocal::current_gpu_proc == gpu_proc); ThreadLocal::current_gpu_proc = 0; return ok; } //////////////////////////////////////////////////////////////////////// // // class GPUProcessor GPUProcessor::GPUProcessor(GPU *_gpu, Processor _me, Realm::CoreReservationSet& crs, size_t _stack_size) : LocalTaskProcessor(_me, Processor::TOC_PROC) , gpu(_gpu) { Realm::CoreReservationParameters params; params.set_num_cores(1); params.set_alu_usage(params.CORE_USAGE_SHARED); params.set_fpu_usage(params.CORE_USAGE_SHARED); params.set_ldst_usage(params.CORE_USAGE_SHARED); params.set_max_stack_size(_stack_size); std::string name = stringbuilder() << "GPU proc " << _me; core_rsrv = new Realm::CoreReservation(name, crs, params); #ifdef REALM_USE_USER_THREADS_FOR_GPU Realm::UserThreadTaskScheduler *sched = new GPUTaskScheduler<Realm::UserThreadTaskScheduler>(me, *core_rsrv, this); // no config settings we want to tweak yet #else Realm::KernelThreadTaskScheduler *sched = new GPUTaskScheduler<Realm::KernelThreadTaskScheduler>(me, *core_rsrv, this); // no config settings we want to tweak yet #endif set_scheduler(sched); } GPUProcessor::~GPUProcessor(void) { delete core_rsrv; } void GPU::copy_to_fb(off_t dst_offset, const void *src, size_t bytes, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, (void *)(fbmem->base + dst_offset), src, bytes, GPU_MEMCPY_HOST_TO_DEVICE, notification); host_to_device_stream->add_copy(copy); } void GPU::copy_to_fb(off_t dst_offset, const void *src, const ElementMask *mask, size_t elmt_size, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, (void *)(fbmem->base + dst_offset), src, mask, elmt_size, GPU_MEMCPY_HOST_TO_DEVICE, notification); host_to_device_stream->add_copy(copy); } void GPU::copy_from_fb(void *dst, off_t src_offset, size_t bytes, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, dst, (const void *)(fbmem->base + src_offset), bytes, GPU_MEMCPY_DEVICE_TO_HOST, notification); device_to_host_stream->add_copy(copy); } void GPU::copy_from_fb(void *dst, off_t src_offset, const ElementMask *mask, size_t elmt_size, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, dst, (const void *)(fbmem->base + src_offset), mask, elmt_size, GPU_MEMCPY_DEVICE_TO_HOST, notification); device_to_host_stream->add_copy(copy); } void GPU::copy_within_fb(off_t dst_offset, off_t src_offset, size_t bytes, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, (void *)(fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), bytes, GPU_MEMCPY_DEVICE_TO_DEVICE, notification); device_to_device_stream->add_copy(copy); } void GPU::copy_within_fb(off_t dst_offset, off_t src_offset, const ElementMask *mask, size_t elmt_size, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, (void *)(fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), mask, elmt_size, GPU_MEMCPY_DEVICE_TO_DEVICE, notification); device_to_device_stream->add_copy(copy); } void GPU::copy_to_fb_2d(off_t dst_offset, const void *src, off_t dst_stride, off_t src_stride, size_t bytes, size_t lines, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy2D(this, (void *)(fbmem->base + dst_offset), src, dst_stride, src_stride, bytes, lines, GPU_MEMCPY_HOST_TO_DEVICE, notification); host_to_device_stream->add_copy(copy); } void GPU::copy_to_fb_3d(off_t dst_offset, const void *src, off_t dst_stride, off_t src_stride, off_t dst_height, off_t src_height, size_t bytes, size_t height, size_t depth, GPUCompletionNotification *notification /* = 0*/) { GPUMemcpy *copy = new GPUMemcpy3D(this, (void *)(fbmem->base + dst_offset), src, dst_stride, src_stride, dst_height, src_height, bytes, height, depth, GPU_MEMCPY_HOST_TO_DEVICE, notification); host_to_device_stream->add_copy(copy); } void GPU::copy_from_fb_2d(void *dst, off_t src_offset, off_t dst_stride, off_t src_stride, size_t bytes, size_t lines, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy2D(this, dst, (const void *)(fbmem->base + src_offset), dst_stride, src_stride, bytes, lines, GPU_MEMCPY_DEVICE_TO_HOST, notification); device_to_host_stream->add_copy(copy); } void GPU::copy_from_fb_3d(void *dst, off_t src_offset, off_t dst_stride, off_t src_stride, off_t dst_height, off_t src_height, size_t bytes, size_t height, size_t depth, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy3D(this, dst, (const void *)(fbmem->base + src_offset), dst_stride, src_stride, dst_height, src_height, bytes, height, depth, GPU_MEMCPY_DEVICE_TO_HOST, notification); device_to_host_stream->add_copy(copy); } void GPU::copy_within_fb_2d(off_t dst_offset, off_t src_offset, off_t dst_stride, off_t src_stride, size_t bytes, size_t lines, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy2D(this, (void *)(fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), dst_stride, src_stride, bytes, lines, GPU_MEMCPY_DEVICE_TO_DEVICE, notification); device_to_device_stream->add_copy(copy); } void GPU::copy_within_fb_3d(off_t dst_offset, off_t src_offset, off_t dst_stride, off_t src_stride, off_t dst_height, off_t src_height, size_t bytes, size_t height, size_t depth, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy3D(this, (void *)(fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), dst_stride, src_stride, dst_height, src_height, bytes, height, depth, GPU_MEMCPY_DEVICE_TO_DEVICE, notification); device_to_device_stream->add_copy(copy); } void GPU::copy_to_peer(GPU *dst, off_t dst_offset, off_t src_offset, size_t bytes, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, (void *)(dst->fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), bytes, GPU_MEMCPY_PEER_TO_PEER, notification); peer_to_peer_stream->add_copy(copy); } void GPU::copy_to_peer_2d(GPU *dst, off_t dst_offset, off_t src_offset, off_t dst_stride, off_t src_stride, size_t bytes, size_t lines, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy2D(this, (void *)(dst->fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), dst_stride, src_stride, bytes, lines, GPU_MEMCPY_PEER_TO_PEER, notification); peer_to_peer_stream->add_copy(copy); } void GPU::copy_to_peer_3d(GPU *dst, off_t dst_offset, off_t src_offset, off_t dst_stride, off_t src_stride, off_t dst_height, off_t src_height, size_t bytes, size_t height, size_t depth, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy3D(this, (void *)(dst->fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), dst_stride, src_stride, dst_height, src_height, bytes, height, depth, GPU_MEMCPY_PEER_TO_PEER, notification); peer_to_peer_stream->add_copy(copy); } void GPU::fence_to_fb(Realm::Operation *op) { GPUWorkFence *f = new GPUWorkFence(op); // this must be done before we enqueue the callback with CUDA op->add_async_work_item(f); host_to_device_stream->add_copy(new GPUMemcpyFence(this, GPU_MEMCPY_HOST_TO_DEVICE, f)); } void GPU::fence_from_fb(Realm::Operation *op) { GPUWorkFence *f = new GPUWorkFence(op); // this must be done before we enqueue the callback with CUDA op->add_async_work_item(f); device_to_host_stream->add_copy(new GPUMemcpyFence(this, GPU_MEMCPY_DEVICE_TO_HOST, f)); } void GPU::fence_within_fb(Realm::Operation *op) { GPUWorkFence *f = new GPUWorkFence(op); // this must be done before we enqueue the callback with CUDA op->add_async_work_item(f); device_to_device_stream->add_copy(new GPUMemcpyFence(this, GPU_MEMCPY_DEVICE_TO_DEVICE, f)); } void GPU::fence_to_peer(Realm::Operation *op, GPU *dst) { GPUWorkFence *f = new GPUWorkFence(op); // this must be done before we enqueue the callback with CUDA op->add_async_work_item(f); peer_to_peer_stream->add_copy(new GPUMemcpyFence(this, GPU_MEMCPY_PEER_TO_PEER, f)); } GPUStream *GPU::get_current_task_stream(void) { return task_streams[current_stream]; } GPUStream *GPU::switch_to_next_task_stream(void) { current_stream++; if(current_stream >= task_streams.size()) current_stream = 0; return task_streams[current_stream]; } void GPUProcessor::shutdown(void) { log_gpu.info("shutting down"); // shut down threads/scheduler LocalTaskProcessor::shutdown(); // synchronize the device so we can flush any printf buffers - do // this after shutting down the threads so that we know all work is done { AutoGPUContext agc(gpu); CHECK_CU( cuCtxSynchronize() ); } } GPUWorker::GPUWorker(void) : condvar(lock) , core_rsrv(0), worker_thread(0), worker_shutdown_requested(false) {} GPUWorker::~GPUWorker(void) { // shutdown should have already been called assert(worker_thread == 0); } void GPUWorker::start_background_thread(Realm::CoreReservationSet &crs, size_t stack_size) { core_rsrv = new Realm::CoreReservation("GPU worker thread", crs, Realm::CoreReservationParameters()); Realm::ThreadLaunchParameters tlp; worker_thread = Realm::Thread::create_kernel_thread<GPUWorker, &GPUWorker::thread_main>(this, tlp, *core_rsrv, 0); } void GPUWorker::shutdown_background_thread(void) { { AutoHSLLock al(lock); worker_shutdown_requested = true; condvar.broadcast(); } worker_thread->join(); delete worker_thread; worker_thread = 0; delete core_rsrv; core_rsrv = 0; } void GPUWorker::add_stream(GPUStream *stream) { AutoHSLLock al(lock); // if the stream is already in the set, nothing to do if(active_streams.count(stream) > 0) return; active_streams.insert(stream); condvar.broadcast(); } bool GPUWorker::process_streams(bool sleep_on_empty) { // we start by grabbing the list of active streams, replacing it with an // empty list - this way we don't have to hold the lock the whole time // for any stream that we leave work on, we'll add it back in std::set<GPUStream *> streams; { AutoHSLLock al(lock); while(active_streams.empty()) { if(!sleep_on_empty || worker_shutdown_requested) return false; condvar.wait(); } streams.swap(active_streams); } bool any_work_left = false; for(std::set<GPUStream *>::const_iterator it = streams.begin(); it != streams.end(); it++) { GPUStream *s = *it; bool stream_work_left = false; if(s->issue_copies()) stream_work_left = true; if(s->reap_events()) stream_work_left = true; if(stream_work_left) { add_stream(s); any_work_left = true; } } return any_work_left; } void GPUWorker::thread_main(void) { // TODO: consider busy-waiting in some cases to reduce latency? while(!worker_shutdown_requested) { bool work_left = process_streams(true); // if there was work left, yield our thread for now to avoid a tight spin loop // TODO: enqueue a callback so we can go to sleep and wake up sooner than a kernel // timeslice? if(work_left) Realm::Thread::yield(); } } //////////////////////////////////////////////////////////////////////// // // class BlockingCompletionNotification class BlockingCompletionNotification : public GPUCompletionNotification { public: BlockingCompletionNotification(void); virtual ~BlockingCompletionNotification(void); virtual void request_completed(void); virtual void wait(void); public: GASNetHSL mutex; GASNetCondVar cv; bool completed; }; BlockingCompletionNotification::BlockingCompletionNotification(void) : cv(mutex) , completed(false) {} BlockingCompletionNotification::~BlockingCompletionNotification(void) {} void BlockingCompletionNotification::request_completed(void) { AutoHSLLock a(mutex); assert(!completed); completed = true; cv.broadcast(); } void BlockingCompletionNotification::wait(void) { AutoHSLLock a(mutex); while(!completed) cv.wait(); } //////////////////////////////////////////////////////////////////////// // // class GPU GPUFBMemory::GPUFBMemory(Memory _me, GPU *_gpu, CUdeviceptr _base, size_t _size) : MemoryImpl(_me, _size, MKIND_GPUFB, 512, Memory::GPU_FB_MEM) , gpu(_gpu), base(_base) { free_blocks[0] = size; } GPUFBMemory::~GPUFBMemory(void) {} RegionInstance GPUFBMemory::create_instance(IndexSpace is, const int *linearization_bits, size_t bytes_needed, size_t block_size, size_t element_size, const std::vector<size_t>& field_sizes, ReductionOpID redopid, off_t list_size, const Realm::ProfilingRequestSet &reqs, RegionInstance parent_inst) { return create_instance_local(is, linearization_bits, bytes_needed, block_size, element_size, field_sizes, redopid, list_size, reqs, parent_inst); } void GPUFBMemory::destroy_instance(RegionInstance i, bool local_destroy) { destroy_instance_local(i, local_destroy); } off_t GPUFBMemory::alloc_bytes(size_t size) { return alloc_bytes_local(size); } void GPUFBMemory::free_bytes(off_t offset, size_t size) { free_bytes_local(offset, size); } // these work, but they are SLOW void GPUFBMemory::get_bytes(off_t offset, void *dst, size_t size) { // create an async copy and then wait for it to finish... BlockingCompletionNotification bcn; gpu->copy_from_fb(dst, offset, size, &bcn); bcn.wait(); } void GPUFBMemory::put_bytes(off_t offset, const void *src, size_t size) { // create an async copy and then wait for it to finish... BlockingCompletionNotification bcn; gpu->copy_to_fb(offset, src, size, &bcn); bcn.wait(); } void *GPUFBMemory::get_direct_ptr(off_t offset, size_t size) { return (void *)(base + offset); } int GPUFBMemory::get_home_node(off_t offset, size_t size) { return -1; } //////////////////////////////////////////////////////////////////////// // // class GPUZCMemory GPUZCMemory::GPUZCMemory(Memory _me, CUdeviceptr _gpu_base, void *_cpu_base, size_t _size) : MemoryImpl(_me, _size, MKIND_ZEROCOPY, 256, Memory::Z_COPY_MEM) , gpu_base(_gpu_base), cpu_base((char *)_cpu_base) { free_blocks[0] = size; } GPUZCMemory::~GPUZCMemory(void) {} RegionInstance GPUZCMemory::create_instance(IndexSpace is, const int *linearization_bits, size_t bytes_needed, size_t block_size, size_t element_size, const std::vector<size_t>& field_sizes, ReductionOpID redopid, off_t list_size, const Realm::ProfilingRequestSet &reqs, RegionInstance parent_inst) { return create_instance_local(is, linearization_bits, bytes_needed, block_size, element_size, field_sizes, redopid, list_size, reqs, parent_inst); } void GPUZCMemory::destroy_instance(RegionInstance i, bool local_destroy) { destroy_instance_local(i, local_destroy); } off_t GPUZCMemory::alloc_bytes(size_t size) { return alloc_bytes_local(size); } void GPUZCMemory::free_bytes(off_t offset, size_t size) { free_bytes_local(offset, size); } void GPUZCMemory::get_bytes(off_t offset, void *dst, size_t size) { memcpy(dst, cpu_base+offset, size); } void GPUZCMemory::put_bytes(off_t offset, const void *src, size_t size) { memcpy(cpu_base+offset, src, size); } void *GPUZCMemory::get_direct_ptr(off_t offset, size_t size) { return (cpu_base + offset); } int GPUZCMemory::get_home_node(off_t offset, size_t size) { return ID(me).memory.owner_node; } #ifdef POINTER_CHECKS static unsigned *get_gpu_valid_mask(RegionMetaDataUntyped region) { const ElementMask &mask = region.get_valid_mask(); void *valid_mask_base; for(size_t p = 0; p < mask.raw_size(); p += 4) log_gpudma.info(" raw mask data[%zd] = %08x\n", p, ((unsigned *)(mask.get_raw()))[p>>2]); CHECK_CU( cuMemAlloc((cuDevicePtr*)(&valid_mask_base), mask.raw_size()) ); log_gpudma.info("copy of valid mask (%zd bytes) created at %p", mask.raw_size(), valid_mask_base); CHECK_CU( cuMemcpyHtoD(vald_mask_base, mask.get_raw(), mask.raw_size()) ); return (unsigned *)&(((ElementMaskImpl *)valid_mask_base)->bits); } #endif // Helper methods for emulating the cuda runtime /*static*/ GPUProcessor* GPUProcessor::get_current_gpu_proc(void) { return ThreadLocal::current_gpu_proc; } void GPUProcessor::stream_synchronize(cudaStream_t stream) { // same as device_synchronize for now GPUStream *current = gpu->get_current_task_stream(); CHECK_CU( cuStreamSynchronize(current->get_stream()) ); } void GPUProcessor::device_synchronize(void) { GPUStream *current = gpu->get_current_task_stream(); CHECK_CU( cuStreamSynchronize(current->get_stream()) ); } void GPUProcessor::event_create(cudaEvent_t *event, int flags) { // int cu_flags = CU_EVENT_DEFAULT; // if((flags & cudaEventBlockingSync) != 0) // cu_flags |= CU_EVENT_BLOCKING_SYNC; // if((flags & cudaEventDisableTiming) != 0) // cu_flags |= CU_EVENT_DISABLE_TIMING; // get an event from our event pool (ignoring the flags for now) CUevent e = gpu->event_pool.get_event(); *event = e; } void GPUProcessor::event_destroy(cudaEvent_t event) { // assume the event is one of ours and put it back in the pool CUevent e = event; if(e) gpu->event_pool.return_event(e); } void GPUProcessor::event_record(cudaEvent_t event, cudaStream_t stream) { // ignore the provided stream and record the event on this task's assigned stream CUevent e = event; GPUStream *current = gpu->get_current_task_stream(); CHECK_CU( cuEventRecord(e, current->get_stream()) ); } void GPUProcessor::event_synchronize(cudaEvent_t event) { // TODO: consider suspending task rather than busy-waiting here... CUevent e = event; CHECK_CU( cuEventSynchronize(e) ); } void GPUProcessor::event_elapsed_time(float *ms, cudaEvent_t start, cudaEvent_t end) { // TODO: consider suspending task rather than busy-waiting here... CUevent e1 = start; CUevent e2 = end; CHECK_CU( cuEventElapsedTime(ms, e1, e2) ); } GPUProcessor::LaunchConfig::LaunchConfig(dim3 _grid, dim3 _block, size_t _shared) : grid(_grid), block(_block), shared(_shared) {} void GPUProcessor::configure_call(dim3 grid_dim, dim3 block_dim, size_t shared_mem, cudaStream_t stream) { launch_configs.push_back(LaunchConfig(grid_dim, block_dim, shared_mem)); } void GPUProcessor::setup_argument(const void *arg, size_t size, size_t offset) { size_t required = offset + size; if(required > kernel_args.size()) kernel_args.resize(required); memcpy(&kernel_args[offset], arg, size); } void GPUProcessor::launch(const void *func) { // make sure we have a launch config assert(!launch_configs.empty()); LaunchConfig &config = launch_configs.back(); // Find our function CUfunction f = gpu->lookup_function(func); size_t arg_size = kernel_args.size(); void *extra[] = { CU_LAUNCH_PARAM_BUFFER_POINTER, &kernel_args[0], CU_LAUNCH_PARAM_BUFFER_SIZE, &arg_size, CU_LAUNCH_PARAM_END }; CUstream raw_stream = gpu->get_current_task_stream()->get_stream(); log_stream.debug() << "kernel " << func << " added to stream " << raw_stream; // Launch the kernel on our stream dammit! CHECK_CU( cuLaunchKernel(f, config.grid.x, config.grid.y, config.grid.z, config.block.x, config.block.y, config.block.z, config.shared, raw_stream, NULL, extra) ); // pop the config we just used launch_configs.pop_back(); // clear out the kernel args kernel_args.clear(); } void GPUProcessor::gpu_memcpy(void *dst, const void *src, size_t size, cudaMemcpyKind kind) { CUstream current = gpu->get_current_task_stream()->get_stream(); // the synchronous copy still uses cuMemcpyAsync so that we can limit the // synchronization to just the right stream CHECK_CU( cuMemcpyAsync((CUdeviceptr)dst, (CUdeviceptr)src, size, current) ); CHECK_CU( cuStreamSynchronize(current) ); } void GPUProcessor::gpu_memcpy_async(void *dst, const void *src, size_t size, cudaMemcpyKind kind, cudaStream_t stream) { CUstream current = gpu->get_current_task_stream()->get_stream(); CHECK_CU( cuMemcpyAsync((CUdeviceptr)dst, (CUdeviceptr)src, size, current) ); // no synchronization here } void GPUProcessor::gpu_memcpy_to_symbol(const void *dst, const void *src, size_t size, size_t offset, cudaMemcpyKind kind) { CUstream current = gpu->get_current_task_stream()->get_stream(); CUdeviceptr var_base = gpu->lookup_variable(dst); CHECK_CU( cuMemcpyAsync(var_base + offset, (CUdeviceptr)src, size, current) ); CHECK_CU( cuStreamSynchronize(current) ); } void GPUProcessor::gpu_memcpy_to_symbol_async(const void *dst, const void *src, size_t size, size_t offset, cudaMemcpyKind kind, cudaStream_t stream) { CUstream current = gpu->get_current_task_stream()->get_stream(); CUdeviceptr var_base = gpu->lookup_variable(dst); CHECK_CU( cuMemcpyAsync(var_base + offset, (CUdeviceptr)src, size, current) ); // no synchronization here } void GPUProcessor::gpu_memcpy_from_symbol(void *dst, const void *src, size_t size, size_t offset, cudaMemcpyKind kind) { CUstream current = gpu->get_current_task_stream()->get_stream(); CUdeviceptr var_base = gpu->lookup_variable(src); CHECK_CU( cuMemcpyAsync((CUdeviceptr)dst, var_base + offset, size, current) ); CHECK_CU( cuStreamSynchronize(current) ); } void GPUProcessor::gpu_memcpy_from_symbol_async(void *dst, const void *src, size_t size, size_t offset, cudaMemcpyKind kind, cudaStream_t stream) { CUstream current = gpu->get_current_task_stream()->get_stream(); CUdeviceptr var_base = gpu->lookup_variable(src); CHECK_CU( cuMemcpyAsync((CUdeviceptr)dst, var_base + offset, size, current) ); // no synchronization here } //////////////////////////////////////////////////////////////////////// // // class GPU GPU::GPU(CudaModule *_module, GPUInfo *_info, GPUWorker *_worker, int num_streams) : module(_module), info(_info), worker(_worker) , proc(0), fbmem(0), current_stream(0) { // create a CUDA context for our device - automatically becomes current CHECK_CU( cuCtxCreate(&context, CU_CTX_MAP_HOST | CU_CTX_SCHED_BLOCKING_SYNC, info->device) ); event_pool.init_pool(); host_to_device_stream = new GPUStream(this, worker); device_to_host_stream = new GPUStream(this, worker); device_to_device_stream = new GPUStream(this, worker); peer_to_peer_stream = new GPUStream(this, worker); task_streams.resize(num_streams); for(int idx = 0; idx < num_streams; idx++) task_streams[idx] = new GPUStream(this, worker); pop_context(); // now hook into the cuda runtime fatbin/etc. registration path GlobalRegistrations::add_gpu_context(this); } GPU::~GPU(void) { push_context(); event_pool.empty_pool(); // destroy streams delete host_to_device_stream; delete device_to_host_stream; delete device_to_device_stream; delete peer_to_peer_stream; while(!task_streams.empty()) { delete task_streams.back(); task_streams.pop_back(); } // free memory CHECK_CU( cuMemFree(fbmem_base) ); CHECK_CU( cuCtxDestroy(context) ); } void GPU::push_context(void) { CHECK_CU( cuCtxPushCurrent(context) ); } void GPU::pop_context(void) { // the context we pop had better be ours... CUcontext popped; CHECK_CU( cuCtxPopCurrent(&popped) ); assert(popped == context); } void GPU::create_processor(RuntimeImpl *runtime, size_t stack_size) { Processor p = runtime->next_local_processor_id(); proc = new GPUProcessor(this, p, runtime->core_reservation_set(), stack_size); runtime->add_processor(proc); // this processor is able to access its own FB and the ZC mem (if any) if(fbmem) { Machine::ProcessorMemoryAffinity pma; pma.p = p; pma.m = fbmem->me; pma.bandwidth = 200; // "big" pma.latency = 5; // "ok" runtime->add_proc_mem_affinity(pma); } if(module->zcmem) { Machine::ProcessorMemoryAffinity pma; pma.p = p; pma.m = module->zcmem->me; pma.bandwidth = 20; // "medium" pma.latency = 200; // "bad" runtime->add_proc_mem_affinity(pma); } // peer access for(std::vector<GPU *>::iterator it = module->gpus.begin(); it != module->gpus.end(); it++) { // ignore ourselves if(*it == this) continue; // ignore gpus that we don't expect to be able to peer with if(info->peers.count((*it)->info->device) == 0) continue; // ignore gpus with no fb if(!((*it)->fbmem)) continue; // enable peer access { AutoGPUContext agc(this); CHECK_CU( cuCtxEnablePeerAccess((*it)->context, 0) ); } log_gpu.print() << "peer access enabled from GPU " << p << " to FB " << (*it)->fbmem->me; peer_fbs.insert((*it)->fbmem->me); { Machine::ProcessorMemoryAffinity pma; pma.p = p; pma.m = (*it)->fbmem->me; pma.bandwidth = 10; // assuming pcie, this should be ~half the bw and pma.latency = 400; // ~twice the latency as zcmem runtime->add_proc_mem_affinity(pma); } } } void GPU::create_fb_memory(RuntimeImpl *runtime, size_t size) { // need the context so we can get an allocation in the right place { AutoGPUContext agc(this); CHECK_CU( cuMemAlloc(&fbmem_base, size) ); } Memory m = runtime->next_local_memory_id(); fbmem = new GPUFBMemory(m, this, fbmem_base, size); runtime->add_memory(fbmem); } void GPU::register_fat_binary(const FatBin *fatbin) { AutoGPUContext agc(this); log_gpu.info() << "registering fat binary " << fatbin << " with GPU " << this; // have we see this one already? if(device_modules.count(fatbin) > 0) { log_gpu.warning() << "duplicate registration of fat binary data " << fatbin; return; } if(fatbin->data != 0) { // binary data to be loaded with cuModuleLoad(Ex) CUmodule module = load_cuda_module(fatbin->data); device_modules[fatbin] = module; return; } assert(0); } void GPU::register_variable(const RegisteredVariable *var) { AutoGPUContext agc(this); log_gpu.debug() << "registering variable " << var->device_name << " (" << var->host_var << ") with GPU " << this; // have we seen it already? if(device_variables.count(var->host_var) > 0) { log_gpu.warning() << "duplicate registration of variable " << var->device_name; return; } // get the module it lives in std::map<const FatBin *, CUmodule>::const_iterator it = device_modules.find(var->fat_bin); assert(it != device_modules.end()); CUmodule module = it->second; CUdeviceptr ptr; size_t size; CHECK_CU( cuModuleGetGlobal(&ptr, &size, module, var->device_name) ); device_variables[var->host_var] = ptr; } void GPU::register_function(const RegisteredFunction *func) { AutoGPUContext agc(this); log_gpu.debug() << "registering function " << func->device_fun << " (" << func->host_fun << ") with GPU " << this; // have we seen it already? if(device_functions.count(func->host_fun) > 0) { log_gpu.warning() << "duplicate registration of function " << func->device_fun; return; } // get the module it lives in std::map<const FatBin *, CUmodule>::const_iterator it = device_modules.find(func->fat_bin); assert(it != device_modules.end()); CUmodule module = it->second; CUfunction f; CHECK_CU( cuModuleGetFunction(&f, module, func->device_fun) ); device_functions[func->host_fun] = f; } CUfunction GPU::lookup_function(const void *func) { std::map<const void *, CUfunction>::iterator finder = device_functions.find(func); assert(finder != device_functions.end()); return finder->second; } CUdeviceptr GPU::lookup_variable(const void *var) { std::map<const void *, CUdeviceptr>::iterator finder = device_variables.find(var); assert(finder != device_variables.end()); return finder->second; } CUmodule GPU::load_cuda_module(const void *data) { const unsigned num_options = 4; CUjit_option jit_options[num_options]; void* option_vals[num_options]; const size_t buffer_size = 16384; char* log_info_buffer = (char*)malloc(buffer_size); char* log_error_buffer = (char*)malloc(buffer_size); jit_options[0] = CU_JIT_INFO_LOG_BUFFER; jit_options[1] = CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES; jit_options[2] = CU_JIT_ERROR_LOG_BUFFER; jit_options[3] = CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES; option_vals[0] = log_info_buffer; option_vals[1] = (void*)buffer_size; option_vals[2] = log_error_buffer; option_vals[3] = (void*)buffer_size; CUmodule module; CUresult result = cuModuleLoadDataEx(&module, data, num_options, jit_options, option_vals); if (result != CUDA_SUCCESS) { #ifdef __MACH__ if (result == CUDA_ERROR_OPERATING_SYSTEM) { log_gpu.error("ERROR: Device side asserts are not supported by the " "CUDA driver for MAC OSX, see NVBugs 1628896."); } #endif if (result == CUDA_ERROR_NO_BINARY_FOR_GPU) { log_gpu.error("ERROR: The binary was compiled for the wrong GPU " "architecture. Update the 'GPU_ARCH' flag at the top " "of runtime/runtime.mk to match your current GPU " "architecture."); } log_gpu.error("Failed to load CUDA module! Error log: %s", log_error_buffer); #if CUDA_VERSION >= 6050 const char *name, *str; CHECK_CU( cuGetErrorName(result, &name) ); CHECK_CU( cuGetErrorString(result, &str) ); fprintf(stderr,"CU: cuModuleLoadDataEx = %d (%s): %s\n", result, name, str); #else fprintf(stderr,"CU: cuModuleLoadDataEx = %d\n", result); #endif assert(0); } else log_gpu.info("Loaded CUDA Module. JIT Output: %s", log_info_buffer); free(log_info_buffer); free(log_error_buffer); return module; } //////////////////////////////////////////////////////////////////////// // // class AutoGPUContext AutoGPUContext::AutoGPUContext(GPU& _gpu) : gpu(&_gpu) { gpu->push_context(); } AutoGPUContext::AutoGPUContext(GPU *_gpu) : gpu(_gpu) { gpu->push_context(); } AutoGPUContext::~AutoGPUContext(void) { gpu->pop_context(); } //////////////////////////////////////////////////////////////////////// // // class CudaModule // our interface to the rest of the runtime CudaModule::CudaModule(void) : Module("cuda") , cfg_zc_mem_size_in_mb(64) , cfg_fb_mem_size_in_mb(256) , cfg_num_gpus(0) , cfg_gpu_streams(12) , cfg_use_background_workers(true) , cfg_use_shared_worker(true) , cfg_pin_sysmem(true) , cfg_fences_use_callbacks(false) , cfg_suppress_hijack_warning(false) , shared_worker(0), zcmem_cpu_base(0), zcmem(0) {} CudaModule::~CudaModule(void) {} /*static*/ Module *CudaModule::create_module(RuntimeImpl *runtime, std::vector<std::string>& cmdline) { // before we do anything, make sure there's a CUDA driver and GPUs to talk to std::vector<GPUInfo *> infos; { CUresult ret = cuInit(0); if(ret != CUDA_SUCCESS) { log_gpu.warning() << "cuInit(0) returned " << ret << " - module not loaded"; return 0; } int num_devices; CHECK_CU( cuDeviceGetCount(&num_devices) ); for(int i = 0; i < num_devices; i++) { GPUInfo *info = new GPUInfo; // TODO: consider environment variables or other ways to tell if certain // GPUs should be ignored info->index = i; CHECK_CU( cuDeviceGet(&info->device, i) ); CHECK_CU( cuDeviceGetName(info->name, GPUInfo::MAX_NAME_LEN, info->device) ); CHECK_CU( cuDeviceComputeCapability(&info->compute_major, &info->compute_minor, info->device) ); CHECK_CU( cuDeviceTotalMem(&info->total_mem, info->device) ); CHECK_CU( cuDeviceGetProperties(&info->props, info->device) ); log_gpu.info() << "GPU #" << i << ": " << info->name << " (" << info->compute_major << '.' << info->compute_minor << ") " << (info->total_mem >> 20) << " MB"; infos.push_back(info); } if(infos.empty()) { log_gpu.warning() << "no CUDA-capable GPUs found - module not loaded"; return 0; } // query peer-to-peer access (all pairs) for(std::vector<GPUInfo *>::iterator it1 = infos.begin(); it1 != infos.end(); it1++) for(std::vector<GPUInfo *>::iterator it2 = infos.begin(); it2 != infos.end(); it2++) if(it1 != it2) { int can_access; CHECK_CU( cuDeviceCanAccessPeer(&can_access, (*it1)->device, (*it2)->device) ); if(can_access) { log_gpu.info() << "p2p access from device " << (*it1)->index << " to device " << (*it2)->index; (*it1)->peers.insert((*it2)->device); } } } CudaModule *m = new CudaModule; // give the gpu info we assembled to the module m->gpu_info.swap(infos); // first order of business - read command line parameters { CommandLineParser cp; cp.add_option_int("-ll:fsize", m->cfg_fb_mem_size_in_mb) .add_option_int("-ll:zsize", m->cfg_zc_mem_size_in_mb) .add_option_int("-ll:gpu", m->cfg_num_gpus) .add_option_int("-ll:streams", m->cfg_gpu_streams) .add_option_int("-ll:gpuworker", m->cfg_use_shared_worker) .add_option_int("-ll:pin", m->cfg_pin_sysmem) .add_option_bool("-cuda:callbacks", m->cfg_fences_use_callbacks) .add_option_bool("-cuda:nohijack", m->cfg_suppress_hijack_warning); bool ok = cp.parse_command_line(cmdline); if(!ok) { log_gpu.error() << "error reading CUDA command line parameters"; exit(1); } } return m; } // do any general initialization - this is called after all configuration is // complete void CudaModule::initialize(RuntimeImpl *runtime) { Module::initialize(runtime); // sanity-check: do we even have enough gpus? if(cfg_num_gpus > gpu_info.size()) { log_gpu.fatal() << cfg_num_gpus << " GPUs requested, but only " << gpu_info.size() << " available!"; assert(false); } // if we are using a shared worker, create that next if(cfg_use_shared_worker) { shared_worker = new GPUWorker; if(cfg_use_background_workers) shared_worker->start_background_thread(runtime->core_reservation_set(), 1 << 20); // hardcoded worker stack size } // just use the GPUs in order right now gpus.resize(cfg_num_gpus); for(unsigned i = 0; i < cfg_num_gpus; i++) { // either create a worker for this GPU or use the shared one GPUWorker *worker; if(cfg_use_shared_worker) { worker = shared_worker; } else { worker = new GPUWorker; if(cfg_use_background_workers) worker->start_background_thread(runtime->core_reservation_set(), 1 << 20); // hardcoded worker stack size } GPU *g = new GPU(this, gpu_info[i], worker, cfg_gpu_streams); if(!cfg_use_shared_worker) dedicated_workers[g] = worker; gpus[i] = g; } } // create any memories provided by this module (default == do nothing) // (each new MemoryImpl should use a Memory from RuntimeImpl::next_local_memory_id) void CudaModule::create_memories(RuntimeImpl *runtime) { Module::create_memories(runtime); // each GPU needs its FB memory if(cfg_fb_mem_size_in_mb > 0) for(std::vector<GPU *>::iterator it = gpus.begin(); it != gpus.end(); it++) (*it)->create_fb_memory(runtime, cfg_fb_mem_size_in_mb << 20); // a single ZC memory for everybody if((cfg_zc_mem_size_in_mb > 0) && !gpus.empty()) { CUdeviceptr zcmem_gpu_base; // borrow GPU 0's context for the allocation call { AutoGPUContext agc(gpus[0]); CHECK_CU( cuMemHostAlloc(&zcmem_cpu_base, cfg_zc_mem_size_in_mb << 20, CU_MEMHOSTALLOC_PORTABLE | CU_MEMHOSTALLOC_DEVICEMAP) ); CHECK_CU( cuMemHostGetDevicePointer(&zcmem_gpu_base, zcmem_cpu_base, 0) ); // right now there are asssumptions in several places that unified addressing keeps // the CPU and GPU addresses the same assert(zcmem_cpu_base == (void *)zcmem_gpu_base); } Memory m = runtime->next_local_memory_id(); zcmem = new GPUZCMemory(m, zcmem_gpu_base, zcmem_cpu_base, cfg_zc_mem_size_in_mb << 20); runtime->add_memory(zcmem); // add the ZC memory as a pinned memory to all GPUs for(unsigned i = 0; i < gpus.size(); i++) { CUdeviceptr gpuptr; CUresult ret; { AutoGPUContext agc(gpus[i]); ret = cuMemHostGetDevicePointer(&gpuptr, zcmem_cpu_base, 0); } if((ret == CUDA_SUCCESS) && (gpuptr == zcmem_gpu_base)) { // <NEW_DMA> add mem mem affinity between GPU FB and ZC Machine::MemoryMemoryAffinity mma; mma.m1 = m; mma.m2 = gpus[i]->fbmem->me; mma.bandwidth = 200; // "big" mma.latency = 5; // "ok" runtime->add_mem_mem_affinity(mma); // </NEW_DMA> gpus[i]->pinned_sysmems.insert(zcmem->me); } else { log_gpu.warning() << "GPU #" << i << " has an unexpected mapping for ZC memory!"; } } } } // create any processors provided by the module (default == do nothing) // (each new ProcessorImpl should use a Processor from // RuntimeImpl::next_local_processor_id) void CudaModule::create_processors(RuntimeImpl *runtime) { Module::create_processors(runtime); // each GPU needs a processor for(std::vector<GPU *>::iterator it = gpus.begin(); it != gpus.end(); it++) (*it)->create_processor(runtime, 2 << 20); // TODO: don't use hardcoded stack size... } // create any DMA channels provided by the module (default == do nothing) void CudaModule::create_dma_channels(RuntimeImpl *runtime) { // before we create dma channels, see how many of the system memory ranges // we can register with CUDA if(cfg_pin_sysmem && !gpus.empty()) { std::vector<MemoryImpl *>& local_mems = runtime->nodes[gasnet_mynode()].memories; for(std::vector<MemoryImpl *>::iterator it = local_mems.begin(); it != local_mems.end(); it++) { // ignore FB/ZC memories or anything that doesn't have a "direct" pointer if(((*it)->kind == MemoryImpl::MKIND_GPUFB) || ((*it)->kind == MemoryImpl::MKIND_ZEROCOPY)) continue; void *base = (*it)->get_direct_ptr(0, (*it)->size); if(base == 0) continue; // using GPU 0's context, attempt a portable registration CUresult ret; { AutoGPUContext agc(gpus[0]); ret = cuMemHostRegister(base, (*it)->size, CU_MEMHOSTREGISTER_PORTABLE | CU_MEMHOSTREGISTER_DEVICEMAP); } if(ret != CUDA_SUCCESS) { log_gpu.info() << "failed to register mem " << (*it)->me << " (" << base << " + " << (*it)->size << ") : " << ret; continue; } // now go through each GPU and verify that it got a GPU pointer (it may not match the CPU // pointer, but that's ok because we'll never refer to it directly) for(unsigned i = 0; i < gpus.size(); i++) { CUdeviceptr gpuptr; CUresult ret; { AutoGPUContext agc(gpus[i]); ret = cuMemHostGetDevicePointer(&gpuptr, base, 0); } if(ret == CUDA_SUCCESS) { // no test for && ((void *)gpuptr == base)) { log_gpu.info() << "memory " << (*it)->me << " successfully registered with GPU " << gpus[i]->proc->me; // <NEW_DMA> add mem mem affinity between GPU FB and ZC Machine::MemoryMemoryAffinity mma; mma.m1 = gpus[i]->fbmem->me; mma.m2 = (*it)->me; mma.bandwidth = 200; // "big" mma.latency = 5; // "ok" runtime->add_mem_mem_affinity(mma); // </NEW_DMA> gpus[i]->pinned_sysmems.insert((*it)->me); } else { log_gpu.warning() << "GPU #" << i << " has no mapping for registered memory (" << (*it)->me << " at " << base << ") !?"; } } } } // now actually let each GPU make its channels for(std::vector<GPU *>::iterator it = gpus.begin(); it != gpus.end(); it++) (*it)->create_dma_channels(runtime); Module::create_dma_channels(runtime); } // create any code translators provided by the module (default == do nothing) void CudaModule::create_code_translators(RuntimeImpl *runtime) { Module::create_code_translators(runtime); } // clean up any common resources created by the module - this will be called // after all memories/processors/etc. have been shut down and destroyed void CudaModule::cleanup(void) { // clean up worker(s) if(shared_worker) { if(cfg_use_background_workers) shared_worker->shutdown_background_thread(); delete shared_worker; shared_worker = 0; } for(std::map<GPU *, GPUWorker *>::iterator it = dedicated_workers.begin(); it != dedicated_workers.end(); it++) { GPUWorker *worker = it->second; if(cfg_use_background_workers) worker->shutdown_background_thread(); delete worker; } dedicated_workers.clear(); // use GPU 0's context to free ZC memory (if any) if(zcmem_cpu_base) { assert(!gpus.empty()); AutoGPUContext agc(gpus[0]); CHECK_CU( cuMemFreeHost(zcmem_cpu_base) ); } for(std::vector<GPU *>::iterator it = gpus.begin(); it != gpus.end(); it++) delete *it; gpus.clear(); Module::cleanup(); } //////////////////////////////////////////////////////////////////////// // // struct RegisteredFunction RegisteredFunction::RegisteredFunction(const FatBin *_fat_bin, const void *_host_fun, const char *_device_fun) : fat_bin(_fat_bin), host_fun(_host_fun), device_fun(_device_fun) {} //////////////////////////////////////////////////////////////////////// // // struct RegisteredVariable RegisteredVariable::RegisteredVariable(const FatBin *_fat_bin, const void *_host_var, const char *_device_name, bool _external, int _size, bool _constant, bool _global) : fat_bin(_fat_bin), host_var(_host_var), device_name(_device_name), external(_external), size(_size), constant(_constant), global(_global) {} //////////////////////////////////////////////////////////////////////// // // class GlobalRegistrations GlobalRegistrations::GlobalRegistrations(void) {} GlobalRegistrations::~GlobalRegistrations(void) {} /*static*/ GlobalRegistrations& GlobalRegistrations::get_global_registrations(void) { static GlobalRegistrations reg; return reg; } // called by a GPU when it has created its context - will result in calls back // into the GPU for any modules/variables/whatever already registered /*static*/ void GlobalRegistrations::add_gpu_context(GPU *gpu) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); // add this gpu to the list assert(g.active_gpus.count(gpu) == 0); g.active_gpus.insert(gpu); // and now tell it about all the previous-registered stuff for(std::vector<FatBin *>::iterator it = g.fat_binaries.begin(); it != g.fat_binaries.end(); it++) gpu->register_fat_binary(*it); for(std::vector<RegisteredVariable *>::iterator it = g.variables.begin(); it != g.variables.end(); it++) gpu->register_variable(*it); for(std::vector<RegisteredFunction *>::iterator it = g.functions.begin(); it != g.functions.end(); it++) gpu->register_function(*it); } /*static*/ void GlobalRegistrations::remove_gpu_context(GPU *gpu) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); assert(g.active_gpus.count(gpu) > 0); g.active_gpus.erase(gpu); } // called by __cuda(un)RegisterFatBinary /*static*/ void GlobalRegistrations::register_fat_binary(FatBin *fatbin) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); // add the fat binary to the list and tell any gpus we know of about it g.fat_binaries.push_back(fatbin); for(std::set<GPU *>::iterator it = g.active_gpus.begin(); it != g.active_gpus.end(); it++) (*it)->register_fat_binary(fatbin); } /*static*/ void GlobalRegistrations::unregister_fat_binary(FatBin *fatbin) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); // remove the fatbin from the list - don't bother telling gpus std::vector<FatBin *>::iterator it = g.fat_binaries.begin(); while(it != g.fat_binaries.end()) if(*it == fatbin) it = g.fat_binaries.erase(it); else it++; } // called by __cudaRegisterVar /*static*/ void GlobalRegistrations::register_variable(RegisteredVariable *var) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); // add the variable to the list and tell any gpus we know g.variables.push_back(var); for(std::set<GPU *>::iterator it = g.active_gpus.begin(); it != g.active_gpus.end(); it++) (*it)->register_variable(var); } // called by __cudaRegisterFunction /*static*/ void GlobalRegistrations::register_function(RegisteredFunction *func) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); // add the function to the list and tell any gpus we know g.functions.push_back(func); for(std::set<GPU *>::iterator it = g.active_gpus.begin(); it != g.active_gpus.end(); it++) (*it)->register_function(func); } }; // namespace Cuda }; // namespace Realm dma: fix a typo for logging cuda dma info /* Copyright 2016 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cuda_module.h" #include "realm/tasks.h" #include "realm/logging.h" #include "realm/cmdline.h" #include "lowlevel_dma.h" #include "channel.h" #include "realm/cuda/cudart_hijack.h" #include "activemsg.h" #include "realm/utils.h" #include <stdio.h> namespace Realm { namespace Cuda { // dma code is still in old namespace typedef LegionRuntime::LowLevel::DmaRequest DmaRequest; typedef LegionRuntime::LowLevel::OASVec OASVec; typedef LegionRuntime::LowLevel::InstPairCopier InstPairCopier; typedef LegionRuntime::LowLevel::MemPairCopier MemPairCopier; typedef LegionRuntime::LowLevel::MemPairCopierFactory MemPairCopierFactory; Logger log_gpu("gpu"); Logger log_gpudma("gpudma"); Logger log_cudart("cudart"); #ifdef EVENT_GRAPH_TRACE extern Logger log_event_graph; #endif Logger log_stream("gpustream"); //////////////////////////////////////////////////////////////////////// // // class GPUStream GPUStream::GPUStream(GPU *_gpu, GPUWorker *_worker) : gpu(_gpu), worker(_worker) { assert(worker != 0); CHECK_CU( cuStreamCreate(&stream, CU_STREAM_NON_BLOCKING) ); log_stream.info() << "CUDA stream " << stream << " created for GPU " << gpu; } GPUStream::~GPUStream(void) { // log_stream.info() << "CUDA stream " << stream << " destroyed - max copies = " // << pending_copies.capacity() << ", max events = " << pending_events.capacity(); CHECK_CU( cuStreamDestroy(stream) ); } GPU *GPUStream::get_gpu(void) const { return gpu; } CUstream GPUStream::get_stream(void) const { return stream; } // may be called by anybody to enqueue a copy or an event void GPUStream::add_copy(GPUMemcpy *copy) { bool add_to_worker = false; { AutoHSLLock al(mutex); // remember to add ourselves to the worker if we didn't already have work add_to_worker = pending_copies.empty(); pending_copies.push_back(copy); } if(add_to_worker) worker->add_stream(this); } void GPUStream::add_fence(GPUWorkFence *fence) { CUevent e = gpu->event_pool.get_event(); CHECK_CU( cuEventRecord(e, stream) ); log_stream.debug() << "CUDA event " << e << " recorded on stream " << stream << " (GPU " << gpu << ")"; add_event(e, fence, 0); } void GPUStream::add_notification(GPUCompletionNotification *notification) { CUevent e = gpu->event_pool.get_event(); CHECK_CU( cuEventRecord(e, stream) ); add_event(e, 0, notification); } void GPUStream::add_event(CUevent event, GPUWorkFence *fence, GPUCompletionNotification *notification) { bool add_to_worker = false; { AutoHSLLock al(mutex); // remember to add ourselves to the worker if we didn't already have work add_to_worker = pending_events.empty(); PendingEvent e; e.event = event; e.fence = fence; e.notification = notification; pending_events.push_back(e); } if(add_to_worker) worker->add_stream(this); } // to be called by a worker (that should already have the GPU context // current) - returns true if any work remains bool GPUStream::issue_copies(void) { while(true) { GPUMemcpy *copy = 0; { AutoHSLLock al(mutex); if(pending_copies.empty()) return false; // no work left copy = pending_copies.front(); pending_copies.pop_front(); } { AutoGPUContext agc(gpu); copy->execute(this); } // no backpressure on copies yet - keep going until list is empty } } bool GPUStream::reap_events(void) { // peek at the first event CUevent event; bool event_valid = false; { AutoHSLLock al(mutex); if(pending_events.empty()) return false; // no work left event = pending_events.front().event; event_valid = true; } // we'll keep looking at events until we find one that hasn't triggered while(event_valid) { CUresult res = cuEventQuery(event); if(res == CUDA_ERROR_NOT_READY) return true; // oldest event hasn't triggered - check again later // no other kind of error is expected assert(res == CUDA_SUCCESS); log_stream.debug() << "CUDA event " << event << " triggered on stream " << stream << " (GPU " << gpu << ")"; // give event back to GPU for reuse gpu->event_pool.return_event(event); // this event has triggered, so figure out the fence/notification to trigger // and also peek at the next event GPUWorkFence *fence = 0; GPUCompletionNotification *notification = 0; { AutoHSLLock al(mutex); const PendingEvent &e = pending_events.front(); assert(e.event == event); fence = e.fence; notification = e.notification; pending_events.pop_front(); if(pending_events.empty()) event_valid = false; else event = pending_events.front().event; } if(fence) fence->mark_finished(true /*successful*/); if(notification) notification->request_completed(); } // if we get all the way to here, we're (temporarily, at least) out of work return false; } //////////////////////////////////////////////////////////////////////// // // class GPUMemcpy GPUMemcpy::GPUMemcpy(GPU *_gpu, GPUMemcpyKind _kind) : gpu(_gpu), kind(_kind) {} //////////////////////////////////////////////////////////////////////// // // class GPUMemcpy1D GPUMemcpy1D::GPUMemcpy1D(GPU *_gpu, void *_dst, const void *_src, size_t _bytes, GPUMemcpyKind _kind, GPUCompletionNotification *_notification) : GPUMemcpy(_gpu, _kind), dst(_dst), src(_src), mask(0), elmt_size(_bytes), notification(_notification) {} GPUMemcpy1D::GPUMemcpy1D(GPU *_gpu, void *_dst, const void *_src, const ElementMask *_mask, size_t _elmt_size, GPUMemcpyKind _kind, GPUCompletionNotification *_notification) : GPUMemcpy(_gpu, _kind), dst(_dst), src(_src), mask(_mask), elmt_size(_elmt_size), notification(_notification) {} GPUMemcpy1D::~GPUMemcpy1D(void) {} void GPUMemcpy1D::do_span(off_t pos, size_t len) { off_t span_start = pos * elmt_size; size_t span_bytes = len * elmt_size; CUstream raw_stream = local_stream->get_stream(); log_stream.debug() << "memcpy added to stream " << raw_stream; switch (kind) { case GPU_MEMCPY_HOST_TO_DEVICE: { CHECK_CU( cuMemcpyHtoDAsync((CUdeviceptr)(((char*)dst)+span_start), (((char*)src)+span_start), span_bytes, raw_stream) ); break; } case GPU_MEMCPY_DEVICE_TO_HOST: { CHECK_CU( cuMemcpyDtoHAsync((((char*)dst)+span_start), (CUdeviceptr)(((char*)src)+span_start), span_bytes, raw_stream) ); break; } case GPU_MEMCPY_DEVICE_TO_DEVICE: { CHECK_CU( cuMemcpyDtoDAsync((CUdeviceptr)(((char*)dst)+span_start), (CUdeviceptr)(((char*)src)+span_start), span_bytes, raw_stream) ); break; } case GPU_MEMCPY_PEER_TO_PEER: { CUcontext src_ctx, dst_ctx; CHECK_CU( cuPointerGetAttribute(&src_ctx, CU_POINTER_ATTRIBUTE_CONTEXT, (CUdeviceptr)src) ); CHECK_CU( cuPointerGetAttribute(&dst_ctx, CU_POINTER_ATTRIBUTE_CONTEXT, (CUdeviceptr)dst) ); CHECK_CU( cuMemcpyPeerAsync((CUdeviceptr)(((char*)dst)+span_start), dst_ctx, (CUdeviceptr)(((char*)src)+span_start), src_ctx, span_bytes, raw_stream) ); break; } default: assert(false); } } void GPUMemcpy1D::execute(GPUStream *stream) { DetailedTimer::ScopedPush sp(TIME_COPY); log_gpudma.info("gpu memcpy: dst=%p src=%p bytes=%zd kind=%d", dst, src, elmt_size, kind); // save stream into local variable for do_spam (which may be called indirectly // by ElementMask::forall_ranges) local_stream = stream; if(mask) { ElementMask::forall_ranges(*this, *mask); } else { do_span(0, 1); } if(notification) stream->add_notification(notification); log_gpudma.info("gpu memcpy complete: dst=%p src=%p bytes=%zd kind=%d", dst, src, elmt_size, kind); } //////////////////////////////////////////////////////////////////////// // // class GPUMemcpy2D GPUMemcpy2D::GPUMemcpy2D(GPU *_gpu, void *_dst, const void *_src, off_t _dst_stride, off_t _src_stride, size_t _bytes, size_t _lines, GPUMemcpyKind _kind, GPUCompletionNotification *_notification) : GPUMemcpy(_gpu, _kind), dst(_dst), src(_src), dst_stride((_dst_stride < (off_t)_bytes) ? _bytes : _dst_stride), src_stride((_src_stride < (off_t)_bytes) ? _bytes : _src_stride), bytes(_bytes), lines(_lines), notification(_notification) {} GPUMemcpy2D::~GPUMemcpy2D(void) {} void GPUMemcpy2D::execute(GPUStream *stream) { log_gpudma.info("gpu memcpy 2d: dst=%p src=%p " "dst_off=%ld src_off=%ld bytes=%ld lines=%ld kind=%d", dst, src, (long)dst_stride, (long)src_stride, bytes, lines, kind); CUDA_MEMCPY2D copy_info; if (kind == GPU_MEMCPY_PEER_TO_PEER) { // If we're doing peer to peer, just let unified memory it deal with it copy_info.srcMemoryType = CU_MEMORYTYPE_UNIFIED; copy_info.dstMemoryType = CU_MEMORYTYPE_UNIFIED; } else { // otherwise we know the answers here copy_info.srcMemoryType = (kind == GPU_MEMCPY_HOST_TO_DEVICE) ? CU_MEMORYTYPE_HOST : CU_MEMORYTYPE_DEVICE; copy_info.dstMemoryType = (kind == GPU_MEMCPY_DEVICE_TO_HOST) ? CU_MEMORYTYPE_HOST : CU_MEMORYTYPE_DEVICE; } copy_info.srcDevice = (CUdeviceptr)src; copy_info.srcHost = src; copy_info.srcPitch = src_stride; copy_info.srcY = 0; copy_info.srcXInBytes = 0; copy_info.dstDevice = (CUdeviceptr)dst; copy_info.dstHost = dst; copy_info.dstPitch = dst_stride; copy_info.dstY = 0; copy_info.dstXInBytes = 0; copy_info.WidthInBytes = bytes; copy_info.Height = lines; CHECK_CU( cuMemcpy2DAsync(&copy_info, stream->get_stream()) ); if(notification) stream->add_notification(notification); log_gpudma.info("gpu memcpy 2d complete: dst=%p src=%p " "dst_off=%ld src_off=%ld bytes=%ld lines=%ld kind=%d", dst, src, (long)dst_stride, (long)src_stride, bytes, lines, kind); } //////////////////////////////////////////////////////////////////////// // // class GPUMemcpy3D GPUMemcpy3D::GPUMemcpy3D(GPU *_gpu, void *_dst, const void *_src, off_t _dst_stride, off_t _src_stride, off_t _dst_height, off_t _src_height, size_t _bytes, size_t _height, size_t _depth, GPUMemcpyKind _kind, GPUCompletionNotification *_notification) : GPUMemcpy(_gpu, _kind), dst(_dst), src(_src), dst_stride((_dst_stride < (off_t)_bytes) ? _bytes : _dst_stride), src_stride((_src_stride < (off_t)_bytes) ? _bytes : _src_stride), dst_height((_dst_height < (off_t)_height) ? _height : _dst_height), src_height((_src_height < (off_t)_height) ? _height : _src_height), bytes(_bytes), height(_height), depth(_depth), notification(_notification) {} GPUMemcpy3D::~GPUMemcpy3D(void) {} void GPUMemcpy3D::execute(GPUStream *stream) { log_gpudma.info("gpu memcpy 3d: dst=%p src=%p" "dst_off=%ld src_off=%ld dst_hei = %ld src_hei = %ld" "bytes=%ld height=%ld depth=%ld kind=%d", dst, src, (long)dst_stride, (long)src_stride, (long)dst_height, (long)src_height, bytes, height, depth, kind); CUDA_MEMCPY3D copy_info; if (kind == GPU_MEMCPY_PEER_TO_PEER) { // If we're doing peer to peer, just let unified memory it deal with it copy_info.srcMemoryType = CU_MEMORYTYPE_UNIFIED; copy_info.dstMemoryType = CU_MEMORYTYPE_UNIFIED; } else { // otherwise we know the answers here copy_info.srcMemoryType = (kind == GPU_MEMCPY_HOST_TO_DEVICE) ? CU_MEMORYTYPE_HOST : CU_MEMORYTYPE_DEVICE; copy_info.dstMemoryType = (kind == GPU_MEMCPY_DEVICE_TO_HOST) ? CU_MEMORYTYPE_HOST : CU_MEMORYTYPE_DEVICE; } copy_info.srcDevice = (CUdeviceptr)src; copy_info.srcHost = src; copy_info.srcPitch = src_stride; copy_info.srcHeight = src_height; copy_info.srcY = 0; copy_info.srcZ = 0; copy_info.srcXInBytes = 0; copy_info.srcLOD = 0; copy_info.dstDevice = (CUdeviceptr)dst; copy_info.dstHost = dst; copy_info.dstPitch = dst_stride; copy_info.dstHeight = dst_height; copy_info.dstY = 0; copy_info.dstZ = 0; copy_info.dstXInBytes = 0; copy_info.dstLOD = 0; copy_info.WidthInBytes = bytes; copy_info.Height = height; copy_info.Depth = depth; CHECK_CU( cuMemcpy3DAsync(&copy_info, stream->get_stream()) ); if(notification) stream->add_notification(notification); log_gpudma.info("gpu memcpy 3d complete: dst=%p src=%p" "dst_off=%ld src_off=%ld dst_hei = %ld src_hei = %ld" "bytes=%ld height=%ld depth=%ld kind=%d", dst, src, (long)dst_stride, (long)src_stride, (long)dst_height, (long)src_height, bytes, height, depth, kind); } //////////////////////////////////////////////////////////////////////// // // mem pair copiers for DMA channels class GPUtoFBMemPairCopier : public MemPairCopier { public: GPUtoFBMemPairCopier(Memory _src_mem, GPU *_gpu) : gpu(_gpu) { MemoryImpl *src_impl = get_runtime()->get_memory_impl(_src_mem); src_base = (const char *)(src_impl->get_direct_ptr(0, src_impl->size)); assert(src_base); } virtual ~GPUtoFBMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new LegionRuntime::LowLevel::SpanBasedInstPairCopier<GPUtoFBMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("gpu write of %zd bytes\n", bytes); gpu->copy_to_fb(dst_offset, src_base + src_offset, bytes); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { gpu->copy_to_fb_2d(dst_offset, src_base + src_offset, dst_stride, src_stride, bytes, lines); record_bytes(bytes * lines); } virtual void flush(DmaRequest *req) { if(total_reqs > 0) gpu->fence_to_fb(req); MemPairCopier::flush(req); } protected: const char *src_base; GPU *gpu; }; class GPUfromFBMemPairCopier : public MemPairCopier { public: GPUfromFBMemPairCopier(GPU *_gpu, Memory _dst_mem) : gpu(_gpu) { MemoryImpl *dst_impl = get_runtime()->get_memory_impl(_dst_mem); dst_base = (char *)(dst_impl->get_direct_ptr(0, dst_impl->size)); assert(dst_base); } virtual ~GPUfromFBMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new LegionRuntime::LowLevel::SpanBasedInstPairCopier<GPUfromFBMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("gpu read of %zd bytes\n", bytes); gpu->copy_from_fb(dst_base + dst_offset, src_offset, bytes); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { gpu->copy_from_fb_2d(dst_base + dst_offset, src_offset, dst_stride, src_stride, bytes, lines); record_bytes(bytes * lines); } virtual void flush(DmaRequest *req) { if(total_reqs > 0) gpu->fence_from_fb(req); MemPairCopier::flush(req); } protected: char *dst_base; GPU *gpu; }; class GPUinFBMemPairCopier : public MemPairCopier { public: GPUinFBMemPairCopier(GPU *_gpu) : gpu(_gpu) { } virtual ~GPUinFBMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new LegionRuntime::LowLevel::SpanBasedInstPairCopier<GPUinFBMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { //printf("gpu write of %zd bytes\n", bytes); gpu->copy_within_fb(dst_offset, src_offset, bytes); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { gpu->copy_within_fb_2d(dst_offset, src_offset, dst_stride, src_stride, bytes, lines); record_bytes(bytes * lines); } virtual void flush(DmaRequest *req) { if(total_reqs > 0) gpu->fence_within_fb(req); MemPairCopier::flush(req); } protected: GPU *gpu; }; class GPUPeerMemPairCopier : public MemPairCopier { public: GPUPeerMemPairCopier(GPU *_src, GPU *_dst) : src(_src), dst(_dst) { } virtual ~GPUPeerMemPairCopier(void) { } virtual InstPairCopier *inst_pair(RegionInstance src_inst, RegionInstance dst_inst, OASVec &oas_vec) { return new LegionRuntime::LowLevel::SpanBasedInstPairCopier<GPUPeerMemPairCopier>(this, src_inst, dst_inst, oas_vec); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes) { src->copy_to_peer(dst, dst_offset, src_offset, bytes); record_bytes(bytes); } void copy_span(off_t src_offset, off_t dst_offset, size_t bytes, off_t src_stride, off_t dst_stride, size_t lines) { src->copy_to_peer_2d(dst, dst_offset, src_offset, dst_stride, src_stride, bytes, lines); record_bytes(bytes * lines); } virtual void flush(DmaRequest *req) { if(total_reqs > 0) src->fence_to_peer(req, dst); MemPairCopier::flush(req); } protected: GPU *src, *dst; }; class GPUDMAChannel_H2D : public MemPairCopierFactory { public: GPUDMAChannel_H2D(GPU *_gpu); virtual bool can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); virtual MemPairCopier *create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); protected: GPU *gpu; }; class GPUDMAChannel_D2H : public MemPairCopierFactory { public: GPUDMAChannel_D2H(GPU *_gpu); virtual bool can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); virtual MemPairCopier *create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); protected: GPU *gpu; }; class GPUDMAChannel_D2D : public MemPairCopierFactory { public: GPUDMAChannel_D2D(GPU *_gpu); virtual bool can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); virtual MemPairCopier *create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); protected: GPU *gpu; }; class GPUDMAChannel_P2P : public MemPairCopierFactory { public: GPUDMAChannel_P2P(GPU *_gpu); virtual bool can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); virtual MemPairCopier *create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold); protected: GPU *gpu; }; //////////////////////////////////////////////////////////////////////// // // class GPUDMAChannel_H2D GPUDMAChannel_H2D::GPUDMAChannel_H2D(GPU *_gpu) : MemPairCopierFactory(stringbuilder() << "gpu_h2d (" << _gpu->proc->me << ")") , gpu(_gpu) {} bool GPUDMAChannel_H2D::can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // copies from pinned system memory to _our_ fb, no reduction support if(redop_id != 0) return false; if(gpu->pinned_sysmems.count(src_mem) == 0) return false; if(!(gpu->fbmem) || (dst_mem != gpu->fbmem->me)) return false; return true; } MemPairCopier *GPUDMAChannel_H2D::create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { return new GPUtoFBMemPairCopier(src_mem, gpu); } //////////////////////////////////////////////////////////////////////// // // class GPUDMAChannel_D2H GPUDMAChannel_D2H::GPUDMAChannel_D2H(GPU *_gpu) : MemPairCopierFactory(stringbuilder() << "gpu_d2h (" << _gpu->proc->me << ")") , gpu(_gpu) {} bool GPUDMAChannel_D2H::can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // copies from _our_ fb to pinned system memory, no reduction support if(redop_id != 0) return false; if(!(gpu->fbmem) || (src_mem != gpu->fbmem->me)) return false; if(gpu->pinned_sysmems.count(dst_mem) == 0) return false; return true; } LegionRuntime::LowLevel::MemPairCopier *GPUDMAChannel_D2H::create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { return new GPUfromFBMemPairCopier(gpu, dst_mem); } //////////////////////////////////////////////////////////////////////// // // class GPUDMAChannel_D2D GPUDMAChannel_D2D::GPUDMAChannel_D2D(GPU *_gpu) : MemPairCopierFactory(stringbuilder() << "gpu_d2d (" << _gpu->proc->me << ")") , gpu(_gpu) {} bool GPUDMAChannel_D2D::can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // copies entirely within our fb, no reduction support if(redop_id != 0) return false; if(!gpu->fbmem) return false; Memory our_fb = gpu->fbmem->me; if((src_mem != our_fb) || (dst_mem != our_fb)) return false; // they can't both be our FB return true; } MemPairCopier *GPUDMAChannel_D2D::create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { return new GPUinFBMemPairCopier(gpu); } //////////////////////////////////////////////////////////////////////// // // class GPUDMAChannel_P2P GPUDMAChannel_P2P::GPUDMAChannel_P2P(GPU *_gpu) : MemPairCopierFactory(stringbuilder() << "gpu_p2p (" << _gpu->proc->me << ")") , gpu(_gpu) {} bool GPUDMAChannel_P2P::can_perform_copy(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // copies from _our_ fb to a peer's fb, no reduction support if(redop_id != 0) return false; if(!(gpu->fbmem) || (src_mem != gpu->fbmem->me)) return false; if(gpu->peer_fbs.count(dst_mem) == 0) return false; return true; } MemPairCopier *GPUDMAChannel_P2P::create_copier(Memory src_mem, Memory dst_mem, ReductionOpID redop_id, bool fold) { // TODO: remove this - the p2p copier doesn't actually need it MemoryImpl *dst_impl = get_runtime()->get_memory_impl(dst_mem); GPU *dst_gpu = ((GPUFBMemory *)dst_impl)->gpu; return new GPUPeerMemPairCopier(gpu, dst_gpu); } void GPU::create_dma_channels(Realm::RuntimeImpl *r) { // <NEW_DMA> // Not a good design choice // For now, channel_manager will creates all channels // for GPUs in dma_all_gpus LegionRuntime::LowLevel::register_gpu_in_dma_systems(this); // </NEW_DMA> // if we don't have any framebuffer memory, we can't do any DMAs if(!fbmem) return; if(!pinned_sysmems.empty()) { r->add_dma_channel(new GPUDMAChannel_H2D(this)); r->add_dma_channel(new GPUDMAChannel_D2H(this)); // TODO: move into the dma channels themselves for(std::set<Memory>::const_iterator it = pinned_sysmems.begin(); it != pinned_sysmems.end(); ++it) { Machine::MemoryMemoryAffinity mma; mma.m1 = fbmem->me; mma.m2 = *it; mma.bandwidth = 20; // "medium" mma.latency = 200; // "bad" r->add_mem_mem_affinity(mma); } } else { log_gpu.warning() << "GPU " << proc->me << " has no pinned system memories!?"; } r->add_dma_channel(new GPUDMAChannel_D2D(this)); // only create a p2p channel if we have peers (and an fb) if(!peer_fbs.empty()) { r->add_dma_channel(new GPUDMAChannel_P2P(this)); // TODO: move into the dma channels themselves for(std::set<Memory>::const_iterator it = peer_fbs.begin(); it != peer_fbs.end(); ++it) { Machine::MemoryMemoryAffinity mma; mma.m1 = fbmem->me; mma.m2 = *it; mma.bandwidth = 10; // assuming pcie, this should be ~half the bw and mma.latency = 400; // ~twice the latency as zcmem r->add_mem_mem_affinity(mma); } } } //////////////////////////////////////////////////////////////////////// // // class GPUWorkFence GPUWorkFence::GPUWorkFence(Realm::Operation *op) : Realm::Operation::AsyncWorkItem(op) {} void GPUWorkFence::request_cancellation(void) { // ignored - no way to shoot down CUDA work } void GPUWorkFence::print(std::ostream& os) const { os << "GPUWorkFence"; } void GPUWorkFence::enqueue_on_stream(GPUStream *stream) { if(stream->get_gpu()->module->cfg_fences_use_callbacks) { CHECK_CU( cuStreamAddCallback(stream->get_stream(), &cuda_callback, (void *)this, 0) ); } else { stream->add_fence(this); } } /*static*/ void GPUWorkFence::cuda_callback(CUstream stream, CUresult res, void *data) { GPUWorkFence *me = (GPUWorkFence *)data; assert(res == CUDA_SUCCESS); me->mark_finished(true /*succesful*/); } //////////////////////////////////////////////////////////////////////// // // class GPUMemcpyFence GPUMemcpyFence::GPUMemcpyFence(GPU *_gpu, GPUMemcpyKind _kind, GPUWorkFence *_fence) : GPUMemcpy(_gpu, _kind), fence(_fence) { //log_stream.info() << "gpu memcpy fence " << this << " (fence = " << fence << ") created"; } void GPUMemcpyFence::execute(GPUStream *stream) { //log_stream.info() << "gpu memcpy fence " << this << " (fence = " << fence << ") executed"; fence->enqueue_on_stream(stream); #ifdef FORCE_GPU_STREAM_SYNCHRONIZE CHECK_CU( cuStreamSynchronize(stream->get_stream()) ); #endif } //////////////////////////////////////////////////////////////////////// // // class GPUEventPool GPUEventPool::GPUEventPool(int _batch_size) : batch_size(_batch_size), current_size(0), total_size(0) { // don't immediately fill the pool because we're not managing the context ourselves } // allocating the initial batch of events and cleaning up are done with // these methods instead of constructor/destructor because we don't // manage the GPU context in this helper class void GPUEventPool::init_pool(int init_size /*= 0 -- default == batch size */) { assert(available_events.empty()); if(init_size == 0) init_size = batch_size; available_events.resize(init_size); current_size = init_size; total_size = init_size; // TODO: measure how much benefit is derived from CU_EVENT_DISABLE_TIMING and // consider using them for completion callbacks for(int i = 0; i < init_size; i++) CHECK_CU( cuEventCreate(&available_events[i], CU_EVENT_DEFAULT) ); } void GPUEventPool::empty_pool(void) { // shouldn't be any events running around still assert(current_size == total_size); for(int i = 0; i < current_size; i++) CHECK_CU( cuEventDestroy(available_events[i]) ); current_size = 0; total_size = 0; // free internal vector storage std::vector<CUevent>().swap(available_events); } CUevent GPUEventPool::get_event(void) { AutoHSLLock al(mutex); if(current_size == 0) { // if we need to make an event, make a bunch current_size = batch_size; total_size += batch_size; log_stream.info() << "event pool " << this << " depleted - adding " << batch_size << " events"; // resize the vector (considering all events that might come back) available_events.resize(total_size); for(int i = 0; i < batch_size; i++) CHECK_CU( cuEventCreate(&available_events[i], CU_EVENT_DEFAULT) ); } return available_events[--current_size]; } void GPUEventPool::return_event(CUevent e) { AutoHSLLock al(mutex); assert(current_size < total_size); available_events[current_size++] = e; } //////////////////////////////////////////////////////////////////////// // // class GPUTaskScheduler<T> // we want to subclass the scheduler to replace the execute_task method, but we also want to // allow the use of user or kernel threads, so we apply a bit of template magic (which only works // because the constructors for the KernelThreadTaskScheduler and UserThreadTaskScheduler classes // have the same prototypes) template <typename T> class GPUTaskScheduler : public T { public: GPUTaskScheduler(Processor _proc, Realm::CoreReservation& _core_rsrv, GPUProcessor *_gpu_proc); virtual ~GPUTaskScheduler(void); protected: virtual bool execute_task(Task *task); // might also need to override the thread-switching methods to keep TLS up to date GPUProcessor *gpu_proc; }; template <typename T> GPUTaskScheduler<T>::GPUTaskScheduler(Processor _proc, Realm::CoreReservation& _core_rsrv, GPUProcessor *_gpu_proc) : T(_proc, _core_rsrv), gpu_proc(_gpu_proc) { // nothing else } template <typename T> GPUTaskScheduler<T>::~GPUTaskScheduler(void) { } namespace ThreadLocal { static __thread GPUProcessor *current_gpu_proc = 0; }; // this flag will be set on the first call into any of the hijack code in // cudart_hijack.cc // an application is linked with -lcudart, we will NOT be hijacking the // application's calls, and the cuda module needs to know that) /*extern*/ bool cudart_hijack_active = false; // used in GPUTaskScheduler<T>::execute_task below static bool already_issued_hijack_warning = false; template <typename T> bool GPUTaskScheduler<T>::execute_task(Task *task) { // use TLS to make sure that the task can find the current GPU processor when it makes // CUDA RT calls // TODO: either eliminate these asserts or do TLS swapping when using user threads assert(ThreadLocal::current_gpu_proc == 0); ThreadLocal::current_gpu_proc = gpu_proc; // push the CUDA context for this GPU onto this thread gpu_proc->gpu->push_context(); // bump the current stream // TODO: sanity-check whether this even works right when GPU tasks suspend GPUStream *s = gpu_proc->gpu->switch_to_next_task_stream(); // we'll use a "work fence" to track when the kernels launched by this task actually // finish - this must be added to the task _BEFORE_ we execute GPUWorkFence *fence = new GPUWorkFence(task); task->add_async_work_item(fence); bool ok = T::execute_task(task); // now enqueue the fence on the local stream fence->enqueue_on_stream(s); // A useful debugging macro #ifdef FORCE_GPU_STREAM_SYNCHRONIZE CHECK_CU( cuStreamSynchronize(s->get_stream()) ); #endif // if our hijack code is not active, the application may have put some work for this // task on streams we don't know about, so it takes an expensive device synchronization // to guarantee that any work enqueued on a stream in the future is ordered with respect // to this task's results if(!cudart_hijack_active) { // print a warning if this is the first time and it hasn't been suppressed if(!(gpu_proc->gpu->module->cfg_suppress_hijack_warning || already_issued_hijack_warning)) { already_issued_hijack_warning = true; log_gpu.warning() << "CUDART hijack code not active" << " - device synchronizations required after every GPU task!"; } CHECK_CU( cuCtxSynchronize() ); } // pop the CUDA context for this GPU back off gpu_proc->gpu->pop_context(); assert(ThreadLocal::current_gpu_proc == gpu_proc); ThreadLocal::current_gpu_proc = 0; return ok; } //////////////////////////////////////////////////////////////////////// // // class GPUProcessor GPUProcessor::GPUProcessor(GPU *_gpu, Processor _me, Realm::CoreReservationSet& crs, size_t _stack_size) : LocalTaskProcessor(_me, Processor::TOC_PROC) , gpu(_gpu) { Realm::CoreReservationParameters params; params.set_num_cores(1); params.set_alu_usage(params.CORE_USAGE_SHARED); params.set_fpu_usage(params.CORE_USAGE_SHARED); params.set_ldst_usage(params.CORE_USAGE_SHARED); params.set_max_stack_size(_stack_size); std::string name = stringbuilder() << "GPU proc " << _me; core_rsrv = new Realm::CoreReservation(name, crs, params); #ifdef REALM_USE_USER_THREADS_FOR_GPU Realm::UserThreadTaskScheduler *sched = new GPUTaskScheduler<Realm::UserThreadTaskScheduler>(me, *core_rsrv, this); // no config settings we want to tweak yet #else Realm::KernelThreadTaskScheduler *sched = new GPUTaskScheduler<Realm::KernelThreadTaskScheduler>(me, *core_rsrv, this); // no config settings we want to tweak yet #endif set_scheduler(sched); } GPUProcessor::~GPUProcessor(void) { delete core_rsrv; } void GPU::copy_to_fb(off_t dst_offset, const void *src, size_t bytes, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, (void *)(fbmem->base + dst_offset), src, bytes, GPU_MEMCPY_HOST_TO_DEVICE, notification); host_to_device_stream->add_copy(copy); } void GPU::copy_to_fb(off_t dst_offset, const void *src, const ElementMask *mask, size_t elmt_size, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, (void *)(fbmem->base + dst_offset), src, mask, elmt_size, GPU_MEMCPY_HOST_TO_DEVICE, notification); host_to_device_stream->add_copy(copy); } void GPU::copy_from_fb(void *dst, off_t src_offset, size_t bytes, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, dst, (const void *)(fbmem->base + src_offset), bytes, GPU_MEMCPY_DEVICE_TO_HOST, notification); device_to_host_stream->add_copy(copy); } void GPU::copy_from_fb(void *dst, off_t src_offset, const ElementMask *mask, size_t elmt_size, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, dst, (const void *)(fbmem->base + src_offset), mask, elmt_size, GPU_MEMCPY_DEVICE_TO_HOST, notification); device_to_host_stream->add_copy(copy); } void GPU::copy_within_fb(off_t dst_offset, off_t src_offset, size_t bytes, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, (void *)(fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), bytes, GPU_MEMCPY_DEVICE_TO_DEVICE, notification); device_to_device_stream->add_copy(copy); } void GPU::copy_within_fb(off_t dst_offset, off_t src_offset, const ElementMask *mask, size_t elmt_size, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, (void *)(fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), mask, elmt_size, GPU_MEMCPY_DEVICE_TO_DEVICE, notification); device_to_device_stream->add_copy(copy); } void GPU::copy_to_fb_2d(off_t dst_offset, const void *src, off_t dst_stride, off_t src_stride, size_t bytes, size_t lines, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy2D(this, (void *)(fbmem->base + dst_offset), src, dst_stride, src_stride, bytes, lines, GPU_MEMCPY_HOST_TO_DEVICE, notification); host_to_device_stream->add_copy(copy); } void GPU::copy_to_fb_3d(off_t dst_offset, const void *src, off_t dst_stride, off_t src_stride, off_t dst_height, off_t src_height, size_t bytes, size_t height, size_t depth, GPUCompletionNotification *notification /* = 0*/) { GPUMemcpy *copy = new GPUMemcpy3D(this, (void *)(fbmem->base + dst_offset), src, dst_stride, src_stride, dst_height, src_height, bytes, height, depth, GPU_MEMCPY_HOST_TO_DEVICE, notification); host_to_device_stream->add_copy(copy); } void GPU::copy_from_fb_2d(void *dst, off_t src_offset, off_t dst_stride, off_t src_stride, size_t bytes, size_t lines, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy2D(this, dst, (const void *)(fbmem->base + src_offset), dst_stride, src_stride, bytes, lines, GPU_MEMCPY_DEVICE_TO_HOST, notification); device_to_host_stream->add_copy(copy); } void GPU::copy_from_fb_3d(void *dst, off_t src_offset, off_t dst_stride, off_t src_stride, off_t dst_height, off_t src_height, size_t bytes, size_t height, size_t depth, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy3D(this, dst, (const void *)(fbmem->base + src_offset), dst_stride, src_stride, dst_height, src_height, bytes, height, depth, GPU_MEMCPY_DEVICE_TO_HOST, notification); device_to_host_stream->add_copy(copy); } void GPU::copy_within_fb_2d(off_t dst_offset, off_t src_offset, off_t dst_stride, off_t src_stride, size_t bytes, size_t lines, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy2D(this, (void *)(fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), dst_stride, src_stride, bytes, lines, GPU_MEMCPY_DEVICE_TO_DEVICE, notification); device_to_device_stream->add_copy(copy); } void GPU::copy_within_fb_3d(off_t dst_offset, off_t src_offset, off_t dst_stride, off_t src_stride, off_t dst_height, off_t src_height, size_t bytes, size_t height, size_t depth, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy3D(this, (void *)(fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), dst_stride, src_stride, dst_height, src_height, bytes, height, depth, GPU_MEMCPY_DEVICE_TO_DEVICE, notification); device_to_device_stream->add_copy(copy); } void GPU::copy_to_peer(GPU *dst, off_t dst_offset, off_t src_offset, size_t bytes, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy1D(this, (void *)(dst->fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), bytes, GPU_MEMCPY_PEER_TO_PEER, notification); peer_to_peer_stream->add_copy(copy); } void GPU::copy_to_peer_2d(GPU *dst, off_t dst_offset, off_t src_offset, off_t dst_stride, off_t src_stride, size_t bytes, size_t lines, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy2D(this, (void *)(dst->fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), dst_stride, src_stride, bytes, lines, GPU_MEMCPY_PEER_TO_PEER, notification); peer_to_peer_stream->add_copy(copy); } void GPU::copy_to_peer_3d(GPU *dst, off_t dst_offset, off_t src_offset, off_t dst_stride, off_t src_stride, off_t dst_height, off_t src_height, size_t bytes, size_t height, size_t depth, GPUCompletionNotification *notification /*= 0*/) { GPUMemcpy *copy = new GPUMemcpy3D(this, (void *)(dst->fbmem->base + dst_offset), (const void *)(fbmem->base + src_offset), dst_stride, src_stride, dst_height, src_height, bytes, height, depth, GPU_MEMCPY_PEER_TO_PEER, notification); peer_to_peer_stream->add_copy(copy); } void GPU::fence_to_fb(Realm::Operation *op) { GPUWorkFence *f = new GPUWorkFence(op); // this must be done before we enqueue the callback with CUDA op->add_async_work_item(f); host_to_device_stream->add_copy(new GPUMemcpyFence(this, GPU_MEMCPY_HOST_TO_DEVICE, f)); } void GPU::fence_from_fb(Realm::Operation *op) { GPUWorkFence *f = new GPUWorkFence(op); // this must be done before we enqueue the callback with CUDA op->add_async_work_item(f); device_to_host_stream->add_copy(new GPUMemcpyFence(this, GPU_MEMCPY_DEVICE_TO_HOST, f)); } void GPU::fence_within_fb(Realm::Operation *op) { GPUWorkFence *f = new GPUWorkFence(op); // this must be done before we enqueue the callback with CUDA op->add_async_work_item(f); device_to_device_stream->add_copy(new GPUMemcpyFence(this, GPU_MEMCPY_DEVICE_TO_DEVICE, f)); } void GPU::fence_to_peer(Realm::Operation *op, GPU *dst) { GPUWorkFence *f = new GPUWorkFence(op); // this must be done before we enqueue the callback with CUDA op->add_async_work_item(f); peer_to_peer_stream->add_copy(new GPUMemcpyFence(this, GPU_MEMCPY_PEER_TO_PEER, f)); } GPUStream *GPU::get_current_task_stream(void) { return task_streams[current_stream]; } GPUStream *GPU::switch_to_next_task_stream(void) { current_stream++; if(current_stream >= task_streams.size()) current_stream = 0; return task_streams[current_stream]; } void GPUProcessor::shutdown(void) { log_gpu.info("shutting down"); // shut down threads/scheduler LocalTaskProcessor::shutdown(); // synchronize the device so we can flush any printf buffers - do // this after shutting down the threads so that we know all work is done { AutoGPUContext agc(gpu); CHECK_CU( cuCtxSynchronize() ); } } GPUWorker::GPUWorker(void) : condvar(lock) , core_rsrv(0), worker_thread(0), worker_shutdown_requested(false) {} GPUWorker::~GPUWorker(void) { // shutdown should have already been called assert(worker_thread == 0); } void GPUWorker::start_background_thread(Realm::CoreReservationSet &crs, size_t stack_size) { core_rsrv = new Realm::CoreReservation("GPU worker thread", crs, Realm::CoreReservationParameters()); Realm::ThreadLaunchParameters tlp; worker_thread = Realm::Thread::create_kernel_thread<GPUWorker, &GPUWorker::thread_main>(this, tlp, *core_rsrv, 0); } void GPUWorker::shutdown_background_thread(void) { { AutoHSLLock al(lock); worker_shutdown_requested = true; condvar.broadcast(); } worker_thread->join(); delete worker_thread; worker_thread = 0; delete core_rsrv; core_rsrv = 0; } void GPUWorker::add_stream(GPUStream *stream) { AutoHSLLock al(lock); // if the stream is already in the set, nothing to do if(active_streams.count(stream) > 0) return; active_streams.insert(stream); condvar.broadcast(); } bool GPUWorker::process_streams(bool sleep_on_empty) { // we start by grabbing the list of active streams, replacing it with an // empty list - this way we don't have to hold the lock the whole time // for any stream that we leave work on, we'll add it back in std::set<GPUStream *> streams; { AutoHSLLock al(lock); while(active_streams.empty()) { if(!sleep_on_empty || worker_shutdown_requested) return false; condvar.wait(); } streams.swap(active_streams); } bool any_work_left = false; for(std::set<GPUStream *>::const_iterator it = streams.begin(); it != streams.end(); it++) { GPUStream *s = *it; bool stream_work_left = false; if(s->issue_copies()) stream_work_left = true; if(s->reap_events()) stream_work_left = true; if(stream_work_left) { add_stream(s); any_work_left = true; } } return any_work_left; } void GPUWorker::thread_main(void) { // TODO: consider busy-waiting in some cases to reduce latency? while(!worker_shutdown_requested) { bool work_left = process_streams(true); // if there was work left, yield our thread for now to avoid a tight spin loop // TODO: enqueue a callback so we can go to sleep and wake up sooner than a kernel // timeslice? if(work_left) Realm::Thread::yield(); } } //////////////////////////////////////////////////////////////////////// // // class BlockingCompletionNotification class BlockingCompletionNotification : public GPUCompletionNotification { public: BlockingCompletionNotification(void); virtual ~BlockingCompletionNotification(void); virtual void request_completed(void); virtual void wait(void); public: GASNetHSL mutex; GASNetCondVar cv; bool completed; }; BlockingCompletionNotification::BlockingCompletionNotification(void) : cv(mutex) , completed(false) {} BlockingCompletionNotification::~BlockingCompletionNotification(void) {} void BlockingCompletionNotification::request_completed(void) { AutoHSLLock a(mutex); assert(!completed); completed = true; cv.broadcast(); } void BlockingCompletionNotification::wait(void) { AutoHSLLock a(mutex); while(!completed) cv.wait(); } //////////////////////////////////////////////////////////////////////// // // class GPU GPUFBMemory::GPUFBMemory(Memory _me, GPU *_gpu, CUdeviceptr _base, size_t _size) : MemoryImpl(_me, _size, MKIND_GPUFB, 512, Memory::GPU_FB_MEM) , gpu(_gpu), base(_base) { free_blocks[0] = size; } GPUFBMemory::~GPUFBMemory(void) {} RegionInstance GPUFBMemory::create_instance(IndexSpace is, const int *linearization_bits, size_t bytes_needed, size_t block_size, size_t element_size, const std::vector<size_t>& field_sizes, ReductionOpID redopid, off_t list_size, const Realm::ProfilingRequestSet &reqs, RegionInstance parent_inst) { return create_instance_local(is, linearization_bits, bytes_needed, block_size, element_size, field_sizes, redopid, list_size, reqs, parent_inst); } void GPUFBMemory::destroy_instance(RegionInstance i, bool local_destroy) { destroy_instance_local(i, local_destroy); } off_t GPUFBMemory::alloc_bytes(size_t size) { return alloc_bytes_local(size); } void GPUFBMemory::free_bytes(off_t offset, size_t size) { free_bytes_local(offset, size); } // these work, but they are SLOW void GPUFBMemory::get_bytes(off_t offset, void *dst, size_t size) { // create an async copy and then wait for it to finish... BlockingCompletionNotification bcn; gpu->copy_from_fb(dst, offset, size, &bcn); bcn.wait(); } void GPUFBMemory::put_bytes(off_t offset, const void *src, size_t size) { // create an async copy and then wait for it to finish... BlockingCompletionNotification bcn; gpu->copy_to_fb(offset, src, size, &bcn); bcn.wait(); } void *GPUFBMemory::get_direct_ptr(off_t offset, size_t size) { return (void *)(base + offset); } int GPUFBMemory::get_home_node(off_t offset, size_t size) { return -1; } //////////////////////////////////////////////////////////////////////// // // class GPUZCMemory GPUZCMemory::GPUZCMemory(Memory _me, CUdeviceptr _gpu_base, void *_cpu_base, size_t _size) : MemoryImpl(_me, _size, MKIND_ZEROCOPY, 256, Memory::Z_COPY_MEM) , gpu_base(_gpu_base), cpu_base((char *)_cpu_base) { free_blocks[0] = size; } GPUZCMemory::~GPUZCMemory(void) {} RegionInstance GPUZCMemory::create_instance(IndexSpace is, const int *linearization_bits, size_t bytes_needed, size_t block_size, size_t element_size, const std::vector<size_t>& field_sizes, ReductionOpID redopid, off_t list_size, const Realm::ProfilingRequestSet &reqs, RegionInstance parent_inst) { return create_instance_local(is, linearization_bits, bytes_needed, block_size, element_size, field_sizes, redopid, list_size, reqs, parent_inst); } void GPUZCMemory::destroy_instance(RegionInstance i, bool local_destroy) { destroy_instance_local(i, local_destroy); } off_t GPUZCMemory::alloc_bytes(size_t size) { return alloc_bytes_local(size); } void GPUZCMemory::free_bytes(off_t offset, size_t size) { free_bytes_local(offset, size); } void GPUZCMemory::get_bytes(off_t offset, void *dst, size_t size) { memcpy(dst, cpu_base+offset, size); } void GPUZCMemory::put_bytes(off_t offset, const void *src, size_t size) { memcpy(cpu_base+offset, src, size); } void *GPUZCMemory::get_direct_ptr(off_t offset, size_t size) { return (cpu_base + offset); } int GPUZCMemory::get_home_node(off_t offset, size_t size) { return ID(me).memory.owner_node; } #ifdef POINTER_CHECKS static unsigned *get_gpu_valid_mask(RegionMetaDataUntyped region) { const ElementMask &mask = region.get_valid_mask(); void *valid_mask_base; for(size_t p = 0; p < mask.raw_size(); p += 4) log_gpudma.info(" raw mask data[%zd] = %08x\n", p, ((unsigned *)(mask.get_raw()))[p>>2]); CHECK_CU( cuMemAlloc((cuDevicePtr*)(&valid_mask_base), mask.raw_size()) ); log_gpudma.info("copy of valid mask (%zd bytes) created at %p", mask.raw_size(), valid_mask_base); CHECK_CU( cuMemcpyHtoD(vald_mask_base, mask.get_raw(), mask.raw_size()) ); return (unsigned *)&(((ElementMaskImpl *)valid_mask_base)->bits); } #endif // Helper methods for emulating the cuda runtime /*static*/ GPUProcessor* GPUProcessor::get_current_gpu_proc(void) { return ThreadLocal::current_gpu_proc; } void GPUProcessor::stream_synchronize(cudaStream_t stream) { // same as device_synchronize for now GPUStream *current = gpu->get_current_task_stream(); CHECK_CU( cuStreamSynchronize(current->get_stream()) ); } void GPUProcessor::device_synchronize(void) { GPUStream *current = gpu->get_current_task_stream(); CHECK_CU( cuStreamSynchronize(current->get_stream()) ); } void GPUProcessor::event_create(cudaEvent_t *event, int flags) { // int cu_flags = CU_EVENT_DEFAULT; // if((flags & cudaEventBlockingSync) != 0) // cu_flags |= CU_EVENT_BLOCKING_SYNC; // if((flags & cudaEventDisableTiming) != 0) // cu_flags |= CU_EVENT_DISABLE_TIMING; // get an event from our event pool (ignoring the flags for now) CUevent e = gpu->event_pool.get_event(); *event = e; } void GPUProcessor::event_destroy(cudaEvent_t event) { // assume the event is one of ours and put it back in the pool CUevent e = event; if(e) gpu->event_pool.return_event(e); } void GPUProcessor::event_record(cudaEvent_t event, cudaStream_t stream) { // ignore the provided stream and record the event on this task's assigned stream CUevent e = event; GPUStream *current = gpu->get_current_task_stream(); CHECK_CU( cuEventRecord(e, current->get_stream()) ); } void GPUProcessor::event_synchronize(cudaEvent_t event) { // TODO: consider suspending task rather than busy-waiting here... CUevent e = event; CHECK_CU( cuEventSynchronize(e) ); } void GPUProcessor::event_elapsed_time(float *ms, cudaEvent_t start, cudaEvent_t end) { // TODO: consider suspending task rather than busy-waiting here... CUevent e1 = start; CUevent e2 = end; CHECK_CU( cuEventElapsedTime(ms, e1, e2) ); } GPUProcessor::LaunchConfig::LaunchConfig(dim3 _grid, dim3 _block, size_t _shared) : grid(_grid), block(_block), shared(_shared) {} void GPUProcessor::configure_call(dim3 grid_dim, dim3 block_dim, size_t shared_mem, cudaStream_t stream) { launch_configs.push_back(LaunchConfig(grid_dim, block_dim, shared_mem)); } void GPUProcessor::setup_argument(const void *arg, size_t size, size_t offset) { size_t required = offset + size; if(required > kernel_args.size()) kernel_args.resize(required); memcpy(&kernel_args[offset], arg, size); } void GPUProcessor::launch(const void *func) { // make sure we have a launch config assert(!launch_configs.empty()); LaunchConfig &config = launch_configs.back(); // Find our function CUfunction f = gpu->lookup_function(func); size_t arg_size = kernel_args.size(); void *extra[] = { CU_LAUNCH_PARAM_BUFFER_POINTER, &kernel_args[0], CU_LAUNCH_PARAM_BUFFER_SIZE, &arg_size, CU_LAUNCH_PARAM_END }; CUstream raw_stream = gpu->get_current_task_stream()->get_stream(); log_stream.debug() << "kernel " << func << " added to stream " << raw_stream; // Launch the kernel on our stream dammit! CHECK_CU( cuLaunchKernel(f, config.grid.x, config.grid.y, config.grid.z, config.block.x, config.block.y, config.block.z, config.shared, raw_stream, NULL, extra) ); // pop the config we just used launch_configs.pop_back(); // clear out the kernel args kernel_args.clear(); } void GPUProcessor::gpu_memcpy(void *dst, const void *src, size_t size, cudaMemcpyKind kind) { CUstream current = gpu->get_current_task_stream()->get_stream(); // the synchronous copy still uses cuMemcpyAsync so that we can limit the // synchronization to just the right stream CHECK_CU( cuMemcpyAsync((CUdeviceptr)dst, (CUdeviceptr)src, size, current) ); CHECK_CU( cuStreamSynchronize(current) ); } void GPUProcessor::gpu_memcpy_async(void *dst, const void *src, size_t size, cudaMemcpyKind kind, cudaStream_t stream) { CUstream current = gpu->get_current_task_stream()->get_stream(); CHECK_CU( cuMemcpyAsync((CUdeviceptr)dst, (CUdeviceptr)src, size, current) ); // no synchronization here } void GPUProcessor::gpu_memcpy_to_symbol(const void *dst, const void *src, size_t size, size_t offset, cudaMemcpyKind kind) { CUstream current = gpu->get_current_task_stream()->get_stream(); CUdeviceptr var_base = gpu->lookup_variable(dst); CHECK_CU( cuMemcpyAsync(var_base + offset, (CUdeviceptr)src, size, current) ); CHECK_CU( cuStreamSynchronize(current) ); } void GPUProcessor::gpu_memcpy_to_symbol_async(const void *dst, const void *src, size_t size, size_t offset, cudaMemcpyKind kind, cudaStream_t stream) { CUstream current = gpu->get_current_task_stream()->get_stream(); CUdeviceptr var_base = gpu->lookup_variable(dst); CHECK_CU( cuMemcpyAsync(var_base + offset, (CUdeviceptr)src, size, current) ); // no synchronization here } void GPUProcessor::gpu_memcpy_from_symbol(void *dst, const void *src, size_t size, size_t offset, cudaMemcpyKind kind) { CUstream current = gpu->get_current_task_stream()->get_stream(); CUdeviceptr var_base = gpu->lookup_variable(src); CHECK_CU( cuMemcpyAsync((CUdeviceptr)dst, var_base + offset, size, current) ); CHECK_CU( cuStreamSynchronize(current) ); } void GPUProcessor::gpu_memcpy_from_symbol_async(void *dst, const void *src, size_t size, size_t offset, cudaMemcpyKind kind, cudaStream_t stream) { CUstream current = gpu->get_current_task_stream()->get_stream(); CUdeviceptr var_base = gpu->lookup_variable(src); CHECK_CU( cuMemcpyAsync((CUdeviceptr)dst, var_base + offset, size, current) ); // no synchronization here } //////////////////////////////////////////////////////////////////////// // // class GPU GPU::GPU(CudaModule *_module, GPUInfo *_info, GPUWorker *_worker, int num_streams) : module(_module), info(_info), worker(_worker) , proc(0), fbmem(0), current_stream(0) { // create a CUDA context for our device - automatically becomes current CHECK_CU( cuCtxCreate(&context, CU_CTX_MAP_HOST | CU_CTX_SCHED_BLOCKING_SYNC, info->device) ); event_pool.init_pool(); host_to_device_stream = new GPUStream(this, worker); device_to_host_stream = new GPUStream(this, worker); device_to_device_stream = new GPUStream(this, worker); peer_to_peer_stream = new GPUStream(this, worker); task_streams.resize(num_streams); for(int idx = 0; idx < num_streams; idx++) task_streams[idx] = new GPUStream(this, worker); pop_context(); // now hook into the cuda runtime fatbin/etc. registration path GlobalRegistrations::add_gpu_context(this); } GPU::~GPU(void) { push_context(); event_pool.empty_pool(); // destroy streams delete host_to_device_stream; delete device_to_host_stream; delete device_to_device_stream; delete peer_to_peer_stream; while(!task_streams.empty()) { delete task_streams.back(); task_streams.pop_back(); } // free memory CHECK_CU( cuMemFree(fbmem_base) ); CHECK_CU( cuCtxDestroy(context) ); } void GPU::push_context(void) { CHECK_CU( cuCtxPushCurrent(context) ); } void GPU::pop_context(void) { // the context we pop had better be ours... CUcontext popped; CHECK_CU( cuCtxPopCurrent(&popped) ); assert(popped == context); } void GPU::create_processor(RuntimeImpl *runtime, size_t stack_size) { Processor p = runtime->next_local_processor_id(); proc = new GPUProcessor(this, p, runtime->core_reservation_set(), stack_size); runtime->add_processor(proc); // this processor is able to access its own FB and the ZC mem (if any) if(fbmem) { Machine::ProcessorMemoryAffinity pma; pma.p = p; pma.m = fbmem->me; pma.bandwidth = 200; // "big" pma.latency = 5; // "ok" runtime->add_proc_mem_affinity(pma); } if(module->zcmem) { Machine::ProcessorMemoryAffinity pma; pma.p = p; pma.m = module->zcmem->me; pma.bandwidth = 20; // "medium" pma.latency = 200; // "bad" runtime->add_proc_mem_affinity(pma); } // peer access for(std::vector<GPU *>::iterator it = module->gpus.begin(); it != module->gpus.end(); it++) { // ignore ourselves if(*it == this) continue; // ignore gpus that we don't expect to be able to peer with if(info->peers.count((*it)->info->device) == 0) continue; // ignore gpus with no fb if(!((*it)->fbmem)) continue; // enable peer access { AutoGPUContext agc(this); CHECK_CU( cuCtxEnablePeerAccess((*it)->context, 0) ); } log_gpu.print() << "peer access enabled from GPU " << p << " to FB " << (*it)->fbmem->me; peer_fbs.insert((*it)->fbmem->me); { Machine::ProcessorMemoryAffinity pma; pma.p = p; pma.m = (*it)->fbmem->me; pma.bandwidth = 10; // assuming pcie, this should be ~half the bw and pma.latency = 400; // ~twice the latency as zcmem runtime->add_proc_mem_affinity(pma); } } } void GPU::create_fb_memory(RuntimeImpl *runtime, size_t size) { // need the context so we can get an allocation in the right place { AutoGPUContext agc(this); CHECK_CU( cuMemAlloc(&fbmem_base, size) ); } Memory m = runtime->next_local_memory_id(); fbmem = new GPUFBMemory(m, this, fbmem_base, size); runtime->add_memory(fbmem); } void GPU::register_fat_binary(const FatBin *fatbin) { AutoGPUContext agc(this); log_gpu.info() << "registering fat binary " << fatbin << " with GPU " << this; // have we see this one already? if(device_modules.count(fatbin) > 0) { log_gpu.warning() << "duplicate registration of fat binary data " << fatbin; return; } if(fatbin->data != 0) { // binary data to be loaded with cuModuleLoad(Ex) CUmodule module = load_cuda_module(fatbin->data); device_modules[fatbin] = module; return; } assert(0); } void GPU::register_variable(const RegisteredVariable *var) { AutoGPUContext agc(this); log_gpu.debug() << "registering variable " << var->device_name << " (" << var->host_var << ") with GPU " << this; // have we seen it already? if(device_variables.count(var->host_var) > 0) { log_gpu.warning() << "duplicate registration of variable " << var->device_name; return; } // get the module it lives in std::map<const FatBin *, CUmodule>::const_iterator it = device_modules.find(var->fat_bin); assert(it != device_modules.end()); CUmodule module = it->second; CUdeviceptr ptr; size_t size; CHECK_CU( cuModuleGetGlobal(&ptr, &size, module, var->device_name) ); device_variables[var->host_var] = ptr; } void GPU::register_function(const RegisteredFunction *func) { AutoGPUContext agc(this); log_gpu.debug() << "registering function " << func->device_fun << " (" << func->host_fun << ") with GPU " << this; // have we seen it already? if(device_functions.count(func->host_fun) > 0) { log_gpu.warning() << "duplicate registration of function " << func->device_fun; return; } // get the module it lives in std::map<const FatBin *, CUmodule>::const_iterator it = device_modules.find(func->fat_bin); assert(it != device_modules.end()); CUmodule module = it->second; CUfunction f; CHECK_CU( cuModuleGetFunction(&f, module, func->device_fun) ); device_functions[func->host_fun] = f; } CUfunction GPU::lookup_function(const void *func) { std::map<const void *, CUfunction>::iterator finder = device_functions.find(func); assert(finder != device_functions.end()); return finder->second; } CUdeviceptr GPU::lookup_variable(const void *var) { std::map<const void *, CUdeviceptr>::iterator finder = device_variables.find(var); assert(finder != device_variables.end()); return finder->second; } CUmodule GPU::load_cuda_module(const void *data) { const unsigned num_options = 4; CUjit_option jit_options[num_options]; void* option_vals[num_options]; const size_t buffer_size = 16384; char* log_info_buffer = (char*)malloc(buffer_size); char* log_error_buffer = (char*)malloc(buffer_size); jit_options[0] = CU_JIT_INFO_LOG_BUFFER; jit_options[1] = CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES; jit_options[2] = CU_JIT_ERROR_LOG_BUFFER; jit_options[3] = CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES; option_vals[0] = log_info_buffer; option_vals[1] = (void*)buffer_size; option_vals[2] = log_error_buffer; option_vals[3] = (void*)buffer_size; CUmodule module; CUresult result = cuModuleLoadDataEx(&module, data, num_options, jit_options, option_vals); if (result != CUDA_SUCCESS) { #ifdef __MACH__ if (result == CUDA_ERROR_OPERATING_SYSTEM) { log_gpu.error("ERROR: Device side asserts are not supported by the " "CUDA driver for MAC OSX, see NVBugs 1628896."); } #endif if (result == CUDA_ERROR_NO_BINARY_FOR_GPU) { log_gpu.error("ERROR: The binary was compiled for the wrong GPU " "architecture. Update the 'GPU_ARCH' flag at the top " "of runtime/runtime.mk to match your current GPU " "architecture."); } log_gpu.error("Failed to load CUDA module! Error log: %s", log_error_buffer); #if CUDA_VERSION >= 6050 const char *name, *str; CHECK_CU( cuGetErrorName(result, &name) ); CHECK_CU( cuGetErrorString(result, &str) ); fprintf(stderr,"CU: cuModuleLoadDataEx = %d (%s): %s\n", result, name, str); #else fprintf(stderr,"CU: cuModuleLoadDataEx = %d\n", result); #endif assert(0); } else log_gpu.info("Loaded CUDA Module. JIT Output: %s", log_info_buffer); free(log_info_buffer); free(log_error_buffer); return module; } //////////////////////////////////////////////////////////////////////// // // class AutoGPUContext AutoGPUContext::AutoGPUContext(GPU& _gpu) : gpu(&_gpu) { gpu->push_context(); } AutoGPUContext::AutoGPUContext(GPU *_gpu) : gpu(_gpu) { gpu->push_context(); } AutoGPUContext::~AutoGPUContext(void) { gpu->pop_context(); } //////////////////////////////////////////////////////////////////////// // // class CudaModule // our interface to the rest of the runtime CudaModule::CudaModule(void) : Module("cuda") , cfg_zc_mem_size_in_mb(64) , cfg_fb_mem_size_in_mb(256) , cfg_num_gpus(0) , cfg_gpu_streams(12) , cfg_use_background_workers(true) , cfg_use_shared_worker(true) , cfg_pin_sysmem(true) , cfg_fences_use_callbacks(false) , cfg_suppress_hijack_warning(false) , shared_worker(0), zcmem_cpu_base(0), zcmem(0) {} CudaModule::~CudaModule(void) {} /*static*/ Module *CudaModule::create_module(RuntimeImpl *runtime, std::vector<std::string>& cmdline) { // before we do anything, make sure there's a CUDA driver and GPUs to talk to std::vector<GPUInfo *> infos; { CUresult ret = cuInit(0); if(ret != CUDA_SUCCESS) { log_gpu.warning() << "cuInit(0) returned " << ret << " - module not loaded"; return 0; } int num_devices; CHECK_CU( cuDeviceGetCount(&num_devices) ); for(int i = 0; i < num_devices; i++) { GPUInfo *info = new GPUInfo; // TODO: consider environment variables or other ways to tell if certain // GPUs should be ignored info->index = i; CHECK_CU( cuDeviceGet(&info->device, i) ); CHECK_CU( cuDeviceGetName(info->name, GPUInfo::MAX_NAME_LEN, info->device) ); CHECK_CU( cuDeviceComputeCapability(&info->compute_major, &info->compute_minor, info->device) ); CHECK_CU( cuDeviceTotalMem(&info->total_mem, info->device) ); CHECK_CU( cuDeviceGetProperties(&info->props, info->device) ); log_gpu.info() << "GPU #" << i << ": " << info->name << " (" << info->compute_major << '.' << info->compute_minor << ") " << (info->total_mem >> 20) << " MB"; infos.push_back(info); } if(infos.empty()) { log_gpu.warning() << "no CUDA-capable GPUs found - module not loaded"; return 0; } // query peer-to-peer access (all pairs) for(std::vector<GPUInfo *>::iterator it1 = infos.begin(); it1 != infos.end(); it1++) for(std::vector<GPUInfo *>::iterator it2 = infos.begin(); it2 != infos.end(); it2++) if(it1 != it2) { int can_access; CHECK_CU( cuDeviceCanAccessPeer(&can_access, (*it1)->device, (*it2)->device) ); if(can_access) { log_gpu.info() << "p2p access from device " << (*it1)->index << " to device " << (*it2)->index; (*it1)->peers.insert((*it2)->device); } } } CudaModule *m = new CudaModule; // give the gpu info we assembled to the module m->gpu_info.swap(infos); // first order of business - read command line parameters { CommandLineParser cp; cp.add_option_int("-ll:fsize", m->cfg_fb_mem_size_in_mb) .add_option_int("-ll:zsize", m->cfg_zc_mem_size_in_mb) .add_option_int("-ll:gpu", m->cfg_num_gpus) .add_option_int("-ll:streams", m->cfg_gpu_streams) .add_option_int("-ll:gpuworker", m->cfg_use_shared_worker) .add_option_int("-ll:pin", m->cfg_pin_sysmem) .add_option_bool("-cuda:callbacks", m->cfg_fences_use_callbacks) .add_option_bool("-cuda:nohijack", m->cfg_suppress_hijack_warning); bool ok = cp.parse_command_line(cmdline); if(!ok) { log_gpu.error() << "error reading CUDA command line parameters"; exit(1); } } return m; } // do any general initialization - this is called after all configuration is // complete void CudaModule::initialize(RuntimeImpl *runtime) { Module::initialize(runtime); // sanity-check: do we even have enough gpus? if(cfg_num_gpus > gpu_info.size()) { log_gpu.fatal() << cfg_num_gpus << " GPUs requested, but only " << gpu_info.size() << " available!"; assert(false); } // if we are using a shared worker, create that next if(cfg_use_shared_worker) { shared_worker = new GPUWorker; if(cfg_use_background_workers) shared_worker->start_background_thread(runtime->core_reservation_set(), 1 << 20); // hardcoded worker stack size } // just use the GPUs in order right now gpus.resize(cfg_num_gpus); for(unsigned i = 0; i < cfg_num_gpus; i++) { // either create a worker for this GPU or use the shared one GPUWorker *worker; if(cfg_use_shared_worker) { worker = shared_worker; } else { worker = new GPUWorker; if(cfg_use_background_workers) worker->start_background_thread(runtime->core_reservation_set(), 1 << 20); // hardcoded worker stack size } GPU *g = new GPU(this, gpu_info[i], worker, cfg_gpu_streams); if(!cfg_use_shared_worker) dedicated_workers[g] = worker; gpus[i] = g; } } // create any memories provided by this module (default == do nothing) // (each new MemoryImpl should use a Memory from RuntimeImpl::next_local_memory_id) void CudaModule::create_memories(RuntimeImpl *runtime) { Module::create_memories(runtime); // each GPU needs its FB memory if(cfg_fb_mem_size_in_mb > 0) for(std::vector<GPU *>::iterator it = gpus.begin(); it != gpus.end(); it++) (*it)->create_fb_memory(runtime, cfg_fb_mem_size_in_mb << 20); // a single ZC memory for everybody if((cfg_zc_mem_size_in_mb > 0) && !gpus.empty()) { CUdeviceptr zcmem_gpu_base; // borrow GPU 0's context for the allocation call { AutoGPUContext agc(gpus[0]); CHECK_CU( cuMemHostAlloc(&zcmem_cpu_base, cfg_zc_mem_size_in_mb << 20, CU_MEMHOSTALLOC_PORTABLE | CU_MEMHOSTALLOC_DEVICEMAP) ); CHECK_CU( cuMemHostGetDevicePointer(&zcmem_gpu_base, zcmem_cpu_base, 0) ); // right now there are asssumptions in several places that unified addressing keeps // the CPU and GPU addresses the same assert(zcmem_cpu_base == (void *)zcmem_gpu_base); } Memory m = runtime->next_local_memory_id(); zcmem = new GPUZCMemory(m, zcmem_gpu_base, zcmem_cpu_base, cfg_zc_mem_size_in_mb << 20); runtime->add_memory(zcmem); // add the ZC memory as a pinned memory to all GPUs for(unsigned i = 0; i < gpus.size(); i++) { CUdeviceptr gpuptr; CUresult ret; { AutoGPUContext agc(gpus[i]); ret = cuMemHostGetDevicePointer(&gpuptr, zcmem_cpu_base, 0); } if((ret == CUDA_SUCCESS) && (gpuptr == zcmem_gpu_base)) { // <NEW_DMA> add mem mem affinity between GPU FB and ZC Machine::MemoryMemoryAffinity mma; mma.m1 = m; mma.m2 = gpus[i]->fbmem->me; mma.bandwidth = 200; // "big" mma.latency = 5; // "ok" runtime->add_mem_mem_affinity(mma); // </NEW_DMA> gpus[i]->pinned_sysmems.insert(zcmem->me); } else { log_gpu.warning() << "GPU #" << i << " has an unexpected mapping for ZC memory!"; } } } } // create any processors provided by the module (default == do nothing) // (each new ProcessorImpl should use a Processor from // RuntimeImpl::next_local_processor_id) void CudaModule::create_processors(RuntimeImpl *runtime) { Module::create_processors(runtime); // each GPU needs a processor for(std::vector<GPU *>::iterator it = gpus.begin(); it != gpus.end(); it++) (*it)->create_processor(runtime, 2 << 20); // TODO: don't use hardcoded stack size... } // create any DMA channels provided by the module (default == do nothing) void CudaModule::create_dma_channels(RuntimeImpl *runtime) { // before we create dma channels, see how many of the system memory ranges // we can register with CUDA if(cfg_pin_sysmem && !gpus.empty()) { std::vector<MemoryImpl *>& local_mems = runtime->nodes[gasnet_mynode()].memories; for(std::vector<MemoryImpl *>::iterator it = local_mems.begin(); it != local_mems.end(); it++) { // ignore FB/ZC memories or anything that doesn't have a "direct" pointer if(((*it)->kind == MemoryImpl::MKIND_GPUFB) || ((*it)->kind == MemoryImpl::MKIND_ZEROCOPY)) continue; void *base = (*it)->get_direct_ptr(0, (*it)->size); if(base == 0) continue; // using GPU 0's context, attempt a portable registration CUresult ret; { AutoGPUContext agc(gpus[0]); ret = cuMemHostRegister(base, (*it)->size, CU_MEMHOSTREGISTER_PORTABLE | CU_MEMHOSTREGISTER_DEVICEMAP); } if(ret != CUDA_SUCCESS) { log_gpu.info() << "failed to register mem " << (*it)->me << " (" << base << " + " << (*it)->size << ") : " << ret; continue; } // now go through each GPU and verify that it got a GPU pointer (it may not match the CPU // pointer, but that's ok because we'll never refer to it directly) for(unsigned i = 0; i < gpus.size(); i++) { CUdeviceptr gpuptr; CUresult ret; { AutoGPUContext agc(gpus[i]); ret = cuMemHostGetDevicePointer(&gpuptr, base, 0); } if(ret == CUDA_SUCCESS) { // no test for && ((void *)gpuptr == base)) { log_gpu.info() << "memory " << (*it)->me << " successfully registered with GPU " << gpus[i]->proc->me; // <NEW_DMA> add mem mem affinity between GPU FB and ZC Machine::MemoryMemoryAffinity mma; mma.m1 = gpus[i]->fbmem->me; mma.m2 = (*it)->me; mma.bandwidth = 200; // "big" mma.latency = 5; // "ok" runtime->add_mem_mem_affinity(mma); // </NEW_DMA> gpus[i]->pinned_sysmems.insert((*it)->me); } else { log_gpu.warning() << "GPU #" << i << " has no mapping for registered memory (" << (*it)->me << " at " << base << ") !?"; } } } } // now actually let each GPU make its channels for(std::vector<GPU *>::iterator it = gpus.begin(); it != gpus.end(); it++) (*it)->create_dma_channels(runtime); Module::create_dma_channels(runtime); } // create any code translators provided by the module (default == do nothing) void CudaModule::create_code_translators(RuntimeImpl *runtime) { Module::create_code_translators(runtime); } // clean up any common resources created by the module - this will be called // after all memories/processors/etc. have been shut down and destroyed void CudaModule::cleanup(void) { // clean up worker(s) if(shared_worker) { if(cfg_use_background_workers) shared_worker->shutdown_background_thread(); delete shared_worker; shared_worker = 0; } for(std::map<GPU *, GPUWorker *>::iterator it = dedicated_workers.begin(); it != dedicated_workers.end(); it++) { GPUWorker *worker = it->second; if(cfg_use_background_workers) worker->shutdown_background_thread(); delete worker; } dedicated_workers.clear(); // use GPU 0's context to free ZC memory (if any) if(zcmem_cpu_base) { assert(!gpus.empty()); AutoGPUContext agc(gpus[0]); CHECK_CU( cuMemFreeHost(zcmem_cpu_base) ); } for(std::vector<GPU *>::iterator it = gpus.begin(); it != gpus.end(); it++) delete *it; gpus.clear(); Module::cleanup(); } //////////////////////////////////////////////////////////////////////// // // struct RegisteredFunction RegisteredFunction::RegisteredFunction(const FatBin *_fat_bin, const void *_host_fun, const char *_device_fun) : fat_bin(_fat_bin), host_fun(_host_fun), device_fun(_device_fun) {} //////////////////////////////////////////////////////////////////////// // // struct RegisteredVariable RegisteredVariable::RegisteredVariable(const FatBin *_fat_bin, const void *_host_var, const char *_device_name, bool _external, int _size, bool _constant, bool _global) : fat_bin(_fat_bin), host_var(_host_var), device_name(_device_name), external(_external), size(_size), constant(_constant), global(_global) {} //////////////////////////////////////////////////////////////////////// // // class GlobalRegistrations GlobalRegistrations::GlobalRegistrations(void) {} GlobalRegistrations::~GlobalRegistrations(void) {} /*static*/ GlobalRegistrations& GlobalRegistrations::get_global_registrations(void) { static GlobalRegistrations reg; return reg; } // called by a GPU when it has created its context - will result in calls back // into the GPU for any modules/variables/whatever already registered /*static*/ void GlobalRegistrations::add_gpu_context(GPU *gpu) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); // add this gpu to the list assert(g.active_gpus.count(gpu) == 0); g.active_gpus.insert(gpu); // and now tell it about all the previous-registered stuff for(std::vector<FatBin *>::iterator it = g.fat_binaries.begin(); it != g.fat_binaries.end(); it++) gpu->register_fat_binary(*it); for(std::vector<RegisteredVariable *>::iterator it = g.variables.begin(); it != g.variables.end(); it++) gpu->register_variable(*it); for(std::vector<RegisteredFunction *>::iterator it = g.functions.begin(); it != g.functions.end(); it++) gpu->register_function(*it); } /*static*/ void GlobalRegistrations::remove_gpu_context(GPU *gpu) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); assert(g.active_gpus.count(gpu) > 0); g.active_gpus.erase(gpu); } // called by __cuda(un)RegisterFatBinary /*static*/ void GlobalRegistrations::register_fat_binary(FatBin *fatbin) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); // add the fat binary to the list and tell any gpus we know of about it g.fat_binaries.push_back(fatbin); for(std::set<GPU *>::iterator it = g.active_gpus.begin(); it != g.active_gpus.end(); it++) (*it)->register_fat_binary(fatbin); } /*static*/ void GlobalRegistrations::unregister_fat_binary(FatBin *fatbin) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); // remove the fatbin from the list - don't bother telling gpus std::vector<FatBin *>::iterator it = g.fat_binaries.begin(); while(it != g.fat_binaries.end()) if(*it == fatbin) it = g.fat_binaries.erase(it); else it++; } // called by __cudaRegisterVar /*static*/ void GlobalRegistrations::register_variable(RegisteredVariable *var) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); // add the variable to the list and tell any gpus we know g.variables.push_back(var); for(std::set<GPU *>::iterator it = g.active_gpus.begin(); it != g.active_gpus.end(); it++) (*it)->register_variable(var); } // called by __cudaRegisterFunction /*static*/ void GlobalRegistrations::register_function(RegisteredFunction *func) { GlobalRegistrations& g = get_global_registrations(); AutoHSLLock al(g.mutex); // add the function to the list and tell any gpus we know g.functions.push_back(func); for(std::set<GPU *>::iterator it = g.active_gpus.begin(); it != g.active_gpus.end(); it++) (*it)->register_function(func); } }; // namespace Cuda }; // namespace Realm
// Copyright (C) 2013 Jérôme Leclercq // This file is part of the "Nazara Engine - Audio module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Audio/Loaders/sndfile.hpp> #include <Nazara/Audio/Audio.hpp> #include <Nazara/Audio/SoundBuffer.hpp> #include <Nazara/Core/Endianness.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/File.hpp> #include <Nazara/Core/InputStream.hpp> #include <Nazara/Core/MemoryStream.hpp> #include <sndfile/sndfile.h> #include <Nazara/Audio/Debug.hpp> namespace { sf_count_t GetSize(void* user_data) { NzInputStream* stream = static_cast<NzInputStream*>(user_data); return stream->GetSize(); } sf_count_t Read(void* ptr, sf_count_t count, void* user_data) { NzInputStream* stream = static_cast<NzInputStream*>(user_data); return stream->Read(ptr, count); } sf_count_t Seek(sf_count_t offset, int whence, void* user_data) { NzInputStream* stream = static_cast<NzInputStream*>(user_data); switch (whence) { case SEEK_CUR: stream->Read(nullptr, offset); break; case SEEK_END: stream->SetCursorPos(stream->GetSize() + offset); // L'offset est négatif ici break; case SEEK_SET: stream->SetCursorPos(offset); break; default: NazaraInternalError("Seek mode not handled"); } return stream->GetCursorPos(); } sf_count_t Tell(void* user_data) { NzInputStream* stream = reinterpret_cast<NzInputStream*>(user_data); return stream->GetCursorPos(); } static SF_VIRTUAL_IO callbacks = {GetSize, Seek, Read, nullptr, Tell}; bool NzLoader_sndfile_Check(NzInputStream& stream, const NzSoundBufferParams& parameters) { NazaraUnused(parameters); SF_INFO info; SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &info, &stream); if (file) { sf_close(file); return true; } else return false; } bool NzLoader_sndfile_Load(NzSoundBuffer* soundBuffer, NzInputStream& stream, const NzSoundBufferParams& parameters) { NazaraUnused(parameters); SF_INFO infos; SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &infos, &stream); if (!file) { NazaraError("Failed to load sound file: " + NzString(sf_strerror(file))); return false; } nzAudioFormat format = NzAudio::GetAudioFormat(infos.channels); if (format == nzAudioFormat_Unknown) { NazaraError("Channel count not handled"); sf_close(file); return false; } // https://github.com/LaurentGomila/SFML/issues/271 // http://www.mega-nerd.com/libsndfile/command.html#SFC_SET_SCALE_FLOAT_INT_READ ///FIXME: Seulement le Vorbis ? if (infos.format & SF_FORMAT_VORBIS) sf_command(file, SFC_SET_SCALE_FLOAT_INT_READ, nullptr, SF_TRUE); unsigned int sampleCount = infos.frames*infos.channels; nzInt16* samples = new nzInt16[sampleCount]; if (sf_read_short(file, samples, sampleCount) != sampleCount) { NazaraError("Failed to read samples"); delete[] samples; sf_close(file); return false; } if (!soundBuffer->Create(format, infos.frames*infos.channels, infos.samplerate, samples)) { NazaraError("Failed to create sound buffer"); delete[] samples; sf_close(file); return false; } delete[] samples; return true; } } void NzLoaders_sndfile_Register() { NzSoundBufferLoader::RegisterLoader("aiff,au,avr,caf,flac,htk,ircam,mat4,mat5,mpc2k,nist,ogg,paf,pvf,raw,rf64,sd2,sds,svx,voc,w64,wav,wve", NzLoader_sndfile_Check, NzLoader_sndfile_Load); } void NzLoaders_sndfile_Unregister() { NzSoundBufferLoader::UnregisterLoader("aiff,au,avr,caf,flac,htk,ircam,mat4,mat5,mpc2k,nist,ogg,paf,pvf,raw,rf64,sd2,sds,svx,voc,w64,wav,wve", NzLoader_sndfile_Check, NzLoader_sndfile_Load); } Fixed audio module not building Former-commit-id: 87276c55c56142b8d10b13f2de19ee93b8148432 // Copyright (C) 2013 Jérôme Leclercq // This file is part of the "Nazara Engine - Audio module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Audio/Loaders/sndfile.hpp> #include <Nazara/Audio/Audio.hpp> #include <Nazara/Audio/SoundBuffer.hpp> #include <Nazara/Core/Endianness.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/File.hpp> #include <Nazara/Core/InputStream.hpp> #include <Nazara/Core/MemoryStream.hpp> #include <sndfile/sndfile.h> #include <Nazara/Audio/Debug.hpp> namespace { sf_count_t GetSize(void* user_data) { NzInputStream* stream = static_cast<NzInputStream*>(user_data); return stream->GetSize(); } sf_count_t Read(void* ptr, sf_count_t count, void* user_data) { NzInputStream* stream = static_cast<NzInputStream*>(user_data); return stream->Read(ptr, count); } sf_count_t Seek(sf_count_t offset, int whence, void* user_data) { NzInputStream* stream = static_cast<NzInputStream*>(user_data); switch (whence) { case SEEK_CUR: stream->Read(nullptr, offset); break; case SEEK_END: stream->SetCursorPos(stream->GetSize() + offset); // L'offset est négatif ici break; case SEEK_SET: stream->SetCursorPos(offset); break; default: NazaraInternalError("Seek mode not handled"); } return stream->GetCursorPos(); } sf_count_t Tell(void* user_data) { NzInputStream* stream = reinterpret_cast<NzInputStream*>(user_data); return stream->GetCursorPos(); } static SF_VIRTUAL_IO callbacks = {GetSize, Seek, Read, nullptr, Tell}; bool IsSupported(const NzString& extension) { static std::set<NzString> supportedExtensions = { "aiff", "au", "avr", "caf", "flac", "htk", "ircam", "mat4", "mat5", "mpc2k", "nist","ogg", "pvf", "raw", "rf64", "sd2", "sds", "svx", "voc", "w64", "wav", "wve" }; return supportedExtensions.find(extension) != supportedExtensions.end(); } bool Check(NzInputStream& stream, const NzSoundBufferParams& parameters) { NazaraUnused(parameters); SF_INFO info; SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &info, &stream); if (file) { sf_close(file); return true; } else return false; } bool Load(NzSoundBuffer* soundBuffer, NzInputStream& stream, const NzSoundBufferParams& parameters) { NazaraUnused(parameters); SF_INFO infos; SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &infos, &stream); if (!file) { NazaraError("Failed to load sound file: " + NzString(sf_strerror(file))); return false; } nzAudioFormat format = NzAudio::GetAudioFormat(infos.channels); if (format == nzAudioFormat_Unknown) { NazaraError("Channel count not handled"); sf_close(file); return false; } // https://github.com/LaurentGomila/SFML/issues/271 // http://www.mega-nerd.com/libsndfile/command.html#SFC_SET_SCALE_FLOAT_INT_READ ///FIXME: Seulement le Vorbis ? if (infos.format & SF_FORMAT_VORBIS) sf_command(file, SFC_SET_SCALE_FLOAT_INT_READ, nullptr, SF_TRUE); unsigned int sampleCount = infos.frames*infos.channels; nzInt16* samples = new nzInt16[sampleCount]; if (sf_read_short(file, samples, sampleCount) != sampleCount) { NazaraError("Failed to read samples"); delete[] samples; sf_close(file); return false; } if (!soundBuffer->Create(format, infos.frames*infos.channels, infos.samplerate, samples)) { NazaraError("Failed to create sound buffer"); delete[] samples; sf_close(file); return false; } delete[] samples; return true; } } void NzLoaders_sndfile_Register() { NzSoundBufferLoader::RegisterLoader(IsSupported, Check, Load); } void NzLoaders_sndfile_Unregister() { NzSoundBufferLoader::UnregisterLoader(IsSupported, Check, Load); }
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $ // mapnik #include <mapnik/datasource_cache.hpp> #include <mapnik/config_error.hpp> // boost #include <boost/version.hpp> #include <boost/make_shared.hpp> #include <boost/filesystem/operations.hpp> #include <boost/algorithm/string.hpp> // ltdl #include <ltdl.h> // stl #include <algorithm> #include <iostream> #include <stdexcept> namespace mapnik { bool is_input_plugin (std::string const& filename) { return boost::algorithm::ends_with(filename,std::string(".input")); } datasource_cache::datasource_cache() { if (lt_dlinit()) throw std::runtime_error("lt_dlinit() failed"); } datasource_cache::~datasource_cache() { lt_dlexit(); } std::map<std::string,boost::shared_ptr<PluginInfo> > datasource_cache::plugins_; bool datasource_cache::registered_=false; std::vector<std::string> datasource_cache::plugin_directories_; datasource_ptr datasource_cache::create(const parameters& params, bool bind) { boost::optional<std::string> type = params.get<std::string>("type"); if ( ! type) { throw config_error(std::string("Could not create datasource. Required ") + "parameter 'type' is missing"); } #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mutex_); #endif datasource_ptr ds; std::map<std::string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type); if ( itr == plugins_.end() ) { throw config_error(std::string("Could not create datasource. No plugin ") + "found for type '" + * type + "' (searched in: " + plugin_directories() + ")"); } if ( ! itr->second->handle()) { throw std::runtime_error(std::string("Cannot load library: ") + lt_dlerror()); } // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings #ifdef __GNUC__ __extension__ #endif create_ds* create_datasource = reinterpret_cast<create_ds*>(lt_dlsym(itr->second->handle(), "create")); if ( ! create_datasource) { throw std::runtime_error(std::string("Cannot load symbols: ") + lt_dlerror()); } #ifdef MAPNIK_DEBUG std::clog << "size = " << params.size() << "\n"; parameters::const_iterator i = params.begin(); for (;i!=params.end();++i) { std::clog << i->first << "=" << i->second << "\n"; } #endif ds=datasource_ptr(create_datasource(params, bind), datasource_deleter()); #ifdef MAPNIK_DEBUG std::clog<<"datasource="<<ds<<" type="<<type<<std::endl; #endif return ds; } bool datasource_cache::insert(const std::string& type,const lt_dlhandle module) { return plugins_.insert(make_pair(type,boost::make_shared<PluginInfo> (type,module))).second; } std::string datasource_cache::plugin_directories() { return boost::algorithm::join(plugin_directories_,", "); } std::vector<std::string> datasource_cache::plugin_names () { std::vector<std::string> names; std::map<std::string,boost::shared_ptr<PluginInfo> >::const_iterator itr; for (itr = plugins_.begin();itr!=plugins_.end();++itr) { names.push_back(itr->first); } return names; } void datasource_cache::register_datasources(const std::string& str) { #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache, mapnik::CreateStatic>::mutex_); #endif boost::filesystem::path path(str); plugin_directories_.push_back(str); boost::filesystem::directory_iterator end_itr; if (exists(path) && is_directory(path)) { for (boost::filesystem::directory_iterator itr(path);itr!=end_itr;++itr ) { #if BOOST_VERSION < 103400 if (!is_directory( *itr ) && is_input_plugin(itr->leaf())) #else #if (BOOST_FILESYSTEM_VERSION == 3) if (!is_directory( *itr ) && is_input_plugin(itr->path().filename().string())) #else // v2 if (!is_directory( *itr ) && is_input_plugin(itr->path().leaf())) #endif #endif { try { #ifdef LIBTOOL_SUPPORTS_ADVISE /* Note: the below was added as a workaround pre http://trac.mapnik.org/ticket/790 It could now be removed, but also is not doing any harm AFAICT. */ // with ltdl >=2.2 we can actually pass RTDL_GLOBAL to dlopen via the // ltdl advise trick which is required on linux unless plugins are directly // linked to libmapnik (and deps) at build time. The only other approach is to // set the dlopen flags in the calling process (like in the python bindings) // clear errors lt_dlerror(); lt_dlhandle module = 0; lt_dladvise advise; int ret; ret = lt_dlinit(); if (ret != 0) { std::clog << "Datasource loader: could not intialize dynamic loading: " << lt_dlerror() << "\n"; } ret = lt_dladvise_init(&advise); if (ret != 0) { std::clog << "Datasource loader: could not intialize dynamic loading: " << lt_dlerror() << "\n"; } ret = lt_dladvise_global(&advise); if (ret != 0) { std::clog << "Datasource loader: could not intialize dynamic loading of global symbols: " << lt_dlerror() << "\n"; } #if (BOOST_FILESYSTEM_VERSION == 3) module = lt_dlopenadvise (itr->path().string().c_str(), advise); #else // v2 module = lt_dlopenadvise (itr->string().c_str(), advise); #endif lt_dladvise_destroy(&advise); #else #if (BOOST_FILESYSTEM_VERSION == 3) lt_dlhandle module = lt_dlopen(itr->path().string().c_str()); #else // v2 lt_dlhandle module = lt_dlopen(itr->string().c_str()); #endif #endif if (module) { // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings #ifdef __GNUC__ __extension__ #endif datasource_name* ds_name = reinterpret_cast<datasource_name*>(lt_dlsym(module, "datasource_name")); if (ds_name && insert(ds_name(),module)) { #ifdef MAPNIK_DEBUG std::clog << "Datasource loader: registered: " << ds_name() << std::endl; #endif registered_=true; } else { std::clog << "Problem loading plugin library '" << itr->path().string() << "' (plugin is lacking compatible interface" << std::endl; } } else { #if (BOOST_FILESYSTEM_VERSION == 3) std::clog << "Problem loading plugin library: " << itr->path().string() << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)" << std::endl; #else // v2 std::clog << "Problem loading plugin library: " << itr->string() << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)" << std::endl; #endif } } catch (...) {} } } } } } only warn if plugin has no declared name - to avoid warnings on double registration of valid plugins /***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $ // mapnik #include <mapnik/datasource_cache.hpp> #include <mapnik/config_error.hpp> // boost #include <boost/version.hpp> #include <boost/make_shared.hpp> #include <boost/filesystem/operations.hpp> #include <boost/algorithm/string.hpp> // ltdl #include <ltdl.h> // stl #include <algorithm> #include <iostream> #include <stdexcept> namespace mapnik { bool is_input_plugin (std::string const& filename) { return boost::algorithm::ends_with(filename,std::string(".input")); } datasource_cache::datasource_cache() { if (lt_dlinit()) throw std::runtime_error("lt_dlinit() failed"); } datasource_cache::~datasource_cache() { lt_dlexit(); } std::map<std::string,boost::shared_ptr<PluginInfo> > datasource_cache::plugins_; bool datasource_cache::registered_=false; std::vector<std::string> datasource_cache::plugin_directories_; datasource_ptr datasource_cache::create(const parameters& params, bool bind) { boost::optional<std::string> type = params.get<std::string>("type"); if ( ! type) { throw config_error(std::string("Could not create datasource. Required ") + "parameter 'type' is missing"); } #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mutex_); #endif datasource_ptr ds; std::map<std::string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type); if ( itr == plugins_.end() ) { throw config_error(std::string("Could not create datasource. No plugin ") + "found for type '" + * type + "' (searched in: " + plugin_directories() + ")"); } if ( ! itr->second->handle()) { throw std::runtime_error(std::string("Cannot load library: ") + lt_dlerror()); } // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings #ifdef __GNUC__ __extension__ #endif create_ds* create_datasource = reinterpret_cast<create_ds*>(lt_dlsym(itr->second->handle(), "create")); if ( ! create_datasource) { throw std::runtime_error(std::string("Cannot load symbols: ") + lt_dlerror()); } #ifdef MAPNIK_DEBUG std::clog << "size = " << params.size() << "\n"; parameters::const_iterator i = params.begin(); for (;i!=params.end();++i) { std::clog << i->first << "=" << i->second << "\n"; } #endif ds=datasource_ptr(create_datasource(params, bind), datasource_deleter()); #ifdef MAPNIK_DEBUG std::clog<<"datasource="<<ds<<" type="<<type<<std::endl; #endif return ds; } bool datasource_cache::insert(const std::string& type,const lt_dlhandle module) { return plugins_.insert(make_pair(type,boost::make_shared<PluginInfo> (type,module))).second; } std::string datasource_cache::plugin_directories() { return boost::algorithm::join(plugin_directories_,", "); } std::vector<std::string> datasource_cache::plugin_names () { std::vector<std::string> names; std::map<std::string,boost::shared_ptr<PluginInfo> >::const_iterator itr; for (itr = plugins_.begin();itr!=plugins_.end();++itr) { names.push_back(itr->first); } return names; } void datasource_cache::register_datasources(const std::string& str) { #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache, mapnik::CreateStatic>::mutex_); #endif boost::filesystem::path path(str); plugin_directories_.push_back(str); boost::filesystem::directory_iterator end_itr; if (exists(path) && is_directory(path)) { for (boost::filesystem::directory_iterator itr(path);itr!=end_itr;++itr ) { #if BOOST_VERSION < 103400 if (!is_directory( *itr ) && is_input_plugin(itr->leaf())) #else #if (BOOST_FILESYSTEM_VERSION == 3) if (!is_directory( *itr ) && is_input_plugin(itr->path().filename().string())) #else // v2 if (!is_directory( *itr ) && is_input_plugin(itr->path().leaf())) #endif #endif { try { #ifdef LIBTOOL_SUPPORTS_ADVISE /* Note: the below was added as a workaround pre http://trac.mapnik.org/ticket/790 It could now be removed, but also is not doing any harm AFAICT. */ // with ltdl >=2.2 we can actually pass RTDL_GLOBAL to dlopen via the // ltdl advise trick which is required on linux unless plugins are directly // linked to libmapnik (and deps) at build time. The only other approach is to // set the dlopen flags in the calling process (like in the python bindings) // clear errors lt_dlerror(); lt_dlhandle module = 0; lt_dladvise advise; int ret; ret = lt_dlinit(); if (ret != 0) { std::clog << "Datasource loader: could not intialize dynamic loading: " << lt_dlerror() << "\n"; } ret = lt_dladvise_init(&advise); if (ret != 0) { std::clog << "Datasource loader: could not intialize dynamic loading: " << lt_dlerror() << "\n"; } ret = lt_dladvise_global(&advise); if (ret != 0) { std::clog << "Datasource loader: could not intialize dynamic loading of global symbols: " << lt_dlerror() << "\n"; } #if (BOOST_FILESYSTEM_VERSION == 3) module = lt_dlopenadvise (itr->path().string().c_str(), advise); #else // v2 module = lt_dlopenadvise (itr->string().c_str(), advise); #endif lt_dladvise_destroy(&advise); #else #if (BOOST_FILESYSTEM_VERSION == 3) lt_dlhandle module = lt_dlopen(itr->path().string().c_str()); #else // v2 lt_dlhandle module = lt_dlopen(itr->string().c_str()); #endif #endif if (module) { // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings #ifdef __GNUC__ __extension__ #endif datasource_name* ds_name = reinterpret_cast<datasource_name*>(lt_dlsym(module, "datasource_name")); if (ds_name && insert(ds_name(),module)) { #ifdef MAPNIK_DEBUG std::clog << "Datasource loader: registered: " << ds_name() << std::endl; #endif registered_=true; } else if (!ds_name) { std::clog << "Problem loading plugin library '" << itr->path().string() << "' (plugin is lacking compatible interface)" << std::endl; } } else { #if (BOOST_FILESYSTEM_VERSION == 3) std::clog << "Problem loading plugin library: " << itr->path().string() << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)" << std::endl; #else // v2 std::clog << "Problem loading plugin library: " << itr->string() << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)" << std::endl; #endif } } catch (...) {} } } } } }
/** * \file GeoConvert.cpp * * Copyright (c) Charles Karney (2008) <charles@karney.com> * http://charles.karney.info/geographic * and licensed under the LGPL. * * Compile with * * g++ -g -O3 -I.. -o GeoConvert GeoConvert.cpp GeoCoords.cpp MGRS.cpp UTMUPS.cpp DMS.cpp Constants.cpp TransverseMercator.cpp PolarStereographic.cpp * **********************************************************************/ #include <iostream> #include "GeoCoords.hpp" #include <sstream> #include <string> #include <stdexcept> #include <iomanip> int main(int argc, char* argv[]) { int outputmode = 0; // Lat/Lon; 1 = DMS; 2 = UTM/UPS; 3 = MGRS int prec = 0; int zone = -2; // -2 = track input, -1 = standard for (int m = 1; m < argc; ++m) { std::string arg = std::string(argv[m]); if (arg == "-g") outputmode = 0; else if (arg == "-d") outputmode = 1; else if (arg == "-u") outputmode = 2; else if (arg == "-m") outputmode = 3; else if (arg == "-c") outputmode = 4; else if (arg == "-p") { std::string a = std::string(argv[++m]); std::istringstream str(a); str >> prec; } else if (arg == "-z") { std::string a = std::string(argv[++m]); std::istringstream str(a); str >> zone; } else if (arg == "-s") zone = -1; else { ( arg == "-h" ? std::cout : std::cerr ) << "Usage: GeoConvert [-g|-d|-u|-m|-c] [-p prec] [-z zone] [-s] [-h]\n\ $Id$\n\ \n\ Convert geographic coordinates to\n\ \n\ -g latitude and longitude (decimal degrees), default output\n\ -d latitude and longitude (degrees mins secs)\n\ -u UTM or UPS\n\ -m MGRS\n\ -c meridian convergence and scale\n\ \n\ Geographic coordinates are given on standard input as\n\ \n\ latitude and longitude (decimal degrees or degrees minutes seconds).\n\ Latitude is given first unless hemisphere is specified, e.g.,\n\ \n\ 33.3 44.4\n\ E44.4 N33.3\n\ 33d18'N 44d24'E\n\ \n\ UTM or UPS given as zone+hemisphere easting northing or easting northing\n\ zone+hemisphere. The zone is absent for a UPS specification. E.g.,\n\ \n\ 38N 444140.54 3684706.36\n\ 444140.54 3684706.36 38N\n\ S 2173854.98 2985980.58\n\ 2173854.98 2985980.58 S\n\ \n\ MRGS is used to specify the center of a grid square, e.g.,\n\ \n\ 38SMB4484\n\ 38SMB44140847064\n\ \n\ -p prec (default 0) sets the precision relative to 1m. This gives the\n\ number of digits after the decimal point for UTM/UPS. The number of digits\n\ per coordinate for MGRS is 5 + prec. For decimal degrees, the number\n\ of digits after the decimal point is 5 + prec. For DMS (degree,\n\ minute, seconds) output, the number of digits after the decimal point\n\ in the seconds components is 1 + prec. The minimum value of prec is -5\n\ and the maximum is 9 for UTM/UPS, 10 for decimal degrees and DMS, and 6 for\n\ MGRS.\n\ \n\ UTM/UPS and MGS are given in zone of the input if applicable, otherwise\n\ in the standard zone.\n\ \n\ -z zone sets the zone for output. Use zone = 0 to specify a UPS (polar)\n\ zone.\n\ \n\ -s uses the standard zone\n\ \n\ For example, the point\n\ \n\ 79.9S 6.1E\n\ \n\ corresponds to 3 possible MGRS coordinates\n\ \n\ 32CMS4324728161 (standard UTM zone = 32)\n\ 31CEM6066227959 (neighboring UTM zone = 31)\n\ BBZ1945517770 (neighboring UPS zone)\n\ \n\ then\n\ echo 31CEM6066227959 | GeoConvert -p -3 -m ==> 31CEM6027\n\ echo 31CEM6066227959 | GeoConvert -p -3 -m -s ==> 32CMS4328\n\ echo 31CEM6066227959 | GeoConvert -p -3 -m -z 0 ==> BBZ1917\n\ \n\ -h prints this help\n"; return arg == "-h" ? 0 : 1; } } GeographicLib::GeoCoords p; std::string s; std::string os; int retval = 0; if (!(zone >= -2 && zone <= 60)) { std::cerr << "Illegal zone " << zone << "\n"; return 1; } while (true) { std::getline(std::cin, s); if (!std::cin.good()) break; try { p.Reset(s); if (zone != -2) p.SetAltZone(zone); switch (outputmode) { case 0: os = p.GeoRepresentation(prec); break; case 1: os = p.DMSRepresentation(prec); break; case 2: os = p.AltUTMUPSRepresentation(prec); break; case 3: os = p.AltMGRSRepresentation(prec); break; case 4: { double gamma = p.AltConvergence(), k = p.AltScale(); std::ostringstream ss; ss << std::fixed << std::setprecision(std::max(0, std::min(8, prec) + 5)) << gamma << " " << std::setprecision(std::max(0, std::min(8, prec) + 7)) << k; os = ss.str(); } } } catch (std::out_of_range& e) { os = std::string("ERROR: ") + e.what(); retval = 1; } std::cout << os << std::endl; } return retval; } Fix include path. /** * \file GeoConvert.cpp * * Copyright (c) Charles Karney (2008) <charles@karney.com> * http://charles.karney.info/geographic * and licensed under the LGPL. * * Compile with * * g++ -g -O3 -I.. -o GeoConvert GeoConvert.cpp GeoCoords.cpp MGRS.cpp UTMUPS.cpp DMS.cpp Constants.cpp TransverseMercator.cpp PolarStereographic.cpp * **********************************************************************/ #include <iostream> #include <sstream> #include <string> #include <stdexcept> #include <iomanip> #include "GeoGraphicLib/GeoCoords.hpp" int main(int argc, char* argv[]) { int outputmode = 0; // Lat/Lon; 1 = DMS; 2 = UTM/UPS; 3 = MGRS int prec = 0; int zone = -2; // -2 = track input, -1 = standard for (int m = 1; m < argc; ++m) { std::string arg = std::string(argv[m]); if (arg == "-g") outputmode = 0; else if (arg == "-d") outputmode = 1; else if (arg == "-u") outputmode = 2; else if (arg == "-m") outputmode = 3; else if (arg == "-c") outputmode = 4; else if (arg == "-p") { std::string a = std::string(argv[++m]); std::istringstream str(a); str >> prec; } else if (arg == "-z") { std::string a = std::string(argv[++m]); std::istringstream str(a); str >> zone; } else if (arg == "-s") zone = -1; else { ( arg == "-h" ? std::cout : std::cerr ) << "Usage: GeoConvert [-g|-d|-u|-m|-c] [-p prec] [-z zone] [-s] [-h]\n\ $Id$\n\ \n\ Convert geographic coordinates to\n\ \n\ -g latitude and longitude (decimal degrees), default output\n\ -d latitude and longitude (degrees mins secs)\n\ -u UTM or UPS\n\ -m MGRS\n\ -c meridian convergence and scale\n\ \n\ Geographic coordinates are given on standard input as\n\ \n\ latitude and longitude (decimal degrees or degrees minutes seconds).\n\ Latitude is given first unless hemisphere is specified, e.g.,\n\ \n\ 33.3 44.4\n\ E44.4 N33.3\n\ 33d18'N 44d24'E\n\ \n\ UTM or UPS given as zone+hemisphere easting northing or easting northing\n\ zone+hemisphere. The zone is absent for a UPS specification. E.g.,\n\ \n\ 38N 444140.54 3684706.36\n\ 444140.54 3684706.36 38N\n\ S 2173854.98 2985980.58\n\ 2173854.98 2985980.58 S\n\ \n\ MRGS is used to specify the center of a grid square, e.g.,\n\ \n\ 38SMB4484\n\ 38SMB44140847064\n\ \n\ -p prec (default 0) sets the precision relative to 1m. This gives the\n\ number of digits after the decimal point for UTM/UPS. The number of digits\n\ per coordinate for MGRS is 5 + prec. For decimal degrees, the number\n\ of digits after the decimal point is 5 + prec. For DMS (degree,\n\ minute, seconds) output, the number of digits after the decimal point\n\ in the seconds components is 1 + prec. The minimum value of prec is -5\n\ and the maximum is 9 for UTM/UPS, 10 for decimal degrees and DMS, and 6 for\n\ MGRS.\n\ \n\ UTM/UPS and MGS are given in zone of the input if applicable, otherwise\n\ in the standard zone.\n\ \n\ -z zone sets the zone for output. Use zone = 0 to specify a UPS (polar)\n\ zone.\n\ \n\ -s uses the standard zone\n\ \n\ For example, the point\n\ \n\ 79.9S 6.1E\n\ \n\ corresponds to 3 possible MGRS coordinates\n\ \n\ 32CMS4324728161 (standard UTM zone = 32)\n\ 31CEM6066227959 (neighboring UTM zone = 31)\n\ BBZ1945517770 (neighboring UPS zone)\n\ \n\ then\n\ echo 31CEM6066227959 | GeoConvert -p -3 -m ==> 31CEM6027\n\ echo 31CEM6066227959 | GeoConvert -p -3 -m -s ==> 32CMS4328\n\ echo 31CEM6066227959 | GeoConvert -p -3 -m -z 0 ==> BBZ1917\n\ \n\ -h prints this help\n"; return arg == "-h" ? 0 : 1; } } GeographicLib::GeoCoords p; std::string s; std::string os; int retval = 0; if (!(zone >= -2 && zone <= 60)) { std::cerr << "Illegal zone " << zone << "\n"; return 1; } while (true) { std::getline(std::cin, s); if (!std::cin.good()) break; try { p.Reset(s); if (zone != -2) p.SetAltZone(zone); switch (outputmode) { case 0: os = p.GeoRepresentation(prec); break; case 1: os = p.DMSRepresentation(prec); break; case 2: os = p.AltUTMUPSRepresentation(prec); break; case 3: os = p.AltMGRSRepresentation(prec); break; case 4: { double gamma = p.AltConvergence(), k = p.AltScale(); std::ostringstream ss; ss << std::fixed << std::setprecision(std::max(0, std::min(8, prec) + 5)) << gamma << " " << std::setprecision(std::max(0, std::min(8, prec) + 7)) << k; os = ss.str(); } } } catch (std::out_of_range& e) { os = std::string("ERROR: ") + e.what(); retval = 1; } std::cout << os << std::endl; } return retval; }
/* * Copyright (c) 2018, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements the spinel based radio transceiver. */ #include "openthread-core-config.h" #include "platform-posix.h" #include "radio_spinel.hpp" #include <assert.h> #include <errno.h> #include <stdarg.h> #include <stdlib.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/wait.h> #include <syslog.h> #include <termios.h> #include <unistd.h> #include <common/code_utils.hpp> #include <common/encoding.hpp> #include <common/logging.hpp> #include <openthread/platform/alarm-milli.h> #include <openthread/platform/diag.h> #include <openthread/platform/radio.h> static ot::PosixApp::RadioSpinel sRadioSpinel; namespace ot { namespace PosixApp { static otError SpinelStatusToOtError(spinel_status_t aError) { otError ret; switch (aError) { case SPINEL_STATUS_OK: ret = OT_ERROR_NONE; break; case SPINEL_STATUS_FAILURE: ret = OT_ERROR_FAILED; break; case SPINEL_STATUS_DROPPED: ret = OT_ERROR_DROP; break; case SPINEL_STATUS_NOMEM: ret = OT_ERROR_NO_BUFS; break; case SPINEL_STATUS_BUSY: ret = OT_ERROR_BUSY; break; case SPINEL_STATUS_PARSE_ERROR: ret = OT_ERROR_PARSE; break; case SPINEL_STATUS_INVALID_ARGUMENT: ret = OT_ERROR_INVALID_ARGS; break; case SPINEL_STATUS_UNIMPLEMENTED: ret = OT_ERROR_NOT_IMPLEMENTED; break; case SPINEL_STATUS_INVALID_STATE: ret = OT_ERROR_INVALID_STATE; break; case SPINEL_STATUS_NO_ACK: ret = OT_ERROR_NO_ACK; break; case SPINEL_STATUS_CCA_FAILURE: ret = OT_ERROR_CHANNEL_ACCESS_FAILURE; break; case SPINEL_STATUS_ALREADY: ret = OT_ERROR_ALREADY; break; case SPINEL_STATUS_PROP_NOT_FOUND: case SPINEL_STATUS_ITEM_NOT_FOUND: ret = OT_ERROR_NOT_FOUND; break; default: if (aError >= SPINEL_STATUS_STACK_NATIVE__BEGIN && aError <= SPINEL_STATUS_STACK_NATIVE__END) { ret = static_cast<otError>(aError - SPINEL_STATUS_STACK_NATIVE__BEGIN); } else { ret = OT_ERROR_FAILED; } break; } return ret; } static void LogIfFail(const char *aText, otError aError) { OT_UNUSED_VARIABLE(aText); OT_UNUSED_VARIABLE(aError); if (aError != OT_ERROR_NONE) { otLogWarnPlat("%s: %s", aText, otThreadErrorToString(aError)); } } void HdlcInterface::Callbacks::HandleReceivedFrame(HdlcInterface &aInterface) { static_cast<RadioSpinel *>(this)->HandleSpinelFrame(aInterface.GetRxFrameBuffer()); } RadioSpinel::RadioSpinel(void) : mInstance(NULL) , mHdlcInterface(*this) , mCmdTidsInUse(0) , mCmdNextTid(1) , mTxRadioTid(0) , mWaitingTid(0) , mWaitingKey(SPINEL_PROP_LAST_STATUS) , mPropertyFormat(NULL) , mExpectedCommand(0) , mError(OT_ERROR_NONE) , mTransmitFrame(NULL) , mShortAddress(0) , mPanId(0xffff) , mRadioCaps(0) , mChannel(0) , mRxSensitivity(0) , mState(kStateDisabled) , mIsPromiscuous(false) , mIsReady(false) , mSupportsLogStream(false) #if OPENTHREAD_ENABLE_DIAG , mDiagMode(false) , mDiagOutput(NULL) , mDiagOutputMaxLen(0) #endif { mVersion[0] = '\0'; } void RadioSpinel::Init(const char *aRadioFile, const char *aRadioConfig) { otError error = OT_ERROR_NONE; SuccessOrExit(error = mHdlcInterface.Init(aRadioFile, aRadioConfig)); SuccessOrExit(error = SendReset()); SuccessOrExit(error = WaitResponse()); VerifyOrExit(mIsReady, error = OT_ERROR_FAILED); SuccessOrExit(error = CheckSpinelVersion()); SuccessOrExit(error = CheckCapabilities()); SuccessOrExit(error = CheckRadioCapabilities()); SuccessOrExit(error = Get(SPINEL_PROP_NCP_VERSION, SPINEL_DATATYPE_UTF8_S, mVersion, sizeof(mVersion))); SuccessOrExit(error = Get(SPINEL_PROP_HWADDR, SPINEL_DATATYPE_UINT64_S, &gNodeId)); gNodeId = ot::Encoding::BigEndian::HostSwap64(gNodeId); mRxRadioFrame.mPsdu = mRxPsdu; mTxRadioFrame.mPsdu = mTxPsdu; mAckRadioFrame.mPsdu = mAckPsdu; exit: SuccessOrDie(error); } otError RadioSpinel::CheckSpinelVersion(void) { otError error = OT_ERROR_NONE; unsigned int versionMajor; unsigned int versionMinor; SuccessOrExit(error = Get(SPINEL_PROP_PROTOCOL_VERSION, (SPINEL_DATATYPE_UINT_PACKED_S SPINEL_DATATYPE_UINT_PACKED_S), &versionMajor, &versionMinor)); if ((versionMajor != SPINEL_PROTOCOL_VERSION_THREAD_MAJOR) || (versionMinor != SPINEL_PROTOCOL_VERSION_THREAD_MINOR)) { otLogCritPlat("Spinel version mismatch - PosixApp:%d.%d, RCP:%d.%d", SPINEL_PROTOCOL_VERSION_THREAD_MAJOR, SPINEL_PROTOCOL_VERSION_THREAD_MINOR, versionMajor, versionMinor); exit(OT_EXIT_RADIO_SPINEL_INCOMPATIBLE); } exit: return error; } otError RadioSpinel::CheckCapabilities(void) { otError error = OT_ERROR_NONE; uint8_t capsBuffer[kCapsBufferSize]; const uint8_t *capsData = capsBuffer; spinel_size_t capsLength = sizeof(capsBuffer); bool supportsRawRadio = false; SuccessOrExit(error = Get(SPINEL_PROP_CAPS, SPINEL_DATATYPE_DATA_S, capsBuffer, &capsLength)); while (capsLength > 0) { unsigned int capability; spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack(capsData, capsLength, SPINEL_DATATYPE_UINT_PACKED_S, &capability); VerifyOrExit(unpacked > 0, error = OT_ERROR_FAILED); if (capability == SPINEL_CAP_OPENTHREAD_LOG_METADATA) { mSupportsLogStream = true; } if (capability == SPINEL_CAP_MAC_RAW) { supportsRawRadio = true; } capsData += unpacked; capsLength -= static_cast<spinel_size_t>(unpacked); } if (!supportsRawRadio) { otLogCritPlat("RCP capability list does not include support for radio/raw mode"); exit(OT_EXIT_RADIO_SPINEL_INCOMPATIBLE); } exit: return error; } otError RadioSpinel::CheckRadioCapabilities(void) { const otRadioCaps kRequiredRadioCaps = OT_RADIO_CAPS_ACK_TIMEOUT | OT_RADIO_CAPS_TRANSMIT_RETRIES | OT_RADIO_CAPS_CSMA_BACKOFF; otError error = OT_ERROR_NONE; unsigned int caps; SuccessOrExit(error = Get(SPINEL_PROP_RADIO_CAPS, SPINEL_DATATYPE_UINT_PACKED_S, &caps)); mRadioCaps = static_cast<otRadioCaps>(caps); if ((mRadioCaps & kRequiredRadioCaps) != kRequiredRadioCaps) { otLogCritPlat("RCP does not support required capabilities: ack-timeout:%s, tx-retries:%s, CSMA-backoff:%s", (mRadioCaps & OT_RADIO_CAPS_ACK_TIMEOUT) ? "yes" : "no", (mRadioCaps & OT_RADIO_CAPS_TRANSMIT_RETRIES) ? "yes" : "no", (mRadioCaps & OT_RADIO_CAPS_CSMA_BACKOFF) ? "yes" : "no"); exit(OT_EXIT_RADIO_SPINEL_INCOMPATIBLE); } exit: return error; } void RadioSpinel::Deinit(void) { mHdlcInterface.Deinit(); } void RadioSpinel::HandleSpinelFrame(HdlcInterface::RxFrameBuffer &aFrameBuffer) { otError error = OT_ERROR_NONE; uint8_t header; spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack(aFrameBuffer.GetFrame(), aFrameBuffer.GetLength(), "C", &header); VerifyOrExit(unpacked > 0 && (header & SPINEL_HEADER_FLAG) == SPINEL_HEADER_FLAG && SPINEL_HEADER_GET_IID(header) == 0, error = OT_ERROR_PARSE); if (SPINEL_HEADER_GET_TID(header) == 0) { HandleNotification(aFrameBuffer); } else { HandleResponse(aFrameBuffer.GetFrame(), aFrameBuffer.GetLength()); aFrameBuffer.DiscardFrame(); } exit: if (error != OT_ERROR_NONE) { aFrameBuffer.DiscardFrame(); otLogWarnPlat("Error handling hdlc frame: %s", otThreadErrorToString(error)); } } void RadioSpinel::HandleNotification(HdlcInterface::RxFrameBuffer &aFrameBuffer) { spinel_prop_key_t key; spinel_size_t len = 0; spinel_ssize_t unpacked; uint8_t * data = NULL; uint32_t cmd; uint8_t header; otError error = OT_ERROR_NONE; bool shouldSaveFrame = false; unpacked = spinel_datatype_unpack(aFrameBuffer.GetFrame(), aFrameBuffer.GetLength(), "CiiD", &header, &cmd, &key, &data, &len); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); VerifyOrExit(SPINEL_HEADER_GET_TID(header) == 0, error = OT_ERROR_PARSE); switch (cmd) { case SPINEL_CMD_PROP_VALUE_IS: // Some spinel properties cannot be handled during `WaitResponse()`, we must cache these events. // `mWaitingTid` is released immediately after received the response. And `mWaitingKey` is be set // to `SPINEL_PROP_LAST_STATUS` at the end of `WaitResponse()`. if (!IsSafeToHandleNow(key)) { ExitNow(shouldSaveFrame = true); } HandleValueIs(key, data, static_cast<uint16_t>(len)); break; case SPINEL_CMD_PROP_VALUE_INSERTED: case SPINEL_CMD_PROP_VALUE_REMOVED: otLogInfoPlat("Ignored command %d", cmd); break; default: ExitNow(error = OT_ERROR_PARSE); } exit: if (shouldSaveFrame) { aFrameBuffer.SaveFrame(); } else { aFrameBuffer.DiscardFrame(); } LogIfFail("Error processing notification", error); } void RadioSpinel::HandleNotification(const uint8_t *aFrame, uint16_t aLength) { spinel_prop_key_t key; spinel_size_t len = 0; spinel_ssize_t unpacked; uint8_t * data = NULL; uint32_t cmd; uint8_t header; otError error = OT_ERROR_NONE; unpacked = spinel_datatype_unpack(aFrame, aLength, "CiiD", &header, &cmd, &key, &data, &len); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); VerifyOrExit(SPINEL_HEADER_GET_TID(header) == 0, error = OT_ERROR_PARSE); VerifyOrExit(cmd == SPINEL_CMD_PROP_VALUE_IS); HandleValueIs(key, data, static_cast<uint16_t>(len)); exit: LogIfFail("Error processing saved notification", error); } void RadioSpinel::HandleResponse(const uint8_t *aBuffer, uint16_t aLength) { spinel_prop_key_t key; uint8_t * data = NULL; spinel_size_t len = 0; uint8_t header = 0; uint32_t cmd = 0; spinel_ssize_t rval = 0; otError error = OT_ERROR_NONE; rval = spinel_datatype_unpack(aBuffer, aLength, "CiiD", &header, &cmd, &key, &data, &len); VerifyOrExit(rval > 0 && cmd >= SPINEL_CMD_PROP_VALUE_IS && cmd <= SPINEL_CMD_PROP_VALUE_REMOVED, error = OT_ERROR_PARSE); if (mWaitingTid == SPINEL_HEADER_GET_TID(header)) { HandleWaitingResponse(cmd, key, data, static_cast<uint16_t>(len)); FreeTid(mWaitingTid); mWaitingTid = 0; } else if (mTxRadioTid == SPINEL_HEADER_GET_TID(header)) { if (mState == kStateTransmitting) { HandleTransmitDone(cmd, key, data, static_cast<uint16_t>(len)); } FreeTid(mTxRadioTid); mTxRadioTid = 0; } else { otLogWarnPlat("Unexpected Spinel transaction message: %u", SPINEL_HEADER_GET_TID(header)); error = OT_ERROR_DROP; } exit: LogIfFail("Error processing response", error); } void RadioSpinel::HandleWaitingResponse(uint32_t aCommand, spinel_prop_key_t aKey, const uint8_t * aBuffer, uint16_t aLength) { if (aKey == SPINEL_PROP_LAST_STATUS) { spinel_status_t status; spinel_ssize_t unpacked = spinel_datatype_unpack(aBuffer, aLength, "i", &status); VerifyOrExit(unpacked > 0, mError = OT_ERROR_PARSE); mError = SpinelStatusToOtError(status); } #if OPENTHREAD_ENABLE_DIAG else if (aKey == SPINEL_PROP_NEST_STREAM_MFG) { spinel_ssize_t unpacked; VerifyOrExit(mDiagOutput != NULL); unpacked = spinel_datatype_unpack_in_place(aBuffer, aLength, SPINEL_DATATYPE_UTF8_S, mDiagOutput, &mDiagOutputMaxLen); VerifyOrExit(unpacked > 0, mError = OT_ERROR_PARSE); } #endif else if (aKey == mWaitingKey) { if (mPropertyFormat) { spinel_ssize_t unpacked = spinel_datatype_vunpack_in_place(aBuffer, aLength, mPropertyFormat, mPropertyArgs); VerifyOrExit(unpacked > 0, mError = OT_ERROR_PARSE); mError = OT_ERROR_NONE; } else { if (aCommand == mExpectedCommand) { mError = OT_ERROR_NONE; } else { mError = OT_ERROR_DROP; } } } else { mError = OT_ERROR_DROP; } exit: LogIfFail("Error processing result", mError); } void RadioSpinel::HandleValueIs(spinel_prop_key_t aKey, const uint8_t *aBuffer, uint16_t aLength) { otError error = OT_ERROR_NONE; if (aKey == SPINEL_PROP_STREAM_RAW) { SuccessOrExit(error = ParseRadioFrame(mRxRadioFrame, aBuffer, aLength)); RadioReceive(); } else if (aKey == SPINEL_PROP_LAST_STATUS) { spinel_status_t status = SPINEL_STATUS_OK; spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack(aBuffer, aLength, "i", &status); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); if (status >= SPINEL_STATUS_RESET__BEGIN && status <= SPINEL_STATUS_RESET__END) { otLogCritPlat("RCP reset: %s", spinel_status_to_cstr(status)); mIsReady = true; // If RCP crashes/resets while radio was enabled, posix app exits. VerifyOrDie(!IsEnabled(), OT_EXIT_RADIO_SPINEL_RESET); } else { otLogInfoPlat("RCP last status: %s", spinel_status_to_cstr(status)); } } else if (aKey == SPINEL_PROP_MAC_ENERGY_SCAN_RESULT) { uint8_t scanChannel; int8_t maxRssi; spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack(aBuffer, aLength, "Cc", &scanChannel, &maxRssi); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); otPlatRadioEnergyScanDone(mInstance, maxRssi); } else if (aKey == SPINEL_PROP_STREAM_DEBUG) { char logStream[OPENTHREAD_CONFIG_NCP_SPINEL_LOG_MAX_SIZE + 1]; unsigned int len = sizeof(logStream); spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack_in_place(aBuffer, aLength, SPINEL_DATATYPE_DATA_S, logStream, &len); assert(len < sizeof(logStream)); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); logStream[len] = '\0'; otLogDebgPlat("RCP => %s", logStream); } else if ((aKey == SPINEL_PROP_STREAM_LOG) && mSupportsLogStream) { const char * logString; spinel_ssize_t unpacked; uint8_t logLevel; unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UTF8_S, &logString); VerifyOrExit(unpacked >= 0, error = OT_ERROR_PARSE); aBuffer += unpacked; aLength -= unpacked; unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UINT8_S, &logLevel); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); switch (logLevel) { case SPINEL_NCP_LOG_LEVEL_EMERG: case SPINEL_NCP_LOG_LEVEL_ALERT: case SPINEL_NCP_LOG_LEVEL_CRIT: otLogCritPlat("RCP => %s", logString); break; case SPINEL_NCP_LOG_LEVEL_ERR: case SPINEL_NCP_LOG_LEVEL_WARN: otLogWarnPlat("RCP => %s", logString); break; case SPINEL_NCP_LOG_LEVEL_NOTICE: otLogNotePlat("RCP => %s", logString); break; case SPINEL_NCP_LOG_LEVEL_INFO: otLogInfoPlat("RCP => %s", logString); break; case SPINEL_NCP_LOG_LEVEL_DEBUG: default: otLogDebgPlat("RCP => %s", logString); break; } } exit: LogIfFail("Failed to handle ValueIs", error); } otError RadioSpinel::ParseRadioFrame(otRadioFrame &aFrame, const uint8_t *aBuffer, uint16_t aLength) { otError error = OT_ERROR_NONE; uint16_t packetLength = 0; spinel_ssize_t unpacked; uint16_t flags = 0; int8_t noiseFloor = -128; spinel_size_t size = OT_RADIO_FRAME_MAX_SIZE; unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UINT16_S, &packetLength); VerifyOrExit(unpacked > 0 && packetLength <= OT_RADIO_FRAME_MAX_SIZE, error = OT_ERROR_PARSE); aFrame.mLength = static_cast<uint8_t>(packetLength); unpacked = spinel_datatype_unpack_in_place(aBuffer, aLength, SPINEL_DATATYPE_DATA_WLEN_S SPINEL_DATATYPE_INT8_S SPINEL_DATATYPE_INT8_S SPINEL_DATATYPE_UINT16_S SPINEL_DATATYPE_STRUCT_S( // PHY-data SPINEL_DATATYPE_UINT8_S // 802.15.4 channel SPINEL_DATATYPE_UINT8_S // 802.15.4 LQI ), aFrame.mPsdu, &size, &aFrame.mInfo.mRxInfo.mRssi, &noiseFloor, &flags, &aFrame.mChannel, &aFrame.mInfo.mRxInfo.mLqi); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); exit: LogIfFail("Handle radio frame failed", error); return error; } void RadioSpinel::ProcessFrameQueue(void) { uint8_t *frame; uint16_t length; while (mHdlcInterface.GetRxFrameBuffer().ReadSavedFrame(frame, length) == OT_ERROR_NONE) { HandleNotification(frame, length); } } void RadioSpinel::RadioReceive(void) { if (!mIsPromiscuous) { switch (mState) { case kStateDisabled: case kStateSleep: ExitNow(); case kStateReceive: case kStateTransmitPending: case kStateTransmitting: case kStateTransmitDone: break; } } #if OPENTHREAD_ENABLE_DIAG if (otPlatDiagModeGet()) { otPlatDiagRadioReceiveDone(mInstance, &mRxRadioFrame, OT_ERROR_NONE); } else #endif { otPlatRadioReceiveDone(mInstance, &mRxRadioFrame, OT_ERROR_NONE); } exit: return; } void RadioSpinel::UpdateFdSet(fd_set &aReadFdSet, fd_set &aWriteFdSet, int &aMaxFd, struct timeval &aTimeout) { int sockFd = mHdlcInterface.GetSocket(); FD_SET(sockFd, &aReadFdSet); if (aMaxFd < sockFd) { aMaxFd = sockFd; } if (mState == kStateTransmitPending) { FD_SET(sockFd, &aWriteFdSet); } if (mHdlcInterface.GetRxFrameBuffer().HasSavedFrame() || (mState == kStateTransmitDone)) { aTimeout.tv_sec = 0; aTimeout.tv_usec = 0; } } void RadioSpinel::Process(const fd_set &aReadFdSet, const fd_set &aWriteFdSet) { if (mHdlcInterface.GetRxFrameBuffer().HasSavedFrame()) { // Handle frames received and saved during `WaitResponse()` ProcessFrameQueue(); } if (FD_ISSET(mHdlcInterface.GetSocket(), &aReadFdSet)) { mHdlcInterface.Read(); ProcessFrameQueue(); } mHdlcInterface.GetRxFrameBuffer().ClearReadFrames(); if (mState == kStateTransmitDone) { mState = kStateReceive; #if OPENTHREAD_ENABLE_DIAG if (otPlatDiagModeGet()) { otPlatDiagRadioTransmitDone(mInstance, mTransmitFrame, mTxError); } else #endif { otPlatRadioTxDone(mInstance, mTransmitFrame, (mAckRadioFrame.mLength != 0) ? &mAckRadioFrame : NULL, mTxError); } } if (FD_ISSET(mHdlcInterface.GetSocket(), &aWriteFdSet)) { if (mState == kStateTransmitPending) { RadioTransmit(); } } } otError RadioSpinel::SetPromiscuous(bool aEnable) { otError error; uint8_t mode = (aEnable ? SPINEL_MAC_PROMISCUOUS_MODE_NETWORK : SPINEL_MAC_PROMISCUOUS_MODE_OFF); SuccessOrExit(error = Set(SPINEL_PROP_MAC_PROMISCUOUS_MODE, SPINEL_DATATYPE_UINT8_S, mode)); mIsPromiscuous = aEnable; exit: return error; } otError RadioSpinel::SetShortAddress(uint16_t aAddress) { otError error = OT_ERROR_NONE; VerifyOrExit(mShortAddress != aAddress); SuccessOrExit(error = sRadioSpinel.Set(SPINEL_PROP_MAC_15_4_SADDR, SPINEL_DATATYPE_UINT16_S, aAddress)); mShortAddress = aAddress; exit: return error; } otError RadioSpinel::GetIeeeEui64(uint8_t *aIeeeEui64) { return Get(SPINEL_PROP_HWADDR, SPINEL_DATATYPE_EUI64_S, aIeeeEui64); } otError RadioSpinel::SetExtendedAddress(const otExtAddress &aExtAddress) { otError error; SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_LADDR, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8)); mExtendedAddress = aExtAddress; exit: return error; } otError RadioSpinel::SetPanId(uint16_t aPanId) { otError error = OT_ERROR_NONE; VerifyOrExit(mPanId != aPanId); SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_PANID, SPINEL_DATATYPE_UINT16_S, aPanId)); mPanId = aPanId; exit: return error; } otError RadioSpinel::EnableSrcMatch(bool aEnable) { return Set(SPINEL_PROP_MAC_SRC_MATCH_ENABLED, SPINEL_DATATYPE_BOOL_S, aEnable); } otError RadioSpinel::AddSrcMatchShortEntry(const uint16_t aShortAddress) { return Insert(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, SPINEL_DATATYPE_UINT16_S, aShortAddress); } otError RadioSpinel::AddSrcMatchExtEntry(const otExtAddress &aExtAddress) { return Insert(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8); } otError RadioSpinel::ClearSrcMatchShortEntry(const uint16_t aShortAddress) { return Remove(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, SPINEL_DATATYPE_UINT16_S, aShortAddress); } otError RadioSpinel::ClearSrcMatchExtEntry(const otExtAddress &aExtAddress) { return Remove(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8); } otError RadioSpinel::ClearSrcMatchShortEntries(void) { return Set(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, NULL); } otError RadioSpinel::ClearSrcMatchExtEntries(void) { return Set(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, NULL); } otError RadioSpinel::GetTransmitPower(int8_t &aPower) { otError error = Get(SPINEL_PROP_PHY_TX_POWER, SPINEL_DATATYPE_INT8_S, &aPower); LogIfFail("Get transmit power failed", error); return error; } int8_t RadioSpinel::GetRssi(void) { int8_t rssi = OT_RADIO_RSSI_INVALID; otError error = Get(SPINEL_PROP_PHY_RSSI, SPINEL_DATATYPE_INT8_S, &rssi); LogIfFail("Get RSSI failed", error); return rssi; } otError RadioSpinel::SetTransmitPower(int8_t aPower) { otError error = Set(SPINEL_PROP_PHY_TX_POWER, SPINEL_DATATYPE_INT8_S, aPower); LogIfFail("Set transmit power failed", error); return error; } otError RadioSpinel::EnergyScan(uint8_t aScanChannel, uint16_t aScanDuration) { otError error; VerifyOrExit(mRadioCaps & OT_RADIO_CAPS_ENERGY_SCAN, error = OT_ERROR_NOT_CAPABLE); SuccessOrExit(error = Set(SPINEL_PROP_MAC_SCAN_MASK, SPINEL_DATATYPE_DATA_S, &aScanChannel, sizeof(uint8_t))); SuccessOrExit(error = Set(SPINEL_PROP_MAC_SCAN_PERIOD, SPINEL_DATATYPE_UINT16_S, aScanDuration)); SuccessOrExit(error = Set(SPINEL_PROP_MAC_SCAN_STATE, SPINEL_DATATYPE_UINT8_S, SPINEL_SCAN_STATE_ENERGY)); exit: return error; } otError RadioSpinel::Get(spinel_prop_key_t aKey, const char *aFormat, ...) { otError error; assert(mWaitingTid == 0); mPropertyFormat = aFormat; va_start(mPropertyArgs, aFormat); error = RequestV(true, SPINEL_CMD_PROP_VALUE_GET, aKey, NULL, mPropertyArgs); va_end(mPropertyArgs); mPropertyFormat = NULL; return error; } otError RadioSpinel::Set(spinel_prop_key_t aKey, const char *aFormat, ...) { otError error; assert(mWaitingTid == 0); mExpectedCommand = SPINEL_CMD_PROP_VALUE_IS; va_start(mPropertyArgs, aFormat); error = RequestV(true, SPINEL_CMD_PROP_VALUE_SET, aKey, aFormat, mPropertyArgs); va_end(mPropertyArgs); mExpectedCommand = SPINEL_CMD_NOOP; return error; } otError RadioSpinel::Insert(spinel_prop_key_t aKey, const char *aFormat, ...) { otError error; assert(mWaitingTid == 0); mExpectedCommand = SPINEL_CMD_PROP_VALUE_INSERTED; va_start(mPropertyArgs, aFormat); error = RequestV(true, SPINEL_CMD_PROP_VALUE_INSERT, aKey, aFormat, mPropertyArgs); va_end(mPropertyArgs); mExpectedCommand = SPINEL_CMD_NOOP; return error; } otError RadioSpinel::Remove(spinel_prop_key_t aKey, const char *aFormat, ...) { otError error; assert(mWaitingTid == 0); mExpectedCommand = SPINEL_CMD_PROP_VALUE_REMOVED; va_start(mPropertyArgs, aFormat); error = RequestV(true, SPINEL_CMD_PROP_VALUE_REMOVE, aKey, aFormat, mPropertyArgs); va_end(mPropertyArgs); mExpectedCommand = SPINEL_CMD_NOOP; return error; } otError RadioSpinel::WaitResponse(void) { uint64_t now = otSysGetTime(); uint64_t end = now + kMaxWaitTime * US_PER_MS; struct timeval timeout = {kMaxWaitTime / 1000, (kMaxWaitTime % 1000) * 1000}; do { #if OPENTHREAD_POSIX_VIRTUAL_TIME struct Event event; otSimSendSleepEvent(&timeout); otSimReceiveEvent(&event); switch (event.mEvent) { case OT_SIM_EVENT_RADIO_SPINEL_WRITE: mHdlcInterface.ProcessReadData(event.mData, event.mDataLength); break; case OT_SIM_EVENT_ALARM_FIRED: FreeTid(mWaitingTid); mWaitingTid = 0; ExitNow(mError = OT_ERROR_RESPONSE_TIMEOUT); break; default: assert(false); break; } #else // OPENTHREAD_POSIX_VIRTUAL_TIME int sockFd = mHdlcInterface.GetSocket(); fd_set read_fds; fd_set error_fds; int rval; FD_ZERO(&read_fds); FD_ZERO(&error_fds); FD_SET(sockFd, &read_fds); FD_SET(sockFd, &error_fds); rval = select(sockFd + 1, &read_fds, NULL, &error_fds, &timeout); if (rval > 0) { if (FD_ISSET(sockFd, &read_fds)) { mHdlcInterface.Read(); } else if (FD_ISSET(sockFd, &error_fds)) { fprintf(stderr, "NCP error\r\n"); exit(OT_EXIT_FAILURE); } else { assert(false); exit(OT_EXIT_FAILURE); } } else if (rval == 0) { FreeTid(mWaitingTid); mWaitingTid = 0; ExitNow(mError = OT_ERROR_RESPONSE_TIMEOUT); } else if (errno != EINTR) { perror("wait response"); exit(OT_EXIT_FAILURE); } #endif // OPENTHREAD_POSIX_VIRTUAL_TIME now = otSysGetTime(); if (end > now) { uint64_t remain = end - now; timeout.tv_sec = remain / US_PER_S; timeout.tv_usec = static_cast<suseconds_t>(remain % US_PER_S); } else { mWaitingTid = 0; mError = OT_ERROR_RESPONSE_TIMEOUT; } } while (mWaitingTid || !mIsReady); exit: LogIfFail("Error waiting response", mError); // This indicates end of waiting repsonse. mWaitingKey = SPINEL_PROP_LAST_STATUS; return mError; } spinel_tid_t RadioSpinel::GetNextTid(void) { spinel_tid_t tid = 0; if (((1 << mCmdNextTid) & mCmdTidsInUse) == 0) { tid = mCmdNextTid; mCmdNextTid = SPINEL_GET_NEXT_TID(mCmdNextTid); mCmdTidsInUse |= (1 << tid); } return tid; } /** * This method delivers the radio frame to transceiver. * * otPlatRadioTxStarted() is triggered immediately for now, which may be earlier than real started time. * */ void RadioSpinel::RadioTransmit(void) { otError error; assert(mTransmitFrame != NULL); otPlatRadioTxStarted(mInstance, mTransmitFrame); assert(mState == kStateTransmitPending); error = Request(true, SPINEL_CMD_PROP_VALUE_SET, SPINEL_PROP_STREAM_RAW, SPINEL_DATATYPE_DATA_WLEN_S SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_INT8_S, mTransmitFrame->mPsdu, mTransmitFrame->mLength, mTransmitFrame->mChannel, mTransmitFrame->mInfo.mRxInfo.mRssi); if (error == OT_ERROR_NONE) { mState = kStateTransmitting; } else { mState = kStateReceive; #if OPENTHREAD_ENABLE_DIAG if (otPlatDiagModeGet()) { otPlatDiagRadioTransmitDone(mInstance, mTransmitFrame, error); } else #endif { otPlatRadioTxDone(mInstance, mTransmitFrame, NULL, error); } } } otError RadioSpinel::SendReset(void) { otError error = OT_ERROR_NONE; uint8_t buffer[kMaxSpinelFrame]; spinel_ssize_t packed; // Pack the header, command and key packed = spinel_datatype_pack(buffer, sizeof(buffer), "Ci", SPINEL_HEADER_FLAG | SPINEL_HEADER_IID_0, SPINEL_CMD_RESET); VerifyOrExit(packed > 0 && static_cast<size_t>(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); SuccessOrExit(error = mHdlcInterface.SendFrame(buffer, static_cast<uint16_t>(packed))); sleep(0); exit: return error; } otError RadioSpinel::SendCommand(uint32_t aCommand, spinel_prop_key_t aKey, spinel_tid_t tid, const char * aFormat, va_list args) { otError error = OT_ERROR_NONE; uint8_t buffer[kMaxSpinelFrame]; spinel_ssize_t packed; uint16_t offset; // Pack the header, command and key packed = spinel_datatype_pack(buffer, sizeof(buffer), "Cii", SPINEL_HEADER_FLAG | SPINEL_HEADER_IID_0 | tid, aCommand, aKey); VerifyOrExit(packed > 0 && static_cast<size_t>(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); offset = static_cast<uint16_t>(packed); // Pack the data (if any) if (aFormat) { packed = spinel_datatype_vpack(buffer + offset, sizeof(buffer) - offset, aFormat, args); VerifyOrExit(packed > 0 && static_cast<size_t>(packed + offset) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); offset += static_cast<uint16_t>(packed); } error = mHdlcInterface.SendFrame(buffer, offset); exit: return error; } otError RadioSpinel::RequestV(bool aWait, uint32_t command, spinel_prop_key_t aKey, const char *aFormat, va_list aArgs) { otError error = OT_ERROR_NONE; spinel_tid_t tid = (aWait ? GetNextTid() : 0); VerifyOrExit(!aWait || tid > 0, error = OT_ERROR_BUSY); error = SendCommand(command, aKey, tid, aFormat, aArgs); VerifyOrExit(error == OT_ERROR_NONE); if (aKey == SPINEL_PROP_STREAM_RAW) { // not allowed to send another frame before the last frame is done. assert(mTxRadioTid == 0); VerifyOrExit(mTxRadioTid == 0, error = OT_ERROR_BUSY); mTxRadioTid = tid; } else if (aWait) { mWaitingKey = aKey; mWaitingTid = tid; error = WaitResponse(); } exit: return error; } otError RadioSpinel::Request(bool aWait, uint32_t aCommand, spinel_prop_key_t aKey, const char *aFormat, ...) { va_list args; va_start(args, aFormat); otError status = RequestV(aWait, aCommand, aKey, aFormat, args); va_end(args); return status; } void RadioSpinel::HandleTransmitDone(uint32_t aCommand, spinel_prop_key_t aKey, const uint8_t * aBuffer, uint16_t aLength) { otError error = OT_ERROR_NONE; spinel_status_t status = SPINEL_STATUS_OK; spinel_ssize_t unpacked; VerifyOrExit(aCommand == SPINEL_CMD_PROP_VALUE_IS && aKey == SPINEL_PROP_LAST_STATUS, error = OT_ERROR_FAILED); unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UINT_PACKED_S, &status); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); aBuffer += unpacked; aLength -= static_cast<uint16_t>(unpacked); if (status == SPINEL_STATUS_OK) { bool framePending = false; unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_BOOL_S, &framePending); OT_UNUSED_VARIABLE(framePending); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); aBuffer += unpacked; aLength -= static_cast<spinel_size_t>(unpacked); if (aLength > 0) { SuccessOrExit(error = ParseRadioFrame(mAckRadioFrame, aBuffer, aLength)); } else { mAckRadioFrame.mLength = 0; } } else { otLogWarnPlat("Spinel status: %d.", status); error = SpinelStatusToOtError(status); } exit: mState = kStateTransmitDone; mTxError = error; LogIfFail("Handle transmit done failed", error); } otError RadioSpinel::Transmit(otRadioFrame &aFrame) { otError error = OT_ERROR_INVALID_STATE; VerifyOrExit(mState == kStateReceive); mState = kStateTransmitPending; error = OT_ERROR_NONE; mTransmitFrame = &aFrame; exit: return error; } otError RadioSpinel::Receive(uint8_t aChannel) { otError error = OT_ERROR_NONE; VerifyOrExit(mState != kStateDisabled, error = OT_ERROR_INVALID_STATE); if (mChannel != aChannel) { error = Set(SPINEL_PROP_PHY_CHAN, SPINEL_DATATYPE_UINT8_S, aChannel); VerifyOrExit(error == OT_ERROR_NONE); mChannel = aChannel; } if (mState == kStateSleep) { error = Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, true); VerifyOrExit(error == OT_ERROR_NONE); } if (mTxRadioTid != 0) { FreeTid(mTxRadioTid); mTxRadioTid = 0; } mState = kStateReceive; exit: assert(error == OT_ERROR_NONE); return error; } otError RadioSpinel::Sleep(void) { otError error = OT_ERROR_NONE; switch (mState) { case kStateReceive: error = sRadioSpinel.Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, false); VerifyOrExit(error == OT_ERROR_NONE); mState = kStateSleep; break; case kStateSleep: break; default: error = OT_ERROR_INVALID_STATE; break; } exit: return error; } otError RadioSpinel::Enable(otInstance *aInstance) { otError error = OT_ERROR_NONE; if (!otPlatRadioIsEnabled(mInstance)) { mInstance = aInstance; SuccessOrExit(error = Set(SPINEL_PROP_PHY_ENABLED, SPINEL_DATATYPE_BOOL_S, true)); SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_PANID, SPINEL_DATATYPE_UINT16_S, mPanId)); SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_SADDR, SPINEL_DATATYPE_UINT16_S, mShortAddress)); error = Get(SPINEL_PROP_PHY_RX_SENSITIVITY, SPINEL_DATATYPE_INT8_S, &mRxSensitivity); VerifyOrExit(error == OT_ERROR_NONE); mState = kStateSleep; } exit: assert(error == OT_ERROR_NONE); return error; } otError RadioSpinel::Disable(void) { otError error = OT_ERROR_NONE; if (otPlatRadioIsEnabled(mInstance)) { mInstance = NULL; error = sRadioSpinel.Set(SPINEL_PROP_PHY_ENABLED, SPINEL_DATATYPE_BOOL_S, false); VerifyOrExit(error == OT_ERROR_NONE); mState = kStateDisabled; } exit: return error; } #if OPENTHREAD_ENABLE_DIAG otError RadioSpinel::PlatDiagProcess(const char *aString, char *aOutput, size_t aOutputMaxLen) { otError error; mDiagOutput = aOutput; mDiagOutputMaxLen = aOutputMaxLen; error = Set(SPINEL_PROP_NEST_STREAM_MFG, SPINEL_DATATYPE_UTF8_S, aString); mDiagOutput = NULL; mDiagOutputMaxLen = 0; return error; } #endif } // namespace PosixApp } // namespace ot void otPlatRadioGetIeeeEui64(otInstance *aInstance, uint8_t *aIeeeEui64) { SuccessOrDie(sRadioSpinel.GetIeeeEui64(aIeeeEui64)); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioSetPanId(otInstance *aInstance, uint16_t panid) { SuccessOrDie(sRadioSpinel.SetPanId(panid)); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioSetExtendedAddress(otInstance *aInstance, const otExtAddress *aAddress) { otExtAddress addr; for (size_t i = 0; i < sizeof(addr); i++) { addr.m8[i] = aAddress->m8[sizeof(addr) - 1 - i]; } SuccessOrDie(sRadioSpinel.SetExtendedAddress(addr)); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioSetShortAddress(otInstance *aInstance, uint16_t aAddress) { SuccessOrDie(sRadioSpinel.SetShortAddress(aAddress)); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) { SuccessOrDie(sRadioSpinel.SetPromiscuous(aEnable)); OT_UNUSED_VARIABLE(aInstance); } void platformRadioInit(const char *aRadioFile, const char *aRadioConfig) { sRadioSpinel.Init(aRadioFile, aRadioConfig); } void platformRadioDeinit(void) { sRadioSpinel.Deinit(); } bool otPlatRadioIsEnabled(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.IsEnabled(); } otError otPlatRadioEnable(otInstance *aInstance) { return sRadioSpinel.Enable(aInstance); } otError otPlatRadioDisable(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.Disable(); } otError otPlatRadioSleep(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.Sleep(); } otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.Receive(aChannel); } otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.Transmit(*aFrame); } otRadioFrame *otPlatRadioGetTransmitBuffer(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return &sRadioSpinel.GetTransmitFrame(); } int8_t otPlatRadioGetRssi(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.GetRssi(); } otRadioCaps otPlatRadioGetCaps(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.GetRadioCaps(); } const char *otPlatRadioGetVersionString(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.GetVersion(); } bool otPlatRadioGetPromiscuous(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.IsPromiscuous(); } void platformRadioUpdateFdSet(fd_set *aReadFdSet, fd_set *aWriteFdSet, int *aMaxFd, struct timeval *aTimeout) { sRadioSpinel.UpdateFdSet(*aReadFdSet, *aWriteFdSet, *aMaxFd, *aTimeout); } void platformRadioProcess(otInstance *aInstance, const fd_set *aReadFdSet, const fd_set *aWriteFdSet) { sRadioSpinel.Process(*aReadFdSet, *aWriteFdSet); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioEnableSrcMatch(otInstance *aInstance, bool aEnable) { SuccessOrDie(sRadioSpinel.EnableSrcMatch(aEnable)); OT_UNUSED_VARIABLE(aInstance); } otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, uint16_t aShortAddress) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.AddSrcMatchShortEntry(aShortAddress); } otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { otExtAddress addr; for (size_t i = 0; i < sizeof(addr); i++) { addr.m8[i] = aExtAddress->m8[sizeof(addr) - 1 - i]; } OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.AddSrcMatchExtEntry(addr); } otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, uint16_t aShortAddress) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.ClearSrcMatchShortEntry(aShortAddress); } otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { otExtAddress addr; for (size_t i = 0; i < sizeof(addr); i++) { addr.m8[i] = aExtAddress->m8[sizeof(addr) - 1 - i]; } OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.ClearSrcMatchExtEntry(addr); } void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) { SuccessOrDie(sRadioSpinel.ClearSrcMatchShortEntries()); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) { SuccessOrDie(sRadioSpinel.ClearSrcMatchExtEntries()); OT_UNUSED_VARIABLE(aInstance); } otError otPlatRadioEnergyScan(otInstance *aInstance, uint8_t aScanChannel, uint16_t aScanDuration) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.EnergyScan(aScanChannel, aScanDuration); } otError otPlatRadioGetTransmitPower(otInstance *aInstance, int8_t *aPower) { assert(aPower != NULL); OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.GetTransmitPower(*aPower); } otError otPlatRadioSetTransmitPower(otInstance *aInstance, int8_t aPower) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.SetTransmitPower(aPower); } int8_t otPlatRadioGetReceiveSensitivity(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.GetReceiveSensitivity(); } #if OPENTHREAD_POSIX_VIRTUAL_TIME void ot::PosixApp::RadioSpinel::Process(const Event &aEvent) { if (mHdlcInterface.GetRxFrameBuffer().HasSavedFrame()) { ProcessFrameQueue(); } // The current event can be other event types if (aEvent.mEvent == OT_SIM_EVENT_RADIO_SPINEL_WRITE) { mHdlcInterface.ProcessReadData(aEvent.mData, aEvent.mDataLength); ProcessFrameQueue(); } mHdlcInterface.GetRxFrameBuffer().ClearReadFrames(); if (mState == kStateTransmitDone) { mState = kStateReceive; #if OPENTHREAD_ENABLE_DIAG if (otPlatDiagModeGet()) { otPlatDiagRadioTransmitDone(mInstance, mTransmitFrame, mTxError); } else #endif { otPlatRadioTxDone(mInstance, mTransmitFrame, (mAckRadioFrame.mLength != 0) ? &mAckRadioFrame : NULL, mTxError); } } if (mState == kStateTransmitPending) { RadioTransmit(); } } void ot::PosixApp::RadioSpinel::Update(struct timeval &aTimeout) { // Prevent sleep event when transmitting if (mState == kStateTransmitPending) { aTimeout.tv_sec = 0; aTimeout.tv_usec = 0; } } void otSimRadioSpinelUpdate(struct timeval *aTimeout) { sRadioSpinel.Update(*aTimeout); } void otSimRadioSpinelProcess(otInstance *aInstance, const struct Event *aEvent) { sRadioSpinel.Process(*aEvent); OT_UNUSED_VARIABLE(aInstance); } #endif // OPENTHREAD_POSIX_VIRTUAL_TIME #if OPENTHREAD_ENABLE_DIAG void otPlatDiagProcess(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen) { // deliver the platform specific diags commands to radio only ncp. OT_UNUSED_VARIABLE(aInstance); char cmd[OPENTHREAD_CONFIG_DIAG_CMD_LINE_BUFFER_SIZE] = {'\0'}; char *cur = cmd; char *end = cmd + sizeof(cmd); for (int index = 0; index < argc; index++) { cur += snprintf(cur, static_cast<size_t>(end - cur), "%s ", argv[index]); } sRadioSpinel.PlatDiagProcess(cmd, aOutput, aOutputMaxLen); } void otPlatDiagModeSet(bool aMode) { SuccessOrExit(sRadioSpinel.PlatDiagProcess(aMode ? "start" : "stop", NULL, 0)); sRadioSpinel.SetDiagEnabled(aMode); exit: return; } bool otPlatDiagModeGet(void) { return sRadioSpinel.IsDiagEnabled(); } void otPlatDiagTxPowerSet(int8_t aTxPower) { char cmd[OPENTHREAD_CONFIG_DIAG_CMD_LINE_BUFFER_SIZE]; snprintf(cmd, sizeof(cmd), "power %d", aTxPower); SuccessOrExit(sRadioSpinel.PlatDiagProcess(cmd, NULL, 0)); exit: return; } void otPlatDiagChannelSet(uint8_t aChannel) { char cmd[OPENTHREAD_CONFIG_DIAG_CMD_LINE_BUFFER_SIZE]; snprintf(cmd, sizeof(cmd), "channel %d", aChannel); SuccessOrExit(sRadioSpinel.PlatDiagProcess(cmd, NULL, 0)); exit: return; } void otPlatDiagRadioReceived(otInstance *aInstance, otRadioFrame *aFrame, otError aError) { OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aFrame); OT_UNUSED_VARIABLE(aError); } void otPlatDiagAlarmCallback(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); } #endif // OPENTHREAD_ENABLE_DIAG [radio-spinel] add meta-data (CSMA/retry counts) in `STREAM_RAW` property set (#3727) This commit updates `RadioSpinel::RadioTrasnmit()` to include the `otRadioFrame` parameters (max CSMA backoffs, max frame retries, and CSMA-CA enabled flag) as part of meta-data in `PROP_STREAM_RAW` property `VALUE_SET` command. /* * Copyright (c) 2018, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements the spinel based radio transceiver. */ #include "openthread-core-config.h" #include "platform-posix.h" #include "radio_spinel.hpp" #include <assert.h> #include <errno.h> #include <stdarg.h> #include <stdlib.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/wait.h> #include <syslog.h> #include <termios.h> #include <unistd.h> #include <common/code_utils.hpp> #include <common/encoding.hpp> #include <common/logging.hpp> #include <openthread/platform/alarm-milli.h> #include <openthread/platform/diag.h> #include <openthread/platform/radio.h> static ot::PosixApp::RadioSpinel sRadioSpinel; namespace ot { namespace PosixApp { static otError SpinelStatusToOtError(spinel_status_t aError) { otError ret; switch (aError) { case SPINEL_STATUS_OK: ret = OT_ERROR_NONE; break; case SPINEL_STATUS_FAILURE: ret = OT_ERROR_FAILED; break; case SPINEL_STATUS_DROPPED: ret = OT_ERROR_DROP; break; case SPINEL_STATUS_NOMEM: ret = OT_ERROR_NO_BUFS; break; case SPINEL_STATUS_BUSY: ret = OT_ERROR_BUSY; break; case SPINEL_STATUS_PARSE_ERROR: ret = OT_ERROR_PARSE; break; case SPINEL_STATUS_INVALID_ARGUMENT: ret = OT_ERROR_INVALID_ARGS; break; case SPINEL_STATUS_UNIMPLEMENTED: ret = OT_ERROR_NOT_IMPLEMENTED; break; case SPINEL_STATUS_INVALID_STATE: ret = OT_ERROR_INVALID_STATE; break; case SPINEL_STATUS_NO_ACK: ret = OT_ERROR_NO_ACK; break; case SPINEL_STATUS_CCA_FAILURE: ret = OT_ERROR_CHANNEL_ACCESS_FAILURE; break; case SPINEL_STATUS_ALREADY: ret = OT_ERROR_ALREADY; break; case SPINEL_STATUS_PROP_NOT_FOUND: case SPINEL_STATUS_ITEM_NOT_FOUND: ret = OT_ERROR_NOT_FOUND; break; default: if (aError >= SPINEL_STATUS_STACK_NATIVE__BEGIN && aError <= SPINEL_STATUS_STACK_NATIVE__END) { ret = static_cast<otError>(aError - SPINEL_STATUS_STACK_NATIVE__BEGIN); } else { ret = OT_ERROR_FAILED; } break; } return ret; } static void LogIfFail(const char *aText, otError aError) { OT_UNUSED_VARIABLE(aText); OT_UNUSED_VARIABLE(aError); if (aError != OT_ERROR_NONE) { otLogWarnPlat("%s: %s", aText, otThreadErrorToString(aError)); } } void HdlcInterface::Callbacks::HandleReceivedFrame(HdlcInterface &aInterface) { static_cast<RadioSpinel *>(this)->HandleSpinelFrame(aInterface.GetRxFrameBuffer()); } RadioSpinel::RadioSpinel(void) : mInstance(NULL) , mHdlcInterface(*this) , mCmdTidsInUse(0) , mCmdNextTid(1) , mTxRadioTid(0) , mWaitingTid(0) , mWaitingKey(SPINEL_PROP_LAST_STATUS) , mPropertyFormat(NULL) , mExpectedCommand(0) , mError(OT_ERROR_NONE) , mTransmitFrame(NULL) , mShortAddress(0) , mPanId(0xffff) , mRadioCaps(0) , mChannel(0) , mRxSensitivity(0) , mState(kStateDisabled) , mIsPromiscuous(false) , mIsReady(false) , mSupportsLogStream(false) #if OPENTHREAD_ENABLE_DIAG , mDiagMode(false) , mDiagOutput(NULL) , mDiagOutputMaxLen(0) #endif { mVersion[0] = '\0'; } void RadioSpinel::Init(const char *aRadioFile, const char *aRadioConfig) { otError error = OT_ERROR_NONE; SuccessOrExit(error = mHdlcInterface.Init(aRadioFile, aRadioConfig)); SuccessOrExit(error = SendReset()); SuccessOrExit(error = WaitResponse()); VerifyOrExit(mIsReady, error = OT_ERROR_FAILED); SuccessOrExit(error = CheckSpinelVersion()); SuccessOrExit(error = CheckCapabilities()); SuccessOrExit(error = CheckRadioCapabilities()); SuccessOrExit(error = Get(SPINEL_PROP_NCP_VERSION, SPINEL_DATATYPE_UTF8_S, mVersion, sizeof(mVersion))); SuccessOrExit(error = Get(SPINEL_PROP_HWADDR, SPINEL_DATATYPE_UINT64_S, &gNodeId)); gNodeId = ot::Encoding::BigEndian::HostSwap64(gNodeId); mRxRadioFrame.mPsdu = mRxPsdu; mTxRadioFrame.mPsdu = mTxPsdu; mAckRadioFrame.mPsdu = mAckPsdu; exit: SuccessOrDie(error); } otError RadioSpinel::CheckSpinelVersion(void) { otError error = OT_ERROR_NONE; unsigned int versionMajor; unsigned int versionMinor; SuccessOrExit(error = Get(SPINEL_PROP_PROTOCOL_VERSION, (SPINEL_DATATYPE_UINT_PACKED_S SPINEL_DATATYPE_UINT_PACKED_S), &versionMajor, &versionMinor)); if ((versionMajor != SPINEL_PROTOCOL_VERSION_THREAD_MAJOR) || (versionMinor != SPINEL_PROTOCOL_VERSION_THREAD_MINOR)) { otLogCritPlat("Spinel version mismatch - PosixApp:%d.%d, RCP:%d.%d", SPINEL_PROTOCOL_VERSION_THREAD_MAJOR, SPINEL_PROTOCOL_VERSION_THREAD_MINOR, versionMajor, versionMinor); exit(OT_EXIT_RADIO_SPINEL_INCOMPATIBLE); } exit: return error; } otError RadioSpinel::CheckCapabilities(void) { otError error = OT_ERROR_NONE; uint8_t capsBuffer[kCapsBufferSize]; const uint8_t *capsData = capsBuffer; spinel_size_t capsLength = sizeof(capsBuffer); bool supportsRawRadio = false; SuccessOrExit(error = Get(SPINEL_PROP_CAPS, SPINEL_DATATYPE_DATA_S, capsBuffer, &capsLength)); while (capsLength > 0) { unsigned int capability; spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack(capsData, capsLength, SPINEL_DATATYPE_UINT_PACKED_S, &capability); VerifyOrExit(unpacked > 0, error = OT_ERROR_FAILED); if (capability == SPINEL_CAP_OPENTHREAD_LOG_METADATA) { mSupportsLogStream = true; } if (capability == SPINEL_CAP_MAC_RAW) { supportsRawRadio = true; } capsData += unpacked; capsLength -= static_cast<spinel_size_t>(unpacked); } if (!supportsRawRadio) { otLogCritPlat("RCP capability list does not include support for radio/raw mode"); exit(OT_EXIT_RADIO_SPINEL_INCOMPATIBLE); } exit: return error; } otError RadioSpinel::CheckRadioCapabilities(void) { const otRadioCaps kRequiredRadioCaps = OT_RADIO_CAPS_ACK_TIMEOUT | OT_RADIO_CAPS_TRANSMIT_RETRIES | OT_RADIO_CAPS_CSMA_BACKOFF; otError error = OT_ERROR_NONE; unsigned int caps; SuccessOrExit(error = Get(SPINEL_PROP_RADIO_CAPS, SPINEL_DATATYPE_UINT_PACKED_S, &caps)); mRadioCaps = static_cast<otRadioCaps>(caps); if ((mRadioCaps & kRequiredRadioCaps) != kRequiredRadioCaps) { otLogCritPlat("RCP does not support required capabilities: ack-timeout:%s, tx-retries:%s, CSMA-backoff:%s", (mRadioCaps & OT_RADIO_CAPS_ACK_TIMEOUT) ? "yes" : "no", (mRadioCaps & OT_RADIO_CAPS_TRANSMIT_RETRIES) ? "yes" : "no", (mRadioCaps & OT_RADIO_CAPS_CSMA_BACKOFF) ? "yes" : "no"); exit(OT_EXIT_RADIO_SPINEL_INCOMPATIBLE); } exit: return error; } void RadioSpinel::Deinit(void) { mHdlcInterface.Deinit(); } void RadioSpinel::HandleSpinelFrame(HdlcInterface::RxFrameBuffer &aFrameBuffer) { otError error = OT_ERROR_NONE; uint8_t header; spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack(aFrameBuffer.GetFrame(), aFrameBuffer.GetLength(), "C", &header); VerifyOrExit(unpacked > 0 && (header & SPINEL_HEADER_FLAG) == SPINEL_HEADER_FLAG && SPINEL_HEADER_GET_IID(header) == 0, error = OT_ERROR_PARSE); if (SPINEL_HEADER_GET_TID(header) == 0) { HandleNotification(aFrameBuffer); } else { HandleResponse(aFrameBuffer.GetFrame(), aFrameBuffer.GetLength()); aFrameBuffer.DiscardFrame(); } exit: if (error != OT_ERROR_NONE) { aFrameBuffer.DiscardFrame(); otLogWarnPlat("Error handling hdlc frame: %s", otThreadErrorToString(error)); } } void RadioSpinel::HandleNotification(HdlcInterface::RxFrameBuffer &aFrameBuffer) { spinel_prop_key_t key; spinel_size_t len = 0; spinel_ssize_t unpacked; uint8_t * data = NULL; uint32_t cmd; uint8_t header; otError error = OT_ERROR_NONE; bool shouldSaveFrame = false; unpacked = spinel_datatype_unpack(aFrameBuffer.GetFrame(), aFrameBuffer.GetLength(), "CiiD", &header, &cmd, &key, &data, &len); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); VerifyOrExit(SPINEL_HEADER_GET_TID(header) == 0, error = OT_ERROR_PARSE); switch (cmd) { case SPINEL_CMD_PROP_VALUE_IS: // Some spinel properties cannot be handled during `WaitResponse()`, we must cache these events. // `mWaitingTid` is released immediately after received the response. And `mWaitingKey` is be set // to `SPINEL_PROP_LAST_STATUS` at the end of `WaitResponse()`. if (!IsSafeToHandleNow(key)) { ExitNow(shouldSaveFrame = true); } HandleValueIs(key, data, static_cast<uint16_t>(len)); break; case SPINEL_CMD_PROP_VALUE_INSERTED: case SPINEL_CMD_PROP_VALUE_REMOVED: otLogInfoPlat("Ignored command %d", cmd); break; default: ExitNow(error = OT_ERROR_PARSE); } exit: if (shouldSaveFrame) { aFrameBuffer.SaveFrame(); } else { aFrameBuffer.DiscardFrame(); } LogIfFail("Error processing notification", error); } void RadioSpinel::HandleNotification(const uint8_t *aFrame, uint16_t aLength) { spinel_prop_key_t key; spinel_size_t len = 0; spinel_ssize_t unpacked; uint8_t * data = NULL; uint32_t cmd; uint8_t header; otError error = OT_ERROR_NONE; unpacked = spinel_datatype_unpack(aFrame, aLength, "CiiD", &header, &cmd, &key, &data, &len); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); VerifyOrExit(SPINEL_HEADER_GET_TID(header) == 0, error = OT_ERROR_PARSE); VerifyOrExit(cmd == SPINEL_CMD_PROP_VALUE_IS); HandleValueIs(key, data, static_cast<uint16_t>(len)); exit: LogIfFail("Error processing saved notification", error); } void RadioSpinel::HandleResponse(const uint8_t *aBuffer, uint16_t aLength) { spinel_prop_key_t key; uint8_t * data = NULL; spinel_size_t len = 0; uint8_t header = 0; uint32_t cmd = 0; spinel_ssize_t rval = 0; otError error = OT_ERROR_NONE; rval = spinel_datatype_unpack(aBuffer, aLength, "CiiD", &header, &cmd, &key, &data, &len); VerifyOrExit(rval > 0 && cmd >= SPINEL_CMD_PROP_VALUE_IS && cmd <= SPINEL_CMD_PROP_VALUE_REMOVED, error = OT_ERROR_PARSE); if (mWaitingTid == SPINEL_HEADER_GET_TID(header)) { HandleWaitingResponse(cmd, key, data, static_cast<uint16_t>(len)); FreeTid(mWaitingTid); mWaitingTid = 0; } else if (mTxRadioTid == SPINEL_HEADER_GET_TID(header)) { if (mState == kStateTransmitting) { HandleTransmitDone(cmd, key, data, static_cast<uint16_t>(len)); } FreeTid(mTxRadioTid); mTxRadioTid = 0; } else { otLogWarnPlat("Unexpected Spinel transaction message: %u", SPINEL_HEADER_GET_TID(header)); error = OT_ERROR_DROP; } exit: LogIfFail("Error processing response", error); } void RadioSpinel::HandleWaitingResponse(uint32_t aCommand, spinel_prop_key_t aKey, const uint8_t * aBuffer, uint16_t aLength) { if (aKey == SPINEL_PROP_LAST_STATUS) { spinel_status_t status; spinel_ssize_t unpacked = spinel_datatype_unpack(aBuffer, aLength, "i", &status); VerifyOrExit(unpacked > 0, mError = OT_ERROR_PARSE); mError = SpinelStatusToOtError(status); } #if OPENTHREAD_ENABLE_DIAG else if (aKey == SPINEL_PROP_NEST_STREAM_MFG) { spinel_ssize_t unpacked; VerifyOrExit(mDiagOutput != NULL); unpacked = spinel_datatype_unpack_in_place(aBuffer, aLength, SPINEL_DATATYPE_UTF8_S, mDiagOutput, &mDiagOutputMaxLen); VerifyOrExit(unpacked > 0, mError = OT_ERROR_PARSE); } #endif else if (aKey == mWaitingKey) { if (mPropertyFormat) { spinel_ssize_t unpacked = spinel_datatype_vunpack_in_place(aBuffer, aLength, mPropertyFormat, mPropertyArgs); VerifyOrExit(unpacked > 0, mError = OT_ERROR_PARSE); mError = OT_ERROR_NONE; } else { if (aCommand == mExpectedCommand) { mError = OT_ERROR_NONE; } else { mError = OT_ERROR_DROP; } } } else { mError = OT_ERROR_DROP; } exit: LogIfFail("Error processing result", mError); } void RadioSpinel::HandleValueIs(spinel_prop_key_t aKey, const uint8_t *aBuffer, uint16_t aLength) { otError error = OT_ERROR_NONE; if (aKey == SPINEL_PROP_STREAM_RAW) { SuccessOrExit(error = ParseRadioFrame(mRxRadioFrame, aBuffer, aLength)); RadioReceive(); } else if (aKey == SPINEL_PROP_LAST_STATUS) { spinel_status_t status = SPINEL_STATUS_OK; spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack(aBuffer, aLength, "i", &status); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); if (status >= SPINEL_STATUS_RESET__BEGIN && status <= SPINEL_STATUS_RESET__END) { otLogCritPlat("RCP reset: %s", spinel_status_to_cstr(status)); mIsReady = true; // If RCP crashes/resets while radio was enabled, posix app exits. VerifyOrDie(!IsEnabled(), OT_EXIT_RADIO_SPINEL_RESET); } else { otLogInfoPlat("RCP last status: %s", spinel_status_to_cstr(status)); } } else if (aKey == SPINEL_PROP_MAC_ENERGY_SCAN_RESULT) { uint8_t scanChannel; int8_t maxRssi; spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack(aBuffer, aLength, "Cc", &scanChannel, &maxRssi); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); otPlatRadioEnergyScanDone(mInstance, maxRssi); } else if (aKey == SPINEL_PROP_STREAM_DEBUG) { char logStream[OPENTHREAD_CONFIG_NCP_SPINEL_LOG_MAX_SIZE + 1]; unsigned int len = sizeof(logStream); spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack_in_place(aBuffer, aLength, SPINEL_DATATYPE_DATA_S, logStream, &len); assert(len < sizeof(logStream)); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); logStream[len] = '\0'; otLogDebgPlat("RCP => %s", logStream); } else if ((aKey == SPINEL_PROP_STREAM_LOG) && mSupportsLogStream) { const char * logString; spinel_ssize_t unpacked; uint8_t logLevel; unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UTF8_S, &logString); VerifyOrExit(unpacked >= 0, error = OT_ERROR_PARSE); aBuffer += unpacked; aLength -= unpacked; unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UINT8_S, &logLevel); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); switch (logLevel) { case SPINEL_NCP_LOG_LEVEL_EMERG: case SPINEL_NCP_LOG_LEVEL_ALERT: case SPINEL_NCP_LOG_LEVEL_CRIT: otLogCritPlat("RCP => %s", logString); break; case SPINEL_NCP_LOG_LEVEL_ERR: case SPINEL_NCP_LOG_LEVEL_WARN: otLogWarnPlat("RCP => %s", logString); break; case SPINEL_NCP_LOG_LEVEL_NOTICE: otLogNotePlat("RCP => %s", logString); break; case SPINEL_NCP_LOG_LEVEL_INFO: otLogInfoPlat("RCP => %s", logString); break; case SPINEL_NCP_LOG_LEVEL_DEBUG: default: otLogDebgPlat("RCP => %s", logString); break; } } exit: LogIfFail("Failed to handle ValueIs", error); } otError RadioSpinel::ParseRadioFrame(otRadioFrame &aFrame, const uint8_t *aBuffer, uint16_t aLength) { otError error = OT_ERROR_NONE; uint16_t packetLength = 0; spinel_ssize_t unpacked; uint16_t flags = 0; int8_t noiseFloor = -128; spinel_size_t size = OT_RADIO_FRAME_MAX_SIZE; unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UINT16_S, &packetLength); VerifyOrExit(unpacked > 0 && packetLength <= OT_RADIO_FRAME_MAX_SIZE, error = OT_ERROR_PARSE); aFrame.mLength = static_cast<uint8_t>(packetLength); unpacked = spinel_datatype_unpack_in_place(aBuffer, aLength, SPINEL_DATATYPE_DATA_WLEN_S SPINEL_DATATYPE_INT8_S SPINEL_DATATYPE_INT8_S SPINEL_DATATYPE_UINT16_S SPINEL_DATATYPE_STRUCT_S( // PHY-data SPINEL_DATATYPE_UINT8_S // 802.15.4 channel SPINEL_DATATYPE_UINT8_S // 802.15.4 LQI ), aFrame.mPsdu, &size, &aFrame.mInfo.mRxInfo.mRssi, &noiseFloor, &flags, &aFrame.mChannel, &aFrame.mInfo.mRxInfo.mLqi); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); exit: LogIfFail("Handle radio frame failed", error); return error; } void RadioSpinel::ProcessFrameQueue(void) { uint8_t *frame; uint16_t length; while (mHdlcInterface.GetRxFrameBuffer().ReadSavedFrame(frame, length) == OT_ERROR_NONE) { HandleNotification(frame, length); } } void RadioSpinel::RadioReceive(void) { if (!mIsPromiscuous) { switch (mState) { case kStateDisabled: case kStateSleep: ExitNow(); case kStateReceive: case kStateTransmitPending: case kStateTransmitting: case kStateTransmitDone: break; } } #if OPENTHREAD_ENABLE_DIAG if (otPlatDiagModeGet()) { otPlatDiagRadioReceiveDone(mInstance, &mRxRadioFrame, OT_ERROR_NONE); } else #endif { otPlatRadioReceiveDone(mInstance, &mRxRadioFrame, OT_ERROR_NONE); } exit: return; } void RadioSpinel::UpdateFdSet(fd_set &aReadFdSet, fd_set &aWriteFdSet, int &aMaxFd, struct timeval &aTimeout) { int sockFd = mHdlcInterface.GetSocket(); FD_SET(sockFd, &aReadFdSet); if (aMaxFd < sockFd) { aMaxFd = sockFd; } if (mState == kStateTransmitPending) { FD_SET(sockFd, &aWriteFdSet); } if (mHdlcInterface.GetRxFrameBuffer().HasSavedFrame() || (mState == kStateTransmitDone)) { aTimeout.tv_sec = 0; aTimeout.tv_usec = 0; } } void RadioSpinel::Process(const fd_set &aReadFdSet, const fd_set &aWriteFdSet) { if (mHdlcInterface.GetRxFrameBuffer().HasSavedFrame()) { // Handle frames received and saved during `WaitResponse()` ProcessFrameQueue(); } if (FD_ISSET(mHdlcInterface.GetSocket(), &aReadFdSet)) { mHdlcInterface.Read(); ProcessFrameQueue(); } mHdlcInterface.GetRxFrameBuffer().ClearReadFrames(); if (mState == kStateTransmitDone) { mState = kStateReceive; #if OPENTHREAD_ENABLE_DIAG if (otPlatDiagModeGet()) { otPlatDiagRadioTransmitDone(mInstance, mTransmitFrame, mTxError); } else #endif { otPlatRadioTxDone(mInstance, mTransmitFrame, (mAckRadioFrame.mLength != 0) ? &mAckRadioFrame : NULL, mTxError); } } if (FD_ISSET(mHdlcInterface.GetSocket(), &aWriteFdSet)) { if (mState == kStateTransmitPending) { RadioTransmit(); } } } otError RadioSpinel::SetPromiscuous(bool aEnable) { otError error; uint8_t mode = (aEnable ? SPINEL_MAC_PROMISCUOUS_MODE_NETWORK : SPINEL_MAC_PROMISCUOUS_MODE_OFF); SuccessOrExit(error = Set(SPINEL_PROP_MAC_PROMISCUOUS_MODE, SPINEL_DATATYPE_UINT8_S, mode)); mIsPromiscuous = aEnable; exit: return error; } otError RadioSpinel::SetShortAddress(uint16_t aAddress) { otError error = OT_ERROR_NONE; VerifyOrExit(mShortAddress != aAddress); SuccessOrExit(error = sRadioSpinel.Set(SPINEL_PROP_MAC_15_4_SADDR, SPINEL_DATATYPE_UINT16_S, aAddress)); mShortAddress = aAddress; exit: return error; } otError RadioSpinel::GetIeeeEui64(uint8_t *aIeeeEui64) { return Get(SPINEL_PROP_HWADDR, SPINEL_DATATYPE_EUI64_S, aIeeeEui64); } otError RadioSpinel::SetExtendedAddress(const otExtAddress &aExtAddress) { otError error; SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_LADDR, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8)); mExtendedAddress = aExtAddress; exit: return error; } otError RadioSpinel::SetPanId(uint16_t aPanId) { otError error = OT_ERROR_NONE; VerifyOrExit(mPanId != aPanId); SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_PANID, SPINEL_DATATYPE_UINT16_S, aPanId)); mPanId = aPanId; exit: return error; } otError RadioSpinel::EnableSrcMatch(bool aEnable) { return Set(SPINEL_PROP_MAC_SRC_MATCH_ENABLED, SPINEL_DATATYPE_BOOL_S, aEnable); } otError RadioSpinel::AddSrcMatchShortEntry(const uint16_t aShortAddress) { return Insert(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, SPINEL_DATATYPE_UINT16_S, aShortAddress); } otError RadioSpinel::AddSrcMatchExtEntry(const otExtAddress &aExtAddress) { return Insert(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8); } otError RadioSpinel::ClearSrcMatchShortEntry(const uint16_t aShortAddress) { return Remove(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, SPINEL_DATATYPE_UINT16_S, aShortAddress); } otError RadioSpinel::ClearSrcMatchExtEntry(const otExtAddress &aExtAddress) { return Remove(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8); } otError RadioSpinel::ClearSrcMatchShortEntries(void) { return Set(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, NULL); } otError RadioSpinel::ClearSrcMatchExtEntries(void) { return Set(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, NULL); } otError RadioSpinel::GetTransmitPower(int8_t &aPower) { otError error = Get(SPINEL_PROP_PHY_TX_POWER, SPINEL_DATATYPE_INT8_S, &aPower); LogIfFail("Get transmit power failed", error); return error; } int8_t RadioSpinel::GetRssi(void) { int8_t rssi = OT_RADIO_RSSI_INVALID; otError error = Get(SPINEL_PROP_PHY_RSSI, SPINEL_DATATYPE_INT8_S, &rssi); LogIfFail("Get RSSI failed", error); return rssi; } otError RadioSpinel::SetTransmitPower(int8_t aPower) { otError error = Set(SPINEL_PROP_PHY_TX_POWER, SPINEL_DATATYPE_INT8_S, aPower); LogIfFail("Set transmit power failed", error); return error; } otError RadioSpinel::EnergyScan(uint8_t aScanChannel, uint16_t aScanDuration) { otError error; VerifyOrExit(mRadioCaps & OT_RADIO_CAPS_ENERGY_SCAN, error = OT_ERROR_NOT_CAPABLE); SuccessOrExit(error = Set(SPINEL_PROP_MAC_SCAN_MASK, SPINEL_DATATYPE_DATA_S, &aScanChannel, sizeof(uint8_t))); SuccessOrExit(error = Set(SPINEL_PROP_MAC_SCAN_PERIOD, SPINEL_DATATYPE_UINT16_S, aScanDuration)); SuccessOrExit(error = Set(SPINEL_PROP_MAC_SCAN_STATE, SPINEL_DATATYPE_UINT8_S, SPINEL_SCAN_STATE_ENERGY)); exit: return error; } otError RadioSpinel::Get(spinel_prop_key_t aKey, const char *aFormat, ...) { otError error; assert(mWaitingTid == 0); mPropertyFormat = aFormat; va_start(mPropertyArgs, aFormat); error = RequestV(true, SPINEL_CMD_PROP_VALUE_GET, aKey, NULL, mPropertyArgs); va_end(mPropertyArgs); mPropertyFormat = NULL; return error; } otError RadioSpinel::Set(spinel_prop_key_t aKey, const char *aFormat, ...) { otError error; assert(mWaitingTid == 0); mExpectedCommand = SPINEL_CMD_PROP_VALUE_IS; va_start(mPropertyArgs, aFormat); error = RequestV(true, SPINEL_CMD_PROP_VALUE_SET, aKey, aFormat, mPropertyArgs); va_end(mPropertyArgs); mExpectedCommand = SPINEL_CMD_NOOP; return error; } otError RadioSpinel::Insert(spinel_prop_key_t aKey, const char *aFormat, ...) { otError error; assert(mWaitingTid == 0); mExpectedCommand = SPINEL_CMD_PROP_VALUE_INSERTED; va_start(mPropertyArgs, aFormat); error = RequestV(true, SPINEL_CMD_PROP_VALUE_INSERT, aKey, aFormat, mPropertyArgs); va_end(mPropertyArgs); mExpectedCommand = SPINEL_CMD_NOOP; return error; } otError RadioSpinel::Remove(spinel_prop_key_t aKey, const char *aFormat, ...) { otError error; assert(mWaitingTid == 0); mExpectedCommand = SPINEL_CMD_PROP_VALUE_REMOVED; va_start(mPropertyArgs, aFormat); error = RequestV(true, SPINEL_CMD_PROP_VALUE_REMOVE, aKey, aFormat, mPropertyArgs); va_end(mPropertyArgs); mExpectedCommand = SPINEL_CMD_NOOP; return error; } otError RadioSpinel::WaitResponse(void) { uint64_t now = otSysGetTime(); uint64_t end = now + kMaxWaitTime * US_PER_MS; struct timeval timeout = {kMaxWaitTime / 1000, (kMaxWaitTime % 1000) * 1000}; do { #if OPENTHREAD_POSIX_VIRTUAL_TIME struct Event event; otSimSendSleepEvent(&timeout); otSimReceiveEvent(&event); switch (event.mEvent) { case OT_SIM_EVENT_RADIO_SPINEL_WRITE: mHdlcInterface.ProcessReadData(event.mData, event.mDataLength); break; case OT_SIM_EVENT_ALARM_FIRED: FreeTid(mWaitingTid); mWaitingTid = 0; ExitNow(mError = OT_ERROR_RESPONSE_TIMEOUT); break; default: assert(false); break; } #else // OPENTHREAD_POSIX_VIRTUAL_TIME int sockFd = mHdlcInterface.GetSocket(); fd_set read_fds; fd_set error_fds; int rval; FD_ZERO(&read_fds); FD_ZERO(&error_fds); FD_SET(sockFd, &read_fds); FD_SET(sockFd, &error_fds); rval = select(sockFd + 1, &read_fds, NULL, &error_fds, &timeout); if (rval > 0) { if (FD_ISSET(sockFd, &read_fds)) { mHdlcInterface.Read(); } else if (FD_ISSET(sockFd, &error_fds)) { fprintf(stderr, "NCP error\r\n"); exit(OT_EXIT_FAILURE); } else { assert(false); exit(OT_EXIT_FAILURE); } } else if (rval == 0) { FreeTid(mWaitingTid); mWaitingTid = 0; ExitNow(mError = OT_ERROR_RESPONSE_TIMEOUT); } else if (errno != EINTR) { perror("wait response"); exit(OT_EXIT_FAILURE); } #endif // OPENTHREAD_POSIX_VIRTUAL_TIME now = otSysGetTime(); if (end > now) { uint64_t remain = end - now; timeout.tv_sec = remain / US_PER_S; timeout.tv_usec = static_cast<suseconds_t>(remain % US_PER_S); } else { mWaitingTid = 0; mError = OT_ERROR_RESPONSE_TIMEOUT; } } while (mWaitingTid || !mIsReady); exit: LogIfFail("Error waiting response", mError); // This indicates end of waiting repsonse. mWaitingKey = SPINEL_PROP_LAST_STATUS; return mError; } spinel_tid_t RadioSpinel::GetNextTid(void) { spinel_tid_t tid = 0; if (((1 << mCmdNextTid) & mCmdTidsInUse) == 0) { tid = mCmdNextTid; mCmdNextTid = SPINEL_GET_NEXT_TID(mCmdNextTid); mCmdTidsInUse |= (1 << tid); } return tid; } /** * This method delivers the radio frame to transceiver. * * otPlatRadioTxStarted() is triggered immediately for now, which may be earlier than real started time. * */ void RadioSpinel::RadioTransmit(void) { otError error; assert(mTransmitFrame != NULL); otPlatRadioTxStarted(mInstance, mTransmitFrame); assert(mState == kStateTransmitPending); error = Request(true, SPINEL_CMD_PROP_VALUE_SET, SPINEL_PROP_STREAM_RAW, SPINEL_DATATYPE_DATA_WLEN_S // Frame data SPINEL_DATATYPE_UINT8_S // Channel SPINEL_DATATYPE_UINT8_S // MaxCsmaBackoffs SPINEL_DATATYPE_UINT8_S // MaxFrameRetries SPINEL_DATATYPE_BOOL_S, // CsmaCaEnabled mTransmitFrame->mPsdu, mTransmitFrame->mLength, mTransmitFrame->mChannel, mTransmitFrame->mInfo.mTxInfo.mMaxCsmaBackoffs, mTransmitFrame->mInfo.mTxInfo.mMaxFrameRetries, mTransmitFrame->mInfo.mTxInfo.mCsmaCaEnabled); if (error == OT_ERROR_NONE) { mState = kStateTransmitting; } else { mState = kStateReceive; #if OPENTHREAD_ENABLE_DIAG if (otPlatDiagModeGet()) { otPlatDiagRadioTransmitDone(mInstance, mTransmitFrame, error); } else #endif { otPlatRadioTxDone(mInstance, mTransmitFrame, NULL, error); } } } otError RadioSpinel::SendReset(void) { otError error = OT_ERROR_NONE; uint8_t buffer[kMaxSpinelFrame]; spinel_ssize_t packed; // Pack the header, command and key packed = spinel_datatype_pack(buffer, sizeof(buffer), "Ci", SPINEL_HEADER_FLAG | SPINEL_HEADER_IID_0, SPINEL_CMD_RESET); VerifyOrExit(packed > 0 && static_cast<size_t>(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); SuccessOrExit(error = mHdlcInterface.SendFrame(buffer, static_cast<uint16_t>(packed))); sleep(0); exit: return error; } otError RadioSpinel::SendCommand(uint32_t aCommand, spinel_prop_key_t aKey, spinel_tid_t tid, const char * aFormat, va_list args) { otError error = OT_ERROR_NONE; uint8_t buffer[kMaxSpinelFrame]; spinel_ssize_t packed; uint16_t offset; // Pack the header, command and key packed = spinel_datatype_pack(buffer, sizeof(buffer), "Cii", SPINEL_HEADER_FLAG | SPINEL_HEADER_IID_0 | tid, aCommand, aKey); VerifyOrExit(packed > 0 && static_cast<size_t>(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); offset = static_cast<uint16_t>(packed); // Pack the data (if any) if (aFormat) { packed = spinel_datatype_vpack(buffer + offset, sizeof(buffer) - offset, aFormat, args); VerifyOrExit(packed > 0 && static_cast<size_t>(packed + offset) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); offset += static_cast<uint16_t>(packed); } error = mHdlcInterface.SendFrame(buffer, offset); exit: return error; } otError RadioSpinel::RequestV(bool aWait, uint32_t command, spinel_prop_key_t aKey, const char *aFormat, va_list aArgs) { otError error = OT_ERROR_NONE; spinel_tid_t tid = (aWait ? GetNextTid() : 0); VerifyOrExit(!aWait || tid > 0, error = OT_ERROR_BUSY); error = SendCommand(command, aKey, tid, aFormat, aArgs); VerifyOrExit(error == OT_ERROR_NONE); if (aKey == SPINEL_PROP_STREAM_RAW) { // not allowed to send another frame before the last frame is done. assert(mTxRadioTid == 0); VerifyOrExit(mTxRadioTid == 0, error = OT_ERROR_BUSY); mTxRadioTid = tid; } else if (aWait) { mWaitingKey = aKey; mWaitingTid = tid; error = WaitResponse(); } exit: return error; } otError RadioSpinel::Request(bool aWait, uint32_t aCommand, spinel_prop_key_t aKey, const char *aFormat, ...) { va_list args; va_start(args, aFormat); otError status = RequestV(aWait, aCommand, aKey, aFormat, args); va_end(args); return status; } void RadioSpinel::HandleTransmitDone(uint32_t aCommand, spinel_prop_key_t aKey, const uint8_t * aBuffer, uint16_t aLength) { otError error = OT_ERROR_NONE; spinel_status_t status = SPINEL_STATUS_OK; spinel_ssize_t unpacked; VerifyOrExit(aCommand == SPINEL_CMD_PROP_VALUE_IS && aKey == SPINEL_PROP_LAST_STATUS, error = OT_ERROR_FAILED); unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UINT_PACKED_S, &status); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); aBuffer += unpacked; aLength -= static_cast<uint16_t>(unpacked); if (status == SPINEL_STATUS_OK) { bool framePending = false; unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_BOOL_S, &framePending); OT_UNUSED_VARIABLE(framePending); VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); aBuffer += unpacked; aLength -= static_cast<spinel_size_t>(unpacked); if (aLength > 0) { SuccessOrExit(error = ParseRadioFrame(mAckRadioFrame, aBuffer, aLength)); } else { mAckRadioFrame.mLength = 0; } } else { otLogWarnPlat("Spinel status: %d.", status); error = SpinelStatusToOtError(status); } exit: mState = kStateTransmitDone; mTxError = error; LogIfFail("Handle transmit done failed", error); } otError RadioSpinel::Transmit(otRadioFrame &aFrame) { otError error = OT_ERROR_INVALID_STATE; VerifyOrExit(mState == kStateReceive); mState = kStateTransmitPending; error = OT_ERROR_NONE; mTransmitFrame = &aFrame; exit: return error; } otError RadioSpinel::Receive(uint8_t aChannel) { otError error = OT_ERROR_NONE; VerifyOrExit(mState != kStateDisabled, error = OT_ERROR_INVALID_STATE); if (mChannel != aChannel) { error = Set(SPINEL_PROP_PHY_CHAN, SPINEL_DATATYPE_UINT8_S, aChannel); VerifyOrExit(error == OT_ERROR_NONE); mChannel = aChannel; } if (mState == kStateSleep) { error = Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, true); VerifyOrExit(error == OT_ERROR_NONE); } if (mTxRadioTid != 0) { FreeTid(mTxRadioTid); mTxRadioTid = 0; } mState = kStateReceive; exit: assert(error == OT_ERROR_NONE); return error; } otError RadioSpinel::Sleep(void) { otError error = OT_ERROR_NONE; switch (mState) { case kStateReceive: error = sRadioSpinel.Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, false); VerifyOrExit(error == OT_ERROR_NONE); mState = kStateSleep; break; case kStateSleep: break; default: error = OT_ERROR_INVALID_STATE; break; } exit: return error; } otError RadioSpinel::Enable(otInstance *aInstance) { otError error = OT_ERROR_NONE; if (!otPlatRadioIsEnabled(mInstance)) { mInstance = aInstance; SuccessOrExit(error = Set(SPINEL_PROP_PHY_ENABLED, SPINEL_DATATYPE_BOOL_S, true)); SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_PANID, SPINEL_DATATYPE_UINT16_S, mPanId)); SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_SADDR, SPINEL_DATATYPE_UINT16_S, mShortAddress)); error = Get(SPINEL_PROP_PHY_RX_SENSITIVITY, SPINEL_DATATYPE_INT8_S, &mRxSensitivity); VerifyOrExit(error == OT_ERROR_NONE); mState = kStateSleep; } exit: assert(error == OT_ERROR_NONE); return error; } otError RadioSpinel::Disable(void) { otError error = OT_ERROR_NONE; if (otPlatRadioIsEnabled(mInstance)) { mInstance = NULL; error = sRadioSpinel.Set(SPINEL_PROP_PHY_ENABLED, SPINEL_DATATYPE_BOOL_S, false); VerifyOrExit(error == OT_ERROR_NONE); mState = kStateDisabled; } exit: return error; } #if OPENTHREAD_ENABLE_DIAG otError RadioSpinel::PlatDiagProcess(const char *aString, char *aOutput, size_t aOutputMaxLen) { otError error; mDiagOutput = aOutput; mDiagOutputMaxLen = aOutputMaxLen; error = Set(SPINEL_PROP_NEST_STREAM_MFG, SPINEL_DATATYPE_UTF8_S, aString); mDiagOutput = NULL; mDiagOutputMaxLen = 0; return error; } #endif } // namespace PosixApp } // namespace ot void otPlatRadioGetIeeeEui64(otInstance *aInstance, uint8_t *aIeeeEui64) { SuccessOrDie(sRadioSpinel.GetIeeeEui64(aIeeeEui64)); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioSetPanId(otInstance *aInstance, uint16_t panid) { SuccessOrDie(sRadioSpinel.SetPanId(panid)); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioSetExtendedAddress(otInstance *aInstance, const otExtAddress *aAddress) { otExtAddress addr; for (size_t i = 0; i < sizeof(addr); i++) { addr.m8[i] = aAddress->m8[sizeof(addr) - 1 - i]; } SuccessOrDie(sRadioSpinel.SetExtendedAddress(addr)); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioSetShortAddress(otInstance *aInstance, uint16_t aAddress) { SuccessOrDie(sRadioSpinel.SetShortAddress(aAddress)); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioSetPromiscuous(otInstance *aInstance, bool aEnable) { SuccessOrDie(sRadioSpinel.SetPromiscuous(aEnable)); OT_UNUSED_VARIABLE(aInstance); } void platformRadioInit(const char *aRadioFile, const char *aRadioConfig) { sRadioSpinel.Init(aRadioFile, aRadioConfig); } void platformRadioDeinit(void) { sRadioSpinel.Deinit(); } bool otPlatRadioIsEnabled(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.IsEnabled(); } otError otPlatRadioEnable(otInstance *aInstance) { return sRadioSpinel.Enable(aInstance); } otError otPlatRadioDisable(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.Disable(); } otError otPlatRadioSleep(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.Sleep(); } otError otPlatRadioReceive(otInstance *aInstance, uint8_t aChannel) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.Receive(aChannel); } otError otPlatRadioTransmit(otInstance *aInstance, otRadioFrame *aFrame) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.Transmit(*aFrame); } otRadioFrame *otPlatRadioGetTransmitBuffer(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return &sRadioSpinel.GetTransmitFrame(); } int8_t otPlatRadioGetRssi(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.GetRssi(); } otRadioCaps otPlatRadioGetCaps(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.GetRadioCaps(); } const char *otPlatRadioGetVersionString(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.GetVersion(); } bool otPlatRadioGetPromiscuous(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.IsPromiscuous(); } void platformRadioUpdateFdSet(fd_set *aReadFdSet, fd_set *aWriteFdSet, int *aMaxFd, struct timeval *aTimeout) { sRadioSpinel.UpdateFdSet(*aReadFdSet, *aWriteFdSet, *aMaxFd, *aTimeout); } void platformRadioProcess(otInstance *aInstance, const fd_set *aReadFdSet, const fd_set *aWriteFdSet) { sRadioSpinel.Process(*aReadFdSet, *aWriteFdSet); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioEnableSrcMatch(otInstance *aInstance, bool aEnable) { SuccessOrDie(sRadioSpinel.EnableSrcMatch(aEnable)); OT_UNUSED_VARIABLE(aInstance); } otError otPlatRadioAddSrcMatchShortEntry(otInstance *aInstance, uint16_t aShortAddress) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.AddSrcMatchShortEntry(aShortAddress); } otError otPlatRadioAddSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { otExtAddress addr; for (size_t i = 0; i < sizeof(addr); i++) { addr.m8[i] = aExtAddress->m8[sizeof(addr) - 1 - i]; } OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.AddSrcMatchExtEntry(addr); } otError otPlatRadioClearSrcMatchShortEntry(otInstance *aInstance, uint16_t aShortAddress) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.ClearSrcMatchShortEntry(aShortAddress); } otError otPlatRadioClearSrcMatchExtEntry(otInstance *aInstance, const otExtAddress *aExtAddress) { otExtAddress addr; for (size_t i = 0; i < sizeof(addr); i++) { addr.m8[i] = aExtAddress->m8[sizeof(addr) - 1 - i]; } OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.ClearSrcMatchExtEntry(addr); } void otPlatRadioClearSrcMatchShortEntries(otInstance *aInstance) { SuccessOrDie(sRadioSpinel.ClearSrcMatchShortEntries()); OT_UNUSED_VARIABLE(aInstance); } void otPlatRadioClearSrcMatchExtEntries(otInstance *aInstance) { SuccessOrDie(sRadioSpinel.ClearSrcMatchExtEntries()); OT_UNUSED_VARIABLE(aInstance); } otError otPlatRadioEnergyScan(otInstance *aInstance, uint8_t aScanChannel, uint16_t aScanDuration) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.EnergyScan(aScanChannel, aScanDuration); } otError otPlatRadioGetTransmitPower(otInstance *aInstance, int8_t *aPower) { assert(aPower != NULL); OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.GetTransmitPower(*aPower); } otError otPlatRadioSetTransmitPower(otInstance *aInstance, int8_t aPower) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.SetTransmitPower(aPower); } int8_t otPlatRadioGetReceiveSensitivity(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); return sRadioSpinel.GetReceiveSensitivity(); } #if OPENTHREAD_POSIX_VIRTUAL_TIME void ot::PosixApp::RadioSpinel::Process(const Event &aEvent) { if (mHdlcInterface.GetRxFrameBuffer().HasSavedFrame()) { ProcessFrameQueue(); } // The current event can be other event types if (aEvent.mEvent == OT_SIM_EVENT_RADIO_SPINEL_WRITE) { mHdlcInterface.ProcessReadData(aEvent.mData, aEvent.mDataLength); ProcessFrameQueue(); } mHdlcInterface.GetRxFrameBuffer().ClearReadFrames(); if (mState == kStateTransmitDone) { mState = kStateReceive; #if OPENTHREAD_ENABLE_DIAG if (otPlatDiagModeGet()) { otPlatDiagRadioTransmitDone(mInstance, mTransmitFrame, mTxError); } else #endif { otPlatRadioTxDone(mInstance, mTransmitFrame, (mAckRadioFrame.mLength != 0) ? &mAckRadioFrame : NULL, mTxError); } } if (mState == kStateTransmitPending) { RadioTransmit(); } } void ot::PosixApp::RadioSpinel::Update(struct timeval &aTimeout) { // Prevent sleep event when transmitting if (mState == kStateTransmitPending) { aTimeout.tv_sec = 0; aTimeout.tv_usec = 0; } } void otSimRadioSpinelUpdate(struct timeval *aTimeout) { sRadioSpinel.Update(*aTimeout); } void otSimRadioSpinelProcess(otInstance *aInstance, const struct Event *aEvent) { sRadioSpinel.Process(*aEvent); OT_UNUSED_VARIABLE(aInstance); } #endif // OPENTHREAD_POSIX_VIRTUAL_TIME #if OPENTHREAD_ENABLE_DIAG void otPlatDiagProcess(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen) { // deliver the platform specific diags commands to radio only ncp. OT_UNUSED_VARIABLE(aInstance); char cmd[OPENTHREAD_CONFIG_DIAG_CMD_LINE_BUFFER_SIZE] = {'\0'}; char *cur = cmd; char *end = cmd + sizeof(cmd); for (int index = 0; index < argc; index++) { cur += snprintf(cur, static_cast<size_t>(end - cur), "%s ", argv[index]); } sRadioSpinel.PlatDiagProcess(cmd, aOutput, aOutputMaxLen); } void otPlatDiagModeSet(bool aMode) { SuccessOrExit(sRadioSpinel.PlatDiagProcess(aMode ? "start" : "stop", NULL, 0)); sRadioSpinel.SetDiagEnabled(aMode); exit: return; } bool otPlatDiagModeGet(void) { return sRadioSpinel.IsDiagEnabled(); } void otPlatDiagTxPowerSet(int8_t aTxPower) { char cmd[OPENTHREAD_CONFIG_DIAG_CMD_LINE_BUFFER_SIZE]; snprintf(cmd, sizeof(cmd), "power %d", aTxPower); SuccessOrExit(sRadioSpinel.PlatDiagProcess(cmd, NULL, 0)); exit: return; } void otPlatDiagChannelSet(uint8_t aChannel) { char cmd[OPENTHREAD_CONFIG_DIAG_CMD_LINE_BUFFER_SIZE]; snprintf(cmd, sizeof(cmd), "channel %d", aChannel); SuccessOrExit(sRadioSpinel.PlatDiagProcess(cmd, NULL, 0)); exit: return; } void otPlatDiagRadioReceived(otInstance *aInstance, otRadioFrame *aFrame, otError aError) { OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aFrame); OT_UNUSED_VARIABLE(aError); } void otPlatDiagAlarmCallback(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); } #endif // OPENTHREAD_ENABLE_DIAG
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" // Needed here to get TARGET_ARCH_XXX. #include "vm/flow_graph_compiler.h" #include "vm/bit_vector.h" #include "vm/cha.h" #include "vm/compiler.h" #include "vm/dart_entry.h" #include "vm/debugger.h" #include "vm/deopt_instructions.h" #include "vm/exceptions.h" #include "vm/flags.h" #include "vm/flow_graph_allocator.h" #include "vm/il_printer.h" #include "vm/intrinsifier.h" #include "vm/locations.h" #include "vm/log.h" #include "vm/longjump.h" #include "vm/object_store.h" #include "vm/parser.h" #include "vm/raw_object.h" #include "vm/stack_frame.h" #include "vm/stub_code.h" #include "vm/symbols.h" #include "vm/timeline.h" namespace dart { DEFINE_FLAG(bool, enable_simd_inline, true, "Enable inlining of SIMD related method calls."); DEFINE_FLAG(int, min_optimization_counter_threshold, 5000, "The minimum invocation count for a function."); DEFINE_FLAG(int, optimization_counter_scale, 2000, "The scale of invocation count, by size of the function."); DEFINE_FLAG(bool, source_lines, false, "Emit source line as assembly comment."); DEFINE_FLAG(bool, trace_inlining_intervals, false, "Inlining interval diagnostics"); DEFINE_FLAG(bool, use_megamorphic_stub, true, "Out of line megamorphic lookup"); DECLARE_FLAG(bool, code_comments); DECLARE_FLAG(charp, deoptimize_filter); DECLARE_FLAG(bool, intrinsify); DECLARE_FLAG(bool, propagate_ic_data); DECLARE_FLAG(int, regexp_optimization_counter_threshold); DECLARE_FLAG(int, reoptimization_counter_threshold); DECLARE_FLAG(int, stacktrace_every); DECLARE_FLAG(charp, stacktrace_filter); DECLARE_FLAG(bool, trace_compiler); DECLARE_FLAG(int, inlining_hotness); DECLARE_FLAG(int, inlining_size_threshold); DECLARE_FLAG(int, inlining_callee_size_threshold); DECLARE_FLAG(int, inline_getters_setters_smaller_than); DECLARE_FLAG(int, inlining_depth_threshold); DECLARE_FLAG(int, inlining_caller_size_threshold); DECLARE_FLAG(int, inlining_constant_arguments_max_size_threshold); DECLARE_FLAG(int, inlining_constant_arguments_min_size_threshold); static void PrecompilationModeHandler(bool value) { if (value) { #if defined(TARGET_ARCH_IA32) FATAL("Precompilation not supported on IA32"); #endif // Flags affecting compilation only: // There is no counter feedback in precompilation, so ignore the counter // when making inlining decisions. FLAG_inlining_hotness = 0; // Use smaller thresholds in precompilation as we are compiling everything // with the optimizing compiler instead of only hot functions. FLAG_inlining_size_threshold = 5; FLAG_inline_getters_setters_smaller_than = 5; FLAG_inlining_callee_size_threshold = 20; FLAG_inlining_depth_threshold = 2; FLAG_inlining_caller_size_threshold = 1000; FLAG_inlining_constant_arguments_max_size_threshold = 100; FLAG_inlining_constant_arguments_min_size_threshold = 30; FLAG_allow_absolute_addresses = false; FLAG_always_megamorphic_calls = true; FLAG_collect_dynamic_function_names = true; FLAG_fields_may_be_reset = true; FLAG_ic_range_profiling = false; FLAG_interpret_irregexp = true; FLAG_lazy_dispatchers = false; FLAG_link_natives_lazily = true; FLAG_optimization_counter_threshold = -1; FLAG_polymorphic_with_deopt = false; FLAG_precompiled_mode = true; FLAG_reorder_basic_blocks = false; FLAG_use_field_guards = false; FLAG_use_cha_deopt = false; #if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME) // Set flags affecting runtime accordingly for dart_noopt. FLAG_background_compilation = false; FLAG_collect_code = false; FLAG_support_debugger = false; FLAG_deoptimize_alot = false; // Used in some tests. FLAG_deoptimize_every = 0; // Used in some tests. FLAG_enable_mirrors = false; FLAG_load_deferred_eagerly = true; FLAG_print_stop_message = false; FLAG_use_osr = false; #endif } } DEFINE_FLAG_HANDLER(PrecompilationModeHandler, precompilation, "Precompilation mode"); #ifdef DART_PRECOMPILED_RUNTIME COMPILE_ASSERT(!FLAG_background_compilation); COMPILE_ASSERT(!FLAG_collect_code); COMPILE_ASSERT(!FLAG_deoptimize_alot); // Used in some tests. COMPILE_ASSERT(!FLAG_enable_mirrors); COMPILE_ASSERT(FLAG_precompiled_runtime); COMPILE_ASSERT(!FLAG_print_stop_message); COMPILE_ASSERT(!FLAG_use_osr); COMPILE_ASSERT(FLAG_deoptimize_every == 0); // Used in some tests. COMPILE_ASSERT(FLAG_load_deferred_eagerly); #endif // DART_PRECOMPILED_RUNTIME // Assign locations to incoming arguments, i.e., values pushed above spill slots // with PushArgument. Recursively allocates from outermost to innermost // environment. void CompilerDeoptInfo::AllocateIncomingParametersRecursive( Environment* env, intptr_t* stack_height) { if (env == NULL) return; AllocateIncomingParametersRecursive(env->outer(), stack_height); for (Environment::ShallowIterator it(env); !it.Done(); it.Advance()) { if (it.CurrentLocation().IsInvalid() && it.CurrentValue()->definition()->IsPushArgument()) { it.SetCurrentLocation(Location::StackSlot((*stack_height)++)); } } } void CompilerDeoptInfo::EmitMaterializations(Environment* env, DeoptInfoBuilder* builder) { for (Environment::DeepIterator it(env); !it.Done(); it.Advance()) { if (it.CurrentLocation().IsInvalid()) { MaterializeObjectInstr* mat = it.CurrentValue()->definition()->AsMaterializeObject(); ASSERT(mat != NULL); builder->AddMaterialization(mat); } } } FlowGraphCompiler::FlowGraphCompiler( Assembler* assembler, FlowGraph* flow_graph, const ParsedFunction& parsed_function, bool is_optimizing, const GrowableArray<const Function*>& inline_id_to_function, const GrowableArray<TokenPosition>& inline_id_to_token_pos, const GrowableArray<intptr_t>& caller_inline_id) : thread_(Thread::Current()), zone_(Thread::Current()->zone()), assembler_(assembler), parsed_function_(parsed_function), flow_graph_(*flow_graph), block_order_(*flow_graph->CodegenBlockOrder(is_optimizing)), current_block_(NULL), exception_handlers_list_(NULL), pc_descriptors_list_(NULL), stackmap_table_builder_(NULL), code_source_map_builder_(NULL), saved_code_size_(0), block_info_(block_order_.length()), deopt_infos_(), static_calls_target_table_(), is_optimizing_(is_optimizing), may_reoptimize_(false), intrinsic_mode_(false), double_class_(Class::ZoneHandle( isolate()->object_store()->double_class())), mint_class_(Class::ZoneHandle( isolate()->object_store()->mint_class())), float32x4_class_(Class::ZoneHandle( isolate()->object_store()->float32x4_class())), float64x2_class_(Class::ZoneHandle( isolate()->object_store()->float64x2_class())), int32x4_class_(Class::ZoneHandle( isolate()->object_store()->int32x4_class())), list_class_(Class::ZoneHandle( Library::Handle(Library::CoreLibrary()). LookupClass(Symbols::List()))), parallel_move_resolver_(this), pending_deoptimization_env_(NULL), lazy_deopt_pc_offset_(Code::kInvalidPc), deopt_id_to_ic_data_(NULL), edge_counters_array_(Array::ZoneHandle()), inlined_code_intervals_(Array::ZoneHandle(Object::empty_array().raw())), inline_id_to_function_(inline_id_to_function), inline_id_to_token_pos_(inline_id_to_token_pos), caller_inline_id_(caller_inline_id) { ASSERT(flow_graph->parsed_function().function().raw() == parsed_function.function().raw()); if (!is_optimizing) { const intptr_t len = thread()->deopt_id(); deopt_id_to_ic_data_ = new(zone()) ZoneGrowableArray<const ICData*>(len); deopt_id_to_ic_data_->SetLength(len); for (intptr_t i = 0; i < len; i++) { (*deopt_id_to_ic_data_)[i] = NULL; } // TODO(fschneider): Abstract iteration into ICDataArrayIterator. const Array& old_saved_ic_data = Array::Handle(zone(), flow_graph->function().ic_data_array()); const intptr_t saved_len = old_saved_ic_data.IsNull() ? 0 : old_saved_ic_data.Length(); for (intptr_t i = 1; i < saved_len; i++) { ICData& ic_data = ICData::ZoneHandle(zone()); ic_data ^= old_saved_ic_data.At(i); (*deopt_id_to_ic_data_)[ic_data.deopt_id()] = &ic_data; } } ASSERT(assembler != NULL); ASSERT(!list_class_.IsNull()); } bool FlowGraphCompiler::IsUnboxedField(const Field& field) { bool valid_class = (SupportsUnboxedDoubles() && (field.guarded_cid() == kDoubleCid)) || (SupportsUnboxedSimd128() && (field.guarded_cid() == kFloat32x4Cid)) || (SupportsUnboxedSimd128() && (field.guarded_cid() == kFloat64x2Cid)); return field.is_unboxing_candidate() && !field.is_final() && !field.is_nullable() && valid_class; } bool FlowGraphCompiler::IsPotentialUnboxedField(const Field& field) { return field.is_unboxing_candidate() && (FlowGraphCompiler::IsUnboxedField(field) || (!field.is_final() && (field.guarded_cid() == kIllegalCid))); } void FlowGraphCompiler::InitCompiler() { #ifndef PRODUCT TimelineDurationScope tds(thread(), Timeline::GetCompilerStream(), "InitCompiler"); #endif // !PRODUCT pc_descriptors_list_ = new(zone()) DescriptorList(64); exception_handlers_list_ = new(zone()) ExceptionHandlerList(); block_info_.Clear(); // Conservative detection of leaf routines used to remove the stack check // on function entry. bool is_leaf = is_optimizing() && !flow_graph().IsCompiledForOsr(); // Initialize block info and search optimized (non-OSR) code for calls // indicating a non-leaf routine and calls without IC data indicating // possible reoptimization. for (int i = 0; i < block_order_.length(); ++i) { block_info_.Add(new(zone()) BlockInfo()); if (is_optimizing() && !flow_graph().IsCompiledForOsr()) { BlockEntryInstr* entry = block_order_[i]; for (ForwardInstructionIterator it(entry); !it.Done(); it.Advance()) { Instruction* current = it.Current(); if (current->IsBranch()) { current = current->AsBranch()->comparison(); } // In optimized code, ICData is always set in the instructions. const ICData* ic_data = NULL; if (current->IsInstanceCall()) { ic_data = current->AsInstanceCall()->ic_data(); } if ((ic_data != NULL) && (ic_data->NumberOfUsedChecks() == 0)) { may_reoptimize_ = true; } if (is_leaf && !current->IsCheckStackOverflow() && !current->IsParallelMove()) { // Note that we do not care if the code contains instructions that // can deoptimize. LocationSummary* locs = current->locs(); if ((locs != NULL) && locs->can_call()) { is_leaf = false; } } } } } if (is_leaf) { // Remove the stack overflow check at function entry. Instruction* first = flow_graph_.graph_entry()->normal_entry()->next(); if (first->IsCheckStackOverflow()) first->RemoveFromGraph(); } if (!is_optimizing()) { // Initialize edge counter array. const intptr_t num_counters = flow_graph_.preorder().length(); const Array& edge_counters = Array::Handle(Array::New(num_counters, Heap::kOld)); const Smi& zero_smi = Smi::Handle(Smi::New(0)); for (intptr_t i = 0; i < num_counters; ++i) { edge_counters.SetAt(i, zero_smi); } edge_counters_array_ = edge_counters.raw(); } } bool FlowGraphCompiler::CanOptimize() { return FLAG_optimization_counter_threshold >= 0; } bool FlowGraphCompiler::CanOptimizeFunction() const { return CanOptimize() && !parsed_function().function().HasBreakpoint(); } bool FlowGraphCompiler::CanOSRFunction() const { return FLAG_use_osr & CanOptimizeFunction() && !is_optimizing(); } bool FlowGraphCompiler::ForceSlowPathForStackOverflow() const { if (FLAG_stacktrace_every > 0 || FLAG_deoptimize_every > 0) { return true; } if (FLAG_stacktrace_filter != NULL && strstr(parsed_function().function().ToFullyQualifiedCString(), FLAG_stacktrace_filter) != NULL) { return true; } if (is_optimizing() && FLAG_deoptimize_filter != NULL && strstr(parsed_function().function().ToFullyQualifiedCString(), FLAG_deoptimize_filter) != NULL) { return true; } return false; } static bool IsEmptyBlock(BlockEntryInstr* block) { return !block->IsCatchBlockEntry() && !block->HasNonRedundantParallelMove() && block->next()->IsGoto() && !block->next()->AsGoto()->HasNonRedundantParallelMove() && !block->IsIndirectEntry(); } void FlowGraphCompiler::CompactBlock(BlockEntryInstr* block) { BlockInfo* block_info = block_info_[block->postorder_number()]; // Break out of cycles in the control flow graph. if (block_info->is_marked()) { return; } block_info->mark(); if (IsEmptyBlock(block)) { // For empty blocks, record a corresponding nonempty target as their // jump label. BlockEntryInstr* target = block->next()->AsGoto()->successor(); CompactBlock(target); block_info->set_jump_label(GetJumpLabel(target)); } } void FlowGraphCompiler::CompactBlocks() { // This algorithm does not garbage collect blocks in place, but merely // records forwarding label information. In this way it avoids having to // change join and target entries. Label* nonempty_label = NULL; for (intptr_t i = block_order().length() - 1; i >= 1; --i) { BlockEntryInstr* block = block_order()[i]; // Unoptimized code must emit all possible deoptimization points. if (is_optimizing()) { CompactBlock(block); } // For nonempty blocks, record the next nonempty block in the block // order. Since no code is emitted for empty blocks, control flow is // eligible to fall through to the next nonempty one. if (!WasCompacted(block)) { BlockInfo* block_info = block_info_[block->postorder_number()]; block_info->set_next_nonempty_label(nonempty_label); nonempty_label = GetJumpLabel(block); } } ASSERT(block_order()[0]->IsGraphEntry()); BlockInfo* block_info = block_info_[block_order()[0]->postorder_number()]; block_info->set_next_nonempty_label(nonempty_label); } void FlowGraphCompiler::EmitInstructionPrologue(Instruction* instr) { if (!is_optimizing()) { if (instr->CanBecomeDeoptimizationTarget() && !instr->IsGoto()) { // Instructions that can be deoptimization targets need to record kDeopt // PcDescriptor corresponding to their deopt id. GotoInstr records its // own so that it can control the placement. AddCurrentDescriptor(RawPcDescriptors::kDeopt, instr->deopt_id(), instr->token_pos()); } AllocateRegistersLocally(instr); } else if (instr->MayThrow() && (CurrentTryIndex() != CatchClauseNode::kInvalidTryIndex)) { // Optimized try-block: Sync locals to fixed stack locations. EmitTrySync(instr, CurrentTryIndex()); } } void FlowGraphCompiler::EmitSourceLine(Instruction* instr) { if (!instr->token_pos().IsReal() || (instr->env() == NULL)) { return; } const Script& script = Script::Handle(zone(), instr->env()->function().script()); intptr_t line_nr; intptr_t column_nr; script.GetTokenLocation(instr->token_pos(), &line_nr, &column_nr); const String& line = String::Handle(zone(), script.GetLine(line_nr)); assembler()->Comment("Line %" Pd " in '%s':\n %s", line_nr, instr->env()->function().ToFullyQualifiedCString(), line.ToCString()); } static void LoopInfoComment( Assembler* assembler, const BlockEntryInstr& block, const ZoneGrowableArray<BlockEntryInstr*>& loop_headers) { if (Assembler::EmittingComments()) { for (intptr_t loop_id = 0; loop_id < loop_headers.length(); ++loop_id) { for (BitVector::Iterator loop_it(loop_headers[loop_id]->loop_info()); !loop_it.Done(); loop_it.Advance()) { if (loop_it.Current() == block.preorder_number()) { assembler->Comment(" Loop %" Pd "", loop_id); } } } } } // We collect intervals while generating code. struct IntervalStruct { // 'start' is the pc-offsets where the inlined code started. // 'pos' is the token position where the inlined call occured. intptr_t start; TokenPosition pos; intptr_t inlining_id; IntervalStruct(intptr_t s, TokenPosition tp, intptr_t id) : start(s), pos(tp), inlining_id(id) {} void Dump() { THR_Print("start: 0x%" Px " iid: %" Pd " pos: %s", start, inlining_id, pos.ToCString()); } }; void FlowGraphCompiler::VisitBlocks() { CompactBlocks(); const ZoneGrowableArray<BlockEntryInstr*>* loop_headers = NULL; if (Assembler::EmittingComments()) { // 'loop_headers' were cleared, recompute. loop_headers = flow_graph().ComputeLoops(); ASSERT(loop_headers != NULL); } // For collecting intervals of inlined code. GrowableArray<IntervalStruct> intervals; intptr_t prev_offset = 0; intptr_t prev_inlining_id = 0; TokenPosition prev_inlining_pos = parsed_function_.function().token_pos(); intptr_t max_inlining_id = 0; for (intptr_t i = 0; i < block_order().length(); ++i) { // Compile the block entry. BlockEntryInstr* entry = block_order()[i]; assembler()->Comment("B%" Pd "", entry->block_id()); set_current_block(entry); if (WasCompacted(entry)) { continue; } #if defined(DEBUG) if (!is_optimizing()) { FrameStateClear(); } #endif LoopInfoComment(assembler(), *entry, *loop_headers); entry->set_offset(assembler()->CodeSize()); BeginCodeSourceRange(); entry->EmitNativeCode(this); EndCodeSourceRange(entry->token_pos()); // Compile all successors until an exit, branch, or a block entry. for (ForwardInstructionIterator it(entry); !it.Done(); it.Advance()) { Instruction* instr = it.Current(); // Compose intervals. if (instr->has_inlining_id() && is_optimizing()) { if (prev_inlining_id != instr->inlining_id()) { intervals.Add( IntervalStruct(prev_offset, prev_inlining_pos, prev_inlining_id)); prev_offset = assembler()->CodeSize(); prev_inlining_id = instr->inlining_id(); if (prev_inlining_id < inline_id_to_token_pos_.length()) { prev_inlining_pos = inline_id_to_token_pos_[prev_inlining_id]; } else { // We will add this token position later when generating the // profile. prev_inlining_pos = TokenPosition::kNoSource; } if (prev_inlining_id > max_inlining_id) { max_inlining_id = prev_inlining_id; } } } if (FLAG_code_comments || FLAG_disassemble || FLAG_disassemble_optimized) { if (FLAG_source_lines) { EmitSourceLine(instr); } EmitComment(instr); } if (instr->IsParallelMove()) { parallel_move_resolver_.EmitNativeCode(instr->AsParallelMove()); } else { BeginCodeSourceRange(); EmitInstructionPrologue(instr); ASSERT(pending_deoptimization_env_ == NULL); pending_deoptimization_env_ = instr->env(); instr->EmitNativeCode(this); pending_deoptimization_env_ = NULL; EmitInstructionEpilogue(instr); EndCodeSourceRange(instr->token_pos()); } #if defined(DEBUG) if (!is_optimizing()) { FrameStateUpdateWith(instr); } #endif } #if defined(DEBUG) ASSERT(is_optimizing() || FrameStateIsSafeToCall()); #endif } if (is_optimizing()) { LogBlock lb; intervals.Add( IntervalStruct(prev_offset, prev_inlining_pos, prev_inlining_id)); inlined_code_intervals_ = Array::New(intervals.length() * Code::kInlIntNumEntries, Heap::kOld); Smi& start_h = Smi::Handle(); Smi& caller_inline_id = Smi::Handle(); Smi& inline_id = Smi::Handle(); for (intptr_t i = 0; i < intervals.length(); i++) { if (FLAG_trace_inlining_intervals && is_optimizing()) { const Function& function = *inline_id_to_function_.At(intervals[i].inlining_id); intervals[i].Dump(); THR_Print(" parent iid %" Pd " %s\n", caller_inline_id_[intervals[i].inlining_id], function.ToQualifiedCString()); } const intptr_t id = intervals[i].inlining_id; start_h = Smi::New(intervals[i].start); inline_id = Smi::New(id); caller_inline_id = Smi::New(caller_inline_id_[intervals[i].inlining_id]); const intptr_t p = i * Code::kInlIntNumEntries; inlined_code_intervals_.SetAt(p + Code::kInlIntStart, start_h); inlined_code_intervals_.SetAt(p + Code::kInlIntInliningId, inline_id); } } set_current_block(NULL); if (FLAG_trace_inlining_intervals && is_optimizing()) { LogBlock lb; THR_Print("Intervals:\n"); for (intptr_t cc = 0; cc < caller_inline_id_.length(); cc++) { THR_Print(" iid: %" Pd " caller iid: %" Pd "\n", cc, caller_inline_id_[cc]); } Smi& temp = Smi::Handle(); for (intptr_t i = 0; i < inlined_code_intervals_.Length(); i += Code::kInlIntNumEntries) { temp ^= inlined_code_intervals_.At(i + Code::kInlIntStart); ASSERT(!temp.IsNull()); THR_Print("% " Pd " start: 0x%" Px " ", i, temp.Value()); temp ^= inlined_code_intervals_.At(i + Code::kInlIntInliningId); THR_Print("iid: %" Pd " ", temp.Value()); } } } void FlowGraphCompiler::Bailout(const char* reason) { const Function& function = parsed_function_.function(); Report::MessageF(Report::kBailout, Script::Handle(function.script()), function.token_pos(), Report::AtLocation, "FlowGraphCompiler Bailout: %s %s", String::Handle(function.name()).ToCString(), reason); UNREACHABLE(); } void FlowGraphCompiler::EmitTrySync(Instruction* instr, intptr_t try_index) { ASSERT(is_optimizing()); Environment* env = instr->env()->Outermost(); CatchBlockEntryInstr* catch_block = flow_graph().graph_entry()->GetCatchEntry(try_index); const GrowableArray<Definition*>* idefs = catch_block->initial_definitions(); // Construct a ParallelMove instruction for parameters and locals. Skip the // special locals exception_var and stacktrace_var since they will be filled // when an exception is thrown. Constant locations are known to be the same // at all instructions that may throw, and do not need to be materialized. // Parameters first. intptr_t i = 0; const intptr_t num_non_copied_params = flow_graph().num_non_copied_params(); ParallelMoveInstr* move_instr = new(zone()) ParallelMoveInstr(); for (; i < num_non_copied_params; ++i) { // Don't sync captured parameters. They are not in the environment. if (flow_graph().captured_parameters()->Contains(i)) continue; if ((*idefs)[i]->IsConstant()) continue; // Common constants Location src = env->LocationAt(i); intptr_t dest_index = i - num_non_copied_params; Location dest = Location::StackSlot(dest_index); move_instr->AddMove(dest, src); } // Process locals. Skip exception_var and stacktrace_var. intptr_t local_base = kFirstLocalSlotFromFp + num_non_copied_params; intptr_t ex_idx = local_base - catch_block->exception_var().index(); intptr_t st_idx = local_base - catch_block->stacktrace_var().index(); for (; i < flow_graph().variable_count(); ++i) { // Don't sync captured parameters. They are not in the environment. if (flow_graph().captured_parameters()->Contains(i)) continue; if (i == ex_idx || i == st_idx) continue; if ((*idefs)[i]->IsConstant()) continue; Location src = env->LocationAt(i); ASSERT(!src.IsFpuRegister()); ASSERT(!src.IsDoubleStackSlot()); intptr_t dest_index = i - num_non_copied_params; Location dest = Location::StackSlot(dest_index); move_instr->AddMove(dest, src); // Update safepoint bitmap to indicate that the target location // now contains a pointer. instr->locs()->SetStackBit(dest_index); } parallel_move_resolver()->EmitNativeCode(move_instr); } intptr_t FlowGraphCompiler::StackSize() const { if (is_optimizing_) { return flow_graph_.graph_entry()->spill_slot_count(); } else { return parsed_function_.num_stack_locals() + parsed_function_.num_copied_params(); } } Label* FlowGraphCompiler::GetJumpLabel( BlockEntryInstr* block_entry) const { const intptr_t block_index = block_entry->postorder_number(); return block_info_[block_index]->jump_label(); } bool FlowGraphCompiler::WasCompacted( BlockEntryInstr* block_entry) const { const intptr_t block_index = block_entry->postorder_number(); return block_info_[block_index]->WasCompacted(); } Label* FlowGraphCompiler::NextNonEmptyLabel() const { const intptr_t current_index = current_block()->postorder_number(); return block_info_[current_index]->next_nonempty_label(); } bool FlowGraphCompiler::CanFallThroughTo(BlockEntryInstr* block_entry) const { return NextNonEmptyLabel() == GetJumpLabel(block_entry); } BranchLabels FlowGraphCompiler::CreateBranchLabels(BranchInstr* branch) const { Label* true_label = GetJumpLabel(branch->true_successor()); Label* false_label = GetJumpLabel(branch->false_successor()); Label* fall_through = NextNonEmptyLabel(); BranchLabels result = { true_label, false_label, fall_through }; return result; } void FlowGraphCompiler::AddSlowPathCode(SlowPathCode* code) { slow_path_code_.Add(code); } void FlowGraphCompiler::GenerateDeferredCode() { for (intptr_t i = 0; i < slow_path_code_.length(); i++) { BeginCodeSourceRange(); slow_path_code_[i]->GenerateCode(this); EndCodeSourceRange(TokenPosition::kDeferredSlowPath); } for (intptr_t i = 0; i < deopt_infos_.length(); i++) { BeginCodeSourceRange(); deopt_infos_[i]->GenerateCode(this, i); EndCodeSourceRange(TokenPosition::kDeferredDeoptInfo); } } void FlowGraphCompiler::AddExceptionHandler(intptr_t try_index, intptr_t outer_try_index, intptr_t pc_offset, const Array& handler_types, bool needs_stacktrace) { exception_handlers_list_->AddHandler(try_index, outer_try_index, pc_offset, handler_types, needs_stacktrace); } void FlowGraphCompiler::SetNeedsStacktrace(intptr_t try_index) { exception_handlers_list_->SetNeedsStacktrace(try_index); } // Uses current pc position and try-index. void FlowGraphCompiler::AddCurrentDescriptor(RawPcDescriptors::Kind kind, intptr_t deopt_id, TokenPosition token_pos) { // When running with optimizations disabled, don't emit deopt-descriptors. if (!CanOptimize() && (kind == RawPcDescriptors::kDeopt)) return; pc_descriptors_list()->AddDescriptor(kind, assembler()->CodeSize(), deopt_id, token_pos, CurrentTryIndex()); } void FlowGraphCompiler::AddStaticCallTarget(const Function& func) { ASSERT(func.IsZoneHandle()); static_calls_target_table_.Add( new(zone()) StaticCallsStruct(assembler()->CodeSize(), &func, NULL)); } void FlowGraphCompiler::AddStubCallTarget(const Code& code) { ASSERT(code.IsZoneHandle()); static_calls_target_table_.Add( new(zone()) StaticCallsStruct(assembler()->CodeSize(), NULL, &code)); } void FlowGraphCompiler::AddDeoptIndexAtCall(intptr_t deopt_id, TokenPosition token_pos) { ASSERT(is_optimizing()); ASSERT(!intrinsic_mode()); CompilerDeoptInfo* info = new(zone()) CompilerDeoptInfo(deopt_id, ICData::kDeoptAtCall, 0, // No flags. pending_deoptimization_env_); info->set_pc_offset(assembler()->CodeSize()); deopt_infos_.Add(info); } // This function must be in sync with FlowGraphCompiler::SaveLiveRegisters // and FlowGraphCompiler::SlowPathEnvironmentFor. // See StackFrame::VisitObjectPointers for the details of how stack map is // interpreted. void FlowGraphCompiler::RecordSafepoint(LocationSummary* locs, intptr_t slow_path_argument_count) { if (is_optimizing() || locs->live_registers()->HasUntaggedValues()) { const intptr_t spill_area_size = is_optimizing() ? flow_graph_.graph_entry()->spill_slot_count() : 0; RegisterSet* registers = locs->live_registers(); ASSERT(registers != NULL); const intptr_t kFpuRegisterSpillFactor = kFpuRegisterSize / kWordSize; const intptr_t live_registers_size = registers->CpuRegisterCount() + (registers->FpuRegisterCount() * kFpuRegisterSpillFactor); BitmapBuilder* bitmap = locs->stack_bitmap(); // An instruction may have two safepoints in deferred code. The // call to RecordSafepoint has the side-effect of appending the live // registers to the bitmap. This is why the second call to RecordSafepoint // with the same instruction (and same location summary) sees a bitmap that // is larger that StackSize(). It will never be larger than StackSize() + // live_registers_size. ASSERT(bitmap->Length() <= (spill_area_size + live_registers_size)); // The first safepoint will grow the bitmap to be the size of // spill_area_size but the second safepoint will truncate the bitmap and // append the live registers to it again. The bitmap produced by both calls // will be the same. bitmap->SetLength(spill_area_size); // Mark the bits in the stack map in the same order we push registers in // slow path code (see FlowGraphCompiler::SaveLiveRegisters). // // Slow path code can have registers at the safepoint. if (!locs->always_calls()) { RegisterSet* regs = locs->live_registers(); if (regs->FpuRegisterCount() > 0) { // Denote FPU registers with 0 bits in the stackmap. Based on the // assumption that there are normally few live FPU registers, this // encoding is simpler and roughly as compact as storing a separate // count of FPU registers. // // FPU registers have the highest register number at the highest // address (i.e., first in the stackmap). for (intptr_t i = kNumberOfFpuRegisters - 1; i >= 0; --i) { FpuRegister reg = static_cast<FpuRegister>(i); if (regs->ContainsFpuRegister(reg)) { for (intptr_t j = 0; j < kFpuRegisterSpillFactor; ++j) { bitmap->Set(bitmap->Length(), false); } } } } // General purpose registers have the highest register number at the // highest address (i.e., first in the stackmap). for (intptr_t i = kNumberOfCpuRegisters - 1; i >= 0; --i) { Register reg = static_cast<Register>(i); if (locs->live_registers()->ContainsRegister(reg)) { bitmap->Set(bitmap->Length(), locs->live_registers()->IsTagged(reg)); } } } // Arguments pushed on top of live registers in the slow path are tagged. for (intptr_t i = 0; i < slow_path_argument_count; ++i) { bitmap->Set(bitmap->Length(), true); } // The slow path area Outside the spill area contains are live registers // and pushed arguments for calls inside the slow path. intptr_t slow_path_bit_count = bitmap->Length() - spill_area_size; stackmap_table_builder()->AddEntry(assembler()->CodeSize(), bitmap, slow_path_bit_count); } } // This function must be kept in sync with: // // FlowGraphCompiler::RecordSafepoint // FlowGraphCompiler::SaveLiveRegisters // MaterializeObjectInstr::RemapRegisters // Environment* FlowGraphCompiler::SlowPathEnvironmentFor( Instruction* instruction) { if (instruction->env() == NULL) { ASSERT(!is_optimizing()); return NULL; } Environment* env = instruction->env()->DeepCopy(zone()); // 1. Iterate the registers in the order they will be spilled to compute // the slots they will be spilled to. intptr_t next_slot = StackSize() + env->CountArgsPushed(); RegisterSet* regs = instruction->locs()->live_registers(); intptr_t fpu_reg_slots[kNumberOfFpuRegisters]; intptr_t cpu_reg_slots[kNumberOfCpuRegisters]; const intptr_t kFpuRegisterSpillFactor = kFpuRegisterSize / kWordSize; // FPU registers are spilled first from highest to lowest register number. for (intptr_t i = kNumberOfFpuRegisters - 1; i >= 0; --i) { FpuRegister reg = static_cast<FpuRegister>(i); if (regs->ContainsFpuRegister(reg)) { // We use the lowest address (thus highest index) to identify a // multi-word spill slot. next_slot += kFpuRegisterSpillFactor; fpu_reg_slots[i] = (next_slot - 1); } else { fpu_reg_slots[i] = -1; } } // General purpose registers are spilled from highest to lowest register // number. for (intptr_t i = kNumberOfCpuRegisters - 1; i >= 0; --i) { Register reg = static_cast<Register>(i); if (regs->ContainsRegister(reg)) { cpu_reg_slots[i] = next_slot++; } else { cpu_reg_slots[i] = -1; } } // 2. Iterate the environment and replace register locations with the // corresponding spill slot locations. for (Environment::DeepIterator it(env); !it.Done(); it.Advance()) { Location loc = it.CurrentLocation(); Value* value = it.CurrentValue(); it.SetCurrentLocation(loc.RemapForSlowPath( value->definition(), cpu_reg_slots, fpu_reg_slots)); } return env; } Label* FlowGraphCompiler::AddDeoptStub(intptr_t deopt_id, ICData::DeoptReasonId reason, uint32_t flags) { if (intrinsic_mode()) { return &intrinsic_slow_path_label_; } // No deoptimization allowed when 'FLAG_precompiled_mode' is set. if (FLAG_precompiled_mode) { if (FLAG_trace_compiler) { THR_Print( "Retrying compilation %s, suppressing inlining of deopt_id:%" Pd "\n", parsed_function_.function().ToFullyQualifiedCString(), deopt_id); } ASSERT(deopt_id != 0); // longjmp must return non-zero value. Thread::Current()->long_jump_base()->Jump( deopt_id, Object::speculative_inlining_error()); } ASSERT(is_optimizing_); CompilerDeoptInfoWithStub* stub = new(zone()) CompilerDeoptInfoWithStub(deopt_id, reason, flags, pending_deoptimization_env_); deopt_infos_.Add(stub); return stub->entry_label(); } void FlowGraphCompiler::FinalizeExceptionHandlers(const Code& code) { ASSERT(exception_handlers_list_ != NULL); const ExceptionHandlers& handlers = ExceptionHandlers::Handle( exception_handlers_list_->FinalizeExceptionHandlers(code.EntryPoint())); code.set_exception_handlers(handlers); if (FLAG_compiler_stats) { Thread* thread = Thread::Current(); INC_STAT(thread, total_code_size, ExceptionHandlers::InstanceSize(handlers.num_entries())); INC_STAT(thread, total_code_size, handlers.num_entries() * sizeof(uword)); } } void FlowGraphCompiler::FinalizePcDescriptors(const Code& code) { ASSERT(pc_descriptors_list_ != NULL); const PcDescriptors& descriptors = PcDescriptors::Handle( pc_descriptors_list_->FinalizePcDescriptors(code.EntryPoint())); if (!is_optimizing_) descriptors.Verify(parsed_function_.function()); code.set_pc_descriptors(descriptors); code.set_lazy_deopt_pc_offset(lazy_deopt_pc_offset_); } RawArray* FlowGraphCompiler::CreateDeoptInfo(Assembler* assembler) { // No deopt information if we precompile (no deoptimization allowed). if (FLAG_precompiled_mode) { return Array::empty_array().raw(); } // For functions with optional arguments, all incoming arguments are copied // to spill slots. The deoptimization environment does not track them. const Function& function = parsed_function().function(); const intptr_t incoming_arg_count = function.HasOptionalParameters() ? 0 : function.num_fixed_parameters(); DeoptInfoBuilder builder(zone(), incoming_arg_count, assembler); intptr_t deopt_info_table_size = DeoptTable::SizeFor(deopt_infos_.length()); if (deopt_info_table_size == 0) { return Object::empty_array().raw(); } else { const Array& array = Array::Handle(Array::New(deopt_info_table_size, Heap::kOld)); Smi& offset = Smi::Handle(); TypedData& info = TypedData::Handle(); Smi& reason_and_flags = Smi::Handle(); for (intptr_t i = 0; i < deopt_infos_.length(); i++) { offset = Smi::New(deopt_infos_[i]->pc_offset()); info = deopt_infos_[i]->CreateDeoptInfo(this, &builder, array); reason_and_flags = DeoptTable::EncodeReasonAndFlags( deopt_infos_[i]->reason(), deopt_infos_[i]->flags()); DeoptTable::SetEntry(array, i, offset, info, reason_and_flags); } return array.raw(); } } void FlowGraphCompiler::FinalizeStackmaps(const Code& code) { if (stackmap_table_builder_ == NULL) { code.set_stackmaps(Object::null_array()); } else { // Finalize the stack map array and add it to the code object. code.set_stackmaps( Array::Handle(stackmap_table_builder_->FinalizeStackmaps(code))); } } void FlowGraphCompiler::FinalizeVarDescriptors(const Code& code) { if (code.is_optimized()) { // Optimized code does not need variable descriptors. They are // only stored in the unoptimized version. code.set_var_descriptors(Object::empty_var_descriptors()); return; } LocalVarDescriptors& var_descs = LocalVarDescriptors::Handle(); if (parsed_function().node_sequence() == NULL) { // Eager local var descriptors computation for Irregexp function as it is // complicated to factor out. // TODO(srdjan): Consider canonicalizing and reusing the local var // descriptor for IrregexpFunction. ASSERT(flow_graph().IsIrregexpFunction()); var_descs = LocalVarDescriptors::New(1); RawLocalVarDescriptors::VarInfo info; info.set_kind(RawLocalVarDescriptors::kSavedCurrentContext); info.scope_id = 0; info.begin_pos = TokenPosition::kMinSource; info.end_pos = TokenPosition::kMinSource; info.set_index(parsed_function().current_context_var()->index()); var_descs.SetVar(0, Symbols::CurrentContextVar(), &info); } code.set_var_descriptors(var_descs); } void FlowGraphCompiler::FinalizeStaticCallTargetsTable(const Code& code) { ASSERT(code.static_calls_target_table() == Array::null()); const Array& targets = Array::Handle(zone(), Array::New( (static_calls_target_table_.length() * Code::kSCallTableEntryLength), Heap::kOld)); Smi& smi_offset = Smi::Handle(zone()); for (intptr_t i = 0; i < static_calls_target_table_.length(); i++) { const intptr_t target_ix = Code::kSCallTableEntryLength * i; smi_offset = Smi::New(static_calls_target_table_[i]->offset); targets.SetAt(target_ix + Code::kSCallTableOffsetEntry, smi_offset); if (static_calls_target_table_[i]->function != NULL) { targets.SetAt(target_ix + Code::kSCallTableFunctionEntry, *static_calls_target_table_[i]->function); } if (static_calls_target_table_[i]->code != NULL) { targets.SetAt(target_ix + Code::kSCallTableCodeEntry, *static_calls_target_table_[i]->code); } } code.set_static_calls_target_table(targets); INC_STAT(Thread::Current(), total_code_size, targets.Length() * sizeof(uword)); } // Returns 'true' if regular code generation should be skipped. bool FlowGraphCompiler::TryIntrinsify() { // Intrinsification skips arguments checks, therefore disable if in checked // mode. if (FLAG_intrinsify && !isolate()->type_checks()) { if (parsed_function().function().kind() == RawFunction::kImplicitGetter) { // An implicit getter must have a specific AST structure. const SequenceNode& sequence_node = *parsed_function().node_sequence(); ASSERT(sequence_node.length() == 1); ASSERT(sequence_node.NodeAt(0)->IsReturnNode()); const ReturnNode& return_node = *sequence_node.NodeAt(0)->AsReturnNode(); ASSERT(return_node.value()->IsLoadInstanceFieldNode()); const LoadInstanceFieldNode& load_node = *return_node.value()->AsLoadInstanceFieldNode(); // Only intrinsify getter if the field cannot contain a mutable double. // Reading from a mutable double box requires allocating a fresh double. if (load_node.field().guarded_cid() == kDynamicCid) { GenerateInlinedGetter(load_node.field().Offset()); return !FLAG_use_field_guards; } return false; } if (parsed_function().function().kind() == RawFunction::kImplicitSetter) { // An implicit setter must have a specific AST structure. // Sequence node has one store node and one return NULL node. const SequenceNode& sequence_node = *parsed_function().node_sequence(); ASSERT(sequence_node.length() == 2); ASSERT(sequence_node.NodeAt(0)->IsStoreInstanceFieldNode()); ASSERT(sequence_node.NodeAt(1)->IsReturnNode()); const StoreInstanceFieldNode& store_node = *sequence_node.NodeAt(0)->AsStoreInstanceFieldNode(); if (store_node.field().guarded_cid() == kDynamicCid) { GenerateInlinedSetter(store_node.field().Offset()); return !FLAG_use_field_guards; } } } EnterIntrinsicMode(); Intrinsifier::Intrinsify(parsed_function(), this); ExitIntrinsicMode(); // "Deoptimization" from intrinsic continues here. All deoptimization // branches from intrinsic code redirect to here where the slow-path // (normal function body) starts. // This means that there must not be any side-effects in intrinsic code // before any deoptimization point. ASSERT(!intrinsic_slow_path_label_.IsBound()); assembler()->Bind(&intrinsic_slow_path_label_); return false; } void FlowGraphCompiler::GenerateInstanceCall( intptr_t deopt_id, TokenPosition token_pos, intptr_t argument_count, LocationSummary* locs, const ICData& ic_data_in) { const ICData& ic_data = ICData::ZoneHandle(ic_data_in.Original()); if (FLAG_precompiled_mode) { EmitSwitchableInstanceCall(ic_data, argument_count, deopt_id, token_pos, locs); return; } if (FLAG_always_megamorphic_calls) { EmitMegamorphicInstanceCall(ic_data, argument_count, deopt_id, token_pos, locs, CatchClauseNode::kInvalidTryIndex); return; } ASSERT(!ic_data.IsNull()); if (is_optimizing() && (ic_data.NumberOfUsedChecks() == 0)) { // Emit IC call that will count and thus may need reoptimization at // function entry. ASSERT(may_reoptimize() || flow_graph().IsCompiledForOsr()); switch (ic_data.NumArgsTested()) { case 1: EmitOptimizedInstanceCall( *StubCode::OneArgOptimizedCheckInlineCache_entry(), ic_data, argument_count, deopt_id, token_pos, locs); return; case 2: EmitOptimizedInstanceCall( *StubCode::TwoArgsOptimizedCheckInlineCache_entry(), ic_data, argument_count, deopt_id, token_pos, locs); return; default: UNIMPLEMENTED(); } return; } if (is_optimizing()) { EmitMegamorphicInstanceCall(ic_data, argument_count, deopt_id, token_pos, locs, CatchClauseNode::kInvalidTryIndex); return; } switch (ic_data.NumArgsTested()) { case 1: EmitInstanceCall( *StubCode::OneArgCheckInlineCache_entry(), ic_data, argument_count, deopt_id, token_pos, locs); break; case 2: EmitInstanceCall( *StubCode::TwoArgsCheckInlineCache_entry(), ic_data, argument_count, deopt_id, token_pos, locs); break; default: UNIMPLEMENTED(); } } void FlowGraphCompiler::GenerateStaticCall(intptr_t deopt_id, TokenPosition token_pos, const Function& function, intptr_t argument_count, const Array& argument_names, LocationSummary* locs, const ICData& ic_data_in) { const ICData& ic_data = ICData::ZoneHandle(ic_data_in.Original()); const Array& arguments_descriptor = Array::ZoneHandle( ic_data.IsNull() ? ArgumentsDescriptor::New(argument_count, argument_names) : ic_data.arguments_descriptor()); if (is_optimizing()) { EmitOptimizedStaticCall(function, arguments_descriptor, argument_count, deopt_id, token_pos, locs); } else { ICData& call_ic_data = ICData::ZoneHandle(ic_data.raw()); if (call_ic_data.IsNull()) { const intptr_t kNumArgsChecked = 0; call_ic_data = GetOrAddStaticCallICData(deopt_id, function, arguments_descriptor, kNumArgsChecked)->raw(); } EmitUnoptimizedStaticCall(argument_count, deopt_id, token_pos, locs, call_ic_data); } } void FlowGraphCompiler::GenerateNumberTypeCheck(Register kClassIdReg, const AbstractType& type, Label* is_instance_lbl, Label* is_not_instance_lbl) { assembler()->Comment("NumberTypeCheck"); GrowableArray<intptr_t> args; if (type.IsNumberType()) { args.Add(kDoubleCid); args.Add(kMintCid); args.Add(kBigintCid); } else if (type.IsIntType()) { args.Add(kMintCid); args.Add(kBigintCid); } else if (type.IsDoubleType()) { args.Add(kDoubleCid); } CheckClassIds(kClassIdReg, args, is_instance_lbl, is_not_instance_lbl); } void FlowGraphCompiler::GenerateStringTypeCheck(Register kClassIdReg, Label* is_instance_lbl, Label* is_not_instance_lbl) { assembler()->Comment("StringTypeCheck"); GrowableArray<intptr_t> args; args.Add(kOneByteStringCid); args.Add(kTwoByteStringCid); args.Add(kExternalOneByteStringCid); args.Add(kExternalTwoByteStringCid); CheckClassIds(kClassIdReg, args, is_instance_lbl, is_not_instance_lbl); } void FlowGraphCompiler::GenerateListTypeCheck(Register kClassIdReg, Label* is_instance_lbl) { assembler()->Comment("ListTypeCheck"); Label unknown; GrowableArray<intptr_t> args; args.Add(kArrayCid); args.Add(kGrowableObjectArrayCid); args.Add(kImmutableArrayCid); CheckClassIds(kClassIdReg, args, is_instance_lbl, &unknown); assembler()->Bind(&unknown); } void FlowGraphCompiler::EmitComment(Instruction* instr) { if (!FLAG_support_il_printer || !FLAG_support_disassembler) { return; } #ifndef PRODUCT char buffer[256]; BufferFormatter f(buffer, sizeof(buffer)); instr->PrintTo(&f); assembler()->Comment("%s", buffer); #endif } bool FlowGraphCompiler::NeedsEdgeCounter(TargetEntryInstr* block) { // Only emit an edge counter if there is not goto at the end of the block, // except for the entry block. return (FLAG_reorder_basic_blocks && (!block->last_instruction()->IsGoto() || (block == flow_graph().graph_entry()->normal_entry()))); } // Allocate a register that is not explicitly blocked. static Register AllocateFreeRegister(bool* blocked_registers) { for (intptr_t regno = 0; regno < kNumberOfCpuRegisters; regno++) { if (!blocked_registers[regno]) { blocked_registers[regno] = true; return static_cast<Register>(regno); } } UNREACHABLE(); return kNoRegister; } static uword RegMaskBit(Register reg) { return ((reg) != kNoRegister) ? (1 << (reg)) : 0; } void FlowGraphCompiler::AllocateRegistersLocally(Instruction* instr) { ASSERT(!is_optimizing()); instr->InitializeLocationSummary(zone(), false); // Not optimizing. LocationSummary* locs = instr->locs(); bool blocked_registers[kNumberOfCpuRegisters]; // Block all registers globally reserved by the assembler, etc and mark // the rest as free. for (intptr_t i = 0; i < kNumberOfCpuRegisters; i++) { blocked_registers[i] = (kDartAvailableCpuRegs & (1 << i)) == 0; } // Mark all fixed input, temp and output registers as used. for (intptr_t i = 0; i < locs->input_count(); i++) { Location loc = locs->in(i); if (loc.IsRegister()) { // Check that a register is not specified twice in the summary. ASSERT(!blocked_registers[loc.reg()]); blocked_registers[loc.reg()] = true; } } for (intptr_t i = 0; i < locs->temp_count(); i++) { Location loc = locs->temp(i); if (loc.IsRegister()) { // Check that a register is not specified twice in the summary. ASSERT(!blocked_registers[loc.reg()]); blocked_registers[loc.reg()] = true; } } if (locs->out(0).IsRegister()) { // Fixed output registers are allowed to overlap with // temps and inputs. blocked_registers[locs->out(0).reg()] = true; } // Allocate all unallocated input locations. const bool should_pop = !instr->IsPushArgument() && !instr->IsPushTemp(); for (intptr_t i = locs->input_count() - 1; i >= 0; i--) { Location loc = locs->in(i); Register reg = kNoRegister; if (loc.IsRegister()) { reg = loc.reg(); } else if (loc.IsUnallocated() || loc.IsConstant()) { ASSERT(loc.IsConstant() || ((loc.policy() == Location::kRequiresRegister) || (loc.policy() == Location::kWritableRegister) || (loc.policy() == Location::kAny))); reg = AllocateFreeRegister(blocked_registers); locs->set_in(i, Location::RegisterLocation(reg)); } ASSERT(reg != kNoRegister); // Inputs are consumed from the simulated frame. In case of a call argument // we leave it until the call instruction. if (should_pop) { assembler()->PopRegister(reg); } } // Allocate all unallocated temp locations. for (intptr_t i = 0; i < locs->temp_count(); i++) { Location loc = locs->temp(i); if (loc.IsUnallocated()) { ASSERT(loc.policy() == Location::kRequiresRegister); loc = Location::RegisterLocation( AllocateFreeRegister(blocked_registers)); locs->set_temp(i, loc); } } Location result_location = locs->out(0); if (result_location.IsUnallocated()) { switch (result_location.policy()) { case Location::kAny: case Location::kPrefersRegister: case Location::kRequiresRegister: case Location::kWritableRegister: result_location = Location::RegisterLocation( AllocateFreeRegister(blocked_registers)); break; case Location::kSameAsFirstInput: result_location = locs->in(0); break; case Location::kRequiresFpuRegister: UNREACHABLE(); break; } locs->set_out(0, result_location); } } ParallelMoveResolver::ParallelMoveResolver(FlowGraphCompiler* compiler) : compiler_(compiler), moves_(32) {} void ParallelMoveResolver::EmitNativeCode(ParallelMoveInstr* parallel_move) { ASSERT(moves_.is_empty()); // Build up a worklist of moves. BuildInitialMoveList(parallel_move); for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& move = *moves_[i]; // Skip constants to perform them last. They don't block other moves // and skipping such moves with register destinations keeps those // registers free for the whole algorithm. if (!move.IsEliminated() && !move.src().IsConstant()) PerformMove(i); } // Perform the moves with constant sources. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& move = *moves_[i]; if (!move.IsEliminated()) { ASSERT(move.src().IsConstant()); compiler_->BeginCodeSourceRange(); EmitMove(i); compiler_->EndCodeSourceRange(TokenPosition::kParallelMove); } } moves_.Clear(); } void ParallelMoveResolver::BuildInitialMoveList( ParallelMoveInstr* parallel_move) { // Perform a linear sweep of the moves to add them to the initial list of // moves to perform, ignoring any move that is redundant (the source is // the same as the destination, the destination is ignored and // unallocated, or the move was already eliminated). for (int i = 0; i < parallel_move->NumMoves(); i++) { MoveOperands* move = parallel_move->MoveOperandsAt(i); if (!move->IsRedundant()) moves_.Add(move); } } void ParallelMoveResolver::PerformMove(int index) { // Each call to this function performs a move and deletes it from the move // graph. We first recursively perform any move blocking this one. We // mark a move as "pending" on entry to PerformMove in order to detect // cycles in the move graph. We use operand swaps to resolve cycles, // which means that a call to PerformMove could change any source operand // in the move graph. ASSERT(!moves_[index]->IsPending()); ASSERT(!moves_[index]->IsRedundant()); // Clear this move's destination to indicate a pending move. The actual // destination is saved in a stack-allocated local. Recursion may allow // multiple moves to be pending. ASSERT(!moves_[index]->src().IsInvalid()); Location destination = moves_[index]->MarkPending(); // Perform a depth-first traversal of the move graph to resolve // dependencies. Any unperformed, unpending move with a source the same // as this one's destination blocks this one so recursively perform all // such moves. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& other_move = *moves_[i]; if (other_move.Blocks(destination) && !other_move.IsPending()) { // Though PerformMove can change any source operand in the move graph, // this call cannot create a blocking move via a swap (this loop does // not miss any). Assume there is a non-blocking move with source A // and this move is blocked on source B and there is a swap of A and // B. Then A and B must be involved in the same cycle (or they would // not be swapped). Since this move's destination is B and there is // only a single incoming edge to an operand, this move must also be // involved in the same cycle. In that case, the blocking move will // be created but will be "pending" when we return from PerformMove. PerformMove(i); } } // We are about to resolve this move and don't need it marked as // pending, so restore its destination. moves_[index]->ClearPending(destination); // This move's source may have changed due to swaps to resolve cycles and // so it may now be the last move in the cycle. If so remove it. if (moves_[index]->src().Equals(destination)) { moves_[index]->Eliminate(); return; } // The move may be blocked on a (at most one) pending move, in which case // we have a cycle. Search for such a blocking move and perform a swap to // resolve it. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& other_move = *moves_[i]; if (other_move.Blocks(destination)) { ASSERT(other_move.IsPending()); compiler_->BeginCodeSourceRange(); EmitSwap(index); compiler_->EndCodeSourceRange(TokenPosition::kParallelMove); return; } } // This move is not blocked. compiler_->BeginCodeSourceRange(); EmitMove(index); compiler_->EndCodeSourceRange(TokenPosition::kParallelMove); } bool ParallelMoveResolver::IsScratchLocation(Location loc) { for (int i = 0; i < moves_.length(); ++i) { if (moves_[i]->Blocks(loc)) { return false; } } for (int i = 0; i < moves_.length(); ++i) { if (moves_[i]->dest().Equals(loc)) { return true; } } return false; } intptr_t ParallelMoveResolver::AllocateScratchRegister( Location::Kind kind, uword blocked_mask, intptr_t first_free_register, intptr_t last_free_register, bool* spilled) { COMPILE_ASSERT(static_cast<intptr_t>(sizeof(blocked_mask)) * kBitsPerByte >= kNumberOfFpuRegisters); COMPILE_ASSERT(static_cast<intptr_t>(sizeof(blocked_mask)) * kBitsPerByte >= kNumberOfCpuRegisters); intptr_t scratch = -1; for (intptr_t reg = first_free_register; reg <= last_free_register; reg++) { if ((((1 << reg) & blocked_mask) == 0) && IsScratchLocation(Location::MachineRegisterLocation(kind, reg))) { scratch = reg; break; } } if (scratch == -1) { *spilled = true; for (intptr_t reg = first_free_register; reg <= last_free_register; reg++) { if (((1 << reg) & blocked_mask) == 0) { scratch = reg; break; } } } else { *spilled = false; } return scratch; } ParallelMoveResolver::ScratchFpuRegisterScope::ScratchFpuRegisterScope( ParallelMoveResolver* resolver, FpuRegister blocked) : resolver_(resolver), reg_(kNoFpuRegister), spilled_(false) { COMPILE_ASSERT(FpuTMP != kNoFpuRegister); uword blocked_mask = ((blocked != kNoFpuRegister) ? 1 << blocked : 0) | 1 << FpuTMP; reg_ = static_cast<FpuRegister>( resolver_->AllocateScratchRegister(Location::kFpuRegister, blocked_mask, 0, kNumberOfFpuRegisters - 1, &spilled_)); if (spilled_) { resolver->SpillFpuScratch(reg_); } } ParallelMoveResolver::ScratchFpuRegisterScope::~ScratchFpuRegisterScope() { if (spilled_) { resolver_->RestoreFpuScratch(reg_); } } ParallelMoveResolver::ScratchRegisterScope::ScratchRegisterScope( ParallelMoveResolver* resolver, Register blocked) : resolver_(resolver), reg_(kNoRegister), spilled_(false) { uword blocked_mask = RegMaskBit(blocked) | kReservedCpuRegisters; if (resolver->compiler_->intrinsic_mode()) { // Block additional registers that must be preserved for intrinsics. blocked_mask |= RegMaskBit(ARGS_DESC_REG); #if !defined(TARGET_ARCH_IA32) // Need to preserve CODE_REG to be able to store the PC marker // and load the pool pointer. blocked_mask |= RegMaskBit(CODE_REG); #endif } reg_ = static_cast<Register>( resolver_->AllocateScratchRegister(Location::kRegister, blocked_mask, 0, kNumberOfCpuRegisters - 1, &spilled_)); if (spilled_) { resolver->SpillScratch(reg_); } } ParallelMoveResolver::ScratchRegisterScope::~ScratchRegisterScope() { if (spilled_) { resolver_->RestoreScratch(reg_); } } static int HighestCountFirst(const CidTarget* a, const CidTarget* b) { // Negative if 'a' should sort before 'b'. return b->count - a->count; } // Returns 'sorted' array in decreasing count order. // The expected number of elements to sort is less than 10. void FlowGraphCompiler::SortICDataByCount(const ICData& ic_data, GrowableArray<CidTarget>* sorted, bool drop_smi) { ASSERT(ic_data.NumArgsTested() == 1); const intptr_t len = ic_data.NumberOfChecks(); sorted->Clear(); for (int i = 0; i < len; i++) { intptr_t receiver_cid = ic_data.GetReceiverClassIdAt(i); if (drop_smi && (receiver_cid == kSmiCid)) continue; sorted->Add(CidTarget(receiver_cid, &Function::ZoneHandle(ic_data.GetTargetAt(i)), ic_data.GetCountAt(i))); } sorted->Sort(HighestCountFirst); } const ICData* FlowGraphCompiler::GetOrAddInstanceCallICData( intptr_t deopt_id, const String& target_name, const Array& arguments_descriptor, intptr_t num_args_tested) { if ((deopt_id_to_ic_data_ != NULL) && ((*deopt_id_to_ic_data_)[deopt_id] != NULL)) { const ICData* res = (*deopt_id_to_ic_data_)[deopt_id]; ASSERT(res->deopt_id() == deopt_id); ASSERT(res->target_name() == target_name.raw()); ASSERT(res->NumArgsTested() == num_args_tested); return res; } const ICData& ic_data = ICData::ZoneHandle(zone(), ICData::New( parsed_function().function(), target_name, arguments_descriptor, deopt_id, num_args_tested)); if (deopt_id_to_ic_data_ != NULL) { (*deopt_id_to_ic_data_)[deopt_id] = &ic_data; } return &ic_data; } const ICData* FlowGraphCompiler::GetOrAddStaticCallICData( intptr_t deopt_id, const Function& target, const Array& arguments_descriptor, intptr_t num_args_tested) { if ((deopt_id_to_ic_data_ != NULL) && ((*deopt_id_to_ic_data_)[deopt_id] != NULL)) { const ICData* res = (*deopt_id_to_ic_data_)[deopt_id]; ASSERT(res->deopt_id() == deopt_id); ASSERT(res->target_name() == target.name()); ASSERT(res->NumArgsTested() == num_args_tested); return res; } const ICData& ic_data = ICData::ZoneHandle(zone(), ICData::New( parsed_function().function(), String::Handle(zone(), target.name()), arguments_descriptor, deopt_id, num_args_tested)); ic_data.AddTarget(target); if (deopt_id_to_ic_data_ != NULL) { (*deopt_id_to_ic_data_)[deopt_id] = &ic_data; } return &ic_data; } intptr_t FlowGraphCompiler::GetOptimizationThreshold() const { intptr_t threshold; if (is_optimizing()) { threshold = FLAG_reoptimization_counter_threshold; } else if (parsed_function_.function().IsIrregexpFunction()) { threshold = FLAG_regexp_optimization_counter_threshold; } else { const intptr_t basic_blocks = flow_graph().preorder().length(); ASSERT(basic_blocks > 0); threshold = FLAG_optimization_counter_scale * basic_blocks + FLAG_min_optimization_counter_threshold; if (threshold > FLAG_optimization_counter_threshold) { threshold = FLAG_optimization_counter_threshold; } } return threshold; } const Class& FlowGraphCompiler::BoxClassFor(Representation rep) { switch (rep) { case kUnboxedDouble: return double_class(); case kUnboxedFloat32x4: return float32x4_class(); case kUnboxedFloat64x2: return float64x2_class(); case kUnboxedInt32x4: return int32x4_class(); case kUnboxedMint: return mint_class(); default: UNREACHABLE(); return Class::ZoneHandle(); } } RawArray* FlowGraphCompiler::InliningIdToFunction() const { if (inline_id_to_function_.length() == 0) { return Object::empty_array().raw(); } const Array& res = Array::Handle( Array::New(inline_id_to_function_.length(), Heap::kOld)); for (intptr_t i = 0; i < inline_id_to_function_.length(); i++) { res.SetAt(i, *inline_id_to_function_[i]); } return res.raw(); } RawArray* FlowGraphCompiler::InliningIdToTokenPos() const { if (inline_id_to_token_pos_.length() == 0) { return Object::empty_array().raw(); } const Array& res = Array::Handle(zone(), Array::New(inline_id_to_token_pos_.length(), Heap::kOld)); Smi& smi = Smi::Handle(zone()); for (intptr_t i = 0; i < inline_id_to_token_pos_.length(); i++) { smi = Smi::New(inline_id_to_token_pos_[i].value()); res.SetAt(i, smi); } return res.raw(); } RawArray* FlowGraphCompiler::CallerInliningIdMap() const { if (caller_inline_id_.length() == 0) { return Object::empty_array().raw(); } const Array& res = Array::Handle( Array::New(caller_inline_id_.length(), Heap::kOld)); Smi& smi = Smi::Handle(); for (intptr_t i = 0; i < caller_inline_id_.length(); i++) { smi = Smi::New(caller_inline_id_[i]); res.SetAt(i, smi); } return res.raw(); } void FlowGraphCompiler::BeginCodeSourceRange() { NOT_IN_PRODUCT( // Remember how many bytes of code we emitted so far. This function // is called before we call into an instruction's EmitNativeCode. saved_code_size_ = assembler()->CodeSize(); ); } bool FlowGraphCompiler::EndCodeSourceRange(TokenPosition token_pos) { NOT_IN_PRODUCT( // This function is called after each instructions' EmitNativeCode. if (saved_code_size_ < assembler()->CodeSize()) { // We emitted more code, now associate the emitted code chunk with // |token_pos|. code_source_map_builder()->AddEntry(saved_code_size_, token_pos); BeginCodeSourceRange(); return true; } ); return false; } void FlowGraphCompiler::EmitPolymorphicInstanceCall( const ICData& ic_data, intptr_t argument_count, const Array& argument_names, intptr_t deopt_id, TokenPosition token_pos, LocationSummary* locs) { if (FLAG_polymorphic_with_deopt) { Label* deopt = AddDeoptStub(deopt_id, ICData::kDeoptPolymorphicInstanceCallTestFail); Label ok; EmitTestAndCall(ic_data, argument_count, argument_names, deopt, // No cid match. &ok, // Found cid. deopt_id, token_pos, locs); assembler()->Bind(&ok); } else { // Instead of deoptimizing, do a megamorphic call when no matching // cid found. Label ok; MegamorphicSlowPath* slow_path = new MegamorphicSlowPath(ic_data, argument_count, deopt_id, token_pos, locs, CurrentTryIndex()); AddSlowPathCode(slow_path); EmitTestAndCall(ic_data, argument_count, argument_names, slow_path->entry_label(), // No cid match. &ok, // Found cid. deopt_id, token_pos, locs); assembler()->Bind(slow_path->exit_label()); assembler()->Bind(&ok); } } #if defined(DEBUG) void FlowGraphCompiler::FrameStateUpdateWith(Instruction* instr) { ASSERT(!is_optimizing()); switch (instr->tag()) { case Instruction::kPushArgument: case Instruction::kPushTemp: // Do nothing. break; case Instruction::kDropTemps: FrameStatePop(instr->locs()->input_count() + instr->AsDropTemps()->num_temps()); break; default: FrameStatePop(instr->locs()->input_count()); break; } ASSERT(!instr->locs()->can_call() || FrameStateIsSafeToCall()); FrameStatePop(instr->ArgumentCount()); Definition* defn = instr->AsDefinition(); if ((defn != NULL) && defn->HasTemp()) { FrameStatePush(defn); } } void FlowGraphCompiler::FrameStatePush(Definition* defn) { Representation rep = defn->representation(); if ((rep == kUnboxedDouble) || (rep == kUnboxedFloat64x2) || (rep == kUnboxedFloat32x4)) { // LoadField instruction lies about its representation in the unoptimized // code because Definition::representation() can't depend on the type of // compilation but MakeLocationSummary and EmitNativeCode can. ASSERT(defn->IsLoadField() && defn->AsLoadField()->IsUnboxedLoad()); ASSERT(defn->locs()->out(0).IsRegister()); rep = kTagged; } ASSERT(!is_optimizing()); ASSERT((rep == kTagged) || (rep == kUntagged)); ASSERT(rep != kUntagged || flow_graph_.IsIrregexpFunction()); frame_state_.Add(rep); } void FlowGraphCompiler::FrameStatePop(intptr_t count) { ASSERT(!is_optimizing()); frame_state_.TruncateTo(Utils::Maximum(static_cast<intptr_t>(0), frame_state_.length() - count)); } bool FlowGraphCompiler::FrameStateIsSafeToCall() { ASSERT(!is_optimizing()); for (intptr_t i = 0; i < frame_state_.length(); i++) { if (frame_state_[i] != kTagged) { return false; } } return true; } void FlowGraphCompiler::FrameStateClear() { ASSERT(!is_optimizing()); frame_state_.TruncateTo(0); } #endif } // namespace dart Fix fast intrinsics for getters and setters; previous strategy was too conservative. BUG= R=rmacnak@google.com Review URL: https://codereview.chromium.org/1812103002 . // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" // Needed here to get TARGET_ARCH_XXX. #include "vm/flow_graph_compiler.h" #include "vm/bit_vector.h" #include "vm/cha.h" #include "vm/compiler.h" #include "vm/dart_entry.h" #include "vm/debugger.h" #include "vm/deopt_instructions.h" #include "vm/exceptions.h" #include "vm/flags.h" #include "vm/flow_graph_allocator.h" #include "vm/il_printer.h" #include "vm/intrinsifier.h" #include "vm/locations.h" #include "vm/log.h" #include "vm/longjump.h" #include "vm/object_store.h" #include "vm/parser.h" #include "vm/raw_object.h" #include "vm/stack_frame.h" #include "vm/stub_code.h" #include "vm/symbols.h" #include "vm/timeline.h" namespace dart { DEFINE_FLAG(bool, enable_simd_inline, true, "Enable inlining of SIMD related method calls."); DEFINE_FLAG(int, min_optimization_counter_threshold, 5000, "The minimum invocation count for a function."); DEFINE_FLAG(int, optimization_counter_scale, 2000, "The scale of invocation count, by size of the function."); DEFINE_FLAG(bool, source_lines, false, "Emit source line as assembly comment."); DEFINE_FLAG(bool, trace_inlining_intervals, false, "Inlining interval diagnostics"); DEFINE_FLAG(bool, use_megamorphic_stub, true, "Out of line megamorphic lookup"); DECLARE_FLAG(bool, code_comments); DECLARE_FLAG(charp, deoptimize_filter); DECLARE_FLAG(bool, intrinsify); DECLARE_FLAG(bool, propagate_ic_data); DECLARE_FLAG(int, regexp_optimization_counter_threshold); DECLARE_FLAG(int, reoptimization_counter_threshold); DECLARE_FLAG(int, stacktrace_every); DECLARE_FLAG(charp, stacktrace_filter); DECLARE_FLAG(bool, trace_compiler); DECLARE_FLAG(int, inlining_hotness); DECLARE_FLAG(int, inlining_size_threshold); DECLARE_FLAG(int, inlining_callee_size_threshold); DECLARE_FLAG(int, inline_getters_setters_smaller_than); DECLARE_FLAG(int, inlining_depth_threshold); DECLARE_FLAG(int, inlining_caller_size_threshold); DECLARE_FLAG(int, inlining_constant_arguments_max_size_threshold); DECLARE_FLAG(int, inlining_constant_arguments_min_size_threshold); static void PrecompilationModeHandler(bool value) { if (value) { #if defined(TARGET_ARCH_IA32) FATAL("Precompilation not supported on IA32"); #endif // Flags affecting compilation only: // There is no counter feedback in precompilation, so ignore the counter // when making inlining decisions. FLAG_inlining_hotness = 0; // Use smaller thresholds in precompilation as we are compiling everything // with the optimizing compiler instead of only hot functions. FLAG_inlining_size_threshold = 5; FLAG_inline_getters_setters_smaller_than = 5; FLAG_inlining_callee_size_threshold = 20; FLAG_inlining_depth_threshold = 2; FLAG_inlining_caller_size_threshold = 1000; FLAG_inlining_constant_arguments_max_size_threshold = 100; FLAG_inlining_constant_arguments_min_size_threshold = 30; FLAG_allow_absolute_addresses = false; FLAG_always_megamorphic_calls = true; FLAG_collect_dynamic_function_names = true; FLAG_fields_may_be_reset = true; FLAG_ic_range_profiling = false; FLAG_interpret_irregexp = true; FLAG_lazy_dispatchers = false; FLAG_link_natives_lazily = true; FLAG_optimization_counter_threshold = -1; FLAG_polymorphic_with_deopt = false; FLAG_precompiled_mode = true; FLAG_reorder_basic_blocks = false; FLAG_use_field_guards = false; FLAG_use_cha_deopt = false; #if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME) // Set flags affecting runtime accordingly for dart_noopt. FLAG_background_compilation = false; FLAG_collect_code = false; FLAG_support_debugger = false; FLAG_deoptimize_alot = false; // Used in some tests. FLAG_deoptimize_every = 0; // Used in some tests. FLAG_enable_mirrors = false; FLAG_load_deferred_eagerly = true; FLAG_print_stop_message = false; FLAG_use_osr = false; #endif } } DEFINE_FLAG_HANDLER(PrecompilationModeHandler, precompilation, "Precompilation mode"); #ifdef DART_PRECOMPILED_RUNTIME COMPILE_ASSERT(!FLAG_background_compilation); COMPILE_ASSERT(!FLAG_collect_code); COMPILE_ASSERT(!FLAG_deoptimize_alot); // Used in some tests. COMPILE_ASSERT(!FLAG_enable_mirrors); COMPILE_ASSERT(FLAG_precompiled_runtime); COMPILE_ASSERT(!FLAG_print_stop_message); COMPILE_ASSERT(!FLAG_use_osr); COMPILE_ASSERT(FLAG_deoptimize_every == 0); // Used in some tests. COMPILE_ASSERT(FLAG_load_deferred_eagerly); #endif // DART_PRECOMPILED_RUNTIME // Assign locations to incoming arguments, i.e., values pushed above spill slots // with PushArgument. Recursively allocates from outermost to innermost // environment. void CompilerDeoptInfo::AllocateIncomingParametersRecursive( Environment* env, intptr_t* stack_height) { if (env == NULL) return; AllocateIncomingParametersRecursive(env->outer(), stack_height); for (Environment::ShallowIterator it(env); !it.Done(); it.Advance()) { if (it.CurrentLocation().IsInvalid() && it.CurrentValue()->definition()->IsPushArgument()) { it.SetCurrentLocation(Location::StackSlot((*stack_height)++)); } } } void CompilerDeoptInfo::EmitMaterializations(Environment* env, DeoptInfoBuilder* builder) { for (Environment::DeepIterator it(env); !it.Done(); it.Advance()) { if (it.CurrentLocation().IsInvalid()) { MaterializeObjectInstr* mat = it.CurrentValue()->definition()->AsMaterializeObject(); ASSERT(mat != NULL); builder->AddMaterialization(mat); } } } FlowGraphCompiler::FlowGraphCompiler( Assembler* assembler, FlowGraph* flow_graph, const ParsedFunction& parsed_function, bool is_optimizing, const GrowableArray<const Function*>& inline_id_to_function, const GrowableArray<TokenPosition>& inline_id_to_token_pos, const GrowableArray<intptr_t>& caller_inline_id) : thread_(Thread::Current()), zone_(Thread::Current()->zone()), assembler_(assembler), parsed_function_(parsed_function), flow_graph_(*flow_graph), block_order_(*flow_graph->CodegenBlockOrder(is_optimizing)), current_block_(NULL), exception_handlers_list_(NULL), pc_descriptors_list_(NULL), stackmap_table_builder_(NULL), code_source_map_builder_(NULL), saved_code_size_(0), block_info_(block_order_.length()), deopt_infos_(), static_calls_target_table_(), is_optimizing_(is_optimizing), may_reoptimize_(false), intrinsic_mode_(false), double_class_(Class::ZoneHandle( isolate()->object_store()->double_class())), mint_class_(Class::ZoneHandle( isolate()->object_store()->mint_class())), float32x4_class_(Class::ZoneHandle( isolate()->object_store()->float32x4_class())), float64x2_class_(Class::ZoneHandle( isolate()->object_store()->float64x2_class())), int32x4_class_(Class::ZoneHandle( isolate()->object_store()->int32x4_class())), list_class_(Class::ZoneHandle( Library::Handle(Library::CoreLibrary()). LookupClass(Symbols::List()))), parallel_move_resolver_(this), pending_deoptimization_env_(NULL), lazy_deopt_pc_offset_(Code::kInvalidPc), deopt_id_to_ic_data_(NULL), edge_counters_array_(Array::ZoneHandle()), inlined_code_intervals_(Array::ZoneHandle(Object::empty_array().raw())), inline_id_to_function_(inline_id_to_function), inline_id_to_token_pos_(inline_id_to_token_pos), caller_inline_id_(caller_inline_id) { ASSERT(flow_graph->parsed_function().function().raw() == parsed_function.function().raw()); if (!is_optimizing) { const intptr_t len = thread()->deopt_id(); deopt_id_to_ic_data_ = new(zone()) ZoneGrowableArray<const ICData*>(len); deopt_id_to_ic_data_->SetLength(len); for (intptr_t i = 0; i < len; i++) { (*deopt_id_to_ic_data_)[i] = NULL; } // TODO(fschneider): Abstract iteration into ICDataArrayIterator. const Array& old_saved_ic_data = Array::Handle(zone(), flow_graph->function().ic_data_array()); const intptr_t saved_len = old_saved_ic_data.IsNull() ? 0 : old_saved_ic_data.Length(); for (intptr_t i = 1; i < saved_len; i++) { ICData& ic_data = ICData::ZoneHandle(zone()); ic_data ^= old_saved_ic_data.At(i); (*deopt_id_to_ic_data_)[ic_data.deopt_id()] = &ic_data; } } ASSERT(assembler != NULL); ASSERT(!list_class_.IsNull()); } bool FlowGraphCompiler::IsUnboxedField(const Field& field) { bool valid_class = (SupportsUnboxedDoubles() && (field.guarded_cid() == kDoubleCid)) || (SupportsUnboxedSimd128() && (field.guarded_cid() == kFloat32x4Cid)) || (SupportsUnboxedSimd128() && (field.guarded_cid() == kFloat64x2Cid)); return field.is_unboxing_candidate() && !field.is_final() && !field.is_nullable() && valid_class; } bool FlowGraphCompiler::IsPotentialUnboxedField(const Field& field) { return field.is_unboxing_candidate() && (FlowGraphCompiler::IsUnboxedField(field) || (!field.is_final() && (field.guarded_cid() == kIllegalCid))); } void FlowGraphCompiler::InitCompiler() { #ifndef PRODUCT TimelineDurationScope tds(thread(), Timeline::GetCompilerStream(), "InitCompiler"); #endif // !PRODUCT pc_descriptors_list_ = new(zone()) DescriptorList(64); exception_handlers_list_ = new(zone()) ExceptionHandlerList(); block_info_.Clear(); // Conservative detection of leaf routines used to remove the stack check // on function entry. bool is_leaf = is_optimizing() && !flow_graph().IsCompiledForOsr(); // Initialize block info and search optimized (non-OSR) code for calls // indicating a non-leaf routine and calls without IC data indicating // possible reoptimization. for (int i = 0; i < block_order_.length(); ++i) { block_info_.Add(new(zone()) BlockInfo()); if (is_optimizing() && !flow_graph().IsCompiledForOsr()) { BlockEntryInstr* entry = block_order_[i]; for (ForwardInstructionIterator it(entry); !it.Done(); it.Advance()) { Instruction* current = it.Current(); if (current->IsBranch()) { current = current->AsBranch()->comparison(); } // In optimized code, ICData is always set in the instructions. const ICData* ic_data = NULL; if (current->IsInstanceCall()) { ic_data = current->AsInstanceCall()->ic_data(); } if ((ic_data != NULL) && (ic_data->NumberOfUsedChecks() == 0)) { may_reoptimize_ = true; } if (is_leaf && !current->IsCheckStackOverflow() && !current->IsParallelMove()) { // Note that we do not care if the code contains instructions that // can deoptimize. LocationSummary* locs = current->locs(); if ((locs != NULL) && locs->can_call()) { is_leaf = false; } } } } } if (is_leaf) { // Remove the stack overflow check at function entry. Instruction* first = flow_graph_.graph_entry()->normal_entry()->next(); if (first->IsCheckStackOverflow()) first->RemoveFromGraph(); } if (!is_optimizing()) { // Initialize edge counter array. const intptr_t num_counters = flow_graph_.preorder().length(); const Array& edge_counters = Array::Handle(Array::New(num_counters, Heap::kOld)); const Smi& zero_smi = Smi::Handle(Smi::New(0)); for (intptr_t i = 0; i < num_counters; ++i) { edge_counters.SetAt(i, zero_smi); } edge_counters_array_ = edge_counters.raw(); } } bool FlowGraphCompiler::CanOptimize() { return FLAG_optimization_counter_threshold >= 0; } bool FlowGraphCompiler::CanOptimizeFunction() const { return CanOptimize() && !parsed_function().function().HasBreakpoint(); } bool FlowGraphCompiler::CanOSRFunction() const { return FLAG_use_osr & CanOptimizeFunction() && !is_optimizing(); } bool FlowGraphCompiler::ForceSlowPathForStackOverflow() const { if (FLAG_stacktrace_every > 0 || FLAG_deoptimize_every > 0) { return true; } if (FLAG_stacktrace_filter != NULL && strstr(parsed_function().function().ToFullyQualifiedCString(), FLAG_stacktrace_filter) != NULL) { return true; } if (is_optimizing() && FLAG_deoptimize_filter != NULL && strstr(parsed_function().function().ToFullyQualifiedCString(), FLAG_deoptimize_filter) != NULL) { return true; } return false; } static bool IsEmptyBlock(BlockEntryInstr* block) { return !block->IsCatchBlockEntry() && !block->HasNonRedundantParallelMove() && block->next()->IsGoto() && !block->next()->AsGoto()->HasNonRedundantParallelMove() && !block->IsIndirectEntry(); } void FlowGraphCompiler::CompactBlock(BlockEntryInstr* block) { BlockInfo* block_info = block_info_[block->postorder_number()]; // Break out of cycles in the control flow graph. if (block_info->is_marked()) { return; } block_info->mark(); if (IsEmptyBlock(block)) { // For empty blocks, record a corresponding nonempty target as their // jump label. BlockEntryInstr* target = block->next()->AsGoto()->successor(); CompactBlock(target); block_info->set_jump_label(GetJumpLabel(target)); } } void FlowGraphCompiler::CompactBlocks() { // This algorithm does not garbage collect blocks in place, but merely // records forwarding label information. In this way it avoids having to // change join and target entries. Label* nonempty_label = NULL; for (intptr_t i = block_order().length() - 1; i >= 1; --i) { BlockEntryInstr* block = block_order()[i]; // Unoptimized code must emit all possible deoptimization points. if (is_optimizing()) { CompactBlock(block); } // For nonempty blocks, record the next nonempty block in the block // order. Since no code is emitted for empty blocks, control flow is // eligible to fall through to the next nonempty one. if (!WasCompacted(block)) { BlockInfo* block_info = block_info_[block->postorder_number()]; block_info->set_next_nonempty_label(nonempty_label); nonempty_label = GetJumpLabel(block); } } ASSERT(block_order()[0]->IsGraphEntry()); BlockInfo* block_info = block_info_[block_order()[0]->postorder_number()]; block_info->set_next_nonempty_label(nonempty_label); } void FlowGraphCompiler::EmitInstructionPrologue(Instruction* instr) { if (!is_optimizing()) { if (instr->CanBecomeDeoptimizationTarget() && !instr->IsGoto()) { // Instructions that can be deoptimization targets need to record kDeopt // PcDescriptor corresponding to their deopt id. GotoInstr records its // own so that it can control the placement. AddCurrentDescriptor(RawPcDescriptors::kDeopt, instr->deopt_id(), instr->token_pos()); } AllocateRegistersLocally(instr); } else if (instr->MayThrow() && (CurrentTryIndex() != CatchClauseNode::kInvalidTryIndex)) { // Optimized try-block: Sync locals to fixed stack locations. EmitTrySync(instr, CurrentTryIndex()); } } void FlowGraphCompiler::EmitSourceLine(Instruction* instr) { if (!instr->token_pos().IsReal() || (instr->env() == NULL)) { return; } const Script& script = Script::Handle(zone(), instr->env()->function().script()); intptr_t line_nr; intptr_t column_nr; script.GetTokenLocation(instr->token_pos(), &line_nr, &column_nr); const String& line = String::Handle(zone(), script.GetLine(line_nr)); assembler()->Comment("Line %" Pd " in '%s':\n %s", line_nr, instr->env()->function().ToFullyQualifiedCString(), line.ToCString()); } static void LoopInfoComment( Assembler* assembler, const BlockEntryInstr& block, const ZoneGrowableArray<BlockEntryInstr*>& loop_headers) { if (Assembler::EmittingComments()) { for (intptr_t loop_id = 0; loop_id < loop_headers.length(); ++loop_id) { for (BitVector::Iterator loop_it(loop_headers[loop_id]->loop_info()); !loop_it.Done(); loop_it.Advance()) { if (loop_it.Current() == block.preorder_number()) { assembler->Comment(" Loop %" Pd "", loop_id); } } } } } // We collect intervals while generating code. struct IntervalStruct { // 'start' is the pc-offsets where the inlined code started. // 'pos' is the token position where the inlined call occured. intptr_t start; TokenPosition pos; intptr_t inlining_id; IntervalStruct(intptr_t s, TokenPosition tp, intptr_t id) : start(s), pos(tp), inlining_id(id) {} void Dump() { THR_Print("start: 0x%" Px " iid: %" Pd " pos: %s", start, inlining_id, pos.ToCString()); } }; void FlowGraphCompiler::VisitBlocks() { CompactBlocks(); const ZoneGrowableArray<BlockEntryInstr*>* loop_headers = NULL; if (Assembler::EmittingComments()) { // 'loop_headers' were cleared, recompute. loop_headers = flow_graph().ComputeLoops(); ASSERT(loop_headers != NULL); } // For collecting intervals of inlined code. GrowableArray<IntervalStruct> intervals; intptr_t prev_offset = 0; intptr_t prev_inlining_id = 0; TokenPosition prev_inlining_pos = parsed_function_.function().token_pos(); intptr_t max_inlining_id = 0; for (intptr_t i = 0; i < block_order().length(); ++i) { // Compile the block entry. BlockEntryInstr* entry = block_order()[i]; assembler()->Comment("B%" Pd "", entry->block_id()); set_current_block(entry); if (WasCompacted(entry)) { continue; } #if defined(DEBUG) if (!is_optimizing()) { FrameStateClear(); } #endif LoopInfoComment(assembler(), *entry, *loop_headers); entry->set_offset(assembler()->CodeSize()); BeginCodeSourceRange(); entry->EmitNativeCode(this); EndCodeSourceRange(entry->token_pos()); // Compile all successors until an exit, branch, or a block entry. for (ForwardInstructionIterator it(entry); !it.Done(); it.Advance()) { Instruction* instr = it.Current(); // Compose intervals. if (instr->has_inlining_id() && is_optimizing()) { if (prev_inlining_id != instr->inlining_id()) { intervals.Add( IntervalStruct(prev_offset, prev_inlining_pos, prev_inlining_id)); prev_offset = assembler()->CodeSize(); prev_inlining_id = instr->inlining_id(); if (prev_inlining_id < inline_id_to_token_pos_.length()) { prev_inlining_pos = inline_id_to_token_pos_[prev_inlining_id]; } else { // We will add this token position later when generating the // profile. prev_inlining_pos = TokenPosition::kNoSource; } if (prev_inlining_id > max_inlining_id) { max_inlining_id = prev_inlining_id; } } } if (FLAG_code_comments || FLAG_disassemble || FLAG_disassemble_optimized) { if (FLAG_source_lines) { EmitSourceLine(instr); } EmitComment(instr); } if (instr->IsParallelMove()) { parallel_move_resolver_.EmitNativeCode(instr->AsParallelMove()); } else { BeginCodeSourceRange(); EmitInstructionPrologue(instr); ASSERT(pending_deoptimization_env_ == NULL); pending_deoptimization_env_ = instr->env(); instr->EmitNativeCode(this); pending_deoptimization_env_ = NULL; EmitInstructionEpilogue(instr); EndCodeSourceRange(instr->token_pos()); } #if defined(DEBUG) if (!is_optimizing()) { FrameStateUpdateWith(instr); } #endif } #if defined(DEBUG) ASSERT(is_optimizing() || FrameStateIsSafeToCall()); #endif } if (is_optimizing()) { LogBlock lb; intervals.Add( IntervalStruct(prev_offset, prev_inlining_pos, prev_inlining_id)); inlined_code_intervals_ = Array::New(intervals.length() * Code::kInlIntNumEntries, Heap::kOld); Smi& start_h = Smi::Handle(); Smi& caller_inline_id = Smi::Handle(); Smi& inline_id = Smi::Handle(); for (intptr_t i = 0; i < intervals.length(); i++) { if (FLAG_trace_inlining_intervals && is_optimizing()) { const Function& function = *inline_id_to_function_.At(intervals[i].inlining_id); intervals[i].Dump(); THR_Print(" parent iid %" Pd " %s\n", caller_inline_id_[intervals[i].inlining_id], function.ToQualifiedCString()); } const intptr_t id = intervals[i].inlining_id; start_h = Smi::New(intervals[i].start); inline_id = Smi::New(id); caller_inline_id = Smi::New(caller_inline_id_[intervals[i].inlining_id]); const intptr_t p = i * Code::kInlIntNumEntries; inlined_code_intervals_.SetAt(p + Code::kInlIntStart, start_h); inlined_code_intervals_.SetAt(p + Code::kInlIntInliningId, inline_id); } } set_current_block(NULL); if (FLAG_trace_inlining_intervals && is_optimizing()) { LogBlock lb; THR_Print("Intervals:\n"); for (intptr_t cc = 0; cc < caller_inline_id_.length(); cc++) { THR_Print(" iid: %" Pd " caller iid: %" Pd "\n", cc, caller_inline_id_[cc]); } Smi& temp = Smi::Handle(); for (intptr_t i = 0; i < inlined_code_intervals_.Length(); i += Code::kInlIntNumEntries) { temp ^= inlined_code_intervals_.At(i + Code::kInlIntStart); ASSERT(!temp.IsNull()); THR_Print("% " Pd " start: 0x%" Px " ", i, temp.Value()); temp ^= inlined_code_intervals_.At(i + Code::kInlIntInliningId); THR_Print("iid: %" Pd " ", temp.Value()); } } } void FlowGraphCompiler::Bailout(const char* reason) { const Function& function = parsed_function_.function(); Report::MessageF(Report::kBailout, Script::Handle(function.script()), function.token_pos(), Report::AtLocation, "FlowGraphCompiler Bailout: %s %s", String::Handle(function.name()).ToCString(), reason); UNREACHABLE(); } void FlowGraphCompiler::EmitTrySync(Instruction* instr, intptr_t try_index) { ASSERT(is_optimizing()); Environment* env = instr->env()->Outermost(); CatchBlockEntryInstr* catch_block = flow_graph().graph_entry()->GetCatchEntry(try_index); const GrowableArray<Definition*>* idefs = catch_block->initial_definitions(); // Construct a ParallelMove instruction for parameters and locals. Skip the // special locals exception_var and stacktrace_var since they will be filled // when an exception is thrown. Constant locations are known to be the same // at all instructions that may throw, and do not need to be materialized. // Parameters first. intptr_t i = 0; const intptr_t num_non_copied_params = flow_graph().num_non_copied_params(); ParallelMoveInstr* move_instr = new(zone()) ParallelMoveInstr(); for (; i < num_non_copied_params; ++i) { // Don't sync captured parameters. They are not in the environment. if (flow_graph().captured_parameters()->Contains(i)) continue; if ((*idefs)[i]->IsConstant()) continue; // Common constants Location src = env->LocationAt(i); intptr_t dest_index = i - num_non_copied_params; Location dest = Location::StackSlot(dest_index); move_instr->AddMove(dest, src); } // Process locals. Skip exception_var and stacktrace_var. intptr_t local_base = kFirstLocalSlotFromFp + num_non_copied_params; intptr_t ex_idx = local_base - catch_block->exception_var().index(); intptr_t st_idx = local_base - catch_block->stacktrace_var().index(); for (; i < flow_graph().variable_count(); ++i) { // Don't sync captured parameters. They are not in the environment. if (flow_graph().captured_parameters()->Contains(i)) continue; if (i == ex_idx || i == st_idx) continue; if ((*idefs)[i]->IsConstant()) continue; Location src = env->LocationAt(i); ASSERT(!src.IsFpuRegister()); ASSERT(!src.IsDoubleStackSlot()); intptr_t dest_index = i - num_non_copied_params; Location dest = Location::StackSlot(dest_index); move_instr->AddMove(dest, src); // Update safepoint bitmap to indicate that the target location // now contains a pointer. instr->locs()->SetStackBit(dest_index); } parallel_move_resolver()->EmitNativeCode(move_instr); } intptr_t FlowGraphCompiler::StackSize() const { if (is_optimizing_) { return flow_graph_.graph_entry()->spill_slot_count(); } else { return parsed_function_.num_stack_locals() + parsed_function_.num_copied_params(); } } Label* FlowGraphCompiler::GetJumpLabel( BlockEntryInstr* block_entry) const { const intptr_t block_index = block_entry->postorder_number(); return block_info_[block_index]->jump_label(); } bool FlowGraphCompiler::WasCompacted( BlockEntryInstr* block_entry) const { const intptr_t block_index = block_entry->postorder_number(); return block_info_[block_index]->WasCompacted(); } Label* FlowGraphCompiler::NextNonEmptyLabel() const { const intptr_t current_index = current_block()->postorder_number(); return block_info_[current_index]->next_nonempty_label(); } bool FlowGraphCompiler::CanFallThroughTo(BlockEntryInstr* block_entry) const { return NextNonEmptyLabel() == GetJumpLabel(block_entry); } BranchLabels FlowGraphCompiler::CreateBranchLabels(BranchInstr* branch) const { Label* true_label = GetJumpLabel(branch->true_successor()); Label* false_label = GetJumpLabel(branch->false_successor()); Label* fall_through = NextNonEmptyLabel(); BranchLabels result = { true_label, false_label, fall_through }; return result; } void FlowGraphCompiler::AddSlowPathCode(SlowPathCode* code) { slow_path_code_.Add(code); } void FlowGraphCompiler::GenerateDeferredCode() { for (intptr_t i = 0; i < slow_path_code_.length(); i++) { BeginCodeSourceRange(); slow_path_code_[i]->GenerateCode(this); EndCodeSourceRange(TokenPosition::kDeferredSlowPath); } for (intptr_t i = 0; i < deopt_infos_.length(); i++) { BeginCodeSourceRange(); deopt_infos_[i]->GenerateCode(this, i); EndCodeSourceRange(TokenPosition::kDeferredDeoptInfo); } } void FlowGraphCompiler::AddExceptionHandler(intptr_t try_index, intptr_t outer_try_index, intptr_t pc_offset, const Array& handler_types, bool needs_stacktrace) { exception_handlers_list_->AddHandler(try_index, outer_try_index, pc_offset, handler_types, needs_stacktrace); } void FlowGraphCompiler::SetNeedsStacktrace(intptr_t try_index) { exception_handlers_list_->SetNeedsStacktrace(try_index); } // Uses current pc position and try-index. void FlowGraphCompiler::AddCurrentDescriptor(RawPcDescriptors::Kind kind, intptr_t deopt_id, TokenPosition token_pos) { // When running with optimizations disabled, don't emit deopt-descriptors. if (!CanOptimize() && (kind == RawPcDescriptors::kDeopt)) return; pc_descriptors_list()->AddDescriptor(kind, assembler()->CodeSize(), deopt_id, token_pos, CurrentTryIndex()); } void FlowGraphCompiler::AddStaticCallTarget(const Function& func) { ASSERT(func.IsZoneHandle()); static_calls_target_table_.Add( new(zone()) StaticCallsStruct(assembler()->CodeSize(), &func, NULL)); } void FlowGraphCompiler::AddStubCallTarget(const Code& code) { ASSERT(code.IsZoneHandle()); static_calls_target_table_.Add( new(zone()) StaticCallsStruct(assembler()->CodeSize(), NULL, &code)); } void FlowGraphCompiler::AddDeoptIndexAtCall(intptr_t deopt_id, TokenPosition token_pos) { ASSERT(is_optimizing()); ASSERT(!intrinsic_mode()); CompilerDeoptInfo* info = new(zone()) CompilerDeoptInfo(deopt_id, ICData::kDeoptAtCall, 0, // No flags. pending_deoptimization_env_); info->set_pc_offset(assembler()->CodeSize()); deopt_infos_.Add(info); } // This function must be in sync with FlowGraphCompiler::SaveLiveRegisters // and FlowGraphCompiler::SlowPathEnvironmentFor. // See StackFrame::VisitObjectPointers for the details of how stack map is // interpreted. void FlowGraphCompiler::RecordSafepoint(LocationSummary* locs, intptr_t slow_path_argument_count) { if (is_optimizing() || locs->live_registers()->HasUntaggedValues()) { const intptr_t spill_area_size = is_optimizing() ? flow_graph_.graph_entry()->spill_slot_count() : 0; RegisterSet* registers = locs->live_registers(); ASSERT(registers != NULL); const intptr_t kFpuRegisterSpillFactor = kFpuRegisterSize / kWordSize; const intptr_t live_registers_size = registers->CpuRegisterCount() + (registers->FpuRegisterCount() * kFpuRegisterSpillFactor); BitmapBuilder* bitmap = locs->stack_bitmap(); // An instruction may have two safepoints in deferred code. The // call to RecordSafepoint has the side-effect of appending the live // registers to the bitmap. This is why the second call to RecordSafepoint // with the same instruction (and same location summary) sees a bitmap that // is larger that StackSize(). It will never be larger than StackSize() + // live_registers_size. ASSERT(bitmap->Length() <= (spill_area_size + live_registers_size)); // The first safepoint will grow the bitmap to be the size of // spill_area_size but the second safepoint will truncate the bitmap and // append the live registers to it again. The bitmap produced by both calls // will be the same. bitmap->SetLength(spill_area_size); // Mark the bits in the stack map in the same order we push registers in // slow path code (see FlowGraphCompiler::SaveLiveRegisters). // // Slow path code can have registers at the safepoint. if (!locs->always_calls()) { RegisterSet* regs = locs->live_registers(); if (regs->FpuRegisterCount() > 0) { // Denote FPU registers with 0 bits in the stackmap. Based on the // assumption that there are normally few live FPU registers, this // encoding is simpler and roughly as compact as storing a separate // count of FPU registers. // // FPU registers have the highest register number at the highest // address (i.e., first in the stackmap). for (intptr_t i = kNumberOfFpuRegisters - 1; i >= 0; --i) { FpuRegister reg = static_cast<FpuRegister>(i); if (regs->ContainsFpuRegister(reg)) { for (intptr_t j = 0; j < kFpuRegisterSpillFactor; ++j) { bitmap->Set(bitmap->Length(), false); } } } } // General purpose registers have the highest register number at the // highest address (i.e., first in the stackmap). for (intptr_t i = kNumberOfCpuRegisters - 1; i >= 0; --i) { Register reg = static_cast<Register>(i); if (locs->live_registers()->ContainsRegister(reg)) { bitmap->Set(bitmap->Length(), locs->live_registers()->IsTagged(reg)); } } } // Arguments pushed on top of live registers in the slow path are tagged. for (intptr_t i = 0; i < slow_path_argument_count; ++i) { bitmap->Set(bitmap->Length(), true); } // The slow path area Outside the spill area contains are live registers // and pushed arguments for calls inside the slow path. intptr_t slow_path_bit_count = bitmap->Length() - spill_area_size; stackmap_table_builder()->AddEntry(assembler()->CodeSize(), bitmap, slow_path_bit_count); } } // This function must be kept in sync with: // // FlowGraphCompiler::RecordSafepoint // FlowGraphCompiler::SaveLiveRegisters // MaterializeObjectInstr::RemapRegisters // Environment* FlowGraphCompiler::SlowPathEnvironmentFor( Instruction* instruction) { if (instruction->env() == NULL) { ASSERT(!is_optimizing()); return NULL; } Environment* env = instruction->env()->DeepCopy(zone()); // 1. Iterate the registers in the order they will be spilled to compute // the slots they will be spilled to. intptr_t next_slot = StackSize() + env->CountArgsPushed(); RegisterSet* regs = instruction->locs()->live_registers(); intptr_t fpu_reg_slots[kNumberOfFpuRegisters]; intptr_t cpu_reg_slots[kNumberOfCpuRegisters]; const intptr_t kFpuRegisterSpillFactor = kFpuRegisterSize / kWordSize; // FPU registers are spilled first from highest to lowest register number. for (intptr_t i = kNumberOfFpuRegisters - 1; i >= 0; --i) { FpuRegister reg = static_cast<FpuRegister>(i); if (regs->ContainsFpuRegister(reg)) { // We use the lowest address (thus highest index) to identify a // multi-word spill slot. next_slot += kFpuRegisterSpillFactor; fpu_reg_slots[i] = (next_slot - 1); } else { fpu_reg_slots[i] = -1; } } // General purpose registers are spilled from highest to lowest register // number. for (intptr_t i = kNumberOfCpuRegisters - 1; i >= 0; --i) { Register reg = static_cast<Register>(i); if (regs->ContainsRegister(reg)) { cpu_reg_slots[i] = next_slot++; } else { cpu_reg_slots[i] = -1; } } // 2. Iterate the environment and replace register locations with the // corresponding spill slot locations. for (Environment::DeepIterator it(env); !it.Done(); it.Advance()) { Location loc = it.CurrentLocation(); Value* value = it.CurrentValue(); it.SetCurrentLocation(loc.RemapForSlowPath( value->definition(), cpu_reg_slots, fpu_reg_slots)); } return env; } Label* FlowGraphCompiler::AddDeoptStub(intptr_t deopt_id, ICData::DeoptReasonId reason, uint32_t flags) { if (intrinsic_mode()) { return &intrinsic_slow_path_label_; } // No deoptimization allowed when 'FLAG_precompiled_mode' is set. if (FLAG_precompiled_mode) { if (FLAG_trace_compiler) { THR_Print( "Retrying compilation %s, suppressing inlining of deopt_id:%" Pd "\n", parsed_function_.function().ToFullyQualifiedCString(), deopt_id); } ASSERT(deopt_id != 0); // longjmp must return non-zero value. Thread::Current()->long_jump_base()->Jump( deopt_id, Object::speculative_inlining_error()); } ASSERT(is_optimizing_); CompilerDeoptInfoWithStub* stub = new(zone()) CompilerDeoptInfoWithStub(deopt_id, reason, flags, pending_deoptimization_env_); deopt_infos_.Add(stub); return stub->entry_label(); } void FlowGraphCompiler::FinalizeExceptionHandlers(const Code& code) { ASSERT(exception_handlers_list_ != NULL); const ExceptionHandlers& handlers = ExceptionHandlers::Handle( exception_handlers_list_->FinalizeExceptionHandlers(code.EntryPoint())); code.set_exception_handlers(handlers); if (FLAG_compiler_stats) { Thread* thread = Thread::Current(); INC_STAT(thread, total_code_size, ExceptionHandlers::InstanceSize(handlers.num_entries())); INC_STAT(thread, total_code_size, handlers.num_entries() * sizeof(uword)); } } void FlowGraphCompiler::FinalizePcDescriptors(const Code& code) { ASSERT(pc_descriptors_list_ != NULL); const PcDescriptors& descriptors = PcDescriptors::Handle( pc_descriptors_list_->FinalizePcDescriptors(code.EntryPoint())); if (!is_optimizing_) descriptors.Verify(parsed_function_.function()); code.set_pc_descriptors(descriptors); code.set_lazy_deopt_pc_offset(lazy_deopt_pc_offset_); } RawArray* FlowGraphCompiler::CreateDeoptInfo(Assembler* assembler) { // No deopt information if we precompile (no deoptimization allowed). if (FLAG_precompiled_mode) { return Array::empty_array().raw(); } // For functions with optional arguments, all incoming arguments are copied // to spill slots. The deoptimization environment does not track them. const Function& function = parsed_function().function(); const intptr_t incoming_arg_count = function.HasOptionalParameters() ? 0 : function.num_fixed_parameters(); DeoptInfoBuilder builder(zone(), incoming_arg_count, assembler); intptr_t deopt_info_table_size = DeoptTable::SizeFor(deopt_infos_.length()); if (deopt_info_table_size == 0) { return Object::empty_array().raw(); } else { const Array& array = Array::Handle(Array::New(deopt_info_table_size, Heap::kOld)); Smi& offset = Smi::Handle(); TypedData& info = TypedData::Handle(); Smi& reason_and_flags = Smi::Handle(); for (intptr_t i = 0; i < deopt_infos_.length(); i++) { offset = Smi::New(deopt_infos_[i]->pc_offset()); info = deopt_infos_[i]->CreateDeoptInfo(this, &builder, array); reason_and_flags = DeoptTable::EncodeReasonAndFlags( deopt_infos_[i]->reason(), deopt_infos_[i]->flags()); DeoptTable::SetEntry(array, i, offset, info, reason_and_flags); } return array.raw(); } } void FlowGraphCompiler::FinalizeStackmaps(const Code& code) { if (stackmap_table_builder_ == NULL) { code.set_stackmaps(Object::null_array()); } else { // Finalize the stack map array and add it to the code object. code.set_stackmaps( Array::Handle(stackmap_table_builder_->FinalizeStackmaps(code))); } } void FlowGraphCompiler::FinalizeVarDescriptors(const Code& code) { if (code.is_optimized()) { // Optimized code does not need variable descriptors. They are // only stored in the unoptimized version. code.set_var_descriptors(Object::empty_var_descriptors()); return; } LocalVarDescriptors& var_descs = LocalVarDescriptors::Handle(); if (parsed_function().node_sequence() == NULL) { // Eager local var descriptors computation for Irregexp function as it is // complicated to factor out. // TODO(srdjan): Consider canonicalizing and reusing the local var // descriptor for IrregexpFunction. ASSERT(flow_graph().IsIrregexpFunction()); var_descs = LocalVarDescriptors::New(1); RawLocalVarDescriptors::VarInfo info; info.set_kind(RawLocalVarDescriptors::kSavedCurrentContext); info.scope_id = 0; info.begin_pos = TokenPosition::kMinSource; info.end_pos = TokenPosition::kMinSource; info.set_index(parsed_function().current_context_var()->index()); var_descs.SetVar(0, Symbols::CurrentContextVar(), &info); } code.set_var_descriptors(var_descs); } void FlowGraphCompiler::FinalizeStaticCallTargetsTable(const Code& code) { ASSERT(code.static_calls_target_table() == Array::null()); const Array& targets = Array::Handle(zone(), Array::New( (static_calls_target_table_.length() * Code::kSCallTableEntryLength), Heap::kOld)); Smi& smi_offset = Smi::Handle(zone()); for (intptr_t i = 0; i < static_calls_target_table_.length(); i++) { const intptr_t target_ix = Code::kSCallTableEntryLength * i; smi_offset = Smi::New(static_calls_target_table_[i]->offset); targets.SetAt(target_ix + Code::kSCallTableOffsetEntry, smi_offset); if (static_calls_target_table_[i]->function != NULL) { targets.SetAt(target_ix + Code::kSCallTableFunctionEntry, *static_calls_target_table_[i]->function); } if (static_calls_target_table_[i]->code != NULL) { targets.SetAt(target_ix + Code::kSCallTableCodeEntry, *static_calls_target_table_[i]->code); } } code.set_static_calls_target_table(targets); INC_STAT(Thread::Current(), total_code_size, targets.Length() * sizeof(uword)); } // Returns 'true' if regular code generation should be skipped. bool FlowGraphCompiler::TryIntrinsify() { // Intrinsification skips arguments checks, therefore disable if in checked // mode. if (FLAG_intrinsify && !isolate()->type_checks()) { if (parsed_function().function().kind() == RawFunction::kImplicitGetter) { // An implicit getter must have a specific AST structure. const SequenceNode& sequence_node = *parsed_function().node_sequence(); ASSERT(sequence_node.length() == 1); ASSERT(sequence_node.NodeAt(0)->IsReturnNode()); const ReturnNode& return_node = *sequence_node.NodeAt(0)->AsReturnNode(); ASSERT(return_node.value()->IsLoadInstanceFieldNode()); const LoadInstanceFieldNode& load_node = *return_node.value()->AsLoadInstanceFieldNode(); // Only intrinsify getter if the field cannot contain a mutable double. // Reading from a mutable double box requires allocating a fresh double. if (!IsPotentialUnboxedField(load_node.field())) { GenerateInlinedGetter(load_node.field().Offset()); return !FLAG_use_field_guards; } return false; } if (parsed_function().function().kind() == RawFunction::kImplicitSetter) { // An implicit setter must have a specific AST structure. // Sequence node has one store node and one return NULL node. const SequenceNode& sequence_node = *parsed_function().node_sequence(); ASSERT(sequence_node.length() == 2); ASSERT(sequence_node.NodeAt(0)->IsStoreInstanceFieldNode()); ASSERT(sequence_node.NodeAt(1)->IsReturnNode()); const StoreInstanceFieldNode& store_node = *sequence_node.NodeAt(0)->AsStoreInstanceFieldNode(); if (store_node.field().guarded_cid() == kDynamicCid) { GenerateInlinedSetter(store_node.field().Offset()); return !FLAG_use_field_guards; } } } EnterIntrinsicMode(); Intrinsifier::Intrinsify(parsed_function(), this); ExitIntrinsicMode(); // "Deoptimization" from intrinsic continues here. All deoptimization // branches from intrinsic code redirect to here where the slow-path // (normal function body) starts. // This means that there must not be any side-effects in intrinsic code // before any deoptimization point. ASSERT(!intrinsic_slow_path_label_.IsBound()); assembler()->Bind(&intrinsic_slow_path_label_); return false; } void FlowGraphCompiler::GenerateInstanceCall( intptr_t deopt_id, TokenPosition token_pos, intptr_t argument_count, LocationSummary* locs, const ICData& ic_data_in) { const ICData& ic_data = ICData::ZoneHandle(ic_data_in.Original()); if (FLAG_precompiled_mode) { EmitSwitchableInstanceCall(ic_data, argument_count, deopt_id, token_pos, locs); return; } if (FLAG_always_megamorphic_calls) { EmitMegamorphicInstanceCall(ic_data, argument_count, deopt_id, token_pos, locs, CatchClauseNode::kInvalidTryIndex); return; } ASSERT(!ic_data.IsNull()); if (is_optimizing() && (ic_data.NumberOfUsedChecks() == 0)) { // Emit IC call that will count and thus may need reoptimization at // function entry. ASSERT(may_reoptimize() || flow_graph().IsCompiledForOsr()); switch (ic_data.NumArgsTested()) { case 1: EmitOptimizedInstanceCall( *StubCode::OneArgOptimizedCheckInlineCache_entry(), ic_data, argument_count, deopt_id, token_pos, locs); return; case 2: EmitOptimizedInstanceCall( *StubCode::TwoArgsOptimizedCheckInlineCache_entry(), ic_data, argument_count, deopt_id, token_pos, locs); return; default: UNIMPLEMENTED(); } return; } if (is_optimizing()) { EmitMegamorphicInstanceCall(ic_data, argument_count, deopt_id, token_pos, locs, CatchClauseNode::kInvalidTryIndex); return; } switch (ic_data.NumArgsTested()) { case 1: EmitInstanceCall( *StubCode::OneArgCheckInlineCache_entry(), ic_data, argument_count, deopt_id, token_pos, locs); break; case 2: EmitInstanceCall( *StubCode::TwoArgsCheckInlineCache_entry(), ic_data, argument_count, deopt_id, token_pos, locs); break; default: UNIMPLEMENTED(); } } void FlowGraphCompiler::GenerateStaticCall(intptr_t deopt_id, TokenPosition token_pos, const Function& function, intptr_t argument_count, const Array& argument_names, LocationSummary* locs, const ICData& ic_data_in) { const ICData& ic_data = ICData::ZoneHandle(ic_data_in.Original()); const Array& arguments_descriptor = Array::ZoneHandle( ic_data.IsNull() ? ArgumentsDescriptor::New(argument_count, argument_names) : ic_data.arguments_descriptor()); if (is_optimizing()) { EmitOptimizedStaticCall(function, arguments_descriptor, argument_count, deopt_id, token_pos, locs); } else { ICData& call_ic_data = ICData::ZoneHandle(ic_data.raw()); if (call_ic_data.IsNull()) { const intptr_t kNumArgsChecked = 0; call_ic_data = GetOrAddStaticCallICData(deopt_id, function, arguments_descriptor, kNumArgsChecked)->raw(); } EmitUnoptimizedStaticCall(argument_count, deopt_id, token_pos, locs, call_ic_data); } } void FlowGraphCompiler::GenerateNumberTypeCheck(Register kClassIdReg, const AbstractType& type, Label* is_instance_lbl, Label* is_not_instance_lbl) { assembler()->Comment("NumberTypeCheck"); GrowableArray<intptr_t> args; if (type.IsNumberType()) { args.Add(kDoubleCid); args.Add(kMintCid); args.Add(kBigintCid); } else if (type.IsIntType()) { args.Add(kMintCid); args.Add(kBigintCid); } else if (type.IsDoubleType()) { args.Add(kDoubleCid); } CheckClassIds(kClassIdReg, args, is_instance_lbl, is_not_instance_lbl); } void FlowGraphCompiler::GenerateStringTypeCheck(Register kClassIdReg, Label* is_instance_lbl, Label* is_not_instance_lbl) { assembler()->Comment("StringTypeCheck"); GrowableArray<intptr_t> args; args.Add(kOneByteStringCid); args.Add(kTwoByteStringCid); args.Add(kExternalOneByteStringCid); args.Add(kExternalTwoByteStringCid); CheckClassIds(kClassIdReg, args, is_instance_lbl, is_not_instance_lbl); } void FlowGraphCompiler::GenerateListTypeCheck(Register kClassIdReg, Label* is_instance_lbl) { assembler()->Comment("ListTypeCheck"); Label unknown; GrowableArray<intptr_t> args; args.Add(kArrayCid); args.Add(kGrowableObjectArrayCid); args.Add(kImmutableArrayCid); CheckClassIds(kClassIdReg, args, is_instance_lbl, &unknown); assembler()->Bind(&unknown); } void FlowGraphCompiler::EmitComment(Instruction* instr) { if (!FLAG_support_il_printer || !FLAG_support_disassembler) { return; } #ifndef PRODUCT char buffer[256]; BufferFormatter f(buffer, sizeof(buffer)); instr->PrintTo(&f); assembler()->Comment("%s", buffer); #endif } bool FlowGraphCompiler::NeedsEdgeCounter(TargetEntryInstr* block) { // Only emit an edge counter if there is not goto at the end of the block, // except for the entry block. return (FLAG_reorder_basic_blocks && (!block->last_instruction()->IsGoto() || (block == flow_graph().graph_entry()->normal_entry()))); } // Allocate a register that is not explicitly blocked. static Register AllocateFreeRegister(bool* blocked_registers) { for (intptr_t regno = 0; regno < kNumberOfCpuRegisters; regno++) { if (!blocked_registers[regno]) { blocked_registers[regno] = true; return static_cast<Register>(regno); } } UNREACHABLE(); return kNoRegister; } static uword RegMaskBit(Register reg) { return ((reg) != kNoRegister) ? (1 << (reg)) : 0; } void FlowGraphCompiler::AllocateRegistersLocally(Instruction* instr) { ASSERT(!is_optimizing()); instr->InitializeLocationSummary(zone(), false); // Not optimizing. LocationSummary* locs = instr->locs(); bool blocked_registers[kNumberOfCpuRegisters]; // Block all registers globally reserved by the assembler, etc and mark // the rest as free. for (intptr_t i = 0; i < kNumberOfCpuRegisters; i++) { blocked_registers[i] = (kDartAvailableCpuRegs & (1 << i)) == 0; } // Mark all fixed input, temp and output registers as used. for (intptr_t i = 0; i < locs->input_count(); i++) { Location loc = locs->in(i); if (loc.IsRegister()) { // Check that a register is not specified twice in the summary. ASSERT(!blocked_registers[loc.reg()]); blocked_registers[loc.reg()] = true; } } for (intptr_t i = 0; i < locs->temp_count(); i++) { Location loc = locs->temp(i); if (loc.IsRegister()) { // Check that a register is not specified twice in the summary. ASSERT(!blocked_registers[loc.reg()]); blocked_registers[loc.reg()] = true; } } if (locs->out(0).IsRegister()) { // Fixed output registers are allowed to overlap with // temps and inputs. blocked_registers[locs->out(0).reg()] = true; } // Allocate all unallocated input locations. const bool should_pop = !instr->IsPushArgument() && !instr->IsPushTemp(); for (intptr_t i = locs->input_count() - 1; i >= 0; i--) { Location loc = locs->in(i); Register reg = kNoRegister; if (loc.IsRegister()) { reg = loc.reg(); } else if (loc.IsUnallocated() || loc.IsConstant()) { ASSERT(loc.IsConstant() || ((loc.policy() == Location::kRequiresRegister) || (loc.policy() == Location::kWritableRegister) || (loc.policy() == Location::kAny))); reg = AllocateFreeRegister(blocked_registers); locs->set_in(i, Location::RegisterLocation(reg)); } ASSERT(reg != kNoRegister); // Inputs are consumed from the simulated frame. In case of a call argument // we leave it until the call instruction. if (should_pop) { assembler()->PopRegister(reg); } } // Allocate all unallocated temp locations. for (intptr_t i = 0; i < locs->temp_count(); i++) { Location loc = locs->temp(i); if (loc.IsUnallocated()) { ASSERT(loc.policy() == Location::kRequiresRegister); loc = Location::RegisterLocation( AllocateFreeRegister(blocked_registers)); locs->set_temp(i, loc); } } Location result_location = locs->out(0); if (result_location.IsUnallocated()) { switch (result_location.policy()) { case Location::kAny: case Location::kPrefersRegister: case Location::kRequiresRegister: case Location::kWritableRegister: result_location = Location::RegisterLocation( AllocateFreeRegister(blocked_registers)); break; case Location::kSameAsFirstInput: result_location = locs->in(0); break; case Location::kRequiresFpuRegister: UNREACHABLE(); break; } locs->set_out(0, result_location); } } ParallelMoveResolver::ParallelMoveResolver(FlowGraphCompiler* compiler) : compiler_(compiler), moves_(32) {} void ParallelMoveResolver::EmitNativeCode(ParallelMoveInstr* parallel_move) { ASSERT(moves_.is_empty()); // Build up a worklist of moves. BuildInitialMoveList(parallel_move); for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& move = *moves_[i]; // Skip constants to perform them last. They don't block other moves // and skipping such moves with register destinations keeps those // registers free for the whole algorithm. if (!move.IsEliminated() && !move.src().IsConstant()) PerformMove(i); } // Perform the moves with constant sources. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& move = *moves_[i]; if (!move.IsEliminated()) { ASSERT(move.src().IsConstant()); compiler_->BeginCodeSourceRange(); EmitMove(i); compiler_->EndCodeSourceRange(TokenPosition::kParallelMove); } } moves_.Clear(); } void ParallelMoveResolver::BuildInitialMoveList( ParallelMoveInstr* parallel_move) { // Perform a linear sweep of the moves to add them to the initial list of // moves to perform, ignoring any move that is redundant (the source is // the same as the destination, the destination is ignored and // unallocated, or the move was already eliminated). for (int i = 0; i < parallel_move->NumMoves(); i++) { MoveOperands* move = parallel_move->MoveOperandsAt(i); if (!move->IsRedundant()) moves_.Add(move); } } void ParallelMoveResolver::PerformMove(int index) { // Each call to this function performs a move and deletes it from the move // graph. We first recursively perform any move blocking this one. We // mark a move as "pending" on entry to PerformMove in order to detect // cycles in the move graph. We use operand swaps to resolve cycles, // which means that a call to PerformMove could change any source operand // in the move graph. ASSERT(!moves_[index]->IsPending()); ASSERT(!moves_[index]->IsRedundant()); // Clear this move's destination to indicate a pending move. The actual // destination is saved in a stack-allocated local. Recursion may allow // multiple moves to be pending. ASSERT(!moves_[index]->src().IsInvalid()); Location destination = moves_[index]->MarkPending(); // Perform a depth-first traversal of the move graph to resolve // dependencies. Any unperformed, unpending move with a source the same // as this one's destination blocks this one so recursively perform all // such moves. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& other_move = *moves_[i]; if (other_move.Blocks(destination) && !other_move.IsPending()) { // Though PerformMove can change any source operand in the move graph, // this call cannot create a blocking move via a swap (this loop does // not miss any). Assume there is a non-blocking move with source A // and this move is blocked on source B and there is a swap of A and // B. Then A and B must be involved in the same cycle (or they would // not be swapped). Since this move's destination is B and there is // only a single incoming edge to an operand, this move must also be // involved in the same cycle. In that case, the blocking move will // be created but will be "pending" when we return from PerformMove. PerformMove(i); } } // We are about to resolve this move and don't need it marked as // pending, so restore its destination. moves_[index]->ClearPending(destination); // This move's source may have changed due to swaps to resolve cycles and // so it may now be the last move in the cycle. If so remove it. if (moves_[index]->src().Equals(destination)) { moves_[index]->Eliminate(); return; } // The move may be blocked on a (at most one) pending move, in which case // we have a cycle. Search for such a blocking move and perform a swap to // resolve it. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& other_move = *moves_[i]; if (other_move.Blocks(destination)) { ASSERT(other_move.IsPending()); compiler_->BeginCodeSourceRange(); EmitSwap(index); compiler_->EndCodeSourceRange(TokenPosition::kParallelMove); return; } } // This move is not blocked. compiler_->BeginCodeSourceRange(); EmitMove(index); compiler_->EndCodeSourceRange(TokenPosition::kParallelMove); } bool ParallelMoveResolver::IsScratchLocation(Location loc) { for (int i = 0; i < moves_.length(); ++i) { if (moves_[i]->Blocks(loc)) { return false; } } for (int i = 0; i < moves_.length(); ++i) { if (moves_[i]->dest().Equals(loc)) { return true; } } return false; } intptr_t ParallelMoveResolver::AllocateScratchRegister( Location::Kind kind, uword blocked_mask, intptr_t first_free_register, intptr_t last_free_register, bool* spilled) { COMPILE_ASSERT(static_cast<intptr_t>(sizeof(blocked_mask)) * kBitsPerByte >= kNumberOfFpuRegisters); COMPILE_ASSERT(static_cast<intptr_t>(sizeof(blocked_mask)) * kBitsPerByte >= kNumberOfCpuRegisters); intptr_t scratch = -1; for (intptr_t reg = first_free_register; reg <= last_free_register; reg++) { if ((((1 << reg) & blocked_mask) == 0) && IsScratchLocation(Location::MachineRegisterLocation(kind, reg))) { scratch = reg; break; } } if (scratch == -1) { *spilled = true; for (intptr_t reg = first_free_register; reg <= last_free_register; reg++) { if (((1 << reg) & blocked_mask) == 0) { scratch = reg; break; } } } else { *spilled = false; } return scratch; } ParallelMoveResolver::ScratchFpuRegisterScope::ScratchFpuRegisterScope( ParallelMoveResolver* resolver, FpuRegister blocked) : resolver_(resolver), reg_(kNoFpuRegister), spilled_(false) { COMPILE_ASSERT(FpuTMP != kNoFpuRegister); uword blocked_mask = ((blocked != kNoFpuRegister) ? 1 << blocked : 0) | 1 << FpuTMP; reg_ = static_cast<FpuRegister>( resolver_->AllocateScratchRegister(Location::kFpuRegister, blocked_mask, 0, kNumberOfFpuRegisters - 1, &spilled_)); if (spilled_) { resolver->SpillFpuScratch(reg_); } } ParallelMoveResolver::ScratchFpuRegisterScope::~ScratchFpuRegisterScope() { if (spilled_) { resolver_->RestoreFpuScratch(reg_); } } ParallelMoveResolver::ScratchRegisterScope::ScratchRegisterScope( ParallelMoveResolver* resolver, Register blocked) : resolver_(resolver), reg_(kNoRegister), spilled_(false) { uword blocked_mask = RegMaskBit(blocked) | kReservedCpuRegisters; if (resolver->compiler_->intrinsic_mode()) { // Block additional registers that must be preserved for intrinsics. blocked_mask |= RegMaskBit(ARGS_DESC_REG); #if !defined(TARGET_ARCH_IA32) // Need to preserve CODE_REG to be able to store the PC marker // and load the pool pointer. blocked_mask |= RegMaskBit(CODE_REG); #endif } reg_ = static_cast<Register>( resolver_->AllocateScratchRegister(Location::kRegister, blocked_mask, 0, kNumberOfCpuRegisters - 1, &spilled_)); if (spilled_) { resolver->SpillScratch(reg_); } } ParallelMoveResolver::ScratchRegisterScope::~ScratchRegisterScope() { if (spilled_) { resolver_->RestoreScratch(reg_); } } static int HighestCountFirst(const CidTarget* a, const CidTarget* b) { // Negative if 'a' should sort before 'b'. return b->count - a->count; } // Returns 'sorted' array in decreasing count order. // The expected number of elements to sort is less than 10. void FlowGraphCompiler::SortICDataByCount(const ICData& ic_data, GrowableArray<CidTarget>* sorted, bool drop_smi) { ASSERT(ic_data.NumArgsTested() == 1); const intptr_t len = ic_data.NumberOfChecks(); sorted->Clear(); for (int i = 0; i < len; i++) { intptr_t receiver_cid = ic_data.GetReceiverClassIdAt(i); if (drop_smi && (receiver_cid == kSmiCid)) continue; sorted->Add(CidTarget(receiver_cid, &Function::ZoneHandle(ic_data.GetTargetAt(i)), ic_data.GetCountAt(i))); } sorted->Sort(HighestCountFirst); } const ICData* FlowGraphCompiler::GetOrAddInstanceCallICData( intptr_t deopt_id, const String& target_name, const Array& arguments_descriptor, intptr_t num_args_tested) { if ((deopt_id_to_ic_data_ != NULL) && ((*deopt_id_to_ic_data_)[deopt_id] != NULL)) { const ICData* res = (*deopt_id_to_ic_data_)[deopt_id]; ASSERT(res->deopt_id() == deopt_id); ASSERT(res->target_name() == target_name.raw()); ASSERT(res->NumArgsTested() == num_args_tested); return res; } const ICData& ic_data = ICData::ZoneHandle(zone(), ICData::New( parsed_function().function(), target_name, arguments_descriptor, deopt_id, num_args_tested)); if (deopt_id_to_ic_data_ != NULL) { (*deopt_id_to_ic_data_)[deopt_id] = &ic_data; } return &ic_data; } const ICData* FlowGraphCompiler::GetOrAddStaticCallICData( intptr_t deopt_id, const Function& target, const Array& arguments_descriptor, intptr_t num_args_tested) { if ((deopt_id_to_ic_data_ != NULL) && ((*deopt_id_to_ic_data_)[deopt_id] != NULL)) { const ICData* res = (*deopt_id_to_ic_data_)[deopt_id]; ASSERT(res->deopt_id() == deopt_id); ASSERT(res->target_name() == target.name()); ASSERT(res->NumArgsTested() == num_args_tested); return res; } const ICData& ic_data = ICData::ZoneHandle(zone(), ICData::New( parsed_function().function(), String::Handle(zone(), target.name()), arguments_descriptor, deopt_id, num_args_tested)); ic_data.AddTarget(target); if (deopt_id_to_ic_data_ != NULL) { (*deopt_id_to_ic_data_)[deopt_id] = &ic_data; } return &ic_data; } intptr_t FlowGraphCompiler::GetOptimizationThreshold() const { intptr_t threshold; if (is_optimizing()) { threshold = FLAG_reoptimization_counter_threshold; } else if (parsed_function_.function().IsIrregexpFunction()) { threshold = FLAG_regexp_optimization_counter_threshold; } else { const intptr_t basic_blocks = flow_graph().preorder().length(); ASSERT(basic_blocks > 0); threshold = FLAG_optimization_counter_scale * basic_blocks + FLAG_min_optimization_counter_threshold; if (threshold > FLAG_optimization_counter_threshold) { threshold = FLAG_optimization_counter_threshold; } } return threshold; } const Class& FlowGraphCompiler::BoxClassFor(Representation rep) { switch (rep) { case kUnboxedDouble: return double_class(); case kUnboxedFloat32x4: return float32x4_class(); case kUnboxedFloat64x2: return float64x2_class(); case kUnboxedInt32x4: return int32x4_class(); case kUnboxedMint: return mint_class(); default: UNREACHABLE(); return Class::ZoneHandle(); } } RawArray* FlowGraphCompiler::InliningIdToFunction() const { if (inline_id_to_function_.length() == 0) { return Object::empty_array().raw(); } const Array& res = Array::Handle( Array::New(inline_id_to_function_.length(), Heap::kOld)); for (intptr_t i = 0; i < inline_id_to_function_.length(); i++) { res.SetAt(i, *inline_id_to_function_[i]); } return res.raw(); } RawArray* FlowGraphCompiler::InliningIdToTokenPos() const { if (inline_id_to_token_pos_.length() == 0) { return Object::empty_array().raw(); } const Array& res = Array::Handle(zone(), Array::New(inline_id_to_token_pos_.length(), Heap::kOld)); Smi& smi = Smi::Handle(zone()); for (intptr_t i = 0; i < inline_id_to_token_pos_.length(); i++) { smi = Smi::New(inline_id_to_token_pos_[i].value()); res.SetAt(i, smi); } return res.raw(); } RawArray* FlowGraphCompiler::CallerInliningIdMap() const { if (caller_inline_id_.length() == 0) { return Object::empty_array().raw(); } const Array& res = Array::Handle( Array::New(caller_inline_id_.length(), Heap::kOld)); Smi& smi = Smi::Handle(); for (intptr_t i = 0; i < caller_inline_id_.length(); i++) { smi = Smi::New(caller_inline_id_[i]); res.SetAt(i, smi); } return res.raw(); } void FlowGraphCompiler::BeginCodeSourceRange() { NOT_IN_PRODUCT( // Remember how many bytes of code we emitted so far. This function // is called before we call into an instruction's EmitNativeCode. saved_code_size_ = assembler()->CodeSize(); ); } bool FlowGraphCompiler::EndCodeSourceRange(TokenPosition token_pos) { NOT_IN_PRODUCT( // This function is called after each instructions' EmitNativeCode. if (saved_code_size_ < assembler()->CodeSize()) { // We emitted more code, now associate the emitted code chunk with // |token_pos|. code_source_map_builder()->AddEntry(saved_code_size_, token_pos); BeginCodeSourceRange(); return true; } ); return false; } void FlowGraphCompiler::EmitPolymorphicInstanceCall( const ICData& ic_data, intptr_t argument_count, const Array& argument_names, intptr_t deopt_id, TokenPosition token_pos, LocationSummary* locs) { if (FLAG_polymorphic_with_deopt) { Label* deopt = AddDeoptStub(deopt_id, ICData::kDeoptPolymorphicInstanceCallTestFail); Label ok; EmitTestAndCall(ic_data, argument_count, argument_names, deopt, // No cid match. &ok, // Found cid. deopt_id, token_pos, locs); assembler()->Bind(&ok); } else { // Instead of deoptimizing, do a megamorphic call when no matching // cid found. Label ok; MegamorphicSlowPath* slow_path = new MegamorphicSlowPath(ic_data, argument_count, deopt_id, token_pos, locs, CurrentTryIndex()); AddSlowPathCode(slow_path); EmitTestAndCall(ic_data, argument_count, argument_names, slow_path->entry_label(), // No cid match. &ok, // Found cid. deopt_id, token_pos, locs); assembler()->Bind(slow_path->exit_label()); assembler()->Bind(&ok); } } #if defined(DEBUG) void FlowGraphCompiler::FrameStateUpdateWith(Instruction* instr) { ASSERT(!is_optimizing()); switch (instr->tag()) { case Instruction::kPushArgument: case Instruction::kPushTemp: // Do nothing. break; case Instruction::kDropTemps: FrameStatePop(instr->locs()->input_count() + instr->AsDropTemps()->num_temps()); break; default: FrameStatePop(instr->locs()->input_count()); break; } ASSERT(!instr->locs()->can_call() || FrameStateIsSafeToCall()); FrameStatePop(instr->ArgumentCount()); Definition* defn = instr->AsDefinition(); if ((defn != NULL) && defn->HasTemp()) { FrameStatePush(defn); } } void FlowGraphCompiler::FrameStatePush(Definition* defn) { Representation rep = defn->representation(); if ((rep == kUnboxedDouble) || (rep == kUnboxedFloat64x2) || (rep == kUnboxedFloat32x4)) { // LoadField instruction lies about its representation in the unoptimized // code because Definition::representation() can't depend on the type of // compilation but MakeLocationSummary and EmitNativeCode can. ASSERT(defn->IsLoadField() && defn->AsLoadField()->IsUnboxedLoad()); ASSERT(defn->locs()->out(0).IsRegister()); rep = kTagged; } ASSERT(!is_optimizing()); ASSERT((rep == kTagged) || (rep == kUntagged)); ASSERT(rep != kUntagged || flow_graph_.IsIrregexpFunction()); frame_state_.Add(rep); } void FlowGraphCompiler::FrameStatePop(intptr_t count) { ASSERT(!is_optimizing()); frame_state_.TruncateTo(Utils::Maximum(static_cast<intptr_t>(0), frame_state_.length() - count)); } bool FlowGraphCompiler::FrameStateIsSafeToCall() { ASSERT(!is_optimizing()); for (intptr_t i = 0; i < frame_state_.length(); i++) { if (frame_state_[i] != kTagged) { return false; } } return true; } void FlowGraphCompiler::FrameStateClear() { ASSERT(!is_optimizing()); frame_state_.TruncateTo(0); } #endif } // namespace dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" // Needed here to get TARGET_ARCH_XXX. #include "vm/flow_graph_compiler.h" #include "vm/cha.h" #include "vm/dart_entry.h" #include "vm/debugger.h" #include "vm/deopt_instructions.h" #include "vm/flow_graph_allocator.h" #include "vm/il_printer.h" #include "vm/intrinsifier.h" #include "vm/locations.h" #include "vm/longjump.h" #include "vm/object_store.h" #include "vm/parser.h" #include "vm/stub_code.h" #include "vm/symbols.h" namespace dart { DEFINE_FLAG(bool, print_scopes, false, "Print scopes of local variables."); DECLARE_FLAG(bool, code_comments); DECLARE_FLAG(bool, enable_type_checks); DECLARE_FLAG(bool, intrinsify); DECLARE_FLAG(bool, propagate_ic_data); DECLARE_FLAG(bool, report_usage_count); DECLARE_FLAG(int, optimization_counter_threshold); DECLARE_FLAG(bool, use_cha); void CompilerDeoptInfo::BuildReturnAddress(DeoptInfoBuilder* builder, const Function& function, intptr_t slot_ix) { builder->AddReturnAddressAfter(function, deopt_id(), slot_ix); } void CompilerDeoptInfoWithStub::BuildReturnAddress(DeoptInfoBuilder* builder, const Function& function, intptr_t slot_ix) { builder->AddReturnAddressBefore(function, deopt_id(), slot_ix); } // Assign locations to incoming arguments, i.e., values pushed above spill slots // with PushArgument. Recursively allocates from outermost to innermost // environment. void CompilerDeoptInfo::AllocateIncomingParametersRecursive( Environment* env, intptr_t* stack_height) { if (env == NULL) return; AllocateIncomingParametersRecursive(env->outer(), stack_height); for (Environment::ShallowIterator it(env); !it.Done(); it.Advance()) { if (it.CurrentLocation().IsInvalid()) { ASSERT(it.CurrentValue()->definition()->IsPushArgument()); it.SetCurrentLocation(Location::StackSlot((*stack_height)++)); } } } RawDeoptInfo* CompilerDeoptInfo::CreateDeoptInfo(FlowGraphCompiler* compiler, DeoptInfoBuilder* builder) { if (deoptimization_env_ == NULL) return DeoptInfo::null(); intptr_t stack_height = compiler->StackSize(); AllocateIncomingParametersRecursive(deoptimization_env_, &stack_height); intptr_t slot_ix = 0; Environment* current = deoptimization_env_; // For the innermost environment, call the virtual return builder. BuildReturnAddress(builder, current->function(), slot_ix++); // For the innermost environment, set outgoing arguments and the locals. for (intptr_t i = current->Length() - 1; i >= current->fixed_parameter_count(); i--) { builder->AddCopy(current->LocationAt(i), *current->ValueAt(i), slot_ix++); } // PC marker and caller FP. builder->AddPcMarker(current->function(), slot_ix++); builder->AddCallerFp(slot_ix++); Environment* previous = current; current = current->outer(); while (current != NULL) { // For any outer environment the deopt id is that of the call instruction // which is recorded in the outer environment. builder->AddReturnAddressAfter(current->function(), current->deopt_id(), slot_ix++); // The values of outgoing arguments can be changed from the inlined call so // we must read them from the previous environment. for (intptr_t i = previous->fixed_parameter_count() - 1; i >= 0; i--) { builder->AddCopy(previous->LocationAt(i), *previous->ValueAt(i), slot_ix++); } // Set the locals, note that outgoing arguments are not in the environment. for (intptr_t i = current->Length() - 1; i >= current->fixed_parameter_count(); i--) { builder->AddCopy(current->LocationAt(i), *current->ValueAt(i), slot_ix++); } // PC marker and caller FP. builder->AddPcMarker(current->function(), slot_ix++); builder->AddCallerFp(slot_ix++); // Iterate on the outer environment. previous = current; current = current->outer(); } // The previous pointer is now the outermost environment. ASSERT(previous != NULL); // For the outermost environment, set caller PC. builder->AddCallerPc(slot_ix++); // For the outermost environment, set the incoming arguments. for (intptr_t i = previous->fixed_parameter_count() - 1; i >= 0; i--) { builder->AddCopy(previous->LocationAt(i), *previous->ValueAt(i), slot_ix++); } const DeoptInfo& deopt_info = DeoptInfo::Handle(builder->CreateDeoptInfo()); return deopt_info.raw(); } FlowGraphCompiler::FlowGraphCompiler(Assembler* assembler, const FlowGraph& flow_graph, bool is_optimizing) : assembler_(assembler), parsed_function_(flow_graph.parsed_function()), block_order_(flow_graph.reverse_postorder()), current_block_(NULL), exception_handlers_list_(NULL), pc_descriptors_list_(NULL), stackmap_table_builder_( is_optimizing ? new StackmapTableBuilder() : NULL), block_info_(block_order_.length()), deopt_infos_(), static_calls_target_table_(GrowableObjectArray::ZoneHandle( GrowableObjectArray::New())), is_optimizing_(is_optimizing), may_reoptimize_(false), bool_true_(Bool::ZoneHandle(Bool::True())), bool_false_(Bool::ZoneHandle(Bool::False())), double_class_(Class::ZoneHandle( Isolate::Current()->object_store()->double_class())), parallel_move_resolver_(this) { ASSERT(assembler != NULL); } FlowGraphCompiler::~FlowGraphCompiler() { // BlockInfos are zone-allocated, so their destructors are not called. // Verify the labels explicitly here. for (int i = 0; i < block_info_.length(); ++i) { ASSERT(!block_info_[i]->label.IsLinked()); ASSERT(!block_info_[i]->label.HasNear()); } } bool FlowGraphCompiler::HasFinally() const { return parsed_function().function().has_finally(); } void FlowGraphCompiler::InitCompiler() { pc_descriptors_list_ = new DescriptorList(64); exception_handlers_list_ = new ExceptionHandlerList(); block_info_.Clear(); for (int i = 0; i < block_order_.length(); ++i) { block_info_.Add(new BlockInfo()); } } bool FlowGraphCompiler::CanOptimize() { return !FLAG_report_usage_count && (FLAG_optimization_counter_threshold >= 0) && !Isolate::Current()->debugger()->IsActive(); } void FlowGraphCompiler::VisitBlocks() { for (intptr_t i = 0; i < block_order().length(); ++i) { // Compile the block entry. BlockEntryInstr* entry = block_order()[i]; assembler()->Comment("B%"Pd"", entry->block_id()); set_current_block(entry); entry->PrepareEntry(this); // Compile all successors until an exit, branch, or a block entry. for (ForwardInstructionIterator it(entry); !it.Done(); it.Advance()) { Instruction* instr = it.Current(); if (FLAG_code_comments) EmitComment(instr); if (instr->IsParallelMove()) { parallel_move_resolver_.EmitNativeCode(instr->AsParallelMove()); } else { ASSERT(instr->locs() != NULL); EmitInstructionPrologue(instr); pending_deoptimization_env_ = instr->env(); instr->EmitNativeCode(this); EmitInstructionEpilogue(instr); } } } set_current_block(NULL); } void FlowGraphCompiler::Bailout(const char* reason) { const char* kFormat = "FlowGraphCompiler Bailout: %s %s."; const char* function_name = parsed_function().function().ToCString(); intptr_t len = OS::SNPrint(NULL, 0, kFormat, function_name, reason) + 1; char* chars = Isolate::Current()->current_zone()->Alloc<char>(len); OS::SNPrint(chars, len, kFormat, function_name, reason); const Error& error = Error::Handle( LanguageError::New(String::Handle(String::New(chars)))); Isolate::Current()->long_jump_base()->Jump(1, error); } intptr_t FlowGraphCompiler::StackSize() const { if (is_optimizing_) { return block_order_[0]->AsGraphEntry()->spill_slot_count(); } else { return parsed_function_.num_stack_locals() + parsed_function_.num_copied_params(); } } Label* FlowGraphCompiler::GetBlockLabel( BlockEntryInstr* block_entry) const { intptr_t block_index = block_entry->postorder_number(); return &block_info_[block_index]->label; } bool FlowGraphCompiler::IsNextBlock(BlockEntryInstr* block_entry) const { intptr_t current_index = reverse_index(current_block()->postorder_number()); return (current_index < (block_order().length() - 1)) && (block_order()[current_index + 1] == block_entry); } void FlowGraphCompiler::AddSlowPathCode(SlowPathCode* code) { slow_path_code_.Add(code); } void FlowGraphCompiler::GenerateDeferredCode() { for (intptr_t i = 0; i < slow_path_code_.length(); i++) { slow_path_code_[i]->EmitNativeCode(this); } for (intptr_t i = 0; i < deopt_infos_.length(); i++) { deopt_infos_[i]->GenerateCode(this, i); } } void FlowGraphCompiler::AddExceptionHandler(intptr_t try_index, intptr_t pc_offset) { exception_handlers_list_->AddHandler(try_index, pc_offset); } // Uses current pc position and try-index. void FlowGraphCompiler::AddCurrentDescriptor(PcDescriptors::Kind kind, intptr_t deopt_id, intptr_t token_pos) { pc_descriptors_list()->AddDescriptor(kind, assembler()->CodeSize(), deopt_id, token_pos, CurrentTryIndex()); } void FlowGraphCompiler::AddStaticCallTarget(const Function& func) { ASSERT(Code::kSCallTableEntryLength == 3); ASSERT(Code::kSCallTableOffsetEntry == 0); static_calls_target_table_.Add( Smi::Handle(Smi::New(assembler()->CodeSize()))); ASSERT(Code::kSCallTableFunctionEntry == 1); static_calls_target_table_.Add(func); ASSERT(Code::kSCallTableCodeEntry == 2); static_calls_target_table_.Add(Code::Handle()); } void FlowGraphCompiler::AddDeoptIndexAtCall(intptr_t deopt_id, intptr_t token_pos) { ASSERT(is_optimizing()); CompilerDeoptInfo* info = new CompilerDeoptInfo(deopt_id, kDeoptAtCall); ASSERT(pending_deoptimization_env_ != NULL); info->set_deoptimization_env(pending_deoptimization_env_); info->set_pc_offset(assembler()->CodeSize()); deopt_infos_.Add(info); } void FlowGraphCompiler::RecordSafepoint(LocationSummary* locs) { if (is_optimizing()) { BitmapBuilder* bitmap = locs->stack_bitmap(); ASSERT(bitmap != NULL); ASSERT(bitmap->Length() <= StackSize()); // Pad the bitmap out to describe all the spill slots. bitmap->SetLength(StackSize()); // Mark the bits in the stack map in the same order we push registers in // slow path code (see FlowGraphCompiler::SaveLiveRegisters). // // Slow path code can have registers at the safepoint. if (!locs->always_calls()) { RegisterSet* regs = locs->live_registers(); if (regs->xmm_regs_count() > 0) { // Denote XMM registers with 0 bits in the stackmap. Based on the // assumption that there are normally few live XMM registers, this // encoding is simpler and roughly as compact as storing a separate // count of XMM registers. // // XMM registers have the highest register number at the highest // address (i.e., first in the stackmap). for (intptr_t i = kNumberOfXmmRegisters - 1; i >= 0; --i) { XmmRegister reg = static_cast<XmmRegister>(i); if (regs->ContainsXmmRegister(reg)) { for (intptr_t j = 0; j < FlowGraphAllocator::kDoubleSpillSlotFactor; ++j) { bitmap->Set(bitmap->Length(), false); } } } } // General purpose registers have the lowest register number at the // highest address (i.e., first in the stackmap). for (intptr_t i = 0; i < kNumberOfCpuRegisters; ++i) { Register reg = static_cast<Register>(i); if (locs->live_registers()->ContainsRegister(reg)) { bitmap->Set(bitmap->Length(), true); } } } intptr_t register_bit_count = bitmap->Length() - StackSize(); stackmap_table_builder_->AddEntry(assembler()->CodeSize(), bitmap, register_bit_count); } } Label* FlowGraphCompiler::AddDeoptStub(intptr_t deopt_id, DeoptReasonId reason) { CompilerDeoptInfoWithStub* stub = new CompilerDeoptInfoWithStub(deopt_id, reason); ASSERT(is_optimizing_); ASSERT(pending_deoptimization_env_ != NULL); stub->set_deoptimization_env(pending_deoptimization_env_); deopt_infos_.Add(stub); return stub->entry_label(); } void FlowGraphCompiler::FinalizeExceptionHandlers(const Code& code) { ASSERT(exception_handlers_list_ != NULL); const ExceptionHandlers& handlers = ExceptionHandlers::Handle( exception_handlers_list_->FinalizeExceptionHandlers(code.EntryPoint())); code.set_exception_handlers(handlers); } void FlowGraphCompiler::FinalizePcDescriptors(const Code& code) { ASSERT(pc_descriptors_list_ != NULL); const PcDescriptors& descriptors = PcDescriptors::Handle( pc_descriptors_list_->FinalizePcDescriptors(code.EntryPoint())); if (!is_optimizing_) descriptors.Verify(parsed_function_.function()); code.set_pc_descriptors(descriptors); } void FlowGraphCompiler::FinalizeDeoptInfo(const Code& code) { // For functions with optional arguments, all incoming arguments are copied // to spill slots. The deoptimization environment does not track them. const Function& function = parsed_function().function(); const intptr_t incoming_arg_count = function.HasOptionalParameters() ? 0 : function.num_fixed_parameters(); DeoptInfoBuilder builder(incoming_arg_count); const Array& array = Array::Handle(Array::New(DeoptTable::SizeFor(deopt_infos_.length()), Heap::kOld)); Smi& offset = Smi::Handle(); DeoptInfo& info = DeoptInfo::Handle(); Smi& reason = Smi::Handle(); for (intptr_t i = 0; i < deopt_infos_.length(); i++) { offset = Smi::New(deopt_infos_[i]->pc_offset()); info = deopt_infos_[i]->CreateDeoptInfo(this, &builder); reason = Smi::New(deopt_infos_[i]->reason()); DeoptTable::SetEntry(array, i, offset, info, reason); } code.set_deopt_info_array(array); const Array& object_array = Array::Handle(Array::MakeArray(builder.object_table())); ASSERT(code.object_table() == Array::null()); code.set_object_table(object_array); } void FlowGraphCompiler::FinalizeStackmaps(const Code& code) { if (stackmap_table_builder_ == NULL) { // The unoptimizing compiler has no stack maps. code.set_stackmaps(Array::Handle()); } else { // Finalize the stack map array and add it to the code object. ASSERT(is_optimizing()); code.set_stackmaps( Array::Handle(stackmap_table_builder_->FinalizeStackmaps(code))); } } void FlowGraphCompiler::FinalizeVarDescriptors(const Code& code) { const LocalVarDescriptors& var_descs = LocalVarDescriptors::Handle( parsed_function_.node_sequence()->scope()->GetVarDescriptors( parsed_function_.function())); code.set_var_descriptors(var_descs); } void FlowGraphCompiler::FinalizeComments(const Code& code) { code.set_comments(assembler()->GetCodeComments()); } void FlowGraphCompiler::FinalizeStaticCallTargetsTable(const Code& code) { ASSERT(code.static_calls_target_table() == Array::null()); code.set_static_calls_target_table( Array::Handle(Array::MakeArray(static_calls_target_table_))); } // Returns 'true' if code generation for this function is complete, i.e., // no fall-through to regular code is needed. bool FlowGraphCompiler::TryIntrinsify() { if (!CanOptimize()) return false; // Intrinsification skips arguments checks, therefore disable if in checked // mode. if (FLAG_intrinsify && !FLAG_enable_type_checks) { if (parsed_function().function().kind() == RawFunction::kImplicitGetter) { // An implicit getter must have a specific AST structure. const SequenceNode& sequence_node = *parsed_function().node_sequence(); ASSERT(sequence_node.length() == 1); ASSERT(sequence_node.NodeAt(0)->IsReturnNode()); const ReturnNode& return_node = *sequence_node.NodeAt(0)->AsReturnNode(); ASSERT(return_node.value()->IsLoadInstanceFieldNode()); const LoadInstanceFieldNode& load_node = *return_node.value()->AsLoadInstanceFieldNode(); GenerateInlinedGetter(load_node.field().Offset()); return true; } if (parsed_function().function().kind() == RawFunction::kImplicitSetter) { // An implicit setter must have a specific AST structure. // Sequence node has one store node and one return NULL node. const SequenceNode& sequence_node = *parsed_function().node_sequence(); ASSERT(sequence_node.length() == 2); ASSERT(sequence_node.NodeAt(0)->IsStoreInstanceFieldNode()); ASSERT(sequence_node.NodeAt(1)->IsReturnNode()); const StoreInstanceFieldNode& store_node = *sequence_node.NodeAt(0)->AsStoreInstanceFieldNode(); GenerateInlinedSetter(store_node.field().Offset()); return true; } } // Even if an intrinsified version of the function was successfully // generated, it may fall through to the non-intrinsified method body. return Intrinsifier::Intrinsify(parsed_function().function(), assembler()); } void FlowGraphCompiler::GenerateInstanceCall( intptr_t deopt_id, intptr_t token_pos, intptr_t argument_count, const Array& argument_names, LocationSummary* locs, const ICData& ic_data) { ASSERT(!ic_data.IsNull()); ASSERT(FLAG_propagate_ic_data || (ic_data.NumberOfChecks() == 0)); const Array& arguments_descriptor = Array::ZoneHandle(ArgumentsDescriptor::New(argument_count, argument_names)); uword label_address = 0; if (is_optimizing() && (ic_data.NumberOfChecks() == 0)) { if (ic_data.is_closure_call()) { // This IC call may be closure call only. label_address = StubCode::ClosureCallInlineCacheEntryPoint(); ExternalLabel target_label("InlineCache", label_address); EmitInstanceCall(&target_label, ICData::ZoneHandle(ic_data.AsUnaryClassChecks()), arguments_descriptor, argument_count, deopt_id, token_pos, locs); return; } // Emit IC call that will count and thus may need reoptimization at // return instruction. may_reoptimize_ = true; switch (ic_data.num_args_tested()) { case 1: label_address = StubCode::OneArgOptimizedCheckInlineCacheEntryPoint(); break; case 2: label_address = StubCode::TwoArgsOptimizedCheckInlineCacheEntryPoint(); break; case 3: label_address = StubCode::ThreeArgsOptimizedCheckInlineCacheEntryPoint(); break; default: UNIMPLEMENTED(); } ExternalLabel target_label("InlineCache", label_address); EmitOptimizedInstanceCall(&target_label, ic_data, arguments_descriptor, argument_count, deopt_id, token_pos, locs); return; } if (is_optimizing()) { EmitMegamorphicInstanceCall(ic_data, arguments_descriptor, argument_count, deopt_id, token_pos, locs); return; } switch (ic_data.num_args_tested()) { case 1: label_address = StubCode::OneArgCheckInlineCacheEntryPoint(); break; case 2: label_address = StubCode::TwoArgsCheckInlineCacheEntryPoint(); break; case 3: label_address = StubCode::ThreeArgsCheckInlineCacheEntryPoint(); break; default: UNIMPLEMENTED(); } ExternalLabel target_label("InlineCache", label_address); EmitInstanceCall(&target_label, ic_data, arguments_descriptor, argument_count, deopt_id, token_pos, locs); } void FlowGraphCompiler::GenerateStaticCall(intptr_t deopt_id, intptr_t token_pos, const Function& function, intptr_t argument_count, const Array& argument_names, LocationSummary* locs) { const Array& arguments_descriptor = Array::ZoneHandle(ArgumentsDescriptor::New(argument_count, argument_names)); EmitStaticCall(function, arguments_descriptor, argument_count, deopt_id, token_pos, locs); } void FlowGraphCompiler::GenerateNumberTypeCheck(Register kClassIdReg, const AbstractType& type, Label* is_instance_lbl, Label* is_not_instance_lbl) { assembler()->Comment("NumberTypeCheck"); GrowableArray<intptr_t> args; if (type.IsNumberType()) { args.Add(kDoubleCid); args.Add(kMintCid); args.Add(kBigintCid); } else if (type.IsIntType()) { args.Add(kMintCid); args.Add(kBigintCid); } else if (type.IsDoubleType()) { args.Add(kDoubleCid); } CheckClassIds(kClassIdReg, args, is_instance_lbl, is_not_instance_lbl); } void FlowGraphCompiler::GenerateStringTypeCheck(Register kClassIdReg, Label* is_instance_lbl, Label* is_not_instance_lbl) { assembler()->Comment("StringTypeCheck"); GrowableArray<intptr_t> args; args.Add(kOneByteStringCid); args.Add(kTwoByteStringCid); args.Add(kExternalOneByteStringCid); args.Add(kExternalTwoByteStringCid); CheckClassIds(kClassIdReg, args, is_instance_lbl, is_not_instance_lbl); } void FlowGraphCompiler::GenerateListTypeCheck(Register kClassIdReg, Label* is_instance_lbl) { assembler()->Comment("ListTypeCheck"); Label unknown; GrowableArray<intptr_t> args; args.Add(kArrayCid); args.Add(kGrowableObjectArrayCid); args.Add(kImmutableArrayCid); CheckClassIds(kClassIdReg, args, is_instance_lbl, &unknown); assembler()->Bind(&unknown); } void FlowGraphCompiler::EmitComment(Instruction* instr) { char buffer[256]; BufferFormatter f(buffer, sizeof(buffer)); instr->PrintTo(&f); assembler()->Comment("%s", buffer); } void FlowGraphCompiler::EmitTestAndCall(const ICData& ic_data, Register class_id_reg, intptr_t arg_count, const Array& arg_names, Label* deopt, intptr_t deopt_id, intptr_t token_index, LocationSummary* locs) { ASSERT(!ic_data.IsNull() && (ic_data.NumberOfChecks() > 0)); Label match_found; const intptr_t len = ic_data.NumberOfChecks(); for (intptr_t i = 0; i < len; i++) { const bool is_last_check = (i == (len - 1)); Label next_test; assembler()->cmpl(class_id_reg, Immediate(ic_data.GetReceiverClassIdAt(i))); if (is_last_check) { assembler()->j(NOT_EQUAL, deopt); } else { assembler()->j(NOT_EQUAL, &next_test); } const Function& target = Function::ZoneHandle(ic_data.GetTargetAt(i)); GenerateStaticCall(deopt_id, token_index, target, arg_count, arg_names, locs); if (!is_last_check) { assembler()->jmp(&match_found); } assembler()->Bind(&next_test); } assembler()->Bind(&match_found); } void FlowGraphCompiler::EmitDoubleCompareBranch(Condition true_condition, XmmRegister left, XmmRegister right, BranchInstr* branch) { ASSERT(branch != NULL); assembler()->comisd(left, right); BlockEntryInstr* nan_result = (true_condition == NOT_EQUAL) ? branch->true_successor() : branch->false_successor(); assembler()->j(PARITY_EVEN, GetBlockLabel(nan_result)); branch->EmitBranchOnCondition(this, true_condition); } void FlowGraphCompiler::EmitDoubleCompareBool(Condition true_condition, XmmRegister left, XmmRegister right, Register result) { assembler()->comisd(left, right); Label is_false, is_true, done; assembler()->j(PARITY_EVEN, &is_false, Assembler::kNearJump); // NaN false; assembler()->j(true_condition, &is_true, Assembler::kNearJump); assembler()->Bind(&is_false); assembler()->LoadObject(result, bool_false()); assembler()->jmp(&done); assembler()->Bind(&is_true); assembler()->LoadObject(result, bool_true()); assembler()->Bind(&done); } // Allocate a register that is not explicitly blocked. static Register AllocateFreeRegister(bool* blocked_registers) { for (intptr_t regno = 0; regno < kNumberOfCpuRegisters; regno++) { if (!blocked_registers[regno]) { blocked_registers[regno] = true; return static_cast<Register>(regno); } } UNREACHABLE(); return kNoRegister; } void FlowGraphCompiler::AllocateRegistersLocally(Instruction* instr) { ASSERT(!is_optimizing()); LocationSummary* locs = instr->locs(); bool blocked_registers[kNumberOfCpuRegisters]; // Mark all available registers free. for (intptr_t i = 0; i < kNumberOfCpuRegisters; i++) { blocked_registers[i] = false; } // Mark all fixed input, temp and output registers as used. for (intptr_t i = 0; i < locs->input_count(); i++) { Location loc = locs->in(i); if (loc.IsRegister()) { ASSERT(!blocked_registers[loc.reg()]); blocked_registers[loc.reg()] = true; } } for (intptr_t i = 0; i < locs->temp_count(); i++) { Location loc = locs->temp(i); if (loc.IsRegister()) { ASSERT(!blocked_registers[loc.reg()]); blocked_registers[loc.reg()] = true; } } if (locs->out().IsRegister()) { // Fixed output registers are allowed to overlap with // temps and inputs. blocked_registers[locs->out().reg()] = true; } // Do not allocate known registers. blocked_registers[CTX] = true; blocked_registers[SPREG] = true; blocked_registers[FPREG] = true; if (TMP != kNoRegister) { blocked_registers[TMP] = true; } // Allocate all unallocated input locations. const bool should_pop = !instr->IsPushArgument(); for (intptr_t i = locs->input_count() - 1; i >= 0; i--) { Location loc = locs->in(i); Register reg = kNoRegister; if (loc.IsRegister()) { reg = loc.reg(); } else if (loc.IsUnallocated() || loc.IsConstant()) { ASSERT(loc.IsConstant() || ((loc.policy() == Location::kRequiresRegister) || (loc.policy() == Location::kWritableRegister))); reg = AllocateFreeRegister(blocked_registers); locs->set_in(i, Location::RegisterLocation(reg)); } ASSERT(reg != kNoRegister); // Inputs are consumed from the simulated frame. In case of a call argument // we leave it until the call instruction. if (should_pop) { assembler()->PopRegister(reg); } } // Allocate all unallocated temp locations. for (intptr_t i = 0; i < locs->temp_count(); i++) { Location loc = locs->temp(i); if (loc.IsUnallocated()) { ASSERT(loc.policy() == Location::kRequiresRegister); loc = Location::RegisterLocation( AllocateFreeRegister(blocked_registers)); locs->set_temp(i, loc); } } Location result_location = locs->out(); if (result_location.IsUnallocated()) { switch (result_location.policy()) { case Location::kAny: case Location::kPrefersRegister: case Location::kRequiresRegister: case Location::kWritableRegister: result_location = Location::RegisterLocation( AllocateFreeRegister(blocked_registers)); break; case Location::kSameAsFirstInput: result_location = locs->in(0); break; case Location::kRequiresXmmRegister: UNREACHABLE(); break; } locs->set_out(result_location); } } ParallelMoveResolver::ParallelMoveResolver(FlowGraphCompiler* compiler) : compiler_(compiler), moves_(32) {} void ParallelMoveResolver::EmitNativeCode(ParallelMoveInstr* parallel_move) { ASSERT(moves_.is_empty()); // Build up a worklist of moves. BuildInitialMoveList(parallel_move); for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& move = *moves_[i]; // Skip constants to perform them last. They don't block other moves // and skipping such moves with register destinations keeps those // registers free for the whole algorithm. if (!move.IsEliminated() && !move.src().IsConstant()) PerformMove(i); } // Perform the moves with constant sources. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& move = *moves_[i]; if (!move.IsEliminated()) { ASSERT(move.src().IsConstant()); EmitMove(i); } } moves_.Clear(); } void ParallelMoveResolver::BuildInitialMoveList( ParallelMoveInstr* parallel_move) { // Perform a linear sweep of the moves to add them to the initial list of // moves to perform, ignoring any move that is redundant (the source is // the same as the destination, the destination is ignored and // unallocated, or the move was already eliminated). for (int i = 0; i < parallel_move->NumMoves(); i++) { MoveOperands* move = parallel_move->MoveOperandsAt(i); if (!move->IsRedundant()) moves_.Add(move); } } void ParallelMoveResolver::PerformMove(int index) { // Each call to this function performs a move and deletes it from the move // graph. We first recursively perform any move blocking this one. We // mark a move as "pending" on entry to PerformMove in order to detect // cycles in the move graph. We use operand swaps to resolve cycles, // which means that a call to PerformMove could change any source operand // in the move graph. ASSERT(!moves_[index]->IsPending()); ASSERT(!moves_[index]->IsRedundant()); // Clear this move's destination to indicate a pending move. The actual // destination is saved in a stack-allocated local. Recursion may allow // multiple moves to be pending. ASSERT(!moves_[index]->src().IsInvalid()); Location destination = moves_[index]->MarkPending(); // Perform a depth-first traversal of the move graph to resolve // dependencies. Any unperformed, unpending move with a source the same // as this one's destination blocks this one so recursively perform all // such moves. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& other_move = *moves_[i]; if (other_move.Blocks(destination) && !other_move.IsPending()) { // Though PerformMove can change any source operand in the move graph, // this call cannot create a blocking move via a swap (this loop does // not miss any). Assume there is a non-blocking move with source A // and this move is blocked on source B and there is a swap of A and // B. Then A and B must be involved in the same cycle (or they would // not be swapped). Since this move's destination is B and there is // only a single incoming edge to an operand, this move must also be // involved in the same cycle. In that case, the blocking move will // be created but will be "pending" when we return from PerformMove. PerformMove(i); } } // We are about to resolve this move and don't need it marked as // pending, so restore its destination. moves_[index]->ClearPending(destination); // This move's source may have changed due to swaps to resolve cycles and // so it may now be the last move in the cycle. If so remove it. if (moves_[index]->src().Equals(destination)) { moves_[index]->Eliminate(); return; } // The move may be blocked on a (at most one) pending move, in which case // we have a cycle. Search for such a blocking move and perform a swap to // resolve it. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& other_move = *moves_[i]; if (other_move.Blocks(destination)) { ASSERT(other_move.IsPending()); EmitSwap(index); return; } } // This move is not blocked. EmitMove(index); } Condition FlowGraphCompiler::FlipCondition(Condition condition) { switch (condition) { case EQUAL: return EQUAL; case NOT_EQUAL: return NOT_EQUAL; case LESS: return GREATER; case LESS_EQUAL: return GREATER_EQUAL; case GREATER: return LESS; case GREATER_EQUAL: return LESS_EQUAL; case BELOW: return ABOVE; case BELOW_EQUAL: return ABOVE_EQUAL; case ABOVE: return BELOW; case ABOVE_EQUAL: return BELOW_EQUAL; default: UNIMPLEMENTED(); return EQUAL; } } bool FlowGraphCompiler::EvaluateCondition(Condition condition, intptr_t left, intptr_t right) { const uintptr_t unsigned_left = static_cast<uintptr_t>(left); const uintptr_t unsigned_right = static_cast<uintptr_t>(right); switch (condition) { case EQUAL: return left == right; case NOT_EQUAL: return left != right; case LESS: return left < right; case LESS_EQUAL: return left <= right; case GREATER: return left > right; case GREATER_EQUAL: return left >= right; case BELOW: return unsigned_left < unsigned_right; case BELOW_EQUAL: return unsigned_left <= unsigned_right; case ABOVE: return unsigned_left > unsigned_right; case ABOVE_EQUAL: return unsigned_left >= unsigned_right; default: UNIMPLEMENTED(); return false; } } FieldAddress FlowGraphCompiler::ElementAddressForIntIndex(intptr_t cid, Register array, intptr_t offset) { switch (cid) { case kArrayCid: case kImmutableArrayCid: { const intptr_t disp = offset * kWordSize + sizeof(RawArray); ASSERT(Utils::IsInt(31, disp)); return FieldAddress(array, disp); } case kFloat32ArrayCid: { const intptr_t disp = offset * kFloatSize + Float32Array::data_offset(); ASSERT(Utils::IsInt(31, disp)); return FieldAddress(array, disp); } case kFloat64ArrayCid: { const intptr_t disp = offset * kDoubleSize + Float64Array::data_offset(); ASSERT(Utils::IsInt(31, disp)); return FieldAddress(array, disp); } case kUint8ArrayCid: { const intptr_t disp = offset + Uint8Array::data_offset(); ASSERT(Utils::IsInt(31, disp)); return FieldAddress(array, disp); } default: UNIMPLEMENTED(); return FieldAddress(SPREG, 0); } } FieldAddress FlowGraphCompiler::ElementAddressForRegIndex(intptr_t cid, Register array, Register index) { // Note that index is Smi, i.e, times 2. ASSERT(kSmiTagShift == 1); switch (cid) { case kArrayCid: case kImmutableArrayCid: return FieldAddress(array, index, TIMES_HALF_WORD_SIZE, sizeof(RawArray)); case kFloat32ArrayCid: return FieldAddress(array, index, TIMES_2, Float32Array::data_offset()); case kFloat64ArrayCid: return FieldAddress(array, index, TIMES_4, Float64Array::data_offset()); case kUint8ArrayCid: return FieldAddress(array, index, TIMES_1, Uint8Array::data_offset()); default: UNIMPLEMENTED(); return FieldAddress(SPREG, 0); } } // Returns true if checking against this type is a direct class id comparison. bool FlowGraphCompiler::TypeCheckAsClassEquality(const AbstractType& type) { ASSERT(type.IsFinalized() && !type.IsMalformed()); // Requires CHA, which can be applied in optimized code only, if (!FLAG_use_cha || !is_optimizing()) return false; if (!type.IsInstantiated()) return false; const Class& type_class = Class::Handle(type.type_class()); // Signature classes have different type checking rules. if (type_class.IsSignatureClass()) return false; // Could be an interface check? if (type_class.is_implemented()) return false; const intptr_t type_cid = type_class.id(); if (CHA::HasSubclasses(type_cid)) return false; if (type_class.HasTypeArguments()) { // Only raw types can be directly compared, thus disregarding type // arguments. const AbstractTypeArguments& type_arguments = AbstractTypeArguments::Handle(type.arguments()); const bool is_raw_type = type_arguments.IsNull() || type_arguments.IsRaw(type_arguments.Length()); return is_raw_type; } return true; } } // namespace dart Sort checks by counts before emitting test-and-call polymorphic instance calls. Review URL: https://codereview.chromium.org//11602014 git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@16517 260f80e4-7a28-3924-810f-c04153c831b5 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" // Needed here to get TARGET_ARCH_XXX. #include "vm/flow_graph_compiler.h" #include "vm/cha.h" #include "vm/dart_entry.h" #include "vm/debugger.h" #include "vm/deopt_instructions.h" #include "vm/flow_graph_allocator.h" #include "vm/il_printer.h" #include "vm/intrinsifier.h" #include "vm/locations.h" #include "vm/longjump.h" #include "vm/object_store.h" #include "vm/parser.h" #include "vm/stub_code.h" #include "vm/symbols.h" namespace dart { DEFINE_FLAG(bool, print_scopes, false, "Print scopes of local variables."); DECLARE_FLAG(bool, code_comments); DECLARE_FLAG(bool, enable_type_checks); DECLARE_FLAG(bool, intrinsify); DECLARE_FLAG(bool, propagate_ic_data); DECLARE_FLAG(bool, report_usage_count); DECLARE_FLAG(int, optimization_counter_threshold); DECLARE_FLAG(bool, use_cha); void CompilerDeoptInfo::BuildReturnAddress(DeoptInfoBuilder* builder, const Function& function, intptr_t slot_ix) { builder->AddReturnAddressAfter(function, deopt_id(), slot_ix); } void CompilerDeoptInfoWithStub::BuildReturnAddress(DeoptInfoBuilder* builder, const Function& function, intptr_t slot_ix) { builder->AddReturnAddressBefore(function, deopt_id(), slot_ix); } // Assign locations to incoming arguments, i.e., values pushed above spill slots // with PushArgument. Recursively allocates from outermost to innermost // environment. void CompilerDeoptInfo::AllocateIncomingParametersRecursive( Environment* env, intptr_t* stack_height) { if (env == NULL) return; AllocateIncomingParametersRecursive(env->outer(), stack_height); for (Environment::ShallowIterator it(env); !it.Done(); it.Advance()) { if (it.CurrentLocation().IsInvalid()) { ASSERT(it.CurrentValue()->definition()->IsPushArgument()); it.SetCurrentLocation(Location::StackSlot((*stack_height)++)); } } } RawDeoptInfo* CompilerDeoptInfo::CreateDeoptInfo(FlowGraphCompiler* compiler, DeoptInfoBuilder* builder) { if (deoptimization_env_ == NULL) return DeoptInfo::null(); intptr_t stack_height = compiler->StackSize(); AllocateIncomingParametersRecursive(deoptimization_env_, &stack_height); intptr_t slot_ix = 0; Environment* current = deoptimization_env_; // For the innermost environment, call the virtual return builder. BuildReturnAddress(builder, current->function(), slot_ix++); // For the innermost environment, set outgoing arguments and the locals. for (intptr_t i = current->Length() - 1; i >= current->fixed_parameter_count(); i--) { builder->AddCopy(current->LocationAt(i), *current->ValueAt(i), slot_ix++); } // PC marker and caller FP. builder->AddPcMarker(current->function(), slot_ix++); builder->AddCallerFp(slot_ix++); Environment* previous = current; current = current->outer(); while (current != NULL) { // For any outer environment the deopt id is that of the call instruction // which is recorded in the outer environment. builder->AddReturnAddressAfter(current->function(), current->deopt_id(), slot_ix++); // The values of outgoing arguments can be changed from the inlined call so // we must read them from the previous environment. for (intptr_t i = previous->fixed_parameter_count() - 1; i >= 0; i--) { builder->AddCopy(previous->LocationAt(i), *previous->ValueAt(i), slot_ix++); } // Set the locals, note that outgoing arguments are not in the environment. for (intptr_t i = current->Length() - 1; i >= current->fixed_parameter_count(); i--) { builder->AddCopy(current->LocationAt(i), *current->ValueAt(i), slot_ix++); } // PC marker and caller FP. builder->AddPcMarker(current->function(), slot_ix++); builder->AddCallerFp(slot_ix++); // Iterate on the outer environment. previous = current; current = current->outer(); } // The previous pointer is now the outermost environment. ASSERT(previous != NULL); // For the outermost environment, set caller PC. builder->AddCallerPc(slot_ix++); // For the outermost environment, set the incoming arguments. for (intptr_t i = previous->fixed_parameter_count() - 1; i >= 0; i--) { builder->AddCopy(previous->LocationAt(i), *previous->ValueAt(i), slot_ix++); } const DeoptInfo& deopt_info = DeoptInfo::Handle(builder->CreateDeoptInfo()); return deopt_info.raw(); } FlowGraphCompiler::FlowGraphCompiler(Assembler* assembler, const FlowGraph& flow_graph, bool is_optimizing) : assembler_(assembler), parsed_function_(flow_graph.parsed_function()), block_order_(flow_graph.reverse_postorder()), current_block_(NULL), exception_handlers_list_(NULL), pc_descriptors_list_(NULL), stackmap_table_builder_( is_optimizing ? new StackmapTableBuilder() : NULL), block_info_(block_order_.length()), deopt_infos_(), static_calls_target_table_(GrowableObjectArray::ZoneHandle( GrowableObjectArray::New())), is_optimizing_(is_optimizing), may_reoptimize_(false), bool_true_(Bool::ZoneHandle(Bool::True())), bool_false_(Bool::ZoneHandle(Bool::False())), double_class_(Class::ZoneHandle( Isolate::Current()->object_store()->double_class())), parallel_move_resolver_(this) { ASSERT(assembler != NULL); } FlowGraphCompiler::~FlowGraphCompiler() { // BlockInfos are zone-allocated, so their destructors are not called. // Verify the labels explicitly here. for (int i = 0; i < block_info_.length(); ++i) { ASSERT(!block_info_[i]->label.IsLinked()); ASSERT(!block_info_[i]->label.HasNear()); } } bool FlowGraphCompiler::HasFinally() const { return parsed_function().function().has_finally(); } void FlowGraphCompiler::InitCompiler() { pc_descriptors_list_ = new DescriptorList(64); exception_handlers_list_ = new ExceptionHandlerList(); block_info_.Clear(); for (int i = 0; i < block_order_.length(); ++i) { block_info_.Add(new BlockInfo()); } } bool FlowGraphCompiler::CanOptimize() { return !FLAG_report_usage_count && (FLAG_optimization_counter_threshold >= 0) && !Isolate::Current()->debugger()->IsActive(); } void FlowGraphCompiler::VisitBlocks() { for (intptr_t i = 0; i < block_order().length(); ++i) { // Compile the block entry. BlockEntryInstr* entry = block_order()[i]; assembler()->Comment("B%"Pd"", entry->block_id()); set_current_block(entry); entry->PrepareEntry(this); // Compile all successors until an exit, branch, or a block entry. for (ForwardInstructionIterator it(entry); !it.Done(); it.Advance()) { Instruction* instr = it.Current(); if (FLAG_code_comments) EmitComment(instr); if (instr->IsParallelMove()) { parallel_move_resolver_.EmitNativeCode(instr->AsParallelMove()); } else { ASSERT(instr->locs() != NULL); EmitInstructionPrologue(instr); pending_deoptimization_env_ = instr->env(); instr->EmitNativeCode(this); EmitInstructionEpilogue(instr); } } } set_current_block(NULL); } void FlowGraphCompiler::Bailout(const char* reason) { const char* kFormat = "FlowGraphCompiler Bailout: %s %s."; const char* function_name = parsed_function().function().ToCString(); intptr_t len = OS::SNPrint(NULL, 0, kFormat, function_name, reason) + 1; char* chars = Isolate::Current()->current_zone()->Alloc<char>(len); OS::SNPrint(chars, len, kFormat, function_name, reason); const Error& error = Error::Handle( LanguageError::New(String::Handle(String::New(chars)))); Isolate::Current()->long_jump_base()->Jump(1, error); } intptr_t FlowGraphCompiler::StackSize() const { if (is_optimizing_) { return block_order_[0]->AsGraphEntry()->spill_slot_count(); } else { return parsed_function_.num_stack_locals() + parsed_function_.num_copied_params(); } } Label* FlowGraphCompiler::GetBlockLabel( BlockEntryInstr* block_entry) const { intptr_t block_index = block_entry->postorder_number(); return &block_info_[block_index]->label; } bool FlowGraphCompiler::IsNextBlock(BlockEntryInstr* block_entry) const { intptr_t current_index = reverse_index(current_block()->postorder_number()); return (current_index < (block_order().length() - 1)) && (block_order()[current_index + 1] == block_entry); } void FlowGraphCompiler::AddSlowPathCode(SlowPathCode* code) { slow_path_code_.Add(code); } void FlowGraphCompiler::GenerateDeferredCode() { for (intptr_t i = 0; i < slow_path_code_.length(); i++) { slow_path_code_[i]->EmitNativeCode(this); } for (intptr_t i = 0; i < deopt_infos_.length(); i++) { deopt_infos_[i]->GenerateCode(this, i); } } void FlowGraphCompiler::AddExceptionHandler(intptr_t try_index, intptr_t pc_offset) { exception_handlers_list_->AddHandler(try_index, pc_offset); } // Uses current pc position and try-index. void FlowGraphCompiler::AddCurrentDescriptor(PcDescriptors::Kind kind, intptr_t deopt_id, intptr_t token_pos) { pc_descriptors_list()->AddDescriptor(kind, assembler()->CodeSize(), deopt_id, token_pos, CurrentTryIndex()); } void FlowGraphCompiler::AddStaticCallTarget(const Function& func) { ASSERT(Code::kSCallTableEntryLength == 3); ASSERT(Code::kSCallTableOffsetEntry == 0); static_calls_target_table_.Add( Smi::Handle(Smi::New(assembler()->CodeSize()))); ASSERT(Code::kSCallTableFunctionEntry == 1); static_calls_target_table_.Add(func); ASSERT(Code::kSCallTableCodeEntry == 2); static_calls_target_table_.Add(Code::Handle()); } void FlowGraphCompiler::AddDeoptIndexAtCall(intptr_t deopt_id, intptr_t token_pos) { ASSERT(is_optimizing()); CompilerDeoptInfo* info = new CompilerDeoptInfo(deopt_id, kDeoptAtCall); ASSERT(pending_deoptimization_env_ != NULL); info->set_deoptimization_env(pending_deoptimization_env_); info->set_pc_offset(assembler()->CodeSize()); deopt_infos_.Add(info); } void FlowGraphCompiler::RecordSafepoint(LocationSummary* locs) { if (is_optimizing()) { BitmapBuilder* bitmap = locs->stack_bitmap(); ASSERT(bitmap != NULL); ASSERT(bitmap->Length() <= StackSize()); // Pad the bitmap out to describe all the spill slots. bitmap->SetLength(StackSize()); // Mark the bits in the stack map in the same order we push registers in // slow path code (see FlowGraphCompiler::SaveLiveRegisters). // // Slow path code can have registers at the safepoint. if (!locs->always_calls()) { RegisterSet* regs = locs->live_registers(); if (regs->xmm_regs_count() > 0) { // Denote XMM registers with 0 bits in the stackmap. Based on the // assumption that there are normally few live XMM registers, this // encoding is simpler and roughly as compact as storing a separate // count of XMM registers. // // XMM registers have the highest register number at the highest // address (i.e., first in the stackmap). for (intptr_t i = kNumberOfXmmRegisters - 1; i >= 0; --i) { XmmRegister reg = static_cast<XmmRegister>(i); if (regs->ContainsXmmRegister(reg)) { for (intptr_t j = 0; j < FlowGraphAllocator::kDoubleSpillSlotFactor; ++j) { bitmap->Set(bitmap->Length(), false); } } } } // General purpose registers have the lowest register number at the // highest address (i.e., first in the stackmap). for (intptr_t i = 0; i < kNumberOfCpuRegisters; ++i) { Register reg = static_cast<Register>(i); if (locs->live_registers()->ContainsRegister(reg)) { bitmap->Set(bitmap->Length(), true); } } } intptr_t register_bit_count = bitmap->Length() - StackSize(); stackmap_table_builder_->AddEntry(assembler()->CodeSize(), bitmap, register_bit_count); } } Label* FlowGraphCompiler::AddDeoptStub(intptr_t deopt_id, DeoptReasonId reason) { CompilerDeoptInfoWithStub* stub = new CompilerDeoptInfoWithStub(deopt_id, reason); ASSERT(is_optimizing_); ASSERT(pending_deoptimization_env_ != NULL); stub->set_deoptimization_env(pending_deoptimization_env_); deopt_infos_.Add(stub); return stub->entry_label(); } void FlowGraphCompiler::FinalizeExceptionHandlers(const Code& code) { ASSERT(exception_handlers_list_ != NULL); const ExceptionHandlers& handlers = ExceptionHandlers::Handle( exception_handlers_list_->FinalizeExceptionHandlers(code.EntryPoint())); code.set_exception_handlers(handlers); } void FlowGraphCompiler::FinalizePcDescriptors(const Code& code) { ASSERT(pc_descriptors_list_ != NULL); const PcDescriptors& descriptors = PcDescriptors::Handle( pc_descriptors_list_->FinalizePcDescriptors(code.EntryPoint())); if (!is_optimizing_) descriptors.Verify(parsed_function_.function()); code.set_pc_descriptors(descriptors); } void FlowGraphCompiler::FinalizeDeoptInfo(const Code& code) { // For functions with optional arguments, all incoming arguments are copied // to spill slots. The deoptimization environment does not track them. const Function& function = parsed_function().function(); const intptr_t incoming_arg_count = function.HasOptionalParameters() ? 0 : function.num_fixed_parameters(); DeoptInfoBuilder builder(incoming_arg_count); const Array& array = Array::Handle(Array::New(DeoptTable::SizeFor(deopt_infos_.length()), Heap::kOld)); Smi& offset = Smi::Handle(); DeoptInfo& info = DeoptInfo::Handle(); Smi& reason = Smi::Handle(); for (intptr_t i = 0; i < deopt_infos_.length(); i++) { offset = Smi::New(deopt_infos_[i]->pc_offset()); info = deopt_infos_[i]->CreateDeoptInfo(this, &builder); reason = Smi::New(deopt_infos_[i]->reason()); DeoptTable::SetEntry(array, i, offset, info, reason); } code.set_deopt_info_array(array); const Array& object_array = Array::Handle(Array::MakeArray(builder.object_table())); ASSERT(code.object_table() == Array::null()); code.set_object_table(object_array); } void FlowGraphCompiler::FinalizeStackmaps(const Code& code) { if (stackmap_table_builder_ == NULL) { // The unoptimizing compiler has no stack maps. code.set_stackmaps(Array::Handle()); } else { // Finalize the stack map array and add it to the code object. ASSERT(is_optimizing()); code.set_stackmaps( Array::Handle(stackmap_table_builder_->FinalizeStackmaps(code))); } } void FlowGraphCompiler::FinalizeVarDescriptors(const Code& code) { const LocalVarDescriptors& var_descs = LocalVarDescriptors::Handle( parsed_function_.node_sequence()->scope()->GetVarDescriptors( parsed_function_.function())); code.set_var_descriptors(var_descs); } void FlowGraphCompiler::FinalizeComments(const Code& code) { code.set_comments(assembler()->GetCodeComments()); } void FlowGraphCompiler::FinalizeStaticCallTargetsTable(const Code& code) { ASSERT(code.static_calls_target_table() == Array::null()); code.set_static_calls_target_table( Array::Handle(Array::MakeArray(static_calls_target_table_))); } // Returns 'true' if code generation for this function is complete, i.e., // no fall-through to regular code is needed. bool FlowGraphCompiler::TryIntrinsify() { if (!CanOptimize()) return false; // Intrinsification skips arguments checks, therefore disable if in checked // mode. if (FLAG_intrinsify && !FLAG_enable_type_checks) { if (parsed_function().function().kind() == RawFunction::kImplicitGetter) { // An implicit getter must have a specific AST structure. const SequenceNode& sequence_node = *parsed_function().node_sequence(); ASSERT(sequence_node.length() == 1); ASSERT(sequence_node.NodeAt(0)->IsReturnNode()); const ReturnNode& return_node = *sequence_node.NodeAt(0)->AsReturnNode(); ASSERT(return_node.value()->IsLoadInstanceFieldNode()); const LoadInstanceFieldNode& load_node = *return_node.value()->AsLoadInstanceFieldNode(); GenerateInlinedGetter(load_node.field().Offset()); return true; } if (parsed_function().function().kind() == RawFunction::kImplicitSetter) { // An implicit setter must have a specific AST structure. // Sequence node has one store node and one return NULL node. const SequenceNode& sequence_node = *parsed_function().node_sequence(); ASSERT(sequence_node.length() == 2); ASSERT(sequence_node.NodeAt(0)->IsStoreInstanceFieldNode()); ASSERT(sequence_node.NodeAt(1)->IsReturnNode()); const StoreInstanceFieldNode& store_node = *sequence_node.NodeAt(0)->AsStoreInstanceFieldNode(); GenerateInlinedSetter(store_node.field().Offset()); return true; } } // Even if an intrinsified version of the function was successfully // generated, it may fall through to the non-intrinsified method body. return Intrinsifier::Intrinsify(parsed_function().function(), assembler()); } void FlowGraphCompiler::GenerateInstanceCall( intptr_t deopt_id, intptr_t token_pos, intptr_t argument_count, const Array& argument_names, LocationSummary* locs, const ICData& ic_data) { ASSERT(!ic_data.IsNull()); ASSERT(FLAG_propagate_ic_data || (ic_data.NumberOfChecks() == 0)); const Array& arguments_descriptor = Array::ZoneHandle(ArgumentsDescriptor::New(argument_count, argument_names)); uword label_address = 0; if (is_optimizing() && (ic_data.NumberOfChecks() == 0)) { if (ic_data.is_closure_call()) { // This IC call may be closure call only. label_address = StubCode::ClosureCallInlineCacheEntryPoint(); ExternalLabel target_label("InlineCache", label_address); EmitInstanceCall(&target_label, ICData::ZoneHandle(ic_data.AsUnaryClassChecks()), arguments_descriptor, argument_count, deopt_id, token_pos, locs); return; } // Emit IC call that will count and thus may need reoptimization at // return instruction. may_reoptimize_ = true; switch (ic_data.num_args_tested()) { case 1: label_address = StubCode::OneArgOptimizedCheckInlineCacheEntryPoint(); break; case 2: label_address = StubCode::TwoArgsOptimizedCheckInlineCacheEntryPoint(); break; case 3: label_address = StubCode::ThreeArgsOptimizedCheckInlineCacheEntryPoint(); break; default: UNIMPLEMENTED(); } ExternalLabel target_label("InlineCache", label_address); EmitOptimizedInstanceCall(&target_label, ic_data, arguments_descriptor, argument_count, deopt_id, token_pos, locs); return; } if (is_optimizing()) { EmitMegamorphicInstanceCall(ic_data, arguments_descriptor, argument_count, deopt_id, token_pos, locs); return; } switch (ic_data.num_args_tested()) { case 1: label_address = StubCode::OneArgCheckInlineCacheEntryPoint(); break; case 2: label_address = StubCode::TwoArgsCheckInlineCacheEntryPoint(); break; case 3: label_address = StubCode::ThreeArgsCheckInlineCacheEntryPoint(); break; default: UNIMPLEMENTED(); } ExternalLabel target_label("InlineCache", label_address); EmitInstanceCall(&target_label, ic_data, arguments_descriptor, argument_count, deopt_id, token_pos, locs); } void FlowGraphCompiler::GenerateStaticCall(intptr_t deopt_id, intptr_t token_pos, const Function& function, intptr_t argument_count, const Array& argument_names, LocationSummary* locs) { const Array& arguments_descriptor = Array::ZoneHandle(ArgumentsDescriptor::New(argument_count, argument_names)); EmitStaticCall(function, arguments_descriptor, argument_count, deopt_id, token_pos, locs); } void FlowGraphCompiler::GenerateNumberTypeCheck(Register kClassIdReg, const AbstractType& type, Label* is_instance_lbl, Label* is_not_instance_lbl) { assembler()->Comment("NumberTypeCheck"); GrowableArray<intptr_t> args; if (type.IsNumberType()) { args.Add(kDoubleCid); args.Add(kMintCid); args.Add(kBigintCid); } else if (type.IsIntType()) { args.Add(kMintCid); args.Add(kBigintCid); } else if (type.IsDoubleType()) { args.Add(kDoubleCid); } CheckClassIds(kClassIdReg, args, is_instance_lbl, is_not_instance_lbl); } void FlowGraphCompiler::GenerateStringTypeCheck(Register kClassIdReg, Label* is_instance_lbl, Label* is_not_instance_lbl) { assembler()->Comment("StringTypeCheck"); GrowableArray<intptr_t> args; args.Add(kOneByteStringCid); args.Add(kTwoByteStringCid); args.Add(kExternalOneByteStringCid); args.Add(kExternalTwoByteStringCid); CheckClassIds(kClassIdReg, args, is_instance_lbl, is_not_instance_lbl); } void FlowGraphCompiler::GenerateListTypeCheck(Register kClassIdReg, Label* is_instance_lbl) { assembler()->Comment("ListTypeCheck"); Label unknown; GrowableArray<intptr_t> args; args.Add(kArrayCid); args.Add(kGrowableObjectArrayCid); args.Add(kImmutableArrayCid); CheckClassIds(kClassIdReg, args, is_instance_lbl, &unknown); assembler()->Bind(&unknown); } void FlowGraphCompiler::EmitComment(Instruction* instr) { char buffer[256]; BufferFormatter f(buffer, sizeof(buffer)); instr->PrintTo(&f); assembler()->Comment("%s", buffer); } struct CidTarget { intptr_t cid; Function* target; intptr_t count; CidTarget(intptr_t cid_arg, Function* target_arg, intptr_t count_arg) : cid(cid_arg), target(target_arg), count(count_arg) {} }; // Returns 'sorted' array in decreasing count order. // The expected number of elements to sort is less than 10. static void SortICDataByCount(const ICData& ic_data, GrowableArray<CidTarget>* sorted) { ASSERT(ic_data.num_args_tested() == 1); const intptr_t len = ic_data.NumberOfChecks(); sorted->Clear(); for (int i = 0; i < len; i++) { sorted->Add(CidTarget(ic_data.GetReceiverClassIdAt(i), &Function::ZoneHandle(ic_data.GetTargetAt(i)), ic_data.GetCountAt(i))); } for (int i = 0; i < len; i++) { intptr_t largest_ix = i; for (int k = i + 1; k < len; k++) { if ((*sorted)[largest_ix].count < (*sorted)[k].count) { largest_ix = k; } } if (i != largest_ix) { // Swap. CidTarget temp = (*sorted)[i]; (*sorted)[i] = (*sorted)[largest_ix]; (*sorted)[largest_ix] = temp; } } } void FlowGraphCompiler::EmitTestAndCall(const ICData& ic_data, Register class_id_reg, intptr_t arg_count, const Array& arg_names, Label* deopt, intptr_t deopt_id, intptr_t token_index, LocationSummary* locs) { ASSERT(!ic_data.IsNull() && (ic_data.NumberOfChecks() > 0)); Label match_found; const intptr_t len = ic_data.NumberOfChecks(); GrowableArray<CidTarget> sorted(len); SortICDataByCount(ic_data, &sorted); for (intptr_t i = 0; i < len; i++) { const bool is_last_check = (i == (len - 1)); Label next_test; assembler()->cmpl(class_id_reg, Immediate(sorted[i].cid)); if (is_last_check) { assembler()->j(NOT_EQUAL, deopt); } else { assembler()->j(NOT_EQUAL, &next_test); } GenerateStaticCall(deopt_id, token_index, *sorted[i].target, arg_count, arg_names, locs); if (!is_last_check) { assembler()->jmp(&match_found); } assembler()->Bind(&next_test); } assembler()->Bind(&match_found); } void FlowGraphCompiler::EmitDoubleCompareBranch(Condition true_condition, XmmRegister left, XmmRegister right, BranchInstr* branch) { ASSERT(branch != NULL); assembler()->comisd(left, right); BlockEntryInstr* nan_result = (true_condition == NOT_EQUAL) ? branch->true_successor() : branch->false_successor(); assembler()->j(PARITY_EVEN, GetBlockLabel(nan_result)); branch->EmitBranchOnCondition(this, true_condition); } void FlowGraphCompiler::EmitDoubleCompareBool(Condition true_condition, XmmRegister left, XmmRegister right, Register result) { assembler()->comisd(left, right); Label is_false, is_true, done; assembler()->j(PARITY_EVEN, &is_false, Assembler::kNearJump); // NaN false; assembler()->j(true_condition, &is_true, Assembler::kNearJump); assembler()->Bind(&is_false); assembler()->LoadObject(result, bool_false()); assembler()->jmp(&done); assembler()->Bind(&is_true); assembler()->LoadObject(result, bool_true()); assembler()->Bind(&done); } // Allocate a register that is not explicitly blocked. static Register AllocateFreeRegister(bool* blocked_registers) { for (intptr_t regno = 0; regno < kNumberOfCpuRegisters; regno++) { if (!blocked_registers[regno]) { blocked_registers[regno] = true; return static_cast<Register>(regno); } } UNREACHABLE(); return kNoRegister; } void FlowGraphCompiler::AllocateRegistersLocally(Instruction* instr) { ASSERT(!is_optimizing()); LocationSummary* locs = instr->locs(); bool blocked_registers[kNumberOfCpuRegisters]; // Mark all available registers free. for (intptr_t i = 0; i < kNumberOfCpuRegisters; i++) { blocked_registers[i] = false; } // Mark all fixed input, temp and output registers as used. for (intptr_t i = 0; i < locs->input_count(); i++) { Location loc = locs->in(i); if (loc.IsRegister()) { ASSERT(!blocked_registers[loc.reg()]); blocked_registers[loc.reg()] = true; } } for (intptr_t i = 0; i < locs->temp_count(); i++) { Location loc = locs->temp(i); if (loc.IsRegister()) { ASSERT(!blocked_registers[loc.reg()]); blocked_registers[loc.reg()] = true; } } if (locs->out().IsRegister()) { // Fixed output registers are allowed to overlap with // temps and inputs. blocked_registers[locs->out().reg()] = true; } // Do not allocate known registers. blocked_registers[CTX] = true; blocked_registers[SPREG] = true; blocked_registers[FPREG] = true; if (TMP != kNoRegister) { blocked_registers[TMP] = true; } // Allocate all unallocated input locations. const bool should_pop = !instr->IsPushArgument(); for (intptr_t i = locs->input_count() - 1; i >= 0; i--) { Location loc = locs->in(i); Register reg = kNoRegister; if (loc.IsRegister()) { reg = loc.reg(); } else if (loc.IsUnallocated() || loc.IsConstant()) { ASSERT(loc.IsConstant() || ((loc.policy() == Location::kRequiresRegister) || (loc.policy() == Location::kWritableRegister))); reg = AllocateFreeRegister(blocked_registers); locs->set_in(i, Location::RegisterLocation(reg)); } ASSERT(reg != kNoRegister); // Inputs are consumed from the simulated frame. In case of a call argument // we leave it until the call instruction. if (should_pop) { assembler()->PopRegister(reg); } } // Allocate all unallocated temp locations. for (intptr_t i = 0; i < locs->temp_count(); i++) { Location loc = locs->temp(i); if (loc.IsUnallocated()) { ASSERT(loc.policy() == Location::kRequiresRegister); loc = Location::RegisterLocation( AllocateFreeRegister(blocked_registers)); locs->set_temp(i, loc); } } Location result_location = locs->out(); if (result_location.IsUnallocated()) { switch (result_location.policy()) { case Location::kAny: case Location::kPrefersRegister: case Location::kRequiresRegister: case Location::kWritableRegister: result_location = Location::RegisterLocation( AllocateFreeRegister(blocked_registers)); break; case Location::kSameAsFirstInput: result_location = locs->in(0); break; case Location::kRequiresXmmRegister: UNREACHABLE(); break; } locs->set_out(result_location); } } ParallelMoveResolver::ParallelMoveResolver(FlowGraphCompiler* compiler) : compiler_(compiler), moves_(32) {} void ParallelMoveResolver::EmitNativeCode(ParallelMoveInstr* parallel_move) { ASSERT(moves_.is_empty()); // Build up a worklist of moves. BuildInitialMoveList(parallel_move); for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& move = *moves_[i]; // Skip constants to perform them last. They don't block other moves // and skipping such moves with register destinations keeps those // registers free for the whole algorithm. if (!move.IsEliminated() && !move.src().IsConstant()) PerformMove(i); } // Perform the moves with constant sources. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& move = *moves_[i]; if (!move.IsEliminated()) { ASSERT(move.src().IsConstant()); EmitMove(i); } } moves_.Clear(); } void ParallelMoveResolver::BuildInitialMoveList( ParallelMoveInstr* parallel_move) { // Perform a linear sweep of the moves to add them to the initial list of // moves to perform, ignoring any move that is redundant (the source is // the same as the destination, the destination is ignored and // unallocated, or the move was already eliminated). for (int i = 0; i < parallel_move->NumMoves(); i++) { MoveOperands* move = parallel_move->MoveOperandsAt(i); if (!move->IsRedundant()) moves_.Add(move); } } void ParallelMoveResolver::PerformMove(int index) { // Each call to this function performs a move and deletes it from the move // graph. We first recursively perform any move blocking this one. We // mark a move as "pending" on entry to PerformMove in order to detect // cycles in the move graph. We use operand swaps to resolve cycles, // which means that a call to PerformMove could change any source operand // in the move graph. ASSERT(!moves_[index]->IsPending()); ASSERT(!moves_[index]->IsRedundant()); // Clear this move's destination to indicate a pending move. The actual // destination is saved in a stack-allocated local. Recursion may allow // multiple moves to be pending. ASSERT(!moves_[index]->src().IsInvalid()); Location destination = moves_[index]->MarkPending(); // Perform a depth-first traversal of the move graph to resolve // dependencies. Any unperformed, unpending move with a source the same // as this one's destination blocks this one so recursively perform all // such moves. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& other_move = *moves_[i]; if (other_move.Blocks(destination) && !other_move.IsPending()) { // Though PerformMove can change any source operand in the move graph, // this call cannot create a blocking move via a swap (this loop does // not miss any). Assume there is a non-blocking move with source A // and this move is blocked on source B and there is a swap of A and // B. Then A and B must be involved in the same cycle (or they would // not be swapped). Since this move's destination is B and there is // only a single incoming edge to an operand, this move must also be // involved in the same cycle. In that case, the blocking move will // be created but will be "pending" when we return from PerformMove. PerformMove(i); } } // We are about to resolve this move and don't need it marked as // pending, so restore its destination. moves_[index]->ClearPending(destination); // This move's source may have changed due to swaps to resolve cycles and // so it may now be the last move in the cycle. If so remove it. if (moves_[index]->src().Equals(destination)) { moves_[index]->Eliminate(); return; } // The move may be blocked on a (at most one) pending move, in which case // we have a cycle. Search for such a blocking move and perform a swap to // resolve it. for (int i = 0; i < moves_.length(); ++i) { const MoveOperands& other_move = *moves_[i]; if (other_move.Blocks(destination)) { ASSERT(other_move.IsPending()); EmitSwap(index); return; } } // This move is not blocked. EmitMove(index); } Condition FlowGraphCompiler::FlipCondition(Condition condition) { switch (condition) { case EQUAL: return EQUAL; case NOT_EQUAL: return NOT_EQUAL; case LESS: return GREATER; case LESS_EQUAL: return GREATER_EQUAL; case GREATER: return LESS; case GREATER_EQUAL: return LESS_EQUAL; case BELOW: return ABOVE; case BELOW_EQUAL: return ABOVE_EQUAL; case ABOVE: return BELOW; case ABOVE_EQUAL: return BELOW_EQUAL; default: UNIMPLEMENTED(); return EQUAL; } } bool FlowGraphCompiler::EvaluateCondition(Condition condition, intptr_t left, intptr_t right) { const uintptr_t unsigned_left = static_cast<uintptr_t>(left); const uintptr_t unsigned_right = static_cast<uintptr_t>(right); switch (condition) { case EQUAL: return left == right; case NOT_EQUAL: return left != right; case LESS: return left < right; case LESS_EQUAL: return left <= right; case GREATER: return left > right; case GREATER_EQUAL: return left >= right; case BELOW: return unsigned_left < unsigned_right; case BELOW_EQUAL: return unsigned_left <= unsigned_right; case ABOVE: return unsigned_left > unsigned_right; case ABOVE_EQUAL: return unsigned_left >= unsigned_right; default: UNIMPLEMENTED(); return false; } } FieldAddress FlowGraphCompiler::ElementAddressForIntIndex(intptr_t cid, Register array, intptr_t offset) { switch (cid) { case kArrayCid: case kImmutableArrayCid: { const intptr_t disp = offset * kWordSize + sizeof(RawArray); ASSERT(Utils::IsInt(31, disp)); return FieldAddress(array, disp); } case kFloat32ArrayCid: { const intptr_t disp = offset * kFloatSize + Float32Array::data_offset(); ASSERT(Utils::IsInt(31, disp)); return FieldAddress(array, disp); } case kFloat64ArrayCid: { const intptr_t disp = offset * kDoubleSize + Float64Array::data_offset(); ASSERT(Utils::IsInt(31, disp)); return FieldAddress(array, disp); } case kUint8ArrayCid: { const intptr_t disp = offset + Uint8Array::data_offset(); ASSERT(Utils::IsInt(31, disp)); return FieldAddress(array, disp); } default: UNIMPLEMENTED(); return FieldAddress(SPREG, 0); } } FieldAddress FlowGraphCompiler::ElementAddressForRegIndex(intptr_t cid, Register array, Register index) { // Note that index is Smi, i.e, times 2. ASSERT(kSmiTagShift == 1); switch (cid) { case kArrayCid: case kImmutableArrayCid: return FieldAddress(array, index, TIMES_HALF_WORD_SIZE, sizeof(RawArray)); case kFloat32ArrayCid: return FieldAddress(array, index, TIMES_2, Float32Array::data_offset()); case kFloat64ArrayCid: return FieldAddress(array, index, TIMES_4, Float64Array::data_offset()); case kUint8ArrayCid: return FieldAddress(array, index, TIMES_1, Uint8Array::data_offset()); default: UNIMPLEMENTED(); return FieldAddress(SPREG, 0); } } // Returns true if checking against this type is a direct class id comparison. bool FlowGraphCompiler::TypeCheckAsClassEquality(const AbstractType& type) { ASSERT(type.IsFinalized() && !type.IsMalformed()); // Requires CHA, which can be applied in optimized code only, if (!FLAG_use_cha || !is_optimizing()) return false; if (!type.IsInstantiated()) return false; const Class& type_class = Class::Handle(type.type_class()); // Signature classes have different type checking rules. if (type_class.IsSignatureClass()) return false; // Could be an interface check? if (type_class.is_implemented()) return false; const intptr_t type_cid = type_class.id(); if (CHA::HasSubclasses(type_cid)) return false; if (type_class.HasTypeArguments()) { // Only raw types can be directly compared, thus disregarding type // arguments. const AbstractTypeArguments& type_arguments = AbstractTypeArguments::Handle(type.arguments()); const bool is_raw_type = type_arguments.IsNull() || type_arguments.IsRaw(type_arguments.Length()); return is_raw_type; } return true; } } // namespace dart
/** * projectM -- Milkdrop-esque visualisation SDK * Copyright (C)2003-2004 projectM Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ #include "video_init.h" #include <fcntl.h> #include <stdlib.h> #include <math.h> #include <SDL/SDL.h> #include <libprojectM/projectM.hpp> #include "sdltoprojectM.h" #include "ConfigFile.h" #include <string> #include <iostream> #include <stdio.h> #include <unistd.h> #include <jack/jack.h> #define CONFIG_FILE "/share/projectM/config.inp" std::string read_config(); jack_port_t *input_port; jack_client_t *client; jack_default_audio_sample_t out[1024*1000]; #ifdef DEBUG FILE *debugFile = NULL; #endif volatile enum { Init, Run, Exit } client_state = Init; SDL_Surface *screen; projectM *globalPM = NULL; int dumpFrame = 0; int frameNumber = 0; int texsize=512; int gx=32,gy=24; int wvw=512,wvh=512; int fvw=1024,fvh=768; int fps=30, fullscreen=0; std::string read_config() { int n; char num[512]; FILE *in; FILE *out; char* home; char projectM_home[1024]; char projectM_config[1024]; strcpy(projectM_config, PROJECTM_PREFIX); strcpy(projectM_config+strlen(PROJECTM_PREFIX), CONFIG_FILE); projectM_config[strlen(PROJECTM_PREFIX)+strlen(CONFIG_FILE)]='\0'; printf("dir:%s \n",projectM_config); home=getenv("HOME"); strcpy(projectM_home, home); strcpy(projectM_home+strlen(home), "/.projectM/config.inp"); projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0'; if ((in = fopen(projectM_home, "r")) != 0) { printf("reading ~/.projectM/config.inp \n"); fclose(in); return std::string(projectM_home); } else { printf("trying to create ~/.projectM/config.inp \n"); strcpy(projectM_home, home); strcpy(projectM_home+strlen(home), "/.projectM"); projectM_home[strlen(home)+strlen("/.projectM")]='\0'; mkdir(projectM_home,0755); strcpy(projectM_home, home); strcpy(projectM_home+strlen(home), "/.projectM/config.inp"); projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0'; if((out = fopen(projectM_home,"w"))!=0) { if ((in = fopen(projectM_config, "r")) != 0) { while(fgets(num,80,in)!=NULL) { fputs(num,out); } fclose(in); fclose(out); if ((in = fopen(projectM_home, "r")) != 0) { printf("created ~/.projectM/config.inp successfully\n"); fclose(in); return std::string(projectM_home); } else{printf("This shouldn't happen, using implementation defualts\n");abort();} } else{printf("Cannot find projectM default config, using implementation defaults\n");abort();} } else { printf("Cannot create ~/.projectM/config.inp, using default config file\n"); if ((in = fopen(projectM_config, "r")) != 0) { printf("Successfully opened default config file\n"); fclose(in); return std::string(projectM_config);} else{ printf("Using implementation defaults, your system is really messed up, I'm suprised we even got this far\n"); abort();} } } abort(); } void renderLoop() { int i; int x, y; int index; short pcm_data[2][512]; while ( 1 ) { projectMEvent evt; projectMKeycode key; projectMModifier mod; /** Process SDL events */ SDL_Event event; while ( SDL_PollEvent( &event ) ) { /** Translate into projectM codes and process */ evt = sdl2pmEvent( event ); key = sdl2pmKeycode( event.key.keysym.sym ); mod = sdl2pmModifier( event.key.keysym.mod ); if ( evt == PROJECTM_KEYDOWN ) { if(key == PROJECTM_K_f) { resize_display(fvw, fvh, fullscreen); globalPM->projectM_resetGL( fvw, fvh ); } else if(key == PROJECTM_K_q || key == PROJECTM_K_ESCAPE) {delete(globalPM); exit (1);} else {globalPM->key_handler(evt,key,mod);} } else if ( evt == PROJECTM_VIDEORESIZE ) { wvw=event.resize.w; wvh=event.resize.h; resize_display(wvw, wvh, 0); globalPM->projectM_resetGL( wvw, wvh ); } } /** Render the new frame */ globalPM->renderFrame( ); SDL_GL_SwapBuffers(); } printf("Worker thread: Exiting\n"); } int process (jack_nframes_t nframes, void *arg) { jack_default_audio_sample_t *in; jack_transport_state_t ts = jack_transport_query(client, NULL); if (ts == JackTransportRolling) { if (client_state == Init) client_state = Run; in = (jack_default_audio_sample_t*)jack_port_get_buffer (input_port, nframes); //memcpy (out, in,sizeof (jack_default_audio_sample_t) * nframes); globalPM->pcm->addPCMfloat(in,nframes); //printf("%x %f\n",nframes,in[128]); } else if (ts == JackTransportStopped) { if (client_state == Run) client_state = Exit; } return 0; } void jack_shutdown (void *arg) { exit (1); } int main( int argc, char **argv ) { const char **ports; const char *client_name; const char *server_name = NULL; jack_options_t options = JackNullOption; jack_status_t status; int i; char projectM_data[1024]; std::string config_file; config_file = read_config(); ConfigFile config(config_file); int wvw = config.read<int>( "Window Width", 512 ); int wvh = config.read<int>( "Window Height", 512 ); int fullscreen = 0; if (config.read("Fullscreen", true)) fullscreen = 1; else fullscreen = 0; #ifdef DEBUG int value; int rgb_size[3]; #endif const SDL_VideoInfo* info = NULL; int bpp = 0; /* Flags we will pass into SDL_SetVideoMode. */ int flags = 0; //JACK INIT //---------------------------------------------- if (argc >= 2) { /* client name specified? */ client_name = argv[1]; if (argc >= 3) { /* server name specified? */ server_name = argv[2]; // options |= JackServerName; } } else { /* use basename of argv[0] */ client_name = strrchr(argv[0], '/'); if (client_name == 0) { client_name = argv[0]; } else { client_name++; } } /* open a client connection to the JACK server */ client = jack_client_open (client_name, options, &status, server_name); if (client == NULL) { fprintf (stderr, "jack_client_open() failed, " "status = 0x%2.0x\n", status); if (status & JackServerFailed) { fprintf (stderr, "Unable to connect to JACK server\n"); } exit (1); } if (status & JackServerStarted) { fprintf (stderr, "JACK server started\n"); } if (status & JackNameNotUnique) { client_name = jack_get_client_name(client); fprintf (stderr, "unique name `%s' assigned\n", client_name); } /* tell the JACK server to call `process()' whenever there is work to be done. */ jack_set_process_callback (client, process, 0); /* tell the JACK server to call `jack_shutdown()' if it ever shuts down, either entirely, or if it just decides to stop calling us. */ jack_on_shutdown (client, jack_shutdown, 0); /* display the current sample rate. */ printf ("engine sample rate: %d\n", jack_get_sample_rate (client)); /* create two ports */ input_port = jack_port_register (client, "input", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); if (input_port == NULL) { fprintf(stderr, "no more JACK ports available\n"); exit (1); } /* Tell the JACK server that we are ready to roll. Our * process() callback will start running now. */ //END JACK INIT ---------------------------------- init_display(wvw,wvh,&fvw,&fvh,fullscreen); /** Setup some window stuff */ SDL_WM_SetCaption( PROJECTM_TITLE, NULL ); globalPM = new projectM(config_file); /** Initialise projectM */ //JACK BEGIN----------------------------- if (jack_activate (client)) { fprintf (stderr, "cannot activate client"); exit (1); } /* Connect the ports. You can't do this before the client is * activated, because we can't make connections to clients * that aren't running. Note the confusing (but necessary) * orientation of the driver backend ports: playback ports are * "input" to the backend, and capture ports are "output" from * it. */ ports = jack_get_ports (client, NULL, NULL, JackPortIsOutput); if (ports == NULL) { fprintf(stderr, "no physical capture ports\n"); exit (1); } i=0; while (ports[i]!=NULL) { printf("Connecting to Jack port %s\n",ports[i]); if (jack_connect (client, ports[i], jack_port_name (input_port))) { fprintf (stderr, "cannot connect input ports\n"); } i++; } free (ports); //----------------------------------END /** Initialise the thread */ renderLoop(); return 1; } Fullscreen fix git-svn-id: 647c2dfdf120d9af8205d960f30c8711574448cd@601 6778bc44-b910-0410-a7a0-be141de4315d /** * projectM -- Milkdrop-esque visualisation SDK * Copyright (C)2003-2004 projectM Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ #include "video_init.h" #include <fcntl.h> #include <stdlib.h> #include <math.h> #include <SDL/SDL.h> #include <libprojectM/projectM.hpp> #include "sdltoprojectM.h" #include "ConfigFile.h" #include <string> #include <iostream> #include <stdio.h> #include <unistd.h> #include <jack/jack.h> #define CONFIG_FILE "/share/projectM/config.inp" std::string read_config(); jack_port_t *input_port; jack_client_t *client; jack_default_audio_sample_t out[1024*1000]; #ifdef DEBUG FILE *debugFile = NULL; #endif volatile enum { Init, Run, Exit } client_state = Init; SDL_Surface *screen; projectM *globalPM = NULL; int dumpFrame = 0; int frameNumber = 0; int texsize=512; int gx=32,gy=24; int wvw=512,wvh=512; int fvw=1024,fvh=768; int fps=30, fullscreen=0; std::string read_config() { int n; char num[512]; FILE *in; FILE *out; char* home; char projectM_home[1024]; char projectM_config[1024]; strcpy(projectM_config, PROJECTM_PREFIX); strcpy(projectM_config+strlen(PROJECTM_PREFIX), CONFIG_FILE); projectM_config[strlen(PROJECTM_PREFIX)+strlen(CONFIG_FILE)]='\0'; printf("dir:%s \n",projectM_config); home=getenv("HOME"); strcpy(projectM_home, home); strcpy(projectM_home+strlen(home), "/.projectM/config.inp"); projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0'; if ((in = fopen(projectM_home, "r")) != 0) { printf("reading ~/.projectM/config.inp \n"); fclose(in); return std::string(projectM_home); } else { printf("trying to create ~/.projectM/config.inp \n"); strcpy(projectM_home, home); strcpy(projectM_home+strlen(home), "/.projectM"); projectM_home[strlen(home)+strlen("/.projectM")]='\0'; mkdir(projectM_home,0755); strcpy(projectM_home, home); strcpy(projectM_home+strlen(home), "/.projectM/config.inp"); projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0'; if((out = fopen(projectM_home,"w"))!=0) { if ((in = fopen(projectM_config, "r")) != 0) { while(fgets(num,80,in)!=NULL) { fputs(num,out); } fclose(in); fclose(out); if ((in = fopen(projectM_home, "r")) != 0) { printf("created ~/.projectM/config.inp successfully\n"); fclose(in); return std::string(projectM_home); } else{printf("This shouldn't happen, using implementation defualts\n");abort();} } else{printf("Cannot find projectM default config, using implementation defaults\n");abort();} } else { printf("Cannot create ~/.projectM/config.inp, using default config file\n"); if ((in = fopen(projectM_config, "r")) != 0) { printf("Successfully opened default config file\n"); fclose(in); return std::string(projectM_config);} else{ printf("Using implementation defaults, your system is really messed up, I'm suprised we even got this far\n"); abort();} } } abort(); } void renderLoop() { int i; int x, y; int index; short pcm_data[2][512]; while ( 1 ) { projectMEvent evt; projectMKeycode key; projectMModifier mod; /** Process SDL events */ SDL_Event event; while ( SDL_PollEvent( &event ) ) { /** Translate into projectM codes and process */ evt = sdl2pmEvent( event ); key = sdl2pmKeycode( event.key.keysym.sym ); mod = sdl2pmModifier( event.key.keysym.mod ); if ( evt == PROJECTM_KEYDOWN ) { if(key == PROJECTM_K_f) { if (++fullscreen%2) { resize_display(fvw, fvh, fullscreen%2); globalPM->projectM_resetGL( fvw, fvh ); } else { resize_display(wvw, wvh, fullscreen%2); globalPM->projectM_resetGL( wvw, wvh ); } } else if(key == PROJECTM_K_q || key == PROJECTM_K_ESCAPE) {delete(globalPM); exit (1);} else {globalPM->key_handler(evt,key,mod);} } else if ( evt == PROJECTM_VIDEORESIZE ) { wvw=event.resize.w; wvh=event.resize.h; resize_display(wvw, wvh, fullscreen%2); globalPM->projectM_resetGL( wvw, wvh ); } } /** Render the new frame */ globalPM->renderFrame( ); SDL_GL_SwapBuffers(); } printf("Worker thread: Exiting\n"); } int process (jack_nframes_t nframes, void *arg) { jack_default_audio_sample_t *in; jack_transport_state_t ts = jack_transport_query(client, NULL); if (ts == JackTransportRolling) { if (client_state == Init) client_state = Run; in = (jack_default_audio_sample_t*)jack_port_get_buffer (input_port, nframes); //memcpy (out, in,sizeof (jack_default_audio_sample_t) * nframes); globalPM->pcm->addPCMfloat(in,nframes); //printf("%x %f\n",nframes,in[128]); } else if (ts == JackTransportStopped) { if (client_state == Run) client_state = Exit; } return 0; } void jack_shutdown (void *arg) { exit (1); } int main( int argc, char **argv ) { const char **ports; const char *client_name; const char *server_name = NULL; jack_options_t options = JackNullOption; jack_status_t status; int i; char projectM_data[1024]; std::string config_file; config_file = read_config(); ConfigFile config(config_file); wvw = config.read<int>( "Window Width", 512 ); wvh = config.read<int>( "Window Height", 512 ); int fullscreen = 0; if (config.read("Fullscreen", true)) fullscreen = 1; else fullscreen = 0; #ifdef DEBUG int value; int rgb_size[3]; #endif const SDL_VideoInfo* info = NULL; int bpp = 0; /* Flags we will pass into SDL_SetVideoMode. */ int flags = 0; //JACK INIT //---------------------------------------------- if (argc >= 2) { /* client name specified? */ client_name = argv[1]; if (argc >= 3) { /* server name specified? */ server_name = argv[2]; // options |= JackServerName; } } else { /* use basename of argv[0] */ client_name = strrchr(argv[0], '/'); if (client_name == 0) { client_name = argv[0]; } else { client_name++; } } /* open a client connection to the JACK server */ client = jack_client_open (client_name, options, &status, server_name); if (client == NULL) { fprintf (stderr, "jack_client_open() failed, " "status = 0x%2.0x\n", status); if (status & JackServerFailed) { fprintf (stderr, "Unable to connect to JACK server\n"); } exit (1); } if (status & JackServerStarted) { fprintf (stderr, "JACK server started\n"); } if (status & JackNameNotUnique) { client_name = jack_get_client_name(client); fprintf (stderr, "unique name `%s' assigned\n", client_name); } /* tell the JACK server to call `process()' whenever there is work to be done. */ jack_set_process_callback (client, process, 0); /* tell the JACK server to call `jack_shutdown()' if it ever shuts down, either entirely, or if it just decides to stop calling us. */ jack_on_shutdown (client, jack_shutdown, 0); /* display the current sample rate. */ printf ("engine sample rate: %d\n", jack_get_sample_rate (client)); /* create two ports */ input_port = jack_port_register (client, "input", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); if (input_port == NULL) { fprintf(stderr, "no more JACK ports available\n"); exit (1); } /* Tell the JACK server that we are ready to roll. Our * process() callback will start running now. */ //END JACK INIT ---------------------------------- init_display(wvw,wvh,&fvw,&fvh,fullscreen); /** Setup some window stuff */ SDL_WM_SetCaption( PROJECTM_TITLE, NULL ); globalPM = new projectM(config_file); /** Initialise projectM */ //JACK BEGIN----------------------------- if (jack_activate (client)) { fprintf (stderr, "cannot activate client"); exit (1); } /* Connect the ports. You can't do this before the client is * activated, because we can't make connections to clients * that aren't running. Note the confusing (but necessary) * orientation of the driver backend ports: playback ports are * "input" to the backend, and capture ports are "output" from * it. */ ports = jack_get_ports (client, NULL, NULL, JackPortIsOutput); if (ports == NULL) { fprintf(stderr, "no physical capture ports\n"); exit (1); } i=0; while (ports[i]!=NULL) { printf("Connecting to Jack port %s\n",ports[i]); if (jack_connect (client, ports[i], jack_port_name (input_port))) { fprintf (stderr, "cannot connect input ports\n"); } i++; } free (ports); //----------------------------------END /** Initialise the thread */ renderLoop(); return 1; }
//============================================================================ // Name : main.cpp // Author : Sammok Kabasi // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ /** * Check for TODO before submitting * * TODO remove unwanted couts and printfs * */ #include <iostream> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <ifaddrs.h> #include <unistd.h> using namespace std; #define STDIN 0 #define MAXIMUM_TIMEOUTS 3 int numberOfNodes; int numberOfNeighbours; int hostServerId = -1; char weights[10][3]; char* ip_address; void print_nodes_table() ; /* http://stackoverflow.com/questions/4139405/how-to-know-ip-address-for-interfaces-in-c Retrieve the IP address of the process. */ int getIP() { struct ifaddrs *ifap, *ifa; struct sockaddr_in *sa; char * ip_address_temp; getifaddrs(&ifap); for (ifa = ifap; ifa; ifa = ifa->ifa_next) { if (ifa->ifa_addr->sa_family == AF_INET) { sa = (struct sockaddr_in *) ifa->ifa_addr; ip_address_temp = inet_ntoa(sa->sin_addr); //Make sure it's not the default localhost address that you are using. if ((strcmp(ip_address_temp, "127.0.0.1") != 0) && (strcmp(ip_address_temp, "0.0.0.0") != 0)) { // cout<<"Setting the IP address as " <<ip_address_temp<<" "; ip_address = ip_address_temp; // cout << ip_address; break; } } } cout<<endl<<"The IP address is "<<ip_address<<endl; freeifaddrs(ifap); return 0; } int readTopologyFile(char* filePath); char* portNumber; //port number of current process /** * Startup function. *TODO: do something here */ int startServer() { return 0; } //HELPER METHODS /** * TODO: kuch badal isme * Checks if the array pointed to by input holds a valid number. * Source: PA2 template * @param input char* to the array holding the value. * @return TRUE or FALSE */ int isNumber(char *input) { while (*input){ if (!isdigit(*input)) return 0; else input += 1; } return 1; } int timeout = -1; struct nodes_table_info { uint32_t serverIp; uint16_t serverPort; uint16_t serverId; int numberOfTimeouts; int isNeighbour; uint16_t linkCost; int isDisabled; int nextHopId; char server_name[20]; nodes_table_info() { serverId = 0; serverPort = 0; serverIp = 0; numberOfTimeouts = 0; isNeighbour = -1; isDisabled = -1; linkCost = 0xffff; nextHopId = -1; } }; struct nodes_table_info nodes[5]; struct serverInfo { uint32_t serverIp; uint16_t port; uint16_t serverId; uint16_t cost; }; //This is the format of the message packet. struct routing_packet{ uint16_t numberOfUpdateFields; uint16_t serverPort; uint32_t serverIp; struct serverInfo updateFields[100]; }; /** TODO : change * converts string array ip address to a uint32_t object */ uint32_t parse_ipaddress_string_to_uint32_t(char* ipAddress) { struct in_addr ip_addr; inet_pton(AF_INET, ipAddress, &ip_addr); return (uint32_t)ntohl(ip_addr.s_addr); } /*TODO : change * * Convert uint32_t to String IP address */ char* print_uint32_ip(uint32_t ip) { char *ipAddress = (char*)malloc(INET_ADDRSTRLEN); struct in_addr ip_addr; ip_addr.s_addr = htonl(ip); inet_ntop(AF_INET, &ip_addr, ipAddress, INET_ADDRSTRLEN); return ipAddress; } /* * Function to print the nodes table */ void print_nodes_table() { printf("%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|\n", "serverId", "noOfTimeouts", "isNeighbour", "linkCost", "nextHopId", "isDisabled", "serverIp", "server_port"); for (int i = 0; i < numberOfNodes; i++) { printf("%-15d|%-15d|%-15d|%-15d|%-15d|%-15d|%-15s|%-15d|\n", nodes[i].serverId, nodes[i].numberOfTimeouts, nodes[i].isNeighbour, nodes[i].linkCost, nodes[i].nextHopId, nodes[i].isDisabled, print_uint32_ip(nodes[i].serverIp), nodes[i].serverPort); } } /** * */ int createSocket(int listeningPort) { int listen_sock_fd = -1; //REQUIRED STRUCTS struct addrinfo listen_sock_details, *ai, *p; memset(&listen_sock_details,0, sizeof (listen_sock_details)); listen_sock_details.ai_family = AF_INET; listen_sock_details.ai_socktype = SOCK_DGRAM; listen_sock_details.ai_flags = AI_PASSIVE | AI_ADDRCONFIG ; listen_sock_details.ai_protocol = 0; if(listeningPort != -1){ char portString[6]; memset(&portString, '\0', 6); sprintf(portString, "%d", listeningPort); int retval = getaddrinfo(NULL, portString, &listen_sock_details, &ai); if (retval!=0){ fprintf(stderr, "UDP_socket creation selectserver: %s\n", gai_strerror(retval)); return(-1); } }else{ int retval = getaddrinfo(NULL, "22134", &listen_sock_details, &ai); if (retval!=0){ fprintf(stderr, "sending_socket creation selectserver: %s\n", gai_strerror(retval)); return (-1); } } for(p = ai;p != NULL; p = p->ai_next){ listen_sock_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if(listen_sock_fd < 0) continue; int y=1; setsockopt(listen_sock_fd, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); if(bind(listen_sock_fd, p->ai_addr, p->ai_addrlen) < 0){ close(listen_sock_fd); continue; } break; } if(p==NULL){ fprintf(stderr, "listen_socket selectserver: failed to bind\n"); return(-2); } freeaddrinfo(ai); return listen_sock_fd; } /** * Reads the topology file, parses the values and populates the nodes_table_info struct object "nodes" */ int readTopologyFile(char* filePath) { FILE *fp; char buf[255]; fp = fopen(filePath, "r"); if (NULL == fp) { printf("Error opening file"); return -1; } //Line 1 is number of nodes fscanf(fp, "%s", buf); numberOfNodes = atoi(buf); printf("number of nodes -->%d\n" , numberOfNodes); //Line 2 is numberOfNeighbours fscanf(fp, "%s", buf); numberOfNeighbours = atoi(buf); printf("number of connections -->%d\n" , numberOfNeighbours); //Next numberOfNodes lines is weight information for (int i = 0; i < numberOfNodes; i++) { fscanf(fp, "%s", buf); cout<<buf<<endl; nodes[i].serverId = atoi(buf); // cout<<"nodes[i].serverIp : "<<nodes[i].serverIp; fscanf(fp, "%s", buf); cout<<buf<<endl; nodes[i].serverIp = parse_ipaddress_string_to_uint32_t(buf); char *ip_str; uint32_t ip_int = parse_ipaddress_string_to_uint32_t(buf); ip_str = print_uint32_ip(ip_int); fscanf(fp, "%s", buf); cout<<buf<<endl; nodes[i].serverPort = atoi(buf); } //Parsed nodes should be in order in table struct nodes_table_info temp_node; for (int i = 0; i < numberOfNodes; i++) { for (int j = 0; j < numberOfNodes; j++) { if (nodes[j].serverId == (i + 1)) { temp_node = nodes[i]; nodes[i] = nodes[j]; nodes[j] = temp_node; break; } } } cout<<"Read Topology File"<<endl; // print_nodes_table(); //Next numberOfNeighbours lines is for(int i=0;i<numberOfNeighbours;i++){ fscanf(fp,"%s",buf); if(hostServerId == -1){ hostServerId = atoi(buf); }else{ if(hostServerId != atoi(buf)){ cout<<"Invalid topology file. More than one host ?"<<endl; } } fscanf(fp,"%s",buf); int neighbour = atoi(buf); int j; for(j=0;j<numberOfNodes;j++){ if(neighbour == nodes[j].serverId){ break; } } nodes[j].isNeighbour = 1; fscanf(fp,"%s",buf); nodes[j].linkCost = atoi(buf); nodes[j].nextHopId = neighbour;//nodes[i].server_id; } for(int i=0;i<numberOfNodes;i++){ if(hostServerId == nodes[i].serverId){ nodes[i].linkCost = 0; nodes[i].nextHopId = hostServerId; break; } } fclose(fp); return 0; } int main(int nNumberofArgs, char* args[]) { int c; char* filePath; //Get the ip address and port number and store it in the local variables getIP(); printf("Printing nodes table..\n"); /*TODO change! * Parse the arguments * http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html */ while ((c = getopt(nNumberofArgs, args, "t:i:")) != -1) { switch (c) { case 't': cout << "Filename:" << optarg << endl; strcpy(filePath, optarg); break; case 'i': //argument should be an integer number (seconds) if (!isNumber(optarg)) { fprintf(stderr, "Invalid value for -i\n"); cout << "Invalid value for -i\n"; return -1; } timeout = atoi(optarg); break; case '?': break; default: cout << "Usage: %s -t <topology-file-name> -i <routing-update-interval-in-seconds>", args[0]; return -1; } } //read the local topology file int r = readTopologyFile(filePath); printf("%d", r); // print_nodes_table(); cout << endl << "sock number : " << createSocket(59999); return 0; } Added printRoutingTable //============================================================================ // Name : main.cpp // Author : Sammok Kabasi // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ /** * Check for TODO before submitting * * TODO remove unwanted couts and printfs * */ #include <iostream> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <ifaddrs.h> #include <unistd.h> using namespace std; #define STDIN 0 #define MAXIMUM_TIMEOUTS 3 int numberOfNodes; int numberOfNeighbours; int hostServerId = -1; char weights[10][3]; char* ip_address; void print_nodes_table() ; //void print_routing_table3(); /* http://stackoverflow.com/questions/4139405/how-to-know-ip-address-for-interfaces-in-c Retrieve the IP address of the process. */ int getIP() { struct ifaddrs *ifap, *ifa; struct sockaddr_in *sa; char * ip_address_temp; getifaddrs(&ifap); for (ifa = ifap; ifa; ifa = ifa->ifa_next) { if (ifa->ifa_addr->sa_family == AF_INET) { sa = (struct sockaddr_in *) ifa->ifa_addr; ip_address_temp = inet_ntoa(sa->sin_addr); //Make sure it's not the default localhost address that you are using. if ((strcmp(ip_address_temp, "127.0.0.1") != 0) && (strcmp(ip_address_temp, "0.0.0.0") != 0)) { // cout<<"Setting the IP address as " <<ip_address_temp<<" "; ip_address = ip_address_temp; // cout << ip_address; break; } } } cout<<endl<<"The IP address is "<<ip_address<<endl; freeifaddrs(ifap); return 0; } int readTopologyFile(char* filePath); char* portNumber; //port number of current process /** * Startup function. *TODO: do something here */ int startServer() { return 0; } //HELPER METHODS /** * TODO: kuch badal isme * Checks if the array pointed to by input holds a valid number. * Source: PA2 template * @param input char* to the array holding the value. * @return TRUE or FALSE */ int isNumber(char *input) { while (*input){ if (!isdigit(*input)) return 0; else input += 1; } return 1; } int timeout = -1; void printRoutingTable(); struct nodes_table_info { uint32_t serverIp; uint16_t serverPort; uint16_t serverId; int numberOfTimeouts; int isNeighbour; uint16_t linkCost; int isDisabled; int nextHopId; char server_name[20]; nodes_table_info() { serverId = 0; serverPort = 0; serverIp = 0; numberOfTimeouts = 0; isNeighbour = -1; isDisabled = -1; linkCost = 0xffff; nextHopId = -1; } }; struct nodes_table_info nodes[10]; struct serverInfo { uint32_t serverIp; uint16_t port; uint16_t serverId; uint16_t cost; }; //This is the format of the message packet. struct RoutingPacket{ uint16_t numberOfUpdateFields; uint16_t serverPort; uint32_t serverIp; struct serverInfo updateFields[10]; }; struct RoutingTableEntry{ uint16_t srcServerId; uint16_t destServerId; int nextHopId; uint16_t linkCost; RoutingTableEntry(){ srcServerId = -1; destServerId = -1; nextHopId = -1; linkCost = 0xffff; } }; struct RoutingTableEntry routingTable[10][10]; /** TODO : change * converts string array ip address to a uint32_t object */ uint32_t parse_ipaddress_string_to_uint32_t(char* ipAddress) { struct in_addr ip_addr; inet_pton(AF_INET, ipAddress, &ip_addr); return (uint32_t)ntohl(ip_addr.s_addr); } /*TODO : change * * Convert uint32_t to String IP address */ char* print_uint32_ip(uint32_t ip) { char *ipAddress = (char*)malloc(INET_ADDRSTRLEN); struct in_addr ip_addr; ip_addr.s_addr = htonl(ip); inet_ntop(AF_INET, &ip_addr, ipAddress, INET_ADDRSTRLEN); return ipAddress; } /* * Function to print the nodes table */ void print_nodes_table() { printf("%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|\n", "serverId", "noOfTimeouts", "isNeighbour", "linkCost", "nextHopId", "isDisabled", "serverIp", "server_port"); for (int i = 0; i < numberOfNodes; i++) { printf("%-15d|%-15d|%-15d|%-15d|%-15d|%-15d|%-15s|%-15d|\n", nodes[i].serverId, nodes[i].numberOfTimeouts, nodes[i].isNeighbour, nodes[i].linkCost, nodes[i].nextHopId, nodes[i].isDisabled, print_uint32_ip(nodes[i].serverIp), nodes[i].serverPort); } } /**TODO: change! * */ int createSocket(int listeningPort) { int listen_sock_fd = -1; //REQUIRED STRUCTS struct addrinfo listen_sock_details, *ai, *p; memset(&listen_sock_details, 0, sizeof(listen_sock_details)); listen_sock_details.ai_family = AF_INET; listen_sock_details.ai_socktype = SOCK_DGRAM; listen_sock_details.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; listen_sock_details.ai_protocol = 0; if (listeningPort != -1) { char portString[6]; memset(&portString, '\0', 6); sprintf(portString, "%d", listeningPort); int retval = getaddrinfo(NULL, portString, &listen_sock_details, &ai); if (retval != 0) { fprintf(stderr, "UDP_socket creation selectserver: %s\n", gai_strerror(retval)); return (-1); } } else { int retval = getaddrinfo(NULL, "22134", &listen_sock_details, &ai); if (retval != 0) { fprintf(stderr, "sending_socket creation selectserver: %s\n", gai_strerror(retval)); return (-1); } } for (p = ai; p != NULL; p = p->ai_next) { listen_sock_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (listen_sock_fd < 0) continue; int y = 1; setsockopt(listen_sock_fd, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); if (bind(listen_sock_fd, p->ai_addr, p->ai_addrlen) < 0) { close(listen_sock_fd); continue; } break; } if (p == NULL) { fprintf(stderr, "listen_socket selectserver: failed to bind\n"); return (-2); } freeaddrinfo(ai); return listen_sock_fd; } /** * Reads the topology file, parses the values and populates the nodes_table_info struct object "nodes" */ int readTopologyFile(char* filePath) { cout<<"inside readTopologyFile"; FILE *fp; char buf[255]; fp = fopen(filePath, "r"); if (NULL == fp) { printf("Error opening file"); return -1; } //Line 1 is number of nodes fscanf(fp, "%s", buf); numberOfNodes = atoi(buf); printf("number of nodes -->%d\n" , numberOfNodes); //Line 2 is numberOfNeighbours fscanf(fp, "%s", buf); numberOfNeighbours = atoi(buf); printf("number of connections -->%d\n" , numberOfNeighbours); //Next numberOfNodes lines is weight information for (int i = 0; i < numberOfNodes; i++) { fscanf(fp, "%s", buf); cout<<buf<<endl; nodes[i].serverId = atoi(buf); // cout<<"nodes[i].serverIp : "<<nodes[i].serverIp; fscanf(fp, "%s", buf); cout<<buf<<endl; nodes[i].serverIp = parse_ipaddress_string_to_uint32_t(buf); char *ip_str; uint32_t ip_int = parse_ipaddress_string_to_uint32_t(buf); ip_str = print_uint32_ip(ip_int); fscanf(fp, "%s", buf); cout<<buf<<endl; nodes[i].serverPort = atoi(buf); } //Parsed nodes should be in order in table struct nodes_table_info temp_node; for (int i = 0; i < numberOfNodes; i++) { for (int j = 0; j < numberOfNodes; j++) { if (nodes[j].serverId == (i + 1)) { temp_node = nodes[i]; nodes[i] = nodes[j]; nodes[j] = temp_node; break; } } } cout<<"Read Topology File"<<endl; // print_nodes_table(); //Next numberOfNeighbours lines is for(int i=0;i<numberOfNeighbours;i++){ fscanf(fp,"%s",buf); if(hostServerId == -1){ hostServerId = atoi(buf); }else{ if(hostServerId != atoi(buf)){ cout<<"Invalid topology file. More than one host ?"<<endl; } } fscanf(fp,"%s",buf); int neighbour = atoi(buf); int j; for(j=0;j<numberOfNodes;j++){ if(neighbour == nodes[j].serverId){ break; } } nodes[j].isNeighbour = 1; fscanf(fp,"%s",buf); nodes[j].linkCost = atoi(buf); nodes[j].nextHopId = neighbour;//nodes[i].server_id; } for(int i=0;i<numberOfNodes;i++){ if(hostServerId == nodes[i].serverId){ nodes[i].linkCost = 0; nodes[i].nextHopId = hostServerId; break; } } fclose(fp); return 0; } int main(int nNumberofArgs, char* args[]) { int c; if (nNumberofArgs < 2) { fprintf(stderr, "Missing arguments\n"); cout << "Usage: -t <topology-file-name> -i <routing-update-interval-in-seconds>"; return -1; } char* filePath = (char*) malloc (200); //Get the ip address and port number and store it in the local variables getIP(); /*TODO change! * Parse the arguments * http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html */ while ((c = getopt(nNumberofArgs, args, "t:i:")) != -1) { switch (c) { case 't': cout << "Topology file name:" << optarg << endl; strcpy(filePath, optarg); cout<<"break"; break; case 'i': cout<<"case i : " <<optarg; //argument should be an integer number (seconds) if (!isNumber(optarg)) { fprintf(stderr, "Invalid value for -i\n"); cout << "Invalid value for -i\n"; return -1; } timeout = atoi(optarg); break; case '?': break; default: cout << "Usage: " << args[0] << " -t <topology-file-name> -i <routing-update-interval-in-seconds>"; return -1; } } cout << "Reading the topology file..."; //read the local topology file, exit if invalid. if (readTopologyFile(filePath) == -1) { cout << "Topology file is invalid. Exiting..."; exit(1); } cout<<"Topology file read successfully"; //Initializing the local routing table... //copy local nodes info table (populated from tpoology file) to routing table, so as to initialize it. for (int i = 0; i < numberOfNodes; i++) { for (int j = 0; j < numberOfNodes; j++) { routingTable[i][j].srcServerId = nodes[i].serverId; routingTable[i][j].destServerId = nodes[j].serverId; //If the node's server id is the current hostId, update the values for that table if (nodes[i].serverId == hostServerId) { routingTable[i][j].linkCost = nodes[j].linkCost; routingTable[j][i].linkCost = nodes[j].linkCost; routingTable[i][j].nextHopId = nodes[j].nextHopId; } } } // printRoutingTable(); // print_nodes_table(); printRoutingTable(); cout << endl << "sock number : " << createSocket(59999); return 0; } //void printRoutingTable() { // cout << endl << "Routing table : " << endl; // // cout<<"\t"; // for (int i = 0; i < numberOfNodes; i++) { // cout << "|Node " <<i << "\t"; // } // cout<<endl; // for (int i = 0; i < numberOfNodes; i++) { // cout<<"Node "<<i; // for (int j = 0; j < numberOfNodes; j++) { // cout <<"\t|" << routingTable[i][j].linkCost; // } // cout << endl; // } //} void printRoutingTableWithProperFormat() { cout << endl << "Routing table : " << endl; cout<<"\t"; for (int i = 0; i < numberOfNodes; i++) { cout << "|Node " <<i << "\t"; } cout<<endl; for (int i = 0; i < numberOfNodes; i++) { cout<<"Node "<<i; for (int j = 0; j < numberOfNodes; j++) { cout <<"\t|" << routingTable[i][j].linkCost; } cout << endl; } } /* * Print routing table */ void printRoutingTable(){ cout<<"\nserverId\t|nextHopId\t|linkCost\n"; for (int i = 0; i < numberOfNodes; i++) { cout<<nodes[i].serverId<<"\t"; for (int j = 0; j < numberOfNodes; j++) { cout << "c(" << routingTable[i][j].srcServerId << "," << routingTable[i][j].destServerId << ") = " << routingTable[i][j].linkCost << ", "; cout << "NH(" << routingTable[i][j].srcServerId << "," << routingTable[i][j].destServerId << ") = " << routingTable[i][j].nextHopId << "\t|"; } printf("\n"); } }
// $Id$ //************************************************************************** //* This file is property of and copyright by the * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /// @file AliHLTTask.cxx /// @author Matthias Richter /// @date /// @brief Implementation of HLT tasks. /// #include <cerrno> #include <cassert> #include <iostream> #include <string> #include <ctime> #include "AliHLTTask.h" #include "AliHLTConfiguration.h" #include "AliHLTConfigurationHandler.h" #include "AliHLTComponent.h" #include "AliHLTComponentHandler.h" #include "AliHLTBaseVGRPAccess.h" #include "TList.h" #include "AliHLTErrorGuard.h" using std::cout; /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTTask) AliHLTTask::AliHLTTask() : fpConfiguration(NULL), fpComponent(NULL), fpDataBuffer(NULL), fListTargets(), fListDependencies(), fBlockDataArray() { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTTask::AliHLTTask(AliHLTConfiguration* pConf) : fpConfiguration(pConf), fpComponent(NULL), fpDataBuffer(NULL), fListTargets(), fListDependencies(), fBlockDataArray() { // see header file for function documentation } AliHLTTask::~AliHLTTask() { // see header file for function documentation TObjLink* lnk=fListDependencies.FirstLink(); while (lnk!=NULL) { AliHLTTask* pTask=(AliHLTTask*)lnk->GetObject(); pTask->UnsetTarget(this); lnk=lnk->Next(); } lnk=fListTargets.FirstLink(); while (lnk!=NULL) { AliHLTTask* pTask=(AliHLTTask*)lnk->GetObject(); pTask->UnsetDependency(this); lnk=lnk->Next(); } if (fpComponent) delete fpComponent; fpComponent=NULL; } int AliHLTTask::Init(AliHLTConfiguration* pConf, AliHLTComponentHandler* pCH) { // see header file for function documentation int iResult=0; if (fpConfiguration!=NULL && pConf!=NULL && fpConfiguration!=pConf) { HLTWarning("overriding existing reference to configuration object %p by %p", fpConfiguration, pConf); } if (pConf!=NULL) fpConfiguration=pConf; iResult=CreateComponent(fpConfiguration, pCH, fpComponent); if (iResult>=0) { iResult=CustomInit(pCH); } return iResult; } int AliHLTTask::CreateComponent(AliHLTConfiguration* pConfiguration, AliHLTComponentHandler* pCH, AliHLTComponent*& pComponent) const { // see header file for class documentation int iResult=0; if (!pConfiguration) return -EINVAL; const AliHLTConfiguration* pConf=AliHLTConfigurationHandler::FindSubstitution(*pConfiguration); if (!pConf) pConf=pConfiguration; if (pConf) { if (pCH) { int argc=0; const char** argv=NULL; if ((iResult=pConf->GetArguments(&argv))>=0) { argc=iResult; // just to make it clear // TODO: we have to think about the optional environment parameter, // currently just set to NULL. iResult=pCH->CreateComponent(pConf->GetComponentID(), pComponent); if (pComponent && iResult>=0) { pComponent->SetTimeStamp(AliHLTBaseVGRPAccess::GetStartTime()); TString description; description.Form("chainid=%s", GetName()); pComponent->SetComponentDescription(description.Data()); const AliHLTAnalysisEnvironment* pEnv=pCH->GetEnvironment(); if ((iResult=pComponent->Init(pEnv, NULL, argc, argv))>=0) { //HLTDebug("component %s (%p) created", pComponent->GetComponentID(), pComponent); } else { HLTError("Initialization of component \"%s\" failed with error %d", pComponent->GetComponentID(), iResult); } } else { //HLTError("can not find component \"%s\" (%d)", pConf->GetComponentID(), iResult); } } else { HLTError("can not get argument list for configuration %s (%s)", pConf->GetName(), pConf->GetComponentID()); iResult=-EINVAL; } } else { HLTError("component handler instance needed for task initialization"); iResult=-EINVAL; } } else { HLTError("configuration object instance needed for task initialization"); iResult=-EINVAL; } return iResult; } int AliHLTTask::Deinit() { // see header file for function documentation int iResult=0; CustomCleanup(); AliHLTComponent* pComponent=GetComponent(); fpComponent=NULL; if (pComponent) { //HLTDebug("delete component %s (%p)", pComponent->GetComponentID(), pComponent); pComponent->SetTimeStamp(AliHLTBaseVGRPAccess::GetEndTime()); pComponent->Deinit(); delete pComponent; } else { HLTWarning("task doesn't seem to be in initialized"); } return iResult; } const char *AliHLTTask::GetName() const { // see header file for function documentation if (fpConfiguration) return fpConfiguration->GetName(); return TObject::GetName(); } AliHLTConfiguration* AliHLTTask::GetConf() const { // see header file for function documentation return fpConfiguration; } AliHLTComponent* AliHLTTask::GetComponent() const { // see header file for function documentation return fpComponent; } AliHLTTask* AliHLTTask::FindDependency(const char* id) { // see header file for function documentation AliHLTTask* pTask=NULL; if (id) { pTask=(AliHLTTask*)fListDependencies.FindObject(id); } return pTask; } int AliHLTTask::FollowDependency(const char* id, TList* pTgtList) { // see header file for function documentation int iResult=0; if (id) { AliHLTTask* pDep=NULL; if ((pDep=(AliHLTTask*)fListDependencies.FindObject(id))!=NULL) { if (pTgtList) pTgtList->Add(pDep); iResult++; } else { TObjLink* lnk=fListDependencies.FirstLink(); while (lnk && iResult==0) { pDep=(AliHLTTask*)lnk->GetObject(); if (pDep) { if ((iResult=pDep->FollowDependency(id, pTgtList))>0) { if (pTgtList) pTgtList->AddFirst(pDep); iResult++; } } else { iResult=-EFAULT; } lnk=lnk->Next(); } } } else { iResult=-EINVAL; } return iResult; } void AliHLTTask::PrintDependencyTree(const char* id, int bFromConfiguration) { // see header file for function documentation HLTLogKeyword("task dependencies"); int iResult=0; TList tgtList; if (bFromConfiguration) { if (fpConfiguration) iResult=fpConfiguration->FollowDependency(id, &tgtList); else iResult=-EFAULT; } else iResult=FollowDependency(id, &tgtList); if (iResult>0) { HLTMessage(" dependency level %d ", iResult); TObjLink* lnk=tgtList.FirstLink(); int i=iResult; char* pSpace = new char[iResult+1]; if (pSpace) { memset(pSpace, 32, iResult); pSpace[i]=0; while (lnk) { TObject* obj=lnk->GetObject(); HLTMessage(" %s^-- %s ", &pSpace[i--], obj->GetName()); lnk=lnk->Next(); } delete [] pSpace; } else { iResult=-ENOMEM; } } } int AliHLTTask::SetDependency(AliHLTTask* pDep) { // see header file for function documentation int iResult=0; if (pDep) { if (FindDependency(pDep->GetName())==NULL) { fListDependencies.Add(pDep); } else { iResult=-EEXIST; } } else { iResult=-EINVAL; } return iResult; } int AliHLTTask::UnsetDependency(AliHLTTask* pDep) { // see header file for function documentation fListDependencies.Remove(pDep); if (fpConfiguration) { fpConfiguration->InvalidateSources(); } return 0; } int AliHLTTask::CheckDependencies() { // see header file for function documentation int iResult=0; AliHLTConfiguration* pSrc=fpConfiguration->GetFirstSource(); while (pSrc) { if (FindDependency(pSrc->GetName())==NULL) { //HLTDebug("dependency \"%s\" unresolved", pSrc->GetName()); iResult++; } pSrc=fpConfiguration->GetNextSource(); } return iResult; } int AliHLTTask::Depends(AliHLTTask* pTask) { // see header file for function documentation int iResult=0; if (pTask) { if (fpConfiguration) { iResult=fpConfiguration->GetSource(pTask->GetName())!=NULL; if (iResult>0) { //HLTDebug("task \"%s\" depends on \"%s\"", GetName(), pTask->GetName()); } else { //HLTDebug("task \"%s\" independend of \"%s\"", GetName(), pTask->GetName()); } } else { iResult=-EFAULT; } } else { iResult=-EINVAL; } return iResult; } AliHLTTask* AliHLTTask::FindTarget(const char* id) { // see header file for function documentation AliHLTTask* pTask=NULL; if (id) { pTask=(AliHLTTask*)fListTargets.FindObject(id); } return pTask; } int AliHLTTask::SetTarget(AliHLTTask* pTgt) { // see header file for function documentation int iResult=0; if (pTgt) { if (FindTarget(pTgt->GetName())==NULL) { fListTargets.Add(pTgt); } else { iResult=-EEXIST; } } else { iResult=-EINVAL; } return iResult; } int AliHLTTask::UnsetTarget(AliHLTTask* pTarget) { // see header file for function documentation fListTargets.Remove(pTarget); return 0; } int AliHLTTask::StartRun() { // see header file for function documentation int iResult=0; int iNofInputDataBlocks=0; AliHLTComponent* pComponent=GetComponent(); if (pComponent) { // determine the number of input data blocks provided from the source tasks { // set scope for lnk as a local variable TObjLink* lnk=fListDependencies.FirstLink(); while (lnk && iResult>=0) { AliHLTTask* pSrcTask=(AliHLTTask*)lnk->GetObject(); if (pSrcTask) { if ((iResult=pSrcTask->GetNofMatchingDataTypes(this))>0) { iNofInputDataBlocks+=iResult; } else if (iResult==0) { HLTWarning("source task %s (%p) does not provide any matching data type for task %s (%p)", pSrcTask->GetName(), pSrcTask, GetName(), this); } else { HLTError("task %s (%p): error getting matching data types for source task %s (%p)", GetName(), this, pSrcTask->GetName(), pSrcTask); iResult=-EFAULT; } } lnk=lnk->Next(); } } if (iResult>=0) { if (fBlockDataArray.size()>0) { HLTWarning("block data array for task %s (%p) was not cleaned", GetName(), this); fBlockDataArray.clear(); } // component init // the initialization of the component is done by the ComponentHandler after creation // of the component. //iResult=Init( AliHLTAnalysisEnvironment* environ, void* environ_param, int argc, const char** argv ); // allocate the data buffer, which controls the output buffer and subscriptions if (iResult>=0) { fpDataBuffer=new AliHLTDataBuffer; if (fpDataBuffer!=NULL) { fpDataBuffer->SetLocalLoggingLevel(GetLocalLoggingLevel()); HLTDebug("created data buffer %p for task %s (%p)", fpDataBuffer, GetName(), this); TObjLink* lnk=fListTargets.FirstLink(); while (lnk && iResult>=0) { AliHLTTask* pTgtTask=(AliHLTTask*)lnk->GetObject(); if (pTgtTask) { if ((iResult=fpDataBuffer->SetConsumer(pTgtTask->GetComponent()))>=0) { } } else { iResult=-EFAULT; break; } lnk=lnk->Next(); } } else { HLTFatal("can not create data buffer object, memory allocation failed"); iResult=-ENOMEM; } } } if (iResult>=0) { // send the SOR event } } else { HLTError("task %s (%p) does not have a component", GetName(), this); iResult=-EFAULT; } return iResult; } int AliHLTTask::EndRun() { // see header file for function documentation int iResult=0; if (fBlockDataArray.size()>0) { fBlockDataArray.clear(); } if (fpDataBuffer) { AliHLTDataBuffer* pBuffer=fpDataBuffer; fpDataBuffer=NULL; delete pBuffer; } return iResult; } int AliHLTTask::ProcessTask(Int_t eventNo, AliHLTUInt32_t eventType, AliHLTTriggerMask_t trgMask, AliHLTUInt32_t timestamp, AliHLTUInt32_t participatingDetectors) { // see header file for function documentation int iResult=0; AliHLTComponent* pComponent=GetComponent(); if (pComponent && fpDataBuffer) { HLTDebug("Processing task %s (%p) fpDataBuffer %p", GetName(), this, fpDataBuffer); fpDataBuffer->Reset(); int iSourceDataBlock=0; int iInputDataVolume=0; AliHLTTask* pSrcTask=NULL; AliHLTTaskPList subscribedTaskList; TObjLink* lnk=fListDependencies.FirstLink(); // instances of SOR and EOR events to be kept int iSOR=-1; int iEOR=-1; // TODO 2009-09-30 // generalize handling of the special blocks to be forwarded on SOR and EOR // just adding a new specific handling for the ECS parameter block as a quick // solution int iECS=-1; // subscribe to all source tasks fBlockDataArray.clear(); while (lnk && iResult>=0) { pSrcTask=(AliHLTTask*)lnk->GetObject(); if (pSrcTask) { int iMatchingDB=pSrcTask->GetNofMatchingDataBlocks(this); if (iMatchingDB<0) { HLTError("task %s (%p): error getting no of matching data blocks from task %s (%p), error %d", GetName(), this, pSrcTask->GetName(), pSrcTask, iMatchingDB); iResult=iMatchingDB; break; } else if (iMatchingDB==0) { HLTDebug("source task %s (%p) does not provide any matching data type for task %s (%p)", pSrcTask->GetName(), pSrcTask, GetName(), this); } if ((iResult=pSrcTask->Subscribe(this, fBlockDataArray))>=0) { iSOR=iEOR=iECS=-1; AliHLTComponentBlockDataList::iterator block=fBlockDataArray.begin(); for (int i=0; block!=fBlockDataArray.end(); i++) { bool bRemove=0; bRemove|=(*block).fDataType==kAliHLTDataTypeSOR && !(iSOR<0 && (iSOR=i)>=0); bRemove|=(*block).fDataType==kAliHLTDataTypeEOR && !(iEOR<0 && (iEOR=i)>=0); bRemove|=(*block).fDataType==kAliHLTDataTypeECSParam && !(iECS<0 && (iECS=i)>=0); //HLTInfo("block %d, iSOR=%d iEOR=%d remove=%d", i, iSOR, iEOR, bRemove); if (i<iSourceDataBlock) { assert(!bRemove); } else if (bRemove) { HLTDebug("remove duplicated event %s (%d)", AliHLTComponent::DataType2Text((*block).fDataType).c_str(), i); pSrcTask->Release(&(*block), this); block=fBlockDataArray.erase(block); continue; } else { iInputDataVolume+=(*block).fSize; // put the source task as many times into the list as it provides data blocks // makes the bookkeeping for the data release easier subscribedTaskList.push_back(pSrcTask); } block++; } HLTDebug("Task %s (%p) successfully subscribed to %d data block(s) of task %s (%p)", GetName(), this, iResult, pSrcTask->GetName(), pSrcTask); iSourceDataBlock=fBlockDataArray.size(); iResult=0; } else { HLTError("Task %s (%p): subscription to task %s (%p) failed with error %d", GetName(), this, pSrcTask->GetName(), pSrcTask, iResult); iResult=-EFAULT; } } else { HLTFatal("fatal internal error in ROOT list handling"); iResult=-EFAULT; } lnk=lnk->Next(); } // process the event int iNofTrial=0; // repeat processing if component returns -ENOSPC AliHLTUInt32_t iLastOutputDataSize=0; if (iResult>=0) { do { long unsigned int iOutputDataSize=0; AliHLTConfiguration* pConf=GetConf(); // check if there was a buffer size specified, query output size // estimator from component otherwize if (pConf && pConf->GetOutputBufferSize()>=0) { iOutputDataSize=pConf->GetOutputBufferSize(); } else { long unsigned int iConstBase=0; double fInputMultiplier=0; if (pComponent->GetComponentType()!=AliHLTComponent::kSink) { pComponent->GetOutputDataSize(iConstBase, fInputMultiplier); // add a small margin to the buffer to allow optional component // statistics iConstBase+=100; #if defined(__DEBUG) || defined(HLT_COMPONENT_STATISTICS) for (AliHLTComponentBlockDataList::iterator element=fBlockDataArray.begin(); element!=fBlockDataArray.end(); element++) { if (element->fDataType==kAliHLTDataTypeComponentStatistics) { iConstBase+=element->fSize; } } #endif } if (fInputMultiplier<0) { HLTWarning("ignoring negative input multiplier"); fInputMultiplier=0; } iOutputDataSize=(long unsigned int)(fInputMultiplier*iInputDataVolume) + iConstBase; //HLTDebug("task %s: reqired output size %d", GetName(), iOutputDataSize); } if (fpDataBuffer->GetMaxBufferSize() < iOutputDataSize) { //If the estimated buffer size exceeds the maximum buffer size of AliHLTRawBuffer, decrease the buffer size. //The estimation is often quite high, and GetMaxBufferSize should usually return a size that is sufficient. HLTImportant("Reducing estimated output buffer size of %lu to maximum output buffer size (%lu)\n", iOutputDataSize, fpDataBuffer->GetMaxBufferSize()); iOutputDataSize = fpDataBuffer->GetMaxBufferSize(); } if (iNofTrial>0) { // dont process again if the buffer size is the same if (iLastOutputDataSize>=iOutputDataSize) break; HLTImportant("processing event %d again with buffer size %d", eventNo, iOutputDataSize); } AliHLTUInt8_t* pTgtBuffer=NULL; if (iOutputDataSize>0) pTgtBuffer=fpDataBuffer->GetTargetBuffer(iOutputDataSize); //HLTDebug("provided raw buffer %p", pTgtBuffer); AliHLTComponentEventData evtData; AliHLTComponent::FillEventData(evtData); if (eventNo>=0) evtData.fEventID=(AliHLTEventID_t)eventNo; if (timestamp < kMaxUInt) evtData.fEventCreation_s=timestamp; else evtData.fEventCreation_s=static_cast<AliHLTUInt32_t>(time(NULL)); AliHLTComponentTriggerData trigData; AliHLTEventTriggerData evtTrigData; trigData.fStructSize=sizeof(trigData); trigData.fDataSize=sizeof(AliHLTEventTriggerData); memset(&evtTrigData, 0, trigData.fDataSize); // Setup the CDH in the trigger data, based on the event type, CTP trigger // mask and participating detectors. evtTrigData.fCommonHeaderWordCnt=gkAliHLTCommonHeaderCount; AliHLTUInt8_t l1msg = 0x0; switch (eventType) { case gkAliEventTypeData: l1msg = 0x00; break; case gkAliEventTypeDataReplay: l1msg = 0x00; break; case gkAliEventTypeStartOfRun: l1msg = (0xE << 2) | 0x01; break; case gkAliEventTypeEndOfRun: l1msg = (0xF << 2) | 0x01; break; case gkAliEventTypeCalibration: l1msg = (0x1 << 6) | 0x01; break; case gkAliEventTypeSoftware: l1msg = 0x01; break; } evtTrigData.fCommonHeader[1] = (AliHLTUInt32_t(l1msg) << 14) | (0x03000000); //We have to set a CDH version, use 3 because we support 100 trigger classes below (0x03000000) evtTrigData.fCommonHeader[3] = ((l1msg & 0x1) == 0x1) ? (participatingDetectors & 0xFFFFFF) : 0x0; evtTrigData.fCommonHeader[5] = (trgMask & AliHLTTriggerMask_t(0xffffffff)).to_ulong(); evtTrigData.fCommonHeader[6] = ((trgMask>>32) & AliHLTTriggerMask_t(0x3ffff)).to_ulong(); evtTrigData.fCommonHeader[7] = ((trgMask>>50) & AliHLTTriggerMask_t(0xffffffff)).to_ulong(); evtTrigData.fCommonHeader[8] = ((trgMask>>72) & AliHLTTriggerMask_t(0x3ffff)).to_ulong(); trigData.fData=&evtTrigData; iLastOutputDataSize=iOutputDataSize; AliHLTUInt32_t size=iOutputDataSize; AliHLTUInt32_t outputBlockCnt=0; AliHLTComponentBlockData* outputBlocks=NULL; AliHLTComponentEventDoneData* edd=NULL; if (pTgtBuffer!=NULL || iOutputDataSize==0) { // add event type data block // the block is removed immediately after processing from the list AliHLTComponentBlockData eventTypeBlock; AliHLTComponent::FillBlockData(eventTypeBlock); // Note: no payload! eventTypeBlock.fDataType=kAliHLTDataTypeEvent; eventTypeBlock.fSpecification=eventType; fBlockDataArray.push_back(eventTypeBlock); if (CheckFilter(kHLTLogDebug)) Print("proc"); AliHLTUInt32_t iblock=0; // check input and output buffers for consistency // to be enabled after fixing bug with DataBuffer and forwarded SOR/EOR //for (iblock=0; iblock<fBlockDataArray.size(); iblock++) { // if ((AliHLTUInt8_t*)fBlockDataArray[iblock].fPtr >= pTgtBuffer+size) continue; // if (pTgtBuffer >= (AliHLTUInt8_t*)fBlockDataArray[iblock].fPtr+fBlockDataArray[iblock].fSize) continue; // HLTFatal("input and output buffer overlap for block descriptor %d (ptr %p size %d): output buffer %p %d", // iblock, fBlockDataArray[iblock].fPtr, fBlockDataArray[iblock].fSize, // pTgtBuffer, size); //} // process evtData.fBlockCnt=fBlockDataArray.size(); iResult=pComponent->ProcessEvent(evtData, &fBlockDataArray[0], trigData, pTgtBuffer, size, outputBlockCnt, outputBlocks, edd); HLTDebug("component %s ProcessEvent finnished (%d): size=%d blocks=%d", pComponent->GetComponentID(), iResult, size, outputBlockCnt); // EventDoneData is for the moment ignored in AliHLTSystem if (edd) { HLTDebug("got EventDoneData size %d", edd->fDataSize); delete [] reinterpret_cast<char*>(edd); edd=NULL; } // remove event data block fBlockDataArray.pop_back(); // check for forwarded blocks. // loop over all output blocks and check // 1. for duplicate blocks (pointing to same location in output buffer // or to the same buffer) // 2. for blocks forwarded from the input. if (iResult>=0 && outputBlocks) { if (fListTargets.First()!=NULL) { AliHLTComponentBlockDataList segments; for (AliHLTUInt32_t oblock=0; oblock<outputBlockCnt; oblock++) { // consistency check for data reference if (outputBlocks[oblock].fPtr!=NULL && outputBlocks[oblock].fPtr!=pTgtBuffer && outputBlocks[oblock].fOffset!=0) { HLTWarning("output block %s 0x%08x has inconsistent data reference ptr=%p offset=0x%08x: " "for new blocks use offset only, forwarded blocks have fPtr set only", AliHLTComponent::DataType2Text(outputBlocks[oblock].fDataType).c_str(), outputBlocks[oblock].fSpecification, outputBlocks[oblock].fPtr, outputBlocks[oblock].fOffset); } // check for duplicates in the output // this check applies for forwarded data blocks where // the ptr is not inside the target buffer AliHLTUInt32_t checkblock=0; for (; checkblock<oblock; checkblock++) { if (outputBlocks[oblock].fPtr!=NULL && outputBlocks[oblock].fPtr!=pTgtBuffer && outputBlocks[checkblock].fPtr==outputBlocks[oblock].fPtr) { if (outputBlocks[checkblock].fSize!=outputBlocks[oblock].fSize || outputBlocks[checkblock].fDataType!=outputBlocks[oblock].fDataType) { HLTWarning("output blocks %d (%s 0x%08x) and %d (%s 0x%08x) have identical data references ptr=%p " "but differ in data type and/or size: %d vs. %d, ignoring block %d", oblock, AliHLTComponent::DataType2Text(outputBlocks[oblock].fDataType).c_str(), outputBlocks[oblock].fSpecification, checkblock, AliHLTComponent::DataType2Text(outputBlocks[checkblock].fDataType).c_str(), outputBlocks[checkblock].fSpecification, outputBlocks[oblock].fPtr, outputBlocks[oblock].fSize, outputBlocks[checkblock].fSize, checkblock); } // ignore from the second copy break; } } if (checkblock<oblock) continue; // search for the forwarded data blocks // new data blocks are announced to the data buffer, forwarded data blocks // to the publisher task. The publisher task of a forwarded data block is // removed from the list in order to keep the buffer open. It will be releases // when the subscribing task releases it iblock=0; for (; iblock<fBlockDataArray.size(); iblock++) { if (outputBlocks[oblock].fDataType==kAliHLTDataTypeEvent) { // the event type data block is an artificial data block // ignore if it was forwarded break; } if (fBlockDataArray[iblock].fPtr==outputBlocks[oblock].fPtr) { assert(subscribedTaskList[iblock]!=NULL); if (subscribedTaskList[iblock]==NULL) { ALIHLTERRORGUARD(1, "missing parent task for forwarded data block %s 0x%08x, original data block %s 0x%08x, subsequent errors are suppressed", AliHLTComponent::DataType2Text(outputBlocks[oblock].fDataType).c_str(), outputBlocks[oblock].fSpecification, AliHLTComponent::DataType2Text(outputBlocks[iblock].fDataType).c_str(), outputBlocks[iblock].fSpecification); continue; } HLTDebug("forward segment %d (source task %s %p) to data buffer %p", iblock, pSrcTask->GetName(), pSrcTask, fpDataBuffer); fpDataBuffer->Forward(subscribedTaskList[iblock], &fBlockDataArray[iblock]); subscribedTaskList[iblock]=NULL; // not to be released in the loop further down break; } } if (iblock==fBlockDataArray.size()) segments.push_back(outputBlocks[oblock]); } if (pTgtBuffer && segments.size()>0) { iResult=fpDataBuffer->SetSegments(pTgtBuffer, &segments[0], segments.size()); } } else { // no forwarding, actually we dont even need to keep the data, this is a // dead end (fListTargets empty) //iResult=fpDataBuffer->SetSegments(pTgtBuffer, outputBlocks, outputBlockCnt); } delete [] outputBlocks; outputBlocks=NULL; outputBlockCnt=0; } else { fpDataBuffer->Reset(); } if (fListTargets.First()!=NULL) { if (iSOR>=0 && subscribedTaskList[iSOR]!=NULL) { HLTDebug("forward SOR event segment %d (source task %s %p) to data buffer %p", iSOR, pSrcTask->GetName(), pSrcTask, fpDataBuffer); fpDataBuffer->Forward(subscribedTaskList[iSOR], &fBlockDataArray[iSOR]); subscribedTaskList[iSOR]=NULL; // not to be released in the loop further down } if (iEOR>=0 && subscribedTaskList[iEOR]!=NULL) { HLTDebug("forward EOR event (%s) segment %d (source task %s %p) to data buffer %p", AliHLTComponent::DataType2Text(fBlockDataArray[iEOR].fDataType).c_str(), iEOR, pSrcTask->GetName(), pSrcTask, fpDataBuffer); fpDataBuffer->Forward(subscribedTaskList[iEOR], &fBlockDataArray[iEOR]); subscribedTaskList[iEOR]=NULL; // not to be released in the loop further down } if (iECS>=0 && subscribedTaskList[iECS]!=NULL) { HLTDebug("forward ECS event (%s) segment %d (source task %s %p) to data buffer %p", AliHLTComponent::DataType2Text(fBlockDataArray[iECS].fDataType).c_str(), iECS, pSrcTask->GetName(), pSrcTask, fpDataBuffer); fpDataBuffer->Forward(subscribedTaskList[iECS], &fBlockDataArray[iECS]); subscribedTaskList[iECS]=NULL; // not to be released in the loop further down } } } else { HLTError("no target buffer available"); iResult=-EFAULT; } } while (iResult==-ENOSPC && iNofTrial++<1); } if (CheckFilter(kHLTLogDebug)) Print("proc"); // now release all buffers which we have subscribed to iSourceDataBlock=0; AliHLTTaskPList::iterator element; while ((element=subscribedTaskList.begin())!=subscribedTaskList.end()) { pSrcTask=*element; if (pSrcTask) { int iTempRes=0; if ((iTempRes=pSrcTask->Release(&fBlockDataArray[iSourceDataBlock], this))>=0) { HLTDebug("successfully released segment of task %s (%p)", pSrcTask->GetName(), pSrcTask); } else { HLTError("realease of task %s (%p) failed with error %d", pSrcTask->GetName(), pSrcTask, iTempRes); } } subscribedTaskList.erase(element); iSourceDataBlock++; } if (subscribedTaskList.size()>0) { HLTError("could not release all data buffers"); } fBlockDataArray.clear(); } else { HLTError("internal failure (not initialized component %p, data buffer %p)", fpComponent, fpDataBuffer); iResult=-EFAULT; } return iResult; } int AliHLTTask::SubscribeSourcesAndSkip() { // function carries out the proper cleanup of the source components // by subscribing and releasing int iResult=0; AliHLTTask* pSrcTask=NULL; AliHLTTaskPList subscribedTaskList; // cleanup the data buffer if (fpDataBuffer) fpDataBuffer->Reset(); // subscribe to all source tasks fBlockDataArray.clear(); for (TObjLink* lnk=fListDependencies.FirstLink(); lnk!=NULL; lnk=lnk->Next()) { if (!lnk->GetObject()) continue; pSrcTask=dynamic_cast<AliHLTTask*>(lnk->GetObject()); if (!pSrcTask) continue; unsigned iPosition=fBlockDataArray.size(); if ((iResult=pSrcTask->Subscribe(this, fBlockDataArray))>0) { for (unsigned i=iPosition; i<fBlockDataArray.size(); i++) { subscribedTaskList.push_back(pSrcTask); } HLTDebug("subscribed to %d blocks of task %s (%p)", iResult, pSrcTask->GetName(), pSrcTask, iResult); } else if (iResult<0) { HLTError("failed to subscribe to task %s (%p) with error %d", pSrcTask->GetName(), pSrcTask, iResult); } } unsigned iSourceDataBlock=0; AliHLTTaskPList::iterator element; while ((element=subscribedTaskList.begin())!=subscribedTaskList.end()) { assert(iSourceDataBlock<fBlockDataArray.size()); pSrcTask=*element; if (pSrcTask && iSourceDataBlock<fBlockDataArray.size()) { if ((iResult=pSrcTask->Release(&fBlockDataArray[iSourceDataBlock], this))>=0) { HLTDebug("successfully released segment of task %s (%p)", pSrcTask->GetName(), pSrcTask); } else if (iSourceDataBlock>=fBlockDataArray.size()) { HLTError("mismatch between list of subscribed tasks and block list in task %s (%p), can not release task %s (%p)", GetName(), this, pSrcTask->GetName(), pSrcTask); } else { HLTError("realease of task %s (%p) failed with error %d", pSrcTask->GetName(), pSrcTask, iResult); } } subscribedTaskList.erase(element); iSourceDataBlock++; } if (iSourceDataBlock<fBlockDataArray.size()) { HLTWarning("not all subscriptions released for task %s (%p)", GetName(), this); } return 0; } int AliHLTTask::GetNofMatchingDataBlocks(const AliHLTTask* pConsumerTask) const { // see header file for function documentation int iResult=0; if (pConsumerTask) { if (fpDataBuffer) { iResult=fpDataBuffer->FindMatchingDataBlocks(pConsumerTask->GetComponent(), NULL); } else { HLTFatal("internal data buffer missing"); iResult=-EFAULT; } } else { iResult=-EINVAL; } return iResult; } int AliHLTTask::GetNofMatchingDataTypes(const AliHLTTask* pConsumerTask) const { // see header file for function documentation int iResult=0; if (pConsumerTask) { AliHLTComponent* pComponent=GetComponent(); if (!pComponent) { // init ? HLTError("component not initialized"); iResult=-EFAULT; } if (pComponent) { iResult=pComponent->FindMatchingDataTypes(pConsumerTask->GetComponent(), NULL); } else { HLTFatal("task initialization failed"); iResult=-EFAULT; } } else { iResult=-EINVAL; } return iResult; } int AliHLTTask::Subscribe(const AliHLTTask* pConsumerTask, AliHLTComponentBlockDataList& blockDescList) { // see header file for function documentation int iResult=0; if (pConsumerTask) { if (fpDataBuffer) { iResult=fpDataBuffer->Subscribe(pConsumerTask->GetComponent(), blockDescList); } else { HLTFatal("internal data buffer missing"); iResult=-EFAULT; } } else { iResult=-EINVAL; } return iResult; } int AliHLTTask::Release(AliHLTComponentBlockData* pBlockDesc, const AliHLTTask* pConsumerTask) { // see header file for function documentation int iResult=0; if (pConsumerTask && pBlockDesc) { if (fpDataBuffer) { iResult=fpDataBuffer->Release(pBlockDesc, pConsumerTask->GetComponent(), this); } else { HLTFatal("internal data buffer missing"); iResult=-EFAULT; } } else { iResult=-EINVAL; } return iResult; } void AliHLTTask::PrintStatus() { // see header file for function documentation HLTLogKeyword("task properties"); AliHLTComponent* pComponent=GetComponent(); if (pComponent) { HLTMessage(" component: %s (%p)", pComponent->GetComponentID(), pComponent); } else { HLTMessage(" no component set!"); } if (fpConfiguration) { AliHLTConfiguration* pSrc=fpConfiguration->GetFirstSource(); while (pSrc) { const char* pQualifier="unresolved"; if (FindDependency(pSrc->GetName())) pQualifier="resolved"; HLTMessage(" source: %s (%s)", pSrc->GetName(), pQualifier); pSrc=fpConfiguration->GetNextSource(); } TObjLink* lnk = fListTargets.FirstLink(); while (lnk) { TObject *obj = lnk->GetObject(); HLTMessage(" target: %s", obj->GetName()); lnk = lnk->Next(); } } else { HLTMessage(" task not initialized"); } } void AliHLTTask::Print(const char* options) const { // Overloaded from TObject if (strcmp(options, "proc")==0) { // print processing info HLTMessage("**********************************************"); HLTMessage("******* AliHLTTask Processing info ***********"); HLTMessage(" component: %p %s", fpComponent, (fpComponent?fpComponent->GetComponentID():"")); HLTMessage(" data buffer: %p", fpDataBuffer); if (fpDataBuffer) fpDataBuffer->Print(""); HLTMessage(" input block descriptors: %d", fBlockDataArray.size()); for (unsigned i=0; i<fBlockDataArray.size(); i++) { HLTMessage(" %d: %s 0x%08x %p %d", i, AliHLTComponent::DataType2Text(fBlockDataArray[i].fDataType).c_str(), fBlockDataArray[i].fSpecification, fBlockDataArray[i].fPtr, fBlockDataArray[i].fSize ); } HLTMessage("**** end of AliHLTTask Processing info *******"); HLTMessage("**********************************************"); return; } cout << "AliHLTTask " << GetName() << " " << this << " component " << fpComponent << " " << (fpComponent?fpComponent->GetComponentID():"") << endl; } int AliHLTTask::CustomInit(AliHLTComponentHandler* /*pCH*/) { // default implementation nothing to do return 0; } int AliHLTTask::CustomCleanup() { // default implementation nothing to do return 0; } int AliHLTTask::LoggingVarargs(AliHLTComponentLogSeverity severity, const char* originClass, const char* originFunc, const char* file, int line, ... ) const { // see header file for function documentation int iResult=0; va_list args; va_start(args, line); AliHLTLogging::SetLogString(this, " (%p)", "%s_pfmt_: ", GetName()); iResult=SendMessage(severity, originClass, originFunc, file, line, AliHLTLogging::BuildLogString(NULL, args, true /*append*/)); va_end(args); return iResult; } make it a fatal error when HLT can not allocate target buffers for components. Can be really dangerous when this is unnoticed in MC simulation! Can lead either to a crash during reconstruction or even to corrupt data for other events // $Id$ //************************************************************************** //* This file is property of and copyright by the * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /// @file AliHLTTask.cxx /// @author Matthias Richter /// @date /// @brief Implementation of HLT tasks. /// #include <cerrno> #include <cassert> #include <iostream> #include <string> #include <ctime> #include "AliHLTTask.h" #include "AliHLTConfiguration.h" #include "AliHLTConfigurationHandler.h" #include "AliHLTComponent.h" #include "AliHLTComponentHandler.h" #include "AliHLTBaseVGRPAccess.h" #include "TList.h" #include "AliHLTErrorGuard.h" using std::cout; /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTTask) AliHLTTask::AliHLTTask() : fpConfiguration(NULL), fpComponent(NULL), fpDataBuffer(NULL), fListTargets(), fListDependencies(), fBlockDataArray() { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTTask::AliHLTTask(AliHLTConfiguration* pConf) : fpConfiguration(pConf), fpComponent(NULL), fpDataBuffer(NULL), fListTargets(), fListDependencies(), fBlockDataArray() { // see header file for function documentation } AliHLTTask::~AliHLTTask() { // see header file for function documentation TObjLink* lnk=fListDependencies.FirstLink(); while (lnk!=NULL) { AliHLTTask* pTask=(AliHLTTask*)lnk->GetObject(); pTask->UnsetTarget(this); lnk=lnk->Next(); } lnk=fListTargets.FirstLink(); while (lnk!=NULL) { AliHLTTask* pTask=(AliHLTTask*)lnk->GetObject(); pTask->UnsetDependency(this); lnk=lnk->Next(); } if (fpComponent) delete fpComponent; fpComponent=NULL; } int AliHLTTask::Init(AliHLTConfiguration* pConf, AliHLTComponentHandler* pCH) { // see header file for function documentation int iResult=0; if (fpConfiguration!=NULL && pConf!=NULL && fpConfiguration!=pConf) { HLTWarning("overriding existing reference to configuration object %p by %p", fpConfiguration, pConf); } if (pConf!=NULL) fpConfiguration=pConf; iResult=CreateComponent(fpConfiguration, pCH, fpComponent); if (iResult>=0) { iResult=CustomInit(pCH); } return iResult; } int AliHLTTask::CreateComponent(AliHLTConfiguration* pConfiguration, AliHLTComponentHandler* pCH, AliHLTComponent*& pComponent) const { // see header file for class documentation int iResult=0; if (!pConfiguration) return -EINVAL; const AliHLTConfiguration* pConf=AliHLTConfigurationHandler::FindSubstitution(*pConfiguration); if (!pConf) pConf=pConfiguration; if (pConf) { if (pCH) { int argc=0; const char** argv=NULL; if ((iResult=pConf->GetArguments(&argv))>=0) { argc=iResult; // just to make it clear // TODO: we have to think about the optional environment parameter, // currently just set to NULL. iResult=pCH->CreateComponent(pConf->GetComponentID(), pComponent); if (pComponent && iResult>=0) { pComponent->SetTimeStamp(AliHLTBaseVGRPAccess::GetStartTime()); TString description; description.Form("chainid=%s", GetName()); pComponent->SetComponentDescription(description.Data()); const AliHLTAnalysisEnvironment* pEnv=pCH->GetEnvironment(); if ((iResult=pComponent->Init(pEnv, NULL, argc, argv))>=0) { //HLTDebug("component %s (%p) created", pComponent->GetComponentID(), pComponent); } else { HLTError("Initialization of component \"%s\" failed with error %d", pComponent->GetComponentID(), iResult); } } else { //HLTError("can not find component \"%s\" (%d)", pConf->GetComponentID(), iResult); } } else { HLTError("can not get argument list for configuration %s (%s)", pConf->GetName(), pConf->GetComponentID()); iResult=-EINVAL; } } else { HLTError("component handler instance needed for task initialization"); iResult=-EINVAL; } } else { HLTError("configuration object instance needed for task initialization"); iResult=-EINVAL; } return iResult; } int AliHLTTask::Deinit() { // see header file for function documentation int iResult=0; CustomCleanup(); AliHLTComponent* pComponent=GetComponent(); fpComponent=NULL; if (pComponent) { //HLTDebug("delete component %s (%p)", pComponent->GetComponentID(), pComponent); pComponent->SetTimeStamp(AliHLTBaseVGRPAccess::GetEndTime()); pComponent->Deinit(); delete pComponent; } else { HLTWarning("task doesn't seem to be in initialized"); } return iResult; } const char *AliHLTTask::GetName() const { // see header file for function documentation if (fpConfiguration) return fpConfiguration->GetName(); return TObject::GetName(); } AliHLTConfiguration* AliHLTTask::GetConf() const { // see header file for function documentation return fpConfiguration; } AliHLTComponent* AliHLTTask::GetComponent() const { // see header file for function documentation return fpComponent; } AliHLTTask* AliHLTTask::FindDependency(const char* id) { // see header file for function documentation AliHLTTask* pTask=NULL; if (id) { pTask=(AliHLTTask*)fListDependencies.FindObject(id); } return pTask; } int AliHLTTask::FollowDependency(const char* id, TList* pTgtList) { // see header file for function documentation int iResult=0; if (id) { AliHLTTask* pDep=NULL; if ((pDep=(AliHLTTask*)fListDependencies.FindObject(id))!=NULL) { if (pTgtList) pTgtList->Add(pDep); iResult++; } else { TObjLink* lnk=fListDependencies.FirstLink(); while (lnk && iResult==0) { pDep=(AliHLTTask*)lnk->GetObject(); if (pDep) { if ((iResult=pDep->FollowDependency(id, pTgtList))>0) { if (pTgtList) pTgtList->AddFirst(pDep); iResult++; } } else { iResult=-EFAULT; } lnk=lnk->Next(); } } } else { iResult=-EINVAL; } return iResult; } void AliHLTTask::PrintDependencyTree(const char* id, int bFromConfiguration) { // see header file for function documentation HLTLogKeyword("task dependencies"); int iResult=0; TList tgtList; if (bFromConfiguration) { if (fpConfiguration) iResult=fpConfiguration->FollowDependency(id, &tgtList); else iResult=-EFAULT; } else iResult=FollowDependency(id, &tgtList); if (iResult>0) { HLTMessage(" dependency level %d ", iResult); TObjLink* lnk=tgtList.FirstLink(); int i=iResult; char* pSpace = new char[iResult+1]; if (pSpace) { memset(pSpace, 32, iResult); pSpace[i]=0; while (lnk) { TObject* obj=lnk->GetObject(); HLTMessage(" %s^-- %s ", &pSpace[i--], obj->GetName()); lnk=lnk->Next(); } delete [] pSpace; } else { iResult=-ENOMEM; } } } int AliHLTTask::SetDependency(AliHLTTask* pDep) { // see header file for function documentation int iResult=0; if (pDep) { if (FindDependency(pDep->GetName())==NULL) { fListDependencies.Add(pDep); } else { iResult=-EEXIST; } } else { iResult=-EINVAL; } return iResult; } int AliHLTTask::UnsetDependency(AliHLTTask* pDep) { // see header file for function documentation fListDependencies.Remove(pDep); if (fpConfiguration) { fpConfiguration->InvalidateSources(); } return 0; } int AliHLTTask::CheckDependencies() { // see header file for function documentation int iResult=0; AliHLTConfiguration* pSrc=fpConfiguration->GetFirstSource(); while (pSrc) { if (FindDependency(pSrc->GetName())==NULL) { //HLTDebug("dependency \"%s\" unresolved", pSrc->GetName()); iResult++; } pSrc=fpConfiguration->GetNextSource(); } return iResult; } int AliHLTTask::Depends(AliHLTTask* pTask) { // see header file for function documentation int iResult=0; if (pTask) { if (fpConfiguration) { iResult=fpConfiguration->GetSource(pTask->GetName())!=NULL; if (iResult>0) { //HLTDebug("task \"%s\" depends on \"%s\"", GetName(), pTask->GetName()); } else { //HLTDebug("task \"%s\" independend of \"%s\"", GetName(), pTask->GetName()); } } else { iResult=-EFAULT; } } else { iResult=-EINVAL; } return iResult; } AliHLTTask* AliHLTTask::FindTarget(const char* id) { // see header file for function documentation AliHLTTask* pTask=NULL; if (id) { pTask=(AliHLTTask*)fListTargets.FindObject(id); } return pTask; } int AliHLTTask::SetTarget(AliHLTTask* pTgt) { // see header file for function documentation int iResult=0; if (pTgt) { if (FindTarget(pTgt->GetName())==NULL) { fListTargets.Add(pTgt); } else { iResult=-EEXIST; } } else { iResult=-EINVAL; } return iResult; } int AliHLTTask::UnsetTarget(AliHLTTask* pTarget) { // see header file for function documentation fListTargets.Remove(pTarget); return 0; } int AliHLTTask::StartRun() { // see header file for function documentation int iResult=0; int iNofInputDataBlocks=0; AliHLTComponent* pComponent=GetComponent(); if (pComponent) { // determine the number of input data blocks provided from the source tasks { // set scope for lnk as a local variable TObjLink* lnk=fListDependencies.FirstLink(); while (lnk && iResult>=0) { AliHLTTask* pSrcTask=(AliHLTTask*)lnk->GetObject(); if (pSrcTask) { if ((iResult=pSrcTask->GetNofMatchingDataTypes(this))>0) { iNofInputDataBlocks+=iResult; } else if (iResult==0) { HLTWarning("source task %s (%p) does not provide any matching data type for task %s (%p)", pSrcTask->GetName(), pSrcTask, GetName(), this); } else { HLTError("task %s (%p): error getting matching data types for source task %s (%p)", GetName(), this, pSrcTask->GetName(), pSrcTask); iResult=-EFAULT; } } lnk=lnk->Next(); } } if (iResult>=0) { if (fBlockDataArray.size()>0) { HLTWarning("block data array for task %s (%p) was not cleaned", GetName(), this); fBlockDataArray.clear(); } // component init // the initialization of the component is done by the ComponentHandler after creation // of the component. //iResult=Init( AliHLTAnalysisEnvironment* environ, void* environ_param, int argc, const char** argv ); // allocate the data buffer, which controls the output buffer and subscriptions if (iResult>=0) { fpDataBuffer=new AliHLTDataBuffer; if (fpDataBuffer!=NULL) { fpDataBuffer->SetLocalLoggingLevel(GetLocalLoggingLevel()); HLTDebug("created data buffer %p for task %s (%p)", fpDataBuffer, GetName(), this); TObjLink* lnk=fListTargets.FirstLink(); while (lnk && iResult>=0) { AliHLTTask* pTgtTask=(AliHLTTask*)lnk->GetObject(); if (pTgtTask) { if ((iResult=fpDataBuffer->SetConsumer(pTgtTask->GetComponent()))>=0) { } } else { iResult=-EFAULT; break; } lnk=lnk->Next(); } } else { HLTFatal("can not create data buffer object, memory allocation failed"); iResult=-ENOMEM; } } } if (iResult>=0) { // send the SOR event } } else { HLTError("task %s (%p) does not have a component", GetName(), this); iResult=-EFAULT; } return iResult; } int AliHLTTask::EndRun() { // see header file for function documentation int iResult=0; if (fBlockDataArray.size()>0) { fBlockDataArray.clear(); } if (fpDataBuffer) { AliHLTDataBuffer* pBuffer=fpDataBuffer; fpDataBuffer=NULL; delete pBuffer; } return iResult; } int AliHLTTask::ProcessTask(Int_t eventNo, AliHLTUInt32_t eventType, AliHLTTriggerMask_t trgMask, AliHLTUInt32_t timestamp, AliHLTUInt32_t participatingDetectors) { // see header file for function documentation int iResult=0; AliHLTComponent* pComponent=GetComponent(); if (pComponent && fpDataBuffer) { HLTDebug("Processing task %s (%p) fpDataBuffer %p", GetName(), this, fpDataBuffer); fpDataBuffer->Reset(); int iSourceDataBlock=0; int iInputDataVolume=0; AliHLTTask* pSrcTask=NULL; AliHLTTaskPList subscribedTaskList; TObjLink* lnk=fListDependencies.FirstLink(); // instances of SOR and EOR events to be kept int iSOR=-1; int iEOR=-1; // TODO 2009-09-30 // generalize handling of the special blocks to be forwarded on SOR and EOR // just adding a new specific handling for the ECS parameter block as a quick // solution int iECS=-1; // subscribe to all source tasks fBlockDataArray.clear(); while (lnk && iResult>=0) { pSrcTask=(AliHLTTask*)lnk->GetObject(); if (pSrcTask) { int iMatchingDB=pSrcTask->GetNofMatchingDataBlocks(this); if (iMatchingDB<0) { HLTError("task %s (%p): error getting no of matching data blocks from task %s (%p), error %d", GetName(), this, pSrcTask->GetName(), pSrcTask, iMatchingDB); iResult=iMatchingDB; break; } else if (iMatchingDB==0) { HLTDebug("source task %s (%p) does not provide any matching data type for task %s (%p)", pSrcTask->GetName(), pSrcTask, GetName(), this); } if ((iResult=pSrcTask->Subscribe(this, fBlockDataArray))>=0) { iSOR=iEOR=iECS=-1; AliHLTComponentBlockDataList::iterator block=fBlockDataArray.begin(); for (int i=0; block!=fBlockDataArray.end(); i++) { bool bRemove=0; bRemove|=(*block).fDataType==kAliHLTDataTypeSOR && !(iSOR<0 && (iSOR=i)>=0); bRemove|=(*block).fDataType==kAliHLTDataTypeEOR && !(iEOR<0 && (iEOR=i)>=0); bRemove|=(*block).fDataType==kAliHLTDataTypeECSParam && !(iECS<0 && (iECS=i)>=0); //HLTInfo("block %d, iSOR=%d iEOR=%d remove=%d", i, iSOR, iEOR, bRemove); if (i<iSourceDataBlock) { assert(!bRemove); } else if (bRemove) { HLTDebug("remove duplicated event %s (%d)", AliHLTComponent::DataType2Text((*block).fDataType).c_str(), i); pSrcTask->Release(&(*block), this); block=fBlockDataArray.erase(block); continue; } else { iInputDataVolume+=(*block).fSize; // put the source task as many times into the list as it provides data blocks // makes the bookkeeping for the data release easier subscribedTaskList.push_back(pSrcTask); } block++; } HLTDebug("Task %s (%p) successfully subscribed to %d data block(s) of task %s (%p)", GetName(), this, iResult, pSrcTask->GetName(), pSrcTask); iSourceDataBlock=fBlockDataArray.size(); iResult=0; } else { HLTError("Task %s (%p): subscription to task %s (%p) failed with error %d", GetName(), this, pSrcTask->GetName(), pSrcTask, iResult); iResult=-EFAULT; } } else { HLTFatal("fatal internal error in ROOT list handling"); iResult=-EFAULT; } lnk=lnk->Next(); } // process the event int iNofTrial=0; // repeat processing if component returns -ENOSPC AliHLTUInt32_t iLastOutputDataSize=0; if (iResult>=0) { do { long unsigned int iOutputDataSize=0; AliHLTConfiguration* pConf=GetConf(); // check if there was a buffer size specified, query output size // estimator from component otherwize if (pConf && pConf->GetOutputBufferSize()>=0) { iOutputDataSize=pConf->GetOutputBufferSize(); } else { long unsigned int iConstBase=0; double fInputMultiplier=0; if (pComponent->GetComponentType()!=AliHLTComponent::kSink) { pComponent->GetOutputDataSize(iConstBase, fInputMultiplier); // add a small margin to the buffer to allow optional component // statistics iConstBase+=100; #if defined(__DEBUG) || defined(HLT_COMPONENT_STATISTICS) for (AliHLTComponentBlockDataList::iterator element=fBlockDataArray.begin(); element!=fBlockDataArray.end(); element++) { if (element->fDataType==kAliHLTDataTypeComponentStatistics) { iConstBase+=element->fSize; } } #endif } if (fInputMultiplier<0) { HLTWarning("ignoring negative input multiplier"); fInputMultiplier=0; } iOutputDataSize=(long unsigned int)(fInputMultiplier*iInputDataVolume) + iConstBase; //HLTDebug("task %s: reqired output size %d", GetName(), iOutputDataSize); } if (fpDataBuffer->GetMaxBufferSize() < iOutputDataSize) { //If the estimated buffer size exceeds the maximum buffer size of AliHLTRawBuffer, decrease the buffer size. //The estimation is often quite high, and GetMaxBufferSize should usually return a size that is sufficient. HLTImportant("Reducing estimated output buffer size of %lu to maximum output buffer size (%lu)\n", iOutputDataSize, fpDataBuffer->GetMaxBufferSize()); iOutputDataSize = fpDataBuffer->GetMaxBufferSize(); } if (iNofTrial>0) { // dont process again if the buffer size is the same if (iLastOutputDataSize>=iOutputDataSize) break; HLTImportant("processing event %d again with buffer size %d", eventNo, iOutputDataSize); } AliHLTUInt8_t* pTgtBuffer=NULL; if (iOutputDataSize>0) pTgtBuffer=fpDataBuffer->GetTargetBuffer(iOutputDataSize); //HLTDebug("provided raw buffer %p", pTgtBuffer); AliHLTComponentEventData evtData; AliHLTComponent::FillEventData(evtData); if (eventNo>=0) evtData.fEventID=(AliHLTEventID_t)eventNo; if (timestamp < kMaxUInt) evtData.fEventCreation_s=timestamp; else evtData.fEventCreation_s=static_cast<AliHLTUInt32_t>(time(NULL)); AliHLTComponentTriggerData trigData; AliHLTEventTriggerData evtTrigData; trigData.fStructSize=sizeof(trigData); trigData.fDataSize=sizeof(AliHLTEventTriggerData); memset(&evtTrigData, 0, trigData.fDataSize); // Setup the CDH in the trigger data, based on the event type, CTP trigger // mask and participating detectors. evtTrigData.fCommonHeaderWordCnt=gkAliHLTCommonHeaderCount; AliHLTUInt8_t l1msg = 0x0; switch (eventType) { case gkAliEventTypeData: l1msg = 0x00; break; case gkAliEventTypeDataReplay: l1msg = 0x00; break; case gkAliEventTypeStartOfRun: l1msg = (0xE << 2) | 0x01; break; case gkAliEventTypeEndOfRun: l1msg = (0xF << 2) | 0x01; break; case gkAliEventTypeCalibration: l1msg = (0x1 << 6) | 0x01; break; case gkAliEventTypeSoftware: l1msg = 0x01; break; } evtTrigData.fCommonHeader[1] = (AliHLTUInt32_t(l1msg) << 14) | (0x03000000); //We have to set a CDH version, use 3 because we support 100 trigger classes below (0x03000000) evtTrigData.fCommonHeader[3] = ((l1msg & 0x1) == 0x1) ? (participatingDetectors & 0xFFFFFF) : 0x0; evtTrigData.fCommonHeader[5] = (trgMask & AliHLTTriggerMask_t(0xffffffff)).to_ulong(); evtTrigData.fCommonHeader[6] = ((trgMask>>32) & AliHLTTriggerMask_t(0x3ffff)).to_ulong(); evtTrigData.fCommonHeader[7] = ((trgMask>>50) & AliHLTTriggerMask_t(0xffffffff)).to_ulong(); evtTrigData.fCommonHeader[8] = ((trgMask>>72) & AliHLTTriggerMask_t(0x3ffff)).to_ulong(); trigData.fData=&evtTrigData; iLastOutputDataSize=iOutputDataSize; AliHLTUInt32_t size=iOutputDataSize; AliHLTUInt32_t outputBlockCnt=0; AliHLTComponentBlockData* outputBlocks=NULL; AliHLTComponentEventDoneData* edd=NULL; if (pTgtBuffer!=NULL || iOutputDataSize==0) { // add event type data block // the block is removed immediately after processing from the list AliHLTComponentBlockData eventTypeBlock; AliHLTComponent::FillBlockData(eventTypeBlock); // Note: no payload! eventTypeBlock.fDataType=kAliHLTDataTypeEvent; eventTypeBlock.fSpecification=eventType; fBlockDataArray.push_back(eventTypeBlock); if (CheckFilter(kHLTLogDebug)) Print("proc"); AliHLTUInt32_t iblock=0; // check input and output buffers for consistency // to be enabled after fixing bug with DataBuffer and forwarded SOR/EOR //for (iblock=0; iblock<fBlockDataArray.size(); iblock++) { // if ((AliHLTUInt8_t*)fBlockDataArray[iblock].fPtr >= pTgtBuffer+size) continue; // if (pTgtBuffer >= (AliHLTUInt8_t*)fBlockDataArray[iblock].fPtr+fBlockDataArray[iblock].fSize) continue; // HLTFatal("input and output buffer overlap for block descriptor %d (ptr %p size %d): output buffer %p %d", // iblock, fBlockDataArray[iblock].fPtr, fBlockDataArray[iblock].fSize, // pTgtBuffer, size); //} // process evtData.fBlockCnt=fBlockDataArray.size(); iResult=pComponent->ProcessEvent(evtData, &fBlockDataArray[0], trigData, pTgtBuffer, size, outputBlockCnt, outputBlocks, edd); HLTDebug("component %s ProcessEvent finnished (%d): size=%d blocks=%d", pComponent->GetComponentID(), iResult, size, outputBlockCnt); // EventDoneData is for the moment ignored in AliHLTSystem if (edd) { HLTDebug("got EventDoneData size %d", edd->fDataSize); delete [] reinterpret_cast<char*>(edd); edd=NULL; } // remove event data block fBlockDataArray.pop_back(); // check for forwarded blocks. // loop over all output blocks and check // 1. for duplicate blocks (pointing to same location in output buffer // or to the same buffer) // 2. for blocks forwarded from the input. if (iResult>=0 && outputBlocks) { if (fListTargets.First()!=NULL) { AliHLTComponentBlockDataList segments; for (AliHLTUInt32_t oblock=0; oblock<outputBlockCnt; oblock++) { // consistency check for data reference if (outputBlocks[oblock].fPtr!=NULL && outputBlocks[oblock].fPtr!=pTgtBuffer && outputBlocks[oblock].fOffset!=0) { HLTWarning("output block %s 0x%08x has inconsistent data reference ptr=%p offset=0x%08x: " "for new blocks use offset only, forwarded blocks have fPtr set only", AliHLTComponent::DataType2Text(outputBlocks[oblock].fDataType).c_str(), outputBlocks[oblock].fSpecification, outputBlocks[oblock].fPtr, outputBlocks[oblock].fOffset); } // check for duplicates in the output // this check applies for forwarded data blocks where // the ptr is not inside the target buffer AliHLTUInt32_t checkblock=0; for (; checkblock<oblock; checkblock++) { if (outputBlocks[oblock].fPtr!=NULL && outputBlocks[oblock].fPtr!=pTgtBuffer && outputBlocks[checkblock].fPtr==outputBlocks[oblock].fPtr) { if (outputBlocks[checkblock].fSize!=outputBlocks[oblock].fSize || outputBlocks[checkblock].fDataType!=outputBlocks[oblock].fDataType) { HLTWarning("output blocks %d (%s 0x%08x) and %d (%s 0x%08x) have identical data references ptr=%p " "but differ in data type and/or size: %d vs. %d, ignoring block %d", oblock, AliHLTComponent::DataType2Text(outputBlocks[oblock].fDataType).c_str(), outputBlocks[oblock].fSpecification, checkblock, AliHLTComponent::DataType2Text(outputBlocks[checkblock].fDataType).c_str(), outputBlocks[checkblock].fSpecification, outputBlocks[oblock].fPtr, outputBlocks[oblock].fSize, outputBlocks[checkblock].fSize, checkblock); } // ignore from the second copy break; } } if (checkblock<oblock) continue; // search for the forwarded data blocks // new data blocks are announced to the data buffer, forwarded data blocks // to the publisher task. The publisher task of a forwarded data block is // removed from the list in order to keep the buffer open. It will be releases // when the subscribing task releases it iblock=0; for (; iblock<fBlockDataArray.size(); iblock++) { if (outputBlocks[oblock].fDataType==kAliHLTDataTypeEvent) { // the event type data block is an artificial data block // ignore if it was forwarded break; } if (fBlockDataArray[iblock].fPtr==outputBlocks[oblock].fPtr) { assert(subscribedTaskList[iblock]!=NULL); if (subscribedTaskList[iblock]==NULL) { ALIHLTERRORGUARD(1, "missing parent task for forwarded data block %s 0x%08x, original data block %s 0x%08x, subsequent errors are suppressed", AliHLTComponent::DataType2Text(outputBlocks[oblock].fDataType).c_str(), outputBlocks[oblock].fSpecification, AliHLTComponent::DataType2Text(outputBlocks[iblock].fDataType).c_str(), outputBlocks[iblock].fSpecification); continue; } HLTDebug("forward segment %d (source task %s %p) to data buffer %p", iblock, pSrcTask->GetName(), pSrcTask, fpDataBuffer); fpDataBuffer->Forward(subscribedTaskList[iblock], &fBlockDataArray[iblock]); subscribedTaskList[iblock]=NULL; // not to be released in the loop further down break; } } if (iblock==fBlockDataArray.size()) segments.push_back(outputBlocks[oblock]); } if (pTgtBuffer && segments.size()>0) { iResult=fpDataBuffer->SetSegments(pTgtBuffer, &segments[0], segments.size()); } } else { // no forwarding, actually we dont even need to keep the data, this is a // dead end (fListTargets empty) //iResult=fpDataBuffer->SetSegments(pTgtBuffer, outputBlocks, outputBlockCnt); } delete [] outputBlocks; outputBlocks=NULL; outputBlockCnt=0; } else { fpDataBuffer->Reset(); } if (fListTargets.First()!=NULL) { if (iSOR>=0 && subscribedTaskList[iSOR]!=NULL) { HLTDebug("forward SOR event segment %d (source task %s %p) to data buffer %p", iSOR, pSrcTask->GetName(), pSrcTask, fpDataBuffer); fpDataBuffer->Forward(subscribedTaskList[iSOR], &fBlockDataArray[iSOR]); subscribedTaskList[iSOR]=NULL; // not to be released in the loop further down } if (iEOR>=0 && subscribedTaskList[iEOR]!=NULL) { HLTDebug("forward EOR event (%s) segment %d (source task %s %p) to data buffer %p", AliHLTComponent::DataType2Text(fBlockDataArray[iEOR].fDataType).c_str(), iEOR, pSrcTask->GetName(), pSrcTask, fpDataBuffer); fpDataBuffer->Forward(subscribedTaskList[iEOR], &fBlockDataArray[iEOR]); subscribedTaskList[iEOR]=NULL; // not to be released in the loop further down } if (iECS>=0 && subscribedTaskList[iECS]!=NULL) { HLTDebug("forward ECS event (%s) segment %d (source task %s %p) to data buffer %p", AliHLTComponent::DataType2Text(fBlockDataArray[iECS].fDataType).c_str(), iECS, pSrcTask->GetName(), pSrcTask, fpDataBuffer); fpDataBuffer->Forward(subscribedTaskList[iECS], &fBlockDataArray[iECS]); subscribedTaskList[iECS]=NULL; // not to be released in the loop further down } } } else { HLTFatal("no target buffer available"); iResult=-EFAULT; } } while (iResult==-ENOSPC && iNofTrial++<1); } if (CheckFilter(kHLTLogDebug)) Print("proc"); // now release all buffers which we have subscribed to iSourceDataBlock=0; AliHLTTaskPList::iterator element; while ((element=subscribedTaskList.begin())!=subscribedTaskList.end()) { pSrcTask=*element; if (pSrcTask) { int iTempRes=0; if ((iTempRes=pSrcTask->Release(&fBlockDataArray[iSourceDataBlock], this))>=0) { HLTDebug("successfully released segment of task %s (%p)", pSrcTask->GetName(), pSrcTask); } else { HLTError("realease of task %s (%p) failed with error %d", pSrcTask->GetName(), pSrcTask, iTempRes); } } subscribedTaskList.erase(element); iSourceDataBlock++; } if (subscribedTaskList.size()>0) { HLTError("could not release all data buffers"); } fBlockDataArray.clear(); } else { HLTError("internal failure (not initialized component %p, data buffer %p)", fpComponent, fpDataBuffer); iResult=-EFAULT; } return iResult; } int AliHLTTask::SubscribeSourcesAndSkip() { // function carries out the proper cleanup of the source components // by subscribing and releasing int iResult=0; AliHLTTask* pSrcTask=NULL; AliHLTTaskPList subscribedTaskList; // cleanup the data buffer if (fpDataBuffer) fpDataBuffer->Reset(); // subscribe to all source tasks fBlockDataArray.clear(); for (TObjLink* lnk=fListDependencies.FirstLink(); lnk!=NULL; lnk=lnk->Next()) { if (!lnk->GetObject()) continue; pSrcTask=dynamic_cast<AliHLTTask*>(lnk->GetObject()); if (!pSrcTask) continue; unsigned iPosition=fBlockDataArray.size(); if ((iResult=pSrcTask->Subscribe(this, fBlockDataArray))>0) { for (unsigned i=iPosition; i<fBlockDataArray.size(); i++) { subscribedTaskList.push_back(pSrcTask); } HLTDebug("subscribed to %d blocks of task %s (%p)", iResult, pSrcTask->GetName(), pSrcTask, iResult); } else if (iResult<0) { HLTError("failed to subscribe to task %s (%p) with error %d", pSrcTask->GetName(), pSrcTask, iResult); } } unsigned iSourceDataBlock=0; AliHLTTaskPList::iterator element; while ((element=subscribedTaskList.begin())!=subscribedTaskList.end()) { assert(iSourceDataBlock<fBlockDataArray.size()); pSrcTask=*element; if (pSrcTask && iSourceDataBlock<fBlockDataArray.size()) { if ((iResult=pSrcTask->Release(&fBlockDataArray[iSourceDataBlock], this))>=0) { HLTDebug("successfully released segment of task %s (%p)", pSrcTask->GetName(), pSrcTask); } else if (iSourceDataBlock>=fBlockDataArray.size()) { HLTError("mismatch between list of subscribed tasks and block list in task %s (%p), can not release task %s (%p)", GetName(), this, pSrcTask->GetName(), pSrcTask); } else { HLTError("realease of task %s (%p) failed with error %d", pSrcTask->GetName(), pSrcTask, iResult); } } subscribedTaskList.erase(element); iSourceDataBlock++; } if (iSourceDataBlock<fBlockDataArray.size()) { HLTWarning("not all subscriptions released for task %s (%p)", GetName(), this); } return 0; } int AliHLTTask::GetNofMatchingDataBlocks(const AliHLTTask* pConsumerTask) const { // see header file for function documentation int iResult=0; if (pConsumerTask) { if (fpDataBuffer) { iResult=fpDataBuffer->FindMatchingDataBlocks(pConsumerTask->GetComponent(), NULL); } else { HLTFatal("internal data buffer missing"); iResult=-EFAULT; } } else { iResult=-EINVAL; } return iResult; } int AliHLTTask::GetNofMatchingDataTypes(const AliHLTTask* pConsumerTask) const { // see header file for function documentation int iResult=0; if (pConsumerTask) { AliHLTComponent* pComponent=GetComponent(); if (!pComponent) { // init ? HLTError("component not initialized"); iResult=-EFAULT; } if (pComponent) { iResult=pComponent->FindMatchingDataTypes(pConsumerTask->GetComponent(), NULL); } else { HLTFatal("task initialization failed"); iResult=-EFAULT; } } else { iResult=-EINVAL; } return iResult; } int AliHLTTask::Subscribe(const AliHLTTask* pConsumerTask, AliHLTComponentBlockDataList& blockDescList) { // see header file for function documentation int iResult=0; if (pConsumerTask) { if (fpDataBuffer) { iResult=fpDataBuffer->Subscribe(pConsumerTask->GetComponent(), blockDescList); } else { HLTFatal("internal data buffer missing"); iResult=-EFAULT; } } else { iResult=-EINVAL; } return iResult; } int AliHLTTask::Release(AliHLTComponentBlockData* pBlockDesc, const AliHLTTask* pConsumerTask) { // see header file for function documentation int iResult=0; if (pConsumerTask && pBlockDesc) { if (fpDataBuffer) { iResult=fpDataBuffer->Release(pBlockDesc, pConsumerTask->GetComponent(), this); } else { HLTFatal("internal data buffer missing"); iResult=-EFAULT; } } else { iResult=-EINVAL; } return iResult; } void AliHLTTask::PrintStatus() { // see header file for function documentation HLTLogKeyword("task properties"); AliHLTComponent* pComponent=GetComponent(); if (pComponent) { HLTMessage(" component: %s (%p)", pComponent->GetComponentID(), pComponent); } else { HLTMessage(" no component set!"); } if (fpConfiguration) { AliHLTConfiguration* pSrc=fpConfiguration->GetFirstSource(); while (pSrc) { const char* pQualifier="unresolved"; if (FindDependency(pSrc->GetName())) pQualifier="resolved"; HLTMessage(" source: %s (%s)", pSrc->GetName(), pQualifier); pSrc=fpConfiguration->GetNextSource(); } TObjLink* lnk = fListTargets.FirstLink(); while (lnk) { TObject *obj = lnk->GetObject(); HLTMessage(" target: %s", obj->GetName()); lnk = lnk->Next(); } } else { HLTMessage(" task not initialized"); } } void AliHLTTask::Print(const char* options) const { // Overloaded from TObject if (strcmp(options, "proc")==0) { // print processing info HLTMessage("**********************************************"); HLTMessage("******* AliHLTTask Processing info ***********"); HLTMessage(" component: %p %s", fpComponent, (fpComponent?fpComponent->GetComponentID():"")); HLTMessage(" data buffer: %p", fpDataBuffer); if (fpDataBuffer) fpDataBuffer->Print(""); HLTMessage(" input block descriptors: %d", fBlockDataArray.size()); for (unsigned i=0; i<fBlockDataArray.size(); i++) { HLTMessage(" %d: %s 0x%08x %p %d", i, AliHLTComponent::DataType2Text(fBlockDataArray[i].fDataType).c_str(), fBlockDataArray[i].fSpecification, fBlockDataArray[i].fPtr, fBlockDataArray[i].fSize ); } HLTMessage("**** end of AliHLTTask Processing info *******"); HLTMessage("**********************************************"); return; } cout << "AliHLTTask " << GetName() << " " << this << " component " << fpComponent << " " << (fpComponent?fpComponent->GetComponentID():"") << endl; } int AliHLTTask::CustomInit(AliHLTComponentHandler* /*pCH*/) { // default implementation nothing to do return 0; } int AliHLTTask::CustomCleanup() { // default implementation nothing to do return 0; } int AliHLTTask::LoggingVarargs(AliHLTComponentLogSeverity severity, const char* originClass, const char* originFunc, const char* file, int line, ... ) const { // see header file for function documentation int iResult=0; va_list args; va_start(args, line); AliHLTLogging::SetLogString(this, " (%p)", "%s_pfmt_: ", GetName()); iResult=SendMessage(severity, originClass, originFunc, file, line, AliHLTLogging::BuildLogString(NULL, args, true /*append*/)); va_end(args); return iResult; }
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // AliHMPIDRecon // // // // HMPID class to perfom pattern recognition based on Hough transfrom // // for single chamber // ////////////////////////////////////////////////////////////////////////// #include "AliHMPIDRecon.h" //class header #include "AliHMPIDParam.h" //CkovAngle() #include "AliHMPIDCluster.h" //CkovAngle() #include <TRotation.h> //TracePhot() #include <TH1D.h> //HoughResponse() #include <TClonesArray.h> //CkovAngle() #include <AliESDtrack.h> //CkovAngle() const Double_t AliHMPIDRecon::fgkRadThick=1.5; const Double_t AliHMPIDRecon::fgkWinThick=0.5; const Double_t AliHMPIDRecon::fgkGapThick=8.0; const Double_t AliHMPIDRecon::fgkWinIdx =1.5787; const Double_t AliHMPIDRecon::fgkGapIdx =1.0005; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AliHMPIDRecon::AliHMPIDRecon():TTask("RichRec","RichPat"), fRadNmean(1.292), fPhotCnt(-1), fCkovSigma2(0), fIsWEIGHT(kFALSE), fDTheta(0.001), fWindowWidth(0.045), fTrkDir(TVector3(0,0,1)),fTrkPos(TVector2(30,40)) { // main ctor for (Int_t i=0; i<3000; i++) { fPhotFlag[i] = 0; fPhotCkov[i] = -1; fPhotPhi [i] = -1; fPhotWei [i] = 0; } } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void AliHMPIDRecon::CkovAngle(AliESDtrack *pTrk,TClonesArray *pCluLst,Double_t nmean) { // Pattern recognition method based on Hough transform // Arguments: pTrk - track for which Ckov angle is to be found // pCluLst - list of clusters for this chamber // Returns: - track ckov angle, [rad], AliHMPIDParam *pParam=AliHMPIDParam::Instance(); if(pCluLst->GetEntries()>pParam->MultCut()) fIsWEIGHT = kTRUE; // offset to take into account bkg in reconstruction else fIsWEIGHT = kFALSE; Float_t xRa,yRa,th,ph; pTrk->GetHMPIDtrk(xRa,yRa,th,ph); //initialize this track: th and ph angles at middle of RAD th=TMath::Pi()- th; // right XYZ local orientation SetTrack(xRa,yRa,th,ph); fRadNmean=nmean; Float_t dMin=999,mipX=-1,mipY=-1;Int_t chId=-1,mipId=-1,mipQ=-1; fPhotCnt=0; for (Int_t iClu=0; iClu<pCluLst->GetEntriesFast();iClu++){//clusters loop AliHMPIDCluster *pClu=(AliHMPIDCluster*)pCluLst->UncheckedAt(iClu); //get pointer to current cluster chId=pClu->Ch(); if(pClu->Q()>pParam->QCut()){ //charge compartible with MIP clusters Float_t dX=fPc.X()-pClu->X(),dY=fPc.Y()-pClu->Y(),d =TMath::Sqrt(dX*dX+dY*dY); //distance between current cluster and intersection point if( d < dMin) {mipId=iClu; dMin=d;mipX=pClu->X();mipY=pClu->Y();mipQ=(Int_t)pClu->Q();} //current cluster is closer, overwrite data for min cluster }else{ //charge compatible with photon cluster Double_t thetaCer,phiCer; if(FindPhotCkov(pClu->X(),pClu->Y(),thetaCer,phiCer)){ //find ckov angle for this photon candidate fPhotCkov[fPhotCnt]=thetaCer; //actual theta Cerenkov (in TRS) fPhotPhi [fPhotCnt]=phiCer; //actual phi Cerenkov (in TRS): -pi to come back to "unusual" ref system (X,Y,-Z) fPhotCnt++; //increment counter of photon candidates } } }//clusters loop Int_t iNacc=FlagPhot(HoughResponse()); //flag photons according to individual theta ckov with respect to most probable pTrk->SetHMPIDmip(mipX,mipY,mipQ,iNacc); //store mip info if(mipId==-1) {pTrk->SetHMPIDsignal(kMipQdcCut); return;} //no clusters with QDC more the threshold at all if(dMin>pParam->DistCut()) {pTrk->SetHMPIDsignal(kMipDistCut); return;} //closest cluster with enough charge is still too far from intersection pTrk->SetHMPIDcluIdx(chId,mipId); //set index of cluster if(iNacc<1) pTrk->SetHMPIDsignal(kNoPhotAccept); //no photon candidates is accepted else pTrk->SetHMPIDsignal(FindRingCkov(pCluLst->GetEntries())); //find best Theta ckov for ring i.e. track pTrk->SetHMPIDchi2(fCkovSigma2); //errors squared }//ThetaCerenkov() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Bool_t AliHMPIDRecon::FindPhotCkov(Double_t cluX,Double_t cluY,Double_t &thetaCer,Double_t &phiCer) { // Finds Cerenkov angle for this photon candidate // Arguments: cluX,cluY - position of cadidate's cluster // Returns: Cerenkov angle TVector3 dirCkov; Double_t zRad= 0.5*AliHMPIDRecon::fgkRadThick +AliHMPIDRecon::fgkWinThick +AliHMPIDRecon::fgkGapThick; //z position of middle of RAD TVector3 rad(fTrkPos.X(),fTrkPos.Y(),zRad); //impact point at middle of RAD TVector3 pc(cluX,cluY,0); //mip at PC: z=0 @ PC Double_t cluR = TMath::Sqrt((cluX-fTrkPos.X())*(cluX-fTrkPos.X())+ (cluY-fTrkPos.Y())*(cluY-fTrkPos.Y()));//ref. distance impact RAD-CLUSTER Double_t phi=(pc-rad).Phi(); //phi of photon Double_t ckov1=0; Double_t ckov2=TMath::Pi()-fTrkDir.Theta()+0.75; //start to find theta cerenkov in DRS const Double_t kTol=0.01; Int_t iIterCnt = 0; while(1){ if(iIterCnt>=50) return kFALSE; Double_t ckov=0.5*(ckov1+ckov2); dirCkov.SetMagThetaPhi(1,TMath::Pi()-ckov,phi); TVector2 posC=TraceForward(dirCkov); //trace photon with actual angles Double_t dist=cluR-(posC-fTrkPos).Mod(); //get distance between trial point and cluster position if(posC.X()==-999) dist = - 999; //total reflection problem iIterCnt++; //counter step if (dist> kTol) ckov1=ckov; //cluster @ larger ckov else if(dist<-kTol) ckov2=ckov; //cluster @ smaller ckov else{ //precision achived: ckov in DRS found dirCkov.SetMagThetaPhi(1,ckov,phi); // RecPhot(dirCkov,thetaCer,phiCer); //find ckov (in TRS:the effective Cherenkov angle!) thetaCer = TMath::Pi() - thetaCer; return kTRUE; } } }//FindPhotTheta() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TVector2 AliHMPIDRecon::TraceForward(TVector3 dirCkov)const { //Trace forward a photon from (x,y) up to PC // Arguments: dirCkov photon vector in LORS // Returns: pos of traced photon at PC TVector2 pos(-999,-999); Double_t thetaCer = TMath::Pi()-dirCkov.Theta(); if(thetaCer > TMath::ASin(1./fRadNmean)) return pos; //total refraction on WIN-GAP boundary Double_t zRad= 0.5*AliHMPIDRecon::fgkRadThick +AliHMPIDRecon::fgkWinThick +AliHMPIDRecon::fgkGapThick; //z position of middle of RAD TVector3 posCkov(fTrkPos.X(),fTrkPos.Y(),zRad); //RAD: photon position is track position @ middle of RAD Propagate(dirCkov,posCkov,fgkWinThick+fgkGapThick); //go to RAD-WIN boundary Refract (dirCkov, fRadNmean,fgkWinIdx ); //RAD-WIN refraction Propagate(dirCkov,posCkov, fgkGapThick); //go to WIN-GAP boundary Refract (dirCkov, fgkWinIdx,fgkGapIdx ); //WIN-GAP refraction Propagate(dirCkov,posCkov, 0); //go to PC pos.Set(posCkov.X(),posCkov.Y()); return pos; }//TraceForward() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void AliHMPIDRecon::RecPhot(TVector3 dirCkov,Double_t &thetaCer,Double_t &phiCer) { //Theta Cerenkov reconstruction // Arguments: (x,y) of initial point in LORS, dirCkov photon vector in LORS // Returns: thetaCer theta cerenkov reconstructed // TVector3 dirTrk; // dirTrk.SetMagThetaPhi(1,fTrkDir.Theta(),fTrkDir.Phi()); // Double_t thetaCer = TMath::ACos(dirCkov*dirTrk); TRotation mtheta; mtheta.RotateY(- fTrkDir.Theta()); TRotation mphi; mphi.RotateZ(- fTrkDir.Phi()); TRotation mrot=mtheta*mphi; TVector3 dirCkovTRS; dirCkovTRS=mrot*dirCkov; phiCer = dirCkovTRS.Phi(); //actual value of the phi of the photon thetaCer= dirCkovTRS.Theta(); //actual value of thetaCerenkov of the photon } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::FindRingArea(Double_t ckovAng)const { // Find area inside the cerenkov ring which lays inside PCs // Arguments: ckovAng - cerenkov angle // Returns: area of the ring in cm^2 for given theta ckov const Int_t kN=100; Double_t area=0; for(Int_t i=0;i<kN;i++){ TVector2 pos1=TracePhot(ckovAng,Double_t(TMath::TwoPi()*i /kN));//trace this photon TVector2 pos2=TracePhot(ckovAng,Double_t(TMath::TwoPi()*(i+1)/kN));//trace the next photon area+=(pos1-fTrkPos)*(pos2-fTrkPos); //add area of the triangle... } return area; }//FindRingArea() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::FindRingCkov(Int_t) { // Loops on all Ckov candidates and estimates the best Theta Ckov for a ring formed by those candidates. Also estimates an error for that Theat Ckov // collecting errors for all single Ckov candidates thetas. (Assuming they are independent) // Arguments: iNclus- total number of clusters in chamber for background estimation // Return: best estimation of track Theta ckov Double_t wei = 0.; Double_t weightThetaCerenkov = 0.; Double_t ckovMin=9999.,ckovMax=0.; Double_t sigma2 = 0; //to collect error squared for this ring for(Int_t i=0;i<fPhotCnt;i++){//candidates loop if(fPhotFlag[i] == 2){ if(fPhotCkov[i]<ckovMin) ckovMin=fPhotCkov[i]; //find max and min Theta ckov from all candidates within probable window if(fPhotCkov[i]>ckovMax) ckovMax=fPhotCkov[i]; weightThetaCerenkov += fPhotCkov[i]*fPhotWei[i]; wei += fPhotWei[i]; //collect weight as sum of all candidate weghts sigma2 += 1./Sigma2(fPhotCkov[i],fPhotPhi[i]); } }//candidates loop if(sigma2>0) fCkovSigma2=1./sigma2; else fCkovSigma2=1e10; if(wei != 0.) weightThetaCerenkov /= wei; else weightThetaCerenkov = 0.; return weightThetaCerenkov; }//FindCkovRing() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Int_t AliHMPIDRecon::FlagPhot(Double_t ckov) { // Flag photon candidates if their individual ckov angle is inside the window around ckov angle returned by HoughResponse() // Arguments: ckov- value of most probable ckov angle for track as returned by HoughResponse() // Returns: number of photon candidates happened to be inside the window // Photon Flag: Flag = 0 initial set; // Flag = 1 good candidate (charge compatible with photon); // Flag = 2 photon used for the ring; Int_t steps = (Int_t)((ckov )/ fDTheta); //how many times we need to have fDTheta to fill the distance between 0 and thetaCkovHough Double_t tmin = (Double_t)(steps - 1)*fDTheta; Double_t tmax = (Double_t)(steps)*fDTheta; Double_t tavg = 0.5*(tmin+tmax); tmin = tavg - 0.5*fWindowWidth; tmax = tavg + 0.5*fWindowWidth; Int_t iInsideCnt = 0; //count photons which Theta ckov inside the window for(Int_t i=0;i<fPhotCnt;i++){//photon candidates loop if(fPhotCkov[i] >= tmin && fPhotCkov[i] <= tmax) { fPhotFlag[i]=2; iInsideCnt++; } } return iInsideCnt; }//FlagPhot() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TVector2 AliHMPIDRecon::TracePhot(Double_t ckovThe,Double_t ckovPhi)const { // Trace a single Ckov photon from emission point somewhere in radiator up to photocathode taking into account ref indexes of materials it travereses // Arguments: ckovThe,ckovPhi- photon ckov angles in DRS, [rad] // Returns: distance between photon point on PC and track projection TRotation mtheta; mtheta.RotateY(fTrkDir.Theta()); TRotation mphi; mphi.RotateZ(fTrkDir.Phi()); TRotation mrot=mphi*mtheta; TVector3 dirCkov,dirCkovTors; ckovThe = TMath::Pi()-ckovThe; dirCkovTors.SetMagThetaPhi(1,ckovThe,ckovPhi); //initially photon is directed according to requested ckov angle dirCkov=mrot*dirCkovTors; //now we know photon direction in LORS return TraceForward(dirCkov); }//TracePhot() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void AliHMPIDRecon::Propagate(const TVector3 dir,TVector3 &pos,Double_t z)const { // Finds an intersection point between a line and XY plane shifted along Z. // Arguments: dir,pos - vector along the line and any point of the line // z - z coordinate of plain // Returns: none // On exit: pos is the position if this intesection if any static TVector3 nrm(0,0,1); TVector3 pnt(0,0,z); TVector3 diff=pnt-pos; Double_t sint=(nrm*diff)/(nrm*dir); pos+=sint*dir; }//Propagate() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void AliHMPIDRecon::Refract(TVector3 &dir,Double_t n1,Double_t n2)const { // Refract direction vector according to Snell law // Arguments: // n1 - ref idx of first substance // n2 - ref idx of second substance // Returns: none // On exit: dir is new direction Double_t sinref=(n1/n2)*TMath::Sin(TMath::Pi()-dir.Theta()); if(sinref>1.) dir.SetXYZ(-999,-999,-999); else dir.SetTheta(TMath::Pi()-TMath::ASin(sinref)); }//Refract() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::HoughResponse() { // // // Double_t kThetaMax=0.75; Int_t nChannels = (Int_t)(kThetaMax/fDTheta+0.5); TH1D *phots = new TH1D("Rphot" ,"phots" ,nChannels,0,kThetaMax); TH1D *photsw = new TH1D("RphotWeighted" ,"photsw" ,nChannels,0,kThetaMax); TH1D *resultw = new TH1D("resultw","resultw" ,nChannels,0,kThetaMax); Int_t nBin = (Int_t)(kThetaMax/fDTheta); Int_t nCorrBand = (Int_t)(fWindowWidth/(2*fDTheta)); for (Int_t i=0; i< fPhotCnt; i++){//photon cadidates loop Double_t angle = fPhotCkov[i]; if(angle<0||angle>kThetaMax) continue; phots->Fill(angle); Int_t bin = (Int_t)(0.5+angle/(fDTheta)); Double_t weight=1.; if(fIsWEIGHT){ Double_t lowerlimit = ((Double_t)bin)*fDTheta - 0.5*fDTheta; Double_t upperlimit = ((Double_t)bin)*fDTheta + 0.5*fDTheta; Double_t diffArea = FindRingArea(upperlimit)-FindRingArea(lowerlimit); if(diffArea>0) weight = 1./diffArea; } photsw->Fill(angle,weight); fPhotWei[i]=weight; }//photon candidates loop for (Int_t i=1; i<=nBin;i++){ Int_t bin1= i-nCorrBand; Int_t bin2= i+nCorrBand; if(bin1<1) bin1=1; if(bin2>nBin)bin2=nBin; Double_t sumPhots=phots->Integral(bin1,bin2); if(sumPhots<3) continue; // if less then 3 photons don't trust to this ring Double_t sumPhotsw=photsw->Integral(bin1,bin2); resultw->Fill((Double_t)((i+0.5)*fDTheta),sumPhotsw); } // evaluate the "BEST" theta ckov as the maximum value of histogramm Double_t *pVec = resultw->GetArray(); Int_t locMax = TMath::LocMax(nBin,pVec); phots->Delete();photsw->Delete();resultw->Delete(); // Reset and delete objects return (Double_t)(locMax*fDTheta+0.5*fDTheta); //final most probable track theta ckov }//HoughResponse() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::Sigma2(Double_t ckovTh, Double_t ckovPh)const { // Analithical calculation of total error (as a sum of localization, geometrical and chromatic errors) on Cerenkov angle for a given Cerenkov photon // created by a given MIP. Fromulae according to CERN-EP-2000-058 // Arguments: Cerenkov and azimuthal angles for Cerenkov photon, [radians] // dip and azimuthal angles for MIP taken at the entrance to radiator, [radians] // MIP beta // Returns: absolute error on Cerenkov angle, [radians] TVector3 v(-999,-999,-999); Double_t trkBeta = 1./(TMath::Cos(ckovTh)*fRadNmean); v.SetX(SigLoc (ckovTh,ckovPh,trkBeta)); v.SetY(SigGeom(ckovTh,ckovPh,trkBeta)); v.SetZ(SigCrom(ckovTh,ckovPh,trkBeta)); return v.Mag2(); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::SigLoc(Double_t thetaC, Double_t phiC,Double_t betaM)const { // Analithical calculation of localization error (due to finite segmentation of PC) on Cerenkov angle for a given Cerenkov photon // created by a given MIP. Fromulae according to CERN-EP-2000-058 // Arguments: Cerenkov and azimuthal angles for Cerenkov photon, [radians] // dip and azimuthal angles for MIP taken at the entrance to radiator, [radians] // MIP beta // Returns: absolute error on Cerenkov angle, [radians] Double_t phiDelta = phiC - fTrkDir.Phi(); Double_t alpha =TMath::Cos(fTrkDir.Theta())-TMath::Tan(thetaC)*TMath::Cos(phiDelta)*TMath::Sin(fTrkDir.Theta()); Double_t k = 1.-fRadNmean*fRadNmean+alpha*alpha/(betaM*betaM); if (k<0) return 1e10; Double_t mu =TMath::Sin(fTrkDir.Theta())*TMath::Sin(fTrkDir.Phi())+TMath::Tan(thetaC)*(TMath::Cos(fTrkDir.Theta())*TMath::Cos(phiDelta)*TMath::Sin(fTrkDir.Phi())+TMath::Sin(phiDelta)*TMath::Cos(fTrkDir.Phi())); Double_t e =TMath::Sin(fTrkDir.Theta())*TMath::Cos(fTrkDir.Phi())+TMath::Tan(thetaC)*(TMath::Cos(fTrkDir.Theta())*TMath::Cos(phiDelta)*TMath::Cos(fTrkDir.Phi())-TMath::Sin(phiDelta)*TMath::Sin(fTrkDir.Phi())); Double_t kk = betaM*TMath::Sqrt(k)/(8*alpha); Double_t dtdxc = kk*(k*(TMath::Cos(phiDelta)*TMath::Cos(fTrkDir.Phi())-TMath::Cos(fTrkDir.Theta())*TMath::Sin(phiDelta)*TMath::Sin(fTrkDir.Phi()))-(alpha*mu/(betaM*betaM))*TMath::Sin(fTrkDir.Theta())*TMath::Sin(phiDelta)); Double_t dtdyc = kk*(k*(TMath::Cos(phiDelta)*TMath::Sin(fTrkDir.Phi())+TMath::Cos(fTrkDir.Theta())*TMath::Sin(phiDelta)*TMath::Cos(fTrkDir.Phi()))+(alpha* e/(betaM*betaM))*TMath::Sin(fTrkDir.Theta())*TMath::Sin(phiDelta)); return TMath::Sqrt(0.2*0.2*dtdxc*dtdxc + 0.25*0.25*dtdyc*dtdyc); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::SigCrom(Double_t thetaC, Double_t phiC,Double_t betaM)const { // Analithical calculation of chromatic error (due to lack of knowledge of Cerenkov photon energy) on Cerenkov angle for a given Cerenkov photon // created by a given MIP. Fromulae according to CERN-EP-2000-058 // Arguments: Cerenkov and azimuthal angles for Cerenkov photon, [radians] // dip and azimuthal angles for MIP taken at the entrance to radiator, [radians] // MIP beta // Returns: absolute error on Cerenkov angle, [radians] Double_t phiDelta = phiC - fTrkDir.Phi(); Double_t alpha =TMath::Cos(fTrkDir.Theta())-TMath::Tan(thetaC)*TMath::Cos(phiDelta)*TMath::Sin(fTrkDir.Theta()); Double_t dtdn = TMath::Cos(fTrkDir.Theta())*fRadNmean*betaM*betaM/(alpha*TMath::Tan(thetaC)); Double_t f = 0.00928*(7.75-5.635)/TMath::Sqrt(12.); return f*dtdn; }//SigCrom() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::SigGeom(Double_t thetaC, Double_t phiC,Double_t betaM)const { // Analithical calculation of geometric error (due to lack of knowledge of creation point in radiator) on Cerenkov angle for a given Cerenkov photon // created by a given MIP. Formulae according to CERN-EP-2000-058 // Arguments: Cerenkov and azimuthal angles for Cerenkov photon, [radians] // dip and azimuthal angles for MIP taken at the entrance to radiator, [radians] // MIP beta // Returns: absolute error on Cerenkov angle, [radians] Double_t phiDelta = phiC - fTrkDir.Phi(); Double_t alpha =TMath::Cos(fTrkDir.Theta())-TMath::Tan(thetaC)*TMath::Cos(phiDelta)*TMath::Sin(fTrkDir.Theta()); Double_t k = 1.-fRadNmean*fRadNmean+alpha*alpha/(betaM*betaM); if (k<0) return 1e10; Double_t eTr = 0.5*1.5*betaM*TMath::Sqrt(k)/(8*alpha); Double_t lambda = 1.-TMath::Sin(fTrkDir.Theta())*TMath::Sin(fTrkDir.Theta())*TMath::Sin(phiC)*TMath::Sin(phiC); Double_t c = 1./(1.+ eTr*k/(alpha*alpha*TMath::Cos(thetaC)*TMath::Cos(thetaC))); Double_t i = betaM*TMath::Tan(thetaC)*lambda*TMath::Power(k,1.5); Double_t ii = 1.+eTr*betaM*i; Double_t err = c * (i/(alpha*alpha*8) + ii*(1.-lambda) / ( alpha*alpha*8*betaM*(1.+eTr)) ); Double_t trErr = 1.5/(TMath::Sqrt(12.)*TMath::Cos(fTrkDir.Theta())); return trErr*err; }//SigGeom() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Right LRS for photon cerenkov angle reconstruction /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // AliHMPIDRecon // // // // HMPID class to perfom pattern recognition based on Hough transfrom // // for single chamber // ////////////////////////////////////////////////////////////////////////// #include "AliHMPIDRecon.h" //class header #include "AliHMPIDParam.h" //CkovAngle() #include "AliHMPIDCluster.h" //CkovAngle() #include <TRotation.h> //TracePhot() #include <TH1D.h> //HoughResponse() #include <TClonesArray.h> //CkovAngle() #include <AliESDtrack.h> //CkovAngle() const Double_t AliHMPIDRecon::fgkRadThick=1.5; const Double_t AliHMPIDRecon::fgkWinThick=0.5; const Double_t AliHMPIDRecon::fgkGapThick=8.0; const Double_t AliHMPIDRecon::fgkWinIdx =1.5787; const Double_t AliHMPIDRecon::fgkGapIdx =1.0005; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AliHMPIDRecon::AliHMPIDRecon():TTask("RichRec","RichPat"), fRadNmean(1.292), fPhotCnt(-1), fCkovSigma2(0), fIsWEIGHT(kFALSE), fDTheta(0.001), fWindowWidth(0.045), fTrkDir(TVector3(0,0,1)),fTrkPos(TVector2(30,40)) { // main ctor for (Int_t i=0; i<3000; i++) { fPhotFlag[i] = 0; fPhotCkov[i] = -1; fPhotPhi [i] = -1; fPhotWei [i] = 0; } } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void AliHMPIDRecon::CkovAngle(AliESDtrack *pTrk,TClonesArray *pCluLst,Double_t nmean) { // Pattern recognition method based on Hough transform // Arguments: pTrk - track for which Ckov angle is to be found // pCluLst - list of clusters for this chamber // Returns: - track ckov angle, [rad], AliHMPIDParam *pParam=AliHMPIDParam::Instance(); if(pCluLst->GetEntries()>pParam->MultCut()) fIsWEIGHT = kTRUE; // offset to take into account bkg in reconstruction else fIsWEIGHT = kFALSE; Float_t xRa,yRa,th,ph; pTrk->GetHMPIDtrk(xRa,yRa,th,ph); //initialize this track: th and ph angles at middle of RAD // ph-=TMath::Pi(); // right XYZ local orientation SetTrack(xRa,yRa,th,ph); fRadNmean=nmean; Float_t dMin=999,mipX=-1,mipY=-1;Int_t chId=-1,mipId=-1,mipQ=-1; fPhotCnt=0; for (Int_t iClu=0; iClu<pCluLst->GetEntriesFast();iClu++){//clusters loop AliHMPIDCluster *pClu=(AliHMPIDCluster*)pCluLst->UncheckedAt(iClu); //get pointer to current cluster chId=pClu->Ch(); if(pClu->Q()>pParam->QCut()){ //charge compartible with MIP clusters Float_t dX=fPc.X()-pClu->X(),dY=fPc.Y()-pClu->Y(),d =TMath::Sqrt(dX*dX+dY*dY); //distance between current cluster and intersection point if( d < dMin) {mipId=iClu; dMin=d;mipX=pClu->X();mipY=pClu->Y();mipQ=(Int_t)pClu->Q();} //current cluster is closer, overwrite data for min cluster }else{ //charge compatible with photon cluster Double_t thetaCer,phiCer; if(FindPhotCkov(pClu->X(),pClu->Y(),thetaCer,phiCer)){ //find ckov angle for this photon candidate fPhotCkov[fPhotCnt]=thetaCer; //actual theta Cerenkov (in TRS) fPhotPhi [fPhotCnt]=phiCer; //actual phi Cerenkov (in TRS): -pi to come back to "unusual" ref system (X,Y,-Z) fPhotCnt++; //increment counter of photon candidates } } }//clusters loop Int_t iNacc=FlagPhot(HoughResponse()); //flag photons according to individual theta ckov with respect to most probable pTrk->SetHMPIDmip(mipX,mipY,mipQ,iNacc); //store mip info if(mipId==-1) {pTrk->SetHMPIDsignal(kMipQdcCut); return;} //no clusters with QDC more the threshold at all if(dMin>pParam->DistCut()) {pTrk->SetHMPIDsignal(kMipDistCut); return;} //closest cluster with enough charge is still too far from intersection pTrk->SetHMPIDcluIdx(chId,mipId); //set index of cluster if(iNacc<1) pTrk->SetHMPIDsignal(kNoPhotAccept); //no photon candidates is accepted else pTrk->SetHMPIDsignal(FindRingCkov(pCluLst->GetEntries())); //find best Theta ckov for ring i.e. track pTrk->SetHMPIDchi2(fCkovSigma2); //errors squared }//ThetaCerenkov() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Bool_t AliHMPIDRecon::FindPhotCkov(Double_t cluX,Double_t cluY,Double_t &thetaCer,Double_t &phiCer) { // Finds Cerenkov angle for this photon candidate // Arguments: cluX,cluY - position of cadidate's cluster // Returns: Cerenkov angle TVector3 dirCkov; Double_t zRad= -0.5*fgkRadThick-0.5*fgkWinThick; //z position of middle of RAD TVector3 rad(fTrkPos.X(),fTrkPos.Y(),zRad); //impact point at middle of RAD TVector3 pc(cluX,cluY,0.5*fgkWinThick+fgkGapIdx); //mip at PC Double_t cluR = TMath::Sqrt((cluX-fTrkPos.X())*(cluX-fTrkPos.X())+ (cluY-fTrkPos.Y())*(cluY-fTrkPos.Y()));//ref. distance impact RAD-CLUSTER Double_t phi=(pc-rad).Phi(); //phi of photon Double_t ckov1=0; Double_t ckov2=0.75+fTrkDir.Theta(); //start to find theta cerenkov in DRS const Double_t kTol=0.01; Int_t iIterCnt = 0; while(1){ if(iIterCnt>=50) return kFALSE; Double_t ckov=0.5*(ckov1+ckov2); dirCkov.SetMagThetaPhi(1,ckov,phi); TVector2 posC=TraceForward(dirCkov); //trace photon with actual angles Double_t dist=cluR-(posC-fTrkPos).Mod(); //get distance between trial point and cluster position if(posC.X()==-999) dist = - 999; //total reflection problem iIterCnt++; //counter step if (dist> kTol) ckov1=ckov; //cluster @ larger ckov else if(dist<-kTol) ckov2=ckov; //cluster @ smaller ckov else{ //precision achived: ckov in DRS found dirCkov.SetMagThetaPhi(1,ckov,phi); // RecPhot(dirCkov,thetaCer,phiCer); //find ckov (in TRS:the effective Cherenkov angle!) return kTRUE; } } }//FindPhotTheta() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TVector2 AliHMPIDRecon::TraceForward(TVector3 dirCkov)const { //Trace forward a photon from (x,y) up to PC // Arguments: dirCkov photon vector in LORS // Returns: pos of traced photon at PC TVector2 pos(-999,-999); Double_t thetaCer = dirCkov.Theta(); if(thetaCer > TMath::ASin(1./fRadNmean)) return pos; //total refraction on WIN-GAP boundary Double_t zRad= -0.5*fgkRadThick-0.5*fgkWinThick; //z position of middle of RAD TVector3 posCkov(fTrkPos.X(),fTrkPos.Y(),zRad); //RAD: photon position is track position @ middle of RAD Propagate(dirCkov,posCkov, -0.5*fgkWinThick); //go to RAD-WIN boundary Refract (dirCkov, fRadNmean,fgkWinIdx); //RAD-WIN refraction Propagate(dirCkov,posCkov, 0.5*fgkWinThick); //go to WIN-GAP boundary Refract (dirCkov, fgkWinIdx,fgkGapIdx); //WIN-GAP refraction Propagate(dirCkov,posCkov,0.5*fgkWinThick+fgkGapThick); //go to PC pos.Set(posCkov.X(),posCkov.Y()); return pos; }//TraceForward() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void AliHMPIDRecon::RecPhot(TVector3 dirCkov,Double_t &thetaCer,Double_t &phiCer) { //Theta Cerenkov reconstruction // Arguments: (x,y) of initial point in LORS, dirCkov photon vector in LORS // Returns: thetaCer theta cerenkov reconstructed // TVector3 dirTrk; // dirTrk.SetMagThetaPhi(1,fTrkDir.Theta(),fTrkDir.Phi()); // Double_t thetaCer = TMath::ACos(dirCkov*dirTrk); TRotation mtheta; mtheta.RotateY(- fTrkDir.Theta()); TRotation mphi; mphi.RotateZ(- fTrkDir.Phi()); TRotation mrot=mtheta*mphi; TVector3 dirCkovTRS; dirCkovTRS=mrot*dirCkov; phiCer = dirCkovTRS.Phi(); //actual value of the phi of the photon thetaCer= dirCkovTRS.Theta(); //actual value of thetaCerenkov of the photon } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::FindRingArea(Double_t ckovAng)const { // Find area inside the cerenkov ring which lays inside PCs // Arguments: ckovAng - cerenkov angle // Returns: area of the ring in cm^2 for given theta ckov const Int_t kN=100; Double_t area=0; for(Int_t i=0;i<kN;i++){ TVector2 pos1=TracePhot(ckovAng,Double_t(TMath::TwoPi()*i /kN));//trace this photon TVector2 pos2=TracePhot(ckovAng,Double_t(TMath::TwoPi()*(i+1)/kN));//trace the next photon area+=(pos1-fTrkPos)*(pos2-fTrkPos); //add area of the triangle... } return area; }//FindRingArea() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::FindRingCkov(Int_t) { // Loops on all Ckov candidates and estimates the best Theta Ckov for a ring formed by those candidates. Also estimates an error for that Theat Ckov // collecting errors for all single Ckov candidates thetas. (Assuming they are independent) // Arguments: iNclus- total number of clusters in chamber for background estimation // Return: best estimation of track Theta ckov Double_t wei = 0.; Double_t weightThetaCerenkov = 0.; Double_t ckovMin=9999.,ckovMax=0.; Double_t sigma2 = 0; //to collect error squared for this ring for(Int_t i=0;i<fPhotCnt;i++){//candidates loop if(fPhotFlag[i] == 2){ if(fPhotCkov[i]<ckovMin) ckovMin=fPhotCkov[i]; //find max and min Theta ckov from all candidates within probable window if(fPhotCkov[i]>ckovMax) ckovMax=fPhotCkov[i]; weightThetaCerenkov += fPhotCkov[i]*fPhotWei[i]; wei += fPhotWei[i]; //collect weight as sum of all candidate weghts sigma2 += 1./Sigma2(fPhotCkov[i],fPhotPhi[i]); } }//candidates loop if(sigma2>0) fCkovSigma2=1./sigma2; else fCkovSigma2=1e10; if(wei != 0.) weightThetaCerenkov /= wei; else weightThetaCerenkov = 0.; return weightThetaCerenkov; }//FindCkovRing() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Int_t AliHMPIDRecon::FlagPhot(Double_t ckov) { // Flag photon candidates if their individual ckov angle is inside the window around ckov angle returned by HoughResponse() // Arguments: ckov- value of most probable ckov angle for track as returned by HoughResponse() // Returns: number of photon candidates happened to be inside the window // Photon Flag: Flag = 0 initial set; // Flag = 1 good candidate (charge compatible with photon); // Flag = 2 photon used for the ring; Int_t steps = (Int_t)((ckov )/ fDTheta); //how many times we need to have fDTheta to fill the distance between 0 and thetaCkovHough Double_t tmin = (Double_t)(steps - 1)*fDTheta; Double_t tmax = (Double_t)(steps)*fDTheta; Double_t tavg = 0.5*(tmin+tmax); tmin = tavg - 0.5*fWindowWidth; tmax = tavg + 0.5*fWindowWidth; Int_t iInsideCnt = 0; //count photons which Theta ckov inside the window for(Int_t i=0;i<fPhotCnt;i++){//photon candidates loop if(fPhotCkov[i] >= tmin && fPhotCkov[i] <= tmax) { fPhotFlag[i]=2; iInsideCnt++; } } return iInsideCnt; }//FlagPhot() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TVector2 AliHMPIDRecon::TracePhot(Double_t ckovThe,Double_t ckovPhi)const { // Trace a single Ckov photon from emission point somewhere in radiator up to photocathode taking into account ref indexes of materials it travereses // Arguments: ckovThe,ckovPhi- photon ckov angles in DRS, [rad] // Returns: distance between photon point on PC and track projection TRotation mtheta; mtheta.RotateY(fTrkDir.Theta()); TRotation mphi; mphi.RotateZ(fTrkDir.Phi()); TRotation mrot=mphi*mtheta; TVector3 dirCkov,dirCkovTors; dirCkovTors.SetMagThetaPhi(1,ckovThe,ckovPhi); //initially photon is directed according to requested ckov angle dirCkov=mrot*dirCkovTors; //now we know photon direction in LORS return TraceForward(dirCkov); }//TracePhot() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void AliHMPIDRecon::Propagate(const TVector3 dir,TVector3 &pos,Double_t z)const { // Finds an intersection point between a line and XY plane shifted along Z. // Arguments: dir,pos - vector along the line and any point of the line // z - z coordinate of plain // Returns: none // On exit: pos is the position if this intesection if any static TVector3 nrm(0,0,1); TVector3 pnt(0,0,z); TVector3 diff=pnt-pos; Double_t sint=(nrm*diff)/(nrm*dir); pos+=sint*dir; }//Propagate() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void AliHMPIDRecon::Refract(TVector3 &dir,Double_t n1,Double_t n2)const { // Refract direction vector according to Snell law // Arguments: // n1 - ref idx of first substance // n2 - ref idx of second substance // Returns: none // On exit: dir is new direction Double_t sinref=(n1/n2)*TMath::Sin(dir.Theta()); if(sinref>1.) dir.SetXYZ(-999,-999,-999); else dir.SetTheta(TMath::ASin(sinref)); }//Refract() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::HoughResponse() { // // // Double_t kThetaMax=0.75; Int_t nChannels = (Int_t)(kThetaMax/fDTheta+0.5); TH1D *phots = new TH1D("Rphot" ,"phots" ,nChannels,0,kThetaMax); TH1D *photsw = new TH1D("RphotWeighted" ,"photsw" ,nChannels,0,kThetaMax); TH1D *resultw = new TH1D("resultw","resultw" ,nChannels,0,kThetaMax); Int_t nBin = (Int_t)(kThetaMax/fDTheta); Int_t nCorrBand = (Int_t)(fWindowWidth/(2*fDTheta)); for (Int_t i=0; i< fPhotCnt; i++){//photon cadidates loop Double_t angle = fPhotCkov[i]; if(angle<0||angle>kThetaMax) continue; phots->Fill(angle); Int_t bin = (Int_t)(0.5+angle/(fDTheta)); Double_t weight=1.; if(fIsWEIGHT){ Double_t lowerlimit = ((Double_t)bin)*fDTheta - 0.5*fDTheta; Double_t upperlimit = ((Double_t)bin)*fDTheta + 0.5*fDTheta; Double_t diffArea = FindRingArea(upperlimit)-FindRingArea(lowerlimit); if(diffArea>0) weight = 1./diffArea; } photsw->Fill(angle,weight); fPhotWei[i]=weight; }//photon candidates loop for (Int_t i=1; i<=nBin;i++){ Int_t bin1= i-nCorrBand; Int_t bin2= i+nCorrBand; if(bin1<1) bin1=1; if(bin2>nBin)bin2=nBin; Double_t sumPhots=phots->Integral(bin1,bin2); if(sumPhots<3) continue; // if less then 3 photons don't trust to this ring Double_t sumPhotsw=photsw->Integral(bin1,bin2); resultw->Fill((Double_t)((i+0.5)*fDTheta),sumPhotsw); } // evaluate the "BEST" theta ckov as the maximum value of histogramm Double_t *pVec = resultw->GetArray(); Int_t locMax = TMath::LocMax(nBin,pVec); phots->Delete();photsw->Delete();resultw->Delete(); // Reset and delete objects return (Double_t)(locMax*fDTheta+0.5*fDTheta); //final most probable track theta ckov }//HoughResponse() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::Sigma2(Double_t ckovTh, Double_t ckovPh)const { // Analithical calculation of total error (as a sum of localization, geometrical and chromatic errors) on Cerenkov angle for a given Cerenkov photon // created by a given MIP. Fromulae according to CERN-EP-2000-058 // Arguments: Cerenkov and azimuthal angles for Cerenkov photon, [radians] // dip and azimuthal angles for MIP taken at the entrance to radiator, [radians] // MIP beta // Returns: absolute error on Cerenkov angle, [radians] TVector3 v(-999,-999,-999); Double_t trkBeta = 1./(TMath::Cos(ckovTh)*fRadNmean); v.SetX(SigLoc (ckovTh,ckovPh,trkBeta)); v.SetY(SigGeom(ckovTh,ckovPh,trkBeta)); v.SetZ(SigCrom(ckovTh,ckovPh,trkBeta)); return v.Mag2(); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::SigLoc(Double_t thetaC, Double_t phiC,Double_t betaM)const { // Analithical calculation of localization error (due to finite segmentation of PC) on Cerenkov angle for a given Cerenkov photon // created by a given MIP. Fromulae according to CERN-EP-2000-058 // Arguments: Cerenkov and azimuthal angles for Cerenkov photon, [radians] // dip and azimuthal angles for MIP taken at the entrance to radiator, [radians] // MIP beta // Returns: absolute error on Cerenkov angle, [radians] Double_t phiDelta = phiC - fTrkDir.Phi(); Double_t alpha =TMath::Cos(fTrkDir.Theta())-TMath::Tan(thetaC)*TMath::Cos(phiDelta)*TMath::Sin(fTrkDir.Theta()); Double_t k = 1.-fRadNmean*fRadNmean+alpha*alpha/(betaM*betaM); if (k<0) return 1e10; Double_t mu =TMath::Sin(fTrkDir.Theta())*TMath::Sin(fTrkDir.Phi())+TMath::Tan(thetaC)*(TMath::Cos(fTrkDir.Theta())*TMath::Cos(phiDelta)*TMath::Sin(fTrkDir.Phi())+TMath::Sin(phiDelta)*TMath::Cos(fTrkDir.Phi())); Double_t e =TMath::Sin(fTrkDir.Theta())*TMath::Cos(fTrkDir.Phi())+TMath::Tan(thetaC)*(TMath::Cos(fTrkDir.Theta())*TMath::Cos(phiDelta)*TMath::Cos(fTrkDir.Phi())-TMath::Sin(phiDelta)*TMath::Sin(fTrkDir.Phi())); Double_t kk = betaM*TMath::Sqrt(k)/(8*alpha); Double_t dtdxc = kk*(k*(TMath::Cos(phiDelta)*TMath::Cos(fTrkDir.Phi())-TMath::Cos(fTrkDir.Theta())*TMath::Sin(phiDelta)*TMath::Sin(fTrkDir.Phi()))-(alpha*mu/(betaM*betaM))*TMath::Sin(fTrkDir.Theta())*TMath::Sin(phiDelta)); Double_t dtdyc = kk*(k*(TMath::Cos(phiDelta)*TMath::Sin(fTrkDir.Phi())+TMath::Cos(fTrkDir.Theta())*TMath::Sin(phiDelta)*TMath::Cos(fTrkDir.Phi()))+(alpha* e/(betaM*betaM))*TMath::Sin(fTrkDir.Theta())*TMath::Sin(phiDelta)); return TMath::Sqrt(0.2*0.2*dtdxc*dtdxc + 0.25*0.25*dtdyc*dtdyc); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::SigCrom(Double_t thetaC, Double_t phiC,Double_t betaM)const { // Analithical calculation of chromatic error (due to lack of knowledge of Cerenkov photon energy) on Cerenkov angle for a given Cerenkov photon // created by a given MIP. Fromulae according to CERN-EP-2000-058 // Arguments: Cerenkov and azimuthal angles for Cerenkov photon, [radians] // dip and azimuthal angles for MIP taken at the entrance to radiator, [radians] // MIP beta // Returns: absolute error on Cerenkov angle, [radians] Double_t phiDelta = phiC - fTrkDir.Phi(); Double_t alpha =TMath::Cos(fTrkDir.Theta())-TMath::Tan(thetaC)*TMath::Cos(phiDelta)*TMath::Sin(fTrkDir.Theta()); Double_t dtdn = TMath::Cos(fTrkDir.Theta())*fRadNmean*betaM*betaM/(alpha*TMath::Tan(thetaC)); Double_t f = 0.00928*(7.75-5.635)/TMath::Sqrt(12.); return f*dtdn; }//SigCrom() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Double_t AliHMPIDRecon::SigGeom(Double_t thetaC, Double_t phiC,Double_t betaM)const { // Analithical calculation of geometric error (due to lack of knowledge of creation point in radiator) on Cerenkov angle for a given Cerenkov photon // created by a given MIP. Formulae according to CERN-EP-2000-058 // Arguments: Cerenkov and azimuthal angles for Cerenkov photon, [radians] // dip and azimuthal angles for MIP taken at the entrance to radiator, [radians] // MIP beta // Returns: absolute error on Cerenkov angle, [radians] Double_t phiDelta = phiC - fTrkDir.Phi(); Double_t alpha =TMath::Cos(fTrkDir.Theta())-TMath::Tan(thetaC)*TMath::Cos(phiDelta)*TMath::Sin(fTrkDir.Theta()); Double_t k = 1.-fRadNmean*fRadNmean+alpha*alpha/(betaM*betaM); if (k<0) return 1e10; Double_t eTr = 0.5*1.5*betaM*TMath::Sqrt(k)/(8*alpha); Double_t lambda = 1.-TMath::Sin(fTrkDir.Theta())*TMath::Sin(fTrkDir.Theta())*TMath::Sin(phiC)*TMath::Sin(phiC); Double_t c = 1./(1.+ eTr*k/(alpha*alpha*TMath::Cos(thetaC)*TMath::Cos(thetaC))); Double_t i = betaM*TMath::Tan(thetaC)*lambda*TMath::Power(k,1.5); Double_t ii = 1.+eTr*betaM*i; Double_t err = c * (i/(alpha*alpha*8) + ii*(1.-lambda) / ( alpha*alpha*8*betaM*(1.+eTr)) ); Double_t trErr = 1.5/(TMath::Sqrt(12.)*TMath::Cos(fTrkDir.Theta())); return trErr*err; }//SigGeom() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// HexEditView.cpp : implementation of the CHexEditView class // // Copyright (c) 1998-2010 by Andrew W. Phillips. // // No restrictions are placed on the noncommercial use of this code, // as long as this text (from the above copyright notice to the // disclaimer below) is preserved. // // This code may be redistributed as long as it remains unmodified // and is not sold for profit without the author's written consent. // // This code, or any part of it, may not be used in any software that // is sold for profit, without the author's written consent. // // DISCLAIMER: This file is provided "as is" with no expressed or // implied warranty. The author accepts no liability for any damage // or loss of business that this product may cause. // #include "stdafx.h" #include "HexEdit.h" #include "HexFileList.h" #include "HexEditDoc.h" #include "HexEditView.h" #include "DataFormatView.h" #include "AerialView.h" #include "CompareView.h" #include "MainFrm.h" #include "ChildFrm.h" #include "Dialog.h" #include "Bookmark.h" #include "NewFile.h" #include "Password.h" #include "Boyer.h" #include "SystemSound.h" #include "Misc.h" #include "BCGMisc.h" #include "SRecord.h" // For import/export of Motorola S record files #include "IntelHex.h" // For import/export of Intel Hex files #include "CopyCSrc.h" // For Copy as C Source dialog #include "zlib/zlib.h" // For compression #include "md5.h" // For MD5 hash #include "sha1.h" // For SHA1 hash #include "HelpID.hm" #ifdef _DEBUG #include "timer.h" #endif // This #define allows checking that the drawing code does clipping properly for // efficiency. For example for very long lines we don't want to draw a huge no // of byte values to the right and/or left of the display area. It does this by // moving the borders in and turning off the clipping rectangle use in OnDraw // (see GetDisplayRect) and also drawing red border lines in OnEraseBkgnd. // Also note that when in vert_display (stacked) mode that up to 3 lines can be // drawn past the top and bottom of the display area. //#define TEST_CLIPPING 1 // A note on the selection: // 1. The selection is a contiguous set of bytes with a start address and a length. // When a discontiguous "selection" is required we use the highlighter. // 2. The actual selection is kept track of in the base class (ScrView) members // caretpos_ and selpos_. SetCaret is used to set the caret with no selection // (ie selection length s zero) so caretpos_ == selpos_. There is also basepos_ // which is the start of the selection (ie either == caretpos_ or selpos_). // 3. At the basic level the selection is set/got using CSrcView::GetSel and SetSel, // which are pixel based. Since CScrView and its selection are text oriented there // is also GetTSel and SetTSel which are character based. // 4. CScrView allows the caret to be at the start or end of the selection, which is // why SetSel takes start/end positions plus a bool to says which end has the caret. // 5. SetSel calls ValidateCaret to find the closest valid caret position for the // start and end positions. // 6. CHexEditView::GetSelAddr/SetSelAddr get/set the selection in terms of file // addresses, by using addr2pos/pos2addr to convert between pixels and file addresses // before calling CScrView::GetSel/SetSel. // Similarly GetPos is the equivalent of GetCaret but returns a file address. // 7. To handle stacked mode addr2pos takes a row as well as an address. The row // can be a value of 0, 1, or 2 for the 3 rows when in stacked mode. // 8. At a higher level GoAddress will set the selection first making sure // its parameters are a valid range. // 9. At an even higher level MoveToAddress allows setting the selection while // updating everything else for consistency including: // - scrolling the display to show the selection // - storing undo information so the move can be undone // - keeping track of nav points // - updating jump tools with new address // - updating properties dialog with value at caret, etc #define MAX_CLIPBOARD 32000000L // Just a rough guideline - may make an option later #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CHexEditApp theApp; //BYTE CHexEditFontCombo::saved_charset = 147; // (see BCGMisc.h) initially 147 to not match // anything -> force initial rebuild of the font list static bool in_recalc_display = false; ///////////////////////////////////////////////////////////////////////////// // CHexEditView IMPLEMENT_DYNCREATE(CHexEditView, CScrView) BEGIN_MESSAGE_MAP(CHexEditView, CScrView) //{{AFX_MSG_MAP(CHexEditView) ON_WM_SIZE() ON_COMMAND(ID_ADDR_TOGGLE, OnAddrToggle) ON_UPDATE_COMMAND_UI(ID_ADDR_TOGGLE, OnUpdateAddrToggle) ON_COMMAND(ID_GRAPHIC_TOGGLE, OnGraphicToggle) ON_UPDATE_COMMAND_UI(ID_GRAPHIC_TOGGLE, OnUpdateGraphicToggle) ON_COMMAND(ID_CHAR_TOGGLE, OnCharToggle) ON_UPDATE_COMMAND_UI(ID_CHAR_TOGGLE, OnUpdateCharToggle) ON_COMMAND(ID_FONT, OnFont) ON_COMMAND(ID_AUTOFIT, OnAutoFit) ON_UPDATE_COMMAND_UI(ID_AUTOFIT, OnUpdateAutofit) ON_COMMAND(ID_ASC_EBC, OnAscEbc) ON_UPDATE_COMMAND_UI(ID_ASC_EBC, OnUpdateAscEbc) ON_COMMAND(ID_CONTROL, OnControl) ON_UPDATE_COMMAND_UI(ID_CONTROL, OnUpdateControl) ON_WM_CHAR() ON_WM_SETFOCUS() ON_WM_KILLFOCUS() ON_WM_DESTROY() ON_WM_LBUTTONDOWN() ON_COMMAND(ID_MARK, OnMark) ON_COMMAND(ID_GOTO_MARK, OnGotoMark) ON_WM_LBUTTONDBLCLK() ON_WM_KEYDOWN() ON_COMMAND(ID_EDIT_UNDO, OnEditUndo) ON_COMMAND(ID_SEARCH_HEX, OnSearchHex) ON_COMMAND(ID_SEARCH_ASCII, OnSearchAscii) ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo) ON_COMMAND(ID_ALLOW_MODS, OnAllowMods) ON_UPDATE_COMMAND_UI(ID_ALLOW_MODS, OnUpdateAllowMods) ON_COMMAND(ID_CONTROL_TOGGLE, OnControlToggle) ON_COMMAND(ID_INSERT, OnInsert) ON_UPDATE_COMMAND_UI(ID_INSERT, OnUpdateInsert) ON_COMMAND(ID_SEARCH_ICASE, OnSearchIcase) ON_COMMAND(ID_EDIT_COMPARE, OnEditCompare) ON_COMMAND(ID_WINDOW_NEXT, OnWindowNext) ON_UPDATE_COMMAND_UI(ID_EDIT_COMPARE, OnUpdateEditCompare) ON_WM_CONTEXTMENU() ON_WM_RBUTTONDOWN() ON_COMMAND(ID_INC_BYTE, OnIncByte) ON_COMMAND(ID_INC_16BIT, OnInc16bit) ON_COMMAND(ID_INC_32BIT, OnInc32bit) ON_COMMAND(ID_INC_64BIT, OnInc64bit) ON_COMMAND(ID_DEC_BYTE, OnDecByte) ON_COMMAND(ID_DEC_16BIT, OnDec16bit) ON_COMMAND(ID_DEC_32BIT, OnDec32bit) ON_COMMAND(ID_DEC_64BIT, OnDec64bit) ON_COMMAND(ID_FLIP_16BIT, OnFlip16bit) ON_COMMAND(ID_FLIP_32BIT, OnFlip32bit) ON_COMMAND(ID_FLIP_64BIT, OnFlip64bit) ON_UPDATE_COMMAND_UI(ID_INC_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_INC_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_INC_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_INC_64BIT, OnUpdate64bit) ON_WM_LBUTTONUP() ON_COMMAND(ID_SELECT_ALL, OnSelectAll) ON_COMMAND(ID_EDIT_COPY, OnEditCopy) ON_COMMAND(ID_EDIT_CUT, OnEditCut) ON_COMMAND(ID_EDIT_PASTE, OnEditPaste) ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdateTextPaste) ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateClipboard) ON_UPDATE_COMMAND_UI(ID_PASTE_UNICODE, OnUpdateUnicodePaste) ON_WM_SETCURSOR() ON_COMMAND(ID_FONT_DEC, OnFontDec) ON_COMMAND(ID_FONT_INC, OnFontInc) ON_UPDATE_COMMAND_UI(ID_FONT_DEC, OnUpdateFontDec) ON_UPDATE_COMMAND_UI(ID_FONT_INC, OnUpdateFontInc) ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateEditCut) ON_COMMAND(ID_PASTE_ASCII, OnPasteAscii) ON_COMMAND(ID_PASTE_EBCDIC, OnPasteEbcdic) ON_COMMAND(ID_PASTE_UNICODE, OnPasteUnicode) ON_COMMAND(ID_COPY_CCHAR, OnCopyCchar) ON_COMMAND(ID_COPY_HEX, OnCopyHex) ON_COMMAND(ID_EDIT_WRITEFILE, OnEditWriteFile) ON_UPDATE_COMMAND_UI(ID_EDIT_READFILE, OnUpdateReadFile) ON_COMMAND(ID_EDIT_READFILE, OnReadFile) ON_WM_HSCROLL() ON_WM_VSCROLL() ON_COMMAND(ID_EXTENDTO_MARK, OnExtendToMark) ON_COMMAND(ID_SWAP_MARK, OnSwapMark) ON_COMMAND(ID_REDRAW, OnRedraw) ON_COMMAND(ID_SCROLL_DOWN, OnScrollDown) ON_COMMAND(ID_SCROLL_UP, OnScrollUp) ON_COMMAND(ID_SWAP, OnSwap) ON_COMMAND(ID_START_LINE, OnStartLine) ON_COMMAND(ID_DEL, OnDel) ON_UPDATE_COMMAND_UI(ID_SWAP, OnUpdateSwap) ON_COMMAND(ID_OEM_TOGGLE, OnOemToggle) ON_UPDATE_COMMAND_UI(ID_OEM_TOGGLE, OnUpdateOemToggle) ON_WM_MOUSEWHEEL() ON_COMMAND(ID_INVERT, OnInvert) ON_COMMAND(ID_NEG_BYTE, OnNegByte) ON_COMMAND(ID_NEG_16BIT, OnNeg16bit) ON_COMMAND(ID_NEG_32BIT, OnNeg32bit) ON_COMMAND(ID_NEG_64BIT, OnNeg64bit) ON_WM_MOUSEMOVE() ON_WM_KEYUP() ON_COMMAND(ID_HIGHLIGHT, OnHighlight) ON_UPDATE_COMMAND_UI(ID_HIGHLIGHT, OnUpdateHighlight) ON_COMMAND(ID_HIGHLIGHT_CLEAR, OnHighlightClear) ON_COMMAND(ID_HIGHLIGHT_PREV, OnHighlightPrev) ON_COMMAND(ID_HIGHLIGHT_NEXT, OnHighlightNext) ON_UPDATE_COMMAND_UI(ID_HIGHLIGHT_PREV, OnUpdateHighlightPrev) ON_UPDATE_COMMAND_UI(ID_HIGHLIGHT_NEXT, OnUpdateHighlightNext) ON_COMMAND(ID_EDIT_GOTO, OnEditGoto) ON_COMMAND(ID_ASC2EBC, OnAscii2Ebcdic) ON_UPDATE_COMMAND_UI(ID_ASC2EBC, OnUpdateConvert) ON_COMMAND(ID_EBC2ASC, OnEbcdic2Ascii) ON_COMMAND(ID_ANSI2IBM, OnAnsi2Ibm) ON_COMMAND(ID_IBM2ANSI, OnIbm2Ansi) ON_COMMAND(ID_ENCRYPT_ENCRYPT, OnEncrypt) ON_COMMAND(ID_ENCRYPT_DECRYPT, OnDecrypt) ON_UPDATE_COMMAND_UI(ID_ENCRYPT_ENCRYPT, OnUpdateEncrypt) ON_COMMAND(ID_EDIT_APPENDFILE, OnEditAppendFile) ON_COMMAND(ID_EDIT_APPENDSAMEFILE, OnEditAppendSameFile) ON_UPDATE_COMMAND_UI(ID_EDIT_APPENDSAMEFILE, OnUpdateEditAppendSameFile) ON_COMMAND(ID_UNDO_CHANGES, OnUndoChanges) ON_UPDATE_COMMAND_UI(ID_UNDO_CHANGES, OnUpdateUndoChanges) ON_COMMAND(ID_CALC_SEL, OnCalcSel) ON_UPDATE_COMMAND_UI(ID_CALC_SEL, OnUpdateCalcSel) ON_COMMAND(ID_DISPLAY_RESET, OnDisplayReset) ON_WM_ERASEBKGND() ON_COMMAND(ID_IMPORT_MOTOROLA_S, OnImportMotorolaS) ON_UPDATE_COMMAND_UI(ID_IMPORT_MOTOROLA_S, OnUpdateImportMotorolaS) ON_COMMAND(ID_IMPORT_INTEL, OnImportIntel) ON_UPDATE_COMMAND_UI(ID_IMPORT_INTEL, OnUpdateImportIntel) ON_COMMAND(ID_EXPORT_INTEL, OnExportIntel) ON_UPDATE_COMMAND_UI(ID_EXPORT_INTEL, OnUpdateExportIntel) ON_COMMAND(ID_IMPORT_HEX_TEXT, OnImportHexText) ON_UPDATE_COMMAND_UI(ID_IMPORT_HEX_TEXT, OnUpdateImportHexText) ON_COMMAND(ID_EXPORT_HEX_TEXT, OnExportHexText) ON_UPDATE_COMMAND_UI(ID_EXPORT_HEX_TEXT, OnUpdateExportHexText) ON_COMMAND(ID_CRC16, OnCrc16) ON_COMMAND(ID_CRC32, OnCrc32) ON_COMMAND(ID_CRC_CCITT, OnCrcCcitt) ON_COMMAND(ID_CRC_CCITT_B, OnCrcCcittB) ON_COMMAND(ID_CRC_XMODEM, OnCrcXmodem) ON_COMMAND(ID_BOOKMARKS_HIDE, OnBookmarksHide) ON_UPDATE_COMMAND_UI(ID_BOOKMARKS_HIDE, OnUpdateBookmarksHide) ON_COMMAND(ID_HIGHLIGHT_HIDE, OnHighlightHide) ON_UPDATE_COMMAND_UI(ID_HIGHLIGHT_HIDE, OnUpdateHighlightHide) ON_COMMAND(ID_BOOKMARKS_NEXT, OnBookmarksNext) ON_UPDATE_COMMAND_UI(ID_BOOKMARKS_NEXT, OnUpdateBookmarksNext) ON_COMMAND(ID_BOOKMARKS_PREV, OnBookmarksPrev) ON_UPDATE_COMMAND_UI(ID_BOOKMARKS_PREV, OnUpdateBookmarksPrev) ON_COMMAND(ID_BOOKMARKS_CLEAR, OnBookmarksClear) ON_UPDATE_COMMAND_UI(ID_BOOKMARKS_CLEAR, OnUpdateBookmarksClear) ON_COMMAND(ID_EDIT_FIND, OnEditFind) ON_COMMAND(ID_BOOKMARK_TOGGLE, OnBookmarkToggle) ON_COMMAND(ID_COLUMN_DEC, OnColumnDec) ON_UPDATE_COMMAND_UI(ID_COLUMN_DEC, OnUpdateColumnDec) ON_COMMAND(ID_COLUMN_INC, OnColumnInc) ON_UPDATE_COMMAND_UI(ID_COLUMN_INC, OnUpdateColumnInc) ON_COMMAND(ID_DFFD_AUTO_SYNC, OnDffdAutoSync) ON_UPDATE_COMMAND_UI(ID_DFFD_AUTO_SYNC, OnUpdateDffdAutoSync) ON_COMMAND(ID_DFFD_SYNC, OnDffdSync) ON_UPDATE_COMMAND_UI(ID_DFFD_SYNC, OnUpdateDffdSync) ON_COMMAND(ID_RAND_SEED_CALC, OnSeedCalc) ON_COMMAND(ID_RAND_SEED, OnSeedRandom) ON_UPDATE_COMMAND_UI(ID_CONTROL_TOGGLE, OnUpdateControl) ON_UPDATE_COMMAND_UI(ID_DEC_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_DEC_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_DEC_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_DEC_64BIT, OnUpdate64bit) ON_UPDATE_COMMAND_UI(ID_FLIP_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_FLIP_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_FLIP_64BIT, OnUpdate64bit) ON_UPDATE_COMMAND_UI(ID_SEARCH_SEL, OnUpdateClipboard) ON_UPDATE_COMMAND_UI(ID_PASTE_ASCII, OnUpdateTextPaste) ON_UPDATE_COMMAND_UI(ID_PASTE_EBCDIC, OnUpdateTextPaste) ON_UPDATE_COMMAND_UI(ID_EDIT_WRITEFILE, OnUpdateClipboard) ON_UPDATE_COMMAND_UI(ID_INVERT, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_NEG_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_NEG_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_NEG_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_NEG_64BIT, OnUpdate64bit) ON_UPDATE_COMMAND_UI(ID_EBC2ASC, OnUpdateConvert) ON_UPDATE_COMMAND_UI(ID_ANSI2IBM, OnUpdateConvert) ON_UPDATE_COMMAND_UI(ID_IBM2ANSI, OnUpdateConvert) ON_UPDATE_COMMAND_UI(ID_ENCRYPT_DECRYPT, OnUpdateEncrypt) ON_UPDATE_COMMAND_UI(ID_EDIT_APPENDFILE, OnUpdateClipboard) ON_UPDATE_COMMAND_UI(ID_CRC16, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_CRC32, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_CRC_CCITT, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_CRC_CCITT_B, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_CRC_XMODEM, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_COPY_CCHAR, OnUpdateClipboard) ON_UPDATE_COMMAND_UI(ID_COPY_HEX, OnUpdateClipboard) ON_COMMAND(ID_TRACK_CHANGES, OnTrackChanges) ON_UPDATE_COMMAND_UI(ID_TRACK_CHANGES, OnUpdateTrackChanges) //}}AFX_MSG_MAP ON_COMMAND(ID_EDIT_REPLACE, OnEditReplace) ON_COMMAND(ID_CHECKSUM8, OnChecksum8) ON_COMMAND(ID_CHECKSUM16, OnChecksum16) ON_COMMAND(ID_CHECKSUM32, OnChecksum32) ON_COMMAND(ID_CHECKSUM64, OnChecksum64) ON_UPDATE_COMMAND_UI(ID_CHECKSUM8, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_CHECKSUM16, OnUpdate16bitNZ) ON_UPDATE_COMMAND_UI(ID_CHECKSUM32, OnUpdate32bitNZ) ON_UPDATE_COMMAND_UI(ID_CHECKSUM64, OnUpdate64bitNZ) ON_COMMAND(ID_XOR_BYTE, OnXorByte) ON_COMMAND(ID_XOR_16BIT, OnXor16bit) ON_COMMAND(ID_XOR_32BIT, OnXor32bit) ON_COMMAND(ID_XOR_64BIT, OnXor64bit) ON_UPDATE_COMMAND_UI(ID_XOR_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_XOR_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_XOR_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_XOR_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_ASSIGN_BYTE, OnAssignByte) ON_COMMAND(ID_ASSIGN_16BIT, OnAssign16bit) ON_COMMAND(ID_ASSIGN_32BIT, OnAssign32bit) ON_COMMAND(ID_ASSIGN_64BIT, OnAssign64bit) ON_UPDATE_COMMAND_UI(ID_ASSIGN_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_ASSIGN_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_ASSIGN_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_ASSIGN_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_RAND_BYTE, OnRandByte) ON_COMMAND(ID_RAND_FAST, OnRandFast) // ON_COMMAND(ID_RAND_16BIT, OnRand16bit) // ON_COMMAND(ID_RAND_32BIT, OnRand32bit) // ON_COMMAND(ID_RAND_64BIT, OnRand64bit) ON_UPDATE_COMMAND_UI(ID_RAND_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_RAND_FAST, OnUpdateByte) // ON_UPDATE_COMMAND_UI(ID_RAND_16BIT, OnUpdate16bit) // ON_UPDATE_COMMAND_UI(ID_RAND_32BIT, OnUpdate32bit) // ON_UPDATE_COMMAND_UI(ID_RAND_64BIT, OnUpdate64bit) ON_COMMAND(ID_ADD_BYTE, OnAddByte) ON_COMMAND(ID_ADD_16BIT, OnAdd16bit) ON_COMMAND(ID_ADD_32BIT, OnAdd32bit) ON_COMMAND(ID_ADD_64BIT, OnAdd64bit) ON_UPDATE_COMMAND_UI(ID_ADD_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_ADD_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_ADD_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_ADD_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_SUBTRACT_BYTE, OnSubtractByte) ON_COMMAND(ID_SUBTRACT_16BIT, OnSubtract16bit) ON_COMMAND(ID_SUBTRACT_32BIT, OnSubtract32bit) ON_COMMAND(ID_SUBTRACT_64BIT, OnSubtract64bit) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_AND_BYTE, OnAndByte) ON_COMMAND(ID_AND_16BIT, OnAnd16bit) ON_COMMAND(ID_AND_32BIT, OnAnd32bit) ON_COMMAND(ID_AND_64BIT, OnAnd64bit) ON_UPDATE_COMMAND_UI(ID_AND_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_AND_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_AND_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_AND_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_OR_BYTE, OnOrByte) ON_COMMAND(ID_OR_16BIT, OnOr16bit) ON_COMMAND(ID_OR_32BIT, OnOr32bit) ON_COMMAND(ID_OR_64BIT, OnOr64bit) ON_UPDATE_COMMAND_UI(ID_OR_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_OR_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_OR_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_OR_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_MUL_BYTE, OnMulByte) ON_UPDATE_COMMAND_UI(ID_MUL_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_MUL_16BIT, OnMul16bit) ON_UPDATE_COMMAND_UI(ID_MUL_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_MUL_32BIT, OnMul32bit) ON_UPDATE_COMMAND_UI(ID_MUL_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_MUL_64BIT, OnMul64bit) ON_UPDATE_COMMAND_UI(ID_MUL_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_DIV_BYTE, OnDivByte) ON_UPDATE_COMMAND_UI(ID_DIV_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_DIV_16BIT, OnDiv16bit) ON_UPDATE_COMMAND_UI(ID_DIV_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_DIV_32BIT, OnDiv32bit) ON_UPDATE_COMMAND_UI(ID_DIV_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_DIV_64BIT, OnDiv64bit) ON_UPDATE_COMMAND_UI(ID_DIV_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_MOD_BYTE, OnModByte) ON_UPDATE_COMMAND_UI(ID_MOD_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_MOD_16BIT, OnMod16bit) ON_UPDATE_COMMAND_UI(ID_MOD_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_MOD_32BIT, OnMod32bit) ON_UPDATE_COMMAND_UI(ID_MOD_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_MOD_64BIT, OnMod64bit) ON_UPDATE_COMMAND_UI(ID_MOD_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_REV_BYTE, OnRevByte) ON_UPDATE_COMMAND_UI(ID_REV_BYTE, OnUpdateByte) ON_COMMAND(ID_REV_16BIT, OnRev16bit) ON_UPDATE_COMMAND_UI(ID_REV_16BIT, OnUpdate16bit) ON_COMMAND(ID_REV_32BIT, OnRev32bit) ON_UPDATE_COMMAND_UI(ID_REV_32BIT, OnUpdate32bit) ON_COMMAND(ID_REV_64BIT, OnRev64bit) ON_UPDATE_COMMAND_UI(ID_REV_64BIT, OnUpdate64bit) ON_COMMAND(ID_SUBTRACT_X_BYTE, OnSubtractXByte) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_X_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_SUBTRACT_X_16BIT, OnSubtractX16bit) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_X_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_SUBTRACT_X_32BIT, OnSubtractX32bit) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_X_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_SUBTRACT_X_64BIT, OnSubtractX64bit) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_X_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_DIV_X_BYTE, OnDivXByte) ON_UPDATE_COMMAND_UI(ID_DIV_X_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_DIV_X_16BIT, OnDivX16bit) ON_UPDATE_COMMAND_UI(ID_DIV_X_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_DIV_X_32BIT, OnDivX32bit) ON_UPDATE_COMMAND_UI(ID_DIV_X_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_DIV_X_64BIT, OnDivX64bit) ON_UPDATE_COMMAND_UI(ID_DIV_X_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_MOD_X_BYTE, OnModXByte) ON_UPDATE_COMMAND_UI(ID_MOD_X_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_MOD_X_16BIT, OnModX16bit) ON_UPDATE_COMMAND_UI(ID_MOD_X_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_MOD_X_32BIT, OnModX32bit) ON_UPDATE_COMMAND_UI(ID_MOD_X_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_MOD_X_64BIT, OnModX64bit) ON_UPDATE_COMMAND_UI(ID_MOD_X_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_GTR_BYTE, OnGtrByte) ON_UPDATE_COMMAND_UI(ID_GTR_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_GTR_16BIT, OnGtr16bit) ON_UPDATE_COMMAND_UI(ID_GTR_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_GTR_32BIT, OnGtr32bit) ON_UPDATE_COMMAND_UI(ID_GTR_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_GTR_64BIT, OnGtr64bit) ON_UPDATE_COMMAND_UI(ID_GTR_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_LESS_BYTE, OnLessByte) ON_UPDATE_COMMAND_UI(ID_LESS_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_LESS_16BIT, OnLess16bit) ON_UPDATE_COMMAND_UI(ID_LESS_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_LESS_32BIT, OnLess32bit) ON_UPDATE_COMMAND_UI(ID_LESS_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_LESS_64BIT, OnLess64bit) ON_UPDATE_COMMAND_UI(ID_LESS_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_GTRU_BYTE, OnGtrUByte) ON_UPDATE_COMMAND_UI(ID_GTRU_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_GTRU_16BIT, OnGtrU16bit) ON_UPDATE_COMMAND_UI(ID_GTRU_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_GTRU_32BIT, OnGtrU32bit) ON_UPDATE_COMMAND_UI(ID_GTRU_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_GTRU_64BIT, OnGtrU64bit) ON_UPDATE_COMMAND_UI(ID_GTRU_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_LESSU_BYTE, OnLessUByte) ON_UPDATE_COMMAND_UI(ID_LESSU_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_LESSU_16BIT, OnLessU16bit) ON_UPDATE_COMMAND_UI(ID_LESSU_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_LESSU_32BIT, OnLessU32bit) ON_UPDATE_COMMAND_UI(ID_LESSU_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_LESSU_64BIT, OnLessU64bit) ON_UPDATE_COMMAND_UI(ID_LESSU_64BIT, OnUpdate64bitBinary) // Note shifts don't care about calc operand size (bits) since values are less than 64 ON_COMMAND(ID_ROL_BYTE, OnRolByte) ON_COMMAND(ID_ROL_16BIT, OnRol16bit) ON_COMMAND(ID_ROL_32BIT, OnRol32bit) ON_COMMAND(ID_ROL_64BIT, OnRol64bit) ON_UPDATE_COMMAND_UI(ID_ROL_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_ROL_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_ROL_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_ROL_64BIT, OnUpdate64bit) ON_COMMAND(ID_ROR_BYTE, OnRorByte) ON_COMMAND(ID_ROR_16BIT, OnRor16bit) ON_COMMAND(ID_ROR_32BIT, OnRor32bit) ON_COMMAND(ID_ROR_64BIT, OnRor64bit) ON_UPDATE_COMMAND_UI(ID_ROR_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_ROR_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_ROR_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_ROR_64BIT, OnUpdate64bit) ON_COMMAND(ID_LSL_BYTE, OnLslByte) ON_COMMAND(ID_LSL_16BIT, OnLsl16bit) ON_COMMAND(ID_LSL_32BIT, OnLsl32bit) ON_COMMAND(ID_LSL_64BIT, OnLsl64bit) ON_UPDATE_COMMAND_UI(ID_LSL_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_LSL_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_LSL_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_LSL_64BIT, OnUpdate64bit) ON_COMMAND(ID_LSR_BYTE, OnLsrByte) ON_COMMAND(ID_LSR_16BIT, OnLsr16bit) ON_COMMAND(ID_LSR_32BIT, OnLsr32bit) ON_COMMAND(ID_LSR_64BIT, OnLsr64bit) ON_UPDATE_COMMAND_UI(ID_LSR_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_LSR_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_LSR_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_LSR_64BIT, OnUpdate64bit) ON_COMMAND(ID_ASR_BYTE, OnAsrByte) ON_COMMAND(ID_ASR_16BIT, OnAsr16bit) ON_COMMAND(ID_ASR_32BIT, OnAsr32bit) ON_COMMAND(ID_ASR_64BIT, OnAsr64bit) ON_UPDATE_COMMAND_UI(ID_ASR_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_ASR_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_ASR_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_ASR_64BIT, OnUpdate64bit) ON_COMMAND_RANGE(ID_EXPORT_S1, ID_EXPORT_S3, OnExportSRecord) ON_UPDATE_COMMAND_UI_RANGE(ID_EXPORT_S1, ID_EXPORT_S3, OnUpdateExportSRecord) ON_UPDATE_COMMAND_UI(ID_INSERT_BLOCK, OnUpdateInsertBlock) ON_COMMAND(ID_INSERT_BLOCK, OnInsertBlock) // New display handling commands ON_COMMAND(ID_DISPLAY_HEX, OnDisplayHex) ON_UPDATE_COMMAND_UI(ID_DISPLAY_HEX, OnUpdateDisplayHex) ON_COMMAND(ID_DISPLAY_CHAR, OnDisplayChar) ON_UPDATE_COMMAND_UI(ID_DISPLAY_CHAR, OnUpdateDisplayChar) ON_COMMAND(ID_DISPLAY_BOTH, OnDisplayBoth) ON_UPDATE_COMMAND_UI(ID_DISPLAY_BOTH, OnUpdateDisplayBoth) ON_COMMAND(ID_DISPLAY_STACKED, OnDisplayStacked) ON_UPDATE_COMMAND_UI(ID_DISPLAY_STACKED, OnUpdateDisplayStacked) ON_COMMAND(ID_CHARSET_ASCII, OnCharsetAscii) ON_UPDATE_COMMAND_UI(ID_CHARSET_ASCII, OnUpdateCharsetAscii) ON_COMMAND(ID_CHARSET_ANSI, OnCharsetAnsi) ON_UPDATE_COMMAND_UI(ID_CHARSET_ANSI, OnUpdateCharsetAnsi) ON_COMMAND(ID_CHARSET_OEM, OnCharsetOem) ON_UPDATE_COMMAND_UI(ID_CHARSET_OEM, OnUpdateCharsetOem) ON_COMMAND(ID_CHARSET_EBCDIC, OnCharsetEbcdic) ON_UPDATE_COMMAND_UI(ID_CHARSET_EBCDIC, OnUpdateCharsetEbcdic) ON_COMMAND(ID_CONTROL_NONE, OnControlNone) ON_UPDATE_COMMAND_UI(ID_CONTROL_NONE, OnUpdateControlNone) ON_COMMAND(ID_CONTROL_ALPHA, OnControlAlpha) ON_UPDATE_COMMAND_UI(ID_CONTROL_ALPHA, OnUpdateControlAlpha) ON_COMMAND(ID_CONTROL_C, OnControlC) ON_UPDATE_COMMAND_UI(ID_CONTROL_C, OnUpdateControlC) ON_COMMAND(ID_TOGGLE_ENDIAN, OnToggleEndian) ON_COMMAND(ID_BIG_ENDIAN, OnBigEndian) ON_COMMAND(ID_LITTLE_ENDIAN, OnLittleEndian) ON_UPDATE_COMMAND_UI(ID_TOGGLE_ENDIAN, OnUpdateToggleEndian) ON_UPDATE_COMMAND_UI(ID_BIG_ENDIAN, OnUpdateBigEndian) ON_UPDATE_COMMAND_UI(ID_LITTLE_ENDIAN, OnUpdateLittleEndian) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview) ON_COMMAND(ID_JUMP_HEX_ADDR, OnJumpHexAddr) // ON_COMMAND(ID_SEARCH_START, OnSearch) // Handle message from BCG search combo ON_COMMAND(ID_JUMP_HEX_START, OnJumpHex) // Handle message from BCG hex combo ON_COMMAND(ID_JUMP_DEC_START, OnJumpDec) // Handle message from BCG dec combo ON_COMMAND(ID_SELECT_LINE, OnSelectLine) ON_COMMAND(IDC_FONTNAME, OnFontName) ON_UPDATE_COMMAND_UI(IDC_FONTNAME, OnUpdateFontName) ON_COMMAND(IDC_FONTSIZE, OnFontSize) ON_UPDATE_COMMAND_UI(IDC_FONTSIZE, OnUpdateFontSize) ON_CBN_SELENDOK(IDC_FONTNAME, OnFontName) ON_CBN_SELENDOK(IDC_FONTSIZE, OnFontSize) ON_COMMAND(ID_ZLIB_COMPRESS, OnCompress) ON_UPDATE_COMMAND_UI(ID_ZLIB_COMPRESS, OnUpdateSelNZ) ON_COMMAND(ID_ZLIB_DECOMPRESS, OnDecompress) ON_UPDATE_COMMAND_UI(ID_ZLIB_DECOMPRESS, OnUpdateSelNZ) ON_COMMAND(ID_MD5, OnMd5) ON_UPDATE_COMMAND_UI(ID_MD5, OnUpdateByteNZ) ON_COMMAND(ID_SHA1, OnSha1) ON_UPDATE_COMMAND_UI(ID_SHA1, OnUpdateByteNZ) ON_COMMAND(ID_UPPERCASE, OnUppercase) ON_UPDATE_COMMAND_UI(ID_UPPERCASE, OnUpdateConvert) ON_COMMAND(ID_LOWERCASE, OnLowercase) ON_UPDATE_COMMAND_UI(ID_LOWERCASE, OnUpdateConvert) ON_COMMAND(ID_DFFD_HIDE, OnDffdHide) ON_UPDATE_COMMAND_UI(ID_DFFD_HIDE, OnUpdateDffdHide) ON_COMMAND(ID_DFFD_SPLIT, OnDffdSplit) ON_UPDATE_COMMAND_UI(ID_DFFD_SPLIT, OnUpdateDffdSplit) ON_COMMAND(ID_DFFD_TAB, OnDffdTab) ON_UPDATE_COMMAND_UI(ID_DFFD_TAB, OnUpdateDffdTab) ON_COMMAND(ID_AERIAL_HIDE, OnAerialHide) ON_UPDATE_COMMAND_UI(ID_AERIAL_HIDE, OnUpdateAerialHide) ON_COMMAND(ID_AERIAL_SPLIT, OnAerialSplit) ON_UPDATE_COMMAND_UI(ID_AERIAL_SPLIT, OnUpdateAerialSplit) ON_COMMAND(ID_AERIAL_TAB, OnAerialTab) ON_UPDATE_COMMAND_UI(ID_AERIAL_TAB, OnUpdateAerialTab) ON_COMMAND(ID_COMP_HIDE, OnCompHide) ON_UPDATE_COMMAND_UI(ID_COMP_HIDE, OnUpdateCompHide) ON_COMMAND(ID_COMP_SPLIT, OnCompSplit) ON_UPDATE_COMMAND_UI(ID_COMP_SPLIT, OnUpdateCompSplit) ON_COMMAND(ID_COMP_TAB, OnCompTab) ON_UPDATE_COMMAND_UI(ID_COMP_TAB, OnUpdateCompTab) ON_COMMAND(ID_HIGHLIGHT_SELECT, OnHighlightSelect) //ON_WM_TIMER() ON_COMMAND(ID_VIEWTEST, OnViewtest) ON_WM_SYSCOLORCHANGE() ON_MESSAGE(WM_MOUSEHOVER, OnMouseHover) ON_MESSAGE(WM_MOUSELEAVE, OnMouseLeave) ON_COMMAND(ID_SCHEME, OnOptScheme) ON_CBN_SELENDOK(ID_SCHEME, OnSelScheme) ON_UPDATE_COMMAND_UI(ID_SCHEME, OnUpdateScheme) ON_COMMAND(ID_SCHEME_US, OnOptScheme) ON_CBN_SELENDOK(ID_SCHEME_US, OnSelScheme) ON_UPDATE_COMMAND_UI(ID_SCHEME_US, OnUpdateScheme) ON_COMMAND(ID_COMP_FIRST, OnCompFirst) ON_COMMAND(ID_COMP_PREV, OnCompPrev) ON_COMMAND(ID_COMP_NEXT, OnCompNext) ON_COMMAND(ID_COMP_LAST, OnCompLast) ON_UPDATE_COMMAND_UI(ID_COMP_FIRST, OnUpdateCompFirst) ON_UPDATE_COMMAND_UI(ID_COMP_PREV, OnUpdateCompPrev) ON_UPDATE_COMMAND_UI(ID_COMP_NEXT, OnUpdateCompNext) ON_UPDATE_COMMAND_UI(ID_COMP_LAST, OnUpdateCompLast) ON_COMMAND(ID_COMP_ALL_FIRST, OnCompAllFirst) ON_COMMAND(ID_COMP_ALL_PREV, OnCompAllPrev) ON_COMMAND(ID_COMP_ALL_NEXT, OnCompAllNext) ON_COMMAND(ID_COMP_ALL_LAST, OnCompAllLast) ON_UPDATE_COMMAND_UI(ID_COMP_ALL_FIRST, OnUpdateCompAllFirst) ON_UPDATE_COMMAND_UI(ID_COMP_ALL_PREV, OnUpdateCompAllPrev) ON_UPDATE_COMMAND_UI(ID_COMP_ALL_NEXT, OnUpdateCompAllNext) ON_UPDATE_COMMAND_UI(ID_COMP_ALL_LAST, OnUpdateCompAllLast) ON_COMMAND(ID_COMP_AUTO_SYNC, OnCompAutoSync) ON_UPDATE_COMMAND_UI(ID_COMP_AUTO_SYNC, OnUpdateCompAutoSync) ON_COMMAND(ID_COMP_AUTO_SCROLL, OnCompAutoScroll) ON_UPDATE_COMMAND_UI(ID_COMP_AUTO_SCROLL, OnUpdateCompAutoScroll) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CHexEditView construction/destruction CHexEditView::CHexEditView() { expr_.SetView(this); text_height_ = 0; // While text_height_ == 0 none of the display settings have been calculated pdfv_ = NULL; pav_ = NULL; pcv_ = NULL; CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); disp_state_ = previous_state_ = 0; resize_start_addr_ = resize_curr_scroll_ = -1; pfont_ = NULL; pbrush_ = NULL; print_font_ = NULL; // Set up opening display based on global options rowsize_ = aa->open_rowsize_; real_offset_ = offset_ = aa->open_offset_; if (real_offset_ >= rowsize_) offset_ = rowsize_ - 1; // In case soemone fiddled with the settings group_by_ = aa->open_group_by_; ASSERT(theApp.open_disp_state_ != -1); disp_state_ = theApp.open_disp_state_; bg_col_ = -1; hl_set_.clear(); mark_ = 0L; // Mark initially at start of file if (!display_.hex_area) display_.edit_char = display_.mark_char = TRUE; // No hex area so must use char else display_.edit_char = display_.mark_char = FALSE; // Caret init. in hex not char area mouse_addr_ = -1; // Only used when theApp.hl_mouse_ is on mouse_down_ = false; drag_bookmark_ = -1; needs_refresh_ = false; needs_hscroll_ = false; needs_vscroll_ = false; memset((void *)&lf_, '\0', sizeof(lf_)); _tcscpy(lf_.lfFaceName, _T("Courier")); // A nice fixed (no-proportional) font lf_.lfHeight = 16; lf_.lfCharSet = ANSI_CHARSET; // Only allow ANSI character set fonts oem_lf_ = lf_; _tcscpy(oem_lf_.lfFaceName, _T("Terminal")); // The only certain OEM font? oem_lf_.lfHeight = 18; oem_lf_.lfCharSet = OEM_CHARSET; // Only allow OEM/IBM character set fonts search_length_ = 0; last_tip_addr_ = -1; tip_show_bookmark_ = true; tip_show_error_ = true; #ifndef NDEBUG // Make default capacity for undo_ vector small to force reallocation sooner. // This increases likelihood of catching bugs related to reallocation. undo_.reserve(4); #else undo_.reserve(1024); #endif #ifdef RULER_ADJUST adjusting_rowsize_ = adjusting_offset_ = adjusting_group_by_ = -1; #endif errors_mentioned_ = false; } CHexEditView::~CHexEditView() { if (pfont_ != NULL) delete pfont_; if (pbrush_ != NULL) delete pbrush_; } BOOL CHexEditView::PreCreateWindow(CREATESTRUCT& cs) { BOOL retval = CScrView::PreCreateWindow(cs); // Get the create context so we can find out if this window is // being created via Window/New and the frame/view it's cloned from CCreateContext *pContext = (CCreateContext *)cs.lpCreateParams; if (pContext != NULL && pContext->m_pCurrentFrame != NULL) { // Must have been created via Window/New (ID_WINDOW_NEW) ASSERT_KINDOF(CMDIChildWnd, pContext->m_pCurrentFrame); // We have the frame so get the view within it CHexEditView *pView = (CHexEditView *)pContext->m_pCurrentFrame->GetActiveView(); if (pView->IsKindOf(RUNTIME_CLASS(CCompareView))) pView = ((CCompareView *)pView)->phev_; else if (pView->IsKindOf(RUNTIME_CLASS(CAerialView))) pView = ((CAerialView *)pView)->phev_; else if (pView->IsKindOf(RUNTIME_CLASS(CDataFormatView))) pView = ((CDataFormatView *)pView)->phev_; ASSERT_KINDOF(CHexEditView, pView); // Make this view's undo stack the same as clone view undo_ = pView->undo_; // Flag any changes as not being made in this view std::vector <view_undo>::iterator pu; for (pu = undo_.begin(); pu != undo_.end(); ++pu) { if (pu->utype == undo_change) pu->flag = FALSE; } } return retval; } void CHexEditView::OnInitialUpdate() { FILE_ADDRESS start_addr = 0; FILE_ADDRESS end_addr = 0; CHexEditDoc *pDoc = GetDocument(); CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); print_map_mode_ = MM_HIENGLISH; split_width_d_ = split_width_a_ = split_width_c_ = -1; // Get options for the window from file settings in CHexFileList CHexFileList *pfl = aa->GetFileList(); int recent_file_index = -1; if (pDoc->pfile1_ != NULL) recent_file_index = pfl->GetIndex(pDoc->pfile1_->GetFilePath()); #ifdef TEST_CLIPPING bdr_top_ = bdr_bottom_ = 80; bdr_left_ = 120; bdr_right_ = 40; #endif if (recent_file_index != -1) { CString ss = pfl->GetData(recent_file_index, CHexFileList::DFFDVIEW); if (ss.IsEmpty()) split_width_d_ = theApp.dffdview_; else split_width_d_ = atoi(ss); ss = pfl->GetData(recent_file_index, CHexFileList::AERIALVIEW); if (ss.IsEmpty()) split_width_a_ = theApp.aerialview_; else split_width_a_ = atoi(ss); ss = pfl->GetData(recent_file_index, CHexFileList::COMPVIEW); if (ss.IsEmpty()) split_width_c_ = theApp.compview_; else split_width_c_ = atoi(ss); disp_state_ = atoi(pfl->GetData(recent_file_index, CHexFileList::DISPLAY)); SetVertBufferZone(atoi(pfl->GetData(recent_file_index, CHexFileList::VERT_BUFFER_ZONE))); // Get the colour scheme, if none try to find one based on file extension, otherwise // let set_colours() handle it using the default scheme for the current char set. scheme_name_ = pfl->GetData(recent_file_index, CHexFileList::SCHEME); if (scheme_name_.IsEmpty()) { // Get file extension and change "." to "_" ss = pDoc->GetFileName(); if (ss.ReverseFind('.') == -1) ss = "_"; else ss = CString("_") + ss.Mid(ss.ReverseFind('.')+1); // If there is a scheme of this name make it the scheme to use std::vector<CScheme>::const_iterator ps; for (ps = theApp.scheme_.begin(); ps != theApp.scheme_.end(); ++ps) { if (ss.CompareNoCase(ps->name_) == 0) { scheme_name_ = ps->name_; break; } } } set_colours(); rowsize_ = atoi(pfl->GetData(recent_file_index, CHexFileList::COLUMNS)); real_offset_ = offset_ = atoi(pfl->GetData(recent_file_index, CHexFileList::OFFSET)); if (real_offset_ >= rowsize_) offset_ = rowsize_ - 1; // In case soemone fiddled with the settings group_by_ = atoi(pfl->GetData(recent_file_index, CHexFileList::GROUPING)); start_addr = _atoi64(pfl->GetData(recent_file_index, CHexFileList::SELSTART)); end_addr = _atoi64(pfl->GetData(recent_file_index, CHexFileList::SELEND)); if (start_addr < 0 || start_addr > pDoc->length()) start_addr = 0; if (end_addr < start_addr || end_addr > pDoc->length()) end_addr = start_addr; mark_ = _atoi64(pfl->GetData(recent_file_index, CHexFileList::MARK)); if (mark_ < 0 || mark_ > pDoc->length()) mark_ = 0; ASSERT(display_.hex_area || display_.edit_char); // if no hex area we must be editing chars // Get saved font info strncpy(lf_.lfFaceName, pfl->GetData(recent_file_index, CHexFileList::FONT), LF_FACESIZE-1); lf_.lfFaceName[LF_FACESIZE-1] = '\0'; lf_.lfHeight = atoi(pfl->GetData(recent_file_index, CHexFileList::HEIGHT)); strncpy(oem_lf_.lfFaceName, pfl->GetData(recent_file_index, CHexFileList::OEMFONT), LF_FACESIZE-1); oem_lf_.lfFaceName[LF_FACESIZE-1] = '\0'; oem_lf_.lfHeight = atoi(pfl->GetData(recent_file_index, CHexFileList::OEMHEIGHT)); std::istringstream strstr((const char *)pfl->GetData(recent_file_index, CHexFileList::HIGHLIGHTS)); strstr >> hl_set_; CRect newpos; newpos.top = atoi(pfl->GetData(recent_file_index, CHexFileList::TOP)); newpos.left = atoi(pfl->GetData(recent_file_index, CHexFileList::LEFT)); newpos.bottom = atoi(pfl->GetData(recent_file_index, CHexFileList::BOTTOM)); newpos.right = atoi(pfl->GetData(recent_file_index, CHexFileList::RIGHT)); // Make sure that window size seems reasonable if (newpos.top != -30000 && newpos.left != -30000 && newpos.top < newpos.bottom && newpos.left < newpos.right ) { WINDOWPLACEMENT wp; wp.length = sizeof(wp); wp.flags = 0; wp.showCmd = atoi(pfl->GetData(recent_file_index, CHexFileList::CMD)); wp.ptMinPosition = CPoint(-1,-1); wp.ptMaxPosition = CPoint(-1,-1); // If this window has sibling view this window was presumably created // using Window/New - make sure its not in the same place as its sibling(s). POSITION pos = pDoc->GetFirstViewPosition(); while (pos != NULL) { WINDOWPLACEMENT frame_wp; frame_wp.length = sizeof(frame_wp); CView *pv = pDoc->GetNextView(pos); if (pv->IsKindOf(RUNTIME_CLASS(CHexEditView))) { ASSERT(pv != NULL && ((CHexEditView *)pv)->GetFrame() != NULL); if (pv != this && ((CHexEditView *)pv)->GetFrame()->GetWindowPlacement(&frame_wp)) { // If the top left corners are about the same move the // new window down and right a bit. if (abs(newpos.top - frame_wp.rcNormalPosition.top) < 20 && abs(newpos.left - frame_wp.rcNormalPosition.left) < 20) { newpos += CSize(30, 30); } } } } // Check that new position is not completely off the left, right or bottom, // and that the top title bar is still visible to allow dragging. CRect rr; ASSERT(GetFrame() != NULL && GetFrame()->GetParent() != NULL); GetFrame()->GetParent()->GetClientRect(&rr); if (newpos.left > rr.right-20) { newpos.left = rr.right - (newpos.right - newpos.left); newpos.right = rr.right; } if (newpos.right < 20) { newpos.right -= newpos.left; newpos.left = 0; } if (newpos.top > rr.bottom-20) { newpos.top = rr.bottom - (newpos.bottom - newpos.top); newpos.bottom = rr.bottom; } if (newpos.top < -20) { newpos.bottom -= newpos.top; newpos.top =0; } wp.rcNormalPosition = newpos; if (wp.showCmd == SW_SHOWMAXIMIZED) wp.flags = WPF_RESTORETOMAXIMIZED; GetFrame()->SetWindowPlacement(&wp); } else if (atoi(pfl->GetData(recent_file_index, CHexFileList::CMD)) == SW_SHOWMAXIMIZED) { WINDOWPLACEMENT wp; ASSERT(GetFrame() != NULL); GetFrame()->GetWindowPlacement(&wp); wp.showCmd = SW_SHOWMAXIMIZED; GetFrame()->SetWindowPlacement(&wp); } // Set horiz size, vert size, and scroll posn if (display_.vert_display || display_.char_area) SetSize(CSize(char_pos(rowsize_-1)+text_width_w_+text_width_w_/2+1, -1)); else { ASSERT(display_.hex_area); display_.hex_area = TRUE; // defensive SetSize(CSize(hex_pos(rowsize_-1)+2*text_width_+text_width_/2+1, -1)); } if (display_.vert_display) SetTSize(CSizeAp(-1, ((GetDocument()->length() + offset_)/rowsize_ + 1)*3)); // 3 rows of text else SetTSize(CSizeAp(-1, (GetDocument()->length() + offset_)/rowsize_ + 1)); SetScroll(CPointAp(0, _atoi64(pfl->GetData(recent_file_index, CHexFileList::POS)))); } else { ASSERT(pDoc->pfile1_ == NULL); // we should only get here (now) if not yet saved to disk split_width_d_ = theApp.dffdview_; split_width_a_ = theApp.aerialview_; split_width_c_ = theApp.compview_; // Force colour scheme based on char set (not file extension as we don't have one) scheme_name_ = ""; set_colours(); if (aa->open_max_) { WINDOWPLACEMENT wp; ASSERT(GetFrame() != NULL); GetFrame()->GetWindowPlacement(&wp); wp.showCmd = SW_SHOWMAXIMIZED; GetFrame()->SetWindowPlacement(&wp); } // Set the normal and OEM graphic font if (aa->open_plf_ != NULL) { lf_ = *aa->open_plf_; } if (aa->open_oem_plf_ != NULL) { oem_lf_ = *aa->open_oem_plf_; } } // Make sure that something is displayed in the address area if (!display_.decimal_addr && !display_.hex_addr && !display_.line_nums) { display_.decimal_addr = display_.dec_addr; display_.hex_addr = !display_.dec_addr; } // if (pfl->GetVersion() < 3) // this is not really sufficient if the file is not actually opened since the recent file list gets written back with same DISPLAY value (but new version number) { // In version 2 files there were 3 separate flags (eg when EBCDIC flag on other 2 flags ignored). // Now the 3 bits are used together to indicate char set but we allow for other bit patterns. if (display_.char_set == 2) display_.char_set = CHARSET_ASCII; // ASCII: 0/2 -> 0 else if (display_.char_set > 4) display_.char_set = CHARSET_EBCDIC; // EBCDIC: 4/5/6/7 -> 4 } if (display_.char_set == 7) // unused value display_.char_set = CHARSET_EBCDIC; // EBCDIC: 7 -> 4 // This is just here as a workaround for a small problem with MDItabs - when // the tabs are at the top then the tab bar gets slightly higher when the first // file is opened which mucks up a small part at the top of the MDI area. static bool first_time_here = true; if (first_time_here) { ((CMainFrame *)AfxGetMainWnd())->redraw_background(); first_time_here = false; } if (!display_.edit_char) SetHorzBufferZone(2); // Convert font sizes to logical units { CPoint convert(0, lf_.lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.DPtoLP(&convert); // Get screen font size in logical units lf_.lfHeight = convert.y; } { CPoint convert(0, oem_lf_.lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.DPtoLP(&convert); // Get screen font size in logical units oem_lf_.lfHeight = convert.y; } // This can't be done till document available (ie. not in constructor) if (GetDocument()->read_only()) display_.readonly = TRUE; // Set control bar buttons to display state of current options // load_bitmaps(); CScrView::SetMapMode(MM_TEXT); ASSERT(pfont_ == NULL); pfont_ = new CFont; pfont_->CreateFontIndirect(display_.FontRequired() == FONT_OEM ? &oem_lf_ : &lf_); SetFont(pfont_); // Create brush that is XORed with selection when focus lost. (This // gives a more subtle grey selection) when window does not have focus.) pbrush_ = new CBrush(RGB(192, 192, 192)); SetBrush(pbrush_); // Reopen template view ASSERT(pdfv_ == NULL); switch (split_width_d_) { case 0: // When last open template view was hidden so do nothing split_width_d_ = -1; break; case 2: // Last opened in tab view split_width_d_ = -1; DoDffdTab(); break; default: // Last opened in splitter DoDffdSplit(); break; } // Reopen aerial view ASSERT(pav_ == NULL); switch (split_width_a_) { case 0: // When last open template view was hidden so do nothing split_width_a_ = -1; break; case 2: // Last opened in tab view split_width_a_ = -1; DoAerialTab(false); // no init as that seems to be done by MFC break; default: // Last opened in splitter DoAerialSplit(false); // no init as that seems to be done by MFC break; } // Reopen compare view ASSERT(pcv_ == NULL); switch (split_width_c_) { case 0: // When last open template view was hidden so do nothing split_width_c_ = -1; break; case 2: // Last opened in tab view split_width_c_ = -1; DoCompTab(false); // no WM_INITIALUPDATE needed here (done by MFC) break; default: // Last opened in splitter DoCompSplit(false); // no WM_INITIALUPDATE needed here (done by MFC) break; } CScrView::OnInitialUpdate(); #if 0 if (recent_file_index != -1) SetScroll(CPointAp(0,pfl->scroll_[recent_file_index])); // What's the point of an empty read-only file if (GetDocument()->length() == 0 && !GetDocument()->read_only()) display_.readonly = display_.overtype = FALSE; #endif if (aa->large_cursor_) BlockCaret(); else LineCaret(); if (!display_.overtype || GetDocument()->length() > 0) { CaretMode(); SetSel(addr2pos(start_addr), addr2pos(end_addr)); show_prop(); show_calc(); show_pos(); } ValidateScroll(GetScroll()); // Save nav info in case we need to create a nav pt here nav_start_ = start_addr; nav_end_ = end_addr; nav_scroll_ = (GetScroll().y/line_height_)*rowsize_ - offset_; theApp.navman_.Add("Opened", get_info(), this, nav_start_, nav_end_, nav_scroll_); nav_moves_ = 0; } // OnInitialUpdate // Update our options to the CHexFileList void CHexEditView::StoreOptions() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CHexFileList *pfl = ((CHexEditApp *)AfxGetApp())->GetFileList(); if (GetDocument()->pfile1_ == NULL) return; // Not in the list if there's no file int ii = pfl->GetIndex(GetDocument()->pfile1_->GetFilePath()); if (ii != -1) { // Found in the list so update all the values; WINDOWPLACEMENT wp; ASSERT(GetFrame() != NULL); if (GetFrame()->GetWindowPlacement(&wp)) { pfl->SetData(ii, CHexFileList::CMD, wp.showCmd); pfl->SetData(ii, CHexFileList::TOP, wp.rcNormalPosition.top); pfl->SetData(ii, CHexFileList::LEFT, wp.rcNormalPosition.left); pfl->SetData(ii, CHexFileList::BOTTOM, wp.rcNormalPosition.bottom); pfl->SetData(ii, CHexFileList::RIGHT, wp.rcNormalPosition.right); } else { pfl->SetData(ii, CHexFileList::CMD, SW_SHOWNORMAL); pfl->SetData(ii, CHexFileList::TOP, -30000); pfl->SetData(ii, CHexFileList::LEFT, -30000); pfl->SetData(ii, CHexFileList::BOTTOM, -30000); pfl->SetData(ii, CHexFileList::RIGHT, -30000); } pfl->SetData(ii, CHexFileList::COLUMNS, rowsize_); pfl->SetData(ii, CHexFileList::GROUPING, group_by_); pfl->SetData(ii, CHexFileList::OFFSET, offset_); pfl->SetData(ii, CHexFileList::SCHEME, scheme_name_); pfl->SetData(ii, CHexFileList::FONT, lf_.lfFaceName); pfl->SetData(ii, CHexFileList::HEIGHT, lf_.lfHeight); pfl->SetData(ii, CHexFileList::OEMFONT, oem_lf_.lfFaceName); pfl->SetData(ii, CHexFileList::OEMHEIGHT, oem_lf_.lfHeight); pfl->SetData(ii, CHexFileList::DISPLAY, disp_state_); pfl->SetData(ii, CHexFileList::DOC_FLAGS, GetDocument()->doc_flags()); pfl->SetData(ii, CHexFileList::FORMAT, GetDocument()->GetFormatFileName()); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pfl->SetData(ii, CHexFileList::SELSTART, start_addr); pfl->SetData(ii, CHexFileList::SELEND, end_addr); pfl->SetData(ii, CHexFileList::POS, GetScroll().y); pfl->SetData(ii, CHexFileList::MARK, mark_); std::ostringstream strstr; strstr << hl_set_; pfl->SetData(ii, CHexFileList::HIGHLIGHTS, strstr.str().c_str()); pfl->SetData(ii, CHexFileList::EDIT_TIME, __int64(GetDocument()->edit_time_.elapsed())); pfl->SetData(ii, CHexFileList::VIEW_TIME, __int64(GetDocument()->view_time_.elapsed())); pfl->SetData(ii, CHexFileList::VERT_BUFFER_ZONE, __int64(GetVertBufferZone())); if (pdfv_ == NULL) { pfl->SetData(ii, CHexFileList::DFFDVIEW, "0"); pfl->SetData(ii, CHexFileList::DFFDWIDTHS, ""); } else { int width = 2; // assume tab view used ASSERT(GetFrame()->splitter_.m_hWnd != 0); int snum_d = GetFrame()->splitter_.FindViewColumn(pdfv_->GetSafeHwnd()); int dummy; // ignored since we don't care about the height if (snum_d > -1) { GetFrame()->splitter_.GetColumnInfo(snum_d, width, dummy); if (width < 10) width = 10; // Make sure it is not too narrow and reserve values 0-9 (2 = tab view) } pfl->SetData(ii, CHexFileList::DFFDVIEW, __int64(width)); pfl->SetData(ii, CHexFileList::DFFDWIDTHS, pdfv_->GetColWidths()); } // DFFDVIEW data is now 0 (none), 2 (tab). or 10+ (splitter width) if (pav_ == NULL) { pfl->SetData(ii, CHexFileList::AERIALVIEW, "0"); } else { int width = 2; // assume tab view used ASSERT(GetFrame()->splitter_.m_hWnd != 0); int snum_a = GetFrame()->splitter_.FindViewColumn(pav_->GetSafeHwnd()); int dummy; // ignored since we don't care about the height if (snum_a > -1) { GetFrame()->splitter_.GetColumnInfo(snum_a, width, dummy); if (width < 10) width = 10; // Make sure it is not too narrow and reserve values 0-9 (2 = tab view) } pfl->SetData(ii, CHexFileList::AERIALVIEW, __int64(width)); } // AERIALVIEW data is now 0 (none), 2 (tab). or 10+ (splitter width) if (pav_ != NULL) pav_->StoreOptions(pfl, ii); if (pcv_ == NULL) { pfl->SetData(ii, CHexFileList::COMPVIEW, "0"); } else { int width = 2; // assume tab view used ASSERT(GetFrame()->splitter_.m_hWnd != 0); int snum_c = GetFrame()->splitter_.FindViewColumn(pcv_->GetSafeHwnd()); int dummy; // ignored since we don't care about the height if (snum_c > -1) { GetFrame()->splitter_.GetColumnInfo(snum_c, width, dummy); if (width < 10) width = 10; // Make sure it is not too narrow and reserve values 0-9 (2 = tab view) } pfl->SetData(ii, CHexFileList::COMPVIEW, __int64(width)); pfl->SetData(ii, CHexFileList::COMPFILENAME, GetDocument()->GetCompFileName()); } } } void CHexEditView::SetScheme(const char *name) { if (scheme_name_ == name) return; // no change to the scheme CString previous_name = scheme_name_; scheme_name_ = name; if (set_colours()) { // Scheme changed so save for undo/macros undo_.push_back(view_undo(undo_scheme)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = previous_name; theApp.SaveToMacro(km_scheme, name); } else { // Scheme was not found (presumably in macro playback) ASSERT(theApp.playing_); CString mess; mess.Format("The color scheme \"%s\" was not found.\n", name); AfxMessageBox(mess); theApp.mac_error_ = 1; scheme_name_ = previous_name; } DoInvalidate(); } // When docked vertically the colour scheme drop down combo (ID_SCHEME) becomes a command // button which when clicked invokes this. We just open the Colour page of the Options dialog. void CHexEditView::OnOptScheme() { theApp.display_options(COLOUR_OPTIONS_PAGE, TRUE); } // Handle selection of a new scheme from colour scheme drop down combo (ID_SCHEME). void CHexEditView::OnSelScheme() { CMFCToolBarComboBoxButton * ptbcbb = NULL; // Get and search all ID_SCHEME toolbar controls (there may be more than one on different toolbars) CObList listButtons; if (CMFCToolBar::GetCommandButtons(::IsUs() ? ID_SCHEME_US : ID_SCHEME, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); posCombo != NULL;) { CMFCToolBarComboBoxButton* pp = DYNAMIC_DOWNCAST(CMFCToolBarComboBoxButton, listButtons.GetNext(posCombo)); if (pp != NULL && CMFCToolBar::IsLastCommandFromButton(pp)) // check that this one actually was the one used { ptbcbb = pp; break; } } } if (ptbcbb != NULL) { ASSERT_VALID(ptbcbb); CString name = CString(ptbcbb->GetItem()); // GetItem(-1) will return the selected one if (name.Right(3) == "...") theApp.display_options(COLOUR_OPTIONS_PAGE, TRUE); else if (!name.IsEmpty() && name[0] != '-') SetScheme(name); } } // Update the colour scheme combo (ID_SCHEME). We need to check that the current list of schemes // matches the combo list AND that the scheme used in this view is the selected one. void CHexEditView::OnUpdateScheme(CCmdUI* pCmdUI) { // First check that it is a scheme combo box if (pCmdUI->m_pOther != NULL && pCmdUI->m_pOther->GetDlgCtrlID() == (::IsUs() ? ID_SCHEME_US : ID_SCHEME)) { // Find the owning CMFCToolBarComboBoxButton of the combo box CMFCToolBarComboBoxButton * ptbcbb = NULL; CObList listButtons; if (CMFCToolBar::GetCommandButtons(::IsUs() ? ID_SCHEME_US : ID_SCHEME, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); posCombo != NULL;) { CMFCToolBarComboBoxButton* pp = DYNAMIC_DOWNCAST(CMFCToolBarComboBoxButton, listButtons.GetNext(posCombo)); ASSERT(pp != NULL && pp->GetComboBox() != NULL); if (pp != NULL && pp->GetComboBox() != NULL && pp->GetComboBox()->m_hWnd == pCmdUI->m_pOther->m_hWnd) { ptbcbb = pp; break; } } } // If we found it and it's not in a dropped state if (ptbcbb != NULL && !ptbcbb->GetComboBox()->GetDroppedState()) { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); // Work out the current scheme of the active view and get vector of scheme names std::vector<CString> scheme_names; int current_scheme = -1; // Build list backwards as ComboNeedsUpdate() assumes top of list is at bottom of vector scheme_names.push_back(CString(::IsUs() ? "Modify Colors..." : "Modify Colours...")); scheme_names.push_back(CString('-', 50)); // Add a divider line above the "Modify Colours" line for (int ii = theApp.scheme_.size(); ii > 0; ii--) { scheme_names.push_back(theApp.scheme_[ii-1].name_); if (theApp.scheme_[ii-1].name_ == GetSchemeName()) current_scheme = ii - 1; } // Make sure the list of schemes in the combo matches the current schemes if (mm->ComboNeedsUpdate(scheme_names, ptbcbb->GetComboBox())) { int max_str = 0; // Max width of all the strings added so far CClientDC dc(ptbcbb->GetComboBox()); int nSave = dc.SaveDC(); dc.SelectObject(ptbcbb->GetComboBox()->GetFont()); ptbcbb->RemoveAllItems(); for (std::vector<CString>::reverse_iterator ps = scheme_names.rbegin(); ps != scheme_names.rend(); ++ps) { if ((*ps)[0] != '-') max_str = __max(max_str, dc.GetTextExtent(*ps).cx); // Add the string to the list ptbcbb->AddItem(*ps); } // Add space for margin and possible scrollbar //max_str += dc.GetTextExtent("0").cx + ::GetSystemMetrics(SM_CXVSCROLL); max_str += ::GetSystemMetrics(SM_CXVSCROLL); ptbcbb->GetComboBox()->SetDroppedWidth(__min(max_str, 640)); dc.RestoreDC(nSave); } // Make sure the selected scheme in the combo matches the scheme in use in this view if (ptbcbb->GetCurSel() != current_scheme) { ptbcbb->SelectItem(current_scheme); // We need to invalidate the button so it show the correct scheme CMFCToolBar *ptb = DYNAMIC_DOWNCAST(CMFCToolBar, ptbcbb->GetComboBox()->GetParent()); int idx = ptb->CommandToIndex(::IsUs() ? ID_SCHEME_US : ID_SCHEME); ptb->InvalidateButton(idx); } } } } // Gets all colour info from the app's scheme vector based on the current scheme_name_. // For efficiency it builds the "kala" array which contains a COLORREF for every byte value. BOOL CHexEditView::set_colours() { if (scheme_name_.IsEmpty()) scheme_name_ = theApp.open_scheme_name_; // Use default BOOL retval = TRUE; std::vector<CScheme>::const_iterator ps; ASSERT(theApp.scheme_.size() > 3); // First find the scheme for (ps = theApp.scheme_.begin(); ps != theApp.scheme_.end(); ++ps) { if (ps->name_ == scheme_name_) break; } // If the scheme was not found use the standard one matching selected options if (ps == theApp.scheme_.end()) { // Current scheme name is not found so set to something OK and return error if (display_.char_set == CHARSET_EBCDIC) ps = theApp.scheme_.begin()+3; else if (display_.char_set == CHARSET_OEM) ps = theApp.scheme_.begin()+2; else if (display_.char_set == CHARSET_ANSI) ps = theApp.scheme_.begin()+1; else ps = theApp.scheme_.begin(); scheme_name_ = ps->name_; retval = FALSE; } // Get colours from scheme, where -1 means use default (Automatic) colour bg_col_ = ps->bg_col_ == -1 ? ::GetSysColor(COLOR_WINDOW) : ps->bg_col_; mark_col_ = ps->mark_col_ == -1 ? RGB(224, 224, 224) : ps->mark_col_; hi_col_ = ps->hi_col_ == -1 ? RGB(255, 255, 0) : ps->hi_col_; // yellow bm_col_ = ps->bm_col_ == -1 ? RGB(160, 192, 255) : ps->bm_col_; search_col_ = ps->search_col_ == -1 ? RGB(160, 255, 224) : ps->search_col_; addr_bg_col_ = ps->addr_bg_col_ == -1 ? ::tone_down(::GetSysColor(COLOR_INACTIVEBORDER), bg_col_, 0.5) : ps->addr_bg_col_; // Getting change tracking colour and make a version closer to the background colour in luminance // trk_col_ is used to underline replacements, trk_bg_col_ is used as background for insertions trk_col_ = ps->trk_col_ == -1 ? RGB(255, 128, 0) : ps->trk_col_; // orange-red trk_bg_col_ = ::tone_down(trk_col_, bg_col_); comp_col_ = ps->comp_col_ == -1 ? RGB(255, 0, 128) : ps->comp_col_; // purple comp_bg_col_ = ::tone_down(comp_col_, bg_col_); sector_col_ = ps->sector_col_ == -1 ? RGB(255, 160, 128) : ps->sector_col_; // pinkish orange sector_bg_col_ = ::tone_down(sector_col_, bg_col_); hex_addr_col_ = ps->hex_addr_col_ == -1 ? ::GetSysColor(COLOR_WINDOWTEXT) : ps->hex_addr_col_; dec_addr_col_ = ps->dec_addr_col_ == -1 ? ::GetSysColor(COLOR_WINDOWTEXT) : ps->dec_addr_col_; // Set the default text colour (used for text not specific to a range) if (ps->range_col_.size() > CColourSchemes::INDEX_LAST) text_col_ = ps->range_col_[CColourSchemes::INDEX_LAST]; // was back() else text_col_ = ::GetSysColor(COLOR_WINDOWTEXT); // no ranges at all so use windows default int ii; // Default colours to background (makes unspecified colours invisible) for (ii = 0; ii < 256; ++ii) kala[ii] = bg_col_; ASSERT(ps->range_val_.size() == ps->range_col_.size()); for (ii = ps->range_val_.size(); ii > 0; ii--) { COLORREF colour = (ps->range_col_[ii-1] == -1 ? ::GetSysColor(COLOR_WINDOWTEXT) : ps->range_col_[ii-1]); // Set colour for all in this range for (range_set<int>::const_iterator rr = ps->range_val_[ii-1].begin(); rr != ps->range_val_[ii-1].end(); ++rr) { kala[*rr] = add_contrast(colour, bg_col_); } } // Keep data format view colours in sync if (pdfv_ != NULL) { ASSERT_KINDOF(CDataFormatView, pdfv_); pdfv_->set_colours(); } if (pav_ != NULL) { ASSERT_KINDOF(CAerialView, pav_); GetDocument()->AerialChange(this); } return retval; } void CHexEditView::get_colours(COLORREF *k) { int ii; // First find the scheme in app's list of schemes std::vector<CScheme>::const_iterator ps; for (ps = theApp.scheme_.begin(); ps != theApp.scheme_.end(); ++ps) if (ps->name_ == scheme_name_) break; // If the scheme was not found use the standard one matching selected options if (ps == theApp.scheme_.end()) { // Current scheme name is not found so set to something OK and return error if (display_.char_set == CHARSET_EBCDIC) ps = theApp.scheme_.begin()+3; else if (display_.char_set == CHARSET_OEM) ps = theApp.scheme_.begin()+2; else if (display_.char_set == CHARSET_ANSI) ps = theApp.scheme_.begin()+1; else ps = theApp.scheme_.begin(); scheme_name_ = ps->name_; } // Default colours to background (ie, init. unspecified colours) for (ii = 0; ii < 256; ++ii) k[ii] = bg_col_; ASSERT(ps->range_val_.size() == ps->range_col_.size()); for (ii = ps->range_val_.size(); ii > 0; ii--) { COLORREF colour = (ps->range_col_[ii-1] == -1 ? ::GetSysColor(COLOR_WINDOWTEXT) : ps->range_col_[ii-1]); // Set colour for all in this range for (range_set<int>::const_iterator rr = ps->range_val_[ii-1].begin(); rr != ps->range_val_[ii-1].end(); ++rr) { assert(*rr < 256); k[*rr] = colour; } } } CFont *CHexEditView::SetFont(CFont *ff) { CFont *retval = CScrView::SetFont(ff); // Work out size of printer font based on the new screen font TEXTMETRIC tm; CClientDC dc(this); OnPrepareDC(&dc); // Get screen map mode/font dc.GetTextMetrics(&tm); CPoint convert(0, tm.tmHeight); dc.LPtoDP(&convert); // Convert screen font size to device units fontsize_.Format("%d", int(convert.y*72.0/dc.GetDeviceCaps(LOGPIXELSX) + 0.5)); dc.SetMapMode(print_map_mode_); dc.DPtoLP(&convert); // Get printer font size in logical units print_lfHeight_ = labs(convert.y); return retval; } // functor object used in searching hl_set_.range_. struct segment_compare { bool operator()(const range_set<FILE_ADDRESS>::segment &x, const range_set<FILE_ADDRESS>::segment &y) const { return x.sfirst < y.sfirst; } }; // These update hints are handled: // CRemoveHint: removes undo info (without undoing anything) - for when document saved // CUndoHint: undo changes up to last doc change - called prior to undoing changes // CHexHint: indicates the document has changed (including as a result of doc undo) // CBGSearchHint: indicates a background search on the doc has finished void CHexEditView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { // Check if this is a change caused by a view if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CRemoveHint))) { // Remove undo info (as opposed to actually undoing everything as below) num_entered_ = num_del_ = num_bs_ = 0; // Changes now gone from doc undo CRemoveHint *prh = dynamic_cast<CRemoveHint *>(pHint); std::vector <view_undo, allocator<view_undo> >::iterator pu; for (pu = undo_.end(); pu != undo_.begin(); pu--) if ((pu-1)->utype == undo_change) { // Remove everything up to & including the last doc change undo ASSERT((pu-1)->index == prh->index); undo_.erase(undo_.begin(), pu); break; } } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CUndoHint))) { num_entered_ = num_del_ = num_bs_ = 0; // Undo all view changes up to last doc change (no window invalidate) CUndoHint *puh = dynamic_cast<CUndoHint *>(pHint); // If this is not the view that is undoing if (puh->pview != this) { // Undo all view moves etc up to this change ASSERT(undo_.size() > 0); while (undo_.size() > 0 && undo_.back().utype != undo_change) do_undo(); ASSERT(undo_.size() > 0); ASSERT(undo_.back().index == puh->index); } } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CHexHint))) { // This hint informs the view that the document has changed with // an insertion, deletion or overtype. This may be as a result of a // document undo (if is_undo is true) // Get current selection before recalc_display changes row offsets FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); int prev_addr_width = addr_width_; // Make sure CScrView knows about any size changes if (display_.vert_display) SetTSize(CSizeAp(-1, ((GetDocument()->length() + offset_)/rowsize_ + 1)*3)); // 3 rows of text else SetTSize(CSizeAp(-1, (GetDocument()->length() + offset_)/rowsize_ + 1)); recalc_display(); // file length, hence addr_width_, may have changed CHexHint *phh = dynamic_cast<CHexHint *>(pHint); ASSERT(phh->address >= 0 && phh->address <= GetDocument()->length()); // Is this the start of a doc modification? // (phh->index == -1 if this a continued modification) if (!phh->is_undo && phh->index > -1) { // New change - save mark, caret + change on undo stack // This could be optimized to save mark and caret // only if they are moved by the change. undo_.push_back(view_undo(undo_setmark, phh->ptoo)); undo_.back().address = mark_; undo_.push_back(view_undo(undo_move, TRUE)); undo_.back().address = start_addr | (FILE_ADDRESS(row)<<62); if (start_addr != end_addr) { undo_.push_back(view_undo(undo_sel, TRUE)); undo_.back().address = end_addr; } undo_.push_back(view_undo(undo_change, TRUE)); if (phh->pview == NULL || phh->pview == this) undo_.back().flag = TRUE; else undo_.back().flag = FALSE; #ifndef NDEBUG undo_.back().index = phh->index; #endif } // Move positions of the caret and the mark if address shifted if (!phh->is_undo && (phh->utype == mod_insert || phh->utype == mod_insert_file)) { if (end_addr > phh->address) { end_addr += phh->len; if (start_addr >= phh->address) start_addr += phh->len; SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); } if (mark_ >= phh->address) mark_ += phh->len; } else if (!phh->is_undo && (phh->utype == mod_delback || phh->utype == mod_delforw)) { // Check if current selection and the deletion intersect if (start_addr < phh->address + phh->len && end_addr > phh->address) { if (start_addr >= phh->address) // If sel start within deletion ... start_addr = phh->address; // ... move it to where chars deleted if (end_addr <= phh->address + phh->len) // If sel end within deletion ... end_addr = phh->address; // ... move it to where chars deleted else end_addr -= phh->len; // past deletion so just move it back SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); } else if (phh->address + phh->len <= start_addr) { // Deletion is before selection - just move selection backwards SetSel(addr2pos(start_addr - phh->len, row), addr2pos(end_addr - phh->len, row)); } if (mark_ > phh->address + phh->len) mark_ -= phh->len; else if (mark_ > phh->address) mark_ = phh->address; } // Fix highlights if (phh->utype == mod_insert || phh->utype == mod_insert_file) { range_set<FILE_ADDRESS>::range_t::iterator pp = lower_bound(hl_set_.range_.begin(), hl_set_.range_.end(), range_set<FILE_ADDRESS>::segment(phh->address+1, phh->address+1), segment_compare()); // If there is a highlight before insert posn check if insert is within it if (pp != hl_set_.range_.begin()) { pp --; // If bytes inserted within highlight move end if (pp->slast > phh->address) pp->slast += phh->len; ++pp; } // Move up all the following highlights for ( ; pp != hl_set_.range_.end(); ++pp) { ASSERT(pp->sfirst > phh->address); pp->sfirst += phh->len; pp->slast += phh->len; } } else if (phh->utype == mod_delback || phh->utype == mod_delforw) { // Remove highlights for deleted bytes (if any) hl_set_.erase_range(phh->address, phh->address+phh->len); range_set<FILE_ADDRESS>::range_t::iterator pp = lower_bound(hl_set_.range_.begin(), hl_set_.range_.end(), range_set<FILE_ADDRESS>::segment(phh->address, phh->address), segment_compare()); if (pp != hl_set_.range_.begin() && pp != hl_set_.range_.end()) { range_set<FILE_ADDRESS>::range_t::iterator tmp = pp; tmp--; // If previous abuts current then join them together if (pp->sfirst - phh->len <= tmp->slast) { ASSERT(pp->sfirst - phh->len == tmp->slast); tmp->slast = pp->slast - phh->len; // Remove extra list elt (and leave pp pointing to next) tmp = pp; pp++; hl_set_.range_.erase(tmp); } } // Move all the following highlights down for ( ; pp != hl_set_.range_.end(); ++pp) { ASSERT(pp->sfirst > phh->address); pp->sfirst -= phh->len; pp->slast -= phh->len; } } // Work out the addresses of the first and last line displayed CRect rct; CRectAp clip_rect; // rectangle for calcs/clipping // Calculate where the display in document GetDisplayRect(&rct); // First: get client rectangle clip_rect = ConvertFromDP(rct); // Calculate the address of the first byte of the top row of the // display and the first byte of the row just past bottom FILE_ADDRESS addr_top = (clip_rect.top/line_height_)*rowsize_ - offset_; FILE_ADDRESS addr_bot = (clip_rect.bottom/line_height_ + 1)*rowsize_ - offset_; if (addr_width_ != prev_addr_width) { // Addresses on left side are now different width so redraw everything DoInvalidate(); } else if (phh->address >= addr_bot || (phh->address + /*(signed)*/ phh->len < addr_top && (phh->utype == mod_replace || phh->utype == mod_repback))) { // Do nothing - changes after display OR before but with no address shift ; /* null statement */ } else if (phh->address < addr_top + rowsize_ && phh->utype != mod_replace && phh->utype != mod_repback) { // Whole display changes, due to address shift DoInvalidate(); } else if (phh->utype == mod_replace || phh->utype == mod_repback) { // Replace starting within display - just invalidate changed area invalidate_addr_range(phh->address, phh->address + (phh->len<1?1:phh->len)); } else if (GetDocument()->length() + ((phh->utype == mod_insert || phh->utype == mod_insert_file) ? -phh->len : +phh->len) < addr_bot) { // Insertion/deletion and previous end was within display // Just invalidate from address to bottom of display CRectAp inv(0, ((phh->address + offset_)/rowsize_) * line_height_, char_pos(rowsize_), ((addr_bot + offset_)/rowsize_) * line_height_); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); } else { // Must be insert/delete starting within the displayed area // - invalidate from first changed line to end of display invalidate_addr_range(phh->address, addr_bot); } // Remove doc change undo from undo array & do any assoc undos if (phh->is_undo && phh->pview != this) { ASSERT(undo_.size() > 0); if (undo_.size() > 0) { BOOL ptoo = undo_.back().previous_too; undo_.pop_back(); // Change already made to doc // while (ptoo) // Note changes made to allow for "previous_too" file changes while (ptoo && undo_.back().utype != undo_change) { if (undo_.size() == 0) break; // Undo anything associated to change to doc ptoo = undo_.back().previous_too; do_undo(); } } } show_prop(); show_calc(); // If mark moved and current search is relative to mark then restart bg search if (theApp.align_rel_ && mark_ != GetDocument()->base_addr_) { GetDocument()->StopSearch(); GetDocument()->base_addr_ = GetSearchBase(); GetDocument()->StartSearch(); } } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CBGSearchHint))) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CBGSearchHint *ph = dynamic_cast<CBGSearchHint *>(pHint); if (ph->finished_ == -1) { // Occurrences in area ph->start_ to ph->end_ have been added or removed // probably due to bytes being inserted or deleted at caret. // Get latest set of search occurrences ValidateScroll(GetScroll()); // Redraw area where occurrences added/removed invalidate_addr_range(ph->start_, ph->end_ + search_length_ - 1); } else if (ph->finished_) { // Background search finished // Get the display area occurrences using ValidateScroll ValidateScroll(GetScroll()); // Invalidate any areas where new search string was found std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp, pend; for (pp = search_pair_.begin(), pend = search_pair_.end(); pp != pend; ++pp) invalidate_addr_range(pp->first, pp->second); } else { // Remove all displayed search strings (but save a copy in tmp for invalidating) std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > tmp; tmp.swap(search_pair_); // Save search_pair_ in tmp (and make it empty) // Invalidate any areas where search string is currently displayed std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp, pend; for (pp = tmp.begin(), pend = tmp.end(); pp != pend; ++pp) invalidate_addr_range(pp->first, pp->second); } } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CDFFDHint))) { // Nothing required (yet?) } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CSaveStateHint))) { } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CRestoreStateHint))) { } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CBookmarkHint))) { CBookmarkHint *pbmh = dynamic_cast<CBookmarkHint *>(pHint); invalidate_addr_range(pbmh->addr_, pbmh->addr_+1); } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CTrackHint))) { if (!display_.hide_replace || !display_.hide_insert || !display_.hide_delete) { CTrackHint *pth = dynamic_cast<CTrackHint *>(pHint); invalidate_addr_range(pth->start_, pth->end_); } } else { recalc_display(); CScrView::OnUpdate(pSender, lHint, pHint); } } void CHexEditView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView) { if (bActivate) GetDocument()->SearchThreadPriority(THREAD_PRIORITY_LOWEST); else GetDocument()->SearchThreadPriority(THREAD_PRIORITY_IDLE); CScrView::OnActivateView(bActivate, pActivateView, pDeactiveView); } // Checks if the document (file) or view (window) is read only. // If the document is read only it just displays a message and returns. // If the view is read only it gives the user the option to turn off RO. // Returns TRUE if the file/view is read only, FALSE if modifiable. BOOL CHexEditView::check_ro(const char *desc) { CString ss; FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (display_.readonly && GetDocument()->read_only()) { ss.Format("This file cannot be modified.\r" "(You can't %s.)", desc); AfxMessageBox(ss); CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); aa->mac_error_ = 10; return TRUE; } else if (pdfv_ != NULL && pdfv_->ReadOnly(start_addr, end_addr)) { ss.Format("The selection contains one or\r" "more read-only template fields,\r" "hence you can't %s.", desc); // AfxMessageBox(ss, MB_OK|MB_HELP, HID_DFFD_RO); AfxMessageBox(ss, MB_OK); theApp.mac_error_ = 10; return TRUE; } else if (display_.readonly) { ss.Format("You can't %s since this window is read only.\r" "Do you want to turn off read only mode?", desc); if (AfxMessageBox(ss, MB_OKCANCEL) != IDOK) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); aa->mac_error_ = 10; return TRUE; } else allow_mods(); } return FALSE; } // Check if we have had read errors on the device and warn the user (but only once) // Note that this will warn once per view not once per file but we don't care too much. void CHexEditView::check_error() { if (GetDocument()->HasSectorErrors()) { // turn on sector display so user can see which sector(s) had errors display_.borders = 1; if (!errors_mentioned_) { AfxMessageBox("Read error(s) were reported by this device", MB_OK|MB_ICONSTOP); errors_mentioned_ = true; } } } ///////////////////////////////////////////////////////////////////////////// // CHexEditView drawing // There are several different coordinate systems used. // - device: pixels on the physical device (screen or printer) // - logical: units set by windows mapping mode // for screen MM_TEXT is used (= device coords) with Y axis down // for printer MM_HIMETRIC is used with Y axis up // - normalised: this is the same as logical but the sign is changed so // that Y axis is always down (and X axis is always right) // in order to simplify comparisons etc // - document: this is the normalised logical coord system with the origin at // the very top of the document. // Note that different mapping modes are used for screen and printer. // MM_TEXT is used for screen otherwise scrolling becomes slightly // out of whack resulting in missing or extra lines of pixels. // MM_TEXT cannot be used for the printer as it comes out tiny on lasers. // void CHexEditView::OnDraw(CDC* pDC) { if (pfont_ == NULL) return; CHexEditDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); /* This was to allow print preview to be grey when active printer was * monochrome, but somehow it's already OK. bool preview = pDC->GetDeviceCaps(NUMCOLORS) == 2 && pDC->m_hDC != pDC->m_hAttribDC; */ //CBrush backBrush; //backBrush.CreateSolidBrush(bg_col_); //backBrush.UnrealizeObject(); pDC->SetBkMode(TRANSPARENT); // Are we in overtype mode and file is empty? if (display_.overtype && pDoc->length() == 0) { // Get the reason that there's no data from the document & display it CRect cli; GetDisplayRect(&cli); pDC->DPtoLP(&cli); if (pDC->IsPrinting()) { if (cli.bottom < 0) cli.top = -2 * print_text_height_; else cli.top = 2 * print_text_height_; } const char *mm = pDoc->why0(); pDC->SetTextColor(GetDefaultTextCol()); pDC->DrawText(mm, -1, &cli, DT_CENTER | DT_TOP | DT_NOPREFIX | DT_SINGLELINE); //::TextOutW(pDC->GetSafeHdc(), 0, 0, L"TEST", 4); // this works! return; } const char *hex; if (theApp.hex_ucase_) hex = "0123456789ABCDEF?"; else hex = "0123456789abcdef?"; CRectAp doc_rect; // Display area relative to whole document CRect norm_rect; // Display area (norm. logical coords) // Note that norm_rect may extend slightly outside the physical view area, for example, // if only half a line is visible at the top of the screen. // These are the first and last "virtual" addresses of the top and (one past) the end // of the addresses within norm_rect. Note that these are not necessarilly the first // and last real addresses. For example, if offset_ != 0 and at the top of file then // first_virt will be -ve. Similarly the file may not even be as long as last_virt. FILE_ADDRESS first_virt, last_virt; FILE_ADDRESS first_line; // First line that needs displaying FILE_ADDRESS last_line; // One past last line to display FILE_ADDRESS first_addr = 0; // First address to actually display FILE_ADDRESS last_addr = pDoc->length(); // One past last address actually displayed FILE_ADDRESS line_inc; // 1 or -1 depending on draw dirn (up/down) CSize rect_inc; // How much to move norm_rect each time FILE_ADDRESS start_addr, end_addr; // Address of current selection bool neg_x(false), neg_y(false); // Does map mode have -ve to left or down bool has_focus; // Does this window have focus? int bitspixel = pDC->GetDeviceCaps(BITSPIXEL); if (bitspixel > 24) bitspixel = 24; // 32 is really only 24 bits of colour long num_colours = 1L << (bitspixel*pDC->GetDeviceCaps(PLANES)); // CBCGDrawManager bcgdm(*pDC); int line_height, char_width, char_width_w; // Text sizes ASSERT(offset_ >= 0 && offset_ < rowsize_); if (offset_ >= rowsize_) offset_ = 0; // xxx kludge - need to track down why offset is wrong ASSERT(rowsize_ > 0 && rowsize_ <= max_buf); ASSERT(group_by_ > 0); if (pDC->IsPrinting()) { // Work out "client" rect of a printer page norm_rect.top = norm_rect.left = 0; norm_rect.bottom = pDC->GetDeviceCaps(VERTRES); norm_rect.right = pDC->GetDeviceCaps(HORZRES); // Convert to logical units but with origin at top left of window // Note we can't use ConvertFromDP here as this is for printer not screen pDC->DPtoLP(&norm_rect); if (norm_rect.right < 0) { neg_x = true; norm_rect.right = -norm_rect.right; } if (norm_rect.bottom < 0) { neg_y = true; norm_rect.bottom = -norm_rect.bottom; } // Text-only printer drivers under Win98 return number of text lines not pixels for VERTRES if (norm_rect.bottom < norm_rect.right/5) norm_rect.bottom *= print_text_height_; // Since there is no translation (only scaling) between device and logical coords origin does not change ASSERT(norm_rect.top == 0 && norm_rect.left == 0); // Work out which part of document to display if (display_.vert_display) doc_rect = CRectAp(norm_rect) + CSizeAp(-margin_size_.cx, curpage_ * FILE_ADDRESS(lines_per_page_) * print_text_height_*3 - margin_size_.cy); else doc_rect = CRectAp(norm_rect) + CSizeAp(-margin_size_.cx, curpage_ * FILE_ADDRESS(lines_per_page_) * print_text_height_ - margin_size_.cy); line_height = print_text_height_; if (display_.vert_display) line_height *= 3; char_width = print_text_width_; char_width_w = print_text_width_w_; } else { has_focus = (GetFocus() == this); HideCaret(); neg_x = negx(); neg_y = negy(); // Get display rect in logical units but with origin at top left of display area in window CRect rct; GetDisplayRect(&rct); doc_rect = ConvertFromDP(rct); // Display = client rectangle translated to posn in document // norm_rect = doc_rect - GetScroll(); norm_rect.left = doc_rect.left - GetScroll().x + bdr_left_; norm_rect.right = doc_rect.right - GetScroll().x + bdr_left_; norm_rect.top = int(doc_rect.top - GetScroll().y) + bdr_top_; norm_rect.bottom = int(doc_rect.bottom - GetScroll().y) + bdr_top_; // Get the current selection so that we can display it in reverse video GetSelAddr(start_addr, end_addr); line_height = line_height_; char_width = text_width_; char_width_w = text_width_w_; } // Get range of addresses that are visible the in window (overridden for printing below) first_virt = (doc_rect.top/line_height) * rowsize_ - offset_; last_virt = (doc_rect.bottom/line_height + 1) * rowsize_ - offset_; // Work out which lines could possibly be in the display area if (pDC->IsPrinting() && print_sel_) { GetSelAddr(first_addr, last_addr); // Start drawing from start of selection (+ allow for subsequent pages) first_line = (first_addr+offset_)/rowsize_ + curpage_*FILE_ADDRESS(lines_per_page_); last_line = first_line + lines_per_page_; // Also if the selection ends on this page set the end if (last_line > (last_addr - 1 + offset_)/rowsize_ + 1) last_line = (last_addr - 1 + offset_)/rowsize_ + 1; line_inc = 1L; rect_inc = CSize(0, line_height); first_virt = first_line * rowsize_ - offset_; last_virt = first_virt + lines_per_page_*rowsize_; // Things are a bit different if merging duplicate lines if (dup_lines_) { if (curpage_ == 0) print_next_line_ = first_line; else first_line = print_next_line_; // We don't know what the last line will be so set to end of selection last_line = (last_addr - 1 + offset_)/rowsize_ + 1; last_virt = last_line * rowsize_ - offset_; } /* Work out where to display the 1st line */ norm_rect.top += margin_size_.cy; norm_rect.bottom = norm_rect.top + line_height; norm_rect.left -= doc_rect.left; doc_rect.top = first_line * line_height - margin_size_.cy; doc_rect.bottom = doc_rect.top + lines_per_page_*print_text_height_; } else if (pDC->IsPrinting()) { // Draw just the lines on this page first_line = curpage_ * FILE_ADDRESS(lines_per_page_); last_line = first_line + lines_per_page_; first_addr = max(0, first_line*rowsize_ - offset_); last_addr = min(pDoc->length(), last_line*rowsize_ - offset_); line_inc = 1L; rect_inc = CSize(0, line_height); first_virt = first_line * rowsize_ - offset_; last_virt = first_virt + lines_per_page_*rowsize_; /* Work out where to display the 1st line */ // norm_rect.top -= int(doc_rect.top - first_line*line_height); norm_rect.top += margin_size_.cy; norm_rect.bottom = norm_rect.top + line_height; // norm_rect.left += margin_size_.cx - doc_rect.left; norm_rect.left -= doc_rect.left; } else if (ScrollUp()) { // Draw from bottom of window up since we're scrolling up (looks better) first_line = doc_rect.bottom/line_height; last_line = doc_rect.top/line_height - 1; line_inc = -1L; rect_inc = CSize(0, -line_height); /* Work out where to display the 1st line */ norm_rect.top -= int(doc_rect.top - first_line*line_height); norm_rect.bottom = norm_rect.top + line_height; norm_rect.left -= doc_rect.left; } else { // Draw from top of window down first_line = doc_rect.top/line_height; last_line = doc_rect.bottom/line_height + 1; line_inc = 1L; rect_inc = CSize(0, line_height); /* Work out where to display the 1st line */ norm_rect.top -= int(doc_rect.top - first_line*line_height); norm_rect.bottom = norm_rect.top + line_height; norm_rect.left -= doc_rect.left; } if (first_addr < first_virt) first_addr = first_virt; if (last_addr > last_virt) last_addr = last_virt; // These are for drawing things on the screen CPoint pt; // moved this here to avoid a spurious compiler error C2362 CPen pen1(PS_SOLID, 0, same_hue(sector_col_, 100, 30)); // dark sector_col_ CPen pen2(PS_SOLID, 0, same_hue(addr_bg_col_, 100, 30)); // dark addr_bg_col_ CPen *psaved_pen; CBrush brush(sector_col_); // Skip background drawing in this case because it's too hard. // Note that this goto greatly simplifies the tests below. if (pDC->IsPrinting() && print_sel_ && dup_lines_) goto end_of_background_drawing; // Preread device blocks so we know if there are bad sectors if (GetDocument()->IsDevice()) { // As long as we ensure that the CFileNC buffer is at least as big as the display area (the // distance from start of top line to end of bottom line) then this should read all // sectors to be dipslayed. unsigned char cc; TRACE("---- Display size is %ld\n", long(last_addr - first_addr)); pDoc->GetData(&cc, 1, (first_addr + last_addr)/2); } if (display_.borders) psaved_pen = pDC->SelectObject(&pen1); else psaved_pen = pDC->SelectObject(&pen2); // Column related screen stuff (ruler, vertical lines etc) if (!pDC->IsPrinting()) { ASSERT(!neg_y && !neg_x); // This should be true when drawing on screen (uses MM_TEXT) // Vert. line between address and hex areas pt.y = bdr_top_ - 4; pt.x = addr_width_*char_width - char_width - doc_rect.left + bdr_left_; pDC->MoveTo(pt); pt.y = 30000; pDC->LineTo(pt); if (!display_.vert_display && display_.hex_area) { // Vert line to right of hex area pt.y = bdr_top_ - 4; pt.x = char_pos(0, char_width) - char_width_w/2 - doc_rect.left + bdr_left_; pDC->MoveTo(pt); pt.y = 30000; pDC->LineTo(pt); } if (display_.vert_display || display_.char_area) { // Vert line to right of char area pt.y = bdr_top_ - 4; pt.x = char_pos(rowsize_ - 1, char_width, char_width_w) + (3*char_width_w)/2 - doc_rect.left + bdr_left_; pDC->MoveTo(pt); pt.y = 30000; pDC->LineTo(pt); } if (theApp.ruler_) { int horz = bdr_left_ - GetScroll().x; // Horiz. offset to window posn of left side ASSERT(bdr_top_ > 0); // Draw horiz line under ruler pt.y = bdr_top_ - 4; pt.x = addr_width_*char_width - char_width - doc_rect.left + bdr_left_; pDC->MoveTo(pt); pt.x = 30000; pDC->LineTo(pt); // Draw ticks using hex offsets for major ticks (if using hex addresses) or // decimal offsets (if using decimal addresses/line numbers and/or hex addresses) int major = 1; if (display_.decimal_addr || display_.line_nums) major = theApp.ruler_dec_ticks_; // decimal ruler or both hex and decimal else major = theApp.ruler_hex_ticks_; // only showing hex ruler // Hex area ticks if (!display_.vert_display && display_.hex_area) for (int column = 1; column < rowsize_; ++column) { if ((!display_.decimal_addr && !display_.line_nums && theApp.ruler_hex_nums_ > 1 && column%theApp.ruler_hex_nums_ == 0) || ((display_.decimal_addr || display_.line_nums) && theApp.ruler_dec_nums_ > 1 && column%theApp.ruler_dec_nums_ == 0) ) continue; // skip when displaying a number at this posn pt.y = bdr_top_ - 5; pt.x = hex_pos(column) - char_width/2 + horz; if (column%group_by_ == 0) pt.x -= char_width/2; pDC->MoveTo(pt); pt.y -= (column%major) ? 3 : 7; pDC->LineTo(pt); } // Char area or stacked display ticks if (display_.vert_display || display_.char_area) for (int column = 0; column <= rowsize_; ++column) { if ((!display_.decimal_addr && !display_.line_nums && theApp.ruler_hex_nums_ > 1 && column%theApp.ruler_hex_nums_ == 0) || ((display_.decimal_addr || display_.line_nums) && theApp.ruler_dec_nums_ > 1 && column%theApp.ruler_dec_nums_ == 0) ) continue; // skip when displaying a number at this posn pt.y = bdr_top_ - 5; pt.x = char_pos(column) + horz; if (display_.vert_display && column%group_by_ == 0) if (column == rowsize_) // skip last one break; else pt.x -= char_width/2; pDC->MoveTo(pt); pt.y -= (column%major) ? 2 : 5; pDC->LineTo(pt); } // Draw numbers in the ruler area // Note that if we are displaying hex and decimal addresses we show 2 rows // - hex offsets at top (then after moving vert down) decimal offsets int vert = 0; // Screen y pixel to the row of nos at int hicol = -1; // Column with cursor is to be highlighted bool hl_box = true; // Highlight mouse/cursor in the ruler using box around col number (or just a small line) if (display_.hex_addr && theApp.ruler_hex_nums_ > 1) hl_box = false; if ((display_.decimal_addr || display_.line_nums) && theApp.ruler_dec_nums_ > 1) hl_box = false; CRect hi_rect(-1, 0, -1, bdr_top_ - 4); if (!hl_box) hi_rect.top = hi_rect.bottom - 2; // A flat rect just inside the ruler // Current caret position shown in the ruler if (theApp.hl_caret_ && !mouse_down_) { // Do highlighting with a background rectangle in ruler hicol = int((start_addr + offset_)%rowsize_); CBrush * psaved_brush = pDC->SelectObject(&brush); CPen * psaved_pen = pDC->SelectObject(&pen1); if (!display_.vert_display && display_.hex_area) { hi_rect.left = hex_pos(hicol) + horz; hi_rect.right = hi_rect.left + text_width_*2 + 1; pDC->Rectangle(&hi_rect); } if (display_.vert_display || display_.char_area) { hi_rect.left = char_pos(hicol) + horz; hi_rect.right = hi_rect.left + text_width_ + 1; pDC->Rectangle(&hi_rect); } (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } // Current mouse position in the ruler if (theApp.hl_mouse_ && mouse_addr_ > -1) { int mousecol = int((mouse_addr_ + offset_)%rowsize_); // Mouse column to be highlighted CBrush * psaved_brush = pDC->SelectObject(CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH))); CPen * psaved_pen = pDC->SelectObject(&pen1); if (!display_.vert_display && display_.hex_area) { hi_rect.left = hex_pos(mousecol) + horz; hi_rect.right = hi_rect.left + text_width_*2 + 1; pDC->Rectangle(&hi_rect); } if (display_.vert_display || display_.char_area) { hi_rect.left = char_pos(mousecol) + horz; hi_rect.right = hi_rect.left + text_width_ + 1; pDC->Rectangle(&hi_rect); } (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } // Get display rect for clipping at right and left CRect cli; GetDisplayRect(&cli); // Show hex offsets in the top border (ruler) if (display_.hex_addr) { bool between = theApp.ruler_hex_nums_ > 1; // Only display numbers above cols if displaying for every column // Do hex numbers in ruler CRect rect(-1, vert, -1, vert + text_height_ + 1); CString ss; pDC->SetTextColor(GetHexAddrCol()); // Colour of hex addresses // Show hex offsets above hex area if (!display_.vert_display && display_.hex_area) for (int column = 0; column < rowsize_; ++column) { if (between && display_.addrbase1 && column == 0) continue; // usee doesn't like seeing zero if (column%theApp.ruler_hex_nums_ != 0) continue; rect.left = hex_pos(column) + horz; if (between) { rect.left -= char_width; if (column > 0 && column%group_by_ == 0) rect.left -= char_width/2; } if (rect.left < cli.left) continue; if (rect.left > cli.right) break; rect.right = rect.left + text_width_ + text_width_; if (!between) { // Draw 2 digit number above every column ss.Format(theApp.hex_ucase_ ? "%02X" : "%02x", (column + display_.addrbase1)%256); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else if (column%16 == 0 && theApp.ruler_hex_nums_ > 3) { // Draw 2 digit numbers to mark end of 16 columns rect.left -= (char_width+1)/2; ss.Format(theApp.hex_ucase_ ? "%02X" : "%02x", column%256); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else { // Draw single digit number in between columns ss.Format(theApp.hex_ucase_ ? "%1X" : "%1x", column%16); pDC->DrawText(ss, &rect, DT_BOTTOM | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } } // Show hex offsets above char area or stacked display if (display_.vert_display || display_.char_area) for (int column = 0; column < rowsize_; ++column) { if (between && display_.addrbase1 && column == 0) continue; // user doesn't like seeing zero if (column%theApp.ruler_hex_nums_ != 0) continue; rect.left = char_pos(column) + horz; if (between) { if (display_.vert_display && column > 0 && column%group_by_ == 0) rect.left -= char_width; else rect.left -= char_width/2; } if (rect.left < cli.left) continue; if (rect.left > cli.right) break; rect.right = rect.left + text_width_ + text_width_; if (!between) { ss.Format(theApp.hex_ucase_ ? "%1X" : "%1x", (column + display_.addrbase1)%16); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else if (column%16 == 0 && theApp.ruler_hex_nums_ > 3) { rect.left -= (char_width+1)/2; ss.Format(theApp.hex_ucase_ ? "%02X" : "%02x", column%256); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else { ss.Format(theApp.hex_ucase_ ? "%1X" : "%1x", column%16); pDC->DrawText(ss, &rect, DT_BOTTOM | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } } vert += text_height_; // Move down for anything to be drawn underneath } // Show decimal offsets in the ruler if (display_.decimal_addr || display_.line_nums) { bool between = theApp.ruler_dec_nums_ > 1; // Only display numbers above cols if displaying for every column CRect rect(-1, vert, -1, vert + text_height_ + 1); CString ss; pDC->SetTextColor(GetDecAddrCol()); // Colour of dec addresses // Decimal offsets above hex area if (!display_.vert_display && display_.hex_area) for (int column = 0; column < rowsize_; ++column) { if (between && display_.addrbase1 && column == 0) continue; // user doesn't like seeing zero if (column%theApp.ruler_dec_nums_ != 0) continue; rect.left = hex_pos(column) + horz; if (between) { rect.left -= char_width; if (column > 0 && column%group_by_ == 0) rect.left -= char_width/2; } if (rect.left < cli.left) continue; if (rect.left > cli.right) break; rect.right = rect.left + text_width_ + text_width_; if (!between) { ss.Format("%02d", (column + display_.addrbase1)%100); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else if (column%10 == 0 && theApp.ruler_dec_nums_ > 4) { rect.left -= (char_width+1)/2; ss.Format("%02d", column%100); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else { ss.Format("%1d", column%10); pDC->DrawText(ss, &rect, DT_BOTTOM | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } } // Decimal offsets above char area or stacked display if (display_.vert_display || display_.char_area) for (int column = 0; column < rowsize_; ++column) { if (between && display_.addrbase1 && column == 0) continue; // user doesn't like seeing zero if (column%theApp.ruler_dec_nums_ != 0) continue; rect.left = char_pos(column) + horz; if (between) { if (display_.vert_display && column > 0 && column%group_by_ == 0) rect.left -= char_width; else rect.left -= char_width/2; } if (rect.left < cli.left) continue; if (rect.left > cli.right) break; rect.right = rect.left + text_width_ + text_width_; if (!between) { ss.Format("%1d", (column + display_.addrbase1)%10); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else if (column%10 == 0 && theApp.ruler_dec_nums_ > 4) { // If displaying nums every 5 or 10 then display 2 digits fo tens column rect.left -= (char_width+1)/2; ss.Format("%02d", column%100); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else { // Display single dit between columns ss.Format("%1d", column%10); pDC->DrawText(ss, &rect, DT_BOTTOM | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } } vert += text_height_; // Move down for anything to be drawn underneath (currently nothing) } #ifdef RULER_ADJUST draw_adjusters(pDC); // Draw adjustment controls in the ruler #endif } // end ruler drawing } // Mask out the ruler so we don't get top of topmost line drawn into it. // Doing it this way allows the address of the top line to be drawn // higher (ie into ruler area) without being clipped. // Note that we currently only use bdr_top_ (for the ruler) but if // other borders are used similarly we would need to clip them too. // Note: This needs to be done after drawing the ruler. #ifndef TEST_CLIPPING if (!pDC->IsPrinting()) { CRect rct; GetDisplayRect(&rct); rct.bottom = rct.top; rct.top = 0; rct.left = (addr_width_ - 1)*char_width + norm_rect.left + bdr_left_; pDC->ExcludeClipRect(&rct); } #endif // Note: We draw bad sectors, change-tracking deletions, etc first // as they are always drawn from the top of screen (or page) downwards. // This is so the user is less likely to notice the wrong direction. // (Major things are drawn from the bottom up when scrolling backwards.) // First decide is we need to draw sector borders int seclen = pDoc->GetSectorSize(); bool draw_borders = pDoc->pfile1_ != NULL && display_.borders && seclen > 0; if (pDC->IsPrinting() && !theApp.print_sectors_) draw_borders = false; if (draw_borders) { ASSERT(seclen > 0); bool prev_bad = first_addr == 0; // don't display sector separator above top of file for (FILE_ADDRESS sector = (first_addr/seclen)*seclen; sector < last_addr; sector += seclen) { // Note that "sector" is the address of the start of the sector if (pDoc->HasSectorErrors() && pDoc->SectorError(sector/seclen) != NO_ERROR) { // Draw colour behind the bytes to indicate there is a problem with this sector draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, sector_bg_col_, max(sector, first_addr), min(sector + seclen, last_addr)); prev_bad = true; } else if (!prev_bad && sector >= first_addr && sector < last_addr) { // Just draw a line above the top of the sector if (!display_.vert_display && display_.hex_area) { // Hex area pt.y = int(((sector + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_); // This is just above the first byte of the sector if (neg_y) pt.y = -pt.y; //pt.x = hex_pos(rowsize_ - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; pt.x = char_pos(0, char_width) - char_width/2 - doc_rect.left + bdr_left_; // Right side of hex area if (neg_x) pt.x = - pt.x; pDC->MoveTo(pt); pt.x = hex_pos(int((sector + offset_)%rowsize_), char_width) - char_width/2 - doc_rect.left + bdr_left_; // This is just to left of first byte of sector if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); if ((sector + offset_)%rowsize_ != 0) { // Draw on line below and vertical bit too pt.y = int(((sector + offset_)/rowsize_ + 1) * line_height - doc_rect.top + bdr_top_); if (neg_y) pt.y = -pt.y; pDC->LineTo(pt); pt.x = hex_pos(0, char_width) - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); } pt.x = addr_width_*char_width - char_width - doc_rect.left + bdr_left_; pDC->LineTo(pt); } if (display_.vert_display || display_.char_area) { // Do char area (or stacked mode) pt.y = int(((sector + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_); if (neg_y) pt.y = -pt.y; //pt.x = char_pos(rowsize_ - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; pt.x = char_pos(rowsize_ - 1, char_width, char_width_w) + (3*char_width_w)/2 - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->MoveTo(pt); pt.x = char_pos(int((sector + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); if ((sector + offset_)%rowsize_ != 0) { // Draw on line below and vertical bit too pt.y = int(((sector + offset_)/rowsize_ + 1) * line_height - doc_rect.top + bdr_top_); if (neg_y) pt.y = -pt.y; pDC->LineTo(pt); pt.x = char_pos(0, char_width, char_width_w) - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); } // Fill in a little bit to join with the vertical line on the left if (display_.vert_display || !display_.hex_area) pt.x = addr_width_*char_width - char_width - doc_rect.left + bdr_left_; else pt.x = char_pos(0, char_width, char_width_w) - char_width_w/2 - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); } // Draw a little bit more in the gap between address area and left side pt.x = addr_width_*char_width - char_width/2 - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->MoveTo(pt); pt.x = addr_width_*char_width + char_width/8 - // Extra char_width/8 due to one pixel out on screen (and many on printer) doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); } else { prev_bad = false; // don't draw border at bottom of previous block fill (just remember this one was OK) } } } pDC->SelectObject(psaved_pen); // restore pen after drawing borders etc // Make sure background compare is on and finished and also print_compare_ is on (if printing) if (!((GetDocument()->CompareDifferences() <= 0) || pDC->IsPrinting() && !theApp.print_compare_)) { // Draw differences with compare file CTime tnew = GetDocument()->ResultTime(0); // time of most recent comparison // xxx TBD make "number of minutes before it completely disappears" into a parameter CTime tearliest = tnew - CTimeSpan(0, 0, 15, 0); // older diffs are shown in lighter shades for (int rr = GetDocument()->ResultCount() - 1; rr >= 0; rr--) { COLORREF col, col2; // colours for replace (underline) + delete, and also for inserts CTime tt = GetDocument()->ResultTime(rr); if (tt < tearliest) continue; // Tone down based on how long agoo the change was made (up to 0.8 since toning down more is not that visible) double amt = 0.8 - double((tt - tearliest).GetTotalSeconds()) / double((tnew - tearliest).GetTotalSeconds()); col = ::tone_down(comp_col_, bg_col_, amt); col2 = ::tone_down(comp_bg_col_, bg_col_, amt); for (int dd = GetDocument()->FirstDiffAt(false, rr, first_virt); dd < GetDocument()->CompareDifferences(rr); ++dd) { FILE_ADDRESS addr; int len; GetDocument()->GetOrigDiff(rr, dd, addr, len); if (addr + len < first_virt) continue; // before top of window else if (addr >= last_virt) break; // after end of window draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, col, max(addr, first_addr), min(addr+len, last_addr), false, // overwrite (not merge) since mutiple changes at the same address really mess up the colours (pDC->IsPrinting() ? print_text_height_ : text_height_)/8); } } } // Draw deletion marks always from top (shouldn't be too visible) if (!(display_.hide_delete || pDC->IsPrinting() && !theApp.print_change_)) { COLORREF prev_col = pDC->SetTextColor(bg_col_); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > *ppr = GetDocument()->Deletions(); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp; for (pp = ppr->begin(); pp != ppr->end(); ++pp) { // Check if its before or after the display area if (pp->first < first_virt) continue; else if (pp->first > last_virt) break; CRect draw_rect; draw_rect.top = int(((pp->first + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_); draw_rect.bottom = draw_rect.top + line_height; if (neg_y) { draw_rect.top = -draw_rect.top; draw_rect.bottom = -draw_rect.bottom; } if (!display_.vert_display && display_.hex_area) { draw_rect.left = hex_pos(int((pp->first + offset_)%rowsize_), char_width) - char_width - doc_rect.left + bdr_left_; draw_rect.right = draw_rect.left + char_width; if (neg_x) { draw_rect.left = -draw_rect.left; draw_rect.right = -draw_rect.right; } pDC->FillSolidRect(&draw_rect, trk_col_); char cc = (pp->second > 9 || !display_.delete_count) ? '*' : '0' + char(pp->second); pDC->DrawText(&cc, 1, &draw_rect, DT_CENTER | DT_TOP | DT_NOPREFIX | DT_SINGLELINE); } if (display_.vert_display || display_.char_area) { draw_rect.left = char_pos(int((pp->first + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_ - 2; draw_rect.right = draw_rect.left + char_width_w/5+1; if (neg_x) { draw_rect.left = -draw_rect.left; draw_rect.right = -draw_rect.right; } pDC->FillSolidRect(&draw_rect, trk_col_); } } pDC->SetTextColor(prev_col); // restore text colour } // Now draw other change tracking stuff top down OR bottom up depending on ScrollUp() if (!pDC->IsPrinting() && ScrollUp()) { // Draw change tracking from bottom up if (!display_.hide_replace) { std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > *ppr = GetDocument()->Replacements(); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::reverse_iterator pp; for (pp = ppr->rbegin(); pp != ppr->rend(); ++pp) if (pp->first < last_virt) break; for ( ; pp != ppr->rend(); ++pp) { if (pp->first + pp->second <= first_virt) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, trk_col_, max(pp->first, first_addr), min(pp->first + pp->second, last_addr), true, (pDC->IsPrinting() ? print_text_height_ : text_height_)/8); } } if (!display_.hide_insert) { std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > *ppr = GetDocument()->Insertions(); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::reverse_iterator pp; for (pp = ppr->rbegin(); pp != ppr->rend(); ++pp) if (pp->first < last_virt) break; for ( ; pp != ppr->rend(); ++pp) { if (pp->first +pp->second <= first_virt) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, trk_bg_col_, max(pp->first, first_addr), min(pp->first + pp->second, last_addr)); } } } else if (!pDC->IsPrinting() || theApp.print_change_) { // Draw change tracking from top down if (!display_.hide_replace) { std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > *ppr = GetDocument()->Replacements(); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp; for (pp = ppr->begin(); pp != ppr->end(); ++pp) if (pp->first + pp->second > first_virt) break; for ( ; pp != ppr->end(); ++pp) { if (pp->first > last_virt) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, trk_col_, max(pp->first, first_addr), min(pp->first + pp->second, last_addr), true, (pDC->IsPrinting() ? print_text_height_ : text_height_)/8); } } if (!display_.hide_insert) { std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > *ppr = GetDocument()->Insertions(); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp; for (pp = ppr->begin(); pp != ppr->end(); ++pp) if (pp->first + pp->second > first_virt) break; for ( ; pp != ppr->end(); ++pp) { if (pp->first > last_virt) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, trk_bg_col_, max(pp->first, first_addr), min(pp->first + pp->second, last_addr)); } } } // Don't print bookmarks if hide_bookmarks is on OR printing and print_bookmarks_ is off if (!(display_.hide_bookmarks || pDC->IsPrinting() && !theApp.print_bookmarks_)) { // Draw bookmarks for (std::vector<FILE_ADDRESS>::const_iterator pbm = pDoc->bm_posn_.begin(); pbm != pDoc->bm_posn_.end(); ++pbm) { if (*pbm >= first_addr && *pbm <= last_addr) { CRect mark_rect; mark_rect.top = int(((*pbm + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_ + 1); // mark_rect.bottom = mark_rect.top + line_height - 3; mark_rect.bottom = mark_rect.top + line_height - 1; if (neg_y) { mark_rect.top = -mark_rect.top; mark_rect.bottom = -mark_rect.bottom; } if (!display_.vert_display && display_.hex_area) { mark_rect.left = hex_pos(int((*pbm + offset_)%rowsize_), char_width) - doc_rect.left + bdr_left_; // mark_rect.right = mark_rect.left + 2*char_width; mark_rect.right = mark_rect.left + 2*char_width + 2; if (neg_x) { mark_rect.left = -mark_rect.left; mark_rect.right = -mark_rect.right; } pDC->FillSolidRect(&mark_rect, bm_col_); } if (display_.vert_display || display_.char_area) { mark_rect.left = char_pos(int((*pbm + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_ + 1; // mark_rect.right = mark_rect.left + char_width_w - 2; mark_rect.right = mark_rect.left + char_width_w; if (neg_x) { mark_rect.left = -mark_rect.left; mark_rect.right = -mark_rect.right; } pDC->FillSolidRect(&mark_rect, bm_col_); } } } } // First work out if we draw the mark - in display and not turned off for printing bool draw_mark; if (pDC->IsPrinting()) draw_mark = theApp.print_mark_ && mark_ >= first_virt && mark_ < last_virt; else draw_mark = mark_ >= first_addr && mark_ < last_addr; if (draw_mark) { CRect mark_rect; // Where mark is drawn in logical coords mark_rect.top = int(((mark_ + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_ + 1); // mark_rect.bottom = mark_rect.top + line_height - 3; mark_rect.bottom = mark_rect.top + line_height - 1; if (neg_y) { mark_rect.top = -mark_rect.top; mark_rect.bottom = -mark_rect.bottom; } if (!display_.vert_display && display_.hex_area) { mark_rect.left = hex_pos(int((mark_ + offset_)%rowsize_), char_width) - doc_rect.left + bdr_left_; // mark_rect.right = mark_rect.left + 2*char_width; mark_rect.right = mark_rect.left + 2*char_width + 2; if (neg_x) { mark_rect.left = -mark_rect.left; mark_rect.right = -mark_rect.right; } pDC->FillSolidRect(&mark_rect, mark_col_); } if (display_.vert_display || display_.char_area) { mark_rect.left = char_pos(int((mark_ + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_ + 1; // mark_rect.right = mark_rect.left + char_width_w - 2; mark_rect.right = mark_rect.left + char_width_w; if (neg_x) { mark_rect.left = -mark_rect.left; mark_rect.right = -mark_rect.right; } pDC->FillSolidRect(&mark_rect, mark_col_); } } // Draw indicator around byte that is used for info tips if (!pDC->IsPrinting() && last_tip_addr_ >= first_virt && last_tip_addr_ < last_virt) { CRect info_rect; // Where mark is drawn in logical coords info_rect.top = int(((last_tip_addr_ + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_ + 1); info_rect.bottom = info_rect.top + line_height - 1; if (neg_y) { info_rect.top = -info_rect.top; info_rect.bottom = -info_rect.bottom; } CBrush * psaved_brush = pDC->SelectObject(CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH))); CPen * psaved_pen = pDC->SelectObject(&pen1); if (!display_.vert_display && display_.hex_area) { info_rect.left = hex_pos(int((last_tip_addr_ + offset_)%rowsize_), char_width) - doc_rect.left + bdr_left_; info_rect.right = info_rect.left + 2*char_width + 1; if (neg_x) { info_rect.left = -info_rect.left; info_rect.right = -info_rect.right; } //pDC->FillSolidRect(&info_rect, sector_bg_col_); pDC->Rectangle(&info_rect); //pDC->MoveTo(info_rect.right, info_rect.bottom-1); //pDC->LineTo(info_rect.left, info_rect.bottom-1); //pDC->LineTo(info_rect.left, info_rect.top); //pDC->LineTo(info_rect.right, info_rect.top); } if (display_.vert_display || display_.char_area) { info_rect.left = char_pos(int((last_tip_addr_ + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_ + 1; info_rect.right = info_rect.left + char_width_w - 1; if (neg_x) { info_rect.left = -info_rect.left; info_rect.right = -info_rect.right; } //pDC->FillSolidRect(&info_rect, sector_bg_col_); pDC->Rectangle(&info_rect); //pDC->MoveTo(info_rect.right, info_rect.bottom-1); //pDC->LineTo(info_rect.left, info_rect.bottom-1); //pDC->LineTo(info_rect.left, info_rect.top); //pDC->LineTo(info_rect.right, info_rect.top); } (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } // Draw indicator around byte where bookmark is being moved to if (!pDC->IsPrinting() && mouse_down_ && drag_bookmark_ > -1) { CRect drag_rect; // Where mark is drawn in logical coords drag_rect.top = int(((drag_address_ + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_ + 1); drag_rect.bottom = drag_rect.top + line_height - 2; if (neg_y) { drag_rect.top = -drag_rect.top; drag_rect.bottom = -drag_rect.bottom; } CBrush * psaved_brush = pDC->SelectObject(CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH))); CPen * psaved_pen = pDC->SelectObject(&pen1); if (!display_.vert_display && display_.hex_area) { drag_rect.left = hex_pos(int((drag_address_ + offset_)%rowsize_), char_width) - doc_rect.left + bdr_left_; drag_rect.right = drag_rect.left + 2*char_width; if (neg_x) { drag_rect.left = -drag_rect.left; drag_rect.right = -drag_rect.right; } pDC->FillSolidRect(&drag_rect, bm_col_); pDC->Rectangle(&drag_rect); } if (display_.vert_display || display_.char_area) { drag_rect.left = char_pos(int((drag_address_ + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_ + 1; drag_rect.right = drag_rect.left + char_width_w - 1; if (neg_x) { drag_rect.left = -drag_rect.left; drag_rect.right = -drag_rect.right; } pDC->FillSolidRect(&drag_rect, bm_col_); pDC->Rectangle(&drag_rect); } (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } // Don't print highlights if hide_highlight is on OR printing and print_highlights_ is off if (!(display_.hide_highlight || pDC->IsPrinting() && !theApp.print_highlights_)) { if (!pDC->IsPrinting() && ScrollUp()) { // Draw highlighted areas bottom up range_set<FILE_ADDRESS>::range_t::reverse_iterator pr; for (pr = hl_set_.range_.rbegin(); pr != hl_set_.range_.rend(); ++pr) if (pr->sfirst < last_addr) break; for ( ; pr != hl_set_.range_.rend(); ++pr) { if (pr->slast <= first_addr) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, hi_col_, max(pr->sfirst, first_addr), min(pr->slast, last_addr)); } } else { // Draw highlighted areas top down range_set<FILE_ADDRESS>::range_t::const_iterator pr; for (pr = hl_set_.range_.begin(); pr != hl_set_.range_.end(); ++pr) if (pr->slast > first_addr) break; for ( ; pr != hl_set_.range_.end(); ++pr) { if (pr->sfirst > last_addr) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, hi_col_, max(pr->sfirst, first_addr), min(pr->slast, last_addr)); } } } if (pDC->IsPrinting()) { // Only print search occurrences if print_search_ is on if (theApp.print_search_) { // Draw search string occurrences // Note this goes through all search occurrences (since search_pair_ is // calculated for the current window) which may be slow but then so is printing. std::vector<FILE_ADDRESS> sf = GetDocument()->SearchAddresses(first_addr-search_length_, last_addr+search_length_); std::vector<FILE_ADDRESS>::const_iterator pp; for (pp = sf.begin(); pp != sf.end(); ++pp) { draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, search_col_, max(*pp, first_addr), min(*pp + search_length_, last_addr)); } } } else if (ScrollUp()) { // Draw search string occurrences bottom up std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::reverse_iterator pp, pend; for (pp = search_pair_.rbegin(), pend = search_pair_.rend(); pp != pend; ++pp) { draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, search_col_, max(pp->first, first_addr), min(pp->second, last_addr)); } } else { // Draw search string occurrences from top down std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp, pend; for (pp = search_pair_.begin(), pend = search_pair_.end(); pp != pend; ++pp) { draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, search_col_, max(pp->first, first_addr), min(pp->second, last_addr)); } } end_of_background_drawing: unsigned char buf[max_buf]; // Holds bytes for current line being displayed size_t last_col = 0; // Number of bytes in buf to display unsigned char prev_buf[max_buf]; // Copy of last buf - used for merging repeated lines size_t prev_last_col; // Number of bytes in last buf that were displayed int repeat_count = 0; // Number of consec. duplicate lines found so far // Move declarations outside loop (faster?) CString ss(' ', 24); // Temp string for formatting CRect tt; // Temp rect CRect addr_rect; // Where address is drawn // This was added for vert_display int vert_offset = 0; if (display_.vert_display) { if (pDC->IsPrinting()) vert_offset = print_text_height_; else vert_offset = text_height_; if (neg_y) vert_offset = - vert_offset; // vert_offset = (vert_offset*15)/16; // Leave a gap between rows } // THIS IS WHERE THE ACTUAL LINES ARE DRAWN // Note: we use != (line != last_line) since we may be drawing from bottom or top for (FILE_ADDRESS line = first_line; line != last_line; line += line_inc, norm_rect += rect_inc) { // Work out where to display line in logical coords (correct sign) tt = norm_rect; if (neg_x) { tt.left = -tt.left; tt.right = -tt.right; } if (neg_y) { tt.top = -tt.top; tt.bottom = -tt.bottom; } // No display needed if outside display area or past end of doc // Note: we don't break when past end since we may be drawing from bottom if (!pDC->RectVisible(&tt) || line*rowsize_ - offset_ > pDoc->length()) continue; // Take a copy of the last line output to check for repeated lines if (pDC->IsPrinting() && print_sel_ && dup_lines_ && last_col > 0) memcpy(prev_buf, buf, last_col); prev_last_col = last_col; // Get the bytes to display size_t ii; // Column of first byte if (line*rowsize_ - offset_ < first_addr) { last_col = pDoc->GetData(buf + offset_, rowsize_ - offset_, line*rowsize_) + offset_; ii = size_t(first_addr - (line*rowsize_ - offset_)); ASSERT(int(ii) < rowsize_); } else { last_col = pDoc->GetData(buf, rowsize_, line*rowsize_ - offset_); ii = 0; } if (line*rowsize_ - offset_ + last_col - last_addr >= rowsize_) last_col = 0; else if (line*rowsize_ - offset_ + last_col > last_addr) last_col = size_t(last_addr - (line*rowsize_ - offset_)); // TRACE("xxx line %ld rowsize_ %ld offset_ %ld last_col %ld first_addr %ld last_addr %ld\n", // long(line), long(rowsize_), long(offset_), long(last_col), long(first_addr), long(last_addr)); if (pDC->IsPrinting() && print_sel_ && dup_lines_) { // Check if the line is the same as the last one // But NOT if very first line (line 0 on page 0) since we may not display the whole line if ((curpage_ > 0 || line > first_line+1) && last_col == prev_last_col && memcmp(buf, prev_buf, last_col) == 0) { ++repeat_count; norm_rect -= rect_inc; continue; } if (repeat_count > 0) { // Display how many times the line was repeated CString mess; if (repeat_count == 1) mess = "Repeated once"; else mess.Format("Repeated %d more times", repeat_count); CRect mess_rect = tt; mess_rect.left += hex_pos(0, char_width); pDC->DrawText(mess, &mess_rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); // Move the current display line down one norm_rect += rect_inc; tt = norm_rect; if (neg_x) { tt.left = -tt.left; tt.right = -tt.right; } if (neg_y) { tt.top = -tt.top; tt.bottom = -tt.bottom; } // Reset the repeated line counter since this was a different line repeat_count = 0; } // See if we are at the bottom of the page yet if (norm_rect.bottom > margin_size_.cy + print_text_height_*lines_per_page_) { print_next_line_ = line; break; } } // Draw address if ... if ((addr_width_ - 1)*char_width + tt.left > 0 && // not off to the left (tt.top + text_height_/4 >= bdr_top_ || pDC->IsPrinting())) // and does not encroach into ruler { addr_rect = tt; // tt with right margin where addresses end addr_rect.right = addr_rect.left + addr_width_*char_width - char_width - 1; if (pDC->IsPrinting()) if (neg_y) addr_rect.bottom = addr_rect.top - print_text_height_; else addr_rect.bottom = addr_rect.top + print_text_height_; else if (neg_y) addr_rect.bottom = addr_rect.top - text_height_; else addr_rect.bottom = addr_rect.top + text_height_; // Not highlighting when the mouse is down avoids a problem with invalidation of // the address area when autoscrolling (old highlights sometimes left behind). if (theApp.hl_caret_ && !pDC->IsPrinting() && !mouse_down_ && start_addr >= line*rowsize_ - offset_ && start_addr < (line+1)*rowsize_ - offset_) { CBrush * psaved_brush = pDC->SelectObject(&brush); CPen * psaved_pen = pDC->SelectObject(&pen1); pDC->Rectangle(&addr_rect); (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } // Show address of current row with a different background colour if (theApp.hl_mouse_ && !pDC->IsPrinting() && mouse_addr_ >= line*rowsize_ - offset_ && mouse_addr_ < (line+1)*rowsize_ - offset_) { CBrush * psaved_brush = pDC->SelectObject(CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH))); CPen * psaved_pen = pDC->SelectObject(&pen1); pDC->Rectangle(&addr_rect); (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } if (hex_width_ > 0) { int ww = hex_width_ + 1; char *addr_buf = ss.GetBuffer(24); // reserve space for 64 bit address sprintf(addr_buf, theApp.hex_ucase_ ? "%0*I64X:" : "%0*I64x:", hex_width_, (line*rowsize_ - offset_ > first_addr ? line*rowsize_ - offset_ : first_addr) + display_.addrbase1); ss.ReleaseBuffer(-1); if (theApp.nice_addr_) { AddSpaces(ss); ww += (hex_width_-1)/4; } pDC->SetTextColor(GetHexAddrCol()); // Colour of hex addresses addr_rect.right = addr_rect.left + ww*char_width; pDC->DrawText(ss, &addr_rect, DT_TOP | DT_NOPREFIX | DT_SINGLELINE); addr_rect.left = addr_rect.right; } if (dec_width_ > 0) { int ww = dec_width_ + 1; char *addr_buf = ss.GetBuffer(24); // reserve space for 64 bit address sprintf(addr_buf, "%*I64d:", dec_width_, (line*rowsize_ - offset_ > first_addr ? line*rowsize_ - offset_ : first_addr) + display_.addrbase1); ss.ReleaseBuffer(-1); if (theApp.nice_addr_) { AddCommas(ss); ww += (dec_width_-1)/3; } pDC->SetTextColor(GetDecAddrCol()); // Colour of dec addresses addr_rect.right = addr_rect.left + ww*char_width; pDC->DrawText(ss, &addr_rect, DT_TOP | DT_RIGHT | DT_NOPREFIX | DT_SINGLELINE); addr_rect.left = addr_rect.right; } if (num_width_ > 0) { int ww = num_width_ + 1; char *addr_buf = ss.GetBuffer(24); // reserve space for 64 bit address sprintf(addr_buf, "%*I64d:", num_width_, line + display_.addrbase1); ss.ReleaseBuffer(-1); if (theApp.nice_addr_) { AddCommas(ss); ww += (num_width_-1)/3; } pDC->SetTextColor(GetDecAddrCol()); // Colour of dec addresses addr_rect.right = addr_rect.left + ww*char_width; pDC->DrawText(ss, &addr_rect, DT_TOP | DT_RIGHT | DT_NOPREFIX | DT_SINGLELINE); addr_rect.left = addr_rect.right; } } // Keep track of the current colour so we only set it when it changes COLORREF current_colour = kala[buf[ii]]; pDC->SetTextColor(current_colour); if (display_.vert_display || display_.hex_area) { int posx = tt.left + hex_pos(0, char_width); // Horiz pos of 1st hex column // Display each byte as hex (and char if nec.) for (size_t jj = ii ; jj < last_col; ++jj) { if (display_.vert_display) { if (posx + int(jj + 1 + jj/group_by_)*char_width_w < 0) continue; else if (posx + int(jj + jj/group_by_)*char_width_w >= tt.right) break; } else { if (posx + int((jj+1)*3 + jj/group_by_)*char_width < 0) continue; else if (posx + int(jj*3 + jj/group_by_)*char_width >= tt.right) break; } if (current_colour != kala[buf[jj]]) { current_colour = kala[buf[jj]]; pDC->SetTextColor(current_colour); } if (display_.vert_display) { // Now display the character in the top row if (display_.char_set != CHARSET_EBCDIC) { if ((buf[jj] >= 32 && buf[jj] < 127) || (display_.char_set != CHARSET_ASCII && buf[jj] >= first_char_ && buf[jj] <= last_char_) ) { // Display normal char or graphic char if in font pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, (char *)&buf[jj], 1); } else if (display_.control == 0 || buf[jj] >= 32) { // Display control char and other chars as red '.' pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, ".", 1); } else if (display_.control == 1) { // Display control chars as red uppercase equiv. char cc = buf[jj] + 0x40; pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, &cc, 1); } else if (display_.control == 2) { // Display control chars as C escape code (in red) const char *check = "\a\b\f\n\r\t\v\0"; const char *display = "abfnrtv0"; const char *pp; if (/*buf[jj] != '\0' && */(pp = strchr(check, buf[jj])) != NULL) pp = display + (pp-check); else pp = "."; pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, pp, 1); } } else { // Display EBCDIC (or red dot if not valid EBCDIC char) if (e2a_tab[buf[jj]] == '\0') { pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, ".", 1); } else { pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, (char *)&e2a_tab[buf[jj]], 1); } } // Display the hex digits below that, one below the other pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top + vert_offset, &hex[(buf[jj]>>4)&0xF], 1); pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top + vert_offset*2, &hex[buf[jj]&0xF], 1); } else { char hh[2]; // Create hex digits and display them hh[0] = hex[(buf[jj]>>4)&0xF]; hh[1] = hex[buf[jj]&0xF]; // This actually displays the bytes (in hex)! // Note: removed calcs that were previously encapsulated in hex_pos pDC->TextOut(posx + (jj*3 + jj/group_by_)*char_width, tt.top, hh, 2); } } } if (!display_.vert_display && display_.char_area) { // Keep track of the current colour so we only set it when it changes int posc = tt.left + char_pos(0, char_width, char_width_w); // Horiz pos of 1st char column for (size_t kk = ii ; kk < last_col; ++kk) { if (posc + int(kk+1)*char_width_w < 0) continue; else if (posc + int(kk)*char_width_w >= tt.right) break; if (current_colour != kala[buf[kk]]) { current_colour = kala[buf[kk]]; pDC->SetTextColor(current_colour); } // Display byte in char display area (as ASCII, EBCDIC etc) if (display_.char_set != CHARSET_EBCDIC) { if ((buf[kk] >= 32 && buf[kk] < 127) || (display_.char_set != CHARSET_ASCII && buf[kk] >= first_char_ && buf[kk] <= last_char_) ) { // Display normal char or graphic char if in font pDC->TextOut(posc + kk*char_width_w, tt.top, (char *)&buf[kk], 1); } else if (display_.control == 0 || buf[kk] > 31) { // Display control char and other chars as red '.' pDC->TextOut(posc + kk*char_width_w, tt.top, ".", 1); } else if (display_.control == 1) { // Display control chars as red uppercase equiv. char cc = buf[kk] + 0x40; pDC->TextOut(posc + kk*char_width_w, tt.top, &cc, 1); } else if (display_.control == 2) { // Display control chars as C escape code (in red) const char *check = "\a\b\f\n\r\t\v\0"; const char *display = "abfnrtv0"; const char *pp; if (/*buf[kk] != '\0' && */(pp = strchr(check, buf[kk])) != NULL) pp = display + (pp-check); else pp = "."; pDC->TextOut(posc + kk*char_width_w, tt.top, pp, 1); } } else { // Display EBCDIC (or red dot if not valid EBCDIC char) if (e2a_tab[buf[kk]] == '\0') { pDC->TextOut(posc + kk*char_width_w, tt.top, ".", 1); } else { pDC->TextOut(posc + kk*char_width_w, tt.top, (char *)&e2a_tab[buf[kk]], 1); } } } } // If any part of the line is within the current selection if (!pDC->IsPrinting() && start_addr < end_addr && end_addr > line*rowsize_ - offset_ && start_addr < (line+1)*rowsize_ - offset_) { FILE_ADDRESS start = max(start_addr, line*rowsize_ - offset_); FILE_ADDRESS end = min(end_addr, (line+1)*rowsize_ - offset_); // ASSERT(end > start); ASSERT(display_.hex_area || display_.char_area); if (!display_.vert_display && display_.hex_area) { CRect rev(norm_rect); rev.right = rev.left + hex_pos(int(end - (line*rowsize_ - offset_) - 1)) + 2*text_width_; rev.left += hex_pos(int(start - (line*rowsize_ - offset_))); if (neg_x) { rev.left = -rev.left; rev.right = -rev.right; } if (neg_y) { rev.top = -rev.top; rev.bottom = -rev.bottom; } if (has_focus && !display_.edit_char || num_colours <= 256) pDC->InvertRect(&rev); // Full contrast reverse video only if in editing in hex area else pDC->PatBlt(rev.left, rev.top, rev.right-rev.left, rev.bottom-rev.top, PATINVERT); } if (display_.vert_display || display_.char_area) { // Draw char selection in inverse CRect rev(norm_rect); rev.right = rev.left + char_pos(int(end - (line*rowsize_ - offset_) - 1)) + text_width_w_; rev.left += char_pos(int(start - (line*rowsize_ - offset_))); if (neg_x) { rev.left = -rev.left; rev.right = -rev.right; } if (neg_y) { rev.top = -rev.top; rev.bottom = -rev.bottom; } if (num_colours <= 256 || has_focus && (display_.vert_display || display_.edit_char)) pDC->InvertRect(&rev); else pDC->PatBlt(rev.left, rev.top, rev.right-rev.left, rev.bottom-rev.top, PATINVERT); } } else if (theApp.show_other_ && has_focus && !display_.vert_display && display_.char_area && display_.hex_area && // we can only display in the other area if both exist !pDC->IsPrinting() && start_addr == end_addr && start_addr >= line*rowsize_ - offset_ && start_addr < (line+1)*rowsize_ - offset_) { // Draw "shadow" cursor in the other area FILE_ADDRESS start = max(start_addr, line*rowsize_ - offset_); FILE_ADDRESS end = min(end_addr, (line+1)*rowsize_ - offset_); CRect rev(norm_rect); if (display_.edit_char) { ASSERT(display_.char_area); rev.right = rev.left + hex_pos(int(end - (line*rowsize_ - offset_))) + 2*text_width_; rev.left += hex_pos(int(start - (line*rowsize_ - offset_))); } else { ASSERT(display_.hex_area); rev.right = rev.left + char_pos(int(end - (line*rowsize_ - offset_))) + text_width_w_; rev.left += char_pos(int(start - (line*rowsize_ - offset_))); } if (neg_x) { rev.left = -rev.left; rev.right = -rev.right; } if (neg_y) { rev.top = -rev.top; rev.bottom = -rev.bottom; } pDC->PatBlt(rev.left, rev.top, rev.right-rev.left, rev.bottom-rev.top, PATINVERT); } else if (!has_focus && !pDC->IsPrinting() && start_addr == end_addr && start_addr >= line*rowsize_ - offset_ && start_addr < (line+1)*rowsize_ - offset_) { // Draw "shadow" for current byte when lost focus if (!display_.vert_display && display_.hex_area) { // Get rect for hex area FILE_ADDRESS start = max(start_addr, line*rowsize_ - offset_); FILE_ADDRESS end = min(end_addr, (line+1)*rowsize_ - offset_); CRect rev(norm_rect); rev.right = rev.left + hex_pos(int(end - (line*rowsize_ - offset_))) + 2*text_width_; rev.left += hex_pos(int(start - (line*rowsize_ - offset_))); if (neg_x) { rev.left = -rev.left; rev.right = -rev.right; } if (neg_y) { rev.top = -rev.top; rev.bottom = -rev.bottom; } pDC->PatBlt(rev.left, rev.top, rev.right-rev.left, rev.bottom-rev.top, PATINVERT); } if (display_.vert_display || display_.char_area) { // Get rect for char area or stacked mode FILE_ADDRESS start = max(start_addr, line*rowsize_ - offset_); FILE_ADDRESS end = min(end_addr, (line+1)*rowsize_ - offset_); CRect rev(norm_rect); rev.right = rev.left + char_pos(int(end - (line*rowsize_ - offset_))) + text_width_w_; rev.left += char_pos(int(start - (line*rowsize_ - offset_))); if (neg_x) { rev.left = -rev.left; rev.right = -rev.right; } if (neg_y) { rev.top = -rev.top; rev.bottom = -rev.bottom; } pDC->PatBlt(rev.left, rev.top, rev.right-rev.left, rev.bottom-rev.top, PATINVERT); } } } // for each display (text) line if (pDC->IsPrinting() && print_sel_ && dup_lines_) { curpage_ = -1; // signal that there is no more to print // Display any residual repeated lines count if (repeat_count > 0) { // Display how many times the line was repeated CString mess; if (repeat_count == 1) mess = "Repeated once"; else mess.Format("Repeated %d more times", repeat_count); CRect mess_rect = norm_rect; if (neg_x) { mess_rect.left = -mess_rect.left; mess_rect.right = -mess_rect.right; } if (neg_y) { mess_rect.top = -mess_rect.top; mess_rect.bottom = -mess_rect.bottom; } mess_rect.left += hex_pos(0, char_width); pDC->DrawText(mess, &mess_rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } } if (!pDC->IsPrinting()) { ShowCaret(); } // move_dlgs(); } #ifdef RULER_ADJUST // Draws adjuster handles in the ruler void CHexEditView::draw_adjusters(CDC* pDC) { int xpos; // Set up pen and brush colours (all adjusters are the same colour) CPen pen(PS_SOLID, 0, RGB(0,0,0)); // black pen CPen pdash(PS_DOT, 0, RGB(0,0,0)); // for dashed black line CBrush bwhite(RGB(255,255,255)); // white brush CBrush bred(RGB(192,0,0)); // red brush CPen * psp = pDC->SelectObject(&pen); // ptr to saved pen CBrush * psb = pDC->SelectObject(&bwhite); // ptr to saved brush // Show rowsize_ in the ruler ASSERT(rowsize_ > 3); if (!display_.vert_display && display_.hex_area) { if (adjusting_rowsize_ == -1 || adjusting_rowsize_ == rowsize_) xpos = char_pos(0) - text_width_w_/2 - scrollpos_.x; else xpos = hex_pos(adjusting_rowsize_) - scrollpos_.x; if (display_.autofit) pDC->SelectObject(&bred); draw_rowsize(pDC, xpos-1); if (display_.autofit) pDC->SelectObject(&bwhite); if (adjusting_rowsize_ > -1) { (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos-1, bdr_top_); pDC->LineTo(xpos-1, 30000); (void)pDC->SelectObject(pen); } } else if (display_.vert_display || display_.char_area) { if (adjusting_rowsize_ == -1 || adjusting_rowsize_ == rowsize_) xpos = char_pos(rowsize_ - 1) + (3*text_width_w_)/2 - scrollpos_.x; else xpos = char_pos(adjusting_rowsize_) - scrollpos_.x; if (display_.autofit) pDC->SelectObject(&bred); draw_rowsize(pDC, xpos-1); if (display_.autofit) pDC->SelectObject(&bwhite); if (adjusting_rowsize_ > -1) { (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos-1, bdr_top_); pDC->LineTo(xpos-1, 30000); (void)pDC->SelectObject(pen); } } // Show position of "offset_" in the ruler (in hex and/or char areas) ASSERT(offset_ < rowsize_); if (!display_.vert_display && display_.hex_area) { if (adjusting_offset_ > -1) xpos = hex_pos(adjusting_offset_) - scrollpos_.x; else xpos = hex_pos(offset_) - scrollpos_.x; draw_offset(pDC, xpos-1); if (adjusting_offset_ > -1) { (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos-1, bdr_top_); pDC->LineTo(xpos-1, 30000); (void)pDC->SelectObject(pen); } } if (display_.vert_display || display_.char_area) { if (adjusting_offset_ > -1) xpos = char_pos(adjusting_offset_) - scrollpos_.x; else xpos = char_pos(offset_) - scrollpos_.x; if (display_.vert_display || !display_.hex_area) draw_offset(pDC, xpos-1); if (adjusting_offset_ > -1) { (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos-1, bdr_top_); pDC->LineTo(xpos-1, 30000); (void)pDC->SelectObject(pen); } } // Show current grouping if not adjusting (adjusting_group_by_ == -1) OR // current adjust column if not dragged past the edge (adjusting_group_by_ < 9999) if (adjusting_group_by_ == -1 && group_by_ < rowsize_ || adjusting_group_by_ > -1 && adjusting_group_by_ < rowsize_) { if (display_.vert_display) { if (adjusting_group_by_ > -1) xpos = char_pos(adjusting_group_by_) - scrollpos_.x; else xpos = char_pos(group_by_) - scrollpos_.x; if (display_.vert_display && (adjusting_group_by_ == -1 || adjusting_group_by_%group_by_ == 0)) xpos -= text_width_w_/2; draw_group_by(pDC, xpos); if (adjusting_group_by_ > -1) { // Draw vertical dashed line (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos, bdr_top_); pDC->LineTo(xpos, 30000); (void)pDC->SelectObject(pen); } } else if (display_.hex_area) { if (adjusting_group_by_ > -1) xpos = hex_pos(adjusting_group_by_) - 2 - scrollpos_.x; else xpos = hex_pos(group_by_) - 2 - scrollpos_.x; if (adjusting_group_by_ == -1 || adjusting_group_by_%group_by_ == 0) xpos -= (text_width_ - 1); draw_group_by(pDC, xpos); if (adjusting_group_by_ > -1) { (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos, bdr_top_); pDC->LineTo(xpos, 30000); (void)pDC->SelectObject(pen); } } } (void)pDC->SelectObject(psp); (void)pDC->SelectObject(psb); } // Draws row size adjustment handle in the ruler void CHexEditView::draw_rowsize(CDC* pDC, int xpos) { pDC->BeginPath(); pDC->MoveTo(xpos + 2, bdr_top_ - 7); pDC->LineTo(xpos, bdr_top_ - 7); pDC->LineTo(xpos - 3, bdr_top_ - 4); pDC->LineTo(xpos, bdr_top_ - 1); pDC->LineTo(xpos + 2, bdr_top_ - 1); pDC->EndPath(); pDC->StrokeAndFillPath(); } // Draws offset handle in the ruler void CHexEditView::draw_offset(CDC* pDC, int xpos) { pDC->BeginPath(); pDC->MoveTo(xpos - 1, bdr_top_ - 6); pDC->LineTo(xpos - 1, bdr_top_ - 2); pDC->LineTo(xpos, bdr_top_ - 1); pDC->LineTo(xpos + 3, bdr_top_ - 4); pDC->LineTo(xpos, bdr_top_ - 7); pDC->EndPath(); pDC->StrokeAndFillPath(); } // Draws group by handle in the ruler void CHexEditView::draw_group_by(CDC* pDC, int xpos) { pDC->BeginPath(); pDC->MoveTo(xpos - 3, bdr_top_ - 7); pDC->LineTo(xpos - 3, bdr_top_ - 5); pDC->LineTo(xpos, bdr_top_ - 2); pDC->LineTo(xpos + 3, bdr_top_ - 5); pDC->LineTo(xpos + 3, bdr_top_ - 7); pDC->EndPath(); pDC->StrokeAndFillPath(); } #endif void CHexEditView::draw_bg(CDC* pDC, const CRectAp &doc_rect, bool neg_x, bool neg_y, int line_height, int char_width, int char_width_w, COLORREF clr, FILE_ADDRESS start_addr, FILE_ADDRESS end_addr, bool merge /*=true*/, int draw_height /*=-1*/) { if (end_addr < start_addr) return; if (draw_height > -1 && draw_height < 2) draw_height = 2; // make it at least 2 pixels (1 does not draw properly) int saved_rop = pDC->SetROP2(R2_NOTXORPEN); CPen pen(PS_SOLID, 0, clr); CPen * psaved_pen = pDC->SelectObject(&pen); CBrush brush(clr); CBrush * psaved_brush = pDC->SelectObject(&brush); FILE_ADDRESS start_line = (start_addr + offset_)/rowsize_; FILE_ADDRESS end_line = (end_addr + offset_)/rowsize_; int start_in_row = int((start_addr+offset_)%rowsize_); int end_in_row = int((end_addr+offset_)%rowsize_); CRect rct; if (start_line == end_line) { // Draw the block (all on one line) rct.bottom = int((start_line+1) * line_height - doc_rect.top + bdr_top_); rct.top = rct.bottom - (draw_height > 0 ? draw_height : line_height); if (neg_y) { rct.top = -rct.top; rct.bottom = -rct.bottom; } if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(start_in_row, char_width) - doc_rect.left + bdr_left_; rct.right = hex_pos(end_in_row - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (neg_x && rct.left > rct.right || !neg_x && rct.left < rct.right) { if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } } if (display_.vert_display || display_.char_area) { // rct.top = start_line * line_height; // rct.bottom = rct.top + line_height; rct.left = char_pos(start_in_row, char_width, char_width_w) - doc_rect.left + bdr_left_; rct.right = char_pos(end_in_row - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } pDC->SetROP2(saved_rop); pDC->SelectObject(psaved_pen); pDC->SelectObject(psaved_brush); return; // All on one line so that's it } // Block extends over (at least) 2 lines so draw the partial lines at each end rct.bottom = int((start_line+1) * line_height - doc_rect.top + bdr_top_); rct.top = rct.bottom - (draw_height > 0 ? draw_height : line_height); if (neg_y) { rct.top = -rct.top; rct.bottom = -rct.bottom; } if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(start_in_row, char_width) - doc_rect.left + bdr_left_; rct.right = hex_pos(rowsize_ - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } ASSERT(neg_x && rct.left > rct.right || !neg_x && rct.left < rct.right); if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } if (display_.vert_display || display_.char_area) { rct.left = char_pos(start_in_row, char_width, char_width_w) - doc_rect.left + bdr_left_; rct.right = char_pos(rowsize_ - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } // Last (partial) line rct.bottom = int((end_line+1) * line_height - doc_rect.top + bdr_top_); rct.top = rct.bottom - (draw_height > 0 ? draw_height : line_height); if (neg_y) { rct.top = -rct.top; rct.bottom = -rct.bottom; } if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(0, char_width) - doc_rect.left + bdr_left_; rct.right = hex_pos(end_in_row - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (neg_x && rct.left > rct.right || !neg_x && rct.left < rct.right) { if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } } if (display_.vert_display || display_.char_area) { rct.left = char_pos(0, char_width, char_width_w) - doc_rect.left + bdr_left_; rct.right = char_pos(end_in_row - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } // Now draw all the full lines if (draw_height > 0) { // Since we ar not doing a complete fill of the lines (eg underline) // we have to do each line of text individually for (++start_line; start_line < end_line; ++start_line) { rct.bottom = int((start_line+1) * line_height - doc_rect.top + bdr_top_); rct.top = rct.bottom - draw_height; if (neg_y) { rct.top = -rct.top; rct.bottom = -rct.bottom; } if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(0, char_width) - doc_rect.left + bdr_left_; rct.right = hex_pos(rowsize_ - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } ASSERT(neg_x && rct.left > rct.right || !neg_x && rct.left < rct.right); if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } if (display_.vert_display || display_.char_area) { rct.left = char_pos(0, char_width, char_width_w) - doc_rect.left + bdr_left_; rct.right = char_pos(rowsize_ - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } } } else if (start_line + 1 < end_line) { // Draw the complete lines as one block rct.top = int((start_line + 1) * line_height - doc_rect.top + bdr_top_); rct.bottom = int(end_line * line_height - doc_rect.top + bdr_top_); if (neg_y) { rct.top = -rct.top; rct.bottom = -rct.bottom; } if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(0, char_width) - doc_rect.left + bdr_left_; rct.right = hex_pos(rowsize_ - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } ASSERT(neg_x && rct.left > rct.right || !neg_x && rct.left < rct.right); if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } if (display_.vert_display || display_.char_area) { rct.left = char_pos(0, char_width, char_width_w) - doc_rect.left + bdr_left_; rct.right = char_pos(rowsize_ - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } } pDC->SetROP2(saved_rop); pDC->SelectObject(psaved_pen); pDC->SelectObject(psaved_brush); return; } // recalc_display() - recalculates everything to do with the display // (and redraws it) if anything about how the window is drawn changes. // This includes font changed, window resized, document changed, display // options changed (address display, char display, autofit turned on etc). void CHexEditView::recalc_display() { // Stop re-entry (can cause inf. recursion) if (in_recalc_display) return; in_recalc_display = true; CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (GetScrollPastEnds() != theApp.scroll_past_ends_) { SetScrollPastEnds(theApp.scroll_past_ends_); SetScroll(GetScroll()); } SetAutoscroll(theApp.autoscroll_accel_); // Save info on the current font { TEXTMETRIC tm; CClientDC dc(this); OnPrepareDC(&dc); dc.GetTextMetrics(&tm); text_height_ = tm.tmHeight + tm.tmExternalLeading; // Height of font first_char_ = tm.tmFirstChar; // 1st valid char of font last_char_ = tm.tmLastChar; // last valid char of font // This causes problems when in IBM/OEM mode since these fonts have characters right down to zero // if (first_char_ < 32) first_char_ = 32; // Some fonts return 30 but 30,31 are nothing // The max char width returned by many fonts is much too big (seems to be bigger than any character in font!?) // text_width_ = tm.tmMaxCharWidth; // width of widest char in font CSize size; ::GetTextExtentPoint32(dc.m_hDC, "D", 1, &size); text_width_ = size.cx; // width of "D" ::GetTextExtentPoint32(dc.m_hDC, "W", 1, &size); text_width_w_ = size.cx; // width of "W" if (display_.vert_display) line_height_ = text_height_ * 3; else line_height_ = text_height_; } // Adjust border for ruler bdr_top_ = 0; if (theApp.ruler_) { if (display_.hex_addr) bdr_top_ += text_height_; // one row of text for hex offsets if (display_.decimal_addr || display_.line_nums) bdr_top_ += text_height_; // one row of text for dec offsets bdr_top_ += 5; // allow room for a thin line } #ifdef TEST_CLIPPING bdr_top_ += 40; #endif FILE_ADDRESS length = GetDocument()->length() + display_.addrbase1; hex_width_ = display_.hex_addr ? SigDigits(length, 16) : 0; dec_width_ = display_.decimal_addr ? SigDigits(length) : 0; num_width_ = 0; calc_addr_width(); if (display_.autofit && display_.line_nums) { // If autofit is on then rowsize_ and num_width_ are mutually dependent so // we have to handle this carefully. int prev_rowsize = 4; // Loop a few timres and see if the value converges for (int ii = 0; ii < 10; ++ii) { num_width_ = SigDigits(length/prev_rowsize); calc_addr_width(); calc_autofit(); if (rowsize_ == prev_rowsize) break; prev_rowsize = rowsize_; } // If it didn't converge then favour the larger value // (I think non-convergence only occurs when the row // size oscillates between 2 adjacent integer values.) if (rowsize_ < prev_rowsize) rowsize_ = prev_rowsize; } else if (display_.autofit) calc_autofit(); else if (display_.line_nums) { num_width_ = SigDigits(length/rowsize_); calc_addr_width(); } // Fit columns to window width? if (display_.autofit) { // Work out the current address of the caret/selection FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Set size before setting scroll/caret to avoid them being moved to "valid" pos if (display_.vert_display) SetTSize(CSizeAp(-1, ((GetDocument()->length() + offset_)/rowsize_ + 1)*3)); // 3 rows of text else SetTSize(CSizeAp(-1, (GetDocument()->length() + offset_)/rowsize_ + 1)); // Make sure scroll position is at left side // SetScroll(CPointAp(0, topleft/rowsize_ * line_height_)); SetScroll(CPointAp(0, GetScroll().y)); // Move the caret/selection to the where the same byte(s) as before SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); } else { if (display_.vert_display) SetTSize(CSizeAp(-1, ((GetDocument()->length() + offset_)/rowsize_ + 1)*3)); // 3 rows of text else SetTSize(CSizeAp(-1, (GetDocument()->length() + offset_)/rowsize_ + 1)); } // Make sure we know the width of the display area if (display_.vert_display || display_.char_area) SetSize(CSize(char_pos(rowsize_-1)+text_width_w_+text_width_w_/2+1, -1)); else { ASSERT(display_.hex_area); display_.hex_area = TRUE; // defensive SetSize(CSize(hex_pos(rowsize_-1)+2*text_width_+text_width_/2+1, -1)); } if (pcv_ != NULL) pcv_->recalc_display(); in_recalc_display = false; } /* recalc_display() */ void CHexEditView::calc_addr_width() { addr_width_ = hex_width_ + dec_width_ + num_width_; // Allow for separators (spaces and commas) if (theApp.nice_addr_) addr_width_ += (hex_width_-1)/4 + (dec_width_-1)/3 + (num_width_-1)/3; // Also add 1 for the colon addr_width_ += hex_width_ > 0 ? 1 : 0; addr_width_ += dec_width_ > 0 ? 1 : 0; addr_width_ += num_width_ > 0 ? 1 : 0; ++addr_width_; } // This is just called from recalc_display void CHexEditView::calc_autofit() { CRect cli; CRectAp rect; // Client rectangle in norm. coords GetDisplayRect(&cli); rect = ConvertFromDP(cli) - GetScroll(); ASSERT(rect.left == 0 && rect.top == 0); // Work out how many columns we can display across the window // NOTE: These calcs are directly related to the calcs in hex_pos and char_pos // Work out width of display area (total minus address area width) int daw = rect.right - addr_width_*text_width_ - text_width_/2 - 1; if (display_.vert_display) { int group_offset = (daw/text_width_w_)%(group_by_ + 1); if (group_offset == 0) group_offset = group_by_; rowsize_ = ((daw/text_width_w_ - 1)/(group_by_ + 1)) * group_by_ + group_offset; // Make sure scroll bars are not shown ASSERT(rowsize_ < 5 || rect.right >= char_pos(rowsize_-1)+text_width_w_); } else if (display_.char_area && display_.hex_area) { int sec_len = group_by_*(3*text_width_ + text_width_w_) + text_width_; int group_offset = (daw % sec_len)/(3*text_width_ + text_width_w_); if (group_offset == group_by_) group_offset = 0; rowsize_ = ((daw + text_width_) / sec_len) * group_by_ + group_offset; ASSERT(rowsize_ < 5 || rect.right >= char_pos(rowsize_-1)+text_width_w_); } else if (display_.char_area) { // This is easy as char area has no grouping rowsize_ = daw/text_width_w_; ASSERT(rowsize_ < 5 || rect.right >= char_pos(rowsize_-1)+text_width_w_); } else { ASSERT(display_.hex_area); display_.hex_area = TRUE; // defensive //rowsize_ = (daw - daw/(3*group_by_+1))/(3*text_width_); int group_offset = (daw/text_width_ - 2)%(3*group_by_ + 1); if (group_offset == 3*group_by_) group_offset--; rowsize_ = ((daw/text_width_ - 2)/(3*group_by_ + 1))*group_by_ + group_offset/3 + 1; ASSERT(rowsize_ < 5 || rect.right >= hex_pos(rowsize_-1)+2*text_width_); } // Must display at least 4 columns & no more than buffer can hold if (rowsize_ < 4) rowsize_ = 4; else if (rowsize_ > max_buf) rowsize_ = max_buf; // Ensure offset is within valid range if (real_offset_ < rowsize_) offset_ = real_offset_; else offset_ = rowsize_ - 1; } // Return doc position given a hex area column number // int CHexEditView::hex_pos(int column, int width) const; // Return closest hex area column given x display position // Inside determines the numbers returned for columns above rowsize_ // 1 (TRUE) will return a value from 0 to rowsize_ - 1 // 0 (FALSE) will return a value from 0 to rowsize_ // -1 will return value possibly greater than rowsize_ int CHexEditView::pos_hex(int pos, int inside) const { int col = pos - addr_width_*text_width_; col -= (col/(text_width_*(group_by_*3+1)))*text_width_; col = col/(3*text_width_); // Make sure col is within valid range if (col < 0) col = 0; else if (inside == 1 && col >= rowsize_) col = rowsize_ - 1; else if (inside == 0 && col > rowsize_) col = rowsize_; return col; } // Return display position given a char area column number // int CHexEditView::char_pos(int column, int width /* = 0 */) const; // Return closest char area column given display (X) coord // Inside determines the numbers returned for columns above rowsize_ // 1 (TRUE) will return a value from 0 to rowsize_ - 1 // 0 (FALSE) will return a value from 0 to rowsize_ // -1 will return value possibly greater than rowsize_ int CHexEditView::pos_char(int pos, int inside) const { int col; if (display_.vert_display) { col = (pos - addr_width_*text_width_)/text_width_w_; col -= col/(group_by_+1); } else if (display_.hex_area) col = (pos - addr_width_*text_width_ - rowsize_*3*text_width_ - ((rowsize_-1)/group_by_)*text_width_) / text_width_w_; else col = (pos - addr_width_*text_width_) / text_width_w_; // Make sure col is within valid range if (col < 0) col = 0; else if (inside == 1 && col >= rowsize_) col = rowsize_ - 1; else if (inside == 0 && col > rowsize_) col = rowsize_; return col; } void CHexEditView::DoInvalidate() { if (((CHexEditApp *)AfxGetApp())->refresh_off_) needs_refresh_ = true; else { if (pav_ != NULL) pav_->Invalidate(); if (pcv_ != NULL) pcv_->Invalidate(); CScrView::DoInvalidate(); } } // Always call this virtual wrapper of CWnd::InvalidateRect // necessary since InvalidateRect is not virtual. void CHexEditView::DoInvalidateRect(LPCRECT lpRect) { if (((CHexEditApp *)AfxGetApp())->refresh_off_) needs_refresh_ = true; else CScrView::DoInvalidateRect(lpRect); } void CHexEditView::DoInvalidateRgn(CRgn* pRgn) { if (((CHexEditApp *)AfxGetApp())->refresh_off_) needs_refresh_ = true; else CScrView::DoInvalidateRgn(pRgn); } void CHexEditView::DoScrollWindow(int xx, int yy) { if (((CHexEditApp *)AfxGetApp())->refresh_off_) needs_refresh_ = true; else { if (theApp.ruler_ && xx != 0) { // We need to scroll the ruler (as it's outside the scroll region) CRect rct; GetDisplayRect(&rct); rct.top = 0; rct.bottom = bdr_top_; ScrollWindow(xx, 0, &rct, &rct); // Also since we do not draw partial numbers at either end // we have to invalidate a bit more at either end than // is invalidated by ScrollWindow. if (xx > 0) rct.right = rct.left + xx + text_width_*3; else rct.left = rct.right + xx - text_width_*3; DoInvalidateRect(&rct); } CScrView::DoScrollWindow(xx, yy); if (yy < 0) { // We need to invalidate a bit of the address area near the top so that partial addresses are not drawn CRect rct; GetDisplayRect(&rct); rct.bottom = rct.top + line_height_; rct.top -= line_height_/4; rct.right = rct.left + addr_width_*text_width_; DoInvalidateRect(&rct); } else if (yy > 0) { // We need to invalidate a bit below the scrolled bit in the address area since // it may be blank when scrolling up (blank area avoids drawing partial address) CRect rct; GetDisplayRect(&rct); rct.top += yy; rct.bottom = rct.top + line_height_; rct.right = rct.left + addr_width_*text_width_; DoInvalidateRect(&rct); } } } void CHexEditView::AfterScroll(CPointAp newpos) { // If we have a compare view and we have synchronised scrolling then scroll to match if (pcv_ != NULL && display_.auto_scroll_comp) pcv_->SetScroll(newpos); } void CHexEditView::DoUpdateWindow() { if (!((CHexEditApp *)AfxGetApp())->refresh_off_) CScrView::DoUpdateWindow(); } void CHexEditView::DoHScroll(int total, int page, int pos) { if (((CHexEditApp *)AfxGetApp())->refresh_off_) { needs_hscroll_ = true; h_total_ = total; h_page_ = page; h_pos_ = pos; } else CScrView::DoHScroll(total, page, pos); } void CHexEditView::DoVScroll(int total, int page, int pos) { if (((CHexEditApp *)AfxGetApp())->refresh_off_) { needs_vscroll_ = true; v_total_ = total; v_page_ = page; v_pos_ = pos; } else CScrView::DoVScroll(total, page, pos); } void CHexEditView::DoUpdate() { if (needs_refresh_) { CScrView::DoInvalidate(); if (pav_ != NULL) pav_->Invalidate(); needs_refresh_ = false; CScrView::DoUpdateWindow(); } if (needs_hscroll_) { CScrView::DoHScroll(h_total_, h_page_, h_pos_); needs_hscroll_ = false; } if (needs_vscroll_) { CScrView::DoVScroll(v_total_, v_page_, v_pos_); needs_vscroll_ = false; } } // InvalidateRange - virtual function called from base class (CScrView) to cause redrawing of // the selection when it is changed due to mouse dragging or Shift+arrow keys. // When dragging with the mouse this function is called twice: // - once with f flag true and passing the whole selection // - once with f flag false and passing only the change in the selection void CHexEditView::InvalidateRange(CPointAp start, CPointAp end, bool f /*=false*/) { BOOL saved_edit_char = display_.edit_char; // Saved value of display_.edit_char FILE_ADDRESS start_addr, end_addr; // Range of addresses to invalidate // Work out what we are invalidating (hex or char area) if (display_.vert_display) ; // do nothing since edit_char does not affect pos2addr for vert_display else if (!display_.hex_area || (display_.char_area && pos_hex(start.x) == rowsize_ && pos_hex(end.x) == rowsize_)) display_.edit_char = TRUE; // Change display_.edit_char so pos2addr() works else display_.edit_char = FALSE; // Work out range to invalidate (WARNING: this relies on display_.edit_char) start_addr = pos2addr(start); end_addr = pos2addr(end); display_.edit_char = saved_edit_char; // Restore display_.edit_char if (theApp.show_other_) ++end_addr; else if (start_addr == end_addr) return; if (f) { // When dragging with the mouse the selected area in the hex view is only // invalidated in the part of the selection that actually changes - this // avoids the flickering which still occurs with kb (Shift+arrow) selection. // However, as the selectiop for the aerial view is drawn with a boundary // (marching ants) this leaves bits of the old boundary behind when increasing // the selection size by dragging the mouse. The f flag signals that the // whole of the selection (start_addr to end_addr) should be invalidated // in the aerial view. if (pav_ != NULL) pav_->InvalidateRange(start_addr, end_addr); } else { // Note: We need to invalidate an extra char backwards because in the hex // display area the white space to the right of the last byte selected is // not shown in reverse video. When the selection is extended towards the // end of file (causing InvalidateRange to be called) not only the newly // selected bytes need to be invalidated but also the previous one so that // the white area after the character is then drawn in reverse video. invalidate_hex_addr_range(start_addr-1, end_addr); // Also invalidate in aerial view so it can "undraw" the selection if it is smaller if (pav_ != NULL) pav_->InvalidateRange(start_addr, end_addr); } } // invalidate_addr_range is called when a part of the display may need redrawing: // - selection changed -> called from InvalidateRange // - focus lost/gained - so that selection can be drawn differently // - replacement of bytes in the document, perhaps in a different view // - insertion/deletion of bytes -> the changed bytes and those following need updating // - undo of changes // - background search finished -> occurrences need updating // - bookmark added or deleted, or bookmarks hidden/shown // - highlight added or highlights hidden/shown // - mark moved (including swap with cursor) -> old and new address // - undo of mark move, highlight etc // Invalidate all addresses in the range that are displayed in the hex view // and aerial view (if there is one). void CHexEditView::invalidate_addr_range(FILE_ADDRESS start_addr, FILE_ADDRESS end_addr) { if (pav_ != NULL) pav_->InvalidateRange(start_addr, end_addr); invalidate_hex_addr_range(start_addr, end_addr); } // Invalidate all of displayed addresses in hex view only void CHexEditView::invalidate_hex_addr_range(FILE_ADDRESS start_addr, FILE_ADDRESS end_addr) { CRect cli; // Client rectangle in device coords CRectAp inv; // The rectangle to actually invalidate (doc coords) CRectAp disp_rect; // Rectangle of display in our coords GetDisplayRect(&cli); disp_rect = ConvertFromDP(cli); // Work out the addresses of the first and (one past) the last byte in display FILE_ADDRESS start_disp = (disp_rect.top/line_height_)*rowsize_ - offset_; FILE_ADDRESS end_disp = (disp_rect.bottom/line_height_ + 1)*rowsize_ - offset_; // Reduce address range to relevant (displayed) area if (start_addr < start_disp) start_addr = start_disp; if (end_addr > end_disp) end_addr = end_disp; if (start_addr >= end_addr) return; // Nothing to invalidate or all outside display // Work out line range that needs invalidating FILE_ADDRESS start_line = (start_addr + offset_)/rowsize_; FILE_ADDRESS end_line = (end_addr + offset_)/rowsize_; // If start and end on the same line just invalidate between them if (start_line == end_line) { ASSERT(display_.hex_area || display_.char_area); if (!display_.vert_display && display_.hex_area) { // Note: (23/11/03) go back an extra text_width_ bytes to allow for // deletion mark (tracking changes) before the byte inv = CRectAp(hex_pos(int((start_addr+offset_)%rowsize_)) - text_width_, start_line * line_height_, hex_pos(int((end_addr+offset_)%rowsize_)) + 1, (start_line + 1) * line_height_ + 1); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); } if (display_.vert_display || display_.char_area) { // Note: (23/11/03) go back an extra 2 pixels to allow for // deletion mark (tracking changes) before the byte inv = CRectAp(char_pos(int((start_addr+offset_)%rowsize_)) - 2, start_line * line_height_, char_pos(int((end_addr+offset_)%rowsize_)) + 1, (start_line + 1) * line_height_ + 1); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); } return; } // Start line is before end line: invalidate partial lines at each end ASSERT(display_.hex_area || display_.char_area); if (!display_.vert_display && display_.hex_area) { // Hex area inv = CRectAp(hex_pos(int((start_addr+offset_)%rowsize_))-text_width_, start_line * line_height_, hex_pos(int(rowsize_)) + 1, (start_line + 1) * line_height_ + 1); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); inv = CRectAp(hex_pos(0)-text_width_, end_line * line_height_, hex_pos(int((end_addr+offset_)%rowsize_)) + 1, (end_line + 1) * line_height_ + 1); dev = ConvertToDP(inv); DoInvalidateRect(&dev); } if (display_.vert_display || display_.char_area) { // Char area or vert_display inv = CRectAp(char_pos(int((start_addr+offset_)%rowsize_))-2, start_line * line_height_, char_pos(int(rowsize_)), (start_line + 1) * line_height_); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); inv = CRectAp(char_pos(0)-2, end_line * line_height_, char_pos(int((end_addr+offset_)%rowsize_)), (end_line + 1) * line_height_); dev = ConvertToDP(inv); DoInvalidateRect(&dev); } // If more than one line between start and end then invalidate that block too if (start_line + 1 < end_line) { ASSERT(display_.hex_area || display_.char_area); if (!display_.vert_display && display_.hex_area) { inv = CRectAp(hex_pos(0)-text_width_, (start_line + 1) * line_height_, hex_pos(rowsize_) + 1, (end_line) * line_height_ + 1); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); } if (display_.vert_display || display_.char_area) { inv = CRectAp(char_pos(0)-2, (start_line + 1) * line_height_, char_pos(rowsize_) + 1, (end_line) * line_height_ + 1); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); } } } // Override CScrView::ValidateScroll() void CHexEditView::ValidateScroll(CPointAp &pos, BOOL strict /* =FALSE */) { CScrView::ValidateScroll(pos, strict); // Get search occurrences currently in display area whenever we change the scroll posn - // this saves checking all addresses (could be millions) in OnDraw search_pair_.clear(); if (GetDocument()->CanDoSearch() && theApp.pboyer_ != NULL) { CHexEditDoc *pdoc = GetDocument(); CRect cli; CRectAp rct; GetDisplayRect(&cli); rct = ConvertFromDP(cli); FILE_ADDRESS start, end; // range of file addresses within display // Get all occurrences that are within the display - this includes those // that have an address before the start of display but extend into it. start = (pos.y/line_height_)*rowsize_ - offset_ // First addr in display - (theApp.pboyer_->length() - 1); // Length of current search string - 1 if (start < 0) start = 0; // Just in case (prob not nec.) end = ((pos.y+rct.Height())/line_height_ + 1)*rowsize_ - offset_; std::vector<FILE_ADDRESS> sf = pdoc->SearchAddresses(start, end); search_length_ = theApp.pboyer_->length(); std::vector<FILE_ADDRESS>::const_iterator pp = sf.begin(); std::vector<FILE_ADDRESS>::const_iterator pend = sf.end(); pair<FILE_ADDRESS, FILE_ADDRESS> good_pair; if (pp != pend) { good_pair.first = *pp; good_pair.second = *pp + search_length_; while (++pp != pend) { if (*pp >= good_pair.second) { search_pair_.push_back(good_pair); good_pair.first = *pp; } good_pair.second = *pp + search_length_; } search_pair_.push_back(good_pair); } } } // Override CScrView::ValidateCaret() void CHexEditView::ValidateCaret(CPointAp &pos, BOOL inside /*=true*/) { // Ensure pos is a valid caret position or move it to the closest such one FILE_ADDRESS address = pos2addr(pos, inside); if (address < 0) address = 0; else if (address > GetDocument()->length()) address = GetDocument()->length(); if (display_.vert_display) { pos = addr2pos(address, pos2row(pos)); // All the following is to avoid problem of dragging a selection within the same "line" but // up a "row" and forward a column. This caused no selection to be drawn and the selection // tip to show a negative selection length. CPointAp start, end; // Current selection CPointAp base; // Base of current selection (initial point clicked) if (GetSel(start, end)) base = end; else base = start; // If we have a non-zero selection if (mouse_down_ && pos != base) pos = addr2pos(address, pos2row(base)); // Make end selection row same as start selection row } else pos = addr2pos(address); } void CHexEditView::DisplayCaret(int char_width /*= -1*/) { // If no character width given default to width of hex or char area text if (char_width == -1 && (display_.edit_char || display_.vert_display)) char_width = text_width_w_; else if (char_width == -1) char_width = text_width_; CScrView::DisplayCaret(char_width); // Since the window may be scrolled without the mouse even moving we // have to make sure that the byte addr/ruler highlight byte is updated. CPoint pt; ::GetCursorPos(&pt); // get mouse location (screen coords) ScreenToClient(&pt); set_mouse_addr(address_at(pt)); move_dlgs(); // scrolling may also have moved caret under a dialog } // Move the modeless dialogs if visible and it/they obscure the caret void CHexEditView::move_dlgs() { // Get doc size so we know width of visible area CSizeAp tt, pp, ll; // Size of document total,page,line GetSize(tt, pp, ll); // Get the selection so we can work out a rectangle bounding the selection CPointAp start, end; // Points of start/end of selection GetSel(start, end); CRectAp selrect; // Rect enclosing selection + a bit if (start.y == end.y) // No selection or all on a single line? selrect = CRectAp(start.x - 2*ll.cx, start.y - ll.cy, end.x + 3*ll.cx, end.y + 2*ll.cy); else selrect = CRectAp(0, start.y - ll.cy, // multi-line selection tt.cx, end.y + 2*ll.cy); // Get display rectangle (also in doc coords) CRect cli; GetDisplayRect(&cli); CRectAp doc_rect = ConvertFromDP(cli); // See if any of the selection is visible (intersect selection & display) CRectAp sd_rect; // selection that is visible if (!sd_rect.IntersectRect(doc_rect, selrect)) return; // Selection not in display // Get rect (selection visible in display) in screen (device) coords CRect dev_rect = ConvertToDP(sd_rect); ClientToScreen(&dev_rect); HideCaret(); // Tell mainframe to move all its dialog bars if (theApp.dlg_move_) ((CMainFrame *)theApp.m_pMainWnd)->move_bars(dev_rect); ShowCaret(); } // Move scroll or caret position in response to a key press. // Note that this overrides CScrView::MovePos(). BOOL CHexEditView::MovePos(UINT nChar, UINT nRepCnt, BOOL control_down, BOOL shift_down, BOOL caret_on) { // CScrView::MovePos scrolling behaviour is OK if (!caret_on) return CScrView::MovePos(nChar, nRepCnt, control_down, shift_down, caret_on); CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (aa->recording_) { long vv = nChar; if (control_down) vv |= 0x10000; if (shift_down) vv |= 0x20000; for (UINT ii = 0; ii < nRepCnt; ++ii) aa->SaveToMacro(km_key, vv); } FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); // Is selection base at end of selection? int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); FILE_ADDRESS new_address; CString desc("Cursor key"); // Start with start of (or end of, if moving forwards) current selection if (shift_down) { // Work out which end of selection is being extended if (end_base) new_address = start_addr; else new_address = end_addr; ++shift_moves_; } else if (start_addr == end_addr ) new_address = start_addr; // No current selection else if (nChar == VK_DOWN || nChar == VK_NEXT) new_address = end_addr; // Move from char after selection else if (nChar == VK_RIGHT || nChar == VK_END) new_address = end_addr - 1; // Move from last char of selection else new_address = start_addr; // Move from start of selection CSizeAp tt, pp, ll; // Size of document total,page,line switch (nChar) { case VK_LEFT: if (control_down) { desc = "Ctrl + Left Arrow"; // Work out how many groups there are to start of file long gpr = (rowsize_ - 1)/group_by_ + 1; // groups per row FILE_ADDRESS groups = ((new_address+offset_)/rowsize_) * gpr + ((new_address+offset_)%rowsize_ + group_by_ - 1)/group_by_; // Calculate the group to move to and address of 1st byte groups -= nRepCnt; new_address = (groups/gpr) * rowsize_ - offset_ + (groups%gpr) * group_by_; } else { desc = "Left Arrow"; new_address -= nRepCnt; } break; case VK_RIGHT: if (control_down) { desc = "Ctrl + Right Arrow"; // First work out how many groups there are to start of file long gpr = (rowsize_ - 1)/group_by_ + 1; // groups per row FILE_ADDRESS groups = ((new_address+offset_)/rowsize_) * gpr + ((new_address+offset_)%rowsize_)/group_by_; // Calculate the group to move to groups += nRepCnt; new_address = (groups/gpr) * rowsize_ - offset_ + (groups%gpr) * group_by_; } else { desc = "Right Arrow"; new_address += nRepCnt; } break; case VK_UP: desc = "Up Arrow"; if (display_.vert_display && !shift_down) { new_address -= rowsize_ * ((2 - row + nRepCnt)/3); row = (3333 + row - nRepCnt)%3; // Add a large number div. by 3 to make sure % operand is +ve } else new_address -= rowsize_ * nRepCnt; break; case VK_DOWN: desc = "Down Arrow"; if (display_.vert_display && !shift_down) { new_address += rowsize_ * ((row + nRepCnt)/3); row = (row + nRepCnt)%3; } else new_address += rowsize_ * nRepCnt; break; case VK_HOME: if (control_down) { desc = "Ctrl + Home key "; // space at end means significant nav pt new_address = 0; } else { desc = "Home key"; new_address = ((new_address+offset_)/rowsize_) * rowsize_ - offset_; } break; case VK_END: if (control_down) { desc = "Ctrl + End key "; // space at end means significant nav pt new_address = GetDocument()->length(); } else { desc = "End key"; new_address = ((new_address+offset_)/rowsize_ + 1) * rowsize_ - offset_ - (shift_down ? 0 : 1); } break; case VK_PRIOR: desc = "Page Up"; GetSize(tt, pp, ll); new_address -= rowsize_ * (pp.cy/line_height_) * nRepCnt; break; case VK_NEXT: desc = "Page Down"; GetSize(tt, pp, ll); new_address += rowsize_ * (pp.cy/line_height_) * nRepCnt; break; default: return CScrView::MovePos(nChar, nRepCnt, control_down, shift_down, caret_on); } if (new_address < 0) { new_address = 0; row = 0; aa->mac_error_ = 2; } else if (new_address > GetDocument()->length()) { new_address = GetDocument()->length(); if (display_.vert_display && !shift_down) row = 2; aa->mac_error_ = 2; } // Scroll addresses into view if moved to left column of hex area or // left column of char area when no hex area displayed if ((new_address + offset_) % rowsize_ == 0 && (display_.vert_display || !display_.edit_char || !display_.hex_area)) SetScroll(CPointAp(0,-1)); if (shift_down && end_base) { MoveWithDesc("Shift + " + desc, end_addr, new_address); // Handle this when shift key released now (in OnKeyUp) // if (aa->highlight_) // add_highlight(new_address, end_addr, TRUE); } else if (shift_down) { MoveWithDesc("Shift + " + desc, start_addr, new_address); // Handle this when shift key released now (in OnKeyUp) // if (aa->highlight_) // add_highlight(start_addr, new_address, TRUE); } else MoveWithDesc(desc, new_address, -1, -1, -1, FALSE, FALSE, row); return TRUE; // Indicate that keystroke used } // Move the caret to new position (or as close as possible). // Returns the new position which may be diff to the requested position if // the requested position was invalid (past EOF). // Note: Does not update address in tool bar combo (use show_pos(GetPos()), // or make sure the caret within display, and does not save undo info. FILE_ADDRESS CHexEditView::GoAddress(FILE_ADDRESS start_addr, FILE_ADDRESS end_addr /*=-1*/) { // Get row from top 2 bits of start_address (vert_display mode) int row = int(start_addr>>62) & 0x3; start_addr &= 0x3fffFFFFffffFFFF; if (end_addr < 0 || end_addr > GetDocument()->length()) end_addr = start_addr; if (start_addr < 0 || start_addr > GetDocument()->length()) start_addr = end_addr = GetDocument()->length(); ASSERT(row == 0 || (row < 3 && display_.vert_display && start_addr == end_addr)); SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); return start_addr; } // Move the caret to new position updating everything: // - saves previous position in undo array (if caret is actually moved) // - updates the display address in the tool bar address edit controls // - Makes sure the caret is visible within display // - astart/aend = new selection (if aend = -1 or aend=astart then just sets caret) // - pstart/pend = previous selection to be saved in undo list (if they are // -1 it uses the current selection/caret) // - ptoo = when undo info saved combine it with previous operation (used if the move is part of a larger operation) // - no_dffd = don't sync DFFD view (if any) even in sync mode (avoids inf. mutually recursive calls) // - row = stacked mode row (0 to 2) - only important when setting caret not for block selection (includes all rows) // - desc = describes why a move was made (eg Bookmark, Search) so that info can be given in nav point list void CHexEditView::MoveToAddress(FILE_ADDRESS astart, FILE_ADDRESS aend /*=-1*/, FILE_ADDRESS pstart /*=-1*/, FILE_ADDRESS pend /*=-1*/, BOOL ptoo /*=FALSE*/, BOOL no_dffd /*=FALSE*/, int row /*=0*/, LPCTSTR desc /*=NULL*/) { ASSERT((astart & ~0x3fffFFFFffffFFFF) == 0); // Make sure top 2 bits not on ASSERT(pstart == -1 || (pstart & ~0x3fffFFFFffffFFFF) == 0); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing since caret moved if (astart < 0 || astart > GetDocument()->length()) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); char buf[128]; sprintf(buf, "Attempt to jump to invalid address %I64d\r" "Jump to EOF instead and continue?", __int64(astart)); if (AfxMessageBox(buf, MB_OKCANCEL) != IDOK) { aa->mac_error_ = 10; return; } else aa->mac_error_ = 1; astart = GetDocument()->length(); } if (aend < 0 || aend > GetDocument()->length()) aend = astart; ASSERT(pstart >= -1 && pstart <= GetDocument()->length()); ASSERT(pend >= pstart && pend <= GetDocument()->length()); int prow = 0; // Row of cursor if vert_display mode if (pstart < 0 || pstart > GetDocument()->length() || pend < pstart || pend > GetDocument()->length()) { GetSelAddr(pstart, pend); if (pstart == pend && display_.vert_display) prow = pos2row(GetCaret()); } // Is the caret/selection now in a different position if (astart != pstart || aend != pend || row != prow) { // Move the caret/selection (THIS IS THE IMPORTANT BIT) SetSel(addr2pos(astart, row), addr2pos(aend, row), true); // Now check if we are just reversing an operation and we should just remove previous undo if (theApp.intelligent_undo_ && // intelligent undo is turned on astart == aend && // not a selection undo_.size() > 0 && // there is an undo op on the stack undo_.back().utype == undo_move && // previous op was a move !undo_.back().previous_too && // and not part of another operation undo_.back().address == (astart | (FILE_ADDRESS(row)<<62))) // and same address/row { undo_.pop_back(); } else { undo_.push_back(view_undo(undo_move, ptoo)); // Save move in undo array undo_.back().address = pstart | (FILE_ADDRESS(prow)<<62); if (pstart != pend) { undo_.push_back(view_undo(undo_sel, ptoo)); // Save selection end in undo array undo_.back().address = pend; } } nav_save(astart, aend, desc); show_prop(); // Update prop modeless dlg show_calc(); show_pos(-1, no_dffd); // Update tool bar } DisplayCaret(); // Make sure caret is in the display } void CHexEditView::SetSel(CPointAp start, CPointAp end, bool base1 /*= false*/) { if (theApp.hl_caret_) { FILE_ADDRESS old_addr, end_addr, new_addr; BOOL end_base = GetSelAddr(old_addr, end_addr); // Get current caret before CScrView::SetSel moves it //if (end_base) old_addr = end_addr; CScrView::SetSel(start, end, base1); new_addr = pos2addr(start); if (old_addr != new_addr) { invalidate_addr(old_addr); invalidate_addr(new_addr); invalidate_ruler(old_addr); invalidate_ruler(new_addr); } } else CScrView::SetSel(start, end, base1); } void CHexEditView::set_mouse_addr(FILE_ADDRESS addr) { if (!theApp.hl_mouse_ || addr == mouse_addr_) return; // no change so do nothing FILE_ADDRESS old_addr = mouse_addr_; mouse_addr_ = addr; invalidate_addr(old_addr); invalidate_ruler(old_addr); invalidate_addr(addr); invalidate_ruler(addr); if (addr > - 1) track_mouse(TME_LEAVE); // make sure we get a leave event when the mouse is moved outside } // Invalidate part of ruler related to an address void CHexEditView::invalidate_ruler(FILE_ADDRESS addr) { if (!theApp.ruler_) return; int horz = bdr_left_ - GetScroll().x; // Offset of left side of doc from left side of window CRect rct; rct.top = 0; rct.bottom = bdr_top_; if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(int((addr+offset_)%rowsize_)) + horz; rct.right = hex_pos(int((addr+offset_)%rowsize_)+1) + horz; DoInvalidateRect(&rct); } if (display_.vert_display || display_.char_area) { rct.left = char_pos(int((addr+offset_)%rowsize_)) + horz; rct.right = char_pos(int((addr+offset_)%rowsize_)+1) + horz + 1; DoInvalidateRect(&rct); } } #ifdef RULER_ADJUST // Invalidate part of ruler related to an address void CHexEditView::invalidate_adjuster(int col) { if (col < 0) return; CRect rct(-1, 0, -1, 30000); if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(col) - scrollpos_.x; rct.right = rct.left + 4; rct.left -= 7; if (col%group_by_ == 0) rct.left -= text_width_; InvalidateRect(&rct); // DoInvalidateRect not nec. as we can't be in a macro?? } if (display_.vert_display || display_.char_area) { rct.left = char_pos(col) - scrollpos_.x; rct.right = rct.left + 4; rct.left -= 7; if (display_.vert_display && col%group_by_ == 0) rct.left -= text_width_w_/2; InvalidateRect(&rct); } } #endif // Invalidate address area based on an address void CHexEditView::invalidate_addr(FILE_ADDRESS addr) { CRect rct; GetDisplayRect(&rct); CRectAp doc_rect = ConvertFromDP(rct); CRect addr_rect; addr_rect.left = bdr_left_; addr_rect.right = bdr_left_ - doc_rect.left + addr_width_*text_width_ - text_width_/2; // If moved and the address area is visible ... if (addr_rect.right <= addr_rect.left) return; // Address area is off window to the left FILE_ADDRESS first_disp = (doc_rect.top/line_height_) * rowsize_ - offset_; FILE_ADDRESS last_disp = (doc_rect.bottom/line_height_ + 1) * rowsize_ - offset_; if (addr >= first_disp && addr < last_disp) { addr_rect.top = int(bdr_top_ - doc_rect.top + addr2pos(addr).y); addr_rect.bottom = addr_rect.top + text_height_; DoInvalidateRect(&addr_rect); } } void CHexEditView::nav_save(FILE_ADDRESS astart, FILE_ADDRESS aend, LPCTSTR desc) { if (theApp.navman_.InMove()) return; // Check if we have moved enough to store a nav pt bool save_nav = false; // Is this a significant enough move to record in nav stack? bool significant = desc != NULL && desc[strlen(desc)-1] == ' '; // Important nav pts have space at end of desc ++nav_moves_; // The number of rows to move before adding a new nav pt (for significant and insignificant events) FILE_ADDRESS significant_rows = 2; FILE_ADDRESS insignificant_rows = 20; //insignificant_rows = win_size_.cy / line_height_ / 2; // Note: The below checks if the caret has moved more than half a page AND the display has // scrolled. BUT if desc is not NULL (a description was supplied) then this is some sort of // significant event (search, jump to bookmark etc) so keep even if just moved > 2 lines. // Check if the start of selection has moved significantly FILE_ADDRESS curr_line = (astart + offset_)/rowsize_; FILE_ADDRESS prev_line = (nav_start_ + offset_)/rowsize_; if (!significant && mac_abs(curr_line - prev_line) > insignificant_rows || significant && mac_abs(curr_line - prev_line) > significant_rows) { save_nav = true; } // Now do the same test on selection end address curr_line = (aend + offset_)/rowsize_; prev_line = (nav_end_ + offset_)/rowsize_; if (!significant && mac_abs(curr_line - prev_line) > insignificant_rows || significant && mac_abs(curr_line - prev_line) > significant_rows) { save_nav = true; } // If we haven't scrolled vertically yet don't add nav point (unless significant) if (!significant && nav_scroll_ == (GetScroll().y/line_height_)*rowsize_ - offset_) save_nav = false; if (save_nav) { nav_start_ = astart; nav_end_ = aend; nav_scroll_ = (GetScroll().y/line_height_)*rowsize_ - offset_; // If no descripition given work out something from the file if (desc == NULL) desc = "Move"; // Save nav pt in the stack theApp.navman_.Add(desc, get_info(), this, nav_start_, nav_end_, nav_scroll_); } } // Get a bit of the file (as hex or text) to save with a nav point CString CHexEditView::get_info() { FILE_ADDRESS start = nav_start_; if (start >= GetDocument()->length()) { return CString("End\nof\r\nfile"); } if (display_.vert_display && pos2row(GetCaret()) == 0 || display_.edit_char) { // Take a sample of the file as text char buf[36]; char *pp = buf; FILE_ADDRESS aa, end; unsigned char cc = '\0'; end = start + 30; if (end > GetDocument()->length()) end = GetDocument()->length(); // Just use the selection if it is short enough if (start != nav_end_ && nav_end_ < end) end = nav_end_; for (aa = start; aa < end; ++aa) { GetDocument()->GetData(&cc, 1, aa); if (display_.char_set != CHARSET_EBCDIC) { if (isprint(cc)) *pp++ = cc; else goto hex_info; } else { if (e2a_tab[cc] != '\0') *pp++ = e2a_tab[cc]; else goto hex_info; } } *pp = '\0'; if (aa < GetDocument()->length()) strcat(pp, "..."); return CString(buf); } hex_info: { // Take a sample of the file as hex char buf[36]; char *pp = buf; FILE_ADDRESS aa, end; unsigned char cc = '\0'; end = start + 10; if (end > GetDocument()->length()) end = GetDocument()->length(); // Just use the selection if it is short enough if (start != nav_end_ && nav_end_ < end) end = nav_end_; for (aa = start; aa < end; ++aa) { GetDocument()->GetData(&cc, 1, aa); if (theApp.hex_ucase_) sprintf(pp, "%2.2X ", cc); else sprintf(pp, "%2.2x ", cc); pp += 3; } if (aa < GetDocument()->length()) strcat(pp, "..."); return CString(buf); } } #if 0 // This saves a move in the undo array for the caret position when focus // was last lost. This is used by the tool bar address edit controls to // add to the undo list when they move the address of the caret. void CHexEditView::SaveMove() { undo_.push_back(view_undo(undo_move)); undo_.back().address = saved_start_ | (FILE_ADDRESS(saved_row_)<<62); if (saved_start_ != saved_end_) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = saved_end_; } } #endif // Convert an address to a document position CPointAp CHexEditView::addr2pos(FILE_ADDRESS address, int row /*=0*/) const { ASSERT(row == 0 || (display_.vert_display && row < 3)); address += offset_; if (display_.vert_display) return CPointAp(char_pos(int(address%rowsize_)), (address/rowsize_) * line_height_ + row * text_height_); else if (display_.edit_char) return CPointAp(char_pos(int(address%rowsize_)), address/rowsize_ * line_height_); else if ((num_entered_ % 2) == 0) return CPointAp(hex_pos(int(address%rowsize_)), address/rowsize_ * line_height_); else return CPointAp(hex_pos(int(address%rowsize_)) + 2*text_width_, address/rowsize_ * line_height_); } FILE_ADDRESS CHexEditView::pos2addr(CPointAp pos, BOOL inside /*=true*/) const { FILE_ADDRESS address; address = (pos.y/line_height_)*rowsize_ - offset_; if (display_.vert_display || display_.edit_char) address += pos_char(pos.x, inside); else address += pos_hex(pos.x + text_width_/2, inside); return address; } // Given a point in doc coords returns which of the 3 rows of the line the point is in // Note that in vert_display mode row 0 = char, row 1 = top nybble, row 2 = bottom nybble int CHexEditView::pos2row(CPointAp pos) { ASSERT(display_.vert_display); ASSERT((pos.y%line_height_)/text_height_ < 3); return int((pos.y%line_height_)/text_height_); } // Update property display if visible // address = address of byte(s) to show properties of // = -1 to use the current cursor address // = -2 to update even when refresh off (using current cursor address) void CHexEditView::show_prop(FILE_ADDRESS address /*=-1*/) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (address != -2 && aa->refresh_off_) return; CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (address < 0) address = GetPos(); mm->m_wndProp.Update(this, address); } void CHexEditView::show_calc() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!aa->refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); } // Update hex and decimal address tools in edit bar // address = address to show in the address tools // = -1 to use the current cursor address // = -2 to update even when refresh off (using current cursor address) void CHexEditView::show_pos(FILE_ADDRESS address /*=-1*/, BOOL no_dffd /*=FALSE*/) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (address != -2 && aa->refresh_off_) return; CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); CString ss; // String to hold text of edit box FILE_ADDRESS end; if (address < 0) GetSelAddr(address, end); else end = address; #if 0 // BCG (this is handled by calls to AfxGetApp()->OnIdle(0) in searches/compares) // Set the hex address edit box if (aa->hex_ucase_) ss.Format("%lX", address); else ss.Format("%lx", address); mm->hec_hex_addr_.SetWindowText(ss); mm->hec_hex_addr_.add_spaces(); mm->hec_hex_addr_.UpdateWindow(); // Force immed. redraw // Set the decimal address edit box ss.Format("%lu", address); mm->dec_dec_addr_.SetWindowText(ss); mm->dec_dec_addr_.add_commas(); mm->dec_dec_addr_.UpdateWindow(); // Force immed. redraw #else // TRACE1("---- Address set to %ld\n", long(address)); ((CMainFrame *)AfxGetMainWnd())->SetAddress(address); // for ON_UPDATE_COMMAND_UI to fix displayed addresses #endif // Move to corresponding place in other views if sync on if (pdfv_ != NULL && !no_dffd && display_.auto_sync_dffd) pdfv_->SelectAt(address); if (pav_ != NULL && display_.auto_sync_aerial) pav_->ShowPos(address); if (pcv_ != NULL && display_.auto_sync_comp) pcv_->MoveToAddress(address, end); } ///////////////////////////////////////////////////////////////////////////// // CHexEditView diagnostics #ifdef _DEBUG void CHexEditView::AssertValid() const { CScrView::AssertValid(); } void CHexEditView::Dump(CDumpContext& dc) const { dc << "\nrowsize_ = " << rowsize_; dc << "\ntext_height_ = " << text_height_; dc << "\ntext_width_ = " << text_width_; dc << "\nmark_ = " << long(mark_); dc << " mark_char_ = " << display_.mark_char; dc << "\nedit_char_ = " << display_.edit_char; dc << "\novertype_ = " << display_.overtype; dc << "\nreadonly_ = " << display_.readonly; dc << "\nsaved_start_/end_ = " << long(saved_start_) << " " << long(saved_end_); std::vector <view_undo, allocator<view_undo> >::const_iterator pu; for (pu = undo_.begin(); pu != undo_.end(); ++pu) { dc << "\nutype = " << (*pu).utype; switch (pu->utype) { case undo_move: dc << " MOVE from " << long((*pu).address); break; case undo_sel: dc << " SELECTION to " << long((*pu).address); break; case undo_change: dc << " DOC CHANGE this view = " << (*pu).flag; dc << " index = " << (*pu).index; break; case undo_font: dc << " FONT CHANGE "; break; case undo_setmark: dc << " MARK SET address = " << long((*pu).address); break; case undo_rowsize: dc << " ROW SIZE = " << (*pu).rowsize; break; case undo_group_by: dc << " GROUP BY = " << (*pu).rowsize; break; case undo_offset: dc << " OFFSET = " << (*pu).rowsize; break; case undo_unknown: dc << " UNKNOWN"; break; default: dc << " NOT RECOGNISED"; break; } } CScrView::Dump(dc); } CHexEditDoc* CHexEditView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CHexEditDoc))); return (CHexEditDoc*)m_pDocument; } #endif //_DEBUG // Get child frame window of this view. This may be the parent if there are no splitters, // or it may be a more distant ancestor if the immediate parent is a splitter. // This could possibly return NULL but I'm not sure why. CChildFrame *CHexEditView::GetFrame() const { CWnd *pp = GetParent(); while (pp != NULL && !pp->IsKindOf(RUNTIME_CLASS(CChildFrame))) pp = pp->GetParent(); ASSERT_KINDOF(CChildFrame, pp); return (CChildFrame *)pp; } ///////////////////////////////////////////////////////////////////////////// // CHexEditView message handlers BOOL CHexEditView::OnEraseBkgnd(CDC* pDC) { if (bg_col_ == -1) return CScrView::OnEraseBkgnd(pDC); CRect rct; GetClientRect(rct); // Fill background with bg_col_ CBrush backBrush; backBrush.CreateSolidBrush(bg_col_); backBrush.UnrealizeObject(); pDC->FillRect(rct, &backBrush); // Get rect for address area rct.right = addr_width_*text_width_ - GetScroll().x - text_width_ + bdr_left_; // If address area is visible and address background is different to normal background ... if (rct.right > rct.left && addr_bg_col_ != bg_col_) { // Draw address background too CBrush addrBrush; addrBrush.CreateSolidBrush(addr_bg_col_); addrBrush.UnrealizeObject(); pDC->FillRect(rct, &addrBrush); } if (theApp.ruler_ && addr_bg_col_ != bg_col_) { // Ruler background GetClientRect(rct); rct.bottom = bdr_top_ - 4; CBrush addrBrush; addrBrush.CreateSolidBrush(addr_bg_col_); addrBrush.UnrealizeObject(); pDC->FillRect(rct, &addrBrush); } #ifdef _DEBUG // Draw the location of the borders to make sure nothing's drawn outside GetClientRect(rct); CPen *psaved, pen(PS_SOLID, 1, RGB(255,0,0)); psaved = pDC->SelectObject(&pen); CPoint pt; pt.x = rct.right - bdr_right_;pt.y = bdr_top_ - 1; pDC->MoveTo(pt); pt.y = rct.bottom - bdr_bottom_; pDC->LineTo(pt); pt.x = bdr_left_ - 1; pDC->LineTo(pt); pt.y = bdr_top_ - 1; pDC->LineTo(pt); pDC->SelectObject(psaved); #endif return TRUE; } void CHexEditView::OnSize(UINT nType, int cx, int cy) { if (cx == 0 && cy == 0 || in_recalc_display) { CScrView::OnSize(nType, cx, cy); return; } num_entered_ = num_del_ = num_bs_ = 0; // Can't be editing while mousing if (display_.autofit && text_height_ > 0) { if (pcv_ != NULL) pcv_->begin_change(); // This is to try to stay at the same part of the file when in // autofit mode and we get multiple consecutive resize events if (resize_start_addr_ == -1 || resize_curr_scroll_ != GetScroll().y) resize_start_addr_ = pos2addr(GetScroll()); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); recalc_display(); CPointAp pt = addr2pos(resize_start_addr_); pt.x = 0; SetScroll(pt); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); } else recalc_display(); CScrView::OnSize(nType, cx, cy); // Make sure we show all visible search occurrences for the new window size ValidateScroll(GetScroll()); resize_curr_scroll_ = GetScroll().y; // Save current pos so we can check if we are at the same place later } void CHexEditView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CScrView::OnHScroll(nSBCode, nPos, pScrollBar); if (nSBCode != SB_THUMBTRACK) ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_hscroll, (nSBCode << 16) | nPos); } void CHexEditView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CScrView::OnVScroll(nSBCode, nPos, pScrollBar); if (nSBCode != SB_THUMBTRACK) ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_vscroll, (nSBCode << 16) | nPos); } BOOL CHexEditView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { BOOL retval; // As the address under the mouse will probably change we need to get // rid of the tip window which shows info about the byte under the mouse. tip_.Hide(0); if (last_tip_addr_ != -1) { FILE_ADDRESS addr = last_tip_addr_; last_tip_addr_ = -1; invalidate_hex_addr_range(addr, addr+1); } #ifdef RULER_ADJUST ruler_tip_.Hide(0); #endif if ((nFlags & MK_CONTROL) != 0) { // Ctrl+ mouse wheel zooms in/out bool zoomIn = zDelta > 0; if (theApp.reverse_zoom_) zoomIn = !zoomIn; if (zoomIn) OnFontInc(); else OnFontDec(); retval = TRUE; } else retval = CScrView::OnMouseWheel(nFlags, zDelta, pt); if (theApp.hl_mouse_) { // Since the window may be scrolled without the mouse even moving we // have to make sure that the byte addr/ruler highlight byte is updated. CPoint point; ::GetCursorPos(&point); // get mouse location (screen coords) ScreenToClient(&point); set_mouse_addr(address_at(point)); } return retval; } void CHexEditView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { if (mouse_down_ && drag_bookmark_ > -1 && nChar == 27) { // Escape key aborts bookmark drag drag_bookmark_ = -1; mouse_down_ = false; invalidate_addr_range(drag_address_, drag_address_+1); // remove current drag position } else if ((nFlags & 0x2100) == 0) { for (UINT ii = 0; ii < nRepCnt; ++ii) do_char(nChar); } else CScrView::OnChar(nChar, nRepCnt, nFlags); } void CHexEditView::do_char(UINT nChar) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Test if edit key (not special key and not BS, ^\ or nul) // Note: nul byte is just ignored and ^\ is only used in debug version if (strchr("\b\034\0", nChar) == NULL) { unsigned char cc = '\0'; num_del_ = num_bs_ = 0; // We're not deleting // Warn of a number of different problems if (( display_.vert_display && row > 0 || !display_.vert_display && !display_.edit_char) && !isxdigit(nChar)) { // Non hex digit typed in hex area #ifdef SYS_SOUNDS if (!CSystemSound::Play("Invalid Character")) #endif ::Beep(5000,200); aa->mac_error_ = 5; return; } if (( display_.vert_display && row == 0 || !display_.vert_display && display_.edit_char) && display_.char_set == CHARSET_EBCDIC && (nChar > 128 || a2e_tab[nChar] == 0)) { AfxMessageBox("The key is not a valid EBCDIC character"); aa->mac_error_ = 10; return; } if (check_ro("edit")) return; if (display_.overtype && start_addr != end_addr) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("This will delete the current selection\r" "which is not allowed in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && start_addr == GetDocument()->length()) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("You can't extend this file while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 5; return; } else if (!do_insert()) return; } if ((num_entered_ % 2) == 0) DisplayCaret(); // Make sure start is visible // If there is a selection then delete it if (start_addr != end_addr) { ASSERT(start_addr >= 0 && end_addr <= GetDocument()->length() && start_addr < end_addr); GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); } if ( display_.vert_display && row == 0 || !display_.vert_display && display_.edit_char) { // In char area so insert/replace char at this curr locn if (display_.char_set == CHARSET_EBCDIC && nChar < 128) cc = a2e_tab[nChar]; else if (display_.char_set == CHARSET_EBCDIC) cc = '\0'; else cc = (unsigned char)nChar; GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this, start_addr != end_addr); // Move the caret to the next char ++start_addr; num_entered_ += 2; // One char == 2 nybbles } else if (display_.vert_display && row == 1) { ASSERT((num_entered_ % 2) == 0); // Convert to hex and store in top nybble cc = '\0'; if (start_addr < GetDocument()->length()) { // If not at end of doc then get nybble to shift size_t got = GetDocument()->GetData(&cc, 1, start_addr); ASSERT(got == 1); } cc = (cc & 0x0F) | ((isdigit(nChar) ? nChar - '0' : toupper(nChar) - 'A' + 10) << 4); GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this, start_addr != end_addr); // Move to bottom nybble row = 2; ++num_entered_; } else if (display_.vert_display && row == 2) { // Bottom nybble cc = '\0'; if (start_addr < GetDocument()->length()) { // If not at end of doc then get nybble to shift size_t got = GetDocument()->GetData(&cc, 1, start_addr); ASSERT(got == 1); // Check if started entering values on 2nd (bottom) nybble if (num_entered_ == 0) { // Fake entry of first (top nybble) GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this); ++num_entered_; } ASSERT((num_entered_ % 2) != 0); } cc = (cc & 0xF0) | (isdigit(nChar) ? nChar - '0' : toupper(nChar) - 'A' + 10); GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this); // Move to first nybble of next byte start_addr++; row = 1; ++num_entered_; } else if ((num_entered_ % 2) == 0) { // First nybble entered - convert hex to low nybble cc = isdigit(nChar) ? nChar - '0' : toupper(nChar) - 'A' + 10; GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this, start_addr != end_addr); ++num_entered_; } else { // 2nd nybble - shift over 1st nybble and add this nybble cc = '\0'; if (start_addr < GetDocument()->length()) { // If not at end of doc then get nybble to shift size_t got = GetDocument()->GetData(&cc, 1, start_addr); ASSERT(got == 1); } cc = (cc << 4) + (isdigit(nChar) ? nChar - '0' : toupper(nChar) - 'A' + 10); GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this); // Move the caret to the next byte ++start_addr; ++num_entered_; } SetCaret(addr2pos(start_addr, row)); show_prop(); // Current char under caret may have changed so update prop dlg show_calc(); show_pos(); // Update tool bar if ((num_entered_ % 2) == 0) DisplayCaret(); // Make sure end is visible } #if 0 else if (nChar == '\f') // ^L - centre caret and redraw { CRect cli; // Work out window height in logical units GetDisplayRect(&cli); CRectAp doc_rect = ConvertFromDP(cli); // Move display so that caret is centred vertically CPointAp pp = GetCaret(); pp.x = 0; // Scroll to left side (but see DisplayCaret() below) if ((pp.y -= (doc_rect.bottom-doc_rect.top)/2) < 0) pp.y = 0; SetScroll(pp); DoInvalidate(); // Also redraw display DisplayCaret(); // Make sure caret not off right side } else if (nChar == '\t' && !display_.vert_display && display_.char_area && display_.hex_area) { // Allow tab between hex and char areas if they are both visible num_entered_ = num_del_ = num_bs_ = 0; // Turn off any consec edits // TAB key swaps between hex and char areas FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); undo_.push_back(view_undo(undo_state)); undo_.back().disp_state = disp_state_; display_.edit_char = !display_.edit_char; if (end_base) SetSel(addr2pos(end_addr), addr2pos(start_addr), true); else SetSel(addr2pos(start_addr), addr2pos(end_addr)); DisplayCaret(); } else if (nChar == '\025') // ^U - scroll up { CPointAp pp = GetScroll(); pp.y -= text_height_; SetScroll(pp); } else if (nChar == '\004') // ^D - scroll down { CPointAp pp = GetScroll(); pp.y += text_height_; SetScroll(pp); } else if (nChar == '\r') { num_entered_ = num_del_ = num_bs_ = 0; // Turn off any consec edits FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Check if offset has actually changed if (real_offset_ != (rowsize_ - start_addr%rowsize_)%rowsize_) { undo_.push_back(view_undo(undo_offset)); undo_.back().rowsize = real_offset_; // Save previous offset for undo real_offset_ = offset_ = (rowsize_ - start_addr%rowsize_)%rowsize_; SetSel(addr2pos(start_addr), addr2pos(end_addr)); recalc_display(); DoInvalidate(); } else { ((CMainFrame *)AfxGetMainWnd())-> StatusBarText("Warning: offset not changed"); aa->mac_error_ = 1; } } #endif else if (nChar == '\b') // Back space { // Warn if view is read only if (check_ro("backspace")) return; if (start_addr != end_addr) { // There is a selection - back space just deletes it if (display_.overtype) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("This will delete the current selection\r" "which is not allowed in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 5; return; } else if (!do_insert()) return; } ASSERT(start_addr >= 0 && end_addr <= GetDocument()->length() && start_addr < end_addr); GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); } else { // Back space deletes/replaces previous byte if ((num_entered_ % 2) != 0) // Check if in middle of byte entry ++start_addr; if (start_addr < 1) // We can't back space at the start of file { aa->mac_error_ = 2; return; } start_addr--; // Work out the address of the byte to delete if (!display_.overtype) { // Delete previous char GetDocument()->Change(mod_delback, start_addr, 1, NULL, num_bs_, this); num_bs_ += 2; } else { // Replace previous char in OVR mode with space or nul byte unsigned char cc; if ( display_.vert_display && row == 0 || !display_.vert_display && display_.edit_char) { // Use EBCDIC or ASCII space cc = display_.char_set == CHARSET_EBCDIC ? 0x40 : 0x20; GetDocument()->Change(mod_repback, start_addr, 1, &cc, num_bs_, this); } else { ASSERT(display_.hex_area); cc = '\0'; GetDocument()->Change(mod_repback, start_addr, 1, &cc, num_bs_, this); } ++num_bs_; } } num_del_ = num_entered_ = 0; // turn off any byte entry // Move the caret SetCaret(addr2pos(start_addr)); show_prop(); // New char - check props show_calc(); show_pos(); // Update tool bar DisplayCaret(); // Make sure caret is visible } #ifdef _DEBUG else if (nChar == '\034') { // Just delay for 3 seconds timer tt(true); // This loop is (hopefully) not optimised away in debug mode (optimisations off) while (tt.elapsed () < 2) ; ((CMainFrame *)AfxGetMainWnd())->StatusBarText("Ctrl+\\"); } #endif aa->SaveToMacro(km_char, nChar); } void CHexEditView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { if (nChar >= VK_PRIOR && nChar <= VK_DELETE) { // Cursor movement - reset consec. entered count num_entered_ = num_del_ = num_bs_ = 0; CPointAp start, end; if (GetSel(start, end)) SetSel(end, start, true); else SetSel(start, end); // Calls ValidateCaret - causing caret selection to be moved to valid locations } CScrView::OnKeyDown(nChar, nRepCnt, nFlags); if (nChar == VK_SHIFT && (nFlags & 0x4000) == 0) { // Key down and not autorepeat reset_tip(); shift_moves_ = 0; } update_sel_tip(); // Also make sure info tip is hidden if (nChar != VK_SHIFT) { tip_.Hide(0); // hide immediately if (last_tip_addr_ != -1) { FILE_ADDRESS addr = last_tip_addr_; last_tip_addr_ = -1; invalidate_hex_addr_range(addr, addr+1); } } #ifdef RULER_ADJUST ruler_tip_.Hide(0); #endif } void CHexEditView::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { CScrView::OnKeyUp(nChar, nRepCnt, nFlags); if (nChar == VK_SHIFT) { update_sel_tip(); // Make sure window hidden when shift released if (theApp.highlight_ && shift_moves_) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); add_highlight(start_addr, end_addr, TRUE); } } } void CHexEditView::OnKillFocus(CWnd* pNewWnd) { if (pav_ != NULL && IsWindow(pav_->m_hWnd)) pav_->StopTimer(); // Turn off any animation in aerial view CScrView::OnKillFocus(pNewWnd); if (text_height_ == 0) return; // Save current address in case edit controls move caret GetSelAddr(saved_start_, saved_end_); // CScrView::OnKillFocus(pNewWnd); if (GetView() == NULL) { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); mm->m_wndProp.Update(NULL, -1); } // Invalidate the current selection so its drawn lighter in inactive window FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) ++end_addr; // if no selection invalidate current byte invalidate_hex_addr_range(start_addr, end_addr); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing } void CHexEditView::OnSetFocus(CWnd* pOldWnd) { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing if (pav_ != NULL && IsWindow(pav_->m_hWnd)) pav_->StartTimer(); // Turn on any animation in aerial view CScrView::OnSetFocus(pOldWnd); if (text_height_ < 1) return; #if 0 // Handled in CChildFrame::OnSetFocus now show_prop(); show_calc(); show_pos(); #endif move_dlgs(); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) ++end_addr; // if no selection invalidate the current byte invalidate_hex_addr_range(start_addr, end_addr); // Save nav info in case we need to create a nav pt here if (theApp.navman_.LastView() != this && !theApp.navman_.InMove()) { nav_start_ = start_addr; nav_end_ = end_addr; nav_scroll_ = (GetScroll().y/line_height_)*rowsize_ - offset_; theApp.navman_.Add("Change window", get_info(), this, nav_start_, nav_end_, nav_scroll_); nav_moves_ = 0; } // km_new now seems to get recorded before km_focus - so check if km_new_str is there // (which always follows km_new) and don't store km_focus if (!(theApp.recording_ && theApp.mac_.size() > 0 && (theApp.mac_.back()).ktype == km_new_str) && theApp.pview_ != this) { // We only want to store focus change in a macro, if the last CHexEditView that // got focus is different to this one. This allows us to ignore focus changes // when other things (find dialog, toolbar buttons etc) temp. get focus. // Also this macro entry may be deleted if followed by km_new, km_open, // km_win_new, km_childsys (next/prev win or win close) or km_win_next // since these implicitly change the focus, and setting it explicitly before // to a certain window may ruin their effect. ASSERT(GetFrame() != NULL); CString ss; GetFrame()->GetWindowText(ss); if (ss.Right(2) == " *") ss = ss.Left(ss.GetLength() - 2); // Ignore setfocus before frame has name if (ss.GetLength() > 0) theApp.SaveToMacro(km_focus, ss); } theApp.pview_ = this; } void CHexEditView::OnDestroy() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing if (pav_ != NULL) GetDocument()->RemoveAerialView(); if (pcv_ != NULL) GetDocument()->RemoveCompView(); CScrView::OnDestroy(); // If there are no more views active ... CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (GetView() == NULL) { // If this is the last window we need to make sure that all file // access buttons are disabled in the calculator (if visible) show_calc(); } } // Point is in window coordinates void CHexEditView::OnLButtonDblClk(UINT nFlags, CPoint point) { #if 0 if (point.x < hex_pos(0)) theApp.OnViewDoubleClick(this, IDR_CONTEXT_ADDRESS); else if (display_.vert_display) { CPointAp pp = ConvertFromDP(point); // Convert point to doc coords if (pp.y%line_height_ < text_height_) theApp.OnViewDoubleClick(this, IDR_CONTEXT_CHAR); // click on top (char) row else theApp.OnViewDoubleClick(this, IDR_CONTEXT_HEX); // click on one of bottom 2 rows } else if (!display_.char_area || point.x < char_pos(0)) theApp.OnViewDoubleClick(this, IDR_CONTEXT_HEX); else theApp.OnViewDoubleClick(this, IDR_CONTEXT_CHAR); #endif CPointAp doc_pt = ConvertFromDP(point); if (( (display_.vert_display || display_.char_area) && doc_pt.x >= char_pos(rowsize_)+text_width_ || !(display_.vert_display || display_.char_area) && doc_pt.x >= hex_pos(rowsize_) ) ) { // Don't do anything if off to right return; } if (doc_pt.x < hex_pos(0)) theApp.OnViewDoubleClick(this, IDR_CONTEXT_ADDRESS); else if (display_.vert_display) { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in char area FILE_ADDRESS addr = (doc_pt.y/line_height_)*rowsize_ - offset_ + pos_char(doc_pt.x); //if (addr >= start_addr && addr < end_addr) // theApp.OnViewDoubleClick(this, IDR_CONTEXT_SELECTION); //else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_BOOKMARKS); // click on bookmark else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_HIGHLIGHT); // click on highlight else if (pos2row(doc_pt) == 0) theApp.OnViewDoubleClick(this, IDR_CONTEXT_CHAR); // click on top (char) row else theApp.OnViewDoubleClick(this, IDR_CONTEXT_HEX); // click on one of bottom 2 rows } else if (!display_.char_area || doc_pt.x < char_pos(0)) { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in hex area FILE_ADDRESS addr = (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_hex(doc_pt.x); //if (addr >= start_addr && addr < end_addr) // theApp.OnViewDoubleClick(this, IDR_CONTEXT_SELECTION); //else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_BOOKMARKS); else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_HIGHLIGHT); // click on highlight else theApp.OnViewDoubleClick(this, IDR_CONTEXT_HEX); } else { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in char area FILE_ADDRESS addr = (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_char(doc_pt.x); //if (addr >= start_addr && addr < end_addr) // theApp.OnViewDoubleClick(this, IDR_CONTEXT_SELECTION); //else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_BOOKMARKS); else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_HIGHLIGHT); // click on highlight else theApp.OnViewDoubleClick(this, IDR_CONTEXT_CHAR); } } #ifdef RULER_ADJUST // Display a tip for an adjuster in the ruler void CHexEditView::add_ruler_tip(CPoint pt, CString ss, COLORREF colour) { CPoint tip_pt; tip_pt = pt + CSize(text_width_w_, text_height_/2); ClientToScreen(&tip_pt); ruler_tip_.Move(tip_pt, false); ruler_tip_.SetWindowText(ss); ruler_tip_.SetBgCol(colour); ruler_tip_.Show(); } // Check if a mouse point is over an adjuster bool CHexEditView::over_rowsize_adjuster(CPointAp pp) { int xpos; if (!display_.vert_display && display_.hex_area) { xpos = char_pos(0) - text_width_w_/2; if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } else if (display_.vert_display || (display_.char_area && !display_.hex_area)) { xpos = char_pos(rowsize_ - 1) + (3*text_width_w_)/2; if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } return false; } bool CHexEditView::over_offset_adjuster(CPointAp pp) { int xpos; if (!display_.vert_display && display_.hex_area) { xpos = hex_pos(offset_); if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } if (display_.vert_display || display_.char_area && !display_.hex_area) { xpos = char_pos(offset_); if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } return false; } bool CHexEditView::over_group_by_adjuster(CPointAp pp) { int xpos; if (display_.vert_display) { xpos = char_pos(group_by_) - text_width_w_/2; if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } else if (display_.hex_area) { xpos = hex_pos(group_by_) - text_width_; if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } return false; } #endif void CHexEditView::OnLButtonDown(UINT nFlags, CPoint point) { CPointAp pp = ConvertFromDP(point); // Point in our coord system // Click to right of everything is ignored, but click on address area (left side) // is now allowed to allow double-click in address area event to be handled if ( (display_.vert_display || display_.char_area) && pp.x >= char_pos(rowsize_)+text_width_ || !(display_.vert_display || display_.char_area) && pp.x >= hex_pos(rowsize_) ) { return; // Do nothing if off to right } GetSelAddr(prev_start_, prev_end_); prev_row_ = 0; if (prev_start_ == prev_end_ && display_.vert_display) prev_row_ = pos2row(GetCaret()); if (point.y < bdr_top_) // above top (ie in ruler) { #ifdef RULER_ADJUST // Ruler area - check if over any of the adjusters // Check if mouse down on row size adjuster adjusting_rowsize_ = -1; if (over_rowsize_adjuster(pp)) { if (pcv_ != NULL) pcv_->begin_change(); adjusting_rowsize_ = rowsize_; invalidate_adjuster(adjusting_rowsize_); SetCapture(); return; } // Check if the offset adjuster has been clicked adjusting_offset_ = -1; if (over_offset_adjuster(pp)) { if (pcv_ != NULL) pcv_->begin_change(); adjusting_offset_ = offset_; invalidate_adjuster(adjusting_offset_); SetCapture(); return; } adjusting_group_by_ = -1; if (over_group_by_adjuster(pp)) { if (pcv_ != NULL) pcv_->begin_change(); adjusting_group_by_ = group_by_; invalidate_adjuster(adjusting_group_by_); SetCapture(); return; } #endif return; // Don't allow any other select for click in ruler } shift_down_ = shift_down(); // Check if clicked on a bookmark if (!shift_down_ && (drag_bookmark_ = bookmark_at(address_at(point))) > -1) { tip_.Hide(0); if (last_tip_addr_ != -1) { FILE_ADDRESS addr = last_tip_addr_; last_tip_addr_ = -1; invalidate_hex_addr_range(addr, addr+1); } drag_address_ = GetDocument()->bm_posn_[drag_bookmark_]; // start at current bookmark addr mouse_down_ = true; return; // no selection wanted when dragging a bookmark } saved_state_ = disp_state_; // Keep the current state for saving in undo stack // Save some info that may be needed for macro recording dev_down_ = point; // Mouse down posn (device coords) doc_down_ = pp; // Mouse down posn (doc coords) FILE_ADDRESS swap_addr = -1; // caret addr before swap (or -1 if no swap) if (!shift_down_) { num_entered_ = num_del_ = num_bs_ = 0; // Can't be editing while mousing if (!display_.vert_display && display_.char_area && display_.hex_area) { // Allow user to move caret between hex and char areas // Which area did the user click in? // Note display_.edit_char must be set before ValidateCaret() is called while the // mouse button is held down so that the dragged selection is drawn correctly. display_.edit_char = pos_hex(pp.x, FALSE) >= rowsize_; if (saved_state_ != disp_state_) { if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); swap_addr = prev_start_; } } } CScrView::OnLButtonDown(nFlags, point); if (theApp.hl_caret_ && swap_addr > -1) invalidate_ruler(swap_addr); reset_tip(); show_prop(); show_calc(); show_pos(); mouse_down_ = true; // We saw left button down event } void CHexEditView::OnLButtonUp(UINT nFlags, CPoint point) { #ifdef RULER_ADJUST if (adjusting_rowsize_ > -1) { FILE_ADDRESS scroll_addr = pos2addr(GetScroll()); undo_.push_back(view_undo(undo_rowsize)); undo_.back().rowsize = rowsize_; if (display_.autofit) { undo_.push_back(view_undo(undo_autofit, TRUE)); display_.autofit = 0; } rowsize_ = adjusting_rowsize_; if (real_offset_ < rowsize_) offset_ = real_offset_; else offset_ = rowsize_ - 1; recalc_display(); // Fix scroll place so it's about the same even though the row length has changed CPointAp pt = addr2pos(scroll_addr); pt.x = 0; SetScroll(pt); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); ReleaseCapture(); adjusting_rowsize_ = -1; SetSel(addr2pos(prev_start_), addr2pos(prev_end_)); return; } if (adjusting_offset_ > -1) { undo_.push_back(view_undo(undo_offset)); undo_.back().rowsize = real_offset_; // Save previous offset for undo real_offset_ = offset_ = adjusting_offset_; if (real_offset_ >= rowsize_) offset_ = rowsize_ - 1; recalc_display(); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); ReleaseCapture(); adjusting_offset_ = -1; SetSel(addr2pos(prev_start_), addr2pos(prev_end_)); return; } if (adjusting_group_by_ > -1) { undo_.push_back(view_undo(undo_group_by)); undo_.back().rowsize = group_by_; // Save previous group_by for undo group_by_ = adjusting_group_by_; recalc_display(); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); ReleaseCapture(); adjusting_group_by_ = -1; SetSel(addr2pos(prev_start_), addr2pos(prev_end_)); return; } #endif if (mouse_down_ && drag_bookmark_ > -1) { // Move the bookmark to drag_address_ FILE_ADDRESS prev = GetDocument()->bm_posn_[drag_bookmark_]; // Previous bm position CBookmarkList *pbl = theApp.GetBookmarkList(); ASSERT(pbl != NULL); pbl->Move(GetDocument()->bm_index_[drag_bookmark_], int(drag_address_ - prev)); // move bm in global list GetDocument()->bm_posn_[drag_bookmark_] = drag_address_; // move in doc's bm list ((CMainFrame *)AfxGetMainWnd())->m_wndBookmarks.UpdateBookmark(GetDocument()->bm_index_[drag_bookmark_]); drag_bookmark_ = -1; // signal that we are no longer dragging mouse_down_ = false; invalidate_addr_range(prev, prev+1); // force redraw to remove bookmark at old position invalidate_addr_range(drag_address_, drag_address_+1); // redraw bookmark at new position } else if (mouse_down_) { num_entered_ = num_del_ = num_bs_ = 0; // Can't be editing while mousing CScrView::OnLButtonUp(nFlags, point); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Save in undo array if position moved if (prev_start_ != start_addr || prev_end_ != end_addr || saved_state_ != disp_state_) { // Save the caret position (or start of selection) undo_.push_back(view_undo(undo_move)); undo_.back().address = prev_start_ | (FILE_ADDRESS(prev_row_)<<62); if (prev_start_ != prev_end_) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end_; } if (saved_state_ != disp_state_) { // Save the fact that we swapped between areas undo_.push_back(view_undo(undo_state, TRUE)); undo_.back().disp_state = saved_state_; } // Save info to keystroke macro (if recording) CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (aa->recording_) { mouse_sel ms; // Info for km_mouse/km_shift_mouse ms.dev_down = dev_down_; // Point in window where selection started CPointAp doc_up = ConvertFromDP(point); // Point where selection ended (doc coords) // ms.doc_dist = doc_up - doc_down_; // To avoid problems where a different number of rows are selected on play // for slightly different scroll positions we round up to mult. of text_height_. ms.doc_dist.cy = (doc_up.y/text_height_ - doc_down_.y/text_height_) * text_height_; // ms.doc_dist.cx = (doc_up.x/text_width_ - doc_down_.x/text_width_) * text_width_; if (shift_down_) aa->SaveToMacro(km_shift_mouse, &ms); else aa->SaveToMacro(km_mouse, &ms); } if (aa->highlight_) add_highlight(start_addr, end_addr, TRUE); nav_save(start_addr, end_addr, "Mouse Click "); } show_prop(); show_calc(); show_pos(); mouse_down_ = false; update_sel_tip(); // Make sure window hidden when mouse button up if (theApp.hl_caret_) { invalidate_addr(start_addr); invalidate_ruler(start_addr); } } } void CHexEditView::OnMouseMove(UINT nFlags, CPoint point) { #ifdef RULER_ADJUST CPointAp doc_pt = ConvertFromDP(point); if (adjusting_rowsize_ > -1) // Dragging row size adjuster? { CString ss; int old = adjusting_rowsize_; // save current so we can "undraw" it if (!display_.vert_display && display_.hex_area) { if (doc_pt.x < hex_pos(4)) adjusting_rowsize_ = 4; else adjusting_rowsize_ = pos_hex(doc_pt.x + text_width_, -1); } else if (display_.vert_display || display_.char_area) { if (doc_pt.x < char_pos(4)) adjusting_rowsize_ = 4; else adjusting_rowsize_ = pos_char(doc_pt.x + text_width_w_/2, -1); } if (adjusting_rowsize_ != old) { invalidate_adjuster(old); invalidate_adjuster(adjusting_rowsize_); } ss.Format("Columns: %d", adjusting_rowsize_); add_ruler_tip(point, ss, adjusting_rowsize_ != rowsize_ ? RGB(224,255,224) : ::GetSysColor(COLOR_INFOBK)); return; } if (adjusting_offset_ > -1) // Dragging offset adjuster? { CString ss; int old = adjusting_offset_; // save current so we can "undraw" it // Work out new offset from current dragged mouse posn if (display_.vert_display) { int left_side = char_pos(0); if (doc_pt.x < left_side - text_width_) adjusting_offset_ = rowsize_ - (left_side-doc_pt.x)/text_width_; else if (doc_pt.x >= char_pos(rowsize_)) adjusting_offset_ = 0; // Use 0 if dragged too far right else adjusting_offset_ = pos_char(doc_pt.x + text_width_w_/2, TRUE); } else if (display_.char_area && display_.hex_area && doc_pt.x < char_pos(0)) { int left_side = hex_pos(0); if (doc_pt.x < left_side - text_width_) adjusting_offset_ = rowsize_ - (left_side-doc_pt.x)/text_width_; else if (doc_pt.x >= hex_pos(rowsize_)) adjusting_offset_ = 0; else adjusting_offset_ = pos_hex(doc_pt.x + text_width_, TRUE); } else if (display_.char_area) { int left_side = char_pos(0); if (doc_pt.x < left_side - text_width_) adjusting_offset_ = rowsize_ - (left_side-doc_pt.x)/text_width_; else if (doc_pt.x >= char_pos(rowsize_)) adjusting_offset_ = 0; else adjusting_offset_ = pos_char(doc_pt.x + text_width_w_/2, TRUE); } else { int left_side = hex_pos(0); if (doc_pt.x < left_side - text_width_) adjusting_offset_ = rowsize_ - (left_side-doc_pt.x)/text_width_; else if (doc_pt.x >= hex_pos(rowsize_)) adjusting_offset_ = 0; else adjusting_offset_ = pos_hex(doc_pt.x + text_width_, TRUE); } if (adjusting_offset_ < 0) adjusting_offset_ = 0; if (adjusting_offset_ != old) { invalidate_adjuster(old); invalidate_adjuster(adjusting_offset_); } ss.Format("Offset: %d", adjusting_offset_); add_ruler_tip(point, ss, adjusting_offset_ != offset_ ? RGB(224,255,224) : ::GetSysColor(COLOR_INFOBK)); return; } if (adjusting_group_by_ > -1) // Dragging grouping adjuster? { CString ss; int old = adjusting_group_by_; // save current so we can "undraw" it // Work out new group_by_ from current dragged mouse posn if (display_.vert_display) { if (doc_pt.x < char_pos(2)) adjusting_group_by_ = 2; // Minimum //else if (doc_pt.x >= char_pos(rowsize_)) // adjusting_group_by_ = 9999; else adjusting_group_by_ = pos_char(doc_pt.x + text_width_w_/2, -1); } else if (display_.hex_area) { if (doc_pt.x < hex_pos(2)) adjusting_group_by_ = 2; //else if (doc_pt.x >= hex_pos(rowsize_)) // adjusting_group_by_ = 9999; else adjusting_group_by_ = pos_hex(doc_pt.x + text_width_, -1); } if (adjusting_group_by_ != old) { invalidate_adjuster(old); invalidate_adjuster(adjusting_group_by_); } ss.Format("Grouping: %d", adjusting_group_by_); add_ruler_tip(point, ss, adjusting_group_by_ != group_by_ ? RGB(224,255,224) : ::GetSysColor(COLOR_INFOBK)); return; } // Now check if we are hovering over a ruler handle. if (point.y < bdr_top_ && (over_rowsize_adjuster(doc_pt) || over_offset_adjuster(doc_pt) || over_group_by_adjuster(doc_pt)) ) { track_mouse(TME_HOVER); return; } if (!ruler_tip_.FadingOut()) ruler_tip_.Hide(300); // Not dragging or hovering over so hide it #endif FILE_ADDRESS addr = address_at(point); // Address of byte mouse is over (or -1) // If dragging a bookmark update the drag location if (mouse_down_ && drag_bookmark_ > -1) { if (addr < 0 || addr > GetDocument()->length()) return; // don't move to invalid pos FILE_ADDRESS prev = drag_address_; drag_address_ = addr; // we must change this before redraw invalidate_addr_range(prev, prev+1); // force redraw at previous drag position invalidate_addr_range(drag_address_, drag_address_+1); // redraw at new position return; } FILE_ADDRESS old_addr, end_addr, new_addr; if (mouse_down_) GetSelAddr(old_addr, end_addr); // Get current caret before moved CScrView::OnMouseMove(nFlags, point); if (mouse_down_) GetSelAddr(new_addr, end_addr); if (mouse_down_) { tip_.Hide(0); // Make sure there is no mouse tip while dragging move_dlgs(); update_sel_tip(200); // Update selection tip } else if (!tip_.IsWindowVisible()) { // Set a timer so that we can check if we want to display a tip window track_mouse(TME_HOVER); if (last_tip_addr_ != -1) { // Hide the box around the tip byte FILE_ADDRESS addr = last_tip_addr_; last_tip_addr_ = -1; invalidate_hex_addr_range(addr, addr+1); } } else if (addr != last_tip_addr_ && tip_.IsWindowVisible()) { // Hide the tip window since the mouse has moved away if (!tip_.FadingOut()) // Don't keep it alive if we have already told it to fade away tip_.Hide(300); } if (theApp.hl_mouse_) set_mouse_addr(addr); } /* void CHexEditView::OnTimer(UINT nIDEvent) { if (nIDEvent == timer_id_) { VERIFY(KillTimer(timer_id_)); timer_id_ = 0; CPoint pt; GetCursorPos(&pt); ScreenToClient(&pt); if (pt != last_mouse_) return; // Time to show a tip window if we are in the right place FILE_ADDRESS addr = address_at(pt); int bm; if (addr != -1 && (bm = bookmark_at(addr)) != -1) { last_tip_addr_ = addr; CBookmarkList *pbl = theApp.GetBookmarkList(); tip_.SetWindowText(pbl->name_[GetDocument()->bm_index_[bm]]); CPoint point = last_mouse_ + CSize(text_width_w_, text_height_); ClientToScreen(&point); tip_.Move(point, false); tip_.Show(); } } else CScrView::OnTimer(nIDEvent); } */ LRESULT CHexEditView::OnMouseHover(WPARAM, LPARAM lp) { CPoint pt(LOWORD(lp), HIWORD(lp)); // client window coords // Time to show a tip window if we are in the right place if (!mouse_down_ && !tip_.IsWindowVisible()) { FILE_ADDRESS addr = address_at(pt); if (addr != -1 && addr < GetDocument()->length() && update_tip(addr)) { CPoint tip_pt; tip_pt = pt + CSize(text_width_w_, text_height_); last_tip_addr_ = addr; invalidate_hex_addr_range(addr, addr+1); ClientToScreen(&tip_pt); tip_.Move(tip_pt, false); tip_.Show(); track_mouse(TME_LEAVE); return 0; } } #ifdef RULER_ADJUST if (pt.y < bdr_top_ && !ruler_tip_.IsWindowVisible()) { CPointAp pp = ConvertFromDP(pt); // Point in our coord system CString ss; if (over_rowsize_adjuster(pp)) ss.Format("Columns: %d%s", rowsize_, display_.autofit ? " (AutoFit)" : ""); else if (over_offset_adjuster(pp)) ss.Format("Offset: %d", offset_); else if (over_group_by_adjuster(pp)) ss.Format("Grouping: %d", group_by_); if (!ss.IsEmpty()) { add_ruler_tip(pt, ss, ::GetSysColor(COLOR_INFOBK)); track_mouse(TME_LEAVE); return 0; } } #endif return 1; } // Returns true if tip text was updated or false if there is nothing to show. // The parameter (addr) if the address about which we show information bool CHexEditView::update_tip(FILE_ADDRESS addr) { size_t ii; tip_addr_ = addr; ASSERT(theApp.tip_name_.size() > 0); // we should at least have bookmarks ASSERT(theApp.tip_on_ .size() == theApp.tip_name_.size()); ASSERT(theApp.tip_expr_ .size() == theApp.tip_name_.size()); ASSERT(theApp.tip_format_.size() == theApp.tip_name_.size()); tip_.Clear(); // Do desciptions for (ii = 0; ii < theApp.tip_name_.size(); ++ii) { if (theApp.tip_on_[ii]) { if (ii == 0) { // Special (hard-coded) bookmark tip ASSERT(theApp.tip_name_[ii] == "Bookmarks"); if (bookmark_at(addr) != -1) tip_.AddString("Bookmark: "); } // Add any more "hard-coded" tip types here ... else { ASSERT(ii >= FIRST_USER_TIP); tip_.AddString(theApp.tip_name_[ii] + ": "); } } } CPoint pt(0,0); CRect rct = tip_.GetTotalRect(); pt.x = rct.right; int idx = 0; for (ii = 0; ii < theApp.tip_name_.size(); ++ii) { if (theApp.tip_on_[ii]) { if (ii == 0) { // Special (hard-coded) bookmark tip ASSERT(theApp.tip_name_[ii] == "Bookmarks"); int bm; // Index into doc's bookmark list of bookmark under cursor if ((bm = bookmark_at(addr)) != -1) { rct = tip_.GetRect(idx); pt.y = rct.top; tip_.AddString(theApp.GetBookmarkList()->name_[GetDocument()->bm_index_[bm]], -1, &pt); ++idx; } } // Add any more "hard-coded" tip types here ... else { COLORREF col = -1; CString format = theApp.tip_format_[ii]; // Work out the colour of the text if (theApp.tip_expr_[ii].Find("address") != -1 || theApp.tip_expr_[ii].Find("cursor") != -1 || theApp.tip_expr_[ii].Find("sel_len") != -1 || theApp.tip_expr_[ii].Find("mark") != -1 || theApp.tip_expr_[ii].Find("eof") != -1) { // If no format given display as current address format if (format.IsEmpty()) format = DecAddresses() ? "dec" : "hex"; // Display addresses in the appropriate colour if (format.Left(3).CompareNoCase("hex") == 0 || format.Find('x') != -1 || format.Find('X') != -1) { col = GetHexAddrCol(); // display in hex address colour } else if (format.Left(3).CompareNoCase("dec") == 0 || format.Find('u') != -1 || format.Find('d') != -1) { col = GetDecAddrCol(); // display in decimal address colour } // else other int formats like octal, or non-int format such as: // octal, %o, bin, false (boolean), no, off, %s (string) etc } // Work out where to put it rct = tip_.GetRect(idx); pt.y = rct.top; int dummy; expr_eval::value_t val = expr_.evaluate(theApp.tip_expr_[ii], 0, dummy); tip_.AddString(val.GetDataString(format, expr_.GetSize(), expr_.GetUnsigned()), col, &pt); ++idx; } } } ASSERT(ii > 0); // This is mainly here for easier stepping in the debugger ASSERT(tip_.Count() == idx*2); // should have added 2 entries for every tip tip_.SetAlpha(theApp.tip_transparency_); return idx > 0; } LRESULT CHexEditView::OnMouseLeave(WPARAM, LPARAM lp) { tip_.Hide(300); #ifdef RULER_ADJUST ruler_tip_.Hide(300); #endif if (theApp.hl_mouse_) set_mouse_addr(-1); return 0; } void CHexEditView::OnSysColorChange() { CScrView::OnSysColorChange(); set_colours(); Invalidate(); } void CHexEditView::track_mouse(unsigned long flag) { TRACKMOUSEEVENT tme; tme.cbSize = sizeof(tme); tme.dwFlags = flag; tme.dwHoverTime = 0; tme.hwndTrack = m_hWnd; VERIFY(::_TrackMouseEvent(&tme)); } FILE_ADDRESS CHexEditView::address_at(CPoint pt) { if (pt.y < bdr_top_) return -1; // Above top border (ie in ruler) CPointAp doc_pt = ConvertFromDP(pt); // Mouse position (doc coords) if (doc_pt.x < hex_pos(0) || doc_pt.x > char_pos(rowsize_)+text_width_) return -1; // Left of hex area (ie in address area) else if ( (display_.vert_display || display_.char_area) && doc_pt.x >= char_pos(rowsize_)+text_width_ || !(display_.vert_display || display_.char_area) && doc_pt.x >= hex_pos(rowsize_) ) return -1; // Right of areas (ie in blank area) else if (display_.vert_display) return (doc_pt.y/line_height_)*rowsize_ - offset_ + pos_char(doc_pt.x, TRUE); else if (!display_.char_area || doc_pt.x < char_pos(0)) return (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_hex(doc_pt.x, TRUE); else return (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_char(doc_pt.x, TRUE); } // Returns the bookmark at file address or -1 if none int CHexEditView::bookmark_at(FILE_ADDRESS addr) { std::vector<FILE_ADDRESS>::const_iterator pp = std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr); if (pp != GetDocument()->bm_posn_.end()) return pp - GetDocument()->bm_posn_.begin(); else return -1; } void CHexEditView::OnHighlight() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (aa->highlight_) aa->highlight_ = FALSE; else if (start_addr != end_addr) add_highlight(start_addr, end_addr, FALSE); else aa->highlight_ = TRUE; aa->SaveToMacro(km_highlight, (unsigned __int64)1); } void CHexEditView::OnUpdateHighlight(CCmdUI* pCmdUI) { pCmdUI->SetCheck(dynamic_cast<CHexEditApp *>(AfxGetApp())->highlight_); } void CHexEditView::OnHighlightClear() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); aa->highlight_ = FALSE; if (!hl_set_.empty()) { undo_.push_back(view_undo(undo_highlight)); undo_.back().phl = new range_set<FILE_ADDRESS>(hl_set_); hl_set_.clear(); DoInvalidate(); } aa->SaveToMacro(km_highlight); } // Select the current highlight. // This is designed for associating with double-click on a highlight event. void CHexEditView::OnHighlightSelect() { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (hl_set_.range_.empty()) { AfxMessageBox("Nothing highlighted"); theApp.mac_error_ = 10; return; } else { range_set<FILE_ADDRESS>::range_t::const_iterator pp = lower_bound(hl_set_.range_.begin(), hl_set_.range_.end(), range_set<FILE_ADDRESS>::segment(start_addr+1, start_addr+1), segment_compare()); if (pp != hl_set_.range_.begin()) pp--; MoveWithDesc("Select Highlight ", pp->sfirst, pp->slast); theApp. SaveToMacro(km_highlight, (unsigned __int64)5); } } void CHexEditView::OnHighlightPrev() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (hl_set_.range_.empty()) { AfxMessageBox("Nothing highlighted"); aa->mac_error_ = 10; return; } else if (hl_set_.range_.front().sfirst >= start_addr) { AfxMessageBox("No highlight before start of file"); aa->mac_error_ = 10; return; } else { range_set<FILE_ADDRESS>::range_t::const_iterator pp = lower_bound(hl_set_.range_.begin(), hl_set_.range_.end(), range_set<FILE_ADDRESS>::segment(start_addr, end_addr), segment_compare()); ASSERT(pp != hl_set_.range_.begin()); pp--; // Get the previous elt MoveWithDesc("Previous Highlight ", pp->sfirst, pp->slast); aa->SaveToMacro(km_highlight, (unsigned __int64)2); } } void CHexEditView::OnUpdateHighlightPrev(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pCmdUI->Enable(!hl_set_.range_.empty() && hl_set_.range_.front().sfirst < start_addr); } void CHexEditView::OnHighlightNext() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (hl_set_.range_.empty()) { AfxMessageBox("Nothing highlighted"); aa->mac_error_ = 10; return; } else if (hl_set_.range_.back().sfirst <= start_addr) { AfxMessageBox("No highlight before end of file"); aa->mac_error_ = 10; return; } else { range_set<FILE_ADDRESS>::range_t::const_iterator pp = lower_bound(hl_set_.range_.begin(), hl_set_.range_.end(), range_set<FILE_ADDRESS>::segment(start_addr+1, end_addr+1), segment_compare()); ASSERT(pp != hl_set_.range_.end()); MoveWithDesc("Next Highlight ", pp->sfirst, pp->slast); aa->SaveToMacro(km_highlight, (unsigned __int64)3); } } void CHexEditView::OnUpdateHighlightNext(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pCmdUI->Enable(!hl_set_.range_.empty() && hl_set_.range_.back().sfirst > start_addr); } void CHexEditView::add_highlight(FILE_ADDRESS start, FILE_ADDRESS end, BOOL ptoo /*=FALSE*/) { if (start < end) { undo_.push_back(view_undo(undo_highlight, ptoo)); undo_.back().phl = new range_set<FILE_ADDRESS>(hl_set_); range_set<FILE_ADDRESS> tt = hl_set_; tt.insert_range(start, end); // If selected area is already part of highlighted area if (tt == hl_set_) hl_set_.erase_range(start, end); // Remove it from highlight else hl_set_.swap(tt); // else add it to highlight invalidate_addr_range(start, end); } #ifdef _DEBUG for (range_set<FILE_ADDRESS>::range_t::iterator pr = hl_set_.range_.begin(); pr != hl_set_.range_.end(); ++pr) { FILE_ADDRESS fa = pr->sfirst; fa = pr->slast; } #endif } void CHexEditView::OnHighlightHide() { begin_change(); display_.hide_highlight = !display_.hide_highlight; make_change(); end_change(); theApp.SaveToMacro(km_highlight, (unsigned __int64)4); } void CHexEditView::OnUpdateHighlightHide(CCmdUI* pCmdUI) { pCmdUI->SetCheck(display_.hide_highlight); } // We will try returning the bookmark above or -1 if there is none int CHexEditView::ClosestBookmark(FILE_ADDRESS &diff) { std::vector<FILE_ADDRESS>::const_iterator prev_bm = GetDocument()->bm_posn_.end(); diff = GetDocument()->length()+1; // Bigger than any possible difference between current & bookmark FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Find the bookmark that is closest but after the current address for (std::vector<FILE_ADDRESS>::const_iterator pbm = GetDocument()->bm_posn_.begin(); pbm != GetDocument()->bm_posn_.end(); ++pbm) { if (*pbm <= start_addr && start_addr - *pbm < diff) { diff = start_addr - *pbm; prev_bm = pbm; } } if (prev_bm == GetDocument()->bm_posn_.end()) return -1; else return GetDocument()->bm_index_[prev_bm - GetDocument()->bm_posn_.begin()]; } void CHexEditView::OnBookmarksClear() { GetDocument()->ClearBookmarks(); theApp.SaveToMacro(km_bookmarks); } void CHexEditView::OnUpdateBookmarksClear(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->bm_posn_.empty()); } void CHexEditView::OnBookmarksPrev() { std::vector<FILE_ADDRESS>::const_iterator prev_bm = GetDocument()->bm_posn_.end(); FILE_ADDRESS diff = GetDocument()->length()+1; // Bigger than any possible difference between current & bookmark FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Find the bookmark that is closest but after the current address for (std::vector<FILE_ADDRESS>::const_iterator pbm = GetDocument()->bm_posn_.begin(); pbm != GetDocument()->bm_posn_.end(); ++pbm) { if (*pbm < start_addr && start_addr - *pbm < diff) { diff = start_addr - *pbm; prev_bm = pbm; } } if (prev_bm == GetDocument()->bm_posn_.end()) { // No bookmarks found (presumably in macro playback) AfxMessageBox("No bookmarks found towards start of file"); theApp.mac_error_ = 10; return; } MoveWithDesc("Previous Bookmark ", *prev_bm, *prev_bm); theApp.SaveToMacro(km_bookmarks, (unsigned __int64)2); } void CHexEditView::OnUpdateBookmarksPrev(CCmdUI* pCmdUI) { std::vector<FILE_ADDRESS>::const_iterator prev_bm = GetDocument()->bm_posn_.end(); FILE_ADDRESS diff = GetDocument()->length()+1; // Bigger than any possible difference between current & bookmark FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Find the bookmark that is closest but after the current address for (std::vector<FILE_ADDRESS>::const_iterator pbm = GetDocument()->bm_posn_.begin(); pbm != GetDocument()->bm_posn_.end(); ++pbm) { if (*pbm < start_addr && start_addr - *pbm < diff) { diff = start_addr - *pbm; prev_bm = pbm; } } pCmdUI->Enable(prev_bm != GetDocument()->bm_posn_.end()); } void CHexEditView::OnBookmarksNext() { std::vector<FILE_ADDRESS>::const_iterator next_bm = GetDocument()->bm_posn_.end(); FILE_ADDRESS diff = GetDocument()->length()+1; // Bigger than any possible difference between current & bookmark FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Find the bookmark that is closest but after the current address for (std::vector<FILE_ADDRESS>::const_iterator pbm = GetDocument()->bm_posn_.begin(); pbm != GetDocument()->bm_posn_.end(); ++pbm) { if (*pbm > start_addr && *pbm - start_addr < diff) { diff = *pbm - start_addr; next_bm = pbm; } } if (next_bm == GetDocument()->bm_posn_.end()) { // No bookmarks found (presumably in macro playback) AfxMessageBox("No bookmarks before end of file"); theApp.mac_error_ = 10; return; } MoveWithDesc("Next Bookmark ", *next_bm, *next_bm); theApp.SaveToMacro(km_bookmarks, (unsigned __int64)3); } void CHexEditView::OnUpdateBookmarksNext(CCmdUI* pCmdUI) { std::vector<FILE_ADDRESS>::const_iterator next_bm = GetDocument()->bm_posn_.end(); FILE_ADDRESS diff = GetDocument()->length()+1; // Bigger than any possible difference between current & bookmark FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Find the bookmark that is closest but after the current address for (std::vector<FILE_ADDRESS>::const_iterator pbm = GetDocument()->bm_posn_.begin(); pbm != GetDocument()->bm_posn_.end(); ++pbm) { if (*pbm > end_addr && *pbm - end_addr < diff) { diff = *pbm - end_addr; next_bm = pbm; } } pCmdUI->Enable(next_bm != GetDocument()->bm_posn_.end()); } void CHexEditView::OnBookmarksHide() { begin_change(); display_.hide_bookmarks = !display_.hide_bookmarks; make_change(); end_change(); theApp.SaveToMacro(km_bookmarks, (unsigned __int64)4); } void CHexEditView::OnUpdateBookmarksHide(CCmdUI* pCmdUI) { pCmdUI->SetCheck(display_.hide_bookmarks); } void CHexEditView::OnBookmarkToggle() { if (GetDocument()->pfile1_ == NULL) { AfxMessageBox("Bookmarks can only be added to disk files.\r\n" "Please save the file to disk and try again."); ((CHexEditApp *)AfxGetApp())->mac_error_ = 5; return; } int index; CBookmarkList *pbl = theApp.GetBookmarkList(); // Test if there is already a bookmark at this location if ((index = GetDocument()->GetBookmarkAt(GetPos())) == -1) { // Add an unnamed bookmark here char *dv_name = "unnamed"; int dummy; long last = pbl->GetSetLast(dv_name, dummy); CString bm_name; bm_name.Format("%s%05ld", dv_name, long(last)); pbl->AddBookmark(bm_name, GetDocument()->pfile1_->GetFilePath(), GetPos(), NULL, GetDocument()); } else pbl->RemoveBookmark(index); // remove the bookmark theApp.SaveToMacro(km_bookmarks, (unsigned __int64)7); } void CHexEditView::reset_tip() { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); CPointAp pt(addr2pos(start_addr)); CPoint point = ConvertToDP(pt); point.x -= 24; ClientToScreen(&point); sel_tip_.Move(point); sel_tip_.Hide(); } void CHexEditView::update_sel_tip(int delay /*=0*/) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (theApp.sel_len_tip_ && (mouse_down_ || shift_down()) && start_addr != end_addr) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CString ss; __int64 len = __int64(end_addr - start_addr); if (!display_.hex_addr) { char buf[22]; // temp buf where we sprintf sprintf(buf, "%I64d", __int64(len)); ss = buf; AddCommas(ss); sel_tip_.SetTextCol(dec_addr_col_); // If there is a fair amount of contrast with standard tip background // colour then use it else use something else. if (abs(BRIGHTNESS(dec_addr_col_) - BRIGHTNESS(::GetSysColor(COLOR_INFOBK))) > 30) sel_tip_.SetBgCol(::GetSysColor(COLOR_INFOBK)); else if (BRIGHTNESS(dec_addr_col_) > 50) sel_tip_.SetBgCol(RGB(64,64,0)); // Light text so use dark "yellow" bg else sel_tip_.SetBgCol(RGB(255,255,224)); // Dark text so use light yellow bg } else { char buf[22]; // temp buf where we sprintf if (len < 10) sprintf(buf, "%I64x", __int64(len)); else if (aa->hex_ucase_) sprintf(buf, "%I64Xh", __int64(len)); else sprintf(buf, "%I64xh", __int64(len)); ss = buf; AddSpaces(ss); sel_tip_.SetTextCol(hex_addr_col_); // If there is a fair amount of contrast with standard tip background // colour then use it else use something else. if (abs(BRIGHTNESS(hex_addr_col_) - BRIGHTNESS(::GetSysColor(COLOR_INFOBK))) > 30) sel_tip_.SetBgCol(::GetSysColor(COLOR_INFOBK)); else if (BRIGHTNESS(hex_addr_col_) > 50) sel_tip_.SetBgCol(RGB(64,64,0)); // Light text so use dark "yellow" bg else sel_tip_.SetBgCol(RGB(255,255,224)); // Dark text so use light yellow bg } #if 0 // We used to indicate divisibility using colour if (len%8 == 0) sel_tip_.SetTextCol(RGB(0, 0, 128)); else if (len%4 == 0) sel_tip_.SetTextCol(RGB(128, 0, 128)); else if (len%2 == 0) sel_tip_.SetTextCol(RGB(128, 128, 0)); else sel_tip_.SetTextCol(RGB(128, 128, 128)); #endif if (theApp.sel_len_div2_ && len > 10) // User should know divisibility by 2,4 for numbers this small so don't show { int pow2; for (pow2 = 0; pow2 < 12; ++pow2) if (((len>>pow2) & 0x1) != 0) break; CString tmp; tmp.Format(" [%d]", 1<<pow2); ss += tmp; } // Don't update text if the string hasn't changed to avoid flicker CString strPrevious; sel_tip_.GetWindowText(strPrevious); if (strPrevious.Compare(ss) != 0) sel_tip_.SetWindowText(ss); // Check if tip window is too far from selection FILE_ADDRESS start_line = (start_addr + offset_)/rowsize_; FILE_ADDRESS end_line = (end_addr + offset_)/rowsize_ + 1; CRect rct; // Get bounding rectangle of selection (we only really need top and bottom) CRectAp bnd_rct; bnd_rct = CRectAp(0, start_line * line_height_, char_pos(rowsize_), end_line * line_height_); sel_tip_.GetWindowRect(&rct); ScreenToClient(&rct); CRectAp tip_rct = ConvertFromDP(rct); GetDisplayRect(&rct); CRectAp cli_rct = ConvertFromDP(rct); bnd_rct.top -= tip_rct.Height()/2; bnd_rct.bottom += tip_rct.Height()/2; // Restrict bounds rect to the visible selection if (bnd_rct.top < cli_rct.top - 10) { bnd_rct.top = cli_rct.top - 10; if (bnd_rct.bottom < bnd_rct.top + tip_rct.Height()) bnd_rct.bottom = bnd_rct.top + tip_rct.Height(); } if (bnd_rct.bottom > cli_rct.bottom + 10) { bnd_rct.bottom = cli_rct.bottom + 10; if (bnd_rct.top > bnd_rct.bottom - tip_rct.Height()) bnd_rct.top = bnd_rct.bottom - tip_rct.Height(); } if (bnd_rct.left < cli_rct.left) bnd_rct.left = cli_rct.left; if (bnd_rct.right > cli_rct.right) bnd_rct.right = cli_rct.right; // Move the rectangle for tip within bounds if (tip_rct.top < bnd_rct.top) { tip_rct.bottom += bnd_rct.top - tip_rct.top; tip_rct.top += bnd_rct.top - tip_rct.top; } else if (tip_rct.bottom > bnd_rct.bottom) { tip_rct.top += bnd_rct.bottom - tip_rct.bottom; tip_rct.bottom += bnd_rct.bottom - tip_rct.bottom; } if (tip_rct.left < bnd_rct.left) { tip_rct.right += bnd_rct.left - tip_rct.left; tip_rct.left += bnd_rct.left - tip_rct.left; } else if (tip_rct.right > bnd_rct.right) { tip_rct.left += bnd_rct.right - tip_rct.right; tip_rct.right += bnd_rct.right - tip_rct.right; } // Calculate centre of rect and move the tip window CPointAp pt((tip_rct.left + tip_rct.right)/2, (tip_rct.top + tip_rct.bottom)/2); CPoint point = ConvertToDP(pt); ClientToScreen(&point); sel_tip_.Move(point); sel_tip_.Show(100, delay); SetFocus(); } else { sel_tip_.Hide(); } } // This is here to implement the macro command km_mouse void CHexEditView::do_mouse(CPoint dev_down, CSizeAp doc_dist) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CPointAp doc_down = ConvertFromDP(dev_down); // Sel start point converted from device to doc coords CPointAp doc_up(doc_down); // Point where selection ends = start + doc_up += doc_dist; // ... distance of selection // Convert selection (doc coords) to addresses and make sure in valid range FILE_ADDRESS start_addr, end_addr; FILE_ADDRESS length = GetDocument()->length(); start_addr = pos2addr(doc_down); end_addr = pos2addr(doc_up); if (start_addr < 0) start_addr = 0; else if (start_addr > length) start_addr = length; if (end_addr < 0) end_addr = 0; else if (end_addr > length) end_addr = length; // Save undo information FILE_ADDRESS prev_start, prev_end; GetSelAddr(prev_start, prev_end); int prev_row = 0; if (prev_start == prev_end && display_.vert_display) prev_row = pos2row(GetCaret()); if (start_addr == prev_start && end_addr == prev_end) // exactly the same selection return; BOOL saved_area = display_.edit_char; if (!display_.vert_display && display_.char_area && display_.hex_area) // If both areas displayed ... display_.edit_char = pos_hex(doc_down.x, FALSE) >= rowsize_; // sel may swap between areas undo_.push_back(view_undo(undo_move)); undo_.back().address = prev_start | (FILE_ADDRESS(prev_row)<<62); if (prev_start != prev_end) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end; } if (display_.edit_char != saved_area) { // Allow more buffer if editing hex if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); // Save the fact that we swapped between areas undo_.push_back(view_undo(undo_state, TRUE)); undo_.back().disp_state = disp_state_; } SetSel(addr2pos(start_addr), addr2pos(end_addr), true); if (aa->highlight_) add_highlight(start_addr, end_addr, TRUE); nav_save(start_addr, end_addr, "Mouse Click (Play) "); } // This is here to implement the macro command km_shift_mouse void CHexEditView::do_shift_mouse(CPoint dev_down, CSizeAp doc_dist) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CPointAp doc_down = ConvertFromDP(dev_down); // Left down point converted from device to doc coords CPointAp doc_up(doc_down); // Point of left button up (doc coords) = ... doc_up += doc_dist; // ... doc_down + length of selection // Convert selection (doc coords) to addresses and make sure in valid range FILE_ADDRESS start_addr, end_addr; // New selection range FILE_ADDRESS prev_start, prev_end; // Previous selection range FILE_ADDRESS length = GetDocument()->length(); // GetSelAddr(start_addr, prev_end); if (GetSelAddr(prev_start, prev_end)) start_addr = prev_end; // Base of previous selection was end else start_addr = prev_start; end_addr = pos2addr(doc_up); if (start_addr < 0) start_addr = 0; else if (start_addr > length) start_addr = length; if (end_addr < 0) end_addr = 0; else if (end_addr > length) end_addr = length; if (end_addr != prev_end) { // Save the previous selection for undo undo_.push_back(view_undo(undo_move)); undo_.back().address = start_addr; undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end; // Extend the selection SetSel(addr2pos(start_addr), addr2pos(end_addr), true); if (aa->highlight_) add_highlight(start_addr, end_addr, TRUE); } nav_save(start_addr, end_addr, "Mouse Click (Play) "); } void CHexEditView::OnRButtonDown(UINT nFlags, CPoint point) { // Move the caret to where the user clicked so that context menu items // that depend on the current address use the address that was clicked on CPointAp pp = ConvertFromDP(point); // Point in our coord system if (( (display_.vert_display || display_.char_area) && pp.x >= char_pos(rowsize_)+text_width_ || !(display_.vert_display || display_.char_area) && pp.x >= hex_pos(rowsize_) ) ) { // Don't do anything if off to right return; } // Save current state, selection etc for undo GetSelAddr(prev_start_, prev_end_); saved_state_ = disp_state_; // Keep the current state for saving in undo stack prev_row_ = 0; if (prev_start_ == prev_end_ && display_.vert_display) prev_row_ = pos2row(GetCaret()); num_entered_ = num_del_ = num_bs_ = 0; // Can't be editing while mousing if (!display_.vert_display && display_.char_area && display_.hex_area) { // Allow user to move caret between hex and char areas display_.edit_char = pos_hex(pp.x, FALSE) >= rowsize_; if (saved_state_ != disp_state_) { // Sett approp. buffering to allow user to see the whole byte that they are editing if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); } } // Note: this relies on display_.edit_char having been set correctly above FILE_ADDRESS addr = pos2addr(pp); FILE_ADDRESS start_addr, end_addr; BOOL end_base = FALSE; // If we have not clicked inside the selection then ... if (addr < prev_start_ || addr >= prev_end_) { // Move the caret to where the user clicked ValidateCaret(pp, FALSE); SetCaret(pp); BOOL end_base = GetSelAddr(start_addr, end_addr); } else { // Don't move if clicked in selection start_addr = prev_start_; end_addr = prev_end_; } // Save in undo array if position moved if (prev_start_ != start_addr || prev_end_ != end_addr || saved_state_ != disp_state_) { // Save the caret position (or start of selection) undo_.push_back(view_undo(undo_move)); undo_.back().address = prev_start_ | (FILE_ADDRESS(prev_row_)<<62); if (prev_start_ != prev_end_) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end_; } if (saved_state_ != disp_state_) { // Save the fact that we swapped between areas undo_.push_back(view_undo(undo_state, TRUE)); undo_.back().disp_state = saved_state_; } if (end_base) SetSel(addr2pos(end_addr), addr2pos(start_addr), true); else SetSel(addr2pos(start_addr), addr2pos(end_addr)); DisplayCaret(); nav_save(start_addr, end_addr, "Right Mouse Click "); } // Update properties etc for new position show_prop(); show_calc(); show_pos(); #if 0 else if (saved_state_ != disp_state_) { // Save the fact that we swapped between areas undo_.push_back(view_undo(undo_state, FALSE)); undo_.back().disp_state = saved_state_; } -------- FILE_ADDRESS addr = pos2addr(pp); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Make sure we have NOT clicked inside the selection if (addr < start_addr || addr > end_addr) { // Move the caret to where the user clicked ValidateCaret(pp, FALSE); SetCaret(pp); // Update properties etc for new position show_prop(); show_calc(); show_pos(); } #endif CScrView::OnRButtonDown(nFlags, point); } void CHexEditView::OnContextMenu(CWnd* pWnd, CPoint point) { view_context(point); } BOOL CHexEditView::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // Only respond if in client area if (nHitTest == HTCLIENT) { // Get mouse location in window coords CPoint point; ::GetCursorPos(&point); ScreenToClient(&point); #ifdef RULER_ADJUST if (point.y < bdr_top_) { CPointAp pp = ConvertFromDP(point); // Point in our coord system if (point.y > bdr_top_ - 7 && (over_rowsize_adjuster(pp) || over_offset_adjuster(pp) || over_group_by_adjuster(pp)) ) { ::SetCursor(theApp.LoadStandardCursor(IDC_SIZEWE)); return TRUE; } return CScrView::OnSetCursor(pWnd, nHitTest, message); } #endif // Work out location of cursor in window and make sure it's // not over address area (on left) or past last chars (on right) CPointAp pt = ConvertFromDP(point); if (pt.x > (addr_width_ - 1)*text_width_ && (display_.vert_display && pt.x < char_pos(rowsize_)+text_width_w_ || !display_.vert_display && display_.char_area && pt.x < char_pos(rowsize_)+text_width_w_ || !display_.vert_display && !display_.char_area && pt.x < hex_pos(rowsize_) ) ) { // Over hex or char area if (drag_bookmark_ > -1 || bookmark_at(address_at(point)) > -1) ::SetCursor(theApp.LoadStandardCursor(IDC_SIZEALL)); // Indicate bookmark can be moved else if (theApp.highlight_) ::SetCursor(theApp.LoadCursor(IDC_HIGHLIGHT)); // Highlighter cursor else ::SetCursor(theApp.LoadStandardCursor(IDC_IBEAM)); // Text insertion cursor return TRUE; } } return CScrView::OnSetCursor(pWnd, nHitTest, message); } // Display views context menu // point is in screen coords void CHexEditView::view_context(CPoint point) { #if 0 // Changes for BCG context menus // Get the top level menu that contains the submenus used as popup menus CMenu top; BOOL ok = top.LoadMenu(IDR_CONTEXT); ASSERT(ok); if (!ok) return; CHECK_SECURITY(51); CMenu *ppop; if (point.x < hex_pos(0)) { // Context menu for address area ppop = top.GetSubMenu(1); } else if (display_.char_area && point.x >= char_pos(0)) { // Context menu for character area ppop = top.GetSubMenu(2); } else { // Context menu for hex area ppop = top.GetSubMenu(3); } ASSERT(ppop != NULL); if (ppop != NULL) { // Convert window coords to the required screen coords ClientToScreen(&point); VERIFY(ppop->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, GetFrame())); } top.DestroyMenu(); #else CContextMenuManager *pCMM = theApp.GetContextMenuManager(); CPoint cli_pt(point); // The point clicked in doc coords ScreenToClient(&cli_pt); CPointAp doc_pt = ConvertFromDP(cli_pt); if (( (display_.vert_display || display_.char_area) && doc_pt.x >= char_pos(rowsize_)+text_width_ || !(display_.vert_display || display_.char_area) && doc_pt.x >= hex_pos(rowsize_) ) ) { // Don't do anything if off to right return; } if (doc_pt.x < hex_pos(0)) pCMM->ShowPopupMenu(IDR_CONTEXT_ADDRESS, point.x, point.y, this); else if (display_.vert_display) { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in char area FILE_ADDRESS addr = (doc_pt.y/line_height_)*rowsize_ - offset_ + pos_char(doc_pt.x); if (addr >= start_addr && addr < end_addr) pCMM->ShowPopupMenu(IDR_CONTEXT_SELECTION, point.x, point.y, this); else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_BOOKMARKS, point.x, point.y, this); else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_HIGHLIGHT, point.x, point.y, this); else if (pos2row(doc_pt) == 0) pCMM->ShowPopupMenu(IDR_CONTEXT_CHAR, point.x, point.y, this); else pCMM->ShowPopupMenu(IDR_CONTEXT_HEX, point.x, point.y, this); } else if (!display_.char_area || doc_pt.x < char_pos(0)) { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in hex area FILE_ADDRESS addr = (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_hex(doc_pt.x); if (addr >= start_addr && addr < end_addr) pCMM->ShowPopupMenu(IDR_CONTEXT_SELECTION, point.x, point.y, this); else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_BOOKMARKS, point.x, point.y, this); else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_HIGHLIGHT, point.x, point.y, this); else pCMM->ShowPopupMenu(IDR_CONTEXT_HEX, point.x, point.y, this); } else { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in char area FILE_ADDRESS addr = (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_char(doc_pt.x); if (addr >= start_addr && addr < end_addr) pCMM->ShowPopupMenu(IDR_CONTEXT_SELECTION, point.x, point.y, this); else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_BOOKMARKS, point.x, point.y, this); else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_HIGHLIGHT, point.x, point.y, this); else pCMM->ShowPopupMenu(IDR_CONTEXT_CHAR, point.x, point.y, this); } #endif } ///////////////////////////////////////////////////////////////////////////// // CHexEditView command handlers void CHexEditView::OnRedraw() { CRect cli; // Work out window height in logical units GetDisplayRect(&cli); CRectAp doc_rect = ConvertFromDP(cli); // Move display so that caret is centred vertically CPointAp pp = GetCaret(); pp.x = 0; // Scroll to left side (but see DisplayCaret() below) if ((pp.y -= (doc_rect.bottom-doc_rect.top)/2) < 0) pp.y = 0; SetScroll(pp); DoInvalidate(); // Also redraw display DisplayCaret(); // Make sure caret not off right side ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_redraw); } void CHexEditView::OnScrollDown() { CPointAp pp = GetScroll(); pp.y += text_height_; SetScroll(pp); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_scroll_down); } void CHexEditView::OnScrollUp() { CPointAp pp = GetScroll(); pp.y -= text_height_; SetScroll(pp); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_scroll_up); } // Move current position to start of display line void CHexEditView::OnStartLine() { num_entered_ = num_del_ = num_bs_ = 0; // Turn off any consec edits FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Check if offset has actually changed if (real_offset_ != (rowsize_ - start_addr%rowsize_)%rowsize_) { undo_.push_back(view_undo(undo_offset)); undo_.back().rowsize = real_offset_; // Save previous offset for undo real_offset_ = offset_ = int((rowsize_ - start_addr%rowsize_)%rowsize_); SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); recalc_display(); DoInvalidate(); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_start_line); } else { ((CMainFrame *)AfxGetMainWnd())->StatusBarText("Warning: offset not changed"); ((CHexEditApp *)AfxGetApp())->mac_error_ = 1; } } void CHexEditView::OnSwap() { if (display_.vert_display) return; CHECK_SECURITY(32); if (display_.char_area && display_.hex_area) { num_entered_ = num_del_ = num_bs_ = 0; // Turn off any consec edits // Swap between hex and char areas FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); undo_.push_back(view_undo(undo_state)); undo_.back().disp_state = disp_state_; display_.edit_char = !display_.edit_char; if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); if (end_base) SetSel(addr2pos(end_addr), addr2pos(start_addr), true); else SetSel(addr2pos(start_addr), addr2pos(end_addr)); DisplayCaret(); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_swap_areas); } else { AfxMessageBox("Cannot swap to character area - not displayed"); ((CHexEditApp *)AfxGetApp())->mac_error_ = 5; } } void CHexEditView::OnUpdateSwap(CCmdUI* pCmdUI) { pCmdUI->Enable(display_.char_area && display_.hex_area); // disallow swap if both areas not displayed } void CHexEditView::OnDel() { num_entered_ = 0; // Not entering but deleting CPointAp pt_start, pt_end; if (GetSel(pt_start, pt_end)) SetSel(pt_end, pt_start, true); else SetSel(pt_start, pt_end); // Calls ValidateCaret - causing caret selection to be moved to valid locations if (check_ro("delete")) return; if (display_.overtype) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("You can't delete while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) return; else if (!do_insert()) return; } // Handle deletion of chars at caret or selection FILE_ADDRESS start, end; GetSelAddr(start, end); // address = pos2addr(GetCaret()); CHECK_SECURITY(190); if (start == end) { // if ((long)nRepCnt > GetDocument()->length() - start) // nRepCnt = (UINT)(GetDocument()->length() - start); // if (nRepCnt > 0) // GetDocument()->Change(mod_delforw, start, nRepCnt, // NULL, num_del_, this); // num_del_ += nRepCnt*2; if (start >= GetDocument()->length()) { ((CHexEditApp *)AfxGetApp())->mac_error_ = 2; return; } GetDocument()->Change(mod_delforw, start, 1, NULL, num_del_, this); num_del_ += 2; } else { GetDocument()->Change(mod_delforw, start, end-start, NULL, 0, this); num_del_ = 0; // Make sure this is separate deletion } DisplayCaret(); // Make sure caret is visible ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_del); } void CHexEditView::OnSelectAll() { num_entered_ = num_del_ = num_bs_ = 0; // Can't be editing while mousing GetSelAddr(prev_start_, prev_end_); prev_row_ = 0; if (prev_start_ == prev_end_ && display_.vert_display) prev_row_ = pos2row(GetCaret()); SetSel(addr2pos(0), addr2pos(GetDocument()->length())); show_prop(); show_calc(); show_pos(); // Save in undo array if position moved if (prev_start_ != 0 || prev_end_ != GetDocument()->length()) { // Save the caret position (or start of selection) undo_.push_back(view_undo(undo_move)); undo_.back().address = prev_start_ | (FILE_ADDRESS(prev_row_)<<62); if (prev_start_ != prev_end_) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end_; } nav_save(0, GetDocument()->length(), "Select All "); } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_sel_all); } void CHexEditView::OnSelectLine() { num_entered_ = num_del_ = num_bs_ = 0; GetSelAddr(prev_start_, prev_end_); prev_row_ = 0; if (prev_start_ == prev_end_ && display_.vert_display) prev_row_ = pos2row(GetCaret()); FILE_ADDRESS new_start = ((prev_start_+offset_)/rowsize_) * rowsize_ - offset_; FILE_ADDRESS new_end = ((prev_end_+offset_)/rowsize_ + 1) * rowsize_ - offset_; ASSERT(new_end > new_start); SetSel(addr2pos(new_start), addr2pos(new_end)); show_prop(); show_calc(); show_pos(); // Save in undo array if position moved if (prev_start_ != new_start || prev_end_ != new_end) { // Save the caret position (or start of selection) undo_.push_back(view_undo(undo_move)); undo_.back().address = prev_start_ | (FILE_ADDRESS(prev_row_)<<62); if (prev_start_ != prev_end_) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end_; } nav_save(new_start, new_end, "Select Line "); } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_sel_line); } void CHexEditView::OnInsertBlock() { CNewFile dlg(this, true); if (dlg.DoModal() == IDOK) { const char *data_str = NULL; dlg.fill_.create_on_disk = 0; // Make sure we are not creating a new file switch (dlg.fill_.type) { default: ASSERT(0); // fall through case CNewFile::FILL_HEX: // count hex digits data_str = dlg.fill_hex_value_; break; case CNewFile::FILL_STRING: // string data_str = dlg.fill_string_value_; break; case CNewFile::FILL_CLIPBOARD: // clipboard break; case CNewFile::FILL_RANDOM: // random - default to one byte data_str = dlg.fill_random_range_; break; case CNewFile::FILL_NUMBER: // number - get size from type data_str = dlg.fill_number_value_; break; } do_insert_block(dlg.fill_state_, data_str); } } void CHexEditView::do_insert_block(_int64 params, const char *data_str) { // Can't modify the file if view is read only or in overtype mode if (check_ro("insert block")) return; if (display_.overtype) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("You can't insert a block while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 5; return; } else if (!do_insert()) return; } num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing FILE_ADDRESS addr = GetPos(); // Current caret (address to insert file) FILE_ADDRESS len = GetDocument()->insert_block(addr, params, data_str, this); if (len > -1) { SetSel(addr2pos(addr), addr2pos(addr+len)); DisplayCaret(); theApp.SaveToMacro(km_insert, params); theApp.SaveToMacro(km_insert_str, data_str); } } void CHexEditView::OnUpdateInsertBlock(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); // disallow insert if file is read only } // Get file name, insert into document and select inserted bytes void CHexEditView::OnReadFile() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Get name of file to read CHexFileDialog dlgFile("ReadFileDlg", HIDD_FILE_READ, TRUE, NULL, aa->current_read_, OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_DONTADDTORECENT, aa->GetCurrentFilters(), "Read", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Insert File"; if (dlgFile.DoModal() == IDOK) { aa->current_read_ = dlgFile.GetPathName(); CHECK_SECURITY(23); do_read(aa->current_read_); } } // Actually open and read the file and select the inserted bytes void CHexEditView::do_read(CString file_name) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Can't modify the file if view is read only or in overtype mode if (check_ro("insert file")) return; if (display_.overtype) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("You can't insert a file while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 5; return; } else if (!do_insert()) return; } num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing FILE_ADDRESS addr = GetPos(); // Current caret (address to insert file) FILE_ADDRESS data_len = CFile64::GetSize(file_name); if (data_len == 0) { // No need to insert a zero length file ((CMainFrame *)AfxGetMainWnd())->StatusBarText("File is empty: nothing inserted"); aa->mac_error_ = 1; return; } int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) if (data_len > (16*1024*1024) && (idx = GetDocument()->AddDataFile(file_name)) != -1) { // Use the file in situ GetDocument()->Change(mod_insert_file, addr, data_len, NULL, idx, this); } else { if (data_len > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files \n" "and cannot open such a large file. \n" "Please save the file to free \n" "temporary file handles and try again.\n", MB_OK); return; } if (data_len > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and opening such a large file may \n" "cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) return; } // Open the file for reading CFile ff; // Don't make this CFile64 as we don't want to read > 2Gbytes into memory CFileException fe; // Used to receive file error information if (!ff.Open(file_name, CFile::modeRead|CFile::shareDenyWrite|CFile::typeBinary, &fe) ) { // Display info about why the open failed CString mess(file_name); CFileStatus fs; switch (fe.m_cause) { case CFileException::fileNotFound: mess += "\rdoes not exist"; break; case CFileException::badPath: mess += "\ris an invalid file name or the drive/path does not exist"; break; case CFileException::tooManyOpenFiles: mess += "\r- too many files already open"; break; case CFileException::accessDenied: if (!CFile::GetStatus(file_name, fs)) mess += "\rdoes not exist"; else { if (fs.m_attribute & CFile::directory) mess += "\ris a directory"; else if (fs.m_attribute & (CFile::volume|CFile::hidden|CFile::system)) mess += "\ris a special file"; else mess += "\rcannot be used (reason unknown)"; } break; case CFileException::sharingViolation: case CFileException::lockViolation: mess += "\ris in use"; break; case CFileException::hardIO: mess += "\r- hardware error"; break; default: mess += "\rcould not be opened (reason unknown)"; break; } AfxMessageBox(mess); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) // If the user tries to insert a huge file we might run out of memory so catch this try { // Get memory to read all of the file unsigned char *file_data = new unsigned char[size_t(data_len)]; // Read the file into memory if (ff.Read((void *)file_data, (UINT)data_len) != data_len) { AfxMessageBox("Not all of the file could be read"); aa->mac_error_ = 10; return; } ff.Close(); // Make the memory part of the document GetDocument()->Change(mod_insert, addr, data_len, file_data, 0, this); delete[] file_data; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); aa->mac_error_ = 10; return; } } ASSERT(data_len > 0); SetSel(addr2pos(addr), addr2pos(addr+data_len)); DisplayCaret(); aa->SaveToMacro(km_read_file, file_name); } void CHexEditView::OnUpdateReadFile(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); // disallow insert if file is read only } void CHexEditView::OnEditWriteFile() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start == end) { // Nothing selected, presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("Nothing selected to write to file!"); aa->mac_error_ = 10; return; } // Get the file name to write the selection to CHexFileDialog dlgFile("WriteFileDlg", HIDD_FILE_WRITE, FALSE, NULL, aa->current_write_, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_SHOWHELP | OFN_NOCHANGEDIR, aa->GetCurrentFilters(), "Write", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Save Selection As"; // if (!aa->current_write_.IsEmpty()) // dlgFile.m_ofn.lpstrInitialDir = aa->current_write_; if (dlgFile.DoModal() != IDOK) { aa->mac_error_ = 2; return; } aa->current_write_ = dlgFile.GetPathName(); CHECK_SECURITY(25); // Write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) if (GetDocument()->WriteData(aa->current_write_, start, end)) aa->SaveToMacro(km_write_file); else aa->current_write_.Empty(); } void CHexEditView::OnEditAppendFile() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start == end) { // Nothing selected, presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("Nothing selected to append to file!"); aa->mac_error_ = 10; return; } // Get the file name to write the selection to CHexFileDialog dlgFile("WriteFileDlg", HIDD_FILE_APPEND, TRUE, NULL, aa->current_write_, OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_DONTADDTORECENT, aa->GetCurrentFilters(), "Append", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Append Selection To"; if (dlgFile.DoModal() != IDOK) { aa->mac_error_ = 2; return; } CHECK_SECURITY(15); aa->current_write_ = dlgFile.GetPathName(); // Write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) if (GetDocument()->WriteData(aa->current_write_, start, end, TRUE)) aa->SaveToMacro(km_append_file); else aa->current_write_.Empty(); } void CHexEditView::OnEditAppendSameFile() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); CHECK_SECURITY(25); if (start == end) { // Nothing selected, presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("Nothing selected to append to file!"); aa->mac_error_ = 10; return; } // Write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) if (GetDocument()->WriteData(aa->current_write_, start, end, TRUE)) aa->SaveToMacro(km_append_same_file); else aa->current_write_.Empty(); } void CHexEditView::OnUpdateEditAppendSameFile(CCmdUI* pCmdUI) { if (theApp.current_write_.IsEmpty()) pCmdUI->Enable(FALSE); else OnUpdateClipboard(pCmdUI); } void CHexEditView::OnExportSRecord(UINT nID) { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); // If no selection and no highlight there is nothing to do if (start == end && hl_set_.empty()) { AfxMessageBox("Nothing to export!"); theApp.mac_error_ = 10; return; } // Get the file name to write to (plus discontinuous setting) CExportDialog dlgFile(theApp.current_export_, HIDD_FILE_EXPORT_MOTOROLA, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_SHOWHELP | OFN_NOCHANGEDIR, "Motorola S Files (*.s)|*.s|"+theApp.GetCurrentFilters(), this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Export S Records"; if (dlgFile.DoModal() != IDOK) { theApp.mac_error_ = 2; return; } theApp.current_export_ = dlgFile.GetPathName(); CHECK_SECURITY(25); if (theApp.import_discon_) { if (hl_set_.empty()) { AfxMessageBox("Nothing highlighted to export!"); theApp.mac_error_ = 10; return; } // Set start and end to the range of highlighted bytes start = *hl_set_.begin(); // First highlighted byte end = *hl_set_.rbegin(); // Last highlighted byte } else { if (start == end) { // Nothing selected AfxMessageBox("Nothing selected to export!"); theApp.mac_error_ = 10; return; } } // Check the range of exported addresses to check that they are valid FILE_ADDRESS last_S_address; // Byte past the last address to be written out int stype = 3; // Type of data records to write (S1, S2, or S3) if (theApp.export_base_addr_ < 0) last_S_address = end; else last_S_address = end - start + theApp.export_base_addr_; // Check that end address is not too big for S Record if (nID == ID_EXPORT_S1) { // Addresses must be within 16 bit range if (last_S_address > 0x10000) { AfxMessageBox("Addresses too big for S1 export!"); theApp.mac_error_ = 10; return; } stype = 1; } else if (nID == ID_EXPORT_S2) { // Addresses must be within 24 bit range if (last_S_address > 0x1000000) { AfxMessageBox("Addresses too big for S2 export!"); theApp.mac_error_ = 10; return; } stype = 2; } else if (nID == ID_EXPORT_S3) { // Addresses must be within 32 bit range if (last_S_address > 0x100000000) { AfxMessageBox("Addresses too big for S3 export!"); theApp.mac_error_ = 10; return; } ASSERT(stype == 3); } // Get ready to write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) CWriteSRecord wsr(theApp.current_export_, theApp.export_base_addr_ >= 0 ? theApp.export_base_addr_ : long(start), stype, theApp.export_line_len_); if (!wsr.Error().IsEmpty()) { AfxMessageBox(wsr.Error()); theApp.mac_error_ = 10; theApp.current_export_.Empty(); return; } unsigned char *buf = new unsigned char[4096]; size_t len; if (theApp.import_discon_) { unsigned long base_address = 0; if (theApp.export_base_addr_ >= 0) base_address = unsigned long(theApp.export_base_addr_ - start); // This puts 1st rec at export address of zero range_set<FILE_ADDRESS>::range_t::iterator pp; for (pp = hl_set_.range_.begin(); pp != hl_set_.range_.end(); ++pp) for (FILE_ADDRESS curr = pp->sfirst; curr < pp->slast; curr += len) { len = int(min(4096, pp->slast - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); wsr.Put(buf, len, unsigned long(base_address + curr)); if (!wsr.Error().IsEmpty()) { AfxMessageBox(wsr.Error()); theApp.mac_error_ = 10; theApp.current_export_.Empty(); goto export_end; } } } else { FILE_ADDRESS curr; for (curr = start; curr < end; curr += len) { len = min(4096, int(end - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); wsr.Put(buf, len); if (!wsr.Error().IsEmpty()) { AfxMessageBox(wsr.Error()); theApp.mac_error_ = 10; theApp.current_export_.Empty(); goto export_end; } } ASSERT(curr == end); } export_end: delete[] buf; if (theApp.mac_error_ < 10) theApp.SaveToMacro(km_write_file, stype); // stype == 1,2, or 3 } void CHexEditView::OnUpdateExportSRecord(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start == end) { // We can still export based on highlights if (hl_set_.empty()) { pCmdUI->Enable(FALSE); return; } FILE_ADDRESS hl_start, hl_end; hl_start = *hl_set_.begin(); // First highlighted byte hl_end = *hl_set_.rbegin(); // Last highlighted byte // Not quite right but should prevent valid export cmds from being disabled if (hl_start > start) start = hl_start; if (hl_end < end) end = hl_end; } // Work out the last address that needs to be exported if (theApp.export_base_addr_ >= 0) end = end - start + theApp.export_base_addr_; if (pCmdUI->m_nID == ID_EXPORT_S1) { // Addresses must be within 16 bit range pCmdUI->Enable(end <= 0x10000); } else if (pCmdUI->m_nID == ID_EXPORT_S2) { // Addresses must be within 24 bit range pCmdUI->Enable(end <= 0x1000000); } else if (pCmdUI->m_nID == ID_EXPORT_S3) { // Addresses must be within 32 bit range pCmdUI->Enable(end <= 0x100000000); } } void CHexEditView::OnImportMotorolaS() { // Get name of file to import // CFileDialog dlgFile(TRUE, NULL, theApp.current_import_, // OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, // theApp.GetCurrentFilters(), this); CImportDialog dlgFile(theApp.current_import_, HIDD_FILE_IMPORT_MOTOROLA, OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_DONTADDTORECENT, "Motorola S Files (*.s)|*.s|"+theApp.GetCurrentFilters(), this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Import Motorola S Records"; if (dlgFile.DoModal() == IDOK) { theApp.current_import_ = dlgFile.GetPathName(); do_motorola(theApp.current_import_); } } void CHexEditView::do_motorola(CString file_name) { if (check_ro("import file")) return; if (!theApp.import_discon_ && display_.overtype) { if (AfxMessageBox("You can't import (non-adjoining) while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 5; return; } else if (!do_insert()) return; } num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CWaitCursor wait; // Turn on wait cursor (hourglass) CHECK_SECURITY(33); if (theApp.import_discon_) { BOOL ptoo = FALSE; // First change is new undo op, thence merged with it if (theApp.import_highlight_ && !hl_set_.empty()) { undo_.push_back(view_undo(undo_highlight)); undo_.back().phl = new range_set<FILE_ADDRESS>(hl_set_); hl_set_.clear(); DoInvalidate(); ptoo = TRUE; } CReadSRecord rsr(file_name, TRUE); if (!rsr.Error().IsEmpty()) { AfxMessageBox(rsr.Error()); theApp.mac_error_ = 10; return; } // Read int count, skipped; // Total records read and ignored size_t data_len = 1024; unsigned char *file_data = new unsigned char[data_len]; // one S record unsigned long address; int len; // length of data from one S record for (count = skipped = 0; (len = rsr.Get(file_data, data_len, address)) > 0; ++count) { if (address + len > GetDocument()->length()) { ++skipped; continue; } if (theApp.import_highlight_) { // Highlight the record add_highlight(address, address+len, ptoo); ptoo = TRUE; } GetDocument()->Change(mod_replace, FILE_ADDRESS(address), FILE_ADDRESS(len), file_data, 0, this, ptoo); ptoo = TRUE; // force subsequent changes to be merged into same undo operation } delete[] file_data; if (!rsr.Error().IsEmpty()) AfxMessageBox(rsr.Error()); CString mess; if (skipped > 0) mess.Format("Wrote %ld records\r\nIgnored %ld records\r\nimporting \"%s\"", long(count - skipped), long(skipped), file_name); else mess.Format("Wrote %ld records importing \"%s\"", long(count), file_name); AfxMessageBox(mess); theApp.SaveToMacro(km_import_motorola, file_name); } else { CReadSRecord rsr(file_name); if (!rsr.Error().IsEmpty()) { AfxMessageBox(rsr.Error()); theApp.mac_error_ = 10; return; } // We need to store the data in fairly large chunks otherwise the doc undo // stack becomes very full and slows things down size_t data_len = 32768; unsigned char *file_data = new unsigned char[data_len]; // work buffer unsigned char *pp = file_data; // Ptr into file_data where we are currently storing unsigned long address; // Import S record address (ignored) int len; // length of data from one S record bool first(true); // is this the first S record read from the file FILE_ADDRESS start_addr, end_addr, curr_addr = -1; GetSelAddr(start_addr, end_addr); // Get the current selection for (;;) { len = rsr.Get(pp, data_len - (pp - file_data), address); if (len <= 0 || (pp - file_data) + len > (int(data_len) - 256)) { // The buffer is almost full or we're finished reading the file - so save buffer if (first) { curr_addr = start_addr; if (start_addr < end_addr) { // Delete current selection and insert new data GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this, TRUE); } else GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this); first = false; } else { ASSERT(curr_addr != -1); GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this, TRUE); } curr_addr += pp - file_data + len; pp = file_data; } else pp += len; if (len <= 0) break; } delete[] file_data; if (!rsr.Error().IsEmpty()) AfxMessageBox(rsr.Error()); theApp.SaveToMacro(km_import_motorola, file_name); SetSel(addr2pos(start_addr), addr2pos(curr_addr)); DisplayCaret(); } } void CHexEditView::OnUpdateImportMotorolaS(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); // disallow insert if file is read only } void CHexEditView::OnImportIntel() { // Get name of file to import // CFileDialog dlgFile(TRUE, NULL, theApp.current_import_, // OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, // theApp.GetCurrentFilters(), this); CImportDialog dlgFile(theApp.current_import_, HIDD_FILE_IMPORT_INTEL, OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_DONTADDTORECENT, "Intel Hex Files (*,hex, *.ihx)|*.hex;*.ihx|"+theApp.GetCurrentFilters(), this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Import Intel Hex File"; if (dlgFile.DoModal() == IDOK) { theApp.current_import_ = dlgFile.GetPathName(); do_intel(theApp.current_import_); } } void CHexEditView::do_intel(CString file_name) { if (check_ro("import Intel hex file")) return; if (!theApp.import_discon_ && display_.overtype) { if (AfxMessageBox("You can't import (non-adjoining) while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 5; return; } else if (!do_insert()) return; } num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHECK_SECURITY(32); CWaitCursor wait; // Turn on wait cursor (hourglass) if (theApp.import_discon_) { BOOL ptoo = FALSE; // First change is new undo op, thence merged with it if (theApp.import_highlight_ && !hl_set_.empty()) { undo_.push_back(view_undo(undo_highlight)); undo_.back().phl = new range_set<FILE_ADDRESS>(hl_set_); hl_set_.clear(); DoInvalidate(); ptoo = TRUE; } CReadIntelHex rih(file_name, TRUE); if (!rih.Error().IsEmpty()) { AfxMessageBox(rih.Error()); theApp.mac_error_ = 10; return; } // Read int count, skipped; // Total records read and ignored size_t data_len = 1024; unsigned char *file_data = new unsigned char[data_len]; // one S record unsigned long address; int len; // length of data from one S record for (count = skipped = 0; (len = rih.Get(file_data, data_len, address)) > 0; ++count) { if (address + len > GetDocument()->length()) { ++skipped; continue; } if (theApp.import_highlight_) { // Highlight the record add_highlight(address, address+len, ptoo); ptoo = TRUE; } GetDocument()->Change(mod_replace, FILE_ADDRESS(address), FILE_ADDRESS(len), file_data, 0, this, ptoo); ptoo = TRUE; // force subsequent changes to be merged into same undo operation } delete[] file_data; if (!rih.Error().IsEmpty()) AfxMessageBox(rih.Error()); CString mess; if (skipped > 0) mess.Format("Wrote %ld records\r\nIgnored %ld records\r\nimporting \"%s\"", long(count - skipped), long(skipped), file_name); else mess.Format("Wrote %ld records importing \"%s\"", long(count), file_name); AfxMessageBox(mess); theApp.SaveToMacro(km_import_intel, file_name); } else { CReadIntelHex rih(file_name); if (!rih.Error().IsEmpty()) { AfxMessageBox(rih.Error()); theApp.mac_error_ = 10; return; } // We need to store the data in fairly large chunks otherwise the doc undo // stack becomes very full and slows things down size_t data_len = 32768; unsigned char *file_data = new unsigned char[data_len]; // work buffer unsigned char *pp = file_data; // Ptr into file_data where we are currently storing int len; // length of data from one S record unsigned long address; // Import record address (ignored) bool first(true); // is this the first S record read from the file FILE_ADDRESS start_addr, end_addr, curr_addr = -1; GetSelAddr(start_addr, end_addr); // Get the current selection for (;;) { len = rih.Get(pp, data_len - (pp - file_data), address); if (len <= 0 || (pp - file_data) + len > (int(data_len) - 256)) { // The buffer is almost full or we're finished reading the file - so save buffer if (first) { curr_addr = start_addr; if (start_addr < end_addr) { // Delete current selection and insert new data GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this, TRUE); } else GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this); first = false; } else { ASSERT(curr_addr != -1); GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this, TRUE); } curr_addr += pp - file_data + len; pp = file_data; } else pp += len; if (len <= 0) break; } delete[] file_data; if (!rih.Error().IsEmpty()) AfxMessageBox(rih.Error()); theApp.SaveToMacro(km_import_intel, file_name); SetSel(addr2pos(start_addr), addr2pos(curr_addr)); DisplayCaret(); } } void CHexEditView::OnUpdateImportIntel(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); // disallow insert if file is read only } void CHexEditView::OnExportIntel() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start == end) { // Nothing selected, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("Nothing selected to export!"); theApp.mac_error_ = 10; return; } FILE_ADDRESS last_address; // Byte past the last address to be written out if (theApp.export_base_addr_ < 0) last_address = end; else last_address = end - start + theApp.export_base_addr_; // Check that end address is not too big for Intel Hex Record // Addresses must be within 16 bit range if (last_address > 0x10000) { ASSERT(theApp.playing_); AfxMessageBox("End address too big for Intel hex address field!"); theApp.mac_error_ = 10; return; } // Get the file name to write the selection to CHexFileDialog dlgFile("ExportFileDlg", HIDD_FILE_EXPORT_INTEL, FALSE, NULL, theApp.current_export_, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_SHOWHELP | OFN_NOCHANGEDIR, theApp.GetCurrentFilters(), "Export", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Export Intel Hex"; if (dlgFile.DoModal() != IDOK) { theApp.mac_error_ = 2; return; } theApp.current_export_ = dlgFile.GetPathName(); // Write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) CWriteIntelHex wih(theApp.current_export_, theApp.export_base_addr_ >= 0 ? theApp.export_base_addr_ : long(start), theApp.export_line_len_); if (!wih.Error().IsEmpty()) { AfxMessageBox(wih.Error()); theApp.mac_error_ = 10; theApp.current_export_.Empty(); } else { unsigned char *buf = new unsigned char[4096]; size_t len; CHECK_SECURITY(16); FILE_ADDRESS curr; for (curr = start; curr < end; curr += len) { len = min(4096, int(end - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); wih.Put(buf, len); if (!wih.Error().IsEmpty()) { AfxMessageBox(wih.Error()); theApp.mac_error_ = 10; theApp.current_export_.Empty(); break; } } delete[] buf; ASSERT(curr == end); if (theApp.mac_error_ < 10) theApp.SaveToMacro(km_write_file, 7); } } void CHexEditView::OnUpdateExportIntel(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start >= end) { // We can't export if there is no selection at all pCmdUI->Enable(FALSE); return; } // Work out the last address that needs to be exported if (theApp.export_base_addr_ >= 0) end = end - start + theApp.export_base_addr_; // Addresses must be within 16 bit range pCmdUI->Enable(end <= 0x10000); } void CHexEditView::OnImportHexText() { // Get name of file to import CHexFileDialog dlgFile("ImportFileDlg", HIDD_FILE_IMPORT_HEX, TRUE, NULL, theApp.current_import_, OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_DONTADDTORECENT, theApp.GetCurrentFilters(), "Import", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Import Hex Text File"; if (dlgFile.DoModal() == IDOK) { theApp.current_import_ = dlgFile.GetPathName(); do_hex_text(theApp.current_import_); } } void CHexEditView::do_hex_text(CString file_name) { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (check_ro("import hex text file")) return; if (display_.overtype) { if (AfxMessageBox("You can't import while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 5; return; } else if (!do_insert()) return; } num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHECK_SECURITY(30); CWaitCursor wait; // Turn on wait cursor (hourglass) CStdioFile ff; // Text file we are reading from CFileException fe; // Stores file exception info // Open the text (input) file if (!ff.Open(file_name, CFile::modeRead|CFile::shareDenyWrite|CFile::typeText, &fe)) { AfxMessageBox(::FileErrorMessage(&fe, CFile::modeRead)); theApp.mac_error_ = 10; return; } __int64 file_len = CFile64::GetSize(file_name); __int64 file_done = 0; // amt of file read so far // Set up handling of a large input hex file by writing result to one of our temp files CFile64 fout; // output file (only used if input file is big) char temp_file[_MAX_PATH]; temp_file[0] = '\0'; // Test if the file is very big if (file_len > (3*16*1024*1024) && GetDocument()->DataFileSlotFree()) // assuming 3 chars/byte ~= 16 Mb { // Create a file to store the bytes char temp_dir[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); if (!fout.Open(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary, &fe)) { AfxMessageBox(::FileErrorMessage(&fe, CFile::modeWrite)); theApp.mac_error_ = 10; return; } } else if (file_len > 3*128*1024*1024) { // Warn of possible memory shortage if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and reading such a large file \n" "may cause memory exhaustion. Please click NO \n" "and save the active file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } // Input buffer (read from hex text file) char buffer[520]; // Where read string is stored char *pp; // Ptr into read string long line_no = 0; // Current text line read // We need to store the data in fairly large chunks otherwise the doc undo // stack becomes very full and slows things down size_t data_len = 32768; unsigned char *file_data = NULL; // work buffer try { file_data = new unsigned char[data_len]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } unsigned char *pout = file_data; // Ptr into file_data where we are currently storing bool first(true); // is this the first line read from the file FILE_ADDRESS start_addr, end_addr, curr_addr = -1; GetSelAddr(start_addr, end_addr); // Get the current selection buffer[0] = '\0'; pp = buffer; for (;;) // loop on output bytes (one or two input hecx digits) { // Skip whitespace/unused characters etc while (*pp != '\0' && !isalpha(*pp) && !isdigit(*pp)) ++pp; // If at end of string get the next line from the file while (*pp == '\0') // skip strings till we get a non-empty one { file_done += pp - buffer + 2; try { pp = ff.ReadString(buffer, sizeof(buffer)-1); ++line_no; } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeRead)); pfe->Delete(); goto error_return; } if (pp == NULL) goto end_file; // EOF // Skip leading whitespace/unused characters etc while (*pp != '\0' && !isalpha(*pp) && !isdigit(*pp)) ++pp; } if (!isxdigit(*pp)) { CString ss; ss.Format("Unexpected alpha characters in hex text file at line %ld", long(line_no)); AfxMessageBox(ss); goto error_return; } if (isdigit(*pp)) *pout = *pp - '0'; else if (isupper(*pp)) *pout = *pp - 'A' + 10; else *pout = *pp - 'a' + 10; ++pp; // If pair of hex digits read as 2 nybbles of a byte if (isxdigit(*pp)) { if (isdigit(*pp)) *pout = (*pout << 4) | (*pp - '0'); else if (isupper(*pp)) *pout = (*pout << 4) | (*pp - 'A' + 10); else *pout = (*pout << 4) | (*pp - 'a' + 10); ++pp; } // Check if the output buffer is full if (++pout >= file_data + data_len) { ASSERT(pout == file_data + data_len); // The buffer is almost full or we're finished reading the file - so save buffer if (fout.GetHandle() != INVALID_HANDLE_VALUE) { // Writing to temp file try { fout.Write(file_data, data_len); } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); fout.Close(); remove(temp_file); goto error_return; } if (AbortKeyPress() && AfxMessageBox("Abort hex import?", MB_YESNO) == IDYES) { fout.Close(); remove(temp_file); goto error_return; } mm->Progress(int((file_done*100)/file_len)); } else if (first) { // First in memory block to be stored - may replace the current selection ASSERT(curr_addr == -1); curr_addr = start_addr; if (start_addr < end_addr) { // Delete current selection and insert new data GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this, TRUE); } else GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this); first = false; } else { // Next in memory block - just insert it ASSERT(curr_addr != -1); GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this, TRUE); } curr_addr += pout - file_data; pout = file_data; } } end_file: // Write out any partial buffer at end if (pout > file_data) { if (fout.GetHandle() != INVALID_HANDLE_VALUE) { // Writing to temp file try { fout.Write(file_data, pout - file_data); } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); fout.Close(); remove(temp_file); goto error_return; } } else if (first) { ASSERT(curr_addr == -1); curr_addr = start_addr; if (start_addr < end_addr) { // Delete current selection and insert new data GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this, TRUE); } else GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this); first = false; } else { ASSERT(curr_addr != -1); GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this, TRUE); } curr_addr += pout - file_data; } if (fout.GetHandle() != INVALID_HANDLE_VALUE) { FILE_ADDRESS fout_len = fout.GetLength(); fout.Close(); // close the file so we can use it // Add the temp file to the document int idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); if (start_addr < end_addr) { // Delete current selection and insert new data GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert_file, start_addr, fout_len, NULL, idx, this, TRUE); } else GetDocument()->Change(mod_insert_file, start_addr, fout_len, NULL, idx, this); // NOTE: curr_data is not used when writing to temp file except below (in selecting // the inserted data) - so we have to set it here. curr_addr = start_addr + fout_len; } delete[] file_data; mm->Progress(-1); // disable progress bar SetSel(addr2pos(start_addr), addr2pos(curr_addr)); DisplayCaret(); theApp.SaveToMacro(km_import_text, file_name); return; error_return: delete[] file_data; mm->Progress(-1); // disable progress bar theApp.mac_error_ = 10; } void CHexEditView::OnUpdateImportHexText(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); // disallow insert if file is read only } void CHexEditView::OnExportHexText() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); ASSERT(start_addr >= 0 && start_addr <= end_addr && end_addr <= GetDocument()->length()); if (start_addr >= end_addr) { // Nothing selected, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("Nothing selected to export!"); theApp.mac_error_ = 10; return; } // Get the file name to write the selection to CHexFileDialog dlgFile("ExportFileDlg", HIDD_FILE_EXPORT_HEX, FALSE, NULL, theApp.current_export_, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_SHOWHELP | OFN_NOCHANGEDIR, theApp.GetCurrentFilters(), "Export", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Export Hex Text"; if (dlgFile.DoModal() != IDOK) { theApp.mac_error_ = 2; return; } theApp.current_export_ = dlgFile.GetPathName(); // Now write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) CHECK_SECURITY(48); CFile64 ff; CFileException fe; // Stores file exception info // Open the file to export to if (!ff.Open(theApp.current_export_, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary, &fe)) { AfxMessageBox(::FileErrorMessage(&fe, CFile::modeWrite)); theApp.mac_error_ = 10; theApp.current_export_.Empty(); return; } // This could be perhaps 2 or 3 times faster by buffering more than a line of text at a time // Buffer used to hold bits of the binary file to convert unsigned char *buf = NULL; // Buffer to hold some input char *out = NULL; // Buffer for output of one line of text unsigned char *pin; FILE_ADDRESS curr; size_t len; try { buf = new unsigned char[theApp.export_line_len_]; out = new char[3*theApp.export_line_len_ + 5]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } const char *hex; if (theApp.hex_ucase_) hex = "0123456789ABCDEF?"; else hex = "0123456789abcdef?"; clock_t last_checked = clock(); for (curr = start_addr; curr < end_addr; curr += len) { // Get the data bytes len = size_t(min(FILE_ADDRESS(theApp.export_line_len_), end_addr - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); // Convert to hex text char *pout = out; for(pin = buf; pin < buf+len; ++pin) { *pout++ = hex[(*pin>>4)&0xF]; *pout++ = hex[*pin&0xF]; *pout++ = ' '; } *pout++ = '\r'; *pout++ = '\n'; // Write the string to the file try { ff.Write(out, pout - out); } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); theApp.mac_error_ = 10; goto func_return; } if (AbortKeyPress() && AfxMessageBox("Abort exporting as hex?", MB_YESNO) == IDYES) { theApp.mac_error_ = 10; goto func_return; } if (double(clock() - last_checked)/CLOCKS_PER_SEC > 3) // update every 3 secs { mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); last_checked = clock(); } } ASSERT(curr == end_addr); func_return: ff.Close(); mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; if (out != NULL) delete[] out; if (theApp.mac_error_ < 5) theApp.SaveToMacro(km_write_file, 10); } void CHexEditView::OnUpdateExportHexText(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); pCmdUI->Enable(start < end); } // This is here only so we can put it in context menu for view void CHexEditView::OnEditFind() { ((CMainFrame *)AfxGetMainWnd())->OnEditFind(); } // This is here only so we can put it in context menu for view void CHexEditView::OnEditReplace() { ((CMainFrame *)AfxGetMainWnd())->OnEditReplace(); } // This is here only so we can put it in context menu for view void CHexEditView::OnEditGoto() { ((CMainFrame *)AfxGetMainWnd())->OnEditGoto(); } void CHexEditView::OnCalcSel() { ((CMainFrame *)AfxGetMainWnd())->OnCalcSel(); } void CHexEditView::OnUpdateCalcSel(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); pCmdUI->Enable(end_addr - start_addr < 9); } void CHexEditView::OnEditCut() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar // Can't delete if view is read only or in overtype mode if (check_ro("cut to the clipboard")) return; if (display_.overtype) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("You can't cut while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 5; return; } else if (!do_insert()) return; } // Copy the selection to the clipboard and then delete it if (!CopyToClipboard()) { ASSERT(aa->mac_error_ > 0); // There must have been an error return; } // Handle deletion of chars at caret or selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start < end && end <= GetDocument()->length()); GetDocument()->Change(mod_delforw, start, end-start, NULL, 0, this); DisplayCaret(); // Make sure caret is visible CHECK_SECURITY(101); aa->SaveToMacro(km_cut); } void CHexEditView::OnUpdateEditCut(CCmdUI* pCmdUI) { if (GetDocument()->read_only()) pCmdUI->Enable(FALSE); // disallow cut if file is read only else OnUpdateClipboard(pCmdUI); } void CHexEditView::OnEditCopy() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar if (CopyToClipboard()) aa->SaveToMacro(km_copy); } // Update handler that turns on certain user interface options (Copy etc) if there // is a selection -- ie. there is something available to be placed on the clipboard void CHexEditView::OnUpdateClipboard(CCmdUI* pCmdUI) { // Is there any text selected? CPointAp start, end; GetSel(start, end); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start != end ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(start != end); } bool CHexEditView::CopyToClipboard() { // Get the addresses of the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); // Clipboard setup and error checking if (!copy2cb_init(start, end)) return false; // Work out which format(s) to put on the clipboard. Generally, we place // both binary data ("BinaryData") and text (either the text chars if valid // characters or binary data as hex digits), but if the data is too big // it may just be stored in a temp binary file ("HexEditLargeDataTempFile"). cb_text_type cb_text = cb_text_chars; bool use_file = false; // Use our own special format if too big for clipboard CString strTemp; // name of temp file is used if (end - start > MAX_CLIPBOARD) { use_file = true; } else if (cb_text == cb_text_auto) { cb_text = is_binary(start, end) ? cb_text_hextext : cb_text_chars; } CWaitCursor wait; // Turn on wait cursor (hourglass) bool some_succeeded = false, some_failed = false; if (!use_file) { // Now put text data onto the clipboard if (cb_text == cb_text_hextext) { // Text is hex text (eg 3 chars "ABC" -> " 61 62 63") if (copy2cb_hextext(start, end)) some_succeeded = true; else some_failed = true; } else { // Text as actual chars (if valid) including char set conversion if (copy2cb_text(start, end)) some_succeeded = true; else some_failed = true; } // And also as binary if (copy2cb_binary(start, end)) some_succeeded = true; else use_file = true; // Possibly too big error - so use temp file format } if (use_file) { // Store all the data as binary in a (semi) temporary file. strTemp = copy2cb_file(start, end); if (!strTemp.IsEmpty()) some_succeeded = true; else some_failed = true; } ASSERT(some_succeeded || some_failed); if (some_succeeded) theApp.ClipBoardAdd(end - start, strTemp); if (!::CloseClipboard() || some_failed) { theApp.mac_error_ = 20; return false; } return true; } // Copy to clipboard as hex text void CHexEditView::OnCopyHex() { // Get the addresses of the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); // Clipboard setup and error checking if (!copy2cb_init(start, end)) return; CWaitCursor wait; // Turn on wait cursor (hourglass) bool ok = copy2cb_hextext(start, end); if (::CloseClipboard() && ok) { theApp.ClipBoardAdd((end - start)*3); theApp.SaveToMacro(km_copy_hex); } else theApp.mac_error_ = 20; } // Set up clipboard ready for having data added to it. // start,end = the part of the file to save (ie the selection) // If there is any problem it returns false after // displaying an error message and setting macro error level. bool CHexEditView::copy2cb_init(FILE_ADDRESS start, FILE_ADDRESS end) { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Check for problems with selection size if (start == end) { ASSERT(theApp.playing_); // Macro might have recorded Copy but when played there is no selection // Copy to clipboard while nothing selected, presumably in macro playback AfxMessageBox("Nothing selected to place on clipboard!"); theApp.mac_error_ = 10; return false; } if (end-start > 4000000L) { CString ss; ss.Format("Do you really want to put %sbytes on\n" "the clipboard? This may take some time.", NumScale(double(end-start))); if (AfxMessageBox(ss, MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return false; } } // Now open and empty the clipboard ready for copying data into if (!OpenClipboard()) { AfxMessageBox("The clipboard is in use!"); theApp.mac_error_ = 10; return false; } if (!::EmptyClipboard()) { AfxMessageBox("Could not delete previous contents of the clipboard!"); ::CloseClipboard(); theApp.mac_error_ = 10; return false; } return true; } // Copy selection to clipboard as text which can be pasted into a text editor etc. // Invalid text characters (eg nul byte) are not copied. // If current display mode is EBCDIC then the characters are converted from // EBCDIC to ASCII as they are added. bool CHexEditView::copy2cb_text(FILE_ADDRESS start, FILE_ADDRESS end) { // Get windows memory to allow data to be put on clipboard HANDLE hh; // Windows handle for memory unsigned char *p_cb, *pp; // Ptrs to + within the clipboard mem if ((hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, size_t(end-start+1))) == NULL || (p_cb = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) == NULL) { AfxMessageBox("Not enough memory to add text to clipboard"); theApp.mac_error_ = 10; return false; } // Copy the data from the document to the global memory unsigned char * buf = new unsigned char[clipboard_buf_len]; size_t len; pp = p_cb; FILE_ADDRESS curr; for (curr = start; curr < end; curr += len) { len = min(clipboard_buf_len, int(end - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); // Copy all characters in buffer to clipboard memory (unless nul) unsigned char *end_buf = buf + len; if (display_.char_set != CHARSET_EBCDIC) { for (unsigned char *ss = buf; ss < end_buf; ++ss) if (*ss != '\0') *pp++ = *ss; } else { for (unsigned char *ss = buf; ss < end_buf; ++ss) if (e2a_tab[*ss] != '\0') *pp++ = e2a_tab[*ss]; } } ASSERT(curr == end); delete[] buf; // If pp has not been incremented then no valid characters were copied if (pp == p_cb) { theApp.mac_error_ = 1; ((CMainFrame *)AfxGetMainWnd())-> StatusBarText("Warning: no valid text bytes - no text placed on clipboard"); } *pp ='\0'; if (::SetClipboardData(CF_TEXT, hh) == NULL) { ::GlobalFree(hh); AfxMessageBox("Could not place text data on clipboard"); theApp.mac_error_ = 10; return false; } // Note: the clipboard now owns the memory so ::GlobalFree(hh) should not be called ::GlobalUnlock(hh); return true; } // Copy to the clipboard in our own custom format "HexEditLargeDataTempFile". // This creates a Windows temporary file with all the data and just // puts the file name onto the clipboard. (The temp file is deleted // later when the clipboard changes or when HexEdit exits.) // It returns the name of the temp file or an empty string if there is // some sort of error, the most likely being a file error. CString CHexEditView::copy2cb_file(FILE_ADDRESS start, FILE_ADDRESS end) { CString TempFileName; // Create a temp file and write the data to it. { char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); TempFileName = temp_file; } if (!GetDocument()->WriteData(TempFileName, start, end)) { //AfxMessageBox("Error writing clipboard to disk"); theApp.mac_error_ = 10; return CString(); } HANDLE hh; // Windows handle for memory unsigned char *pp; // Actual pointer to the memory // Create the custom clipboard format (or get it if it already exists) // and get the memory to store the file name. UINT temp_format; if ((temp_format = ::RegisterClipboardFormat(CHexEditApp::temp_format_name)) == 0 || (hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, size_t(TempFileName.GetLength()+4))) == NULL || (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) == NULL) { AfxMessageBox("Not enough memory to add binary data to clipboard"); theApp.mac_error_ = 10; return CString(); } // Put the length of the file name long *pl = reinterpret_cast<long *>(pp); *pl = TempFileName.GetLength(); // Put the filename memcpy(pp+4, TempFileName.GetBuffer(), TempFileName.GetLength()); if (::SetClipboardData(temp_format, hh) == NULL) { ::GlobalFree(hh); AfxMessageBox("Could not place custom data on clipboard"); theApp.mac_error_ = 10; return CString(); } // Note: the clipboard now owns the memory so ::GlobalFree(hh) should not be called ::GlobalUnlock(hh); return TempFileName; } // Copy the selection to the clipboard in custom "BinaryData" format. // This is the same format as used by the Visual Studio hex editor, // simply consisting of a length (32-bit integer) followed by the bytes. // May return false due to errors such as insufficient memory, whence // a message has been shown to the user and mac_error_ has been set. bool CHexEditView::copy2cb_binary(FILE_ADDRESS start, FILE_ADDRESS end) { HANDLE hh; // Windows handle for memory unsigned char *pp; // Actual pointer to the memory // Create the "BinaryData" clipboard format (or get it if it already exists) // then get windows memory to allow binary data to be put on clipboard // then lock the memory UINT bin_format; if ((bin_format = ::RegisterClipboardFormat(CHexEditApp::bin_format_name)) == 0 || (hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, size_t(end-start+4))) == NULL || (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) == NULL) { AfxMessageBox("Not enough memory to add binary data to clipboard"); theApp.mac_error_ = 10; return false; } // Add the binary data length to first 4 bytes of BinaryData clipboard memory long *pl = reinterpret_cast<long *>(pp); *pl = long(end - start); // Copy the data from the document to the global memory VERIFY(GetDocument()->GetData(pp+4, size_t(end - start), start) == end - start); if (::SetClipboardData(bin_format, hh) == NULL) { ::GlobalFree(hh); AfxMessageBox("Could not place binary data on clipboard"); theApp.mac_error_ = 10; return false; } // Note: the clipboard now owns the memory so ::GlobalFree(hh) should not be called ::GlobalUnlock(hh); return true; } // Copy to clipboard as hex text, ie, each byte is stored as // 2 hex digits + also includes spaces etc. bool CHexEditView::copy2cb_hextext(FILE_ADDRESS start, FILE_ADDRESS end) { // Work out the amount of memory needed (may be slightly more than needed). FILE_ADDRESS mem_needed = hex_text_size(start, end); // Get windows memory to allow data to be put on clipboard HANDLE hh; // Windows handle for memory char *p_cb, *pp; // Ptr to start and within the clipboard text if ((hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, DWORD(mem_needed))) == NULL || (p_cb = reinterpret_cast<char *>(::GlobalLock(hh))) == NULL) { AfxMessageBox("Not enough memory to add hex text to clipboard"); theApp.mac_error_ = 10; return false; } unsigned char cc; const char *hex; if (theApp.hex_ucase_) hex = "0123456789ABCDEF?"; else hex = "0123456789abcdef?"; pp = p_cb; FILE_ADDRESS curr; for (curr = start; curr < end; ) { VERIFY(GetDocument()->GetData(&cc, 1, curr) == 1); *pp++ = hex[(cc>>4)&0xF]; *pp++ = hex[cc&0xF]; *pp++ = ' '; if ((++curr + offset_)%rowsize_ == 0) { *pp++ = '\r'; *pp++ = '\n'; } } if ((curr + offset_)%rowsize_ != 0) { // Add line termination at end *pp++ = '\r'; *pp++ = '\n'; } *pp ='\0'; if (::SetClipboardData(CF_TEXT, hh) == NULL) { ::GlobalFree(hh); AfxMessageBox("Could not place hex text data on clipboard"); theApp.mac_error_ = 10; return false; } // Note: the clipboard now owns the memory so ::GlobalFree(hh) should not be called ::GlobalUnlock(hh); return true; } bool CHexEditView::is_binary(FILE_ADDRESS start, FILE_ADDRESS end) { unsigned char buf[8192]; size_t len; for (FILE_ADDRESS curr = start; curr < end; curr += len) { // Get the next buffer full from the document len = size_t(min(sizeof(buf), end - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); // For now we only consider data with a null byte to be binary // since the clipboard can actually have any other character // added to it in text format. However, it may make sense to be // more restrictive later. if (memchr(buf, '\0', len) != NULL) return true; } return false; } // Copy to cipboard as C source (characters stored as hex ints) void CHexEditView::OnCopyCchar() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the addresses of the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start == end) { // Copy to clipboard while nothing selected, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("Nothing selected to place on clipboard!"); theApp.mac_error_ = 10; return; } CCopyCSrc dlg; if (dlg.DoModal() == IDOK) { do_copy_src(dlg.type_, dlg.type_ == CCopyCSrc::FLOAT ? dlg.float_size_ : dlg.int_size_, dlg.int_type_, dlg.big_endian_, dlg.show_address_, dlg.indent_); } } // do_copy_src: creates text on the clipboard from the current selection based on parameters passed // src_type = CCopyCSrc::STRING, CCopyCSrc::CHAR, CCopyCSrc::INT, or CCopyCSrc::FLOAT // src_size = 0,1,2,3 for 4 sizes of int, or 0,1 for 2 sizes of float // int_type = 0,1,2,3 for how the ints are to be output // big_endian = determines the byte order for ints and floats void CHexEditView::do_copy_src(int src_type, int src_size, int int_type, BOOL big_endian, BOOL show_address, int indent) { FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); // Clipboard setup and error checking if (!copy2cb_init(start, end)) return; // // Work out the amount of memory needed (may be slightly more than needed). // // Allow 6 chars for every byte ("0x" + 2 hex digits + comma + space), plus // // 7 ("/**/ "+CR+LF) + addr_width_ chars per line, + 1 trailing nul byte. // FILE_ADDRESS mem_needed = (end-start)*6+((end-start)/rowsize_+2)*(7+addr_width_)+1; FILE_ADDRESS mem_needed; switch (src_type) { default: ASSERT(0); // fall through case CCopyCSrc::STRING: // Max 4 chars per byte + 9 bytes for each line (/**/ ""\r\n) + address for each line + terminator mem_needed = (end-start)*4 + ((end-start)/rowsize_+2)*(indent+9+addr_width_) + 2; break; case CCopyCSrc::CHAR: case CCopyCSrc::INT: case CCopyCSrc::FLOAT: // Max 8 chars per byte + 7 bytes per line (/**/ \r\n) + address per line + terminator mem_needed = (end-start)*8 + ((end-start)/rowsize_+2)*(indent+7+addr_width_) + 2; break; } CWaitCursor wait; // Turn on wait cursor (hourglass) { // Get windows memory to allow data to be put on clipboard HANDLE hh; // Windows handle for memory char *p_cb, *pp; // Ptr to start and within the clipboard text size_t slen; // Number of characters added to ouput buffer by sprintf call if ((hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, DWORD(mem_needed))) == NULL || (p_cb = reinterpret_cast<char *>(::GlobalLock(hh))) == NULL) { AfxMessageBox("Insufficient memory for clipboard data"); ::CloseClipboard(); theApp.mac_error_ = 10; return; } p_cb[mem_needed-1] = '\xCD'; // Add marker char at end so we can check if buffer was overflowed // string containing 128 spaces const char *spaces = " " " "; const char *hex; // string containing hex digits (in current selected case) if (theApp.hex_ucase_) hex = "0123456789ABCDEF?"; else hex = "0123456789abcdef?"; pp = p_cb; // Add any indenting ASSERT(indent < 128); slen = sprintf(pp, "%.*s", indent, spaces); pp += slen; if (show_address) { // Add initial address *pp++ = '/'; *pp++ = '*'; if (hex_width_ > 0) { slen = sprintf(pp, theApp.hex_ucase_ ? "%0*I64X:" : "%0*I64x:", hex_width_, start + display_.addrbase1); pp += slen; } if (dec_width_ > 0) { slen = sprintf(pp, "%*I64d:", dec_width_, start + display_.addrbase1); pp += slen; } // xxx also line numbers (num_width_) *pp++ = '*'; *pp++ = '/'; *pp++ = ' '; } if (src_type == CCopyCSrc::STRING) *pp++ = '"'; FILE_ADDRESS curr = start; // Address of current byte being worked on FILE_ADDRESS line_end; // Address of byte at end of current line line_end = ((start + offset_)/rowsize_ + 1)*rowsize_ - offset_; // Work out how many bytes in each chunk size_t get_len; // Size of each chunk (1,2,4, or 8) switch (src_type) { default: ASSERT(0); // fall through case CCopyCSrc::STRING: case CCopyCSrc::CHAR: get_len = 1; break; case CCopyCSrc::INT: switch (src_size) { default: ASSERT(0); // fall through case CCopyCSrc::INT_32: get_len = 4; break; case CCopyCSrc::INT_8: get_len = 1; break; case CCopyCSrc::INT_16: get_len = 2; break; case CCopyCSrc::INT_64: get_len = 8; break; } break; case CCopyCSrc::FLOAT: switch (src_size) { default: ASSERT(0); // fall through case CCopyCSrc::FLOAT_64: get_len = 8; break; case CCopyCSrc::FLOAT_32: get_len = 4; break; case CCopyCSrc::REAL_48: get_len = 6; break; } break; } for (curr = start; curr + get_len <= end; ) { unsigned char buf[8]; // Largest is 64 bit int/float (8 bytes) VERIFY(GetDocument()->GetData(buf, get_len, curr) == get_len); switch (src_type) { default: ASSERT(0); // fall through case CCopyCSrc::STRING: // if (isprint(buf[0])) // isprint seems to return true for ANSI chars too if (buf[0] >= ' ' && buf[0] < 127) { // Backslash (\) and double-quote (") must be escaped and also do question // mark (?) to avoid accidentally creating a trigraph sequence (??=, etc) if (strchr("\\\"\?", buf[0])) *pp++ = '\\'; *pp++ = buf[0]; } else { // Control char or non-ASCII char - display as escape char or in hex const char *check = "\a\b\f\n\r\t\v"; // used in search for escape char const char *display = "abfnrtv0"; const char *ps; // Note we output a nul byte as hex just in case it is followed by another // digit. Since strchr includes the terminating nul byte in the search // we have to explicitly check for it. if (buf[0] != '\0' && (ps = strchr(check, buf[0])) != NULL) { // Ouput C/C++ escape sequence *pp++ = '\\'; *pp++ = display[ps-check]; } else { // Output using hex escape sequence *pp++ = '\\'; *pp++ = 'x'; *pp++ = hex[(buf[0]>>4)&0xF]; *pp++ = hex[buf[0]&0xF]; ASSERT(get_len == 1); // If not at end of line we have to watch that the following char is not a hex digit if (curr + get_len < line_end && curr + get_len < end) { // Not at EOL so get the next character into buf[1] VERIFY(GetDocument()->GetData(buf+1, 1, curr + get_len) == 1); if (isxdigit(buf[1])) { // Terminate the string and start a new one so that the following char // does not become concatenated with the 2 hex digits already output *pp++ = '"'; *pp++ = ' '; *pp++ = '"'; } } } } break; case CCopyCSrc::CHAR: *pp++ = '\''; // put in single quotes // if (isprint(buf[0])) if (buf[0] >= ' ' && buf[0] < 127) { // Backslash (\) and apostrophe or single quote (') must be escaped if (strchr("\\'", buf[0])) *pp++ = '\\'; *pp++ = buf[0]; } else { // Control char or non-ASCII char - display as escape char or in hex const char *check = "\a\b\f\n\r\t\v\0"; const char *display = "abfnrtv0"; const char *ps; if ((ps = strchr(check, buf[0])) != NULL) { // Ouput C/C++ escape sequence *pp++ = '\\'; *pp++ = display[ps-check]; } else { // Output using hex escape sequence *pp++ = '\\'; *pp++ = 'x'; *pp++ = hex[(buf[0]>>4)&0xF]; *pp++ = hex[buf[0]&0xF]; } } *pp++ = '\''; // trailing single quote *pp++ = ','; *pp++ = ' '; break; case CCopyCSrc::INT: if (big_endian) flip_bytes(buf, get_len); switch (src_size) { default: ASSERT(0); // fall through case CCopyCSrc::INT_32: switch (int_type) { default: ASSERT(0); // fall through case CCopyCSrc::INT_UNSIGNED: slen = sprintf(pp, "%10u, ", *(long *)buf); break; case CCopyCSrc::INT_SIGNED: slen = sprintf(pp, "%11d, ", *(long *)buf); break; case CCopyCSrc::INT_OCTAL: slen = sprintf(pp, "%012o, ", *(long *)buf); // octal with leading zeroes break; case CCopyCSrc::INT_HEX: if (theApp.hex_ucase_) slen = sprintf(pp, "0x%08X, ", *(long *)buf); // 0x then leading zeroes else slen = sprintf(pp, "0x%08x, ", *(long *)buf); break; } break; case CCopyCSrc::INT_8: switch (int_type) { default: ASSERT(0); // fall through case CCopyCSrc::INT_UNSIGNED: slen = sprintf(pp, "%3u, ", buf[0]); break; case CCopyCSrc::INT_SIGNED: slen = sprintf(pp, "%4d, ", (signed char)buf[0]); break; case CCopyCSrc::INT_OCTAL: slen = sprintf(pp, "%04o, ", buf[0]); break; case CCopyCSrc::INT_HEX: if (theApp.hex_ucase_) slen = sprintf(pp, "0x%02.2X, ", buf[0]); else slen = sprintf(pp, "0x%02.2x, ", buf[0]); break; } break; case CCopyCSrc::INT_16: switch (int_type) { default: ASSERT(0); // fall through case CCopyCSrc::INT_UNSIGNED: slen = sprintf(pp, "%5hu, ", *(short *)buf); break; case CCopyCSrc::INT_SIGNED: slen = sprintf(pp, "%6hd, ", *(short *)buf); break; case CCopyCSrc::INT_OCTAL: slen = sprintf(pp, "%07ho, ", *(short *)buf); break; case CCopyCSrc::INT_HEX: if (theApp.hex_ucase_) slen = sprintf(pp, "0x%04.4hX, ", *(short *)buf); else slen = sprintf(pp, "0x%04.4hx, ", *(short *)buf); break; } break; case CCopyCSrc::INT_64: switch (int_type) { default: ASSERT(0); // fall through case CCopyCSrc::INT_UNSIGNED: slen = sprintf(pp, "%20I64u, ", *(__int64 *)buf); break; case CCopyCSrc::INT_SIGNED: slen = sprintf(pp, "%20I64d, ", *(__int64 *)buf); break; case CCopyCSrc::INT_OCTAL: slen = sprintf(pp, "%023I64o, ", *(__int64 *)buf); break; case CCopyCSrc::INT_HEX: if (theApp.hex_ucase_) slen = sprintf(pp, "0x%016I64X, ", *(__int64 *)buf); else slen = sprintf(pp, "0x%016I64x, ", *(__int64 *)buf); break; } break; } pp += slen; ASSERT(*(pp-1) == ' '); // Checks that slen was correct and trailing space added break; case CCopyCSrc::FLOAT: if (big_endian) flip_bytes(buf, get_len); switch (src_size) { default: ASSERT(0); // fall through case CCopyCSrc::FLOAT_64: slen = sprintf(pp, "%22.15g, ", *(double *)buf); break; case CCopyCSrc::FLOAT_32: slen = sprintf(pp, "%14.7g, ", *(float *)buf); break; case CCopyCSrc::REAL_48: slen = sprintf(pp, "%19.12g, ", real48(buf)); break; } pp += slen; ASSERT(*(pp-1) == ' '); break; } // Check if we need to start a new line if ((curr += get_len) >= line_end || curr >= end) { // Terminate previous line if (src_type == CCopyCSrc::STRING) *pp++ = '"'; // terminate string on this line *pp++ = '\r'; *pp++ = '\n'; // If this is not the last line if (curr < end) { // Add any indenting slen = sprintf(pp, "%.*s", indent, spaces); pp += slen; if (show_address) { // Output address (in comments) at the start of the line *pp++ = '/'; *pp++ = '*'; if (hex_width_ > 0) { slen = sprintf(pp, theApp.hex_ucase_ ? "%0*I64X:" : "%0*I64x:", hex_width_, curr + display_.addrbase1); pp += slen; } if (dec_width_ > 0) { slen = sprintf(pp, "%*I64d:", dec_width_, curr + display_.addrbase1); pp += slen; } // xxx also line numbers (num_width_) *pp++ = '*'; *pp++ = '/'; *pp++ = ' '; } if (src_type == CCopyCSrc::STRING) *pp++ = '"'; // start new string on this new line } // Work out where this next line ends line_end += rowsize_; } } *pp ='\0'; ASSERT(pp-p_cb < mem_needed); ASSERT(p_cb[mem_needed-1] == '\xCD'); // Check if buffer was overflowed if (::SetClipboardData(CF_TEXT, hh) == NULL) { ASSERT(0); ::GlobalFree(hh); AfxMessageBox("Could not place data on clipboard"); ::CloseClipboard(); theApp.mac_error_ = 10; return; } theApp.ClipBoardAdd(pp - p_cb); // Note: the clipboard now owns the memory so ::GlobalFree(hh) should not be called ::GlobalUnlock(hh); } if (!::CloseClipboard()) theApp.mac_error_ = 20; else theApp.SaveToMacro(km_copy_cchar, src_type | (src_size<<3) | (int_type<<6) | (big_endian ? 0x0200 : 0) | (show_address ? 0 : 0x0400) | /* bit off means show */ (__int64(indent&0x7F)<<11)); } // start+end define the bytes to be replaced // pp points to the new bytes and len is the number of new bytes void CHexEditView::do_replace(FILE_ADDRESS start, FILE_ADDRESS end, unsigned char *pp, size_t len) { // Can't replace if view is read only if (check_ro("replace")) return; num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing ASSERT(start < end && end <= GetDocument()->length()); if (display_.overtype && end-start != len) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("This replacement requires insert mode..\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { theApp.mac_error_ = 10; return; } else if (!do_insert()) return; } if (display_.overtype || end-start == len) { GetDocument()->Change(mod_replace, start, len, pp, 0, this); } else { GetDocument()->Change(mod_delforw, start, end-start, NULL, 0, this); if (len > 0) GetDocument()->Change(mod_insert, start, len, pp, 0, this, TRUE); } int row = 0; if (display_.vert_display) row = pos2row(GetCaret()); SetSel(addr2pos(start+len, row), addr2pos(start+len, row)); DisplayCaret(); show_prop(); // Make sure dialogs don't obscure our changes show_calc(); show_pos(); // Update tool bar } void CHexEditView::OnEditPaste() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar // Can't paste if view is read only if (check_ro("paste")) return; num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing UINT ff = 0; // Clipboard format number HANDLE hh; // Handle to clipboard memory unsigned char *pp; // Pointer to actual data if (!OpenClipboard()) { ASSERT(0); AfxMessageBox("The clipboard is in use!"); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) // Check if there is a "BinaryData" format (added by us or DevStudio) while ((ff = EnumClipboardFormats(ff)) != 0) { CString tt; char name[16]; size_t nlen = ::GetClipboardFormatName(ff, name, 15); name[nlen] = '\0'; if (strcmp(name, CHexEditApp::bin_format_name) == 0) { // BINARY DATA if ((hh = ::GetClipboardData(ff)) != NULL && (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) != NULL) { long *pl = reinterpret_cast<long *>(pp); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + *pl > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) { ::CloseClipboard(); return; } } else if (display_.overtype && end_addr-start_addr != *pl) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) { ::CloseClipboard(); return; } break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; ::CloseClipboard(); return; } } // OK make the change if (display_.overtype || end_addr-start_addr == *pl) GetDocument()->Change(mod_replace, start_addr, *pl, pp+4, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, *pl, pp+4, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, *pl, pp+4, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr+*pl)); SetSel(addr2pos(start_addr+*pl, row), addr2pos(start_addr+*pl, row)); DisplayCaret(); show_prop(); // New char - check props show_calc(); show_pos(); // Update tool bar aa->SaveToMacro(km_paste); } else aa->mac_error_ = 20; // It's there but couldn't get it ::CloseClipboard(); return; } else if (strcmp(name, CHexEditApp::temp_format_name) == 0) { // Binary data in temp file if ((hh = ::GetClipboardData(ff)) != NULL && (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) != NULL) { // Get the temp file name CString strTemp; long *pl = reinterpret_cast<long *>(pp); memcpy(strTemp.GetBuffer(*pl), pp+4, *pl); strTemp.ReleaseBuffer(*pl); // adds null byte at end ::CloseClipboard(); // We have got everything from the cb memory // Make sure there is a temp file handle available. (We are going to // use mod_insert_file to access data directly from the temp file // as we don't want to read the whole (large} file into memory.) int idx = GetDocument()->AddDataFile(strTemp); if (idx == -1) { AfxMessageBox("HexEdit is out of temporary files and\n" "cannot paste from a temporary clipboard file. \n" "Please save your file to free \n" "temporary file handles and try again.\n", MB_OK); aa->mac_error_ = 10; return; } // Get the file's length so we know how much is being pasted CFileStatus fs; VERIFY(CFile64::GetStatus(strTemp, fs)); // Get selection so we can replace it (and also to restore caret later) FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Do some file mode checks and fixes as specified by the user if (display_.overtype && start_addr + fs.m_size > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != fs.m_size) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // Insert/replace with temp data file if (display_.overtype) { // Effectively replace using the file length GetDocument()->Change(mod_delforw, start_addr, fs.m_size, NULL, 0, this); GetDocument()->Change(mod_insert_file, start_addr, fs.m_size, NULL, idx, this, TRUE); } else { // Wipe out any current selection then insert the data if (start_addr < end_addr) GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert_file, start_addr, fs.m_size, NULL, idx, this, TRUE); } // Restore caret and update everything due to possible new data at the caret SetSel(addr2pos(start_addr+fs.m_size, row), addr2pos(start_addr+fs.m_size, row)); DisplayCaret(); show_prop(); // New current char - check props show_calc(); show_pos(); // Update tool bar aa->SaveToMacro(km_paste); } else aa->mac_error_ = 20; // It's there but couldn't get it return; } } // BinaryData format not found so just use text format if ((hh = ::GetClipboardData(CF_TEXT)) != NULL && (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) != NULL) { size_t len = strlen(reinterpret_cast<char *>(pp)); if (len > 0 && display_.char_set != CHARSET_EBCDIC) // Bugs in other apps (eg Hedit) might cause len == 0 { // TEXT DATA SAVED AS ASCII FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + len > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != len) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // OK make the change if (display_.overtype || end_addr-start_addr == len) GetDocument()->Change(mod_replace, start_addr, len, pp, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, len, pp, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, len, pp, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr+len)); SetSel(addr2pos(start_addr+len, row), addr2pos(start_addr+len, row)); DisplayCaret(); } else if (len > 0) { // TEXT DATA SAVED AS EBCDIC // Copy from clipboard to temp buffer converting to EBCDIC unsigned char *buf = new unsigned char[len]; size_t newlen = 0; for (size_t ii = 0; ii < len; ++ii) if (a2e_tab[pp[ii]] != '\0') buf[newlen++] = a2e_tab[pp[ii]]; if (newlen > 0) { // Insert the EBCDIC characters FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + newlen > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != newlen) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // OK make the change if (display_.overtype || end_addr-start_addr == newlen) GetDocument()->Change(mod_replace, start_addr, newlen, buf, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, newlen, buf, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, newlen, buf, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr+newlen)); SetSel(addr2pos(start_addr+newlen, row), addr2pos(start_addr+newlen, row)); DisplayCaret(); } else { AfxMessageBox("No valid EBCDIC characters to paste"); aa->mac_error_ = 2; } delete[] buf; } else { AfxMessageBox("Text on clipboard is not valid ASCII text!"); aa->mac_error_ = 10; // Invalid text on clipboard? } } else { // Paste when nothing to paste, presumably in macro AfxMessageBox("There is nothing on the clipboard to paste"); aa->mac_error_ = 10; } CHECK_SECURITY(49); ::CloseClipboard(); // This actually records even when there were some errors & probably shouldn't show_prop(); // New char - check props show_calc(); show_pos(); // Update tool bar aa->SaveToMacro(km_paste); } void CHexEditView::OnPasteAscii() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Can't insert text if view is read only or in overtype mode if (check_ro("paste (ASCII)")) return; num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing HANDLE hh; // Handle to clipboard memory unsigned char *pp; // Pointer to actual data if (!OpenClipboard()) { ASSERT(0); AfxMessageBox("The clipboard is in use!"); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) if ((hh = ::GetClipboardData(CF_TEXT)) != NULL && (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) != NULL) { size_t len = strlen(reinterpret_cast<char *>(pp)); if (len > 0) // Bugs in other apps (eg Hedit) might cause len == 0 { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + len > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != len) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // OK make the change if (display_.overtype || end_addr-start_addr == len) GetDocument()->Change(mod_replace, start_addr, len, pp, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, len, pp, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, len, pp, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr+len)); SetSel(addr2pos(start_addr+len, row), addr2pos(start_addr+len, row)); DisplayCaret(); } else aa->mac_error_ = 20; } else { // Paste when nothing to paste, presumably in macro AfxMessageBox("There is nothing on the clipboard to paste"); aa->mac_error_ = 10; } ::CloseClipboard(); // This actually records even when there were some errors & probably shouldn't aa->SaveToMacro(km_paste_ascii); } void CHexEditView::OnPasteEbcdic() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Can't insert text if view is read only or in overtype mode if (check_ro("paste (EBCDIC)")) return; num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing HANDLE hh; // Handle to clipboard memory unsigned char *pp; // Pointer to actual data if (!OpenClipboard()) { ASSERT(0); AfxMessageBox("The clipboard is in use!"); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) if ((hh = ::GetClipboardData(CF_TEXT)) != NULL && (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) != NULL) { size_t len = strlen(reinterpret_cast<char *>(pp)); if (len > 0) // Bugs in other apps (eg Hedit) might cause len == 0 { // Copy from clipboard to temp buffer converting to EBCDIC unsigned char *buf = new unsigned char[len]; size_t newlen = 0; for (size_t ii = 0; ii < len; ++ii) if (pp[ii] < 128 && a2e_tab[pp[ii]] != '\0') buf[newlen++] = a2e_tab[pp[ii]]; if (newlen > 0) { // Insert the EBCDIC characters FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + newlen > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != newlen) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // OK make the change if (display_.overtype || end_addr-start_addr == newlen) GetDocument()->Change(mod_replace, start_addr, newlen, buf, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, newlen, buf, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, newlen, buf, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr+newlen)); SetSel(addr2pos(start_addr+newlen, row), addr2pos(start_addr+newlen, row)); DisplayCaret(); } delete[] buf; } else aa->mac_error_ = 20; } else { // Paste when nothing to paste, presumably in macro AfxMessageBox("There is nothing on the clipboard to paste"); aa->mac_error_ = 10; } ::CloseClipboard(); aa->SaveToMacro(km_paste_ebcdic); // Don't record if error (mac_error_ > 3)??? } // Update handler that turns on user interface options (Paste etc) if there is // text on the clipboard -- ie. there is text that can be pasted into the document void CHexEditView::OnUpdateTextPaste(CCmdUI* pCmdUI) { BOOL bEnable = !GetDocument()->read_only() && ::IsClipboardFormatAvailable(CF_TEXT); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (bEnable ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(bEnable); // if (GetDocument()->read_only()) // pCmdUI->Enable(FALSE); // Disallow paste if file is read only // else // pCmdUI->Enable(::IsClipboardFormatAvailable(CF_TEXT)); } void CHexEditView::OnPasteUnicode() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Can't insert text if view is read only or in overtype mode if (check_ro("paste (Unicode)")) return; num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing HANDLE hh; // Handle to clipboard memory wchar_t *pp; // Pointer to actual data if (!OpenClipboard()) { ASSERT(0); AfxMessageBox("The clipboard is in use!"); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) if ((hh = ::GetClipboardData(CF_UNICODETEXT)) != NULL && (pp = reinterpret_cast<wchar_t *>(::GlobalLock(hh))) != NULL) { size_t len = wcslen(reinterpret_cast<wchar_t *>(pp)); if (len > 0) // Bugs in other apps (eg Hedit) might cause len == 0 { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + 2*len > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != 2*len) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // OK make the change if (display_.overtype || end_addr-start_addr == 2*len) GetDocument()->Change(mod_replace, start_addr, 2*len, (unsigned char *)pp, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, 2*len, (unsigned char *)pp, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, 2*len, (unsigned char *)pp, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr + 2*len)); SetSel(addr2pos(start_addr + 2*len, row), addr2pos(start_addr + 2*len, row)); DisplayCaret(); } else aa->mac_error_ = 20; } else { // Paste when nothing to paste, presumably in macro AfxMessageBox("There is nothing on the clipboard to paste"); aa->mac_error_ = 10; } ::CloseClipboard(); // This actually records even when there were some errors & probably shouldn't aa->SaveToMacro(km_paste_unicode); } void CHexEditView::OnUpdateUnicodePaste(CCmdUI* pCmdUI) { BOOL bEnable = !GetDocument()->read_only() && ::IsClipboardFormatAvailable(CF_UNICODETEXT); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (bEnable ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(bEnable); // if (GetDocument()->read_only()) // pCmdUI->Enable(FALSE); // else // pCmdUI->Enable(::IsClipboardFormatAvailable(CF_UNICODETEXT)); } // Reset all options to the current defaults void CHexEditView::OnDisplayReset() { // Change search type in find modeless dlg if open CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (theApp.open_display_.char_set != display_.char_set) { // Character set is to be changed - so update find dlg to match if (theApp.open_display_.char_set == CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_EBCDIC); else mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); } begin_change(); // Change font undo_.push_back(view_undo(undo_font)); if (display_.FontRequired() == FONT_OEM) { undo_.back().plf = new LOGFONT; *(undo_.back().plf) = oem_lf_; if (theApp.open_oem_plf_ != NULL) oem_lf_ = *theApp.open_oem_plf_; else { memset((void *)&oem_lf_, '\0', sizeof(oem_lf_)); _tcscpy(oem_lf_.lfFaceName, _T("Terminal")); // The only certain OEM font? oem_lf_.lfHeight = 18; oem_lf_.lfCharSet = OEM_CHARSET; // Only allow OEM/IBM character set fonts } } else { undo_.back().plf = new LOGFONT; *(undo_.back().plf) = lf_; if (theApp.open_plf_ != NULL) lf_ = *theApp.open_plf_; else { memset((void *)&lf_, '\0', sizeof(lf_)); _tcscpy(lf_.lfFaceName, _T("Courier")); // A nice fixed (no-proportional) font lf_.lfHeight = 16; lf_.lfCharSet = ANSI_CHARSET; // Only allow ANSI character set fonts } } // Change autofit undo_.push_back(view_undo(undo_autofit, TRUE)); if (!display_.autofit) undo_.back().rowsize = rowsize_; else undo_.back().rowsize = 0; // Note: we don't use disp_state_ = theApp.disp_state_ as this loses edit_char and mark_char settings display_.hex_area = theApp.open_display_.hex_area; display_.char_area = theApp.open_display_.char_area; display_.char_set = theApp.open_display_.char_set; display_.control = theApp.open_display_.control; display_.autofit = theApp.open_display_.autofit; display_.dec_addr = theApp.open_display_.dec_addr; // remove now or later? display_.decimal_addr = theApp.open_display_.decimal_addr; display_.hex_addr = theApp.open_display_.hex_area; display_.line_nums = theApp.open_display_.line_nums; display_.addrbase1 = theApp.open_display_.addrbase1; // addresses start at 1 (not 0) display_.readonly = theApp.open_display_.readonly; display_.overtype = theApp.open_display_.overtype; display_.vert_display = theApp.open_display_.vert_display; display_.borders = theApp.open_display_.borders; if (GetDocument()->IsDevice()) { display_.overtype = 1; // INS not allowed display_.borders = 1; // Always display borders for devices by default } // Make sure that caret and mark are not in hidden area ASSERT(display_.char_area || display_.hex_area); if (!display_.hex_area) { display_.edit_char = TRUE; display_.mark_char = TRUE; } else if (!display_.char_area) { display_.edit_char = FALSE; display_.mark_char = FALSE; } make_change(TRUE); if (rowsize_ != theApp.open_rowsize_) { undo_.push_back(view_undo(undo_rowsize, TRUE)); undo_.back().rowsize = rowsize_; // Save previous rowsize for undo rowsize_ = theApp.open_rowsize_; } if (real_offset_ != theApp.open_offset_) { undo_.push_back(view_undo(undo_offset, TRUE)); undo_.back().rowsize = real_offset_; // Save previous offset for undo real_offset_ = offset_ = theApp.open_offset_; if (real_offset_ >= rowsize_) offset_ = rowsize_ - 1; } undo_.push_back(view_undo(undo_group_by, TRUE)); undo_.back().rowsize = group_by_; // Save previous group_by for undo group_by_ = theApp.open_group_by_; undo_.push_back(view_undo(undo_scheme, TRUE)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = scheme_name_; scheme_name_ = ""; // Force scheme reset set_colours(); end_change(); theApp.SaveToMacro(km_display_reset, unsigned __int64(0)); // Store zero to allow for future additions } void CHexEditView::OnEditUndo() { CWaitCursor wait; // Turn on wait cursor (hourglass) // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing BOOL more = TRUE; while (more) { ASSERT(undo_.size() > 0 || theApp.playing_); more = undo_.back().previous_too; if (!do_undo()) { theApp.mac_error_ = 10; return; } } theApp.SaveToMacro(km_undo); } void CHexEditView::OnUpdateEditUndo(CCmdUI* pCmdUI) { pCmdUI->Enable(undo_.size() > 0); } void CHexEditView::OnUndoChanges() { CWaitCursor wait; // Turn on wait cursor (hourglass) num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing BOOL more; BOOL last_change = is_last_change(); do { ASSERT(undo_.size() > 0 || theApp.playing_); more = undo_.back().previous_too; if (!do_undo()) { theApp.mac_error_ = 10; return; } } while (undo_.size() > 0 && (more || !(last_change || is_last_change()))); // } while ((more || (last_change == is_last_change() && undo_.size() > 0)); theApp.SaveToMacro(km_undo_changes); } // Check if the top "operation" on the undo stack is a file change. Note that an operation // consists of all elts on the stack back until one without the previous_too flag set. BOOL CHexEditView::is_last_change() { #ifdef _DEBUG { // Why can't the debugger look into STL containers? int undo_size = undo_.size(); for (std::vector<view_undo>::reverse_iterator rr = undo_.rbegin(); rr != undo_.rend(); ++rr) { view_undo undo_elt = *rr; } } #endif // Check if the last thing on undo stack is a change for (std::vector<view_undo>::reverse_iterator pp = undo_.rbegin(); pp != undo_.rend(); ++pp) { if (pp->utype == undo_change) return TRUE; // Top undo op is a change if (!pp->previous_too) break; // End of top undo operation } return FALSE; } void CHexEditView::OnUpdateUndoChanges(CCmdUI* pCmdUI) { BOOL change_present = FALSE; // Check if the last thing on undo stack is a change for (std::vector<view_undo>::iterator pp = undo_.begin(); pp != undo_.end(); ++pp) { if (pp->utype == undo_change) { change_present = TRUE; // There is a change break; } } pCmdUI->Enable(change_present); } BOOL CHexEditView::do_undo() { // The string 'mess' is used to display a message in the status // bar if it is not obvious what has been undone. CString mess, tmp; CMainFrame *mm = dynamic_cast<CMainFrame *>(AfxGetMainWnd()); BOOL caret_displayed = CaretDisplayed(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); CHECK_SECURITY(191); if (undo_.size() == 0) { // This can only (presumably) happen during a macro AfxMessageBox("There is nothing to undo"); return FALSE; } switch (undo_.back().utype) { case undo_move: GoAddress(undo_.back().address); show_prop(); show_calc(); show_pos(); DisplayCaret(); // Make sure move visible break; case undo_sel: end_addr = undo_.back().address; // Now go back to previous undo (which should be undo_move) undo_.pop_back(); ASSERT(undo_.size() > 0); ASSERT(undo_.back().utype == undo_move); GoAddress(undo_.back().address, end_addr); show_prop(); show_calc(); show_pos(); DisplayCaret(); // Make sure move visible break; case undo_change: #if 0 if (display_.readonly) { if (AfxMessageBox("You can't undo changes while the window is read only.\r" "Do you want to turn off read only mode?", MB_OKCANCEL) == IDCANCEL) return FALSE; else allow_mods(); } #endif // Note: flag == TRUE if this view originally made the change. if (!undo_.back().flag) mess += "Undo: changes made in different window undone "; #ifndef NDEBUG if (!GetDocument()->Undo(this, undo_.back().index, undo_.back().flag)) return FALSE; #else if (!GetDocument()->Undo(this, 0, undo_.back().flag)) return FALSE; #endif break; case undo_state: disp_state_ = undo_.back().disp_state; redo_font(); recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display DoInvalidate(); { // Make sure calculator big-endian checkbox is correct CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!theApp.refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); } break; case undo_overtype: ASSERT(!GetDocument()->IsDevice()); display_.overtype = undo_.back().flag; if (GetDocument()->length() == 0) DoInvalidate(); if (display_.overtype) mess += "Undo: overtype now ON "; else mess += "Undo: overtype now OFF "; break; case undo_readonly: display_.readonly = undo_.back().flag; if (display_.readonly) mess += "Undo: read only now ON "; else mess += "Undo: read only now OFF "; break; case undo_font: if (display_.FontRequired() == FONT_OEM) oem_lf_ = *(undo_.back().plf); else lf_ = *(undo_.back().plf); if (pcv_ != NULL) pcv_->begin_change(); redo_font(); // Calculate new position based on new font size recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); mess += "Undo: font restored "; break; case undo_scheme: tmp = scheme_name_; scheme_name_ = *(undo_.back()).pscheme_name; if (set_colours()) DoInvalidate(); else { scheme_name_ = tmp; if (::IsUs()) AfxMessageBox("Previous color scheme not found.\n" "The operation could not be undone."); else AfxMessageBox("Previous colour scheme not found.\n" "The operation could not be undone."); } break; case undo_rowsize: { FILE_ADDRESS scroll_addr = pos2addr(GetScroll()); if (pcv_ != NULL) pcv_->begin_change(); rowsize_ = undo_.back().rowsize; offset_ = real_offset_; if (offset_ >= rowsize_) offset_ = rowsize_ - 1; recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); // Fix scroll place so it's about the same even though the row length has changed CPointAp pt = addr2pos(scroll_addr); pt.x = 0; SetScroll(pt); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); } break; case undo_group_by: if (pcv_ != NULL) pcv_->begin_change(); group_by_ = undo_.back().rowsize; recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); break; case undo_offset: if (pcv_ != NULL) pcv_->begin_change(); real_offset_ = offset_ = undo_.back().rowsize; if (real_offset_ >= rowsize_) offset_ = rowsize_ - 1; recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); break; case undo_autofit: { FILE_ADDRESS scroll_addr = pos2addr(GetScroll()); if (pcv_ != NULL) pcv_->begin_change(); // If rowsize has been specified then autofit is now off (undo turn on) display_.autofit = undo_.back().rowsize == 0; if (!display_.autofit) { mess += "Undo: auto fit now OFF "; rowsize_ = undo_.back().rowsize; offset_ = real_offset_; if (offset_ >= rowsize_) offset_ = rowsize_ - 1; } recalc_display(); // Fix scroll place so it's about the same even though the row length has changed CPointAp pt = addr2pos(scroll_addr); pt.x = 0; SetScroll(pt); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); } break; case undo_setmark: invalidate_addr_range(mark_, mark_ + 1); mark_ = undo_.back().address; if (theApp.align_rel_ && mark_ != GetDocument()->base_addr_) { GetDocument()->StopSearch(); GetDocument()->base_addr_ = GetSearchBase(); GetDocument()->StartSearch(); } invalidate_addr_range(mark_, mark_ + 1); show_calc(); // Status of some buttons may have changed when mark_ moves break; case undo_highlight: hl_set_ = *(undo_.back().phl); DoInvalidate(); break; case undo_unknown: default: ASSERT(0); mess += " Unknown undo! "; } undo_.pop_back(); mm->StatusBarText(mess); return TRUE; } void CHexEditView::OnAddrToggle() { begin_change(); display_.decimal_addr = display_.hex_addr; // Display decimal addr if currently displaying hex or both display_.hex_addr = !display_.decimal_addr; make_change(); end_change(); theApp.SaveToMacro(km_addr); } void CHexEditView::OnUpdateAddrToggle(CCmdUI* pCmdUI) { pCmdUI->SetCheck(!display_.hex_addr); } void CHexEditView::OnGraphicToggle() { if (!display_.char_area || display_.char_set == CHARSET_EBCDIC) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Can't toggle graphic chars, presumably in macro playback ASSERT(aa->playing_); if (!display_.char_area) AfxMessageBox("You can't display graphic characters without the char area"); else AfxMessageBox("Graphic characters are not supported for EBCDIC"); aa->mac_error_ = 2; return; } begin_change(); if (display_.char_set == CHARSET_ASCII) display_.char_set = CHARSET_ANSI; else display_.char_set = CHARSET_ASCII; make_change(); end_change(); CHECK_SECURITY(22); theApp.SaveToMacro(km_graphic); } void CHexEditView::OnUpdateGraphicToggle(CCmdUI* pCmdUI) { pCmdUI->Enable(display_.char_area && display_.char_set != CHARSET_EBCDIC); pCmdUI->SetCheck(display_.char_set == CHARSET_ANSI || display_.char_set == CHARSET_OEM); } void CHexEditView::OnCharToggle() { do_chartoggle(); } void CHexEditView::do_chartoggle(int state /*=-1*/) { if (display_.vert_display) { AfxMessageBox("You can't toggle char area in stacked mode"); theApp.mac_error_ = 2; return; } CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); begin_change(); // Change state of char area flag if (state == -1) display_.char_area = !display_.char_area; else if (state != display_.char_area) display_.char_area = state; // Make sure things are kept consistent if (!display_.char_area && display_.edit_char) { display_.edit_char = FALSE; SetHorzBufferZone(2); // Allow more room in hex area } if (!display_.char_area && !display_.hex_area) { display_.hex_area = TRUE; } make_change(); end_change(); aa->SaveToMacro(km_char_area, state); } void CHexEditView::OnUpdateCharToggle(CCmdUI* pCmdUI) { pCmdUI->Enable(!display_.vert_display); pCmdUI->SetCheck(display_.char_area); } void CHexEditView::do_hextoggle(int state /*=-1*/) { if (display_.vert_display) { AfxMessageBox("You can't toggle hex area in stacked mode"); theApp.mac_error_ = 2; return; } begin_change(); if (state == -1) display_.hex_area = !display_.hex_area; else if (state != display_.hex_area) display_.hex_area = state; // Save previous value of display hex for undo and also swap edit area if nec. if (!display_.hex_area && !display_.edit_char) { display_.edit_char = TRUE; SetHorzBufferZone(1); } if (!display_.hex_area && !display_.char_area) { display_.char_area = TRUE; } make_change(); end_change(); theApp.SaveToMacro(km_hex_area, state); } void CHexEditView::OnOemToggle() { if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { // Can't toggle OEM chars, presumably in macro playback ASSERT(theApp.playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display OEM/ANSI graphic characters without the char area"); else if (display_.char_set == CHARSET_EBCDIC) AfxMessageBox("Graphic characters are not supported for EBCDIC"); theApp.mac_error_ = 2; return; } begin_change(); if (display_.char_set == CHARSET_OEM) display_.char_set = CHARSET_ANSI; else display_.char_set = CHARSET_OEM; make_change(); end_change(); theApp.SaveToMacro(km_oem); } void CHexEditView::OnUpdateOemToggle(CCmdUI* pCmdUI) { pCmdUI->Enable((display_.vert_display || display_.char_area) && display_.char_set != CHARSET_EBCDIC); pCmdUI->SetCheck(display_.char_set == CHARSET_OEM); } void CHexEditView::OnFontInc() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing if (pcv_ != NULL) pcv_->begin_change(); // Save font for undo LOGFONT *plf = new LOGFONT; *plf = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; for ( ; ; ) { // Increase font size by one pixel CPoint convert(plf->lfWidth, plf->lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.LPtoDP(&convert); if (convert.y < max_font_size) ++convert.y; else { ((CMainFrame *)AfxGetMainWnd())-> StatusBarText("Warning: Font size too big - not increased"); aa->mac_error_ = 2; return; } dc.DPtoLP(&convert); plf->lfHeight = convert.y; plf->lfWidth = 0; // Calced from height CFont font; font.CreateFontIndirect(plf); // if (display_.char_area && !display_.ebcdic && display_.graphic && display_.oem) // { // oem_lf_.lfHeight = convert.y; // oem_lf_.lfWidth = 0; // Calced from height // font.CreateFontIndirect(&oem_lf_); // } // else // { // lf_.lfHeight = convert.y; // lf_.lfWidth = 0; // Calced from height // font.CreateFontIndirect(&lf_); // } TEXTMETRIC tm; CFont *tf = dc.SelectObject(&font); dc.GetTextMetrics(&tm); dc.SelectObject(tf); // Deselect font before it is destroyed if (tm.tmHeight + tm.tmExternalLeading > text_height_) { if (display_.FontRequired() == FONT_OEM) oem_lf_.lfHeight = convert.y; else lf_.lfHeight = convert.y; break; } } BOOL caret_displayed = CaretDisplayed(); // FILE_ADDRESS address = pos2addr(GetCaret()); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Create and install the new font redo_font(); // Calculate new position (and new total size) based on change in font size recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); undo_.push_back(view_undo(undo_font)); // Allow undo of font change undo_.back().plf = plf; aa->SaveToMacro(km_inc_font); } void CHexEditView::OnUpdateFontInc(CCmdUI* pCmdUI) { // Create a large (max_font_size) font and see if the current font is // displayed at the same size on screen. If so we can't increase the size LOGFONT logfont; logfont = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; // Get font the same as current ... { CPoint convert(0, max_font_size); // ... but very big CClientDC dc(this); OnPrepareDC(&dc); dc.DPtoLP(&convert); logfont.lfHeight = convert.y; } logfont.lfWidth = 0; // Width calced from height // Create font, put into DC, and see what size it would be on screen CFont font; font.CreateFontIndirect(&logfont); { TEXTMETRIC tm; CClientDC dc(this); OnPrepareDC(&dc); CFont *tf = dc.SelectObject(&font); dc.GetTextMetrics(&tm); dc.SelectObject(tf); if (tm.tmHeight + tm.tmExternalLeading == text_height_) pCmdUI->Enable(FALSE); // Already at smallest displayable font } } void CHexEditView::OnFontDec() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing if (pcv_ != NULL) pcv_->begin_change(); // Save font for undo LOGFONT *plf = new LOGFONT; *plf = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; for ( ; ; ) { // Decrease font size by one pixel CPoint convert(plf->lfWidth, plf->lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.LPtoDP(&convert); if (convert.y > 1) convert.y--; else { ((CMainFrame *)AfxGetMainWnd())-> StatusBarText("Warning: Font size already at minimum - not decreased"); aa->mac_error_ = 2; return; } dc.DPtoLP(&convert); plf->lfHeight = convert.y; plf->lfWidth = 0; // Calced from height CFont font; font.CreateFontIndirect(plf); // if (display_.char_area && !display_.ebcdic && display_.graphic && display_.oem) // { // oem_lf_.lfHeight = convert.y; // oem_lf_.lfWidth = 0; // Calced from height // font.CreateFontIndirect(&oem_lf_); // } // else // { // lf_.lfHeight = convert.y; // lf_.lfWidth = 0; // Calced from height // font.CreateFontIndirect(&lf_); // } TEXTMETRIC tm; CFont *tf = dc.SelectObject(&font); dc.GetTextMetrics(&tm); dc.SelectObject(tf); // Deselect font before it is destroyed if (tm.tmHeight + tm.tmExternalLeading < text_height_) { if (display_.FontRequired() == FONT_OEM) oem_lf_.lfHeight = convert.y; else lf_.lfHeight = convert.y; break; } } BOOL caret_displayed = CaretDisplayed(); // FILE_ADDRESS address = pos2addr(GetCaret()); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Create and install the new font redo_font(); // Calculate new position (and new total size) based on change in font size recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); undo_.push_back(view_undo(undo_font)); // Allow undo of font change undo_.back().plf = plf; aa->SaveToMacro(km_dec_font); } void CHexEditView::OnUpdateFontDec(CCmdUI* pCmdUI) { // If we create a very small font then see what the text height is when that // font is used. If this height is the same as the current text height then the // font size can not be decreased any more. LOGFONT logfont; logfont = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; // Get font the same as current ... { CPoint convert(0, 1); // ... but just one pixel high CClientDC dc(this); OnPrepareDC(&dc); dc.DPtoLP(&convert); logfont.lfHeight = convert.y; } logfont.lfWidth = 0; // Width calced from height // Create font, put into DC, and see what size it would be on screen CFont font; font.CreateFontIndirect(&logfont); { TEXTMETRIC tm; CClientDC dc(this); OnPrepareDC(&dc); CFont *tf = dc.SelectObject(&font); dc.GetTextMetrics(&tm); dc.SelectObject(tf); if (tm.tmHeight + tm.tmExternalLeading == text_height_) pCmdUI->Enable(FALSE); // Already at smallest displayable font } } void CHexEditView::OnFont() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing LOGFONT logfont = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; // Convert font size to units that user can relate to { CPoint convert(logfont.lfWidth, logfont.lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.LPtoDP(&convert); logfont.lfWidth = convert.x; logfont.lfHeight = convert.y; } CFontDialog dlg; dlg.m_cf.lpLogFont = &logfont; dlg.m_cf.Flags |= CF_INITTOLOGFONTSTRUCT | CF_SHOWHELP; dlg.m_cf.Flags &= ~(CF_EFFECTS); // Disable selection of strikethrough, colours etc if (dlg.DoModal() == IDOK) { // Convert font size back to logical units dlg.GetCurrentFont(&logfont); if (logfont.lfHeight < 0) logfont.lfHeight = -logfont.lfHeight; { CPoint convert(logfont.lfWidth, logfont.lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.DPtoLP(&convert); logfont.lfWidth = convert.x; logfont.lfHeight = convert.y; } do_font(&logfont); } else { ((CHexEditApp *)AfxGetApp())->mac_error_ = 2; } } void CHexEditView::OnFontName() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHexEditFontCombo* pSrcCombo = (CHexEditFontCombo*)CMFCToolBarComboBoxButton::GetByCmd(IDC_FONTNAME, TRUE); if (pSrcCombo == NULL) { OnFont(); return; } LOGFONT logfont = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; CString str = pSrcCombo->GetText(); if (pSrcCombo->SetFont(str)) { const CMFCFontInfo *pDesc = pSrcCombo->GetFontDesc(); ASSERT_VALID(pDesc); ASSERT(pDesc->m_strName.GetLength() < LF_FACESIZE); strncpy(logfont.lfFaceName, pDesc->m_strName, LF_FACESIZE); logfont.lfCharSet = pDesc->m_nCharSet; logfont.lfPitchAndFamily = pDesc->m_nPitchAndFamily; do_font(&logfont); } } void CHexEditView::OnUpdateFontName(CCmdUI* pCmdUI) { CObList listButtons; static int last_font_required = -1; bool font_list_changed = last_font_required != display_.FontRequired(); if (CMFCToolBar::GetCommandButtons (IDC_FONTNAME, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition (); posCombo != NULL; ) { CHexEditFontCombo * pCombo = DYNAMIC_DOWNCAST(CHexEditFontCombo, listButtons.GetNext (posCombo)); if (pCombo != NULL && !pCombo->HasFocus ()) { if (display_.FontRequired() == FONT_OEM) { if (font_list_changed) pCombo->FixFontList(OEM_CHARSET); CString ss = pCombo->GetText(); if (ss != oem_lf_.lfFaceName) pCombo->SetText(oem_lf_.lfFaceName); } else { if (font_list_changed) pCombo->FixFontList(ANSI_CHARSET); CString ss = pCombo->GetText(); if (ss != lf_.lfFaceName) pCombo->SetText(lf_.lfFaceName); } } } } last_font_required = display_.FontRequired(); // remeber the font set we are now using } void CHexEditView::OnFontSize() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHexEditFontSizeCombo* pSrcCombo = (CHexEditFontSizeCombo*)CMFCToolBarComboBoxButton::GetByCmd(IDC_FONTSIZE, TRUE); if (pSrcCombo == NULL) { OnFont(); return; } LOGFONT logfont = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; int nSize = pSrcCombo->GetTwipSize(); if (nSize == -2 || (nSize >= 0 && nSize < 20) || nSize > 32760) { AfxMessageBox("Invalid font size."); } else if (nSize > 0) { CClientDC dc(this); OnPrepareDC(&dc); logfont.lfHeight = int((nSize * dc.GetDeviceCaps(LOGPIXELSX)) / 1440.0 + 0.5); do_font(&logfont); // Store the exact font size (due to rounding probs do_font (SetFont) calc may be slightly off) fontsize_.Format("%d", nSize/20); } } void CHexEditView::OnUpdateFontSize(CCmdUI* pCmdUI) { CObList listButtons; if (CMFCToolBar::GetCommandButtons (IDC_FONTSIZE, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition (); posCombo != NULL;) { CMFCToolBarFontSizeComboBox * pCombo = DYNAMIC_DOWNCAST(CMFCToolBarFontSizeComboBox, listButtons.GetNext (posCombo)); if (pCombo != NULL && !pCombo->HasFocus ()) { static CString savedFontName; CString fontName; if (display_.FontRequired() == FONT_OEM) fontName = oem_lf_.lfFaceName; else fontName = lf_.lfFaceName; if (!fontName.IsEmpty() && (pCombo->GetCount() == 0 || fontName != savedFontName)) { savedFontName = fontName; pCombo->RebuildFontSizes(fontName); } int nSize = atoi(fontsize_)*20; if (nSize == -2 || (nSize >= 0 && nSize < 20) || nSize > 32760) nSize = 20*12; pCombo->SetTwipSize(nSize); // Store the exact font size (due to rounding probs do_font (SetFont) calc may be slightly off) fontsize_.Format("%d", nSize/20); CString ss = pCombo->GetText(); if (ss != fontsize_) pCombo->SetText(fontsize_); } } } } void CHexEditView::do_font(LOGFONT *plf) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (pcv_ != NULL) pcv_->begin_change(); // Save current LOGFONT for undo LOGFONT *prev_lf = new LOGFONT; if (display_.FontRequired() == FONT_OEM) { // We can't switch to an ANSI char set because we are displaying OEM graphics if (plf->lfCharSet == ANSI_CHARSET) { mm->StatusBarText("Can't switch to ANSI font when displaying IBM/OEM graphics chars"); aa->mac_error_ = 2; return; } *prev_lf = oem_lf_; oem_lf_ = *plf; } else { // We can't switch to an OEM char set if (plf->lfCharSet == OEM_CHARSET) { mm->StatusBarText("Can't switch to this font unless displaying IBM/OEM graphics chars"); aa->mac_error_ = 2; return; } *prev_lf = lf_; lf_ = *plf; } // Set new LOGFONT BOOL caret_displayed = CaretDisplayed(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); CHECK_SECURITY(9); // Create and install the new font redo_font(); // Calculate new position (and new total size) based on change in font size recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); undo_.push_back(view_undo(undo_font)); // Allow undo of font change undo_.back().plf = prev_lf; ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_font, display_.FontRequired() == FONT_OEM ? &oem_lf_ : &lf_); } void CHexEditView::change_rowsize(int rowsize) { if (rowsize != rowsize_) { if (pcv_ != NULL) pcv_->begin_change(); FILE_ADDRESS scroll_addr = pos2addr(GetScroll()); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); undo_.push_back(view_undo(undo_rowsize)); undo_.back().rowsize = rowsize_; // Save previous rowsize for undo rowsize_ = rowsize; recalc_display(); // Fix scroll place so it's about the same even though the row length has changed CPointAp pt = addr2pos(scroll_addr); pt.x = 0; SetScroll(pt); // Fix selection if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_rowsize, rowsize); } void CHexEditView::change_group_by(int group_by) { if (group_by != group_by_) { if (pcv_ != NULL) pcv_->begin_change(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); undo_.push_back(view_undo(undo_group_by)); undo_.back().rowsize = group_by_; // Save previous group_by for undo group_by_ = group_by; recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_group_by, group_by); } void CHexEditView::change_offset(int offset) { if (offset != real_offset_) { if (pcv_ != NULL) pcv_->begin_change(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); undo_.push_back(view_undo(undo_offset)); undo_.back().rowsize = real_offset_; // Save previous offset for undo real_offset_ = offset_ = offset; recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_offset, offset); } void CHexEditView::OnAutoFit() { do_autofit(); } // Change autofit mode to state (0 or 1). If state is -1 then toggle autofit. void CHexEditView::do_autofit(int state /*=-1*/) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (pcv_ != NULL) pcv_->begin_change(); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing BOOL caret_displayed = CaretDisplayed(); FILE_ADDRESS scroll_addr = pos2addr(GetScroll()); // FILE_ADDRESS address = pos2addr(GetCaret()); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); if (state == -1) display_.autofit = !display_.autofit; else if ((BOOL)state == display_.autofit) return; // No change - do nothing else display_.autofit = (BOOL)state; undo_.push_back(view_undo(undo_autofit)); if (display_.autofit) undo_.back().rowsize = rowsize_; else undo_.back().rowsize = 0; if (!display_.autofit && real_offset_ != offset_) { // If autofit turned off but offset has been squeezed then save so it's undone undo_.push_back(view_undo(undo_offset, TRUE)); undo_.back().rowsize = real_offset_; // Save previous offset for undo } recalc_display(); // Fix scroll place so it's about the same even though the row length has changed CPointAp pt = addr2pos(scroll_addr); pt.x = 0; SetScroll(pt); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); aa->SaveToMacro(km_autofit, state); CHECK_SECURITY(19); } void CHexEditView::OnUpdateAutofit(CCmdUI* pCmdUI) { pCmdUI->SetCheck(display_.autofit); } void CHexEditView::OnColumnDec() { if (rowsize_ > 4) { if (pcv_ != NULL) pcv_->begin_change(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Try to stay at the same place when multiple column adjustments are made if (resize_start_addr_ == -1 || resize_curr_scroll_ != GetScroll().y) resize_start_addr_ = pos2addr(GetScroll()); undo_.push_back(view_undo(undo_rowsize)); undo_.back().rowsize = rowsize_; // Save previous rowsize for undo rowsize_ = rowsize_ - 1; recalc_display(); // Adjust scroll so that about the same row is visible CPointAp pt = addr2pos(resize_start_addr_); pt.x = 0; SetScroll(pt); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); resize_curr_scroll_ = GetScroll().y; // Save current pos so we can check if we are at the same place later } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_rowsize, -1); } void CHexEditView::OnUpdateColumnDec(CCmdUI* pCmdUI) { pCmdUI->Enable(!display_.autofit && rowsize_ > 4); } void CHexEditView::OnColumnInc() { if (rowsize_ < max_buf) { if (pcv_ != NULL) pcv_->begin_change(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Try to stay at the same place when multiple column adjustments are made if (resize_start_addr_ == -1 || resize_curr_scroll_ != GetScroll().y) resize_start_addr_ = pos2addr(GetScroll()); undo_.push_back(view_undo(undo_rowsize)); undo_.back().rowsize = rowsize_; // Save previous rowsize for undo rowsize_ = rowsize_ + 1; recalc_display(); // Adjust scroll so that about the same row is visible CPointAp pt = addr2pos(resize_start_addr_); pt.x = 0; SetScroll(pt); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); resize_curr_scroll_ = GetScroll().y; // Save current pos so we can check if we are at the same place later } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_rowsize, -2); } void CHexEditView::OnUpdateColumnInc(CCmdUI* pCmdUI) { pCmdUI->Enable(!display_.autofit && rowsize_ < max_buf); } void CHexEditView::redo_font() { CFont *tf = pfont_; pfont_ = new CFont; pfont_->CreateFontIndirect(display_.FontRequired() == FONT_OEM ? &oem_lf_ : &lf_); SetFont(pfont_); if (pcv_ != NULL) pcv_->SetFont(pfont_); if (tf != NULL) delete tf; // Delete old font after it's deselected } void CHexEditView::begin_change() { ASSERT(previous_state_ == 0); previous_caret_displayed_ = CaretDisplayed(); previous_end_base_ = GetSelAddr(previous_start_addr_, previous_end_addr_); previous_row_ = 0; if (previous_start_addr_ == previous_end_addr_ && display_.vert_display) previous_row_ = pos2row(GetCaret()); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHECK_SECURITY(21); previous_state_ = disp_state_; if (pcv_ != NULL) pcv_->begin_change(); } // Return ptoo or TRUE if it added to the undo stack BOOL CHexEditView::make_change(BOOL ptoo /*=FALSE*/) { if (previous_state_ != disp_state_) { if (theApp.intelligent_undo_ && // intelligent undo is turned on undo_.size() > 0 && // there is an undo op on the stack undo_.back().utype == undo_state && // previous op was a state change !undo_.back().previous_too && // and not part of another operation undo_.back().disp_state == disp_state_) // and same state { ASSERT(!ptoo); // if part of larger op then previous utype should not have been undo_state undo_.pop_back(); } else { undo_.push_back(view_undo(undo_state, ptoo)); undo_.back().disp_state = previous_state_; ptoo = TRUE; } } return ptoo; } void CHexEditView::end_change() { redo_font(); recalc_display(); if (!display_.vert_display) previous_row_ = 0; // If vert mode turned off make sure row is zero if (previous_end_base_) SetSel(addr2pos(previous_end_addr_, previous_row_), addr2pos(previous_start_addr_, previous_row_), true); else SetSel(addr2pos(previous_start_addr_, previous_row_), addr2pos(previous_end_addr_, previous_row_)); if (previous_caret_displayed_) DisplayCaret(); // Keep caret within display DoInvalidate(); if (pcv_ != NULL) pcv_->end_change(); // Make sure calculator big-endian checkbox is correct CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!theApp.refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); previous_state_ = 0; // Used to make sure begin_change/end_change are in pairs } void CHexEditView::OnDisplayHex() { // Change the current state (storing previous state in undo vector if changed) begin_change(); display_.hex_area = TRUE; display_.char_area = FALSE; display_.edit_char = FALSE; display_.vert_display = FALSE; SetHorzBufferZone(2); make_change(); end_change(); theApp.SaveToMacro(km_area, 1); } void CHexEditView::OnUpdateDisplayHex(CCmdUI *pCmdUI) { pCmdUI->SetCheck(!display_.vert_display && display_.hex_area && !display_.char_area); } void CHexEditView::OnDisplayChar() { // Change the current state (storing previous state in undo vector if changed) begin_change(); display_.hex_area = FALSE; display_.char_area = TRUE; display_.edit_char = TRUE; display_.vert_display = FALSE; SetHorzBufferZone(1); make_change(); end_change(); theApp.SaveToMacro(km_area, 2); } void CHexEditView::OnUpdateDisplayChar(CCmdUI *pCmdUI) { pCmdUI->SetCheck(!display_.vert_display && !display_.hex_area && display_.char_area); } void CHexEditView::OnDisplayBoth() { // Change the current state (storing previous state in undo vector if changed) begin_change(); CHECK_SECURITY(50); display_.hex_area = TRUE; display_.char_area = TRUE; display_.vert_display = FALSE; if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); make_change(); end_change(); theApp.SaveToMacro(km_area, 3); } void CHexEditView::OnUpdateDisplayBoth(CCmdUI *pCmdUI) { pCmdUI->SetCheck(!display_.vert_display && display_.hex_area && display_.char_area); } void CHexEditView::OnDisplayStacked() { // Change the current state (storing previous state in undo vector if changed) begin_change(); display_.vert_display = TRUE; if (GetVertBufferZone() < 2) SetVertBufferZone(2); // Make sure we can always see the other 2 rows at the same address SetHorzBufferZone(1); make_change(); end_change(); CHECK_SECURITY(30); theApp.SaveToMacro(km_area, 4); } void CHexEditView::OnUpdateDisplayStacked(CCmdUI *pCmdUI) { pCmdUI->SetCheck(display_.vert_display); } void CHexEditView::OnCharsetAscii() { bool std_scheme = false; if (!(display_.vert_display || display_.char_area)) { ASSERT(theApp.playing_); AfxMessageBox("You can't change characters sets without the char area"); theApp.mac_error_ = 2; return; } // Change search type in find modeless dlg CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (display_.char_set == CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); if (scheme_name_ == ANSI_NAME && display_.char_set == CHARSET_ANSI || scheme_name_ == OEM_NAME && display_.char_set == CHARSET_OEM || scheme_name_ == EBCDIC_NAME && display_.char_set == CHARSET_EBCDIC ) { std_scheme = true; } begin_change(); display_.char_set = CHARSET_ASCII; BOOL ptoo = make_change(); if (std_scheme) { undo_.push_back(view_undo(undo_scheme, ptoo)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = scheme_name_; scheme_name_ = ASCII_NAME; set_colours(); } end_change(); CHECK_SECURITY(51); theApp.SaveToMacro(km_charset, unsigned __int64(0)); } void CHexEditView::OnUpdateCharsetAscii(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area)); pCmdUI->SetCheck(display_.char_set == CHARSET_ASCII); } } void CHexEditView::OnCharsetAnsi() { bool std_scheme = false; if (!(display_.vert_display || display_.char_area)) { ASSERT(theApp.playing_); AfxMessageBox("You can't change characters sets without the char area"); theApp.mac_error_ = 2; return; } // Change search type in find modeless dlg CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); ASSERT(mm != NULL); if (display_.char_set == CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); if (scheme_name_ == ASCII_NAME && display_.char_set == CHARSET_ASCII || scheme_name_ == OEM_NAME && display_.char_set == CHARSET_OEM || scheme_name_ == EBCDIC_NAME && display_.char_set == CHARSET_EBCDIC) { std_scheme = true; } begin_change(); display_.char_set = CHARSET_ANSI; BOOL ptoo = make_change(); if (std_scheme) { undo_.push_back(view_undo(undo_scheme, ptoo)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = scheme_name_; scheme_name_ = ANSI_NAME; set_colours(); } end_change(); theApp.SaveToMacro(km_charset, 1); } void CHexEditView::OnUpdateCharsetAnsi(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area)); pCmdUI->SetCheck(display_.char_set == CHARSET_ANSI); } } void CHexEditView::OnCharsetOem() { bool std_scheme = false; if (!(display_.vert_display || display_.char_area)) { ASSERT(theApp.playing_); AfxMessageBox("You can't change characters sets without the char area"); theApp.mac_error_ = 2; return; } // Change search type in find modeless dlg CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); ASSERT(mm != NULL); if (display_.char_set == CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); if (scheme_name_ == ASCII_NAME && display_.char_set == CHARSET_ASCII || scheme_name_ == ANSI_NAME && display_.char_set == CHARSET_ANSI || scheme_name_ == EBCDIC_NAME && display_.char_set == CHARSET_EBCDIC) { std_scheme = true; } begin_change(); display_.char_set = CHARSET_OEM; BOOL ptoo = make_change(); if (std_scheme) { undo_.push_back(view_undo(undo_scheme, ptoo)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = scheme_name_; scheme_name_ = OEM_NAME; set_colours(); } end_change(); theApp.SaveToMacro(km_charset, 2); } void CHexEditView::OnUpdateCharsetOem(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area)); pCmdUI->SetCheck(display_.char_set == CHARSET_OEM); } } void CHexEditView::OnCharsetEbcdic() { bool std_scheme = false; if (!(display_.vert_display || display_.char_area)) { ASSERT(theApp.playing_); AfxMessageBox("You can't change characters sets without the char area"); theApp.mac_error_ = 2; return; } // Change search type in find modeless dlg CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); ASSERT(mm != NULL); if (display_.char_set != CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_EBCDIC); if (scheme_name_ == ASCII_NAME && display_.char_set == CHARSET_ASCII || scheme_name_ == ANSI_NAME && display_.char_set == CHARSET_ANSI || scheme_name_ == OEM_NAME && display_.char_set == CHARSET_OEM ) { std_scheme = true; } begin_change(); display_.char_set = CHARSET_EBCDIC; BOOL ptoo = make_change(); if (std_scheme) { undo_.push_back(view_undo(undo_scheme, ptoo)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = scheme_name_; scheme_name_ = EBCDIC_NAME; set_colours(); } end_change(); theApp.SaveToMacro(km_charset, 3); } void CHexEditView::OnUpdateCharsetEbcdic(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area)); pCmdUI->SetCheck(display_.char_set == CHARSET_EBCDIC); } } void CHexEditView::OnControlNone() { if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { ASSERT(theApp.playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display control characters without the char area"); else if (display_.char_set == CHARSET_EBCDIC) AfxMessageBox("You can't display control characters in EBCDIC"); theApp.mac_error_ = 2; return; } // Change the current state (storing previous state in undo vector if changed) begin_change(); display_.control = 0; make_change(); end_change(); theApp.SaveToMacro(km_control, 1); } void CHexEditView::OnUpdateControlNone(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI)); pCmdUI->SetCheck(display_.control == 0); } } void CHexEditView::OnControlAlpha() { if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { ASSERT(theApp.playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display control characters without the char area"); else if (display_.char_set == CHARSET_EBCDIC) AfxMessageBox("You can't display control characters in EBCDIC"); theApp.mac_error_ = 2; return; } begin_change(); display_.control = 1; make_change(); end_change(); theApp.SaveToMacro(km_control, 2); } void CHexEditView::OnUpdateControlAlpha(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI)); pCmdUI->SetCheck(display_.control == 1); } } void CHexEditView::OnControlC() { if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { ASSERT(theApp.playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display control characters without the char area"); else if (display_.char_set == CHARSET_EBCDIC) AfxMessageBox("You can't display control characters in EBCDIC"); theApp.mac_error_ = 2; return; } begin_change(); display_.control = 2; make_change(); end_change(); theApp.SaveToMacro(km_control, 3); } void CHexEditView::OnUpdateControlC(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI)); pCmdUI->SetCheck(display_.control == 2); } } void CHexEditView::OnAscEbc() { if (!(display_.vert_display || display_.char_area)) { // Can't display EBCDIC, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("You can't display EBCDIC without the char area"); theApp.mac_error_ = 2; return; } // Change search type in find modeless dlg CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); ASSERT(mm != NULL); if (display_.char_set == CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); else mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_EBCDIC); begin_change(); if (display_.char_set == CHARSET_EBCDIC) display_.char_set = CHARSET_ANSI; else display_.char_set = CHARSET_EBCDIC; make_change(); end_change(); theApp.SaveToMacro(km_ebcdic); } void CHexEditView::OnUpdateAscEbc(CCmdUI* pCmdUI) { pCmdUI->Enable((display_.vert_display || display_.char_area)); pCmdUI->SetCheck(display_.char_set == CHARSET_EBCDIC); } void CHexEditView::OnControl() { CHECK_SECURITY(18); CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { // Can't toggle control chars, presumably in macro playback ASSERT(aa->playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display control characters without the char area"); else AfxMessageBox("Control character display is not supported for EBCDIC"); aa->mac_error_ = 2; return; } begin_change(); display_.control = (display_.control + 1)%3; make_change(); end_change(); aa->SaveToMacro(km_control, unsigned __int64(0)); } void CHexEditView::OnControlToggle() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { // Can't toggle control chars, presumably in macro playback ASSERT(aa->playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display control characters without the char area"); else AfxMessageBox("Control character display is not supported for EBCDIC"); aa->mac_error_ = 2; return; } begin_change(); // This is called as a result of menu item which has only 2 states (unlike // dialog bar button handled by OnControl() above which has 3) if (display_.control > 0) display_.control = 0; else display_.control = 1; make_change(); end_change(); aa->SaveToMacro(km_control, 99); } void CHexEditView::OnUpdateControl(CCmdUI* pCmdUI) { pCmdUI->Enable((display_.vert_display || display_.char_area) && display_.char_set != CHARSET_EBCDIC); pCmdUI->SetCheck(display_.control != 0); } void CHexEditView::OnMark() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar SetMark(GetPos()); // Keep track whether mark is in hex or char area (if char area on) if (display_.vert_display) { // If cursor is in char row set mark to be in char area if (pos2row(GetCaret()) == 0) display_.mark_char = TRUE; else display_.mark_char = FALSE; } else if (display_.char_area && display_.hex_area) display_.mark_char = display_.edit_char; else if (display_.char_area) display_.mark_char = TRUE; else if (display_.hex_area) display_.mark_char = FALSE; aa->SaveToMacro(km_mark_pos); } void CHexEditView::SetMark(FILE_ADDRESS new_mark) { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Invalidate where mark was to change colours invalidate_addr_range(mark_, mark_ + 1); // Save current mark and move mark_ undo_.push_back(view_undo(undo_setmark)); undo_.back().address = mark_; undo_.push_back(view_undo(undo_state, TRUE)); undo_.back().disp_state = disp_state_; mark_ = new_mark; if (theApp.align_rel_ && mark_ != GetDocument()->base_addr_) { GetDocument()->StopSearch(); GetDocument()->base_addr_ = GetSearchBase(); GetDocument()->StartSearch(); } // Invalidate where mark now is to change background colour invalidate_addr_range(mark_, mark_ + 1); CHECK_SECURITY(41); show_calc(); // Some button enablement depends on mark_ position (eg. @ Mark) } void CHexEditView::OnGotoMark() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing if (!display_.vert_display && display_.char_area && display_.hex_area && display_.edit_char != display_.mark_char) { // Going to mark also entails swapping between hex and char areas FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); undo_.push_back(view_undo(undo_state)); undo_.back().disp_state = disp_state_; display_.edit_char = display_.mark_char; if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); // We need to specify the previous address since otherwise MoveToAddress // will use the current selection which is now in the wrong area. MoveWithDesc("Jump to Mark ", mark_, mark_, start_addr, end_addr, TRUE); // space at end means significant nav pt // Need to call SetSel in case MoveToAddress did not, due to no move (only area swap) SetSel(addr2pos(mark_, row), addr2pos(mark_, row), true); } else MoveWithDesc("Jump to Mark ", mark_); // space at end means significant nav pt aa->SaveToMacro(km_goto_mark); } void CHexEditView::OnExtendToMark() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); if ((end_base && mark_ == end_addr) || (!end_base && mark_ == start_addr)) { // There is nothing to do aa->mac_error_ = 1; return; } // Move the non-base end of the selection to the mark (MoveToAddress saves undo info) if (end_base) MoveToAddress(mark_, end_addr); else MoveWithDesc("Extend to Mark ", start_addr, mark_); // space at end means significant nav pt aa->SaveToMacro(km_extendto_mark); } // Swap the current caret position with the mark void CHexEditView::OnSwapMark() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // If same address and mark/caret are in same areas (both in hex or both in char area) return if (mark_ == start_addr && start_addr == end_addr && (display_.vert_display || !display_.char_area || !display_.hex_area || display_.edit_char == display_.mark_char)) { // There is nothing to do aa->mac_error_ = 1; return; } // If the caret and the mark are in different areas we have to swap them if (!display_.vert_display && display_.char_area && display_.hex_area && display_.edit_char != display_.mark_char) { undo_.push_back(view_undo(undo_state)); // save undo for edit_char_ and mark_char_ undo_.back().disp_state = disp_state_; display_.edit_char = !display_.edit_char; display_.mark_char = !display_.mark_char; if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); // We need to specify the previous address since otherwise MoveToAddress // will use the current selection which is now in the wrong area since // display_.edit_char has changed. MoveWithDesc("Swap Cursor with Mark ", mark_, mark_, start_addr, end_addr, TRUE); // Need to call SetSel in case MoveToAddress did not due to no move (only area swap) SetSel(addr2pos(mark_), addr2pos(mark_), true); } else MoveWithDesc("Swap Cursor with Mark ", mark_, -1, -1, -1, FALSE, FALSE, row); // Move the mark undo_.push_back(view_undo(undo_setmark, TRUE)); // save undo for move mark undo_.back().address = mark_; invalidate_addr_range(mark_, mark_ + 1); // force undraw of mark mark_ = start_addr; invalidate_addr_range(mark_, mark_ + 1); // force draw of new mark if (theApp.align_rel_ && mark_ != GetDocument()->base_addr_) { GetDocument()->StopSearch(); GetDocument()->base_addr_ = GetSearchBase(); GetDocument()->StartSearch(); } show_calc(); aa->SaveToMacro(km_swap_mark); } void CHexEditView::OnJumpDec() // message from BCG edit bar combo { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); CString addr_str, err_str; FILE_ADDRESS address = mm->GetDecAddress(addr_str, err_str); if (address == -1) { CString ss; ss.Format("Invalid expression\r\r%s\r\r%s", addr_str, err_str); AfxMessageBox(ss); return; } // If recording macro indicate jump & store address jumped to aa->SaveToMacro(km_address_dec, addr_str); #if 0 // Try to go to the address requested FILE_ADDRESS actual; if ((actual = GoAddress(address)) != address) { // Could not go to the requested address - tell user AfxMessageBox("Invalid address entered. Address set to EOF"); } SaveMove(); // Save prev pos in undo array DisplayCaret(); #else MoveWithDesc("Jump (Decimal Jump Tool) ", address); // space at end means significant nav pt #endif } void CHexEditView::OnJumpHex() // message from BCG edit bar combo { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); CString addr_str, err_str; FILE_ADDRESS address = mm->GetHexAddress(addr_str, err_str); if (address == -1) { CString ss; ss.Format("Invalid hex expression\r\r%s\r\r%s", addr_str, err_str); AfxMessageBox(ss); return; } // If recording macro indicate jump & store address jumped to theApp.SaveToMacro(km_address_hex, addr_str); MoveWithDesc("Jump (Hex Jump Tool) ", address); // space at end means significant nav pt } void CHexEditView::OnJumpHexAddr() // Alt-J { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHexEditControl::BeginJump(); } void CHexEditView::OnInsert() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; if (!do_insert()) return; aa->SaveToMacro(km_ovr_ins); } bool CHexEditView::do_insert() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (display_.readonly) { AfxMessageBox("Attempt to toggle OVR/INS in read only mode"); aa->mac_error_ = 10; return false; } if (GetDocument()->IsDevice()) { AfxMessageBox("You cannot use INS mode for devices (logical volumes and physical disks)"); aa->mac_error_ = 10; return false; } display_.overtype = !display_.overtype; undo_.push_back(view_undo(undo_overtype)); undo_.back().flag = !display_.overtype; if (GetDocument()->length() == 0) { DoInvalidate(); if (display_.overtype) ScrollMode(); else { CaretMode(); SetCaret(addr2pos(0)); // very start of file } } return true; } void CHexEditView::OnUpdateInsert(CCmdUI* pCmdUI) { pCmdUI->Enable(!display_.readonly && !GetDocument()->IsDevice()); pCmdUI->SetCheck(!display_.overtype); } void CHexEditView::OnAllowMods() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; allow_mods(); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); // Make sure calc buttons reflect modifiability of file if (!aa->refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); #if 0 // Obviated by BCG // Change the toolbar button mm->bb_allow_mods_.LoadBitmaps(display_.readonly ? IDB_MODSU : IDB_MODSS, IDB_MODSD,0,IDB_MODSX); mm->bb_allow_mods_.Invalidate(); #endif aa->SaveToMacro(km_ro_rw); } void CHexEditView::allow_mods() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (display_.readonly && GetDocument()->read_only()) { AfxMessageBox("This file cannot be modified"); aa->mac_error_ = 10; return; } display_.readonly = !display_.readonly; undo_.push_back(view_undo(undo_readonly)); undo_.back().flag = !display_.readonly; show_prop(); // things may be changeable now } void CHexEditView::OnUpdateAllowMods(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); pCmdUI->SetCheck(!display_.readonly); } void CHexEditView::OnToggleEndian() { begin_change(); display_.big_endian = !display_.big_endian; make_change(); end_change(); // Make calculator big endian check box reflects this file's big endian status CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!theApp.refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); theApp.SaveToMacro(km_big_endian, (__int64)-1); // -1 = toggle } void CHexEditView::OnUpdateToggleEndian(CCmdUI* pCmdUI) { pCmdUI->SetCheck(display_.big_endian); } void CHexEditView::OnBigEndian() { begin_change(); display_.big_endian = 1; make_change(); end_change(); // Make calculator big endian check box reflects this file's big endian status CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!theApp.refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); theApp.SaveToMacro(km_big_endian, (__int64)1); // 1 = big endian on } void CHexEditView::OnUpdateBigEndian(CCmdUI* pCmdUI) { pCmdUI->SetCheck(display_.big_endian); } void CHexEditView::OnLittleEndian() { begin_change(); display_.big_endian = 0; make_change(); end_change(); // Make calculator big endian check box reflects this file's big endian status CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!theApp.refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); theApp.SaveToMacro(km_big_endian, unsigned __int64(0)); // 0 = big endian off (ie little-endian) } void CHexEditView::OnUpdateLittleEndian(CCmdUI* pCmdUI) { pCmdUI->SetCheck(!display_.big_endian); } void CHexEditView::OnTrackChanges() { begin_change(); if (display_.hide_replace && display_.hide_insert && display_.hide_delete) { // All off - so turn them all on display_.hide_replace = display_.hide_insert = display_.hide_delete = 0; } else { // Turn them all off display_.hide_replace = display_.hide_insert = display_.hide_delete = 1; } make_change(); end_change(); theApp.SaveToMacro(km_track_changes, (__int64)-1); // -1 = toggle } void CHexEditView::OnUpdateTrackChanges(CCmdUI* pCmdUI) { pCmdUI->SetCheck(!(display_.hide_replace && display_.hide_insert && display_.hide_delete)); } void CHexEditView::OnDffdAutoSync() { if (pdfv_ == NULL) { AfxMessageBox("No DFFD tree view is displayed"); theApp.mac_error_ = 10; return; } begin_change(); display_.auto_sync_dffd = !display_.auto_sync_dffd; make_change(); end_change(); // If has been turned on then sync now if (display_.auto_sync_dffd) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pdfv_->SelectAt(start_addr); } theApp.SaveToMacro(km_dffd_sync, 2); } void CHexEditView::OnUpdateDffdAutoSync(CCmdUI* pCmdUI) { pCmdUI->Enable(pdfv_ != NULL); pCmdUI->SetCheck(display_.auto_sync_dffd); } void CHexEditView::OnDffdSync() { if (pdfv_ == NULL) { AfxMessageBox("No DFFD tree view is displayed"); theApp.mac_error_ = 10; return; } FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pdfv_->SelectAt(start_addr); pdfv_->SetFocus(); theApp.SaveToMacro(km_dffd_sync, 255); } void CHexEditView::OnUpdateDffdSync(CCmdUI* pCmdUI) { // Don't allow manual sync if auto sync is on pCmdUI->Enable(pdfv_ != NULL && !display_.auto_sync_dffd); } void CHexEditView::OnSearchHex() // Alt-L, F6 { CSearchEditControl::BeginSearch(CSearchEditControl::mode_hex); } void CHexEditView::OnSearchAscii() // F5 { CSearchEditControl::BeginSearch(CSearchEditControl::mode_char); } void CHexEditView::OnSearchIcase() // F4 { CSearchEditControl::BeginSearch(CSearchEditControl::mode_icase); } // CChildFrame *CHexEditView::comp_window() { CMainFrame *mm = dynamic_cast<CMainFrame *>(AfxGetMainWnd()); CChildFrame *nextc; // Loops through all MDI child frames CChildFrame *compc = NULL; // Frame of view available to compare with BOOL got_one; // Have we gound an appropriate view? // Get the currently active child MDI window nextc = dynamic_cast<CChildFrame *>(mm->MDIGetActive()); ASSERT(nextc != NULL); ASSERT(nextc->GetHexEditView() == this); // Search for another (non-iconized) window for (got_one = FALSE, nextc = dynamic_cast<CChildFrame *>(nextc->GetWindow(GW_HWNDNEXT)); nextc != NULL; nextc = dynamic_cast<CChildFrame *>(nextc->GetWindow(GW_HWNDNEXT)) ) { if (!nextc->IsIconic()) { // More than one found - use which one? if (got_one) { // Can't display message when used in OnUpdateEditCompare call // AfxMessageBox("Comparison not performed\r" // "- more than two (non-iconized) windows"); return NULL; } got_one = TRUE; compc = nextc; } } // If we didn't find a non-iconized window search for iconized one if (compc == NULL) { nextc = dynamic_cast<CChildFrame *>(mm->MDIGetActive()); // Search for an iconized window for (got_one = FALSE, nextc = dynamic_cast<CChildFrame *>(nextc->GetWindow(GW_HWNDNEXT)); nextc != NULL; nextc = dynamic_cast<CChildFrame *>(nextc->GetWindow(GW_HWNDNEXT)) ) { ASSERT(nextc->IsIconic()); // else compc != NULL // If more than one window - use which one? if (got_one) { // Can't display message when used in OnUpdateEditCompare call // AfxMessageBox("Comparison not performed\r" // "- more than two windows found"); return NULL; } got_one = TRUE; compc = nextc; } } return compc; } void CHexEditView::OnEditCompare() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = dynamic_cast<CMainFrame *>(AfxGetMainWnd()); CChildFrame *origc; // Pointer to MDI child frame of current view // Save the currently active child MDI window origc = dynamic_cast<CChildFrame *>(mm->MDIGetActive()); ASSERT(origc != NULL); ASSERT(origc->GetHexEditView() == this); // Restore current window if iconized if (origc->IsIconic()) { WINDOWPLACEMENT wp; origc->GetWindowPlacement(&wp); wp.showCmd = SW_RESTORE; origc->SetWindowPlacement(&wp); } // Get MDI child frame of compare window CChildFrame *compc = comp_window(); // If we found nothing to compare with, display message and return if (compc == NULL) { AfxMessageBox("Comparison not performed\r" "- two non-minimized windows required"); aa->mac_error_ = 10; return; } // Get view to compare with - active view of compc. (Actually the // active view should be the only view since we don't have splitters.) CHexEditView *compv = dynamic_cast<CHexEditView *>(compc->GetHexEditView()); if (compv == NULL) { AfxMessageBox("Cannot compare with this type of window"); aa->mac_error_ = 10; return; } ASSERT_KINDOF(CHexEditView, compv); CString orig_title, comp_title; // Title of the windows to be compared origc->GetWindowText(orig_title); compc->GetWindowText(comp_title); CHexEditDoc *origd, *compd; // Documents of the compared views origd = GetDocument(); compd = compv->GetDocument(); // Now compare the data from each view starting at END of current selection CString mess; // Message for user when problem encountered FILE_ADDRESS dummy; // Not used - start address of selection FILE_ADDRESS start_addr; // Start address in current view FILE_ADDRESS orig_addr, comp_addr; // Current comp location in both views GetSelAddr(dummy, start_addr); orig_addr = start_addr; compv->GetSelAddr(dummy, comp_addr); // start_addr = orig_addr = GetPos(); // comp_addr = compv->pos2addr(compv->GetCaret()); #ifndef _DEBUG // Allow self-compare for testing purposes // If same doc and same address then we aren't doing anything useful if (origd == compd && orig_addr == comp_addr) { mess.Format("Comparing data with itself in windows\r%s and %s", (const char *)orig_title, (const char *)comp_title); AfxMessageBox(mess); aa->mac_error_ = 10; return; } #endif size_t orig_got, comp_got; // How many bytes obtained from docs FILE_ADDRESS show_inc = 0x80000; // How far between showing addresses FILE_ADDRESS next_show = (orig_addr/show_inc + 1)*show_inc; // Next address to show FILE_ADDRESS slow_show = ((orig_addr+0x800000)/0x800000 + 1)*0x800000; // When we slow showing FILE_ADDRESS comp_length = min(origd->length() - orig_addr, compd->length() - comp_addr); // Get memory for compare buffers unsigned char *orig_buf = new unsigned char[compare_buf_len]; unsigned char *comp_buf = new unsigned char[compare_buf_len]; CWaitCursor wait; aa->SaveToMacro(km_compare); while (1) { if (orig_addr > next_show) { if (AbortKeyPress() && AfxMessageBox("Abort comparison?", MB_YESNO) == IDYES) { delete[] orig_buf; delete[] comp_buf; mm->Progress(-1); ((CMainFrame *)AfxGetMainWnd()) ->StatusBarText("Comparison aborted"); aa->mac_error_ = 10; show_pos(); return; } show_pos(next_show); // If we've been showing the current address for awhile then show // less often (and show progress) to avoid slowing down the actual compare if (next_show >= slow_show) { mm->Progress(int(((next_show-start_addr)*100)/comp_length)); show_inc = 0x800000; } AfxGetApp()->OnIdle(0); // Force display of updated address next_show += show_inc; } orig_got = origd->GetData(orig_buf, compare_buf_len, orig_addr); comp_got = compd->GetData(comp_buf, compare_buf_len, comp_addr); size_t comp_len = min(orig_got, comp_got); if (comp_len == 0) // EOF of one or both files break; if (memcmp(orig_buf, comp_buf, comp_len) != 0) { // Difference found size_t pos; for (pos = 0; pos < comp_len; ++pos) if (orig_buf[pos] != comp_buf[pos]) break; ASSERT(pos < comp_len); #ifdef SYS_SOUNDS CSystemSound::Play("Comparison Difference Found"); #endif // mess.Format("Difference found after $%I64X (decimal %I64d) bytes\r" // "%s at address $%I64X (decimal %I64d)\r%s at address $%I64X (decimal %I64d)", // __int64(orig_addr + pos - start_addr), __int64(orig_addr + pos - start_addr), // orig_title, __int64(orig_addr + pos), __int64(orig_addr + pos), // comp_title, __int64(comp_addr + pos), __int64(comp_addr + pos)); // AfxMessageBox(mess); mm->Progress(-1); char buf[32]; sprintf(buf, "%I64d", __int64(orig_addr + pos - start_addr)); mess = CString("Difference found after ") + buf + CString(" bytes"); mm->StatusBarText(mess); // Move to where diff found and select that byte in both views // (Selecting the byte allows the differences to be seen in both // windows without flipping between them, and allows another // compare immediately starting at the byte after.) compv->MoveWithDesc("Comparison Difference Found ", comp_addr + pos, comp_addr + pos + 1); MoveWithDesc("Comparison Difference Found ", orig_addr + pos, orig_addr + pos + 1); if (aa->highlight_) { compv->add_highlight(comp_addr + pos, comp_addr + pos + 1, TRUE); add_highlight(orig_addr + pos, orig_addr + pos + 1, TRUE); } delete[] orig_buf; delete[] comp_buf; return; } if (orig_got != comp_got) break; orig_addr += orig_got; comp_addr += comp_got; } mm->Progress(-1); // If we got here then we hit EOF on one or both files if (orig_got == comp_got && orig_addr + orig_got - start_addr == 0) { #ifdef SYS_SOUNDS CSystemSound::Play("Comparison Difference Not Found"); #endif mess = "Both files are at EOF"; if (aa->playing_) mm->StatusBarText(mess); else AfxMessageBox(mess); } else if (orig_got == comp_got) { #ifdef SYS_SOUNDS CSystemSound::Play("Comparison Difference Not Found"); #endif // EOF (both files) encountered ASSERT(orig_got == 0); show_pos(orig_addr); // Display message box when no differences found so that user sees that // something happened -- the caret is not moved and they may not notice // a message in the status bar (or the status bar may be invisible). // (On the other hand if a difference is found then the caret of both views // is moved and we just display a message in the status bar -- putting up // a dialog would just be annoying.) CString sdec, shex; char buf[22]; // temp buf where we sprintf sprintf(buf, "%I64d", __int64(orig_addr + orig_got - start_addr)); sdec = buf; AddCommas(sdec); if (aa->hex_ucase_) sprintf(buf, "%I64X", __int64(orig_addr + orig_got - start_addr)); else sprintf(buf, "%I64x", __int64(orig_addr + orig_got - start_addr)); shex = buf; AddSpaces(shex); mess.Format("No differences found after\r" "%s (%sh) bytes.", sdec, shex); // mess.Format("No differences found\r" // "after %lX (hex) or\r" // "%ld (decimal) bytes.", // orig_addr + orig_got - start_addr, // orig_addr + orig_got - start_addr); if (aa->playing_) mm->StatusBarText(mess); else AfxMessageBox(mess); aa->mac_error_ = 1; } else if (orig_got < comp_got) { #ifdef SYS_SOUNDS CSystemSound::Play("Comparison Difference Found"); #endif // EOF on orig file before EOF on comp file // mess.Format("Difference found after $%I64X (decimal %I64d) bytes\r" // "%s at EOF - address $%I64X (decimal %I64d)\r%s at address $%I64X (decimal %I64d)", // __int64(orig_addr + orig_got - start_addr), __int64(orig_addr + orig_got - start_addr), // orig_title, __int64(orig_addr + orig_got), __int64(orig_addr + orig_got), // comp_title, __int64(comp_addr + orig_got), __int64(comp_addr + orig_got)); // AfxMessageBox(mess); char buf[32]; sprintf(buf, "%I64d", __int64(orig_addr + orig_got - start_addr)); mess.Format("EOF on \"%s\" after %s bytes", orig_title, buf); mm->StatusBarText(mess); compv->MoveWithDesc("Comparison Difference Found ", comp_addr + orig_got, comp_addr + orig_got + 1); if (aa->highlight_) compv->add_highlight(comp_addr + orig_got, comp_addr + orig_got + 1, TRUE); MoveWithDesc("EOF in Comparison ", orig_addr + orig_got); } else { #ifdef SYS_SOUNDS CSystemSound::Play("Comparison Difference Found"); #endif // EOF on comp file before EOF on orig file // mess.Format("Difference found after $%lX (decimal %ld) bytes\r" // "%s at address $%lX (decimal %ld)\r%s at EOF - address $%lX (decimal %ld)", // orig_addr + comp_got - start_addr, orig_addr + comp_got - start_addr, // orig_title, orig_addr + comp_got, orig_addr + comp_got, // comp_title, comp_addr + comp_got, comp_addr + comp_got); // AfxMessageBox(mess); char buf[32]; sprintf(buf, "%I64d", __int64(orig_addr + comp_got - start_addr)); mess.Format("EOF on \"%s\" after %s bytes", comp_title, buf); mm->StatusBarText(mess); compv->MoveWithDesc("EOF in Comparison ", comp_addr + comp_got); MoveWithDesc("Comparison Difference Found ", orig_addr + comp_got, orig_addr + comp_got + 1); if (aa->highlight_) add_highlight(orig_addr + comp_got, orig_addr + comp_got + 1, TRUE); } delete[] orig_buf; delete[] comp_buf; } void CHexEditView::OnUpdateEditCompare(CCmdUI* pCmdUI) { pCmdUI->Enable(comp_window() != NULL); } // Activate next window void CHexEditView::OnWindowNext() { #if 0 // This was changed for consistency with km_win_next in macros. // The problem is to make sure all windows are cycled through when // Window/Next is used whether or not in a macro (and in the same order). // - next window in macro does not change focus now (for speed) but just keeps track of active view // - if focus is set Windows changes order of windows (Z order) returned by GetWindow(GW_HWNDNEXT) // - the MDI functions (MDINext etc) seem to use some sort of list where order does not change with focus change // - but MDINext changes focus and there appears to be no way to get at the list without changing focus // For the above reasons and for consistency the next window command both // in and not in macros uses the new NextView function below. // Activate next window that is not a print preview window and is not minimized CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = dynamic_cast<CMainFrame *>(::AfxGetMainWnd()); CChildFrame *currc; // Currently active MDI child frame CChildFrame *nextc; // Loops through all MDI child frames // Save the currently active child MDI window currc = dynamic_cast<CChildFrame *>(mm->MDIGetActive()); ASSERT(currc != NULL); ASSERT(currc->GetHexEditView() == this); while (mm->MDINext(), (nextc = dynamic_cast<CChildFrame *>(mm->MDIGetActive())) != currc) { // Don't change to iconized windows if (!nextc->IsIconic()) { // Make sure it's a CHexEditView (don't change to print preview windows) CHexEditView *pview = dynamic_cast<CHexEditView *>(nextc->GetHexEditView()); if (pview != NULL && pview->IsKindOf(RUNTIME_CLASS(CHexEditView))) { nextc->SetActiveView(pview); if (aa->recording_ && aa->mac_.size() > 0 && (aa->mac_.back()).ktype == km_focus) { // We don't want focus change recorded (see CHexEditView::OnSetFocus) aa->mac_.pop_back(); } aa->SaveToMacro(km_win_next); return; } } } ((CMainFrame *)AfxGetMainWnd())-> StatusBarText("Warning: no other non-minimized windows found"); aa->mac_error_ = 2; #endif // Get the next window CHexEditView *pnext = NextView(); if (pnext == NULL) { AfxMessageBox("Warning: no other non-minimized windows found"); theApp.mac_error_ = 2; return; } // Make new view active pnext->GetFrame()->MDIActivate(); // Activate next frame pnext->GetFrame()->SetActiveView(pnext); // Make sure active view is normal (hex) view ASSERT(pnext == GetView()); // Make sure it is now the active view if (theApp.recording_ && theApp.mac_.size() > 0 && (theApp.mac_.back()).ktype == km_focus) { // We don't want focus change recorded (see CHexEditView::OnSetFocus) theApp.mac_.pop_back(); } theApp.SaveToMacro(km_win_next); } // Return next view in list non-minimised view or NULL if none. // Cycles through the list in reverse order so repeated calls // and focus changes still return all the non-minimised frames. CHexEditView * CHexEditView::NextView() const { CChildFrame *currc = dynamic_cast<CChildFrame *>(GetFrame()); ASSERT(currc != NULL); CChildFrame *nextc = currc; do { nextc = dynamic_cast<CChildFrame *>(nextc->GetWindow(GW_HWNDPREV)); // If reached the top of the list go to the end if (nextc == NULL) nextc = dynamic_cast<CChildFrame *>(currc->GetWindow(GW_HWNDLAST)); } while (nextc != NULL && nextc != currc && nextc->IsIconic()); if (nextc == NULL || nextc == currc) return NULL; else return nextc->GetHexEditView(); } void CHexEditView::OnAscii2Ebcdic() { DoConversion(CONVERT_ASC2EBC, "convert ASCII to EBCDIC"); } void CHexEditView::OnEbcdic2Ascii() { DoConversion(CONVERT_EBC2ASC, "convert EBCDIC to ASCII"); } void CHexEditView::OnAnsi2Ibm() { DoConversion(CONVERT_ANSI2IBM, "convert ANSI to IBM/OEM"); } void CHexEditView::OnIbm2Ansi() { DoConversion(CONVERT_IBM2ANSI, "convert IBM/OEM to ANSI"); } void CHexEditView::OnUppercase() { DoConversion(CONVERT_UPPER, "convert to upper case"); } void CHexEditView::OnLowercase() { DoConversion(CONVERT_LOWER, "convert to lower case"); } // Performs particular conversions on a memory buffer void CHexEditView::ProcConversion(unsigned char *buf, size_t count, convert_type op) { // Operate on all the selected values for (size_t ii = 0; ii < count; ++ii) { switch (op) { case CONVERT_ASC2EBC: if (buf[ii] < 128) buf[ii] = a2e_tab[buf[ii]]; else buf[ii] = '\0'; break; case CONVERT_EBC2ASC: buf[ii] = e2a_tab[buf[ii]]; break; case CONVERT_ANSI2IBM: if (buf[ii] > 128) buf[ii] = a2i_tab[buf[ii]&0x7F]; break; case CONVERT_IBM2ANSI: if (buf[ii] > 128) buf[ii] = i2a_tab[buf[ii]&0x7F]; break; case CONVERT_UPPER: if (EbcdicMode()) { if (buf[ii] >= 0x81 && buf[ii] <= 0x89 || buf[ii] >= 0x91 && buf[ii] <= 0x99 || buf[ii] >= 0xA2 && buf[ii] <= 0xA9 ) { buf[ii] += 0x40; } } else if (ANSIMode() || buf[ii] < 128) buf[ii] = toupper(buf[ii]); break; case CONVERT_LOWER: if (EbcdicMode()) { if (buf[ii] >= 0xC1 && buf[ii] <= 0xC9 || buf[ii] >= 0xD1 && buf[ii] <= 0xD9 || buf[ii] >= 0xE2 && buf[ii] <= 0xE9 ) { buf[ii] -= 0x40; } } else if (ANSIMode() || buf[ii] < 128) buf[ii] = tolower(buf[ii]); break; default: ASSERT(0); } } } // This handles conversion operations (everything except for the actual data // convert operation - see ProcConversion) including getting the selection // and allocating memory buffers to store the result (or temp file for // really big selections) and updating the document. // It also updates progress in the status bar and allows user abort. void CHexEditView::DoConversion(convert_type op, LPCSTR desc) { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; if (check_ro(desc)) return; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); // Make sure there is a selection if (start_addr >= end_addr) { ASSERT(theApp.playing_); CString mess; mess.Format("There is no selection to %s", desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } ASSERT(start_addr < end_addr && end_addr <= GetDocument()->length()); // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && GetDocument()->DataFileSlotFree()) { int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) // Create a file to store the resultant data // (Temp file used by the document until it is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); // Get data buffer size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); if (op != unary_at) // We don't need to get old value if assigning VERIFY(GetDocument()->GetData(buf, len, curr) == len); ProcConversion(buf, len, op); ff.Write(buf, len); if (AbortKeyPress()) { CString mess; mess.Format("Abort %s?", desc); if (AfxMessageBox(mess, MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the unprocessed block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); // Add the temp file to the document idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); GetDocument()->Change(mod_insert_file, start_addr, end_addr - start_addr, NULL, idx, this, TRUE); } else { // Allocate memory block and process it // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot convert such a large selection. \n" "Please save the file to deallocate \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and converting such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) try { buf = new unsigned char[size_t(end_addr - start_addr)]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } size_t got = GetDocument()->GetData(buf, size_t(end_addr - start_addr), start_addr); ASSERT(got == size_t(end_addr - start_addr)); ProcConversion(buf, got, op); GetDocument()->Change(mod_replace, start_addr, got, (unsigned char *)buf, 0, this); } DisplayCaret(); theApp.SaveToMacro(km_convert, op); func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } // Make sure there is a selection before doing conversion void CHexEditView::OnUpdateConvert(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start_addr < end_addr ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(start_addr < end_addr); } void CHexEditView::OnEncrypt() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (check_ro("encrypt")) return; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); // Make sure there is a selection if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("There is no selection to encrypt"); aa->mac_error_ = 10; return; } if (aa->password_.IsEmpty()) { CPassword dlg; dlg.m_password = aa->password_; if (dlg.DoModal() == IDOK) { aa->password_ = dlg.m_password; // Create encryption key with new password if (aa->algorithm_ > 0) { ASSERT(aa->algorithm_ - 1 < (int)aa->crypto_.GetNum()); aa->crypto_.SetPassword(aa->algorithm_-1, aa->password_); } } else return; } else if (aa->algorithm_ > 0 && aa->crypto_.NeedsPassword(aa->algorithm_-1)) { // We have a password but somehow it has not been set for this alg ASSERT(aa->algorithm_ - 1 < (int)aa->crypto_.GetNum()); aa->crypto_.SetPassword(aa->algorithm_-1, aa->password_); } unsigned char *buf = NULL; if (aa->algorithm_ > 0) { if (display_.overtype && aa->crypto_.needed(aa->algorithm_-1, 256) != 256) { if (AfxMessageBox("Encrypting with this algorithm will increase the\r" "the length of the current (unencrypted) selection.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 10; return; } else if (!do_insert()) return; } // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && GetDocument()->DataFileSlotFree()) { CWaitCursor wait; // Turn on wait cursor (hourglass) // Get input and output buffers size_t inbuflen = 32768; size_t outbuflen = aa->crypto_.needed(aa->algorithm_-1, inbuflen); FILE_ADDRESS total_out = 0; try { buf = new unsigned char[outbuflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } // Create a "temp" file to store the encrypted data // (This file stores the data until the document is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); size_t len; // size of data to be encrypted for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(inbuflen, end_addr - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); // Encrypt and write it size_t outlen = aa->crypto_.encrypt(aa->algorithm_-1, buf, len, outbuflen, curr + len == end_addr); ff.Write(buf, outlen); total_out += outlen; if (AbortKeyPress() && AfxMessageBox("Abort encryption?", MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the unencrypted block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); // Add the temp file to the document int idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); GetDocument()->Change(mod_insert_file, start_addr, total_out, NULL, idx, this, TRUE); // If length changed update the selection and makde sure it is undoable if (total_out != end_addr - start_addr) { // Select encrypted data SetSel(addr2pos(start_addr), addr2pos(start_addr + total_out)); // Inform the user in case they don't notice the selection has been increased CString mess; mess.Format("Encryption increased the selection length by %ld bytes", long(total_out - (end_addr - start_addr))); ((CMainFrame *)AfxGetMainWnd())->StatusBarText(mess); } } else { // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot encrypt such a large selection. \n" "Please save the file to free \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // More than 128 Mb may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and encrypting such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) size_t len = size_t(end_addr - start_addr); // Length of selection size_t outlen = aa->crypto_.needed(aa->algorithm_-1, len); // Get memory for selection and read it from the document try { buf = new unsigned char[outlen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); aa->mac_error_ = 10; return; } VERIFY(GetDocument()->GetData(buf, len, start_addr) == len); if (aa->crypto_.encrypt(aa->algorithm_-1, buf, len, outlen) != outlen) { ASSERT(0); AfxMessageBox("Encryption error"); aa->mac_error_ = 10; goto func_return; } if (len != outlen) { ASSERT(outlen > len); // Since the encrypted text is bigger we must delete then insert GetDocument()->Change(mod_delforw, start_addr, len, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, outlen, buf, 0, this, TRUE); ASSERT(undo_.back().utype == undo_change); undo_.back().previous_too = true; // Merge changes (at least in this view) // Select encrypted data and save undo of selection SetSel(addr2pos(start_addr), addr2pos(start_addr+outlen)); // Inform the user in case they don't notice the selection has been increased CString mess; mess.Format("Encryption increased the selection length by %ld bytes", long(outlen-len)); ((CMainFrame *)AfxGetMainWnd())->StatusBarText(mess); } else GetDocument()->Change(mod_replace, start_addr, len, buf, 0, this); } } else { // Note that CryptoAPI algs (above) the key is set when password // or alg is changed (more efficient) but for internal we set it here // in case other internal use (security) has changed the current key ::set_key(aa->password_, aa->password_.GetLength()); // Make sure selection is right size if ((end_addr-start_addr)%8 != 0) { // Presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("The selection is not a multiple of 8 (encryption block length)"); aa->mac_error_ = 10; return; } size_t len; // Length of selection // Note: for internal alg. we don't break the encryption up and write // to temp file in order to handle huge selections as above (yet?) // Get memory for selection and read it from the document try { if (end_addr - start_addr > UINT_MAX) throw std::bad_alloc(); len = size_t(end_addr - start_addr); buf = new unsigned char[len]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory - selection too large"); aa->mac_error_ = 10; return; } VERIFY(GetDocument()->GetData(buf, len, start_addr) == len); ::encrypt(buf, len); GetDocument()->Change(mod_replace, start_addr, len, buf, 0, this); } DisplayCaret(); aa->SaveToMacro(km_encrypt, 1); // 1 == encrypt (2 == decrypt) func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnDecrypt() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (aa->algorithm_ < 0 || check_ro("decrypt")) return; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); // Make sure there is a selection if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("There is no selection to decrypt"); aa->mac_error_ = 10; return; } if (aa->password_.IsEmpty()) { CPassword dlg; dlg.m_password = aa->password_; if (dlg.DoModal() == IDOK) { aa->password_ = dlg.m_password; // Create encryption key with new password if (aa->algorithm_ > 0) { ASSERT(aa->algorithm_ - 1 < (int)aa->crypto_.GetNum()); aa->crypto_.SetPassword(aa->algorithm_-1, aa->password_); } } else return; } else if (aa->algorithm_ > 0 && aa->crypto_.NeedsPassword(aa->algorithm_-1)) { // We have a password but somehow it has not been set for this alg ASSERT(aa->algorithm_ - 1 < (int)aa->crypto_.GetNum()); aa->crypto_.SetPassword(aa->algorithm_-1, aa->password_); } unsigned char *buf = NULL; if (aa->algorithm_ > 0) { int blen = aa->crypto_.GetBlockLength(aa->algorithm_-1); if (blen == -1) { AfxMessageBox("Encryption block length error"); aa->mac_error_ = 10; return; } if (blen != 0 && display_.overtype) { if (AfxMessageBox("Decrypting with this algorithm may decrease \r" "the length of the current (encrypted) selection.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 10; return; } else if (!do_insert()) return; } ASSERT(blen%8 == 0); // Should be multiple of number of bits/byte if (blen == 0) blen = 1; // Stream cipher - don't restrict selection length else blen = blen/8; // Convert bits to bytes // Make sure selection is right size if ((end_addr-start_addr)%blen != 0) { // Presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("The selection is not a multiple of encryption block length"); aa->mac_error_ = 10; return; } // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && GetDocument()->DataFileSlotFree()) { CWaitCursor wait; // Turn on wait cursor (hourglass) size_t len, buflen = 32768; ASSERT(buflen % blen == 0); // buffer length must be multiple of cipher block length FILE_ADDRESS total_out = 0; try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } // Create a "temp" file to store the decrypted data // (This file stores the data until the document is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); size_t outlen = aa->crypto_.decrypt(aa->algorithm_-1, buf, len, curr + len == end_addr); if (outlen == size_t(-1)) { AfxMessageBox(CString("Could not decrypt using:\n") + aa->crypto_.GetName(aa->algorithm_-1)); ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } ff.Write(buf, outlen); total_out += outlen; if (AbortKeyPress() && AfxMessageBox("Abort decryption?", MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the original encrypted block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); // Add the temp file to the document int idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); GetDocument()->Change(mod_insert_file, start_addr, total_out, NULL, idx, this, TRUE); if (total_out != end_addr - start_addr) { // Select the decrypted data SetSel(addr2pos(start_addr), addr2pos(start_addr + total_out)); // Inform the user in case they don't notice the selection has been increased CString mess; mess.Format("Decryption decreased the selection length by %ld bytes", long(end_addr - start_addr - total_out)); ((CMainFrame *)AfxGetMainWnd())->StatusBarText(mess); } } else { // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot decrypt such a large selection. \n" "Please save the file to free \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and decrypting such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } size_t len = size_t(end_addr - start_addr); // Length of selection size_t outlen; // Size of decrypted text (may be less than encrypted) // Get memory for selection and read it from the document try { buf = new unsigned char[len]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); aa->mac_error_ = 10; return; } VERIFY(GetDocument()->GetData(buf, len, start_addr) == len); outlen = aa->crypto_.decrypt(aa->algorithm_-1, buf, len); if (outlen == size_t(-1)) { AfxMessageBox(CString("Could not decrypt using:\n") + aa->crypto_.GetName(aa->algorithm_-1)); aa->mac_error_ = 10; goto func_return; } if (len != outlen) { ASSERT(outlen < len); // Since the decrypted text is smaller we must delete then insert GetDocument()->Change(mod_delforw, start_addr, len, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, outlen, buf, 0, this, TRUE); ASSERT(undo_.back().utype == undo_change); undo_.back().previous_too = true; // Merge changes (at least in this view) // Select encrypted data and save undo of selection SetSel(addr2pos(start_addr), addr2pos(start_addr+outlen)); // Inform the user in case they don't notice the selection has been decreased CString mess; mess.Format("Decryption decreased the selection length by %ld bytes", long(len-outlen)); ((CMainFrame *)AfxGetMainWnd())->StatusBarText(mess); } else GetDocument()->Change(mod_replace, start_addr, len, buf, 0, this); } } else { // Note that CryptoAPI algs (above) the key is set when password // or alg is changed (more efficient) but for internal we set it here // in case other internal use (security) has changed the current key ::set_key(aa->password_, aa->password_.GetLength()); // Make sure selection is right size if ((end_addr-start_addr)%8 != 0) { // Presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("The selection is not a multiple of 8 (encryption block length)"); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) size_t len; // Length of selection // Note: for internal alg. we don't break the decryption up and write // to temp file to handle huge selections as above (yet?) // Get memory for selection and read it from the document try { if (end_addr - start_addr > UINT_MAX) throw std::bad_alloc(); len = size_t(end_addr - start_addr); buf = new unsigned char[len]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); aa->mac_error_ = 10; return; } VERIFY(GetDocument()->GetData(buf, len, start_addr) == len); ::decrypt(buf, len); GetDocument()->Change(mod_replace, start_addr, len, buf, 0, this); } DisplayCaret(); aa->SaveToMacro(km_encrypt, 2); // 2 == decrypt (1 == encrypt) func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnUpdateEncrypt(CCmdUI* pCmdUI) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) pCmdUI->Enable(FALSE); else if (aa->algorithm_ == 0) { // Internal algorithm must encrypt mult. of 8 bytes (Blow Fish has 64 bit block length) pCmdUI->Enable((end_addr-start_addr)%8 == 0); } } void CHexEditView::OnCompress() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *in_data = NULL; unsigned char *out_data = NULL; // Check if file is read-only and ask user if they want to turn this off if (check_ro("compress")) return; // Check if in OVR mode and ask the user if they want to turn this off if (display_.overtype) { if (AfxMessageBox("Compression will change the selection length\r" "which is not allowed in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 10; return; } else if (!do_insert()) return; } // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); // Make sure there is a selection if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("There is no selection to compress"); theApp.mac_error_ = 10; return; } // Initialise structure used to communicate with the zlib routines z_stream zs; int level = Z_DEFAULT_COMPRESSION; if (theApp.GetProfileInt("Options", "ZlibCompressionDVLevel", 1) == 0) level = theApp.GetProfileInt("Options", "ZlibCompressionLevel", level); ASSERT(level == Z_DEFAULT_COMPRESSION || (level >= 1 && level <= 9)); int windowBits = 15; if (theApp.GetProfileInt("Options", "ZlibCompressionDVWindow", 1) == 0) windowBits = theApp.GetProfileInt("Options", "ZlibCompressionWindow", windowBits); ASSERT(windowBits >= 8 && windowBits <= 15); switch (theApp.GetProfileInt("Options", "ZlibCompressionHeaderType", 1)) { case 0: // raw (no header) windowBits = - windowBits; break; case 2: // gzip header windowBits += 16; break; default: ASSERT(0); case 1: break; } int memLevel = 8; if (theApp.GetProfileInt("Options", "ZlibCompressionDVMemory", 1) == 0) memLevel = theApp.GetProfileInt("Options", "ZlibCompressionMemory", memLevel); ASSERT(memLevel >= 1 && memLevel <= 9); int strategy = theApp.GetProfileInt("Options", "ZlibCompressionStrategy", Z_DEFAULT_STRATEGY); ASSERT( strategy == Z_DEFAULT_STRATEGY || strategy == Z_FILTERED || strategy == Z_HUFFMAN_ONLY || strategy == Z_RLE || strategy == Z_FIXED ); zs.zalloc = (alloc_func)0; zs.zfree = (free_func)0; zs.opaque = (voidpf)0; // VERIFY(deflateInit(&zs, Z_DEFAULT_COMPRESSION) == Z_OK); VERIFY(deflateInit2(&zs, level, Z_DEFLATED, // only method currently supported by zlib windowBits, memLevel, strategy ) == Z_OK); // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && GetDocument()->DataFileSlotFree()) { CWaitCursor wait; // Turn on wait cursor (hourglass) int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) // Create a "temp" file to store the compressed data // (This file stores the compressed data until the document is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); // Get input and output buffers size_t len, inbuflen = size_t(min(32768, end_addr - start_addr)), outbuflen = max(inbuflen/2, 256); // Work out no of input blocks per sync int sync_every = (theApp.GetProfileInt("Options", "ZlibCompressionSync", 0)*1024)/inbuflen; FILE_ADDRESS total_out = 0; int err; try { in_data = new unsigned char[inbuflen]; out_data = new unsigned char[outbuflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { int flush; if (sync_every > 0 && (curr - start_addr)/inbuflen % sync_every == sync_every - 1) // time to sync? flush = Z_FULL_FLUSH; else flush = Z_NO_FLUSH; // Get the next buffer full from the document len = size_t(min(inbuflen, end_addr - curr)); VERIFY(GetDocument()->GetData(in_data, len, curr) == len); // Compress this buffer zs.next_in = in_data; zs.avail_in = len; do { zs.next_out = out_data; zs.avail_out = outbuflen; err = deflate(&zs, flush); ASSERT(err == Z_OK); // Write to "temp" file ff.Write(out_data, outbuflen - zs.avail_out); total_out += outbuflen - zs.avail_out; // we need to keep track of this ourselves since zs.total_out can overflow } while (zs.avail_out == 0); ASSERT(zs.avail_in == 0); if (AbortKeyPress() && AfxMessageBox("Abort compression?", MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } // Process any residual data do { zs.next_out = out_data; zs.avail_out = outbuflen; err = deflate(&zs, Z_FINISH); ASSERT(err == Z_OK || err == Z_STREAM_END); ff.Write(out_data, outbuflen - zs.avail_out); total_out += outbuflen - zs.avail_out; } while (err == Z_OK); ASSERT(err == Z_STREAM_END); } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the uncompressed block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); // Add the temp file to the document idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); GetDocument()->Change(mod_insert_file, start_addr, total_out, NULL, idx, this, TRUE); // Select compressed data SetSel(addr2pos(start_addr), addr2pos(start_addr + total_out)); // Inform the user about the amount of compression CString mess; mess.Format("Compressed %d%%", int((1.0 - double(total_out)/(end_addr - start_addr))*100.0 + 0.5)); mm->StatusBarText(mess); } else { // Allocate memory block and compress into it // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot compress such a large selection. \n" "Please save the file to free \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and compressing such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) try { // Get buffer for data, get the data, and get buffer for compressed data in_data = new unsigned char[size_t(end_addr - start_addr)]; size_t got = GetDocument()->GetData(in_data, size_t(end_addr - start_addr), start_addr); ASSERT(got == size_t(end_addr - start_addr)); // Remove uncompressed data from the document GetDocument()->Change(mod_delforw, start_addr, got, NULL, 0, this); size_t outbuflen = max(got/2, 256); out_data = new unsigned char[outbuflen]; FILE_ADDRESS curr = start_addr; int err; // return value from inflate (normally Z_OK or Z_STREAM_END) zs.next_in = in_data; zs.avail_in = got; do { zs.next_out = out_data; zs.avail_out = outbuflen; err = deflate(&zs, Z_FINISH); ASSERT(err == Z_OK || err == Z_STREAM_END); // Replace the selection with the compressed data if (outbuflen - zs.avail_out > 0) GetDocument()->Change(mod_insert, curr, outbuflen - zs.avail_out, out_data, 0, this, TRUE); curr += outbuflen - zs.avail_out; } while (err == Z_OK); ASSERT(err == Z_STREAM_END); // Select compressed block SetSel(addr2pos(start_addr), addr2pos(start_addr+zs.total_out)); // Inform the user about the amount of compression CString mess; mess.Format("Compressed %d%%", int((1.0 - double(zs.total_out)/got)*100.0 + 0.5)); mm->StatusBarText(mess); } catch (std::bad_alloc) { // Note: this exception may come from ZLIB AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; // Undo changes already made (but make sure we don't record undo in macros) OnEditUndo(); if (theApp.recording_ && theApp.mac_.size() > 0 && (theApp.mac_.back()).ktype == km_undo) theApp.mac_.pop_back(); goto func_return; } } VERIFY(deflateEnd(&zs) == Z_OK); DisplayCaret(); theApp.SaveToMacro(km_compress, 1); // 1 = compress (2 = decompress) func_return: mm->Progress(-1); // disable progress bar if (in_data != NULL) delete[] in_data; if (out_data != NULL) delete[] out_data; } void CHexEditView::OnDecompress() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *in_data = NULL; unsigned char *out_data = NULL; // Check if file is read-only and ask user if they want to turn this off if (check_ro("decompress")) return; // Check if in OVR mode and ask the user if they want to turn this off if (display_.overtype) { if (AfxMessageBox("Decompression will change the selection length\r" "which is not allowed in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 10; return; } else if (!do_insert()) return; } // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); // Make sure there is a selection if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("There is no selection to decompress"); theApp.mac_error_ = 10; return; } // Initialise structure used to communicate with the zlib routines z_stream zs; zs.zalloc = (alloc_func)0; zs.zfree = (free_func)0; zs.opaque = (voidpf)0; zs.next_in = (Bytef*)0; zs.avail_in = 0; // VERIFY(inflateInit(&zs) == Z_OK); int windowBits = 15; if (theApp.GetProfileInt("Options", "ZlibCompressionDVWindow", 1) == 0) windowBits = theApp.GetProfileInt("Options", "ZlibCompressionWindow", windowBits); ASSERT(windowBits >= 8 && windowBits <= 15); switch (theApp.GetProfileInt("Options", "ZlibCompressionHeaderType", 1)) { case 0: // raw (no header) windowBits = - windowBits; // assume no header break; default: ASSERT(0); case 1: case 2: windowBits += 32; // auto detect header type break; } VERIFY(inflateInit2(&zs, windowBits ) == Z_OK); // Test if selection is too big to do in memory (Note that even a small selection can expand greatly) if (end_addr - start_addr > (2*1024*1024) && GetDocument()->DataFileSlotFree()) { CWaitCursor wait; // Turn on wait cursor (hourglass) int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) // Create a "temp" file to store the compressed data // (This file stores the compressed data until the document is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); // Get input and output buffers size_t len, outbuflen = size_t(min(32768, end_addr - start_addr)), inbuflen = max(outbuflen/4, 256); FILE_ADDRESS total_out = 0; int err = Z_OK; try { in_data = new unsigned char[inbuflen]; out_data = new unsigned char[outbuflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); // For each chunk of the currently selected block for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(inbuflen, end_addr - curr)); VERIFY(GetDocument()->GetData(in_data, len, curr) == len); zs.next_in = in_data; zs.avail_in = len; do { // Prepare output buffer zs.next_out = out_data; zs.avail_out = outbuflen; if (err == Z_DATA_ERROR) { // We must still be trying to sync from previously encountered data error err = inflateSync(&zs); } else { err = inflate(&zs, Z_NO_FLUSH); ASSERT(err == Z_OK || err == Z_STREAM_END || err == Z_DATA_ERROR || err == Z_BUF_ERROR); // Note Z_BUF_ERROR can occur when zs.avail_out == 0 (and zs.avail_in after previous call was zero). // This is not a fatal error and according to the docs we should continue looping while zs.avail_in == 0. if (err == Z_DATA_ERROR) { theApp.mac_error_ = 5; if (AfxMessageBox("The compression data is corrupted. \n" "HexEdit can save the data decompressed \n" "so far and attempt to recover from \n" "this error but some data will be lost. \n\n" "Do you want to continue?", MB_YESNO) != IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Continue reading the data checking for sync point (see inflateSync call above) } ff.Write(out_data, outbuflen - zs.avail_out); // write all that we got total_out += outbuflen - zs.avail_out; // we need to keep track of this ourselves since zs.total_out can overflow } } while (zs.avail_out == 0 || zs.avail_in != 0); // if output buffer is full there may be more if (AbortKeyPress() && AfxMessageBox("Abort decompression?", MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } ASSERT(err == Z_STREAM_END || err == Z_DATA_ERROR); ASSERT(ff.GetLength() == total_out); if (err == Z_DATA_ERROR) { AfxMessageBox("HexEdit did not recover from \n" "the compression data error. "); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } if (total_out == 0) { // This could happen if there were data errors remove(temp_file); theApp.mac_error_ = 5; goto func_return; } // Delete the input (compressed) block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); // Add the temp file to the document idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); GetDocument()->Change(mod_insert_file, start_addr, total_out, NULL, idx, this, TRUE); // Select uncompressed block SetSel(addr2pos(start_addr), addr2pos(start_addr + total_out)); // Inform the user about the amount of compression CString mess; mess.Format("Expanded by %d%%", int((double(total_out)/(end_addr - start_addr) - 1.0)*100.0 + 0.5)); mm->StatusBarText(mess); } else { // Allocate memory block and decompress into it // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot decompress such a large selection. \n" "Please save the file to free \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and decompressing such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) try { // Get buffer for input data, get the data, and get buffer for output (decompressed) data in_data = new unsigned char[size_t(end_addr - start_addr)]; size_t got = GetDocument()->GetData(in_data, size_t(end_addr - start_addr), start_addr); ASSERT(got == size_t(end_addr - start_addr)); // Remove input (compressed) block from the document GetDocument()->Change(mod_delforw, start_addr, got, NULL, 0, this); size_t outbuflen = max(4*got, 256); out_data = new unsigned char[outbuflen]; FILE_ADDRESS curr = start_addr; // Current output address int err = Z_OK; // return value from inflate or inflateSync zs.next_in = in_data; zs.avail_in = got; do { zs.next_out = out_data; zs.avail_out = outbuflen; if (err == Z_DATA_ERROR) { // We must still be trying to sync from previously encountered data error err = inflateSync(&zs); } if (err != Z_DATA_ERROR) { err = inflate(&zs, Z_NO_FLUSH); ASSERT(err == Z_OK || err == Z_STREAM_END || err == Z_BUF_ERROR || err == Z_DATA_ERROR); if (err == Z_DATA_ERROR) { if (AfxMessageBox("The compression data is corrupted. \n" "HexEdit can attempt to recover from \n" "this error but some data will be lost. \n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 10; // Undo changes already (but make sure we don't record undo in macros) OnEditUndo(); if (theApp.recording_ && theApp.mac_.size() > 0 && (theApp.mac_.back()).ktype == km_undo) theApp.mac_.pop_back(); goto func_return; } } // Add the decompressed data block to the file if (outbuflen - zs.avail_out > 0) GetDocument()->Change(mod_insert, curr, outbuflen - zs.avail_out, out_data, 0, this, TRUE); curr += outbuflen - zs.avail_out; } } while (zs.avail_out == 0 || zs.avail_in != 0); ASSERT(err == Z_STREAM_END); // Select uncompressed block SetSel(addr2pos(start_addr), addr2pos(start_addr+zs.total_out)); // Inform the user about the amount of compression CString mess; mess.Format("Expanded by %d%%", int((double(zs.total_out)/got - 1.0)*100.0 + 0.5)); mm->StatusBarText(mess); } catch (std::bad_alloc) { // Note this exception may come from ZLIB AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; // Undo changes already made (but make sure we don't record undo in macros) OnEditUndo(); if (theApp.recording_ && theApp.mac_.size() > 0 && (theApp.mac_.back()).ktype == km_undo) theApp.mac_.pop_back(); goto func_return; } } VERIFY(inflateEnd(&zs) == Z_OK); DisplayCaret(); theApp.SaveToMacro(km_compress, 2); // 2 = decompress (1 = compress) func_return: mm->Progress(-1); // disable progress bar if (in_data != NULL) delete[] in_data; if (out_data != NULL) delete[] out_data; } // Enable commands that depend simply on a non-zero selection void CHexEditView::OnUpdateSelNZ(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); pCmdUI->Enable(start_addr < end_addr); } // The following functions are used as update handlers // They enable their corresponding UI handlers if there are // enough bytes between the current address and the end of file void CHexEditView::OnUpdateByte(CCmdUI* pCmdUI) { pCmdUI->Enable(GetPos() < GetDocument()->length()); } void CHexEditView::OnUpdate16bit(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) // No selection so only enable if enough before EOF (2 bytes) pCmdUI->Enable(start_addr + 1 < GetDocument()->length()); else // Else make sure selection is multiple of 2 pCmdUI->Enable((end_addr - start_addr)%2 == 0); } void CHexEditView::OnUpdate32bit(CCmdUI* pCmdUI) { // pCmdUI->Enable(GetPos() + 3 < GetDocument()->length()); FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) // No selection so only enable if enough before EOF (4 bytes) pCmdUI->Enable(start_addr + 3 < GetDocument()->length()); else // Else make sure selection is multiple of 4 pCmdUI->Enable((end_addr - start_addr)%4 == 0); } void CHexEditView::OnUpdate64bit(CCmdUI* pCmdUI) { // pCmdUI->Enable(GetPos() + 7 < GetDocument()->length()); FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) // No selection so only enable if enough before EOF (8 bytes) pCmdUI->Enable(start_addr + 7 < GetDocument()->length()); else // Else make sure selection is multiple of 8 pCmdUI->Enable((end_addr - start_addr)%8 == 0); } // These update handlers are similar to the above but for binary operations // As binary operations use the current value from the calculator we also need // to ensure that the current operand size in the calculator is not too big. void CHexEditView::OnUpdateByteBinary(CCmdUI* pCmdUI) { if (((CMainFrame *)AfxGetMainWnd())->m_wndCalc.ByteSize() > 1) { pCmdUI->Enable(FALSE); return; } OnUpdateByte(pCmdUI); } void CHexEditView::OnUpdate16bitBinary(CCmdUI* pCmdUI) { if (((CMainFrame *)AfxGetMainWnd())->m_wndCalc.ByteSize() > 2) { pCmdUI->Enable(FALSE); return; } OnUpdate16bit(pCmdUI); } void CHexEditView::OnUpdate32bitBinary(CCmdUI* pCmdUI) { if (((CMainFrame *)AfxGetMainWnd())->m_wndCalc.ByteSize() > 4) { pCmdUI->Enable(FALSE); return; } OnUpdate32bit(pCmdUI); } void CHexEditView::OnUpdate64bitBinary(CCmdUI* pCmdUI) { if (((CMainFrame *)AfxGetMainWnd())->m_wndCalc.ByteSize() > 8) { ASSERT(0); // Max size is 8 at present pCmdUI->Enable(FALSE); return; } OnUpdate64bit(pCmdUI); } template<class T> void DoChecksum(CHexEditView *pv, checksum_type op, LPCSTR desc) { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection pv->GetSelAddr(start_addr, end_addr); if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(theApp.playing_); CString mess; mess.Format("There is no selection to calculate %s on", desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } if (op >= CHECKSUM_8 && op < 10 && (end_addr - start_addr)%sizeof(T) != 0) { // Selection is wrong length, presumably in macro playback ASSERT(theApp.playing_); CString mess; mess.Format("The selection must be a multiple of %d for %s", sizeof(T), desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } ASSERT(start_addr < pv->GetDocument()->length()); // Get a buffer - fairly large for efficiency size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } ASSERT(buf != NULL); T val; void * hh; switch (op) { case CHECKSUM_CRC16: hh = crc_16_init(); break; case CHECKSUM_CRC_CCITT: hh = crc_ccitt_init(); break; case CHECKSUM_CRC_CCITT_B: hh = crc_ccitt_b_init(); break; case CHECKSUM_CRC_XMODEM: hh = crc_xmodem_init(); break; case CHECKSUM_CRC32: hh = crc_32_init(); break; case CHECKSUM_8: case CHECKSUM_16: case CHECKSUM_32: case CHECKSUM_64: val = 0; break; default: ASSERT(0); } for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); VERIFY(pv->GetDocument()->GetData(buf, len, curr) == len); switch (op) { case CHECKSUM_8: case CHECKSUM_16: case CHECKSUM_32: case CHECKSUM_64: ASSERT(len % sizeof(T) == 0); { T *pp, *endp = (T *)(buf + len); for (pp = (T *)buf; pp < endp; ++pp) val += *pp; } break; case CHECKSUM_CRC16: crc_16_update(hh, buf, len); break; case CHECKSUM_CRC_CCITT: crc_ccitt_update(hh, buf, len); break; case CHECKSUM_CRC_CCITT_B: crc_ccitt_b_update(hh, buf, len); break; case CHECKSUM_CRC_XMODEM: crc_xmodem_update(hh, buf, len); break; case CHECKSUM_CRC32: crc_32_update(hh, buf, len); break; } if (AbortKeyPress() && AfxMessageBox("Abort calculation?", MB_YESNO) == IDYES) { theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } switch (op) { case CHECKSUM_CRC16: val = T(crc_16_final(hh)); break; case CHECKSUM_CRC_CCITT: val = T(crc_ccitt_final(hh)); break; case CHECKSUM_CRC_CCITT_B: val = T(crc_ccitt_b_final(hh)); break; case CHECKSUM_CRC_XMODEM: val = T(crc_xmodem_final(hh)); break; case CHECKSUM_CRC32: val = T(crc_32_final(hh)); break; } // Get final CRC and store it in the calculator if (((CMainFrame *)AfxGetMainWnd())->m_wndCalc.ByteSize() < sizeof(T)) ((CMainFrame *)AfxGetMainWnd())->m_wndCalc.change_bits(sizeof(T)*8); ((CMainFrame *)AfxGetMainWnd())->m_wndCalc.Set(val); dynamic_cast<CMainFrame *>(::AfxGetMainWnd())->show_calc(); // make sure calc is displayed theApp.SaveToMacro(km_checksum, op); func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnChecksum8() { DoChecksum<unsigned char>(this, CHECKSUM_8, "8 bit Checksum"); } void CHexEditView::OnChecksum16() { DoChecksum<unsigned short>(this, CHECKSUM_16, "16 bit Checksum"); } void CHexEditView::OnChecksum32() { DoChecksum<unsigned long>(this, CHECKSUM_32, "32 bit Checksum"); } void CHexEditView::OnChecksum64() { DoChecksum<unsigned __int64>(this, CHECKSUM_64, "64 bit Checksum"); } void CHexEditView::OnCrc16() { DoChecksum<unsigned short>(this, CHECKSUM_CRC16, "CRC 16"); } void CHexEditView::OnCrcCcitt() { DoChecksum<unsigned short>(this, CHECKSUM_CRC_CCITT, "CRC CCITT"); } void CHexEditView::OnCrcCcittB() { DoChecksum<unsigned short>(this, CHECKSUM_CRC_CCITT_B, "CRC CCITT B"); } void CHexEditView::OnCrcXmodem() { DoChecksum<unsigned short>(this, CHECKSUM_CRC_XMODEM, "CRC XMODEM"); } void CHexEditView::OnCrc32() { DoChecksum<DWORD>(this, CHECKSUM_CRC32, "CRC 32"); } void CHexEditView::OnMd5() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("There is no selection to calculate MD5 on"); theApp.mac_error_ = 10; return; } ASSERT(start_addr < GetDocument()->length()); // Get a buffer - fairly large for efficiency size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } ASSERT(buf != NULL); struct MD5Context ctx; MD5Init(&ctx); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); MD5Update(&ctx, buf, len); if (AbortKeyPress() && AfxMessageBox("Abort MD5 calculation?", MB_YESNO) == IDYES) { theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } unsigned char digest[16]; MD5Final(digest, &ctx); { // Display MD5 value (when calculator can handle 128 bits we will put it there instead) CString ss, fmt; if (theApp.hex_ucase_) fmt = "MD5: %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X"; else fmt = "MD5: %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x"; ss.Format(fmt, digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]); AfxMessageBox(ss); } // Record in macro since we did it successfully theApp.SaveToMacro(km_checksum, CHECKSUM_MD5); func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnSha1() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("There is no selection to calculate SHA1 on"); theApp.mac_error_ = 10; return; } ASSERT(start_addr < GetDocument()->length()); // Get a buffer - fairly large for efficiency size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } ASSERT(buf != NULL); sha1_context ctx; sha1_starts(&ctx); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); sha1_update(&ctx, buf, len); if (AbortKeyPress() && AfxMessageBox("Abort SHA1 calculation?", MB_YESNO) == IDYES) { theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } unsigned char digest[20]; sha1_finish(&ctx, digest); { // Display SHA1 value (when calculator can handle 128 bits we will put it there instead) CString ss, fmt; if (theApp.hex_ucase_) fmt = "SHA1: %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X"; else fmt = "SHA1: %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x"; ss.Format(fmt, digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15], digest[16], digest[17], digest[18], digest[19]); AfxMessageBox(ss); } // Record in macro since we did it successfully theApp.SaveToMacro(km_checksum, CHECKSUM_SHA1); func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnUpdateByteNZ(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start_addr < end_addr ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else // ??? is start_addr < end_addr then pos must be less than EOF ??? pCmdUI->Enable(start_addr < end_addr && GetPos() < GetDocument()->length()); } void CHexEditView::OnUpdate16bitNZ(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start_addr < end_addr ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(end_addr > start_addr && (end_addr - start_addr)%2 == 0); } void CHexEditView::OnUpdate32bitNZ(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start_addr < end_addr ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(end_addr > start_addr && (end_addr - start_addr)%4 == 0); } void CHexEditView::OnUpdate64bitNZ(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start_addr < end_addr ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(end_addr > start_addr && (end_addr - start_addr)%8 == 0); } template<class T> void ProcBinary(CHexEditView *pv, T val, T *buf, size_t count, binop_type op, int &div0) { for (size_t ii = 0; ii < count; ++ii) { // Reverse byte order if using big-endian if (pv->BigEndian()) ::flip_bytes((unsigned char *)&buf[ii], sizeof(T)); switch (op) { case binop_add: buf[ii] += val; break; case binop_subtract: buf[ii] -= val; break; case binop_subtract_x: buf[ii] = val - buf[ii]; break; case binop_multiply: buf[ii] *= val; break; case binop_divide: ASSERT(val != 0); buf[ii] /= val; break; case binop_divide_x: if (buf[ii] != 0) buf[ii] = val / buf[ii]; else ++div0; break; case binop_mod: ASSERT(val != 0); buf[ii] %= val; break; case binop_mod_x: if (buf[ii] != 0) buf[ii] = val % buf[ii]; else ++div0; break; case binop_and: buf[ii] &= val; break; case binop_or: buf[ii] |= val; break; case binop_xor: buf[ii] ^= val; break; // Signed/unsigned comparisons are differentiated by type of T passed to the template function case binop_gtr: case binop_gtr_unsigned: if (val > buf[ii]) buf[ii] = val; break; case binop_less: case binop_less_unsigned: if (val < buf[ii]) buf[ii] = val; break; case binop_rol: // T must be unsigned type for zero fill in >> { int tmp = int(val) % (sizeof(T)*8); buf[ii] = (buf[ii] << tmp) | (buf[ii] >> (sizeof(T)*8 - tmp)); } break; case binop_ror: // T must be unsigned type for zero fill in >> { int tmp = int(val) % (sizeof(T)*8); buf[ii] = (buf[ii] >> tmp) | (buf[ii] << (sizeof(T)*8 - tmp)); } break; case binop_lsl: buf[ii] <<= int(val); break; case binop_lsr: // T must be unsigned type for zero fill case binop_asr: // T must be signed type for sign to be extended buf[ii] >>= int(val); break; default: ASSERT(0); } // Reverse byte order back again before putting back to the file if (pv->BigEndian()) ::flip_bytes((unsigned char *)&buf[ii], sizeof(T)); } } // Perform binary operations (where the 2nd operand is taken from the calculator). // [This is used to replace numerous other functions (OnAddByte, OnXor64Bit etc).] // T = template parameter specifying size of operand (1,2,4 or 8 byte integer) // pv = pointer to the view (we had to do this as VC6 does not support member templates) // op = operation to perform // desc = describes the operations and operand size for use in error messages // dummy = determines template operand type (should not be nec. except for VC6 template bugs) template<class T> void OnOperateBinary(CHexEditView *pv, binop_type op, LPCSTR desc, T dummy) { (void)dummy; // The dummy param. makes sure we get the right template (VC++ 6 bug) CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; ASSERT(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8); if (pv->check_ro(desc)) return; if (mm->m_wndCalc.ByteSize() > sizeof(T)) { ASSERT(theApp.playing_); // This should only happen during playback since commands are disabled otherwise CString mess; mess.Format("Can't %s unless operand (calculator) is %d bytes or less", desc, sizeof(T)); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } // Get current address of selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection pv->GetSelAddr(start_addr, end_addr); // If no selection just do one if (start_addr >= end_addr) { end_addr = start_addr + sizeof(T); if (end_addr > pv->GetDocument()->length()) { // Not enough bytes before EOF, presumably in macro playback ASSERT(theApp.playing_); CString mess; mess.Format("Insufficient bytes before EOF to %s", desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } } // Make sure selection is a multiple of the data type length if ((end_addr - start_addr) % sizeof(T) != 0) { ASSERT(theApp.playing_); CString mess; mess.Format("Selection must be a multiple of %d bytes to %s", sizeof(T), desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } ASSERT(start_addr < end_addr && end_addr <= pv->GetDocument()->length()); // Get the other operand from the calculator T val = T(mm->m_wndCalc.GetValue()); // Check for calculator val of zero causing divide by zero if (val == 0 && (op == binop_divide || op == binop_mod)) { CString mess; mess.Format("Calculator value is zero (causing divide by 0) while performing %s", desc); AfxMessageBox(mess); theApp.mac_error_ = 5; return; } int div0 = 0; // Count of divide by zero errors (for binop_divide_x and binop_mod_x) // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && pv->GetDocument()->DataFileSlotFree()) { int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) // Create a file to store the resultant data // (Temp file used by the document until it is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); // Get data buffer size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); VERIFY(pv->GetDocument()->GetData(buf, len, curr) == len); ProcBinary(pv, val, (T *)buf, len/sizeof(T), op, div0); ff.Write(buf, len); if (AbortKeyPress()) { CString mess; mess.Format("Abort %s operation?", desc); if (AfxMessageBox(mess, MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the unprocessed block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. pv->GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, pv); // Add the temp file to the document idx = pv->GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); pv->GetDocument()->Change(mod_insert_file, start_addr, end_addr - start_addr, NULL, idx, pv, TRUE); } else { // Allocate memory block and process it // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot operate on such a large selection. \n" "Please save the file to deallocate \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and operating on such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) try { buf = new unsigned char[size_t(end_addr - start_addr)]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } size_t got = pv->GetDocument()->GetData(buf, size_t(end_addr - start_addr), start_addr); ASSERT(got == size_t(end_addr - start_addr)); ProcBinary(pv, val, (T *)buf, got/sizeof(T), op, div0); pv->GetDocument()->Change(mod_replace, start_addr, got, (unsigned char *)buf, 0, pv); } if (div0 > 0) { // Tell the user about divide by zero errors CString mess; mess.Format("There were %d divide by zero errors while performing %s", int(div0), desc); AfxMessageBox(mess); theApp.mac_error_ = 5; } pv->DisplayCaret(); { static int bit_pos[8] = {0, 1, -1, 2, -1, -1, -1, 3}; ASSERT(sizeof(T)-1 < 8 && bit_pos[sizeof(T)-1] != -1); // size must be 1,2,4,8 giving bit_pos of 0,1,2,3 theApp.SaveToMacro(km_op_binary, (op<<8)|bit_pos[sizeof(T)-1]); } func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnAddByte() { ::OnOperateBinary<char>(this, binop_add, "Add bytes", char(0)); } void CHexEditView::OnAdd16bit() { ::OnOperateBinary<short>(this, binop_add, "Add words", short(0)); } void CHexEditView::OnAdd32bit() { ::OnOperateBinary<long>(this, binop_add, "Add double words", long(0)); } void CHexEditView::OnAdd64bit() { ::OnOperateBinary<__int64>(this, binop_add, "Add quad words", __int64(0)); } void CHexEditView::OnSubtractByte() { ::OnOperateBinary<char>(this, binop_subtract, "Subtract bytes", char(0)); } void CHexEditView::OnSubtract16bit() { ::OnOperateBinary<short>(this, binop_subtract, "Subtract words", short(0)); } void CHexEditView::OnSubtract32bit() { ::OnOperateBinary<long>(this, binop_subtract, "Subtract double words", long(0)); } void CHexEditView::OnSubtract64bit() { ::OnOperateBinary<__int64>(this, binop_subtract, "Subtract quad words", __int64(0)); } void CHexEditView::OnAndByte() { ::OnOperateBinary<char>(this, binop_and, "AND bytes", char(0)); } void CHexEditView::OnAnd16bit() { ::OnOperateBinary<short>(this, binop_and, "AND words", short(0)); } void CHexEditView::OnAnd32bit() { ::OnOperateBinary<long>(this, binop_and, "AND double words", long(0)); } void CHexEditView::OnAnd64bit() { ::OnOperateBinary<__int64>(this, binop_and, "AND quad words", __int64(0)); } void CHexEditView::OnOrByte() { ::OnOperateBinary<char>(this, binop_or, "OR bytes", char(0)); } void CHexEditView::OnOr16bit() { ::OnOperateBinary<short>(this, binop_or, "OR words", short(0)); } void CHexEditView::OnOr32bit() { ::OnOperateBinary<long>(this, binop_or, "OR double words", long(0)); } void CHexEditView::OnOr64bit() { ::OnOperateBinary<__int64>(this, binop_or, "OR quad words", __int64(0)); } void CHexEditView::OnXorByte() { ::OnOperateBinary<char>(this, binop_xor, "XOR bytes", char(0)); } void CHexEditView::OnXor16bit() { ::OnOperateBinary<short>(this, binop_xor, "XOR words", short(0)); } void CHexEditView::OnXor32bit() { ::OnOperateBinary<long>(this, binop_xor, "XOR double words", long(0)); } void CHexEditView::OnXor64bit() { ::OnOperateBinary<__int64>(this, binop_xor, "XOR quad words", __int64(0)); } void CHexEditView::OnMulByte() { ::OnOperateBinary<unsigned char>(this, binop_multiply, "multiply bytes", unsigned char(0)); } void CHexEditView::OnMul16bit() { ::OnOperateBinary<unsigned short>(this, binop_multiply, "multiply words", unsigned short(0)); } void CHexEditView::OnMul32bit() { ::OnOperateBinary<unsigned long>(this, binop_multiply, "multiply double words", unsigned long(0)); } void CHexEditView::OnMul64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_multiply, "multiply quad words", unsigned __int64(0)); } void CHexEditView::OnDivByte() { ::OnOperateBinary<unsigned char>(this, binop_divide, "divide bytes", unsigned char(0)); } void CHexEditView::OnDiv16bit() { ::OnOperateBinary<unsigned short>(this, binop_divide, "divide words", unsigned short(0)); } void CHexEditView::OnDiv32bit() { ::OnOperateBinary<unsigned long>(this, binop_divide, "divide double words", unsigned long(0)); } void CHexEditView::OnDiv64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_divide, "divide quad words", unsigned __int64(0)); } void CHexEditView::OnModByte() { ::OnOperateBinary<unsigned char>(this, binop_mod, "modulus bytes", unsigned char(0)); } void CHexEditView::OnMod16bit() { ::OnOperateBinary<unsigned short>(this, binop_mod, "modulus words", unsigned short(0)); } void CHexEditView::OnMod32bit() { ::OnOperateBinary<unsigned long>(this, binop_mod, "modulus double words", unsigned long(0)); } void CHexEditView::OnMod64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_mod, "modulus quad words", unsigned __int64(0)); } void CHexEditView::OnSubtractXByte() { ::OnOperateBinary<char>(this, binop_subtract_x, "Subtract bytes", char(0)); } void CHexEditView::OnSubtractX16bit() { ::OnOperateBinary<short>(this, binop_subtract_x, "Subtract words", short(0)); } void CHexEditView::OnSubtractX32bit() { ::OnOperateBinary<long>(this, binop_subtract_x, "Subtract double words", long(0)); } void CHexEditView::OnSubtractX64bit() { ::OnOperateBinary<__int64>(this, binop_subtract_x, "Subtract quad words", __int64(0)); } void CHexEditView::OnDivXByte() { ::OnOperateBinary<unsigned char>(this, binop_divide_x, "divide bytes", unsigned char(0)); } void CHexEditView::OnDivX16bit() { ::OnOperateBinary<unsigned short>(this, binop_divide_x, "divide words", unsigned short(0)); } void CHexEditView::OnDivX32bit() { ::OnOperateBinary<unsigned long>(this, binop_divide_x, "divide double words", unsigned long(0)); } void CHexEditView::OnDivX64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_divide_x, "divide quad words", unsigned __int64(0)); } void CHexEditView::OnModXByte() { ::OnOperateBinary<unsigned char>(this, binop_mod_x, "modulus bytes", unsigned char(0)); } void CHexEditView::OnModX16bit() { ::OnOperateBinary<unsigned short>(this, binop_mod_x, "modulus words", unsigned short(0)); } void CHexEditView::OnModX32bit() { ::OnOperateBinary<unsigned long>(this, binop_mod_x, "modulus double words", unsigned long(0)); } void CHexEditView::OnModX64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_mod_x, "modulus quad words", unsigned __int64(0)); } void CHexEditView::OnGtrByte() { ::OnOperateBinary<signed char>(this, binop_gtr, "finding greater of bytes", signed char(0)); } void CHexEditView::OnGtr16bit() { ::OnOperateBinary<short>(this, binop_gtr, "finding greater of words", short(0)); } void CHexEditView::OnGtr32bit() { ::OnOperateBinary<long>(this, binop_gtr, "finding greater of double words", long(0)); } void CHexEditView::OnGtr64bit() { ::OnOperateBinary<__int64>(this, binop_gtr, "finding greater of quad words", __int64(0)); } void CHexEditView::OnLessByte() { ::OnOperateBinary<signed char>(this, binop_less, "finding lesser of bytes", signed char(0)); } void CHexEditView::OnLess16bit() { ::OnOperateBinary<short>(this, binop_less, "finding lesser of words", short(0)); } void CHexEditView::OnLess32bit() { ::OnOperateBinary<long>(this, binop_less, "finding lesser of double words", long(0)); } void CHexEditView::OnLess64bit() { ::OnOperateBinary<__int64>(this, binop_less, "finding lesser of quad words", __int64(0)); } void CHexEditView::OnGtrUByte() { ::OnOperateBinary<unsigned char>(this, binop_gtr_unsigned, "finding unsigned greater of bytes", unsigned char(0)); } void CHexEditView::OnGtrU16bit() { ::OnOperateBinary<unsigned short>(this, binop_gtr_unsigned, "finding unsigned greater of words", unsigned short(0)); } void CHexEditView::OnGtrU32bit() { ::OnOperateBinary<unsigned long>(this, binop_gtr_unsigned, "finding unsigned greater of double words", unsigned long(0)); } void CHexEditView::OnGtrU64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_gtr_unsigned, "finding unsigned greater of quad words", unsigned __int64(0)); } void CHexEditView::OnLessUByte() { ::OnOperateBinary<unsigned char>(this, binop_less_unsigned, "finding unsigned lesser of bytes", unsigned char(0)); } void CHexEditView::OnLessU16bit() { ::OnOperateBinary<unsigned short>(this, binop_less_unsigned, "finding unsigned lesser of words", unsigned short(0)); } void CHexEditView::OnLessU32bit() { ::OnOperateBinary<unsigned long>(this, binop_less_unsigned, "finding unsigned lesser of double words", unsigned long(0)); } void CHexEditView::OnLessU64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_less_unsigned, "finding unsigned lesser of quad words", unsigned __int64(0)); } void CHexEditView::OnRolByte() { ::OnOperateBinary<unsigned char>(this, binop_rol, "rotate left bytes", unsigned char(0)); } void CHexEditView::OnRol16bit() { ::OnOperateBinary<unsigned short>(this, binop_rol, "rotate left words", unsigned short(0)); } void CHexEditView::OnRol32bit() { ::OnOperateBinary<unsigned long>(this, binop_rol, "rotate left double words", unsigned long(0)); } void CHexEditView::OnRol64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_rol, "rotate left quad words", unsigned __int64(0)); } void CHexEditView::OnRorByte() { ::OnOperateBinary<unsigned char>(this, binop_ror, "rotate right bytes", unsigned char(0)); } void CHexEditView::OnRor16bit() { ::OnOperateBinary<unsigned short>(this, binop_ror, "rotate right words", unsigned short(0)); } void CHexEditView::OnRor32bit() { ::OnOperateBinary<unsigned long>(this, binop_ror, "rotate right double words", unsigned long(0)); } void CHexEditView::OnRor64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_ror, "rotate right quad words", unsigned __int64(0)); } void CHexEditView::OnLslByte() { ::OnOperateBinary<char>(this, binop_lsl, "shift left bytes", char(0)); } void CHexEditView::OnLsl16bit() { ::OnOperateBinary<short>(this, binop_lsl, "shift left words", short(0)); } void CHexEditView::OnLsl32bit() { ::OnOperateBinary<long>(this, binop_lsl, "shift left double words", long(0)); } void CHexEditView::OnLsl64bit() { ::OnOperateBinary<__int64>(this, binop_lsl, "shift left quad words", __int64(0)); } void CHexEditView::OnLsrByte() { ::OnOperateBinary<unsigned char>(this, binop_lsr, "shift right bytes", unsigned char(0)); } void CHexEditView::OnLsr16bit() { ::OnOperateBinary<unsigned short>(this, binop_lsr, "shift right words", unsigned short(0)); } void CHexEditView::OnLsr32bit() { ::OnOperateBinary<unsigned long>(this, binop_lsr, "shift right double words", unsigned long(0)); } void CHexEditView::OnLsr64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_lsr, "shift right quad words", unsigned __int64(0)); } void CHexEditView::OnAsrByte() { ::OnOperateBinary<signed char>(this, binop_asr, "arithmetic shift right bytes", signed char(0)); } void CHexEditView::OnAsr16bit() { ::OnOperateBinary<short>(this, binop_asr, "arithmetic shift right words", short(0)); } void CHexEditView::OnAsr32bit() { ::OnOperateBinary<long>(this, binop_asr, "arithmetic shift right double words", long(0)); } void CHexEditView::OnAsr64bit() { ::OnOperateBinary<__int64>(this, binop_asr, "arithmetic shift right quad words", __int64(0)); } template<class T> void ProcUnary(CHexEditView *pv, T val, T *buf, size_t count, unary_type op) { // Operate on all the selected values for (size_t ii = 0; ii < count; ++ii) { // Reverse if big endian and the operation calls for it. if (pv->BigEndian() && op != unary_flip) ::flip_bytes((unsigned char *)&buf[ii], sizeof(T)); switch (op) { case unary_at: buf[ii] = val; break; case unary_sign: buf[ii] = -buf[ii]; break; case unary_inc: ++buf[ii]; if (buf[ii] == 0) { ((CMainFrame *)AfxGetMainWnd())->StatusBarText("Warning: Increment wrapped around to zero"); theApp.mac_error_ = 1; // Signal warning on wrap } break; case unary_dec: buf[ii]--; if (buf[ii] == -1) { ((CMainFrame *)AfxGetMainWnd())->StatusBarText("Warning: Decrement wrapped past zero"); theApp.mac_error_ = 1; // Signal warning on wrap } break; case unary_not: ASSERT(sizeof(T) == 1); // Only need to perform NOT on bytes buf[ii] = ~buf[ii]; break; case unary_flip: ASSERT(sizeof(T) > 1); // No point in flipping a single byte // Do nothing here (let ::flip_bytes below handle it) break; case unary_rev: { T result = 0; T tmp = buf[ii]; for (int jj = 0; jj < sizeof(T)*8; ++jj) { result <<= 1; // Make room for the next bit if (tmp & 0x1) result |= 0x1; tmp >>= 1; // Move bits down to test the next } buf[ii] = result; } break; case unary_rand: ASSERT(sizeof(T) == 1); // Only really need random bytes buf[ii] = T(::rand_good()>>16); break; case unary_rand_fast: ASSERT(sizeof(T) == 1); // Only really need random bytes buf[ii] = T(::rand()>>7); break; default: ASSERT(0); } if (pv->BigEndian() || op == unary_flip) ::flip_bytes((unsigned char *)&buf[ii], sizeof(T)); } } // Perform unary operations on the selection // [This is used to replace numerous other functions (OnIncByte, OnFlip64Bit etc).] // T = template parameter specifying size of operand (1,2,4 or 8 byte integer) // op = operation to perform // desc = describes the operations and operand size for use in error messages template<class T> void OnOperateUnary(CHexEditView *pv, unary_type op, LPCSTR desc, T dummy) { (void)dummy; // The dummy param. makes sure we get the right template (VC++ 6 bug) CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; ASSERT(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8); if (pv->check_ro(desc)) return; T val = 0; // For assign operation we get the value from calc if (op == unary_at) { val = T(mm->m_wndCalc.GetValue()); // prefetch the value // Make sure the operand is not too big if (mm->m_wndCalc.ByteSize() > sizeof(T)) { ASSERT(theApp.playing_); // This should only happen during playback since commands are disabled otherwise CString mess; mess.Format("Can't %s unless operand (calculator) is %d bytes or less", desc, sizeof(T)); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } } // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection pv->GetSelAddr(start_addr, end_addr); // If no selection just do one if (start_addr >= end_addr) { end_addr = start_addr + sizeof(T); if (end_addr > pv->GetDocument()->length()) { // Not enough bytes before EOF, presumably in macro playback ASSERT(theApp.playing_); CString mess; mess.Format("Insufficient bytes before EOF to %s", desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } } // Make sure selection is a multiple of the data type length if ((end_addr - start_addr) % sizeof(T) != 0) { ASSERT(theApp.playing_); CString mess; mess.Format("Selection must be a multiple of %d bytes to %s", sizeof(T), desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } ASSERT(start_addr < end_addr && end_addr <= pv->GetDocument()->length()); // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && pv->GetDocument()->DataFileSlotFree()) { int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) // Create a file to store the resultant data // (Temp file used by the document until it is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); // Get data buffer size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); if (op != unary_at) // We don't need to get old value if assigning VERIFY(pv->GetDocument()->GetData(buf, len, curr) == len); ProcUnary(pv, val, (T *)buf, len/sizeof(T), op); ff.Write(buf, len); if (AbortKeyPress()) { CString mess; mess.Format("Abort %s operation?", desc); if (AfxMessageBox(mess, MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the unprocessed block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. pv->GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, pv); // Add the temp file to the document idx = pv->GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); pv->GetDocument()->Change(mod_insert_file, start_addr, end_addr - start_addr, NULL, idx, pv, TRUE); } else { // Allocate memory block and process it // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot operate on such a large selection. \n" "Please save the file to deallocate \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and operating on such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) try { buf = new unsigned char[size_t(end_addr - start_addr)]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } size_t got; if (op != unary_at) // We don't need to get old value if assigning { got = pv->GetDocument()->GetData(buf, size_t(end_addr - start_addr), start_addr); ASSERT(got == size_t(end_addr - start_addr)); } else got = size_t(end_addr - start_addr); ProcUnary(pv, val, (T *)buf, got/sizeof(T), op); pv->GetDocument()->Change(mod_replace, start_addr, got, (unsigned char *)buf, 0, pv); } pv->DisplayCaret(); { static int bit_pos[8] = {0, 1, -1, 2, -1, -1, -1, 3}; ASSERT(sizeof(T)-1 < 8 && bit_pos[sizeof(T)-1] != -1); // size must be 1,2,4,8 giving bit_pos of 0,1,2,3 theApp.SaveToMacro(km_op_unary, (op<<8)|bit_pos[sizeof(T)-1]); } func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnIncByte() { ::OnOperateUnary<char>(this, unary_inc, "increment bytes", char(0)); } void CHexEditView::OnInc16bit() { ::OnOperateUnary<short>(this, unary_inc, "increment words", short(0)); } void CHexEditView::OnInc32bit() { ::OnOperateUnary<long>(this, unary_inc, "increment double words", long(0)); } void CHexEditView::OnInc64bit() { ::OnOperateUnary<__int64>(this, unary_inc, "increment quad words", __int64(0)); } void CHexEditView::OnDecByte() { ::OnOperateUnary<char>(this, unary_dec, "decrement bytes", char(0)); } void CHexEditView::OnDec16bit() { ::OnOperateUnary<short>(this, unary_dec, "decrement words", short(0)); } void CHexEditView::OnDec32bit() { ::OnOperateUnary<long>(this, unary_dec, "decrement double words", long(0)); } void CHexEditView::OnDec64bit() { ::OnOperateUnary<__int64>(this, unary_dec, "decrement quad words", __int64(0)); } void CHexEditView::OnRevByte() { ::OnOperateUnary<char>(this, unary_rev, "reverse bits of bytes", char(0)); } void CHexEditView::OnRev16bit() { ::OnOperateUnary<short>(this, unary_rev, "reverse bits of words", short(0)); } void CHexEditView::OnRev32bit() { ::OnOperateUnary<long>(this, unary_rev, "reverse bits of double words", long(0)); } void CHexEditView::OnRev64bit() { ::OnOperateUnary<__int64>(this, unary_rev, "reverse bits of quad words", __int64(0)); } // There is NO OnFlipByte (since it would not do anything) void CHexEditView::OnFlip16bit() { ::OnOperateUnary<short>(this, unary_flip, "flip bytes of words", short(0)); } void CHexEditView::OnFlip32bit() { ::OnOperateUnary<long>(this, unary_flip, "flip bytes of double words", long(0)); } void CHexEditView::OnFlip64bit() { ::OnOperateUnary<__int64>(this, unary_flip, "flip bytes of quad words", __int64(0)); } void CHexEditView::OnInvert() { ::OnOperateUnary<char>(this, unary_not, "invert bits", char(0)); } void CHexEditView::OnNegByte() { ::OnOperateUnary<signed char>(this, unary_sign, "negate bytes", signed char(0)); } void CHexEditView::OnNeg16bit() { ::OnOperateUnary<short>(this, unary_sign, "negate words", short(0)); } void CHexEditView::OnNeg32bit() { ::OnOperateUnary<long>(this, unary_sign, "negate double words", long(0)); } void CHexEditView::OnNeg64bit() { ::OnOperateUnary<__int64>(this, unary_sign, "negate quad words", __int64(0)); } void CHexEditView::OnAssignByte() { ::OnOperateUnary<char>(this, unary_at, "assign bytes", char(0)); } void CHexEditView::OnAssign16bit() { ::OnOperateUnary<short>(this, unary_at, "assign words", short(0)); } void CHexEditView::OnAssign32bit() { ::OnOperateUnary<long>(this, unary_at, "assign double words", long(0)); } void CHexEditView::OnAssign64bit() { ::OnOperateUnary<__int64>(this, unary_at, "assign quad words", __int64(0)); } void CHexEditView::OnSeedCalc() { unsigned long seed = unsigned long(((CMainFrame *)AfxGetMainWnd())->m_wndCalc.GetValue()); srand(seed); // Seed compiler PRNG (simple one) rand_good_seed(seed); // Seed our own PRNG theApp.SaveToMacro(km_seed, 1); } void CHexEditView::OnSeedRandom() { unsigned long seed = ::GetTickCount(); srand(seed); // Seed compiler PRNG (simple fast one) rand_good_seed(seed); // Seed our own PRNG theApp.SaveToMacro(km_seed); } void CHexEditView::OnRandByte() { ::OnOperateUnary<char>(this, unary_rand, "randomize bytes", char(0)); } void CHexEditView::OnRandFast() { ::OnOperateUnary<char>(this, unary_rand_fast, "fast randomize bytes", char(0)); } // The display of views in tabs and split windows is complicated, mainly because the BCG tab view class // behaves very differently from a splitter (eg is derived from CView). // Currently we need to show 3 types of views: CHexEditView (normal hex view), CDataFormatView (template), // and CAerialView (bitmap overview). There is also a CHexTabView that just contains one or more other views. // * The child frame has a splitter called "splitter_" // - there is always at least one pane so at least one view // - if there is only one pane then it contains the tab view // * One of the splits is always a tab view called "ptv_" in the child frame // - if the window has not been split this is the only view // - this may be the 2nd split (since the first one can be template view) // * The tab view always contains the hex view but may also have tabs for the other views // - the left most tab is always the hex view // - the tabs are not shown if there is just one view (the hex view) // * The template and aerial views are either not shown, in a pane of the splitter or in a tab view // // In the code below we often store the index of a view in the splitter or in the tab view using this convention: // snum_t = index of tab view in the splitter (currently only 0 or 1) // snum_d = index of DFFD (template) view in the left splitter (currently only 0 or -1) // snum_a = index of aerial view in the right splitter (currently only 1, 2 or -1) // tnum_d = index of DFFD (template) view in the tab view (currently -1, 1 or 2) // tnum_a = index of aerial view in the tab view (currently -1, 1 or 2) // where -1 indicates the view is not present // Note tnum_h is not required as the hex view is always the left (0) view in the tab view void CHexEditView::ShowDffd() { if (pdfv_ == NULL) OnDffdSplit(); } void CHexEditView::OnDffdHide() { if (pdfv_ == NULL) return; // already hidden int snum_d = GetFrame()->splitter_.FindViewColumn(pdfv_->GetSafeHwnd()); int tnum_d = GetFrame()->ptv_->FindTab(pdfv_->GetSafeHwnd()); ASSERT(snum_d > -1 || tnum_d > -1); // It must be open in tab or splitter pdfv_ = NULL; if (snum_d > -1) // splitter? { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_d, split_width_d_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_d, TRUE)); GetFrame()->splitter_.RecalcLayout(); } else if (tnum_d > -1) // tab? { GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing tree view VERIFY(GetFrame()->ptv_->RemoveView(tnum_d)); } } void CHexEditView::OnUpdateDffdHide(CCmdUI* pCmdUI) { //pCmdUI->Enable(TRUE); pCmdUI->SetCheck(TemplateViewType() == 0); } void CHexEditView::OnDffdSplit() { if (DoDffdSplit()) pdfv_->SendMessage(WM_INITIALUPDATE); } bool CHexEditView::DoDffdSplit() { //if (pdfv_ == GetFrame()->splitter_.GetPane(0, 0)) if (TemplateViewType() == 1) return false; // already open in splitter // If open then it is open in a tab - close it if (pdfv_ != NULL) { int tnum_d = GetFrame()->ptv_->FindTab(pdfv_->GetSafeHwnd()); ASSERT(tnum_d > -1); pdfv_ = NULL; GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing tree view if (tnum_d > -1) VERIFY(GetFrame()->ptv_->RemoveView(tnum_d)); } // Reopen in the splitter CCreateContext ctxt; ctxt.m_pNewViewClass = RUNTIME_CLASS(CDataFormatView); ctxt.m_pCurrentDoc = GetDocument(); ctxt.m_pLastView = this; ctxt.m_pCurrentFrame = GetFrame(); CHexEditSplitter *psplitter = &(GetFrame()->splitter_); ASSERT(psplitter->m_hWnd != 0); // Make sure width of splitter window is OK CRect rr; GetFrame()->GetClientRect(&rr); if (split_width_d_ < 10 || split_width_d_ > rr.Width()) { split_width_d_ = rr.Width()/3; if (split_width_d_ < 10) split_width_d_ = 10; } // Add tree view in left splitter column VERIFY(psplitter->InsColumn(0, split_width_d_, 10, RUNTIME_CLASS(CDataFormatView), &ctxt)); psplitter->SetActivePane(0, 1); // make hex (tab) view active = now in col 1 pdfv_ = (CDataFormatView *)psplitter->GetPane(0, 0); ASSERT_KINDOF(CDataFormatView, pdfv_); // Make sure dataformat view knows which hex view it is assoc. with pdfv_->phev_ = this; psplitter->RecalcLayout(); AdjustColumns(); return true; } void CHexEditView::OnUpdateDffdSplit(CCmdUI* pCmdUI) { pCmdUI->SetCheck(TemplateViewType() == 1); pCmdUI->Enable(GetDocument()->ptree_ != NULL); } void CHexEditView::OnDffdTab() { if (DoDffdTab()) pdfv_->SendMessage(WM_INITIALUPDATE); } bool CHexEditView::DoDffdTab() { if (TemplateViewType() == 2) return false; // already open in tab // Close DFFD view in split window if there is one if (pdfv_ != NULL) { int snum_d = GetFrame()->splitter_.FindViewColumn(pdfv_->GetSafeHwnd()); ASSERT(snum_d > -1); pdfv_ = NULL; if (snum_d > -1) { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_d, split_width_d_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_d, TRUE)); GetFrame()->splitter_.RecalcLayout(); } } // Reopen in the tab CHexTabView *ptv = GetFrame()->ptv_; int tnum_d = ptv->AddView(RUNTIME_CLASS (CDataFormatView), _T("Template (Tree) View")); ptv->SetActiveView(tnum_d); pdfv_ = (CDataFormatView *)ptv->GetActiveView(); ASSERT_KINDOF(CDataFormatView, pdfv_); // Make sure dataformat view knows which hex view it is assoc. with pdfv_->phev_ = this; ptv->SetActiveView(0); return true; } void CHexEditView::OnUpdateDffdTab(CCmdUI* pCmdUI) { pCmdUI->SetCheck(TemplateViewType() == 2); pCmdUI->Enable(GetDocument()->ptree_ != NULL); } // public function that just says how the template is displayed int CHexEditView::TemplateViewType() const { if (pdfv_ == NULL) return 0; else if (GetFrame()->splitter_.FindViewColumn(pdfv_->GetSafeHwnd()) > -1) return 1; else if (GetFrame()->ptv_->FindTab(pdfv_->GetSafeHwnd()) > -1) return 2; else { ASSERT(FALSE); return 0; } } // Aerial View commands void CHexEditView::OnAerialHide() { if (pav_ == NULL) return; // already hidden int snum_a = GetFrame()->splitter_.FindViewColumn(pav_->GetSafeHwnd()); int tnum_a = GetFrame()->ptv_->FindTab(pav_->GetSafeHwnd()); ASSERT(snum_a > -1 || tnum_a > -1); // It must be open in tab or splitter // Set pav_ to NULL now to avoid the view getting messages while invalid pav_ = NULL; GetDocument()->RemoveAerialView(); if (snum_a > -1) // splitter? { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_a, split_width_a_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_a, TRUE)); GetFrame()->splitter_.RecalcLayout(); } else if (tnum_a > -1) // tab? { GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing aerial view VERIFY(GetFrame()->ptv_->RemoveView(tnum_a)); } } void CHexEditView::OnUpdateAerialHide(CCmdUI* pCmdUI) { //pCmdUI->Enable(TRUE); pCmdUI->SetCheck(AerialViewType() == 0); } void CHexEditView::OnAerialSplit() { DoAerialSplit(); } bool CHexEditView::DoAerialSplit(bool init /*=true*/) { int snum_a; if (pav_ != NULL && (snum_a = GetFrame()->splitter_.FindViewColumn(pav_->GetSafeHwnd())) > -1) { if (GetFrame()->splitter_.ColWidth(snum_a) < 8) AdjustColumns(); return false; // already open in splitter } CAerialView * pSaved = pav_; // Save this so we can delete tab view after open in split view pav_ = NULL; // Reopen in the splitter CCreateContext ctxt; ctxt.m_pNewViewClass = RUNTIME_CLASS(CAerialView); ctxt.m_pCurrentDoc = GetDocument(); ctxt.m_pLastView = this; ctxt.m_pCurrentFrame = GetFrame(); CHexEditSplitter *psplitter = &(GetFrame()->splitter_); ASSERT(psplitter->m_hWnd != 0); // Make sure width of splitter window is OK CRect rr; GetFrame()->GetClientRect(&rr); if (split_width_a_ < 8 || split_width_a_ > rr.Width()) { split_width_a_ = rr.Width()/3; if (split_width_a_ < 8) split_width_a_ = 8; } // Add aerial view column to the right of hex (tab) view column int snum_t = GetFrame()->splitter_.FindViewColumn(GetFrame()->ptv_->GetSafeHwnd()); VERIFY(psplitter->InsColumn(snum_t + 1, split_width_a_, 8, RUNTIME_CLASS(CAerialView), &ctxt)); psplitter->SetActivePane(0, snum_t); // make hex view active pav_ = (CAerialView *)psplitter->GetPane(0, snum_t + 1); ASSERT_KINDOF(CAerialView, pav_); // Make sure aerial view knows which hex view it is assoc. with pav_->phev_ = this; psplitter->SetColumnInfo(snum_t, rr.Width() - split_width_a_, 10); psplitter->RecalcLayout(); AdjustColumns(); if (init) pav_->SendMessage(WM_INITIALUPDATE); // If open then it is open in a tab - close it if (pSaved != NULL) { int tnum_a = GetFrame()->ptv_->FindTab(pSaved->GetSafeHwnd()); ASSERT(tnum_a > -1); GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing aerial view if (tnum_a > -1) VERIFY(GetFrame()->ptv_->RemoveView(tnum_a)); GetDocument()->RemoveAerialView(); } return true; } void CHexEditView::OnUpdateAerialSplit(CCmdUI* pCmdUI) { pCmdUI->SetCheck(AerialViewType() == 1); } void CHexEditView::OnAerialTab() { DoAerialTab(); } bool CHexEditView::DoAerialTab(bool init /*=true*/) { if (pav_ != NULL && GetFrame()->ptv_->FindTab(pav_->GetSafeHwnd()) > -1) return false; CAerialView *pSaved = pav_; // Save this so we can delete the tab view after open in split view pav_ = NULL; // Reopen in the tab CHexTabView *ptv = GetFrame()->ptv_; int tnum_a = ptv->AddView(RUNTIME_CLASS (CAerialView), _T("Aerial View")); ASSERT(tnum_a > 0); if (tnum_a == -1) return false; ptv->SetActiveView(tnum_a); pav_ = (CAerialView *)ptv->GetActiveView(); ASSERT_KINDOF(CAerialView, pav_); // Make sure aerial view knows which hex view it is assoc. with pav_->phev_ = this; ptv->SetActiveView(0); if (init) pav_->SendMessage(WM_INITIALUPDATE); // Close Aerial view in split window if there is one if (pSaved != NULL) { int snum_a = GetFrame()->splitter_.FindViewColumn(pSaved->GetSafeHwnd()); ASSERT(snum_a > 0); // Should be there (not -1) and not the left one (not 0) if (snum_a > -1) { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_a, split_width_a_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_a, TRUE)); GetFrame()->splitter_.RecalcLayout(); GetDocument()->RemoveAerialView(); } } return true; } void CHexEditView::OnUpdateAerialTab(CCmdUI* pCmdUI) { pCmdUI->SetCheck(AerialViewType() == 2); } // public functiom that just says how we are displaying the aerial view int CHexEditView::AerialViewType() const { if (pav_ == NULL) return 0; else if (GetFrame()->splitter_.FindViewColumn(pav_->GetSafeHwnd()) > -1) return 1; else if (GetFrame()->ptv_->FindTab(pav_->GetSafeHwnd()) > -1) return 2; else { ASSERT(FALSE); return 0; } } // Compare View commands void CHexEditView::OnCompHide() { if (pcv_ == NULL) return; // already hidden int snum_c = GetFrame()->splitter_.FindViewColumn(pcv_->GetSafeHwnd()); int tnum_c = GetFrame()->ptv_->FindTab(pcv_->GetSafeHwnd()); pcv_ = NULL; // Clear it now to avoid getting errors by trying to use it when dead GetDocument()->RemoveCompView(); // compare window is detroyed directly (no WM_CLOSE) so we need this here ASSERT(snum_c > -1 || tnum_c > -1); // It must be open in tab or splitter if (snum_c > -1) // splitter? { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_c, split_width_c_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_c, TRUE)); GetFrame()->splitter_.RecalcLayout(); } else if (tnum_c > -1) // tab? { GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing compare view VERIFY(GetFrame()->ptv_->RemoveView(tnum_c)); } } void CHexEditView::OnUpdateCompHide(CCmdUI* pCmdUI) { //pCmdUI->Enable(TRUE); pCmdUI->SetCheck(CompViewType() == 0); } void CHexEditView::OnCompSplit() { DoCompSplit(); } bool CHexEditView::DoCompSplit(bool init /*=true*/) { int snum_c; if (pcv_ != NULL && (snum_c = GetFrame()->splitter_.FindViewColumn(pcv_->GetSafeHwnd())) > -1) { if (GetFrame()->splitter_.ColWidth(snum_c) < 8) AdjustColumns(); return false; // already open in splitter } // Make sure we have the name of the compare file to open if (!GetDocument()->GetCompareFile()) return false; // Save current view so we can close it later CCompareView * pSaved = pcv_; pcv_ = NULL; // Reopen in the splitter CCreateContext ctxt; ctxt.m_pNewViewClass = RUNTIME_CLASS(CCompareView); ctxt.m_pCurrentDoc = GetDocument(); ctxt.m_pLastView = this; ctxt.m_pCurrentFrame = GetFrame(); CHexEditSplitter *psplitter = &(GetFrame()->splitter_); ASSERT(psplitter->m_hWnd != 0); // Make sure width of splitter window is OK CRect rr; GetFrame()->GetClientRect(&rr); if (split_width_c_ < 8 || split_width_c_ > rr.Width()) { split_width_c_ = rr.Width()/3; if (split_width_c_ < 8) split_width_c_ = 8; } // Add compare view column to the right of hex (tab) view column int snum_t = GetFrame()->splitter_.FindViewColumn(GetFrame()->ptv_->GetSafeHwnd()); VERIFY(psplitter->InsColumn(snum_t + 1, split_width_c_, 8, RUNTIME_CLASS(CCompareView), &ctxt)); psplitter->SetActivePane(0, snum_t); // make hex view active pcv_ = (CCompareView *)psplitter->GetPane(0, snum_t + 1); ASSERT_KINDOF(CCompareView, pcv_); pcv_->phev_ = this; psplitter->SetColumnInfo(snum_t, rr.Width() - split_width_c_, 10); psplitter->RecalcLayout(); AdjustColumns(); // Make sure compare view knows which hex view it is assoc. with if (init) pcv_->SendMessage(WM_INITIALUPDATE); // If it was open in the tabbed view close that view if (pSaved != NULL) { int tnum_c = GetFrame()->ptv_->FindTab(pSaved->GetSafeHwnd()); ASSERT(tnum_c > -1); GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing compare view if (tnum_c > -1) VERIFY(GetFrame()->ptv_->RemoveView(tnum_c)); GetDocument()->RemoveCompView(); // compare window is detroyed directly (no WM_CLOSE) so we need this here } return true; } void CHexEditView::OnUpdateCompSplit(CCmdUI* pCmdUI) { pCmdUI->SetCheck(CompViewType() == 1); } void CHexEditView::OnCompTab() { DoCompTab(); } bool CHexEditView::DoCompTab(bool init /*=true*/) { if (pcv_ != NULL && GetFrame()->ptv_->FindTab(pcv_->GetSafeHwnd()) > -1) return false; // already open in tab // Save current view so we can close it later CCompareView * pSaved = pcv_; pcv_ = NULL; // Make sure we have the name of the compare file to open if (!GetDocument()->GetCompareFile()) return false; // Reopen in the tab CHexTabView *ptv = GetFrame()->ptv_; int tnum_c = ptv->AddView(RUNTIME_CLASS (CCompareView), _T("Compare View")); ASSERT(tnum_c > 0); if (tnum_c == -1) return false; ptv->SetActiveView(tnum_c); pcv_ = (CCompareView *)ptv->GetActiveView(); ASSERT_KINDOF(CCompareView, pcv_); // Make sure compare view knows which hex view it is assoc. with pcv_->phev_ = this; ptv->SetActiveView(0); if (init) pcv_->SendMessage(WM_INITIALUPDATE); // Close Compare view in split window if there is one if (pSaved != NULL) { int snum_c = GetFrame()->splitter_.FindViewColumn(pSaved->GetSafeHwnd()); ASSERT(snum_c > 0); // Should be there (not -1) and not the left one (not 0) if (snum_c > -1) { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_c, split_width_c_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_c, TRUE)); GetFrame()->splitter_.RecalcLayout(); GetDocument()->RemoveCompView(); // compare window is detroyed directly (no WM_CLOSE) so we need this here } } return true; } void CHexEditView::OnUpdateCompTab(CCmdUI* pCmdUI) { pCmdUI->SetCheck(CompViewType() == 2); } int CHexEditView::CompViewType() const { if (pcv_ == NULL) return 0; else if (GetFrame()->splitter_.FindViewColumn(pcv_->GetSafeHwnd()) > -1) return 1; else if (GetFrame()->ptv_->FindTab(pcv_->GetSafeHwnd()) > -1) return 2; else { ASSERT(FALSE); return 0; } } // private function which hopefully makes sure all the splitter columns are obvious (ie a min width) void CHexEditView::AdjustColumns() { int d, t, a, c, min; // Current width of dffd, tab, aerial, and compare columns d = t = a = c = -1; int snum_d, snum_t, snum_a, snum_c; snum_d = snum_t = snum_a = snum_c = -1; // Get current column widths CHexEditSplitter *psplitter = &(GetFrame()->splitter_); if (pdfv_ != NULL) snum_d = psplitter->FindViewColumn(pdfv_->GetSafeHwnd()); snum_t = psplitter->FindViewColumn(GetFrame()->ptv_->GetSafeHwnd()); // We always have a tab column since it contains the hex view if (pav_ != NULL) snum_a = psplitter->FindViewColumn(pav_->GetSafeHwnd()); if (pcv_ != NULL) snum_c = psplitter->FindViewColumn(pcv_->GetSafeHwnd()); if (snum_d > -1) psplitter->GetColumnInfo(snum_d, d, min); if (snum_t > -1) psplitter->GetColumnInfo(snum_t, t, min); if (snum_a > -1) psplitter->GetColumnInfo(snum_a, a, min); if (snum_c > -1) psplitter->GetColumnInfo(snum_c, c, min); // Make ideal widths slightly smaller but not less than a minimum bool adjust = false; d -= 20; if (snum_d > -1 && d < 20) { d = 20; adjust = true; } t -= 30; if (snum_t > -1 && t < 30) { t = 30; adjust = true; } a -= 10; if (snum_a > -1 && a < 10) { a = 10; adjust = true; } c -= 10; if (snum_c > -1 && c < 10) { c = 10; adjust = true; } if (adjust) { if (snum_d > -1) psplitter->SetColumnInfo(snum_d, d, 10); if (snum_t > -1) psplitter->SetColumnInfo(snum_t, t, 10); if (snum_a > -1) psplitter->SetColumnInfo(snum_a, a, 8); if (snum_c > -1) psplitter->SetColumnInfo(snum_c, c, 8); psplitter->RecalcLayout(); } if (snum_d > -1) psplitter->GetColumnInfo(snum_d, split_width_d_, min); if (snum_a > -1) psplitter->GetColumnInfo(snum_a, split_width_a_, min); if (snum_c > -1) psplitter->GetColumnInfo(snum_c, split_width_c_, min); } // Command to go to first recent difference in compare view void CHexEditView::OnCompFirst() { if (GetDocument()->CompareDifferences() > 0) { FILE_ADDRESS addr; int len; GetDocument()->GetOrigDiff(0, 0, addr, len); MoveToAddress(addr, addr+len); } } void CHexEditView::OnUpdateCompFirst(CCmdUI* pCmdUI) { pCmdUI->Enable(GetDocument()->CompareDifferences() > 0); } // Command to go to previous recent difference in compare view void CHexEditView::OnCompPrev() { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); int idx = GetDocument()->FirstDiffAt(false, 0, start - 1); if (idx > 0) { FILE_ADDRESS addr; int len; GetDocument()->GetOrigDiff(0, idx - 1, addr, len); MoveToAddress(addr, addr+len); } } void CHexEditView::OnUpdateCompPrev(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); pCmdUI->Enable(GetDocument()->CompareDifferences() >= 0 && GetDocument()->FirstDiffAt(false, 0, start - 1) > 0); } // Command to go to next recent difference in compare view void CHexEditView::OnCompNext() { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); int idx = GetDocument()->FirstDiffAt(false, 0, start); if (idx < GetDocument()->CompareDifferences(0)) { FILE_ADDRESS addr; int len; GetDocument()->GetOrigDiff(0, idx, addr, len); MoveToAddress(addr, addr+len); } } void CHexEditView::OnUpdateCompNext(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); pCmdUI->Enable(GetDocument()->CompareDifferences() >= 0 && GetDocument()->FirstDiffAt(false, 0, start) < GetDocument()->CompareDifferences()); } // Command to go to last recent difference in compare view void CHexEditView::OnCompLast() { int count = GetDocument()->CompareDifferences(); if (count > 0) { FILE_ADDRESS addr; int len; GetDocument()->GetOrigDiff(0, count - 1, addr, len); MoveToAddress(addr, addr+len); } } void CHexEditView::OnUpdateCompLast(CCmdUI* pCmdUI) { pCmdUI->Enable(GetDocument()->CompareDifferences() > 0); } // Command to go to first of all differences (not just recent) in compare view void CHexEditView::OnCompAllFirst() { FILE_ADDRESS addr; int len; GetDocument()->GetFirstDiffAll(addr, len); if (addr > -1) MoveToAddress(addr, addr+len); } void CHexEditView::OnUpdateCompAllFirst(CCmdUI* pCmdUI) { FILE_ADDRESS addr; int len; GetDocument()->GetFirstDiffAll(addr, len); pCmdUI->Enable(addr > -1); } void CHexEditView::OnCompAllPrev() { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); FILE_ADDRESS addr; int len; GetDocument()->GetPrevDiffAll(start - 1, addr, len); if (addr > -1) MoveToAddress(addr, addr+len); } void CHexEditView::OnUpdateCompAllPrev(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); FILE_ADDRESS addr; int len; GetDocument()->GetPrevDiffAll(start - 1, addr, len); pCmdUI->Enable(addr > -1); } void CHexEditView::OnCompAllNext() { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); FILE_ADDRESS addr; int len; GetDocument()->GetNextDiffAll(end, addr, len); if (addr > -1) MoveToAddress(addr, addr+len); } void CHexEditView::OnUpdateCompAllNext(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); FILE_ADDRESS addr; int len; GetDocument()->GetNextDiffAll(end, addr, len); pCmdUI->Enable(addr > -1); } void CHexEditView::OnCompAllLast() { FILE_ADDRESS addr; int len; GetDocument()->GetLastDiffAll(addr, len); if (addr > -1) MoveToAddress(addr, addr+len); } void CHexEditView::OnUpdateCompAllLast(CCmdUI* pCmdUI) { FILE_ADDRESS addr; int len; GetDocument()->GetLastDiffAll(addr, len); pCmdUI->Enable(addr > -1); } void CHexEditView::OnCompAutoSync() { if (pcv_ == NULL) { AfxMessageBox("No Compare is available"); theApp.mac_error_ = 10; return; } begin_change(); display_.auto_sync_comp = !display_.auto_sync_comp; make_change(); end_change(); // If has been turned on then sync now if (display_.auto_sync_comp) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pcv_->MoveToAddress(start_addr, end_addr); } theApp.SaveToMacro(km_comp_sync, 2); } void CHexEditView::OnUpdateCompAutoSync(CCmdUI* pCmdUI) { pCmdUI->Enable(pcv_ != NULL); pCmdUI->SetCheck(display_.auto_sync_comp); } void CHexEditView::OnCompAutoScroll() { if (pcv_ == NULL) { AfxMessageBox("No Compare is available"); theApp.mac_error_ = 10; return; } begin_change(); display_.auto_scroll_comp = !display_.auto_scroll_comp; make_change(); end_change(); // If has been turned on then scroll now if (display_.auto_scroll_comp) pcv_->SetScroll(GetScroll()); theApp.SaveToMacro(km_comp_sync, 3); } void CHexEditView::OnUpdateCompAutoScroll(CCmdUI* pCmdUI) { pCmdUI->Enable(pcv_ != NULL); pCmdUI->SetCheck(display_.auto_scroll_comp); } // This is connected to Ctrl+T and is used for testing new dialogs etc void CHexEditView::OnViewtest() { // for testing new commands double dd = 65535.0; NumScale(dd); } CTipExpr::value_t CTipExpr::find_symbol(const char *sym, value_t parent, size_t index, int *pac, __int64 &sym_size, __int64 &sym_address, CString &) { ASSERT(pview_ != NULL); ASSERT(parent.typ == TYPE_NONE); // Parent is not used here value_t retval; retval.typ = TYPE_NONE; // Default to symbol not found retval.error = false; retval.int64 = 0; sym_address = pview_->tip_addr_; unsigned_ = false; CString sym_str(sym); if (sym_str.CompareNoCase("address") == 0) { retval.typ = TYPE_INT; // Just return the address retval.int64 = sym_address; sym_size = 4; // Addresses can be up to 8 but this restricts display to 32-bits (and if bigger then extra bits are shown) unsigned_ = true; } else if (sym_str.CompareNoCase("cursor") == 0) { FILE_ADDRESS start, end; pview_->GetSelAddr(start, end); retval.typ = TYPE_INT; retval.int64 = start; sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("sel_len") == 0) { FILE_ADDRESS start, end; pview_->GetSelAddr(start, end); retval.typ = TYPE_INT; retval.int64 = end - start; sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("mark") == 0) { retval.typ = TYPE_INT; retval.int64 = pview_->GetMark(); sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("eof") == 0) { retval.typ = TYPE_INT; retval.int64 = pview_->GetDocument()->length(); sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("sector") == 0) { retval.typ = TYPE_INT; // current sector int seclen = pview_->GetDocument()->GetSectorSize(); if (seclen > 0) retval.int64 = sym_address / seclen; else retval.int64 = 0; sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("offset") == 0) { retval.typ = TYPE_INT; // offset within current sector int seclen = pview_->GetDocument()->GetSectorSize(); if (seclen > 0) retval.int64 = sym_address % seclen; else retval.int64 = 0; sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("sbyte") == 0) { signed char val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { retval.typ = TYPE_INT; // Just return the current byte retval.int64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("byte") == 0) { unsigned char val; if (pview_->GetDocument()->GetData(&val, sizeof(val), sym_address) == sizeof(val)) { retval.typ = TYPE_INT; // Just return the current byte retval.int64 = val; sym_size = sizeof(val); unsigned_ = true; } } else if (sym_str.CompareNoCase("word") == 0) { short val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("uword") == 0) { unsigned short val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); unsigned_ = true; } } else if (sym_str.CompareNoCase("dword") == 0) { long val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("udword") == 0) { unsigned long val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); unsigned_ = true; } } else if (sym_str.CompareNoCase("qword") == 0) { __int64 val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("uqword") == 0) { unsigned __int64 val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); unsigned_ = true; } } else if (sym_str.CompareNoCase("ieee32") == 0) { float val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_REAL; retval.real64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("ieee64") == 0) { double val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_REAL; retval.real64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("ibm32") == 0) { unsigned char val[4]; if (pview_->GetDocument()->GetData(val, sizeof(val), sym_address) == sizeof(val)) { retval.typ = TYPE_REAL; retval.real64 = ::ibm_fp32(val, NULL, NULL, !pview_->BigEndian()); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("ibm64") == 0) { unsigned char val[8]; if (pview_->GetDocument()->GetData(val, sizeof(val), sym_address) == sizeof(val)) { retval.typ = TYPE_REAL; retval.real64 = ::ibm_fp64(val, NULL, NULL, !pview_->BigEndian()); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("real48") == 0) { unsigned char val[6]; if (pview_->GetDocument()->GetData(val, sizeof(val), sym_address) == sizeof(val)) { retval.typ = TYPE_REAL; retval.real64 = ::real48(val, NULL, NULL, pview_->BigEndian() == TRUE); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("time_t") == 0) { time_t val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_DATE; retval.date = FromTime_t(val); sym_size = sizeof(val); } } #ifdef TIME64_T else if (sym_str.CompareNoCase("time64_t") == 0) { __int64 val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_DATE; retval.date = FromTime_t(val); sym_size = sizeof(val); } } #endif else if (sym_str.CompareNoCase("time_t_80") == 0) // MSC 5.1 time_t { long val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_DATE; retval.date = FromTime_t_80(val); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("time_t_1899") == 0) // MSC 7 time_t { unsigned long val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_DATE; retval.date = FromTime_t_1899(val); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("time_t_mins") == 0) // MSC 7 time_t { long val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_DATE; retval.date = FromTime_t_mins(val); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("astring") == 0) { char buf[256]; size_t len = pview_->GetDocument()->GetData((unsigned char *)buf, sizeof(buf)-1, sym_address); buf[len] = '\0'; retval.typ = TYPE_STRING; retval.pstr = new ExprStringType((LPCTSTR)buf); } size_ = int(sym_size); // Remember size of the symbol we encountered return retval; } Allow click on a bookmark (without dragging to move it) to just set the caret posn. git-svn-id: c806da28ca781a1e2f2d0b1fde2a9d9a144b325a@962 295070fd-a27b-da4f-a32e-77c6a882a0e3 // HexEditView.cpp : implementation of the CHexEditView class // // Copyright (c) 1998-2010 by Andrew W. Phillips. // // No restrictions are placed on the noncommercial use of this code, // as long as this text (from the above copyright notice to the // disclaimer below) is preserved. // // This code may be redistributed as long as it remains unmodified // and is not sold for profit without the author's written consent. // // This code, or any part of it, may not be used in any software that // is sold for profit, without the author's written consent. // // DISCLAIMER: This file is provided "as is" with no expressed or // implied warranty. The author accepts no liability for any damage // or loss of business that this product may cause. // #include "stdafx.h" #include "HexEdit.h" #include "HexFileList.h" #include "HexEditDoc.h" #include "HexEditView.h" #include "DataFormatView.h" #include "AerialView.h" #include "CompareView.h" #include "MainFrm.h" #include "ChildFrm.h" #include "Dialog.h" #include "Bookmark.h" #include "NewFile.h" #include "Password.h" #include "Boyer.h" #include "SystemSound.h" #include "Misc.h" #include "BCGMisc.h" #include "SRecord.h" // For import/export of Motorola S record files #include "IntelHex.h" // For import/export of Intel Hex files #include "CopyCSrc.h" // For Copy as C Source dialog #include "zlib/zlib.h" // For compression #include "md5.h" // For MD5 hash #include "sha1.h" // For SHA1 hash #include "HelpID.hm" #ifdef _DEBUG #include "timer.h" #endif // This #define allows checking that the drawing code does clipping properly for // efficiency. For example for very long lines we don't want to draw a huge no // of byte values to the right and/or left of the display area. It does this by // moving the borders in and turning off the clipping rectangle use in OnDraw // (see GetDisplayRect) and also drawing red border lines in OnEraseBkgnd. // Also note that when in vert_display (stacked) mode that up to 3 lines can be // drawn past the top and bottom of the display area. //#define TEST_CLIPPING 1 // A note on the selection: // 1. The selection is a contiguous set of bytes with a start address and a length. // When a discontiguous "selection" is required we use the highlighter. // 2. The actual selection is kept track of in the base class (ScrView) members // caretpos_ and selpos_. SetCaret is used to set the caret with no selection // (ie selection length s zero) so caretpos_ == selpos_. There is also basepos_ // which is the start of the selection (ie either == caretpos_ or selpos_). // 3. At the basic level the selection is set/got using CSrcView::GetSel and SetSel, // which are pixel based. Since CScrView and its selection are text oriented there // is also GetTSel and SetTSel which are character based. // 4. CScrView allows the caret to be at the start or end of the selection, which is // why SetSel takes start/end positions plus a bool to says which end has the caret. // 5. SetSel calls ValidateCaret to find the closest valid caret position for the // start and end positions. // 6. CHexEditView::GetSelAddr/SetSelAddr get/set the selection in terms of file // addresses, by using addr2pos/pos2addr to convert between pixels and file addresses // before calling CScrView::GetSel/SetSel. // Similarly GetPos is the equivalent of GetCaret but returns a file address. // 7. To handle stacked mode addr2pos takes a row as well as an address. The row // can be a value of 0, 1, or 2 for the 3 rows when in stacked mode. // 8. At a higher level GoAddress will set the selection first making sure // its parameters are a valid range. // 9. At an even higher level MoveToAddress allows setting the selection while // updating everything else for consistency including: // - scrolling the display to show the selection // - storing undo information so the move can be undone // - keeping track of nav points // - updating jump tools with new address // - updating properties dialog with value at caret, etc #define MAX_CLIPBOARD 32000000L // Just a rough guideline - may make an option later #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CHexEditApp theApp; //BYTE CHexEditFontCombo::saved_charset = 147; // (see BCGMisc.h) initially 147 to not match // anything -> force initial rebuild of the font list static bool in_recalc_display = false; ///////////////////////////////////////////////////////////////////////////// // CHexEditView IMPLEMENT_DYNCREATE(CHexEditView, CScrView) BEGIN_MESSAGE_MAP(CHexEditView, CScrView) //{{AFX_MSG_MAP(CHexEditView) ON_WM_SIZE() ON_COMMAND(ID_ADDR_TOGGLE, OnAddrToggle) ON_UPDATE_COMMAND_UI(ID_ADDR_TOGGLE, OnUpdateAddrToggle) ON_COMMAND(ID_GRAPHIC_TOGGLE, OnGraphicToggle) ON_UPDATE_COMMAND_UI(ID_GRAPHIC_TOGGLE, OnUpdateGraphicToggle) ON_COMMAND(ID_CHAR_TOGGLE, OnCharToggle) ON_UPDATE_COMMAND_UI(ID_CHAR_TOGGLE, OnUpdateCharToggle) ON_COMMAND(ID_FONT, OnFont) ON_COMMAND(ID_AUTOFIT, OnAutoFit) ON_UPDATE_COMMAND_UI(ID_AUTOFIT, OnUpdateAutofit) ON_COMMAND(ID_ASC_EBC, OnAscEbc) ON_UPDATE_COMMAND_UI(ID_ASC_EBC, OnUpdateAscEbc) ON_COMMAND(ID_CONTROL, OnControl) ON_UPDATE_COMMAND_UI(ID_CONTROL, OnUpdateControl) ON_WM_CHAR() ON_WM_SETFOCUS() ON_WM_KILLFOCUS() ON_WM_DESTROY() ON_WM_LBUTTONDOWN() ON_COMMAND(ID_MARK, OnMark) ON_COMMAND(ID_GOTO_MARK, OnGotoMark) ON_WM_LBUTTONDBLCLK() ON_WM_KEYDOWN() ON_COMMAND(ID_EDIT_UNDO, OnEditUndo) ON_COMMAND(ID_SEARCH_HEX, OnSearchHex) ON_COMMAND(ID_SEARCH_ASCII, OnSearchAscii) ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo) ON_COMMAND(ID_ALLOW_MODS, OnAllowMods) ON_UPDATE_COMMAND_UI(ID_ALLOW_MODS, OnUpdateAllowMods) ON_COMMAND(ID_CONTROL_TOGGLE, OnControlToggle) ON_COMMAND(ID_INSERT, OnInsert) ON_UPDATE_COMMAND_UI(ID_INSERT, OnUpdateInsert) ON_COMMAND(ID_SEARCH_ICASE, OnSearchIcase) ON_COMMAND(ID_EDIT_COMPARE, OnEditCompare) ON_COMMAND(ID_WINDOW_NEXT, OnWindowNext) ON_UPDATE_COMMAND_UI(ID_EDIT_COMPARE, OnUpdateEditCompare) ON_WM_CONTEXTMENU() ON_WM_RBUTTONDOWN() ON_COMMAND(ID_INC_BYTE, OnIncByte) ON_COMMAND(ID_INC_16BIT, OnInc16bit) ON_COMMAND(ID_INC_32BIT, OnInc32bit) ON_COMMAND(ID_INC_64BIT, OnInc64bit) ON_COMMAND(ID_DEC_BYTE, OnDecByte) ON_COMMAND(ID_DEC_16BIT, OnDec16bit) ON_COMMAND(ID_DEC_32BIT, OnDec32bit) ON_COMMAND(ID_DEC_64BIT, OnDec64bit) ON_COMMAND(ID_FLIP_16BIT, OnFlip16bit) ON_COMMAND(ID_FLIP_32BIT, OnFlip32bit) ON_COMMAND(ID_FLIP_64BIT, OnFlip64bit) ON_UPDATE_COMMAND_UI(ID_INC_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_INC_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_INC_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_INC_64BIT, OnUpdate64bit) ON_WM_LBUTTONUP() ON_COMMAND(ID_SELECT_ALL, OnSelectAll) ON_COMMAND(ID_EDIT_COPY, OnEditCopy) ON_COMMAND(ID_EDIT_CUT, OnEditCut) ON_COMMAND(ID_EDIT_PASTE, OnEditPaste) ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdateTextPaste) ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateClipboard) ON_UPDATE_COMMAND_UI(ID_PASTE_UNICODE, OnUpdateUnicodePaste) ON_WM_SETCURSOR() ON_COMMAND(ID_FONT_DEC, OnFontDec) ON_COMMAND(ID_FONT_INC, OnFontInc) ON_UPDATE_COMMAND_UI(ID_FONT_DEC, OnUpdateFontDec) ON_UPDATE_COMMAND_UI(ID_FONT_INC, OnUpdateFontInc) ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateEditCut) ON_COMMAND(ID_PASTE_ASCII, OnPasteAscii) ON_COMMAND(ID_PASTE_EBCDIC, OnPasteEbcdic) ON_COMMAND(ID_PASTE_UNICODE, OnPasteUnicode) ON_COMMAND(ID_COPY_CCHAR, OnCopyCchar) ON_COMMAND(ID_COPY_HEX, OnCopyHex) ON_COMMAND(ID_EDIT_WRITEFILE, OnEditWriteFile) ON_UPDATE_COMMAND_UI(ID_EDIT_READFILE, OnUpdateReadFile) ON_COMMAND(ID_EDIT_READFILE, OnReadFile) ON_WM_HSCROLL() ON_WM_VSCROLL() ON_COMMAND(ID_EXTENDTO_MARK, OnExtendToMark) ON_COMMAND(ID_SWAP_MARK, OnSwapMark) ON_COMMAND(ID_REDRAW, OnRedraw) ON_COMMAND(ID_SCROLL_DOWN, OnScrollDown) ON_COMMAND(ID_SCROLL_UP, OnScrollUp) ON_COMMAND(ID_SWAP, OnSwap) ON_COMMAND(ID_START_LINE, OnStartLine) ON_COMMAND(ID_DEL, OnDel) ON_UPDATE_COMMAND_UI(ID_SWAP, OnUpdateSwap) ON_COMMAND(ID_OEM_TOGGLE, OnOemToggle) ON_UPDATE_COMMAND_UI(ID_OEM_TOGGLE, OnUpdateOemToggle) ON_WM_MOUSEWHEEL() ON_COMMAND(ID_INVERT, OnInvert) ON_COMMAND(ID_NEG_BYTE, OnNegByte) ON_COMMAND(ID_NEG_16BIT, OnNeg16bit) ON_COMMAND(ID_NEG_32BIT, OnNeg32bit) ON_COMMAND(ID_NEG_64BIT, OnNeg64bit) ON_WM_MOUSEMOVE() ON_WM_KEYUP() ON_COMMAND(ID_HIGHLIGHT, OnHighlight) ON_UPDATE_COMMAND_UI(ID_HIGHLIGHT, OnUpdateHighlight) ON_COMMAND(ID_HIGHLIGHT_CLEAR, OnHighlightClear) ON_COMMAND(ID_HIGHLIGHT_PREV, OnHighlightPrev) ON_COMMAND(ID_HIGHLIGHT_NEXT, OnHighlightNext) ON_UPDATE_COMMAND_UI(ID_HIGHLIGHT_PREV, OnUpdateHighlightPrev) ON_UPDATE_COMMAND_UI(ID_HIGHLIGHT_NEXT, OnUpdateHighlightNext) ON_COMMAND(ID_EDIT_GOTO, OnEditGoto) ON_COMMAND(ID_ASC2EBC, OnAscii2Ebcdic) ON_UPDATE_COMMAND_UI(ID_ASC2EBC, OnUpdateConvert) ON_COMMAND(ID_EBC2ASC, OnEbcdic2Ascii) ON_COMMAND(ID_ANSI2IBM, OnAnsi2Ibm) ON_COMMAND(ID_IBM2ANSI, OnIbm2Ansi) ON_COMMAND(ID_ENCRYPT_ENCRYPT, OnEncrypt) ON_COMMAND(ID_ENCRYPT_DECRYPT, OnDecrypt) ON_UPDATE_COMMAND_UI(ID_ENCRYPT_ENCRYPT, OnUpdateEncrypt) ON_COMMAND(ID_EDIT_APPENDFILE, OnEditAppendFile) ON_COMMAND(ID_EDIT_APPENDSAMEFILE, OnEditAppendSameFile) ON_UPDATE_COMMAND_UI(ID_EDIT_APPENDSAMEFILE, OnUpdateEditAppendSameFile) ON_COMMAND(ID_UNDO_CHANGES, OnUndoChanges) ON_UPDATE_COMMAND_UI(ID_UNDO_CHANGES, OnUpdateUndoChanges) ON_COMMAND(ID_CALC_SEL, OnCalcSel) ON_UPDATE_COMMAND_UI(ID_CALC_SEL, OnUpdateCalcSel) ON_COMMAND(ID_DISPLAY_RESET, OnDisplayReset) ON_WM_ERASEBKGND() ON_COMMAND(ID_IMPORT_MOTOROLA_S, OnImportMotorolaS) ON_UPDATE_COMMAND_UI(ID_IMPORT_MOTOROLA_S, OnUpdateImportMotorolaS) ON_COMMAND(ID_IMPORT_INTEL, OnImportIntel) ON_UPDATE_COMMAND_UI(ID_IMPORT_INTEL, OnUpdateImportIntel) ON_COMMAND(ID_EXPORT_INTEL, OnExportIntel) ON_UPDATE_COMMAND_UI(ID_EXPORT_INTEL, OnUpdateExportIntel) ON_COMMAND(ID_IMPORT_HEX_TEXT, OnImportHexText) ON_UPDATE_COMMAND_UI(ID_IMPORT_HEX_TEXT, OnUpdateImportHexText) ON_COMMAND(ID_EXPORT_HEX_TEXT, OnExportHexText) ON_UPDATE_COMMAND_UI(ID_EXPORT_HEX_TEXT, OnUpdateExportHexText) ON_COMMAND(ID_CRC16, OnCrc16) ON_COMMAND(ID_CRC32, OnCrc32) ON_COMMAND(ID_CRC_CCITT, OnCrcCcitt) ON_COMMAND(ID_CRC_CCITT_B, OnCrcCcittB) ON_COMMAND(ID_CRC_XMODEM, OnCrcXmodem) ON_COMMAND(ID_BOOKMARKS_HIDE, OnBookmarksHide) ON_UPDATE_COMMAND_UI(ID_BOOKMARKS_HIDE, OnUpdateBookmarksHide) ON_COMMAND(ID_HIGHLIGHT_HIDE, OnHighlightHide) ON_UPDATE_COMMAND_UI(ID_HIGHLIGHT_HIDE, OnUpdateHighlightHide) ON_COMMAND(ID_BOOKMARKS_NEXT, OnBookmarksNext) ON_UPDATE_COMMAND_UI(ID_BOOKMARKS_NEXT, OnUpdateBookmarksNext) ON_COMMAND(ID_BOOKMARKS_PREV, OnBookmarksPrev) ON_UPDATE_COMMAND_UI(ID_BOOKMARKS_PREV, OnUpdateBookmarksPrev) ON_COMMAND(ID_BOOKMARKS_CLEAR, OnBookmarksClear) ON_UPDATE_COMMAND_UI(ID_BOOKMARKS_CLEAR, OnUpdateBookmarksClear) ON_COMMAND(ID_EDIT_FIND, OnEditFind) ON_COMMAND(ID_BOOKMARK_TOGGLE, OnBookmarkToggle) ON_COMMAND(ID_COLUMN_DEC, OnColumnDec) ON_UPDATE_COMMAND_UI(ID_COLUMN_DEC, OnUpdateColumnDec) ON_COMMAND(ID_COLUMN_INC, OnColumnInc) ON_UPDATE_COMMAND_UI(ID_COLUMN_INC, OnUpdateColumnInc) ON_COMMAND(ID_DFFD_AUTO_SYNC, OnDffdAutoSync) ON_UPDATE_COMMAND_UI(ID_DFFD_AUTO_SYNC, OnUpdateDffdAutoSync) ON_COMMAND(ID_DFFD_SYNC, OnDffdSync) ON_UPDATE_COMMAND_UI(ID_DFFD_SYNC, OnUpdateDffdSync) ON_COMMAND(ID_RAND_SEED_CALC, OnSeedCalc) ON_COMMAND(ID_RAND_SEED, OnSeedRandom) ON_UPDATE_COMMAND_UI(ID_CONTROL_TOGGLE, OnUpdateControl) ON_UPDATE_COMMAND_UI(ID_DEC_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_DEC_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_DEC_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_DEC_64BIT, OnUpdate64bit) ON_UPDATE_COMMAND_UI(ID_FLIP_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_FLIP_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_FLIP_64BIT, OnUpdate64bit) ON_UPDATE_COMMAND_UI(ID_SEARCH_SEL, OnUpdateClipboard) ON_UPDATE_COMMAND_UI(ID_PASTE_ASCII, OnUpdateTextPaste) ON_UPDATE_COMMAND_UI(ID_PASTE_EBCDIC, OnUpdateTextPaste) ON_UPDATE_COMMAND_UI(ID_EDIT_WRITEFILE, OnUpdateClipboard) ON_UPDATE_COMMAND_UI(ID_INVERT, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_NEG_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_NEG_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_NEG_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_NEG_64BIT, OnUpdate64bit) ON_UPDATE_COMMAND_UI(ID_EBC2ASC, OnUpdateConvert) ON_UPDATE_COMMAND_UI(ID_ANSI2IBM, OnUpdateConvert) ON_UPDATE_COMMAND_UI(ID_IBM2ANSI, OnUpdateConvert) ON_UPDATE_COMMAND_UI(ID_ENCRYPT_DECRYPT, OnUpdateEncrypt) ON_UPDATE_COMMAND_UI(ID_EDIT_APPENDFILE, OnUpdateClipboard) ON_UPDATE_COMMAND_UI(ID_CRC16, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_CRC32, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_CRC_CCITT, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_CRC_CCITT_B, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_CRC_XMODEM, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_COPY_CCHAR, OnUpdateClipboard) ON_UPDATE_COMMAND_UI(ID_COPY_HEX, OnUpdateClipboard) ON_COMMAND(ID_TRACK_CHANGES, OnTrackChanges) ON_UPDATE_COMMAND_UI(ID_TRACK_CHANGES, OnUpdateTrackChanges) //}}AFX_MSG_MAP ON_COMMAND(ID_EDIT_REPLACE, OnEditReplace) ON_COMMAND(ID_CHECKSUM8, OnChecksum8) ON_COMMAND(ID_CHECKSUM16, OnChecksum16) ON_COMMAND(ID_CHECKSUM32, OnChecksum32) ON_COMMAND(ID_CHECKSUM64, OnChecksum64) ON_UPDATE_COMMAND_UI(ID_CHECKSUM8, OnUpdateByteNZ) ON_UPDATE_COMMAND_UI(ID_CHECKSUM16, OnUpdate16bitNZ) ON_UPDATE_COMMAND_UI(ID_CHECKSUM32, OnUpdate32bitNZ) ON_UPDATE_COMMAND_UI(ID_CHECKSUM64, OnUpdate64bitNZ) ON_COMMAND(ID_XOR_BYTE, OnXorByte) ON_COMMAND(ID_XOR_16BIT, OnXor16bit) ON_COMMAND(ID_XOR_32BIT, OnXor32bit) ON_COMMAND(ID_XOR_64BIT, OnXor64bit) ON_UPDATE_COMMAND_UI(ID_XOR_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_XOR_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_XOR_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_XOR_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_ASSIGN_BYTE, OnAssignByte) ON_COMMAND(ID_ASSIGN_16BIT, OnAssign16bit) ON_COMMAND(ID_ASSIGN_32BIT, OnAssign32bit) ON_COMMAND(ID_ASSIGN_64BIT, OnAssign64bit) ON_UPDATE_COMMAND_UI(ID_ASSIGN_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_ASSIGN_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_ASSIGN_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_ASSIGN_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_RAND_BYTE, OnRandByte) ON_COMMAND(ID_RAND_FAST, OnRandFast) // ON_COMMAND(ID_RAND_16BIT, OnRand16bit) // ON_COMMAND(ID_RAND_32BIT, OnRand32bit) // ON_COMMAND(ID_RAND_64BIT, OnRand64bit) ON_UPDATE_COMMAND_UI(ID_RAND_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_RAND_FAST, OnUpdateByte) // ON_UPDATE_COMMAND_UI(ID_RAND_16BIT, OnUpdate16bit) // ON_UPDATE_COMMAND_UI(ID_RAND_32BIT, OnUpdate32bit) // ON_UPDATE_COMMAND_UI(ID_RAND_64BIT, OnUpdate64bit) ON_COMMAND(ID_ADD_BYTE, OnAddByte) ON_COMMAND(ID_ADD_16BIT, OnAdd16bit) ON_COMMAND(ID_ADD_32BIT, OnAdd32bit) ON_COMMAND(ID_ADD_64BIT, OnAdd64bit) ON_UPDATE_COMMAND_UI(ID_ADD_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_ADD_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_ADD_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_ADD_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_SUBTRACT_BYTE, OnSubtractByte) ON_COMMAND(ID_SUBTRACT_16BIT, OnSubtract16bit) ON_COMMAND(ID_SUBTRACT_32BIT, OnSubtract32bit) ON_COMMAND(ID_SUBTRACT_64BIT, OnSubtract64bit) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_AND_BYTE, OnAndByte) ON_COMMAND(ID_AND_16BIT, OnAnd16bit) ON_COMMAND(ID_AND_32BIT, OnAnd32bit) ON_COMMAND(ID_AND_64BIT, OnAnd64bit) ON_UPDATE_COMMAND_UI(ID_AND_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_AND_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_AND_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_AND_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_OR_BYTE, OnOrByte) ON_COMMAND(ID_OR_16BIT, OnOr16bit) ON_COMMAND(ID_OR_32BIT, OnOr32bit) ON_COMMAND(ID_OR_64BIT, OnOr64bit) ON_UPDATE_COMMAND_UI(ID_OR_BYTE, OnUpdateByteBinary) ON_UPDATE_COMMAND_UI(ID_OR_16BIT, OnUpdate16bitBinary) ON_UPDATE_COMMAND_UI(ID_OR_32BIT, OnUpdate32bitBinary) ON_UPDATE_COMMAND_UI(ID_OR_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_MUL_BYTE, OnMulByte) ON_UPDATE_COMMAND_UI(ID_MUL_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_MUL_16BIT, OnMul16bit) ON_UPDATE_COMMAND_UI(ID_MUL_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_MUL_32BIT, OnMul32bit) ON_UPDATE_COMMAND_UI(ID_MUL_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_MUL_64BIT, OnMul64bit) ON_UPDATE_COMMAND_UI(ID_MUL_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_DIV_BYTE, OnDivByte) ON_UPDATE_COMMAND_UI(ID_DIV_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_DIV_16BIT, OnDiv16bit) ON_UPDATE_COMMAND_UI(ID_DIV_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_DIV_32BIT, OnDiv32bit) ON_UPDATE_COMMAND_UI(ID_DIV_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_DIV_64BIT, OnDiv64bit) ON_UPDATE_COMMAND_UI(ID_DIV_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_MOD_BYTE, OnModByte) ON_UPDATE_COMMAND_UI(ID_MOD_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_MOD_16BIT, OnMod16bit) ON_UPDATE_COMMAND_UI(ID_MOD_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_MOD_32BIT, OnMod32bit) ON_UPDATE_COMMAND_UI(ID_MOD_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_MOD_64BIT, OnMod64bit) ON_UPDATE_COMMAND_UI(ID_MOD_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_REV_BYTE, OnRevByte) ON_UPDATE_COMMAND_UI(ID_REV_BYTE, OnUpdateByte) ON_COMMAND(ID_REV_16BIT, OnRev16bit) ON_UPDATE_COMMAND_UI(ID_REV_16BIT, OnUpdate16bit) ON_COMMAND(ID_REV_32BIT, OnRev32bit) ON_UPDATE_COMMAND_UI(ID_REV_32BIT, OnUpdate32bit) ON_COMMAND(ID_REV_64BIT, OnRev64bit) ON_UPDATE_COMMAND_UI(ID_REV_64BIT, OnUpdate64bit) ON_COMMAND(ID_SUBTRACT_X_BYTE, OnSubtractXByte) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_X_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_SUBTRACT_X_16BIT, OnSubtractX16bit) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_X_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_SUBTRACT_X_32BIT, OnSubtractX32bit) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_X_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_SUBTRACT_X_64BIT, OnSubtractX64bit) ON_UPDATE_COMMAND_UI(ID_SUBTRACT_X_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_DIV_X_BYTE, OnDivXByte) ON_UPDATE_COMMAND_UI(ID_DIV_X_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_DIV_X_16BIT, OnDivX16bit) ON_UPDATE_COMMAND_UI(ID_DIV_X_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_DIV_X_32BIT, OnDivX32bit) ON_UPDATE_COMMAND_UI(ID_DIV_X_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_DIV_X_64BIT, OnDivX64bit) ON_UPDATE_COMMAND_UI(ID_DIV_X_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_MOD_X_BYTE, OnModXByte) ON_UPDATE_COMMAND_UI(ID_MOD_X_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_MOD_X_16BIT, OnModX16bit) ON_UPDATE_COMMAND_UI(ID_MOD_X_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_MOD_X_32BIT, OnModX32bit) ON_UPDATE_COMMAND_UI(ID_MOD_X_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_MOD_X_64BIT, OnModX64bit) ON_UPDATE_COMMAND_UI(ID_MOD_X_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_GTR_BYTE, OnGtrByte) ON_UPDATE_COMMAND_UI(ID_GTR_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_GTR_16BIT, OnGtr16bit) ON_UPDATE_COMMAND_UI(ID_GTR_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_GTR_32BIT, OnGtr32bit) ON_UPDATE_COMMAND_UI(ID_GTR_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_GTR_64BIT, OnGtr64bit) ON_UPDATE_COMMAND_UI(ID_GTR_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_LESS_BYTE, OnLessByte) ON_UPDATE_COMMAND_UI(ID_LESS_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_LESS_16BIT, OnLess16bit) ON_UPDATE_COMMAND_UI(ID_LESS_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_LESS_32BIT, OnLess32bit) ON_UPDATE_COMMAND_UI(ID_LESS_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_LESS_64BIT, OnLess64bit) ON_UPDATE_COMMAND_UI(ID_LESS_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_GTRU_BYTE, OnGtrUByte) ON_UPDATE_COMMAND_UI(ID_GTRU_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_GTRU_16BIT, OnGtrU16bit) ON_UPDATE_COMMAND_UI(ID_GTRU_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_GTRU_32BIT, OnGtrU32bit) ON_UPDATE_COMMAND_UI(ID_GTRU_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_GTRU_64BIT, OnGtrU64bit) ON_UPDATE_COMMAND_UI(ID_GTRU_64BIT, OnUpdate64bitBinary) ON_COMMAND(ID_LESSU_BYTE, OnLessUByte) ON_UPDATE_COMMAND_UI(ID_LESSU_BYTE, OnUpdateByteBinary) ON_COMMAND(ID_LESSU_16BIT, OnLessU16bit) ON_UPDATE_COMMAND_UI(ID_LESSU_16BIT, OnUpdate16bitBinary) ON_COMMAND(ID_LESSU_32BIT, OnLessU32bit) ON_UPDATE_COMMAND_UI(ID_LESSU_32BIT, OnUpdate32bitBinary) ON_COMMAND(ID_LESSU_64BIT, OnLessU64bit) ON_UPDATE_COMMAND_UI(ID_LESSU_64BIT, OnUpdate64bitBinary) // Note shifts don't care about calc operand size (bits) since values are less than 64 ON_COMMAND(ID_ROL_BYTE, OnRolByte) ON_COMMAND(ID_ROL_16BIT, OnRol16bit) ON_COMMAND(ID_ROL_32BIT, OnRol32bit) ON_COMMAND(ID_ROL_64BIT, OnRol64bit) ON_UPDATE_COMMAND_UI(ID_ROL_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_ROL_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_ROL_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_ROL_64BIT, OnUpdate64bit) ON_COMMAND(ID_ROR_BYTE, OnRorByte) ON_COMMAND(ID_ROR_16BIT, OnRor16bit) ON_COMMAND(ID_ROR_32BIT, OnRor32bit) ON_COMMAND(ID_ROR_64BIT, OnRor64bit) ON_UPDATE_COMMAND_UI(ID_ROR_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_ROR_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_ROR_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_ROR_64BIT, OnUpdate64bit) ON_COMMAND(ID_LSL_BYTE, OnLslByte) ON_COMMAND(ID_LSL_16BIT, OnLsl16bit) ON_COMMAND(ID_LSL_32BIT, OnLsl32bit) ON_COMMAND(ID_LSL_64BIT, OnLsl64bit) ON_UPDATE_COMMAND_UI(ID_LSL_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_LSL_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_LSL_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_LSL_64BIT, OnUpdate64bit) ON_COMMAND(ID_LSR_BYTE, OnLsrByte) ON_COMMAND(ID_LSR_16BIT, OnLsr16bit) ON_COMMAND(ID_LSR_32BIT, OnLsr32bit) ON_COMMAND(ID_LSR_64BIT, OnLsr64bit) ON_UPDATE_COMMAND_UI(ID_LSR_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_LSR_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_LSR_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_LSR_64BIT, OnUpdate64bit) ON_COMMAND(ID_ASR_BYTE, OnAsrByte) ON_COMMAND(ID_ASR_16BIT, OnAsr16bit) ON_COMMAND(ID_ASR_32BIT, OnAsr32bit) ON_COMMAND(ID_ASR_64BIT, OnAsr64bit) ON_UPDATE_COMMAND_UI(ID_ASR_BYTE, OnUpdateByte) ON_UPDATE_COMMAND_UI(ID_ASR_16BIT, OnUpdate16bit) ON_UPDATE_COMMAND_UI(ID_ASR_32BIT, OnUpdate32bit) ON_UPDATE_COMMAND_UI(ID_ASR_64BIT, OnUpdate64bit) ON_COMMAND_RANGE(ID_EXPORT_S1, ID_EXPORT_S3, OnExportSRecord) ON_UPDATE_COMMAND_UI_RANGE(ID_EXPORT_S1, ID_EXPORT_S3, OnUpdateExportSRecord) ON_UPDATE_COMMAND_UI(ID_INSERT_BLOCK, OnUpdateInsertBlock) ON_COMMAND(ID_INSERT_BLOCK, OnInsertBlock) // New display handling commands ON_COMMAND(ID_DISPLAY_HEX, OnDisplayHex) ON_UPDATE_COMMAND_UI(ID_DISPLAY_HEX, OnUpdateDisplayHex) ON_COMMAND(ID_DISPLAY_CHAR, OnDisplayChar) ON_UPDATE_COMMAND_UI(ID_DISPLAY_CHAR, OnUpdateDisplayChar) ON_COMMAND(ID_DISPLAY_BOTH, OnDisplayBoth) ON_UPDATE_COMMAND_UI(ID_DISPLAY_BOTH, OnUpdateDisplayBoth) ON_COMMAND(ID_DISPLAY_STACKED, OnDisplayStacked) ON_UPDATE_COMMAND_UI(ID_DISPLAY_STACKED, OnUpdateDisplayStacked) ON_COMMAND(ID_CHARSET_ASCII, OnCharsetAscii) ON_UPDATE_COMMAND_UI(ID_CHARSET_ASCII, OnUpdateCharsetAscii) ON_COMMAND(ID_CHARSET_ANSI, OnCharsetAnsi) ON_UPDATE_COMMAND_UI(ID_CHARSET_ANSI, OnUpdateCharsetAnsi) ON_COMMAND(ID_CHARSET_OEM, OnCharsetOem) ON_UPDATE_COMMAND_UI(ID_CHARSET_OEM, OnUpdateCharsetOem) ON_COMMAND(ID_CHARSET_EBCDIC, OnCharsetEbcdic) ON_UPDATE_COMMAND_UI(ID_CHARSET_EBCDIC, OnUpdateCharsetEbcdic) ON_COMMAND(ID_CONTROL_NONE, OnControlNone) ON_UPDATE_COMMAND_UI(ID_CONTROL_NONE, OnUpdateControlNone) ON_COMMAND(ID_CONTROL_ALPHA, OnControlAlpha) ON_UPDATE_COMMAND_UI(ID_CONTROL_ALPHA, OnUpdateControlAlpha) ON_COMMAND(ID_CONTROL_C, OnControlC) ON_UPDATE_COMMAND_UI(ID_CONTROL_C, OnUpdateControlC) ON_COMMAND(ID_TOGGLE_ENDIAN, OnToggleEndian) ON_COMMAND(ID_BIG_ENDIAN, OnBigEndian) ON_COMMAND(ID_LITTLE_ENDIAN, OnLittleEndian) ON_UPDATE_COMMAND_UI(ID_TOGGLE_ENDIAN, OnUpdateToggleEndian) ON_UPDATE_COMMAND_UI(ID_BIG_ENDIAN, OnUpdateBigEndian) ON_UPDATE_COMMAND_UI(ID_LITTLE_ENDIAN, OnUpdateLittleEndian) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview) ON_COMMAND(ID_JUMP_HEX_ADDR, OnJumpHexAddr) // ON_COMMAND(ID_SEARCH_START, OnSearch) // Handle message from BCG search combo ON_COMMAND(ID_JUMP_HEX_START, OnJumpHex) // Handle message from BCG hex combo ON_COMMAND(ID_JUMP_DEC_START, OnJumpDec) // Handle message from BCG dec combo ON_COMMAND(ID_SELECT_LINE, OnSelectLine) ON_COMMAND(IDC_FONTNAME, OnFontName) ON_UPDATE_COMMAND_UI(IDC_FONTNAME, OnUpdateFontName) ON_COMMAND(IDC_FONTSIZE, OnFontSize) ON_UPDATE_COMMAND_UI(IDC_FONTSIZE, OnUpdateFontSize) ON_CBN_SELENDOK(IDC_FONTNAME, OnFontName) ON_CBN_SELENDOK(IDC_FONTSIZE, OnFontSize) ON_COMMAND(ID_ZLIB_COMPRESS, OnCompress) ON_UPDATE_COMMAND_UI(ID_ZLIB_COMPRESS, OnUpdateSelNZ) ON_COMMAND(ID_ZLIB_DECOMPRESS, OnDecompress) ON_UPDATE_COMMAND_UI(ID_ZLIB_DECOMPRESS, OnUpdateSelNZ) ON_COMMAND(ID_MD5, OnMd5) ON_UPDATE_COMMAND_UI(ID_MD5, OnUpdateByteNZ) ON_COMMAND(ID_SHA1, OnSha1) ON_UPDATE_COMMAND_UI(ID_SHA1, OnUpdateByteNZ) ON_COMMAND(ID_UPPERCASE, OnUppercase) ON_UPDATE_COMMAND_UI(ID_UPPERCASE, OnUpdateConvert) ON_COMMAND(ID_LOWERCASE, OnLowercase) ON_UPDATE_COMMAND_UI(ID_LOWERCASE, OnUpdateConvert) ON_COMMAND(ID_DFFD_HIDE, OnDffdHide) ON_UPDATE_COMMAND_UI(ID_DFFD_HIDE, OnUpdateDffdHide) ON_COMMAND(ID_DFFD_SPLIT, OnDffdSplit) ON_UPDATE_COMMAND_UI(ID_DFFD_SPLIT, OnUpdateDffdSplit) ON_COMMAND(ID_DFFD_TAB, OnDffdTab) ON_UPDATE_COMMAND_UI(ID_DFFD_TAB, OnUpdateDffdTab) ON_COMMAND(ID_AERIAL_HIDE, OnAerialHide) ON_UPDATE_COMMAND_UI(ID_AERIAL_HIDE, OnUpdateAerialHide) ON_COMMAND(ID_AERIAL_SPLIT, OnAerialSplit) ON_UPDATE_COMMAND_UI(ID_AERIAL_SPLIT, OnUpdateAerialSplit) ON_COMMAND(ID_AERIAL_TAB, OnAerialTab) ON_UPDATE_COMMAND_UI(ID_AERIAL_TAB, OnUpdateAerialTab) ON_COMMAND(ID_COMP_HIDE, OnCompHide) ON_UPDATE_COMMAND_UI(ID_COMP_HIDE, OnUpdateCompHide) ON_COMMAND(ID_COMP_SPLIT, OnCompSplit) ON_UPDATE_COMMAND_UI(ID_COMP_SPLIT, OnUpdateCompSplit) ON_COMMAND(ID_COMP_TAB, OnCompTab) ON_UPDATE_COMMAND_UI(ID_COMP_TAB, OnUpdateCompTab) ON_COMMAND(ID_HIGHLIGHT_SELECT, OnHighlightSelect) //ON_WM_TIMER() ON_COMMAND(ID_VIEWTEST, OnViewtest) ON_WM_SYSCOLORCHANGE() ON_MESSAGE(WM_MOUSEHOVER, OnMouseHover) ON_MESSAGE(WM_MOUSELEAVE, OnMouseLeave) ON_COMMAND(ID_SCHEME, OnOptScheme) ON_CBN_SELENDOK(ID_SCHEME, OnSelScheme) ON_UPDATE_COMMAND_UI(ID_SCHEME, OnUpdateScheme) ON_COMMAND(ID_SCHEME_US, OnOptScheme) ON_CBN_SELENDOK(ID_SCHEME_US, OnSelScheme) ON_UPDATE_COMMAND_UI(ID_SCHEME_US, OnUpdateScheme) ON_COMMAND(ID_COMP_FIRST, OnCompFirst) ON_COMMAND(ID_COMP_PREV, OnCompPrev) ON_COMMAND(ID_COMP_NEXT, OnCompNext) ON_COMMAND(ID_COMP_LAST, OnCompLast) ON_UPDATE_COMMAND_UI(ID_COMP_FIRST, OnUpdateCompFirst) ON_UPDATE_COMMAND_UI(ID_COMP_PREV, OnUpdateCompPrev) ON_UPDATE_COMMAND_UI(ID_COMP_NEXT, OnUpdateCompNext) ON_UPDATE_COMMAND_UI(ID_COMP_LAST, OnUpdateCompLast) ON_COMMAND(ID_COMP_ALL_FIRST, OnCompAllFirst) ON_COMMAND(ID_COMP_ALL_PREV, OnCompAllPrev) ON_COMMAND(ID_COMP_ALL_NEXT, OnCompAllNext) ON_COMMAND(ID_COMP_ALL_LAST, OnCompAllLast) ON_UPDATE_COMMAND_UI(ID_COMP_ALL_FIRST, OnUpdateCompAllFirst) ON_UPDATE_COMMAND_UI(ID_COMP_ALL_PREV, OnUpdateCompAllPrev) ON_UPDATE_COMMAND_UI(ID_COMP_ALL_NEXT, OnUpdateCompAllNext) ON_UPDATE_COMMAND_UI(ID_COMP_ALL_LAST, OnUpdateCompAllLast) ON_COMMAND(ID_COMP_AUTO_SYNC, OnCompAutoSync) ON_UPDATE_COMMAND_UI(ID_COMP_AUTO_SYNC, OnUpdateCompAutoSync) ON_COMMAND(ID_COMP_AUTO_SCROLL, OnCompAutoScroll) ON_UPDATE_COMMAND_UI(ID_COMP_AUTO_SCROLL, OnUpdateCompAutoScroll) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CHexEditView construction/destruction CHexEditView::CHexEditView() { expr_.SetView(this); text_height_ = 0; // While text_height_ == 0 none of the display settings have been calculated pdfv_ = NULL; pav_ = NULL; pcv_ = NULL; CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); disp_state_ = previous_state_ = 0; resize_start_addr_ = resize_curr_scroll_ = -1; pfont_ = NULL; pbrush_ = NULL; print_font_ = NULL; // Set up opening display based on global options rowsize_ = aa->open_rowsize_; real_offset_ = offset_ = aa->open_offset_; if (real_offset_ >= rowsize_) offset_ = rowsize_ - 1; // In case soemone fiddled with the settings group_by_ = aa->open_group_by_; ASSERT(theApp.open_disp_state_ != -1); disp_state_ = theApp.open_disp_state_; bg_col_ = -1; hl_set_.clear(); mark_ = 0L; // Mark initially at start of file if (!display_.hex_area) display_.edit_char = display_.mark_char = TRUE; // No hex area so must use char else display_.edit_char = display_.mark_char = FALSE; // Caret init. in hex not char area mouse_addr_ = -1; // Only used when theApp.hl_mouse_ is on mouse_down_ = false; drag_bookmark_ = -1; needs_refresh_ = false; needs_hscroll_ = false; needs_vscroll_ = false; memset((void *)&lf_, '\0', sizeof(lf_)); _tcscpy(lf_.lfFaceName, _T("Courier")); // A nice fixed (no-proportional) font lf_.lfHeight = 16; lf_.lfCharSet = ANSI_CHARSET; // Only allow ANSI character set fonts oem_lf_ = lf_; _tcscpy(oem_lf_.lfFaceName, _T("Terminal")); // The only certain OEM font? oem_lf_.lfHeight = 18; oem_lf_.lfCharSet = OEM_CHARSET; // Only allow OEM/IBM character set fonts search_length_ = 0; last_tip_addr_ = -1; tip_show_bookmark_ = true; tip_show_error_ = true; #ifndef NDEBUG // Make default capacity for undo_ vector small to force reallocation sooner. // This increases likelihood of catching bugs related to reallocation. undo_.reserve(4); #else undo_.reserve(1024); #endif #ifdef RULER_ADJUST adjusting_rowsize_ = adjusting_offset_ = adjusting_group_by_ = -1; #endif errors_mentioned_ = false; } CHexEditView::~CHexEditView() { if (pfont_ != NULL) delete pfont_; if (pbrush_ != NULL) delete pbrush_; } BOOL CHexEditView::PreCreateWindow(CREATESTRUCT& cs) { BOOL retval = CScrView::PreCreateWindow(cs); // Get the create context so we can find out if this window is // being created via Window/New and the frame/view it's cloned from CCreateContext *pContext = (CCreateContext *)cs.lpCreateParams; if (pContext != NULL && pContext->m_pCurrentFrame != NULL) { // Must have been created via Window/New (ID_WINDOW_NEW) ASSERT_KINDOF(CMDIChildWnd, pContext->m_pCurrentFrame); // We have the frame so get the view within it CHexEditView *pView = (CHexEditView *)pContext->m_pCurrentFrame->GetActiveView(); if (pView->IsKindOf(RUNTIME_CLASS(CCompareView))) pView = ((CCompareView *)pView)->phev_; else if (pView->IsKindOf(RUNTIME_CLASS(CAerialView))) pView = ((CAerialView *)pView)->phev_; else if (pView->IsKindOf(RUNTIME_CLASS(CDataFormatView))) pView = ((CDataFormatView *)pView)->phev_; ASSERT_KINDOF(CHexEditView, pView); // Make this view's undo stack the same as clone view undo_ = pView->undo_; // Flag any changes as not being made in this view std::vector <view_undo>::iterator pu; for (pu = undo_.begin(); pu != undo_.end(); ++pu) { if (pu->utype == undo_change) pu->flag = FALSE; } } return retval; } void CHexEditView::OnInitialUpdate() { FILE_ADDRESS start_addr = 0; FILE_ADDRESS end_addr = 0; CHexEditDoc *pDoc = GetDocument(); CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); print_map_mode_ = MM_HIENGLISH; split_width_d_ = split_width_a_ = split_width_c_ = -1; // Get options for the window from file settings in CHexFileList CHexFileList *pfl = aa->GetFileList(); int recent_file_index = -1; if (pDoc->pfile1_ != NULL) recent_file_index = pfl->GetIndex(pDoc->pfile1_->GetFilePath()); #ifdef TEST_CLIPPING bdr_top_ = bdr_bottom_ = 80; bdr_left_ = 120; bdr_right_ = 40; #endif if (recent_file_index != -1) { CString ss = pfl->GetData(recent_file_index, CHexFileList::DFFDVIEW); if (ss.IsEmpty()) split_width_d_ = theApp.dffdview_; else split_width_d_ = atoi(ss); ss = pfl->GetData(recent_file_index, CHexFileList::AERIALVIEW); if (ss.IsEmpty()) split_width_a_ = theApp.aerialview_; else split_width_a_ = atoi(ss); ss = pfl->GetData(recent_file_index, CHexFileList::COMPVIEW); if (ss.IsEmpty()) split_width_c_ = theApp.compview_; else split_width_c_ = atoi(ss); disp_state_ = atoi(pfl->GetData(recent_file_index, CHexFileList::DISPLAY)); SetVertBufferZone(atoi(pfl->GetData(recent_file_index, CHexFileList::VERT_BUFFER_ZONE))); // Get the colour scheme, if none try to find one based on file extension, otherwise // let set_colours() handle it using the default scheme for the current char set. scheme_name_ = pfl->GetData(recent_file_index, CHexFileList::SCHEME); if (scheme_name_.IsEmpty()) { // Get file extension and change "." to "_" ss = pDoc->GetFileName(); if (ss.ReverseFind('.') == -1) ss = "_"; else ss = CString("_") + ss.Mid(ss.ReverseFind('.')+1); // If there is a scheme of this name make it the scheme to use std::vector<CScheme>::const_iterator ps; for (ps = theApp.scheme_.begin(); ps != theApp.scheme_.end(); ++ps) { if (ss.CompareNoCase(ps->name_) == 0) { scheme_name_ = ps->name_; break; } } } set_colours(); rowsize_ = atoi(pfl->GetData(recent_file_index, CHexFileList::COLUMNS)); real_offset_ = offset_ = atoi(pfl->GetData(recent_file_index, CHexFileList::OFFSET)); if (real_offset_ >= rowsize_) offset_ = rowsize_ - 1; // In case soemone fiddled with the settings group_by_ = atoi(pfl->GetData(recent_file_index, CHexFileList::GROUPING)); start_addr = _atoi64(pfl->GetData(recent_file_index, CHexFileList::SELSTART)); end_addr = _atoi64(pfl->GetData(recent_file_index, CHexFileList::SELEND)); if (start_addr < 0 || start_addr > pDoc->length()) start_addr = 0; if (end_addr < start_addr || end_addr > pDoc->length()) end_addr = start_addr; mark_ = _atoi64(pfl->GetData(recent_file_index, CHexFileList::MARK)); if (mark_ < 0 || mark_ > pDoc->length()) mark_ = 0; ASSERT(display_.hex_area || display_.edit_char); // if no hex area we must be editing chars // Get saved font info strncpy(lf_.lfFaceName, pfl->GetData(recent_file_index, CHexFileList::FONT), LF_FACESIZE-1); lf_.lfFaceName[LF_FACESIZE-1] = '\0'; lf_.lfHeight = atoi(pfl->GetData(recent_file_index, CHexFileList::HEIGHT)); strncpy(oem_lf_.lfFaceName, pfl->GetData(recent_file_index, CHexFileList::OEMFONT), LF_FACESIZE-1); oem_lf_.lfFaceName[LF_FACESIZE-1] = '\0'; oem_lf_.lfHeight = atoi(pfl->GetData(recent_file_index, CHexFileList::OEMHEIGHT)); std::istringstream strstr((const char *)pfl->GetData(recent_file_index, CHexFileList::HIGHLIGHTS)); strstr >> hl_set_; CRect newpos; newpos.top = atoi(pfl->GetData(recent_file_index, CHexFileList::TOP)); newpos.left = atoi(pfl->GetData(recent_file_index, CHexFileList::LEFT)); newpos.bottom = atoi(pfl->GetData(recent_file_index, CHexFileList::BOTTOM)); newpos.right = atoi(pfl->GetData(recent_file_index, CHexFileList::RIGHT)); // Make sure that window size seems reasonable if (newpos.top != -30000 && newpos.left != -30000 && newpos.top < newpos.bottom && newpos.left < newpos.right ) { WINDOWPLACEMENT wp; wp.length = sizeof(wp); wp.flags = 0; wp.showCmd = atoi(pfl->GetData(recent_file_index, CHexFileList::CMD)); wp.ptMinPosition = CPoint(-1,-1); wp.ptMaxPosition = CPoint(-1,-1); // If this window has sibling view this window was presumably created // using Window/New - make sure its not in the same place as its sibling(s). POSITION pos = pDoc->GetFirstViewPosition(); while (pos != NULL) { WINDOWPLACEMENT frame_wp; frame_wp.length = sizeof(frame_wp); CView *pv = pDoc->GetNextView(pos); if (pv->IsKindOf(RUNTIME_CLASS(CHexEditView))) { ASSERT(pv != NULL && ((CHexEditView *)pv)->GetFrame() != NULL); if (pv != this && ((CHexEditView *)pv)->GetFrame()->GetWindowPlacement(&frame_wp)) { // If the top left corners are about the same move the // new window down and right a bit. if (abs(newpos.top - frame_wp.rcNormalPosition.top) < 20 && abs(newpos.left - frame_wp.rcNormalPosition.left) < 20) { newpos += CSize(30, 30); } } } } // Check that new position is not completely off the left, right or bottom, // and that the top title bar is still visible to allow dragging. CRect rr; ASSERT(GetFrame() != NULL && GetFrame()->GetParent() != NULL); GetFrame()->GetParent()->GetClientRect(&rr); if (newpos.left > rr.right-20) { newpos.left = rr.right - (newpos.right - newpos.left); newpos.right = rr.right; } if (newpos.right < 20) { newpos.right -= newpos.left; newpos.left = 0; } if (newpos.top > rr.bottom-20) { newpos.top = rr.bottom - (newpos.bottom - newpos.top); newpos.bottom = rr.bottom; } if (newpos.top < -20) { newpos.bottom -= newpos.top; newpos.top =0; } wp.rcNormalPosition = newpos; if (wp.showCmd == SW_SHOWMAXIMIZED) wp.flags = WPF_RESTORETOMAXIMIZED; GetFrame()->SetWindowPlacement(&wp); } else if (atoi(pfl->GetData(recent_file_index, CHexFileList::CMD)) == SW_SHOWMAXIMIZED) { WINDOWPLACEMENT wp; ASSERT(GetFrame() != NULL); GetFrame()->GetWindowPlacement(&wp); wp.showCmd = SW_SHOWMAXIMIZED; GetFrame()->SetWindowPlacement(&wp); } // Set horiz size, vert size, and scroll posn if (display_.vert_display || display_.char_area) SetSize(CSize(char_pos(rowsize_-1)+text_width_w_+text_width_w_/2+1, -1)); else { ASSERT(display_.hex_area); display_.hex_area = TRUE; // defensive SetSize(CSize(hex_pos(rowsize_-1)+2*text_width_+text_width_/2+1, -1)); } if (display_.vert_display) SetTSize(CSizeAp(-1, ((GetDocument()->length() + offset_)/rowsize_ + 1)*3)); // 3 rows of text else SetTSize(CSizeAp(-1, (GetDocument()->length() + offset_)/rowsize_ + 1)); SetScroll(CPointAp(0, _atoi64(pfl->GetData(recent_file_index, CHexFileList::POS)))); } else { ASSERT(pDoc->pfile1_ == NULL); // we should only get here (now) if not yet saved to disk split_width_d_ = theApp.dffdview_; split_width_a_ = theApp.aerialview_; split_width_c_ = theApp.compview_; // Force colour scheme based on char set (not file extension as we don't have one) scheme_name_ = ""; set_colours(); if (aa->open_max_) { WINDOWPLACEMENT wp; ASSERT(GetFrame() != NULL); GetFrame()->GetWindowPlacement(&wp); wp.showCmd = SW_SHOWMAXIMIZED; GetFrame()->SetWindowPlacement(&wp); } // Set the normal and OEM graphic font if (aa->open_plf_ != NULL) { lf_ = *aa->open_plf_; } if (aa->open_oem_plf_ != NULL) { oem_lf_ = *aa->open_oem_plf_; } } // Make sure that something is displayed in the address area if (!display_.decimal_addr && !display_.hex_addr && !display_.line_nums) { display_.decimal_addr = display_.dec_addr; display_.hex_addr = !display_.dec_addr; } // if (pfl->GetVersion() < 3) // this is not really sufficient if the file is not actually opened since the recent file list gets written back with same DISPLAY value (but new version number) { // In version 2 files there were 3 separate flags (eg when EBCDIC flag on other 2 flags ignored). // Now the 3 bits are used together to indicate char set but we allow for other bit patterns. if (display_.char_set == 2) display_.char_set = CHARSET_ASCII; // ASCII: 0/2 -> 0 else if (display_.char_set > 4) display_.char_set = CHARSET_EBCDIC; // EBCDIC: 4/5/6/7 -> 4 } if (display_.char_set == 7) // unused value display_.char_set = CHARSET_EBCDIC; // EBCDIC: 7 -> 4 // This is just here as a workaround for a small problem with MDItabs - when // the tabs are at the top then the tab bar gets slightly higher when the first // file is opened which mucks up a small part at the top of the MDI area. static bool first_time_here = true; if (first_time_here) { ((CMainFrame *)AfxGetMainWnd())->redraw_background(); first_time_here = false; } if (!display_.edit_char) SetHorzBufferZone(2); // Convert font sizes to logical units { CPoint convert(0, lf_.lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.DPtoLP(&convert); // Get screen font size in logical units lf_.lfHeight = convert.y; } { CPoint convert(0, oem_lf_.lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.DPtoLP(&convert); // Get screen font size in logical units oem_lf_.lfHeight = convert.y; } // This can't be done till document available (ie. not in constructor) if (GetDocument()->read_only()) display_.readonly = TRUE; // Set control bar buttons to display state of current options // load_bitmaps(); CScrView::SetMapMode(MM_TEXT); ASSERT(pfont_ == NULL); pfont_ = new CFont; pfont_->CreateFontIndirect(display_.FontRequired() == FONT_OEM ? &oem_lf_ : &lf_); SetFont(pfont_); // Create brush that is XORed with selection when focus lost. (This // gives a more subtle grey selection) when window does not have focus.) pbrush_ = new CBrush(RGB(192, 192, 192)); SetBrush(pbrush_); // Reopen template view ASSERT(pdfv_ == NULL); switch (split_width_d_) { case 0: // When last open template view was hidden so do nothing split_width_d_ = -1; break; case 2: // Last opened in tab view split_width_d_ = -1; DoDffdTab(); break; default: // Last opened in splitter DoDffdSplit(); break; } // Reopen aerial view ASSERT(pav_ == NULL); switch (split_width_a_) { case 0: // When last open template view was hidden so do nothing split_width_a_ = -1; break; case 2: // Last opened in tab view split_width_a_ = -1; DoAerialTab(false); // no init as that seems to be done by MFC break; default: // Last opened in splitter DoAerialSplit(false); // no init as that seems to be done by MFC break; } // Reopen compare view ASSERT(pcv_ == NULL); switch (split_width_c_) { case 0: // When last open template view was hidden so do nothing split_width_c_ = -1; break; case 2: // Last opened in tab view split_width_c_ = -1; DoCompTab(false); // no WM_INITIALUPDATE needed here (done by MFC) break; default: // Last opened in splitter DoCompSplit(false); // no WM_INITIALUPDATE needed here (done by MFC) break; } CScrView::OnInitialUpdate(); #if 0 if (recent_file_index != -1) SetScroll(CPointAp(0,pfl->scroll_[recent_file_index])); // What's the point of an empty read-only file if (GetDocument()->length() == 0 && !GetDocument()->read_only()) display_.readonly = display_.overtype = FALSE; #endif if (aa->large_cursor_) BlockCaret(); else LineCaret(); if (!display_.overtype || GetDocument()->length() > 0) { CaretMode(); SetSel(addr2pos(start_addr), addr2pos(end_addr)); show_prop(); show_calc(); show_pos(); } ValidateScroll(GetScroll()); // Save nav info in case we need to create a nav pt here nav_start_ = start_addr; nav_end_ = end_addr; nav_scroll_ = (GetScroll().y/line_height_)*rowsize_ - offset_; theApp.navman_.Add("Opened", get_info(), this, nav_start_, nav_end_, nav_scroll_); nav_moves_ = 0; } // OnInitialUpdate // Update our options to the CHexFileList void CHexEditView::StoreOptions() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CHexFileList *pfl = ((CHexEditApp *)AfxGetApp())->GetFileList(); if (GetDocument()->pfile1_ == NULL) return; // Not in the list if there's no file int ii = pfl->GetIndex(GetDocument()->pfile1_->GetFilePath()); if (ii != -1) { // Found in the list so update all the values; WINDOWPLACEMENT wp; ASSERT(GetFrame() != NULL); if (GetFrame()->GetWindowPlacement(&wp)) { pfl->SetData(ii, CHexFileList::CMD, wp.showCmd); pfl->SetData(ii, CHexFileList::TOP, wp.rcNormalPosition.top); pfl->SetData(ii, CHexFileList::LEFT, wp.rcNormalPosition.left); pfl->SetData(ii, CHexFileList::BOTTOM, wp.rcNormalPosition.bottom); pfl->SetData(ii, CHexFileList::RIGHT, wp.rcNormalPosition.right); } else { pfl->SetData(ii, CHexFileList::CMD, SW_SHOWNORMAL); pfl->SetData(ii, CHexFileList::TOP, -30000); pfl->SetData(ii, CHexFileList::LEFT, -30000); pfl->SetData(ii, CHexFileList::BOTTOM, -30000); pfl->SetData(ii, CHexFileList::RIGHT, -30000); } pfl->SetData(ii, CHexFileList::COLUMNS, rowsize_); pfl->SetData(ii, CHexFileList::GROUPING, group_by_); pfl->SetData(ii, CHexFileList::OFFSET, offset_); pfl->SetData(ii, CHexFileList::SCHEME, scheme_name_); pfl->SetData(ii, CHexFileList::FONT, lf_.lfFaceName); pfl->SetData(ii, CHexFileList::HEIGHT, lf_.lfHeight); pfl->SetData(ii, CHexFileList::OEMFONT, oem_lf_.lfFaceName); pfl->SetData(ii, CHexFileList::OEMHEIGHT, oem_lf_.lfHeight); pfl->SetData(ii, CHexFileList::DISPLAY, disp_state_); pfl->SetData(ii, CHexFileList::DOC_FLAGS, GetDocument()->doc_flags()); pfl->SetData(ii, CHexFileList::FORMAT, GetDocument()->GetFormatFileName()); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pfl->SetData(ii, CHexFileList::SELSTART, start_addr); pfl->SetData(ii, CHexFileList::SELEND, end_addr); pfl->SetData(ii, CHexFileList::POS, GetScroll().y); pfl->SetData(ii, CHexFileList::MARK, mark_); std::ostringstream strstr; strstr << hl_set_; pfl->SetData(ii, CHexFileList::HIGHLIGHTS, strstr.str().c_str()); pfl->SetData(ii, CHexFileList::EDIT_TIME, __int64(GetDocument()->edit_time_.elapsed())); pfl->SetData(ii, CHexFileList::VIEW_TIME, __int64(GetDocument()->view_time_.elapsed())); pfl->SetData(ii, CHexFileList::VERT_BUFFER_ZONE, __int64(GetVertBufferZone())); if (pdfv_ == NULL) { pfl->SetData(ii, CHexFileList::DFFDVIEW, "0"); pfl->SetData(ii, CHexFileList::DFFDWIDTHS, ""); } else { int width = 2; // assume tab view used ASSERT(GetFrame()->splitter_.m_hWnd != 0); int snum_d = GetFrame()->splitter_.FindViewColumn(pdfv_->GetSafeHwnd()); int dummy; // ignored since we don't care about the height if (snum_d > -1) { GetFrame()->splitter_.GetColumnInfo(snum_d, width, dummy); if (width < 10) width = 10; // Make sure it is not too narrow and reserve values 0-9 (2 = tab view) } pfl->SetData(ii, CHexFileList::DFFDVIEW, __int64(width)); pfl->SetData(ii, CHexFileList::DFFDWIDTHS, pdfv_->GetColWidths()); } // DFFDVIEW data is now 0 (none), 2 (tab). or 10+ (splitter width) if (pav_ == NULL) { pfl->SetData(ii, CHexFileList::AERIALVIEW, "0"); } else { int width = 2; // assume tab view used ASSERT(GetFrame()->splitter_.m_hWnd != 0); int snum_a = GetFrame()->splitter_.FindViewColumn(pav_->GetSafeHwnd()); int dummy; // ignored since we don't care about the height if (snum_a > -1) { GetFrame()->splitter_.GetColumnInfo(snum_a, width, dummy); if (width < 10) width = 10; // Make sure it is not too narrow and reserve values 0-9 (2 = tab view) } pfl->SetData(ii, CHexFileList::AERIALVIEW, __int64(width)); } // AERIALVIEW data is now 0 (none), 2 (tab). or 10+ (splitter width) if (pav_ != NULL) pav_->StoreOptions(pfl, ii); if (pcv_ == NULL) { pfl->SetData(ii, CHexFileList::COMPVIEW, "0"); } else { int width = 2; // assume tab view used ASSERT(GetFrame()->splitter_.m_hWnd != 0); int snum_c = GetFrame()->splitter_.FindViewColumn(pcv_->GetSafeHwnd()); int dummy; // ignored since we don't care about the height if (snum_c > -1) { GetFrame()->splitter_.GetColumnInfo(snum_c, width, dummy); if (width < 10) width = 10; // Make sure it is not too narrow and reserve values 0-9 (2 = tab view) } pfl->SetData(ii, CHexFileList::COMPVIEW, __int64(width)); pfl->SetData(ii, CHexFileList::COMPFILENAME, GetDocument()->GetCompFileName()); } } } void CHexEditView::SetScheme(const char *name) { if (scheme_name_ == name) return; // no change to the scheme CString previous_name = scheme_name_; scheme_name_ = name; if (set_colours()) { // Scheme changed so save for undo/macros undo_.push_back(view_undo(undo_scheme)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = previous_name; theApp.SaveToMacro(km_scheme, name); } else { // Scheme was not found (presumably in macro playback) ASSERT(theApp.playing_); CString mess; mess.Format("The color scheme \"%s\" was not found.\n", name); AfxMessageBox(mess); theApp.mac_error_ = 1; scheme_name_ = previous_name; } DoInvalidate(); } // When docked vertically the colour scheme drop down combo (ID_SCHEME) becomes a command // button which when clicked invokes this. We just open the Colour page of the Options dialog. void CHexEditView::OnOptScheme() { theApp.display_options(COLOUR_OPTIONS_PAGE, TRUE); } // Handle selection of a new scheme from colour scheme drop down combo (ID_SCHEME). void CHexEditView::OnSelScheme() { CMFCToolBarComboBoxButton * ptbcbb = NULL; // Get and search all ID_SCHEME toolbar controls (there may be more than one on different toolbars) CObList listButtons; if (CMFCToolBar::GetCommandButtons(::IsUs() ? ID_SCHEME_US : ID_SCHEME, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); posCombo != NULL;) { CMFCToolBarComboBoxButton* pp = DYNAMIC_DOWNCAST(CMFCToolBarComboBoxButton, listButtons.GetNext(posCombo)); if (pp != NULL && CMFCToolBar::IsLastCommandFromButton(pp)) // check that this one actually was the one used { ptbcbb = pp; break; } } } if (ptbcbb != NULL) { ASSERT_VALID(ptbcbb); CString name = CString(ptbcbb->GetItem()); // GetItem(-1) will return the selected one if (name.Right(3) == "...") theApp.display_options(COLOUR_OPTIONS_PAGE, TRUE); else if (!name.IsEmpty() && name[0] != '-') SetScheme(name); } } // Update the colour scheme combo (ID_SCHEME). We need to check that the current list of schemes // matches the combo list AND that the scheme used in this view is the selected one. void CHexEditView::OnUpdateScheme(CCmdUI* pCmdUI) { // First check that it is a scheme combo box if (pCmdUI->m_pOther != NULL && pCmdUI->m_pOther->GetDlgCtrlID() == (::IsUs() ? ID_SCHEME_US : ID_SCHEME)) { // Find the owning CMFCToolBarComboBoxButton of the combo box CMFCToolBarComboBoxButton * ptbcbb = NULL; CObList listButtons; if (CMFCToolBar::GetCommandButtons(::IsUs() ? ID_SCHEME_US : ID_SCHEME, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); posCombo != NULL;) { CMFCToolBarComboBoxButton* pp = DYNAMIC_DOWNCAST(CMFCToolBarComboBoxButton, listButtons.GetNext(posCombo)); ASSERT(pp != NULL && pp->GetComboBox() != NULL); if (pp != NULL && pp->GetComboBox() != NULL && pp->GetComboBox()->m_hWnd == pCmdUI->m_pOther->m_hWnd) { ptbcbb = pp; break; } } } // If we found it and it's not in a dropped state if (ptbcbb != NULL && !ptbcbb->GetComboBox()->GetDroppedState()) { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); // Work out the current scheme of the active view and get vector of scheme names std::vector<CString> scheme_names; int current_scheme = -1; // Build list backwards as ComboNeedsUpdate() assumes top of list is at bottom of vector scheme_names.push_back(CString(::IsUs() ? "Modify Colors..." : "Modify Colours...")); scheme_names.push_back(CString('-', 50)); // Add a divider line above the "Modify Colours" line for (int ii = theApp.scheme_.size(); ii > 0; ii--) { scheme_names.push_back(theApp.scheme_[ii-1].name_); if (theApp.scheme_[ii-1].name_ == GetSchemeName()) current_scheme = ii - 1; } // Make sure the list of schemes in the combo matches the current schemes if (mm->ComboNeedsUpdate(scheme_names, ptbcbb->GetComboBox())) { int max_str = 0; // Max width of all the strings added so far CClientDC dc(ptbcbb->GetComboBox()); int nSave = dc.SaveDC(); dc.SelectObject(ptbcbb->GetComboBox()->GetFont()); ptbcbb->RemoveAllItems(); for (std::vector<CString>::reverse_iterator ps = scheme_names.rbegin(); ps != scheme_names.rend(); ++ps) { if ((*ps)[0] != '-') max_str = __max(max_str, dc.GetTextExtent(*ps).cx); // Add the string to the list ptbcbb->AddItem(*ps); } // Add space for margin and possible scrollbar //max_str += dc.GetTextExtent("0").cx + ::GetSystemMetrics(SM_CXVSCROLL); max_str += ::GetSystemMetrics(SM_CXVSCROLL); ptbcbb->GetComboBox()->SetDroppedWidth(__min(max_str, 640)); dc.RestoreDC(nSave); } // Make sure the selected scheme in the combo matches the scheme in use in this view if (ptbcbb->GetCurSel() != current_scheme) { ptbcbb->SelectItem(current_scheme); // We need to invalidate the button so it show the correct scheme CMFCToolBar *ptb = DYNAMIC_DOWNCAST(CMFCToolBar, ptbcbb->GetComboBox()->GetParent()); int idx = ptb->CommandToIndex(::IsUs() ? ID_SCHEME_US : ID_SCHEME); ptb->InvalidateButton(idx); } } } } // Gets all colour info from the app's scheme vector based on the current scheme_name_. // For efficiency it builds the "kala" array which contains a COLORREF for every byte value. BOOL CHexEditView::set_colours() { if (scheme_name_.IsEmpty()) scheme_name_ = theApp.open_scheme_name_; // Use default BOOL retval = TRUE; std::vector<CScheme>::const_iterator ps; ASSERT(theApp.scheme_.size() > 3); // First find the scheme for (ps = theApp.scheme_.begin(); ps != theApp.scheme_.end(); ++ps) { if (ps->name_ == scheme_name_) break; } // If the scheme was not found use the standard one matching selected options if (ps == theApp.scheme_.end()) { // Current scheme name is not found so set to something OK and return error if (display_.char_set == CHARSET_EBCDIC) ps = theApp.scheme_.begin()+3; else if (display_.char_set == CHARSET_OEM) ps = theApp.scheme_.begin()+2; else if (display_.char_set == CHARSET_ANSI) ps = theApp.scheme_.begin()+1; else ps = theApp.scheme_.begin(); scheme_name_ = ps->name_; retval = FALSE; } // Get colours from scheme, where -1 means use default (Automatic) colour bg_col_ = ps->bg_col_ == -1 ? ::GetSysColor(COLOR_WINDOW) : ps->bg_col_; mark_col_ = ps->mark_col_ == -1 ? RGB(224, 224, 224) : ps->mark_col_; hi_col_ = ps->hi_col_ == -1 ? RGB(255, 255, 0) : ps->hi_col_; // yellow bm_col_ = ps->bm_col_ == -1 ? RGB(160, 192, 255) : ps->bm_col_; search_col_ = ps->search_col_ == -1 ? RGB(160, 255, 224) : ps->search_col_; addr_bg_col_ = ps->addr_bg_col_ == -1 ? ::tone_down(::GetSysColor(COLOR_INACTIVEBORDER), bg_col_, 0.5) : ps->addr_bg_col_; // Getting change tracking colour and make a version closer to the background colour in luminance // trk_col_ is used to underline replacements, trk_bg_col_ is used as background for insertions trk_col_ = ps->trk_col_ == -1 ? RGB(255, 128, 0) : ps->trk_col_; // orange-red trk_bg_col_ = ::tone_down(trk_col_, bg_col_); comp_col_ = ps->comp_col_ == -1 ? RGB(255, 0, 128) : ps->comp_col_; // purple comp_bg_col_ = ::tone_down(comp_col_, bg_col_); sector_col_ = ps->sector_col_ == -1 ? RGB(255, 160, 128) : ps->sector_col_; // pinkish orange sector_bg_col_ = ::tone_down(sector_col_, bg_col_); hex_addr_col_ = ps->hex_addr_col_ == -1 ? ::GetSysColor(COLOR_WINDOWTEXT) : ps->hex_addr_col_; dec_addr_col_ = ps->dec_addr_col_ == -1 ? ::GetSysColor(COLOR_WINDOWTEXT) : ps->dec_addr_col_; // Set the default text colour (used for text not specific to a range) if (ps->range_col_.size() > CColourSchemes::INDEX_LAST) text_col_ = ps->range_col_[CColourSchemes::INDEX_LAST]; // was back() else text_col_ = ::GetSysColor(COLOR_WINDOWTEXT); // no ranges at all so use windows default int ii; // Default colours to background (makes unspecified colours invisible) for (ii = 0; ii < 256; ++ii) kala[ii] = bg_col_; ASSERT(ps->range_val_.size() == ps->range_col_.size()); for (ii = ps->range_val_.size(); ii > 0; ii--) { COLORREF colour = (ps->range_col_[ii-1] == -1 ? ::GetSysColor(COLOR_WINDOWTEXT) : ps->range_col_[ii-1]); // Set colour for all in this range for (range_set<int>::const_iterator rr = ps->range_val_[ii-1].begin(); rr != ps->range_val_[ii-1].end(); ++rr) { kala[*rr] = add_contrast(colour, bg_col_); } } // Keep data format view colours in sync if (pdfv_ != NULL) { ASSERT_KINDOF(CDataFormatView, pdfv_); pdfv_->set_colours(); } if (pav_ != NULL) { ASSERT_KINDOF(CAerialView, pav_); GetDocument()->AerialChange(this); } return retval; } void CHexEditView::get_colours(COLORREF *k) { int ii; // First find the scheme in app's list of schemes std::vector<CScheme>::const_iterator ps; for (ps = theApp.scheme_.begin(); ps != theApp.scheme_.end(); ++ps) if (ps->name_ == scheme_name_) break; // If the scheme was not found use the standard one matching selected options if (ps == theApp.scheme_.end()) { // Current scheme name is not found so set to something OK and return error if (display_.char_set == CHARSET_EBCDIC) ps = theApp.scheme_.begin()+3; else if (display_.char_set == CHARSET_OEM) ps = theApp.scheme_.begin()+2; else if (display_.char_set == CHARSET_ANSI) ps = theApp.scheme_.begin()+1; else ps = theApp.scheme_.begin(); scheme_name_ = ps->name_; } // Default colours to background (ie, init. unspecified colours) for (ii = 0; ii < 256; ++ii) k[ii] = bg_col_; ASSERT(ps->range_val_.size() == ps->range_col_.size()); for (ii = ps->range_val_.size(); ii > 0; ii--) { COLORREF colour = (ps->range_col_[ii-1] == -1 ? ::GetSysColor(COLOR_WINDOWTEXT) : ps->range_col_[ii-1]); // Set colour for all in this range for (range_set<int>::const_iterator rr = ps->range_val_[ii-1].begin(); rr != ps->range_val_[ii-1].end(); ++rr) { assert(*rr < 256); k[*rr] = colour; } } } CFont *CHexEditView::SetFont(CFont *ff) { CFont *retval = CScrView::SetFont(ff); // Work out size of printer font based on the new screen font TEXTMETRIC tm; CClientDC dc(this); OnPrepareDC(&dc); // Get screen map mode/font dc.GetTextMetrics(&tm); CPoint convert(0, tm.tmHeight); dc.LPtoDP(&convert); // Convert screen font size to device units fontsize_.Format("%d", int(convert.y*72.0/dc.GetDeviceCaps(LOGPIXELSX) + 0.5)); dc.SetMapMode(print_map_mode_); dc.DPtoLP(&convert); // Get printer font size in logical units print_lfHeight_ = labs(convert.y); return retval; } // functor object used in searching hl_set_.range_. struct segment_compare { bool operator()(const range_set<FILE_ADDRESS>::segment &x, const range_set<FILE_ADDRESS>::segment &y) const { return x.sfirst < y.sfirst; } }; // These update hints are handled: // CRemoveHint: removes undo info (without undoing anything) - for when document saved // CUndoHint: undo changes up to last doc change - called prior to undoing changes // CHexHint: indicates the document has changed (including as a result of doc undo) // CBGSearchHint: indicates a background search on the doc has finished void CHexEditView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { // Check if this is a change caused by a view if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CRemoveHint))) { // Remove undo info (as opposed to actually undoing everything as below) num_entered_ = num_del_ = num_bs_ = 0; // Changes now gone from doc undo CRemoveHint *prh = dynamic_cast<CRemoveHint *>(pHint); std::vector <view_undo, allocator<view_undo> >::iterator pu; for (pu = undo_.end(); pu != undo_.begin(); pu--) if ((pu-1)->utype == undo_change) { // Remove everything up to & including the last doc change undo ASSERT((pu-1)->index == prh->index); undo_.erase(undo_.begin(), pu); break; } } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CUndoHint))) { num_entered_ = num_del_ = num_bs_ = 0; // Undo all view changes up to last doc change (no window invalidate) CUndoHint *puh = dynamic_cast<CUndoHint *>(pHint); // If this is not the view that is undoing if (puh->pview != this) { // Undo all view moves etc up to this change ASSERT(undo_.size() > 0); while (undo_.size() > 0 && undo_.back().utype != undo_change) do_undo(); ASSERT(undo_.size() > 0); ASSERT(undo_.back().index == puh->index); } } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CHexHint))) { // This hint informs the view that the document has changed with // an insertion, deletion or overtype. This may be as a result of a // document undo (if is_undo is true) // Get current selection before recalc_display changes row offsets FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); int prev_addr_width = addr_width_; // Make sure CScrView knows about any size changes if (display_.vert_display) SetTSize(CSizeAp(-1, ((GetDocument()->length() + offset_)/rowsize_ + 1)*3)); // 3 rows of text else SetTSize(CSizeAp(-1, (GetDocument()->length() + offset_)/rowsize_ + 1)); recalc_display(); // file length, hence addr_width_, may have changed CHexHint *phh = dynamic_cast<CHexHint *>(pHint); ASSERT(phh->address >= 0 && phh->address <= GetDocument()->length()); // Is this the start of a doc modification? // (phh->index == -1 if this a continued modification) if (!phh->is_undo && phh->index > -1) { // New change - save mark, caret + change on undo stack // This could be optimized to save mark and caret // only if they are moved by the change. undo_.push_back(view_undo(undo_setmark, phh->ptoo)); undo_.back().address = mark_; undo_.push_back(view_undo(undo_move, TRUE)); undo_.back().address = start_addr | (FILE_ADDRESS(row)<<62); if (start_addr != end_addr) { undo_.push_back(view_undo(undo_sel, TRUE)); undo_.back().address = end_addr; } undo_.push_back(view_undo(undo_change, TRUE)); if (phh->pview == NULL || phh->pview == this) undo_.back().flag = TRUE; else undo_.back().flag = FALSE; #ifndef NDEBUG undo_.back().index = phh->index; #endif } // Move positions of the caret and the mark if address shifted if (!phh->is_undo && (phh->utype == mod_insert || phh->utype == mod_insert_file)) { if (end_addr > phh->address) { end_addr += phh->len; if (start_addr >= phh->address) start_addr += phh->len; SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); } if (mark_ >= phh->address) mark_ += phh->len; } else if (!phh->is_undo && (phh->utype == mod_delback || phh->utype == mod_delforw)) { // Check if current selection and the deletion intersect if (start_addr < phh->address + phh->len && end_addr > phh->address) { if (start_addr >= phh->address) // If sel start within deletion ... start_addr = phh->address; // ... move it to where chars deleted if (end_addr <= phh->address + phh->len) // If sel end within deletion ... end_addr = phh->address; // ... move it to where chars deleted else end_addr -= phh->len; // past deletion so just move it back SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); } else if (phh->address + phh->len <= start_addr) { // Deletion is before selection - just move selection backwards SetSel(addr2pos(start_addr - phh->len, row), addr2pos(end_addr - phh->len, row)); } if (mark_ > phh->address + phh->len) mark_ -= phh->len; else if (mark_ > phh->address) mark_ = phh->address; } // Fix highlights if (phh->utype == mod_insert || phh->utype == mod_insert_file) { range_set<FILE_ADDRESS>::range_t::iterator pp = lower_bound(hl_set_.range_.begin(), hl_set_.range_.end(), range_set<FILE_ADDRESS>::segment(phh->address+1, phh->address+1), segment_compare()); // If there is a highlight before insert posn check if insert is within it if (pp != hl_set_.range_.begin()) { pp --; // If bytes inserted within highlight move end if (pp->slast > phh->address) pp->slast += phh->len; ++pp; } // Move up all the following highlights for ( ; pp != hl_set_.range_.end(); ++pp) { ASSERT(pp->sfirst > phh->address); pp->sfirst += phh->len; pp->slast += phh->len; } } else if (phh->utype == mod_delback || phh->utype == mod_delforw) { // Remove highlights for deleted bytes (if any) hl_set_.erase_range(phh->address, phh->address+phh->len); range_set<FILE_ADDRESS>::range_t::iterator pp = lower_bound(hl_set_.range_.begin(), hl_set_.range_.end(), range_set<FILE_ADDRESS>::segment(phh->address, phh->address), segment_compare()); if (pp != hl_set_.range_.begin() && pp != hl_set_.range_.end()) { range_set<FILE_ADDRESS>::range_t::iterator tmp = pp; tmp--; // If previous abuts current then join them together if (pp->sfirst - phh->len <= tmp->slast) { ASSERT(pp->sfirst - phh->len == tmp->slast); tmp->slast = pp->slast - phh->len; // Remove extra list elt (and leave pp pointing to next) tmp = pp; pp++; hl_set_.range_.erase(tmp); } } // Move all the following highlights down for ( ; pp != hl_set_.range_.end(); ++pp) { ASSERT(pp->sfirst > phh->address); pp->sfirst -= phh->len; pp->slast -= phh->len; } } // Work out the addresses of the first and last line displayed CRect rct; CRectAp clip_rect; // rectangle for calcs/clipping // Calculate where the display in document GetDisplayRect(&rct); // First: get client rectangle clip_rect = ConvertFromDP(rct); // Calculate the address of the first byte of the top row of the // display and the first byte of the row just past bottom FILE_ADDRESS addr_top = (clip_rect.top/line_height_)*rowsize_ - offset_; FILE_ADDRESS addr_bot = (clip_rect.bottom/line_height_ + 1)*rowsize_ - offset_; if (addr_width_ != prev_addr_width) { // Addresses on left side are now different width so redraw everything DoInvalidate(); } else if (phh->address >= addr_bot || (phh->address + /*(signed)*/ phh->len < addr_top && (phh->utype == mod_replace || phh->utype == mod_repback))) { // Do nothing - changes after display OR before but with no address shift ; /* null statement */ } else if (phh->address < addr_top + rowsize_ && phh->utype != mod_replace && phh->utype != mod_repback) { // Whole display changes, due to address shift DoInvalidate(); } else if (phh->utype == mod_replace || phh->utype == mod_repback) { // Replace starting within display - just invalidate changed area invalidate_addr_range(phh->address, phh->address + (phh->len<1?1:phh->len)); } else if (GetDocument()->length() + ((phh->utype == mod_insert || phh->utype == mod_insert_file) ? -phh->len : +phh->len) < addr_bot) { // Insertion/deletion and previous end was within display // Just invalidate from address to bottom of display CRectAp inv(0, ((phh->address + offset_)/rowsize_) * line_height_, char_pos(rowsize_), ((addr_bot + offset_)/rowsize_) * line_height_); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); } else { // Must be insert/delete starting within the displayed area // - invalidate from first changed line to end of display invalidate_addr_range(phh->address, addr_bot); } // Remove doc change undo from undo array & do any assoc undos if (phh->is_undo && phh->pview != this) { ASSERT(undo_.size() > 0); if (undo_.size() > 0) { BOOL ptoo = undo_.back().previous_too; undo_.pop_back(); // Change already made to doc // while (ptoo) // Note changes made to allow for "previous_too" file changes while (ptoo && undo_.back().utype != undo_change) { if (undo_.size() == 0) break; // Undo anything associated to change to doc ptoo = undo_.back().previous_too; do_undo(); } } } show_prop(); show_calc(); // If mark moved and current search is relative to mark then restart bg search if (theApp.align_rel_ && mark_ != GetDocument()->base_addr_) { GetDocument()->StopSearch(); GetDocument()->base_addr_ = GetSearchBase(); GetDocument()->StartSearch(); } } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CBGSearchHint))) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CBGSearchHint *ph = dynamic_cast<CBGSearchHint *>(pHint); if (ph->finished_ == -1) { // Occurrences in area ph->start_ to ph->end_ have been added or removed // probably due to bytes being inserted or deleted at caret. // Get latest set of search occurrences ValidateScroll(GetScroll()); // Redraw area where occurrences added/removed invalidate_addr_range(ph->start_, ph->end_ + search_length_ - 1); } else if (ph->finished_) { // Background search finished // Get the display area occurrences using ValidateScroll ValidateScroll(GetScroll()); // Invalidate any areas where new search string was found std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp, pend; for (pp = search_pair_.begin(), pend = search_pair_.end(); pp != pend; ++pp) invalidate_addr_range(pp->first, pp->second); } else { // Remove all displayed search strings (but save a copy in tmp for invalidating) std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > tmp; tmp.swap(search_pair_); // Save search_pair_ in tmp (and make it empty) // Invalidate any areas where search string is currently displayed std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp, pend; for (pp = tmp.begin(), pend = tmp.end(); pp != pend; ++pp) invalidate_addr_range(pp->first, pp->second); } } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CDFFDHint))) { // Nothing required (yet?) } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CSaveStateHint))) { } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CRestoreStateHint))) { } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CBookmarkHint))) { CBookmarkHint *pbmh = dynamic_cast<CBookmarkHint *>(pHint); invalidate_addr_range(pbmh->addr_, pbmh->addr_+1); } else if (pHint != NULL && pHint->IsKindOf(RUNTIME_CLASS(CTrackHint))) { if (!display_.hide_replace || !display_.hide_insert || !display_.hide_delete) { CTrackHint *pth = dynamic_cast<CTrackHint *>(pHint); invalidate_addr_range(pth->start_, pth->end_); } } else { recalc_display(); CScrView::OnUpdate(pSender, lHint, pHint); } } void CHexEditView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView) { if (bActivate) GetDocument()->SearchThreadPriority(THREAD_PRIORITY_LOWEST); else GetDocument()->SearchThreadPriority(THREAD_PRIORITY_IDLE); CScrView::OnActivateView(bActivate, pActivateView, pDeactiveView); } // Checks if the document (file) or view (window) is read only. // If the document is read only it just displays a message and returns. // If the view is read only it gives the user the option to turn off RO. // Returns TRUE if the file/view is read only, FALSE if modifiable. BOOL CHexEditView::check_ro(const char *desc) { CString ss; FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (display_.readonly && GetDocument()->read_only()) { ss.Format("This file cannot be modified.\r" "(You can't %s.)", desc); AfxMessageBox(ss); CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); aa->mac_error_ = 10; return TRUE; } else if (pdfv_ != NULL && pdfv_->ReadOnly(start_addr, end_addr)) { ss.Format("The selection contains one or\r" "more read-only template fields,\r" "hence you can't %s.", desc); // AfxMessageBox(ss, MB_OK|MB_HELP, HID_DFFD_RO); AfxMessageBox(ss, MB_OK); theApp.mac_error_ = 10; return TRUE; } else if (display_.readonly) { ss.Format("You can't %s since this window is read only.\r" "Do you want to turn off read only mode?", desc); if (AfxMessageBox(ss, MB_OKCANCEL) != IDOK) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); aa->mac_error_ = 10; return TRUE; } else allow_mods(); } return FALSE; } // Check if we have had read errors on the device and warn the user (but only once) // Note that this will warn once per view not once per file but we don't care too much. void CHexEditView::check_error() { if (GetDocument()->HasSectorErrors()) { // turn on sector display so user can see which sector(s) had errors display_.borders = 1; if (!errors_mentioned_) { AfxMessageBox("Read error(s) were reported by this device", MB_OK|MB_ICONSTOP); errors_mentioned_ = true; } } } ///////////////////////////////////////////////////////////////////////////// // CHexEditView drawing // There are several different coordinate systems used. // - device: pixels on the physical device (screen or printer) // - logical: units set by windows mapping mode // for screen MM_TEXT is used (= device coords) with Y axis down // for printer MM_HIMETRIC is used with Y axis up // - normalised: this is the same as logical but the sign is changed so // that Y axis is always down (and X axis is always right) // in order to simplify comparisons etc // - document: this is the normalised logical coord system with the origin at // the very top of the document. // Note that different mapping modes are used for screen and printer. // MM_TEXT is used for screen otherwise scrolling becomes slightly // out of whack resulting in missing or extra lines of pixels. // MM_TEXT cannot be used for the printer as it comes out tiny on lasers. // void CHexEditView::OnDraw(CDC* pDC) { if (pfont_ == NULL) return; CHexEditDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); /* This was to allow print preview to be grey when active printer was * monochrome, but somehow it's already OK. bool preview = pDC->GetDeviceCaps(NUMCOLORS) == 2 && pDC->m_hDC != pDC->m_hAttribDC; */ //CBrush backBrush; //backBrush.CreateSolidBrush(bg_col_); //backBrush.UnrealizeObject(); pDC->SetBkMode(TRANSPARENT); // Are we in overtype mode and file is empty? if (display_.overtype && pDoc->length() == 0) { // Get the reason that there's no data from the document & display it CRect cli; GetDisplayRect(&cli); pDC->DPtoLP(&cli); if (pDC->IsPrinting()) { if (cli.bottom < 0) cli.top = -2 * print_text_height_; else cli.top = 2 * print_text_height_; } const char *mm = pDoc->why0(); pDC->SetTextColor(GetDefaultTextCol()); pDC->DrawText(mm, -1, &cli, DT_CENTER | DT_TOP | DT_NOPREFIX | DT_SINGLELINE); //::TextOutW(pDC->GetSafeHdc(), 0, 0, L"TEST", 4); // this works! return; } const char *hex; if (theApp.hex_ucase_) hex = "0123456789ABCDEF?"; else hex = "0123456789abcdef?"; CRectAp doc_rect; // Display area relative to whole document CRect norm_rect; // Display area (norm. logical coords) // Note that norm_rect may extend slightly outside the physical view area, for example, // if only half a line is visible at the top of the screen. // These are the first and last "virtual" addresses of the top and (one past) the end // of the addresses within norm_rect. Note that these are not necessarilly the first // and last real addresses. For example, if offset_ != 0 and at the top of file then // first_virt will be -ve. Similarly the file may not even be as long as last_virt. FILE_ADDRESS first_virt, last_virt; FILE_ADDRESS first_line; // First line that needs displaying FILE_ADDRESS last_line; // One past last line to display FILE_ADDRESS first_addr = 0; // First address to actually display FILE_ADDRESS last_addr = pDoc->length(); // One past last address actually displayed FILE_ADDRESS line_inc; // 1 or -1 depending on draw dirn (up/down) CSize rect_inc; // How much to move norm_rect each time FILE_ADDRESS start_addr, end_addr; // Address of current selection bool neg_x(false), neg_y(false); // Does map mode have -ve to left or down bool has_focus; // Does this window have focus? int bitspixel = pDC->GetDeviceCaps(BITSPIXEL); if (bitspixel > 24) bitspixel = 24; // 32 is really only 24 bits of colour long num_colours = 1L << (bitspixel*pDC->GetDeviceCaps(PLANES)); // CBCGDrawManager bcgdm(*pDC); int line_height, char_width, char_width_w; // Text sizes ASSERT(offset_ >= 0 && offset_ < rowsize_); if (offset_ >= rowsize_) offset_ = 0; // xxx kludge - need to track down why offset is wrong ASSERT(rowsize_ > 0 && rowsize_ <= max_buf); ASSERT(group_by_ > 0); if (pDC->IsPrinting()) { // Work out "client" rect of a printer page norm_rect.top = norm_rect.left = 0; norm_rect.bottom = pDC->GetDeviceCaps(VERTRES); norm_rect.right = pDC->GetDeviceCaps(HORZRES); // Convert to logical units but with origin at top left of window // Note we can't use ConvertFromDP here as this is for printer not screen pDC->DPtoLP(&norm_rect); if (norm_rect.right < 0) { neg_x = true; norm_rect.right = -norm_rect.right; } if (norm_rect.bottom < 0) { neg_y = true; norm_rect.bottom = -norm_rect.bottom; } // Text-only printer drivers under Win98 return number of text lines not pixels for VERTRES if (norm_rect.bottom < norm_rect.right/5) norm_rect.bottom *= print_text_height_; // Since there is no translation (only scaling) between device and logical coords origin does not change ASSERT(norm_rect.top == 0 && norm_rect.left == 0); // Work out which part of document to display if (display_.vert_display) doc_rect = CRectAp(norm_rect) + CSizeAp(-margin_size_.cx, curpage_ * FILE_ADDRESS(lines_per_page_) * print_text_height_*3 - margin_size_.cy); else doc_rect = CRectAp(norm_rect) + CSizeAp(-margin_size_.cx, curpage_ * FILE_ADDRESS(lines_per_page_) * print_text_height_ - margin_size_.cy); line_height = print_text_height_; if (display_.vert_display) line_height *= 3; char_width = print_text_width_; char_width_w = print_text_width_w_; } else { has_focus = (GetFocus() == this); HideCaret(); neg_x = negx(); neg_y = negy(); // Get display rect in logical units but with origin at top left of display area in window CRect rct; GetDisplayRect(&rct); doc_rect = ConvertFromDP(rct); // Display = client rectangle translated to posn in document // norm_rect = doc_rect - GetScroll(); norm_rect.left = doc_rect.left - GetScroll().x + bdr_left_; norm_rect.right = doc_rect.right - GetScroll().x + bdr_left_; norm_rect.top = int(doc_rect.top - GetScroll().y) + bdr_top_; norm_rect.bottom = int(doc_rect.bottom - GetScroll().y) + bdr_top_; // Get the current selection so that we can display it in reverse video GetSelAddr(start_addr, end_addr); line_height = line_height_; char_width = text_width_; char_width_w = text_width_w_; } // Get range of addresses that are visible the in window (overridden for printing below) first_virt = (doc_rect.top/line_height) * rowsize_ - offset_; last_virt = (doc_rect.bottom/line_height + 1) * rowsize_ - offset_; // Work out which lines could possibly be in the display area if (pDC->IsPrinting() && print_sel_) { GetSelAddr(first_addr, last_addr); // Start drawing from start of selection (+ allow for subsequent pages) first_line = (first_addr+offset_)/rowsize_ + curpage_*FILE_ADDRESS(lines_per_page_); last_line = first_line + lines_per_page_; // Also if the selection ends on this page set the end if (last_line > (last_addr - 1 + offset_)/rowsize_ + 1) last_line = (last_addr - 1 + offset_)/rowsize_ + 1; line_inc = 1L; rect_inc = CSize(0, line_height); first_virt = first_line * rowsize_ - offset_; last_virt = first_virt + lines_per_page_*rowsize_; // Things are a bit different if merging duplicate lines if (dup_lines_) { if (curpage_ == 0) print_next_line_ = first_line; else first_line = print_next_line_; // We don't know what the last line will be so set to end of selection last_line = (last_addr - 1 + offset_)/rowsize_ + 1; last_virt = last_line * rowsize_ - offset_; } /* Work out where to display the 1st line */ norm_rect.top += margin_size_.cy; norm_rect.bottom = norm_rect.top + line_height; norm_rect.left -= doc_rect.left; doc_rect.top = first_line * line_height - margin_size_.cy; doc_rect.bottom = doc_rect.top + lines_per_page_*print_text_height_; } else if (pDC->IsPrinting()) { // Draw just the lines on this page first_line = curpage_ * FILE_ADDRESS(lines_per_page_); last_line = first_line + lines_per_page_; first_addr = max(0, first_line*rowsize_ - offset_); last_addr = min(pDoc->length(), last_line*rowsize_ - offset_); line_inc = 1L; rect_inc = CSize(0, line_height); first_virt = first_line * rowsize_ - offset_; last_virt = first_virt + lines_per_page_*rowsize_; /* Work out where to display the 1st line */ // norm_rect.top -= int(doc_rect.top - first_line*line_height); norm_rect.top += margin_size_.cy; norm_rect.bottom = norm_rect.top + line_height; // norm_rect.left += margin_size_.cx - doc_rect.left; norm_rect.left -= doc_rect.left; } else if (ScrollUp()) { // Draw from bottom of window up since we're scrolling up (looks better) first_line = doc_rect.bottom/line_height; last_line = doc_rect.top/line_height - 1; line_inc = -1L; rect_inc = CSize(0, -line_height); /* Work out where to display the 1st line */ norm_rect.top -= int(doc_rect.top - first_line*line_height); norm_rect.bottom = norm_rect.top + line_height; norm_rect.left -= doc_rect.left; } else { // Draw from top of window down first_line = doc_rect.top/line_height; last_line = doc_rect.bottom/line_height + 1; line_inc = 1L; rect_inc = CSize(0, line_height); /* Work out where to display the 1st line */ norm_rect.top -= int(doc_rect.top - first_line*line_height); norm_rect.bottom = norm_rect.top + line_height; norm_rect.left -= doc_rect.left; } if (first_addr < first_virt) first_addr = first_virt; if (last_addr > last_virt) last_addr = last_virt; // These are for drawing things on the screen CPoint pt; // moved this here to avoid a spurious compiler error C2362 CPen pen1(PS_SOLID, 0, same_hue(sector_col_, 100, 30)); // dark sector_col_ CPen pen2(PS_SOLID, 0, same_hue(addr_bg_col_, 100, 30)); // dark addr_bg_col_ CPen *psaved_pen; CBrush brush(sector_col_); // Skip background drawing in this case because it's too hard. // Note that this goto greatly simplifies the tests below. if (pDC->IsPrinting() && print_sel_ && dup_lines_) goto end_of_background_drawing; // Preread device blocks so we know if there are bad sectors if (GetDocument()->IsDevice()) { // As long as we ensure that the CFileNC buffer is at least as big as the display area (the // distance from start of top line to end of bottom line) then this should read all // sectors to be dipslayed. unsigned char cc; TRACE("---- Display size is %ld\n", long(last_addr - first_addr)); pDoc->GetData(&cc, 1, (first_addr + last_addr)/2); } if (display_.borders) psaved_pen = pDC->SelectObject(&pen1); else psaved_pen = pDC->SelectObject(&pen2); // Column related screen stuff (ruler, vertical lines etc) if (!pDC->IsPrinting()) { ASSERT(!neg_y && !neg_x); // This should be true when drawing on screen (uses MM_TEXT) // Vert. line between address and hex areas pt.y = bdr_top_ - 4; pt.x = addr_width_*char_width - char_width - doc_rect.left + bdr_left_; pDC->MoveTo(pt); pt.y = 30000; pDC->LineTo(pt); if (!display_.vert_display && display_.hex_area) { // Vert line to right of hex area pt.y = bdr_top_ - 4; pt.x = char_pos(0, char_width) - char_width_w/2 - doc_rect.left + bdr_left_; pDC->MoveTo(pt); pt.y = 30000; pDC->LineTo(pt); } if (display_.vert_display || display_.char_area) { // Vert line to right of char area pt.y = bdr_top_ - 4; pt.x = char_pos(rowsize_ - 1, char_width, char_width_w) + (3*char_width_w)/2 - doc_rect.left + bdr_left_; pDC->MoveTo(pt); pt.y = 30000; pDC->LineTo(pt); } if (theApp.ruler_) { int horz = bdr_left_ - GetScroll().x; // Horiz. offset to window posn of left side ASSERT(bdr_top_ > 0); // Draw horiz line under ruler pt.y = bdr_top_ - 4; pt.x = addr_width_*char_width - char_width - doc_rect.left + bdr_left_; pDC->MoveTo(pt); pt.x = 30000; pDC->LineTo(pt); // Draw ticks using hex offsets for major ticks (if using hex addresses) or // decimal offsets (if using decimal addresses/line numbers and/or hex addresses) int major = 1; if (display_.decimal_addr || display_.line_nums) major = theApp.ruler_dec_ticks_; // decimal ruler or both hex and decimal else major = theApp.ruler_hex_ticks_; // only showing hex ruler // Hex area ticks if (!display_.vert_display && display_.hex_area) for (int column = 1; column < rowsize_; ++column) { if ((!display_.decimal_addr && !display_.line_nums && theApp.ruler_hex_nums_ > 1 && column%theApp.ruler_hex_nums_ == 0) || ((display_.decimal_addr || display_.line_nums) && theApp.ruler_dec_nums_ > 1 && column%theApp.ruler_dec_nums_ == 0) ) continue; // skip when displaying a number at this posn pt.y = bdr_top_ - 5; pt.x = hex_pos(column) - char_width/2 + horz; if (column%group_by_ == 0) pt.x -= char_width/2; pDC->MoveTo(pt); pt.y -= (column%major) ? 3 : 7; pDC->LineTo(pt); } // Char area or stacked display ticks if (display_.vert_display || display_.char_area) for (int column = 0; column <= rowsize_; ++column) { if ((!display_.decimal_addr && !display_.line_nums && theApp.ruler_hex_nums_ > 1 && column%theApp.ruler_hex_nums_ == 0) || ((display_.decimal_addr || display_.line_nums) && theApp.ruler_dec_nums_ > 1 && column%theApp.ruler_dec_nums_ == 0) ) continue; // skip when displaying a number at this posn pt.y = bdr_top_ - 5; pt.x = char_pos(column) + horz; if (display_.vert_display && column%group_by_ == 0) if (column == rowsize_) // skip last one break; else pt.x -= char_width/2; pDC->MoveTo(pt); pt.y -= (column%major) ? 2 : 5; pDC->LineTo(pt); } // Draw numbers in the ruler area // Note that if we are displaying hex and decimal addresses we show 2 rows // - hex offsets at top (then after moving vert down) decimal offsets int vert = 0; // Screen y pixel to the row of nos at int hicol = -1; // Column with cursor is to be highlighted bool hl_box = true; // Highlight mouse/cursor in the ruler using box around col number (or just a small line) if (display_.hex_addr && theApp.ruler_hex_nums_ > 1) hl_box = false; if ((display_.decimal_addr || display_.line_nums) && theApp.ruler_dec_nums_ > 1) hl_box = false; CRect hi_rect(-1, 0, -1, bdr_top_ - 4); if (!hl_box) hi_rect.top = hi_rect.bottom - 2; // A flat rect just inside the ruler // Current caret position shown in the ruler if (theApp.hl_caret_ && !mouse_down_) { // Do highlighting with a background rectangle in ruler hicol = int((start_addr + offset_)%rowsize_); CBrush * psaved_brush = pDC->SelectObject(&brush); CPen * psaved_pen = pDC->SelectObject(&pen1); if (!display_.vert_display && display_.hex_area) { hi_rect.left = hex_pos(hicol) + horz; hi_rect.right = hi_rect.left + text_width_*2 + 1; pDC->Rectangle(&hi_rect); } if (display_.vert_display || display_.char_area) { hi_rect.left = char_pos(hicol) + horz; hi_rect.right = hi_rect.left + text_width_ + 1; pDC->Rectangle(&hi_rect); } (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } // Current mouse position in the ruler if (theApp.hl_mouse_ && mouse_addr_ > -1) { int mousecol = int((mouse_addr_ + offset_)%rowsize_); // Mouse column to be highlighted CBrush * psaved_brush = pDC->SelectObject(CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH))); CPen * psaved_pen = pDC->SelectObject(&pen1); if (!display_.vert_display && display_.hex_area) { hi_rect.left = hex_pos(mousecol) + horz; hi_rect.right = hi_rect.left + text_width_*2 + 1; pDC->Rectangle(&hi_rect); } if (display_.vert_display || display_.char_area) { hi_rect.left = char_pos(mousecol) + horz; hi_rect.right = hi_rect.left + text_width_ + 1; pDC->Rectangle(&hi_rect); } (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } // Get display rect for clipping at right and left CRect cli; GetDisplayRect(&cli); // Show hex offsets in the top border (ruler) if (display_.hex_addr) { bool between = theApp.ruler_hex_nums_ > 1; // Only display numbers above cols if displaying for every column // Do hex numbers in ruler CRect rect(-1, vert, -1, vert + text_height_ + 1); CString ss; pDC->SetTextColor(GetHexAddrCol()); // Colour of hex addresses // Show hex offsets above hex area if (!display_.vert_display && display_.hex_area) for (int column = 0; column < rowsize_; ++column) { if (between && display_.addrbase1 && column == 0) continue; // usee doesn't like seeing zero if (column%theApp.ruler_hex_nums_ != 0) continue; rect.left = hex_pos(column) + horz; if (between) { rect.left -= char_width; if (column > 0 && column%group_by_ == 0) rect.left -= char_width/2; } if (rect.left < cli.left) continue; if (rect.left > cli.right) break; rect.right = rect.left + text_width_ + text_width_; if (!between) { // Draw 2 digit number above every column ss.Format(theApp.hex_ucase_ ? "%02X" : "%02x", (column + display_.addrbase1)%256); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else if (column%16 == 0 && theApp.ruler_hex_nums_ > 3) { // Draw 2 digit numbers to mark end of 16 columns rect.left -= (char_width+1)/2; ss.Format(theApp.hex_ucase_ ? "%02X" : "%02x", column%256); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else { // Draw single digit number in between columns ss.Format(theApp.hex_ucase_ ? "%1X" : "%1x", column%16); pDC->DrawText(ss, &rect, DT_BOTTOM | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } } // Show hex offsets above char area or stacked display if (display_.vert_display || display_.char_area) for (int column = 0; column < rowsize_; ++column) { if (between && display_.addrbase1 && column == 0) continue; // user doesn't like seeing zero if (column%theApp.ruler_hex_nums_ != 0) continue; rect.left = char_pos(column) + horz; if (between) { if (display_.vert_display && column > 0 && column%group_by_ == 0) rect.left -= char_width; else rect.left -= char_width/2; } if (rect.left < cli.left) continue; if (rect.left > cli.right) break; rect.right = rect.left + text_width_ + text_width_; if (!between) { ss.Format(theApp.hex_ucase_ ? "%1X" : "%1x", (column + display_.addrbase1)%16); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else if (column%16 == 0 && theApp.ruler_hex_nums_ > 3) { rect.left -= (char_width+1)/2; ss.Format(theApp.hex_ucase_ ? "%02X" : "%02x", column%256); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else { ss.Format(theApp.hex_ucase_ ? "%1X" : "%1x", column%16); pDC->DrawText(ss, &rect, DT_BOTTOM | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } } vert += text_height_; // Move down for anything to be drawn underneath } // Show decimal offsets in the ruler if (display_.decimal_addr || display_.line_nums) { bool between = theApp.ruler_dec_nums_ > 1; // Only display numbers above cols if displaying for every column CRect rect(-1, vert, -1, vert + text_height_ + 1); CString ss; pDC->SetTextColor(GetDecAddrCol()); // Colour of dec addresses // Decimal offsets above hex area if (!display_.vert_display && display_.hex_area) for (int column = 0; column < rowsize_; ++column) { if (between && display_.addrbase1 && column == 0) continue; // user doesn't like seeing zero if (column%theApp.ruler_dec_nums_ != 0) continue; rect.left = hex_pos(column) + horz; if (between) { rect.left -= char_width; if (column > 0 && column%group_by_ == 0) rect.left -= char_width/2; } if (rect.left < cli.left) continue; if (rect.left > cli.right) break; rect.right = rect.left + text_width_ + text_width_; if (!between) { ss.Format("%02d", (column + display_.addrbase1)%100); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else if (column%10 == 0 && theApp.ruler_dec_nums_ > 4) { rect.left -= (char_width+1)/2; ss.Format("%02d", column%100); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else { ss.Format("%1d", column%10); pDC->DrawText(ss, &rect, DT_BOTTOM | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } } // Decimal offsets above char area or stacked display if (display_.vert_display || display_.char_area) for (int column = 0; column < rowsize_; ++column) { if (between && display_.addrbase1 && column == 0) continue; // user doesn't like seeing zero if (column%theApp.ruler_dec_nums_ != 0) continue; rect.left = char_pos(column) + horz; if (between) { if (display_.vert_display && column > 0 && column%group_by_ == 0) rect.left -= char_width; else rect.left -= char_width/2; } if (rect.left < cli.left) continue; if (rect.left > cli.right) break; rect.right = rect.left + text_width_ + text_width_; if (!between) { ss.Format("%1d", (column + display_.addrbase1)%10); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else if (column%10 == 0 && theApp.ruler_dec_nums_ > 4) { // If displaying nums every 5 or 10 then display 2 digits fo tens column rect.left -= (char_width+1)/2; ss.Format("%02d", column%100); pDC->DrawText(ss, &rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } else { // Display single dit between columns ss.Format("%1d", column%10); pDC->DrawText(ss, &rect, DT_BOTTOM | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } } vert += text_height_; // Move down for anything to be drawn underneath (currently nothing) } #ifdef RULER_ADJUST draw_adjusters(pDC); // Draw adjustment controls in the ruler #endif } // end ruler drawing } // Mask out the ruler so we don't get top of topmost line drawn into it. // Doing it this way allows the address of the top line to be drawn // higher (ie into ruler area) without being clipped. // Note that we currently only use bdr_top_ (for the ruler) but if // other borders are used similarly we would need to clip them too. // Note: This needs to be done after drawing the ruler. #ifndef TEST_CLIPPING if (!pDC->IsPrinting()) { CRect rct; GetDisplayRect(&rct); rct.bottom = rct.top; rct.top = 0; rct.left = (addr_width_ - 1)*char_width + norm_rect.left + bdr_left_; pDC->ExcludeClipRect(&rct); } #endif // Note: We draw bad sectors, change-tracking deletions, etc first // as they are always drawn from the top of screen (or page) downwards. // This is so the user is less likely to notice the wrong direction. // (Major things are drawn from the bottom up when scrolling backwards.) // First decide is we need to draw sector borders int seclen = pDoc->GetSectorSize(); bool draw_borders = pDoc->pfile1_ != NULL && display_.borders && seclen > 0; if (pDC->IsPrinting() && !theApp.print_sectors_) draw_borders = false; if (draw_borders) { ASSERT(seclen > 0); bool prev_bad = first_addr == 0; // don't display sector separator above top of file for (FILE_ADDRESS sector = (first_addr/seclen)*seclen; sector < last_addr; sector += seclen) { // Note that "sector" is the address of the start of the sector if (pDoc->HasSectorErrors() && pDoc->SectorError(sector/seclen) != NO_ERROR) { // Draw colour behind the bytes to indicate there is a problem with this sector draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, sector_bg_col_, max(sector, first_addr), min(sector + seclen, last_addr)); prev_bad = true; } else if (!prev_bad && sector >= first_addr && sector < last_addr) { // Just draw a line above the top of the sector if (!display_.vert_display && display_.hex_area) { // Hex area pt.y = int(((sector + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_); // This is just above the first byte of the sector if (neg_y) pt.y = -pt.y; //pt.x = hex_pos(rowsize_ - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; pt.x = char_pos(0, char_width) - char_width/2 - doc_rect.left + bdr_left_; // Right side of hex area if (neg_x) pt.x = - pt.x; pDC->MoveTo(pt); pt.x = hex_pos(int((sector + offset_)%rowsize_), char_width) - char_width/2 - doc_rect.left + bdr_left_; // This is just to left of first byte of sector if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); if ((sector + offset_)%rowsize_ != 0) { // Draw on line below and vertical bit too pt.y = int(((sector + offset_)/rowsize_ + 1) * line_height - doc_rect.top + bdr_top_); if (neg_y) pt.y = -pt.y; pDC->LineTo(pt); pt.x = hex_pos(0, char_width) - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); } pt.x = addr_width_*char_width - char_width - doc_rect.left + bdr_left_; pDC->LineTo(pt); } if (display_.vert_display || display_.char_area) { // Do char area (or stacked mode) pt.y = int(((sector + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_); if (neg_y) pt.y = -pt.y; //pt.x = char_pos(rowsize_ - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; pt.x = char_pos(rowsize_ - 1, char_width, char_width_w) + (3*char_width_w)/2 - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->MoveTo(pt); pt.x = char_pos(int((sector + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); if ((sector + offset_)%rowsize_ != 0) { // Draw on line below and vertical bit too pt.y = int(((sector + offset_)/rowsize_ + 1) * line_height - doc_rect.top + bdr_top_); if (neg_y) pt.y = -pt.y; pDC->LineTo(pt); pt.x = char_pos(0, char_width, char_width_w) - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); } // Fill in a little bit to join with the vertical line on the left if (display_.vert_display || !display_.hex_area) pt.x = addr_width_*char_width - char_width - doc_rect.left + bdr_left_; else pt.x = char_pos(0, char_width, char_width_w) - char_width_w/2 - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); } // Draw a little bit more in the gap between address area and left side pt.x = addr_width_*char_width - char_width/2 - doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->MoveTo(pt); pt.x = addr_width_*char_width + char_width/8 - // Extra char_width/8 due to one pixel out on screen (and many on printer) doc_rect.left + bdr_left_; if (neg_x) pt.x = - pt.x; pDC->LineTo(pt); } else { prev_bad = false; // don't draw border at bottom of previous block fill (just remember this one was OK) } } } pDC->SelectObject(psaved_pen); // restore pen after drawing borders etc // Make sure background compare is on and finished and also print_compare_ is on (if printing) if (!((GetDocument()->CompareDifferences() <= 0) || pDC->IsPrinting() && !theApp.print_compare_)) { // Draw differences with compare file CTime tnew = GetDocument()->ResultTime(0); // time of most recent comparison // xxx TBD make "number of minutes before it completely disappears" into a parameter CTime tearliest = tnew - CTimeSpan(0, 0, 15, 0); // older diffs are shown in lighter shades for (int rr = GetDocument()->ResultCount() - 1; rr >= 0; rr--) { COLORREF col, col2; // colours for replace (underline) + delete, and also for inserts CTime tt = GetDocument()->ResultTime(rr); if (tt < tearliest) continue; // Tone down based on how long agoo the change was made (up to 0.8 since toning down more is not that visible) double amt = 0.8 - double((tt - tearliest).GetTotalSeconds()) / double((tnew - tearliest).GetTotalSeconds()); col = ::tone_down(comp_col_, bg_col_, amt); col2 = ::tone_down(comp_bg_col_, bg_col_, amt); for (int dd = GetDocument()->FirstDiffAt(false, rr, first_virt); dd < GetDocument()->CompareDifferences(rr); ++dd) { FILE_ADDRESS addr; int len; GetDocument()->GetOrigDiff(rr, dd, addr, len); if (addr + len < first_virt) continue; // before top of window else if (addr >= last_virt) break; // after end of window draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, col, max(addr, first_addr), min(addr+len, last_addr), false, // overwrite (not merge) since mutiple changes at the same address really mess up the colours (pDC->IsPrinting() ? print_text_height_ : text_height_)/8); } } } // Draw deletion marks always from top (shouldn't be too visible) if (!(display_.hide_delete || pDC->IsPrinting() && !theApp.print_change_)) { COLORREF prev_col = pDC->SetTextColor(bg_col_); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > *ppr = GetDocument()->Deletions(); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp; for (pp = ppr->begin(); pp != ppr->end(); ++pp) { // Check if its before or after the display area if (pp->first < first_virt) continue; else if (pp->first > last_virt) break; CRect draw_rect; draw_rect.top = int(((pp->first + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_); draw_rect.bottom = draw_rect.top + line_height; if (neg_y) { draw_rect.top = -draw_rect.top; draw_rect.bottom = -draw_rect.bottom; } if (!display_.vert_display && display_.hex_area) { draw_rect.left = hex_pos(int((pp->first + offset_)%rowsize_), char_width) - char_width - doc_rect.left + bdr_left_; draw_rect.right = draw_rect.left + char_width; if (neg_x) { draw_rect.left = -draw_rect.left; draw_rect.right = -draw_rect.right; } pDC->FillSolidRect(&draw_rect, trk_col_); char cc = (pp->second > 9 || !display_.delete_count) ? '*' : '0' + char(pp->second); pDC->DrawText(&cc, 1, &draw_rect, DT_CENTER | DT_TOP | DT_NOPREFIX | DT_SINGLELINE); } if (display_.vert_display || display_.char_area) { draw_rect.left = char_pos(int((pp->first + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_ - 2; draw_rect.right = draw_rect.left + char_width_w/5+1; if (neg_x) { draw_rect.left = -draw_rect.left; draw_rect.right = -draw_rect.right; } pDC->FillSolidRect(&draw_rect, trk_col_); } } pDC->SetTextColor(prev_col); // restore text colour } // Now draw other change tracking stuff top down OR bottom up depending on ScrollUp() if (!pDC->IsPrinting() && ScrollUp()) { // Draw change tracking from bottom up if (!display_.hide_replace) { std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > *ppr = GetDocument()->Replacements(); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::reverse_iterator pp; for (pp = ppr->rbegin(); pp != ppr->rend(); ++pp) if (pp->first < last_virt) break; for ( ; pp != ppr->rend(); ++pp) { if (pp->first + pp->second <= first_virt) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, trk_col_, max(pp->first, first_addr), min(pp->first + pp->second, last_addr), true, (pDC->IsPrinting() ? print_text_height_ : text_height_)/8); } } if (!display_.hide_insert) { std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > *ppr = GetDocument()->Insertions(); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::reverse_iterator pp; for (pp = ppr->rbegin(); pp != ppr->rend(); ++pp) if (pp->first < last_virt) break; for ( ; pp != ppr->rend(); ++pp) { if (pp->first +pp->second <= first_virt) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, trk_bg_col_, max(pp->first, first_addr), min(pp->first + pp->second, last_addr)); } } } else if (!pDC->IsPrinting() || theApp.print_change_) { // Draw change tracking from top down if (!display_.hide_replace) { std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > *ppr = GetDocument()->Replacements(); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp; for (pp = ppr->begin(); pp != ppr->end(); ++pp) if (pp->first + pp->second > first_virt) break; for ( ; pp != ppr->end(); ++pp) { if (pp->first > last_virt) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, trk_col_, max(pp->first, first_addr), min(pp->first + pp->second, last_addr), true, (pDC->IsPrinting() ? print_text_height_ : text_height_)/8); } } if (!display_.hide_insert) { std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> > *ppr = GetDocument()->Insertions(); std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp; for (pp = ppr->begin(); pp != ppr->end(); ++pp) if (pp->first + pp->second > first_virt) break; for ( ; pp != ppr->end(); ++pp) { if (pp->first > last_virt) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, trk_bg_col_, max(pp->first, first_addr), min(pp->first + pp->second, last_addr)); } } } // Don't print bookmarks if hide_bookmarks is on OR printing and print_bookmarks_ is off if (!(display_.hide_bookmarks || pDC->IsPrinting() && !theApp.print_bookmarks_)) { // Draw bookmarks for (std::vector<FILE_ADDRESS>::const_iterator pbm = pDoc->bm_posn_.begin(); pbm != pDoc->bm_posn_.end(); ++pbm) { if (*pbm >= first_addr && *pbm <= last_addr) { CRect mark_rect; mark_rect.top = int(((*pbm + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_ + 1); // mark_rect.bottom = mark_rect.top + line_height - 3; mark_rect.bottom = mark_rect.top + line_height - 1; if (neg_y) { mark_rect.top = -mark_rect.top; mark_rect.bottom = -mark_rect.bottom; } if (!display_.vert_display && display_.hex_area) { mark_rect.left = hex_pos(int((*pbm + offset_)%rowsize_), char_width) - doc_rect.left + bdr_left_; // mark_rect.right = mark_rect.left + 2*char_width; mark_rect.right = mark_rect.left + 2*char_width + 2; if (neg_x) { mark_rect.left = -mark_rect.left; mark_rect.right = -mark_rect.right; } pDC->FillSolidRect(&mark_rect, bm_col_); } if (display_.vert_display || display_.char_area) { mark_rect.left = char_pos(int((*pbm + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_ + 1; // mark_rect.right = mark_rect.left + char_width_w - 2; mark_rect.right = mark_rect.left + char_width_w; if (neg_x) { mark_rect.left = -mark_rect.left; mark_rect.right = -mark_rect.right; } pDC->FillSolidRect(&mark_rect, bm_col_); } } } } // First work out if we draw the mark - in display and not turned off for printing bool draw_mark; if (pDC->IsPrinting()) draw_mark = theApp.print_mark_ && mark_ >= first_virt && mark_ < last_virt; else draw_mark = mark_ >= first_addr && mark_ < last_addr; if (draw_mark) { CRect mark_rect; // Where mark is drawn in logical coords mark_rect.top = int(((mark_ + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_ + 1); // mark_rect.bottom = mark_rect.top + line_height - 3; mark_rect.bottom = mark_rect.top + line_height - 1; if (neg_y) { mark_rect.top = -mark_rect.top; mark_rect.bottom = -mark_rect.bottom; } if (!display_.vert_display && display_.hex_area) { mark_rect.left = hex_pos(int((mark_ + offset_)%rowsize_), char_width) - doc_rect.left + bdr_left_; // mark_rect.right = mark_rect.left + 2*char_width; mark_rect.right = mark_rect.left + 2*char_width + 2; if (neg_x) { mark_rect.left = -mark_rect.left; mark_rect.right = -mark_rect.right; } pDC->FillSolidRect(&mark_rect, mark_col_); } if (display_.vert_display || display_.char_area) { mark_rect.left = char_pos(int((mark_ + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_ + 1; // mark_rect.right = mark_rect.left + char_width_w - 2; mark_rect.right = mark_rect.left + char_width_w; if (neg_x) { mark_rect.left = -mark_rect.left; mark_rect.right = -mark_rect.right; } pDC->FillSolidRect(&mark_rect, mark_col_); } } // Draw indicator around byte that is used for info tips if (!pDC->IsPrinting() && last_tip_addr_ >= first_virt && last_tip_addr_ < last_virt) { CRect info_rect; // Where mark is drawn in logical coords info_rect.top = int(((last_tip_addr_ + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_ + 1); info_rect.bottom = info_rect.top + line_height - 1; if (neg_y) { info_rect.top = -info_rect.top; info_rect.bottom = -info_rect.bottom; } CBrush * psaved_brush = pDC->SelectObject(CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH))); CPen * psaved_pen = pDC->SelectObject(&pen1); if (!display_.vert_display && display_.hex_area) { info_rect.left = hex_pos(int((last_tip_addr_ + offset_)%rowsize_), char_width) - doc_rect.left + bdr_left_; info_rect.right = info_rect.left + 2*char_width + 1; if (neg_x) { info_rect.left = -info_rect.left; info_rect.right = -info_rect.right; } //pDC->FillSolidRect(&info_rect, sector_bg_col_); pDC->Rectangle(&info_rect); //pDC->MoveTo(info_rect.right, info_rect.bottom-1); //pDC->LineTo(info_rect.left, info_rect.bottom-1); //pDC->LineTo(info_rect.left, info_rect.top); //pDC->LineTo(info_rect.right, info_rect.top); } if (display_.vert_display || display_.char_area) { info_rect.left = char_pos(int((last_tip_addr_ + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_ + 1; info_rect.right = info_rect.left + char_width_w - 1; if (neg_x) { info_rect.left = -info_rect.left; info_rect.right = -info_rect.right; } //pDC->FillSolidRect(&info_rect, sector_bg_col_); pDC->Rectangle(&info_rect); //pDC->MoveTo(info_rect.right, info_rect.bottom-1); //pDC->LineTo(info_rect.left, info_rect.bottom-1); //pDC->LineTo(info_rect.left, info_rect.top); //pDC->LineTo(info_rect.right, info_rect.top); } (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } // Draw indicator around byte where bookmark is being moved to if (!pDC->IsPrinting() && mouse_down_ && drag_bookmark_ > -1) { CRect drag_rect; // Where mark is drawn in logical coords drag_rect.top = int(((drag_address_ + offset_)/rowsize_) * line_height - doc_rect.top + bdr_top_ + 1); drag_rect.bottom = drag_rect.top + line_height - 2; if (neg_y) { drag_rect.top = -drag_rect.top; drag_rect.bottom = -drag_rect.bottom; } CBrush * psaved_brush = pDC->SelectObject(CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH))); CPen * psaved_pen = pDC->SelectObject(&pen1); if (!display_.vert_display && display_.hex_area) { drag_rect.left = hex_pos(int((drag_address_ + offset_)%rowsize_), char_width) - doc_rect.left + bdr_left_; drag_rect.right = drag_rect.left + 2*char_width; if (neg_x) { drag_rect.left = -drag_rect.left; drag_rect.right = -drag_rect.right; } pDC->FillSolidRect(&drag_rect, bm_col_); pDC->Rectangle(&drag_rect); } if (display_.vert_display || display_.char_area) { drag_rect.left = char_pos(int((drag_address_ + offset_)%rowsize_), char_width, char_width_w) - doc_rect.left + bdr_left_ + 1; drag_rect.right = drag_rect.left + char_width_w - 1; if (neg_x) { drag_rect.left = -drag_rect.left; drag_rect.right = -drag_rect.right; } pDC->FillSolidRect(&drag_rect, bm_col_); pDC->Rectangle(&drag_rect); } (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } // Don't print highlights if hide_highlight is on OR printing and print_highlights_ is off if (!(display_.hide_highlight || pDC->IsPrinting() && !theApp.print_highlights_)) { if (!pDC->IsPrinting() && ScrollUp()) { // Draw highlighted areas bottom up range_set<FILE_ADDRESS>::range_t::reverse_iterator pr; for (pr = hl_set_.range_.rbegin(); pr != hl_set_.range_.rend(); ++pr) if (pr->sfirst < last_addr) break; for ( ; pr != hl_set_.range_.rend(); ++pr) { if (pr->slast <= first_addr) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, hi_col_, max(pr->sfirst, first_addr), min(pr->slast, last_addr)); } } else { // Draw highlighted areas top down range_set<FILE_ADDRESS>::range_t::const_iterator pr; for (pr = hl_set_.range_.begin(); pr != hl_set_.range_.end(); ++pr) if (pr->slast > first_addr) break; for ( ; pr != hl_set_.range_.end(); ++pr) { if (pr->sfirst > last_addr) break; draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, hi_col_, max(pr->sfirst, first_addr), min(pr->slast, last_addr)); } } } if (pDC->IsPrinting()) { // Only print search occurrences if print_search_ is on if (theApp.print_search_) { // Draw search string occurrences // Note this goes through all search occurrences (since search_pair_ is // calculated for the current window) which may be slow but then so is printing. std::vector<FILE_ADDRESS> sf = GetDocument()->SearchAddresses(first_addr-search_length_, last_addr+search_length_); std::vector<FILE_ADDRESS>::const_iterator pp; for (pp = sf.begin(); pp != sf.end(); ++pp) { draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, search_col_, max(*pp, first_addr), min(*pp + search_length_, last_addr)); } } } else if (ScrollUp()) { // Draw search string occurrences bottom up std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::reverse_iterator pp, pend; for (pp = search_pair_.rbegin(), pend = search_pair_.rend(); pp != pend; ++pp) { draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, search_col_, max(pp->first, first_addr), min(pp->second, last_addr)); } } else { // Draw search string occurrences from top down std::vector<pair<FILE_ADDRESS, FILE_ADDRESS> >::const_iterator pp, pend; for (pp = search_pair_.begin(), pend = search_pair_.end(); pp != pend; ++pp) { draw_bg(pDC, doc_rect, neg_x, neg_y, line_height, char_width, char_width_w, search_col_, max(pp->first, first_addr), min(pp->second, last_addr)); } } end_of_background_drawing: unsigned char buf[max_buf]; // Holds bytes for current line being displayed size_t last_col = 0; // Number of bytes in buf to display unsigned char prev_buf[max_buf]; // Copy of last buf - used for merging repeated lines size_t prev_last_col; // Number of bytes in last buf that were displayed int repeat_count = 0; // Number of consec. duplicate lines found so far // Move declarations outside loop (faster?) CString ss(' ', 24); // Temp string for formatting CRect tt; // Temp rect CRect addr_rect; // Where address is drawn // This was added for vert_display int vert_offset = 0; if (display_.vert_display) { if (pDC->IsPrinting()) vert_offset = print_text_height_; else vert_offset = text_height_; if (neg_y) vert_offset = - vert_offset; // vert_offset = (vert_offset*15)/16; // Leave a gap between rows } // THIS IS WHERE THE ACTUAL LINES ARE DRAWN // Note: we use != (line != last_line) since we may be drawing from bottom or top for (FILE_ADDRESS line = first_line; line != last_line; line += line_inc, norm_rect += rect_inc) { // Work out where to display line in logical coords (correct sign) tt = norm_rect; if (neg_x) { tt.left = -tt.left; tt.right = -tt.right; } if (neg_y) { tt.top = -tt.top; tt.bottom = -tt.bottom; } // No display needed if outside display area or past end of doc // Note: we don't break when past end since we may be drawing from bottom if (!pDC->RectVisible(&tt) || line*rowsize_ - offset_ > pDoc->length()) continue; // Take a copy of the last line output to check for repeated lines if (pDC->IsPrinting() && print_sel_ && dup_lines_ && last_col > 0) memcpy(prev_buf, buf, last_col); prev_last_col = last_col; // Get the bytes to display size_t ii; // Column of first byte if (line*rowsize_ - offset_ < first_addr) { last_col = pDoc->GetData(buf + offset_, rowsize_ - offset_, line*rowsize_) + offset_; ii = size_t(first_addr - (line*rowsize_ - offset_)); ASSERT(int(ii) < rowsize_); } else { last_col = pDoc->GetData(buf, rowsize_, line*rowsize_ - offset_); ii = 0; } if (line*rowsize_ - offset_ + last_col - last_addr >= rowsize_) last_col = 0; else if (line*rowsize_ - offset_ + last_col > last_addr) last_col = size_t(last_addr - (line*rowsize_ - offset_)); // TRACE("xxx line %ld rowsize_ %ld offset_ %ld last_col %ld first_addr %ld last_addr %ld\n", // long(line), long(rowsize_), long(offset_), long(last_col), long(first_addr), long(last_addr)); if (pDC->IsPrinting() && print_sel_ && dup_lines_) { // Check if the line is the same as the last one // But NOT if very first line (line 0 on page 0) since we may not display the whole line if ((curpage_ > 0 || line > first_line+1) && last_col == prev_last_col && memcmp(buf, prev_buf, last_col) == 0) { ++repeat_count; norm_rect -= rect_inc; continue; } if (repeat_count > 0) { // Display how many times the line was repeated CString mess; if (repeat_count == 1) mess = "Repeated once"; else mess.Format("Repeated %d more times", repeat_count); CRect mess_rect = tt; mess_rect.left += hex_pos(0, char_width); pDC->DrawText(mess, &mess_rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); // Move the current display line down one norm_rect += rect_inc; tt = norm_rect; if (neg_x) { tt.left = -tt.left; tt.right = -tt.right; } if (neg_y) { tt.top = -tt.top; tt.bottom = -tt.bottom; } // Reset the repeated line counter since this was a different line repeat_count = 0; } // See if we are at the bottom of the page yet if (norm_rect.bottom > margin_size_.cy + print_text_height_*lines_per_page_) { print_next_line_ = line; break; } } // Draw address if ... if ((addr_width_ - 1)*char_width + tt.left > 0 && // not off to the left (tt.top + text_height_/4 >= bdr_top_ || pDC->IsPrinting())) // and does not encroach into ruler { addr_rect = tt; // tt with right margin where addresses end addr_rect.right = addr_rect.left + addr_width_*char_width - char_width - 1; if (pDC->IsPrinting()) if (neg_y) addr_rect.bottom = addr_rect.top - print_text_height_; else addr_rect.bottom = addr_rect.top + print_text_height_; else if (neg_y) addr_rect.bottom = addr_rect.top - text_height_; else addr_rect.bottom = addr_rect.top + text_height_; // Not highlighting when the mouse is down avoids a problem with invalidation of // the address area when autoscrolling (old highlights sometimes left behind). if (theApp.hl_caret_ && !pDC->IsPrinting() && !mouse_down_ && start_addr >= line*rowsize_ - offset_ && start_addr < (line+1)*rowsize_ - offset_) { CBrush * psaved_brush = pDC->SelectObject(&brush); CPen * psaved_pen = pDC->SelectObject(&pen1); pDC->Rectangle(&addr_rect); (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } // Show address of current row with a different background colour if (theApp.hl_mouse_ && !pDC->IsPrinting() && mouse_addr_ >= line*rowsize_ - offset_ && mouse_addr_ < (line+1)*rowsize_ - offset_) { CBrush * psaved_brush = pDC->SelectObject(CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH))); CPen * psaved_pen = pDC->SelectObject(&pen1); pDC->Rectangle(&addr_rect); (void)pDC->SelectObject(psaved_pen); (void)pDC->SelectObject(psaved_brush); } if (hex_width_ > 0) { int ww = hex_width_ + 1; char *addr_buf = ss.GetBuffer(24); // reserve space for 64 bit address sprintf(addr_buf, theApp.hex_ucase_ ? "%0*I64X:" : "%0*I64x:", hex_width_, (line*rowsize_ - offset_ > first_addr ? line*rowsize_ - offset_ : first_addr) + display_.addrbase1); ss.ReleaseBuffer(-1); if (theApp.nice_addr_) { AddSpaces(ss); ww += (hex_width_-1)/4; } pDC->SetTextColor(GetHexAddrCol()); // Colour of hex addresses addr_rect.right = addr_rect.left + ww*char_width; pDC->DrawText(ss, &addr_rect, DT_TOP | DT_NOPREFIX | DT_SINGLELINE); addr_rect.left = addr_rect.right; } if (dec_width_ > 0) { int ww = dec_width_ + 1; char *addr_buf = ss.GetBuffer(24); // reserve space for 64 bit address sprintf(addr_buf, "%*I64d:", dec_width_, (line*rowsize_ - offset_ > first_addr ? line*rowsize_ - offset_ : first_addr) + display_.addrbase1); ss.ReleaseBuffer(-1); if (theApp.nice_addr_) { AddCommas(ss); ww += (dec_width_-1)/3; } pDC->SetTextColor(GetDecAddrCol()); // Colour of dec addresses addr_rect.right = addr_rect.left + ww*char_width; pDC->DrawText(ss, &addr_rect, DT_TOP | DT_RIGHT | DT_NOPREFIX | DT_SINGLELINE); addr_rect.left = addr_rect.right; } if (num_width_ > 0) { int ww = num_width_ + 1; char *addr_buf = ss.GetBuffer(24); // reserve space for 64 bit address sprintf(addr_buf, "%*I64d:", num_width_, line + display_.addrbase1); ss.ReleaseBuffer(-1); if (theApp.nice_addr_) { AddCommas(ss); ww += (num_width_-1)/3; } pDC->SetTextColor(GetDecAddrCol()); // Colour of dec addresses addr_rect.right = addr_rect.left + ww*char_width; pDC->DrawText(ss, &addr_rect, DT_TOP | DT_RIGHT | DT_NOPREFIX | DT_SINGLELINE); addr_rect.left = addr_rect.right; } } // Keep track of the current colour so we only set it when it changes COLORREF current_colour = kala[buf[ii]]; pDC->SetTextColor(current_colour); if (display_.vert_display || display_.hex_area) { int posx = tt.left + hex_pos(0, char_width); // Horiz pos of 1st hex column // Display each byte as hex (and char if nec.) for (size_t jj = ii ; jj < last_col; ++jj) { if (display_.vert_display) { if (posx + int(jj + 1 + jj/group_by_)*char_width_w < 0) continue; else if (posx + int(jj + jj/group_by_)*char_width_w >= tt.right) break; } else { if (posx + int((jj+1)*3 + jj/group_by_)*char_width < 0) continue; else if (posx + int(jj*3 + jj/group_by_)*char_width >= tt.right) break; } if (current_colour != kala[buf[jj]]) { current_colour = kala[buf[jj]]; pDC->SetTextColor(current_colour); } if (display_.vert_display) { // Now display the character in the top row if (display_.char_set != CHARSET_EBCDIC) { if ((buf[jj] >= 32 && buf[jj] < 127) || (display_.char_set != CHARSET_ASCII && buf[jj] >= first_char_ && buf[jj] <= last_char_) ) { // Display normal char or graphic char if in font pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, (char *)&buf[jj], 1); } else if (display_.control == 0 || buf[jj] >= 32) { // Display control char and other chars as red '.' pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, ".", 1); } else if (display_.control == 1) { // Display control chars as red uppercase equiv. char cc = buf[jj] + 0x40; pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, &cc, 1); } else if (display_.control == 2) { // Display control chars as C escape code (in red) const char *check = "\a\b\f\n\r\t\v\0"; const char *display = "abfnrtv0"; const char *pp; if (/*buf[jj] != '\0' && */(pp = strchr(check, buf[jj])) != NULL) pp = display + (pp-check); else pp = "."; pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, pp, 1); } } else { // Display EBCDIC (or red dot if not valid EBCDIC char) if (e2a_tab[buf[jj]] == '\0') { pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, ".", 1); } else { pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top, (char *)&e2a_tab[buf[jj]], 1); } } // Display the hex digits below that, one below the other pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top + vert_offset, &hex[(buf[jj]>>4)&0xF], 1); pDC->TextOut(posx + (jj + jj/group_by_)*char_width_w, tt.top + vert_offset*2, &hex[buf[jj]&0xF], 1); } else { char hh[2]; // Create hex digits and display them hh[0] = hex[(buf[jj]>>4)&0xF]; hh[1] = hex[buf[jj]&0xF]; // This actually displays the bytes (in hex)! // Note: removed calcs that were previously encapsulated in hex_pos pDC->TextOut(posx + (jj*3 + jj/group_by_)*char_width, tt.top, hh, 2); } } } if (!display_.vert_display && display_.char_area) { // Keep track of the current colour so we only set it when it changes int posc = tt.left + char_pos(0, char_width, char_width_w); // Horiz pos of 1st char column for (size_t kk = ii ; kk < last_col; ++kk) { if (posc + int(kk+1)*char_width_w < 0) continue; else if (posc + int(kk)*char_width_w >= tt.right) break; if (current_colour != kala[buf[kk]]) { current_colour = kala[buf[kk]]; pDC->SetTextColor(current_colour); } // Display byte in char display area (as ASCII, EBCDIC etc) if (display_.char_set != CHARSET_EBCDIC) { if ((buf[kk] >= 32 && buf[kk] < 127) || (display_.char_set != CHARSET_ASCII && buf[kk] >= first_char_ && buf[kk] <= last_char_) ) { // Display normal char or graphic char if in font pDC->TextOut(posc + kk*char_width_w, tt.top, (char *)&buf[kk], 1); } else if (display_.control == 0 || buf[kk] > 31) { // Display control char and other chars as red '.' pDC->TextOut(posc + kk*char_width_w, tt.top, ".", 1); } else if (display_.control == 1) { // Display control chars as red uppercase equiv. char cc = buf[kk] + 0x40; pDC->TextOut(posc + kk*char_width_w, tt.top, &cc, 1); } else if (display_.control == 2) { // Display control chars as C escape code (in red) const char *check = "\a\b\f\n\r\t\v\0"; const char *display = "abfnrtv0"; const char *pp; if (/*buf[kk] != '\0' && */(pp = strchr(check, buf[kk])) != NULL) pp = display + (pp-check); else pp = "."; pDC->TextOut(posc + kk*char_width_w, tt.top, pp, 1); } } else { // Display EBCDIC (or red dot if not valid EBCDIC char) if (e2a_tab[buf[kk]] == '\0') { pDC->TextOut(posc + kk*char_width_w, tt.top, ".", 1); } else { pDC->TextOut(posc + kk*char_width_w, tt.top, (char *)&e2a_tab[buf[kk]], 1); } } } } // If any part of the line is within the current selection if (!pDC->IsPrinting() && start_addr < end_addr && end_addr > line*rowsize_ - offset_ && start_addr < (line+1)*rowsize_ - offset_) { FILE_ADDRESS start = max(start_addr, line*rowsize_ - offset_); FILE_ADDRESS end = min(end_addr, (line+1)*rowsize_ - offset_); // ASSERT(end > start); ASSERT(display_.hex_area || display_.char_area); if (!display_.vert_display && display_.hex_area) { CRect rev(norm_rect); rev.right = rev.left + hex_pos(int(end - (line*rowsize_ - offset_) - 1)) + 2*text_width_; rev.left += hex_pos(int(start - (line*rowsize_ - offset_))); if (neg_x) { rev.left = -rev.left; rev.right = -rev.right; } if (neg_y) { rev.top = -rev.top; rev.bottom = -rev.bottom; } if (has_focus && !display_.edit_char || num_colours <= 256) pDC->InvertRect(&rev); // Full contrast reverse video only if in editing in hex area else pDC->PatBlt(rev.left, rev.top, rev.right-rev.left, rev.bottom-rev.top, PATINVERT); } if (display_.vert_display || display_.char_area) { // Draw char selection in inverse CRect rev(norm_rect); rev.right = rev.left + char_pos(int(end - (line*rowsize_ - offset_) - 1)) + text_width_w_; rev.left += char_pos(int(start - (line*rowsize_ - offset_))); if (neg_x) { rev.left = -rev.left; rev.right = -rev.right; } if (neg_y) { rev.top = -rev.top; rev.bottom = -rev.bottom; } if (num_colours <= 256 || has_focus && (display_.vert_display || display_.edit_char)) pDC->InvertRect(&rev); else pDC->PatBlt(rev.left, rev.top, rev.right-rev.left, rev.bottom-rev.top, PATINVERT); } } else if (theApp.show_other_ && has_focus && !display_.vert_display && display_.char_area && display_.hex_area && // we can only display in the other area if both exist !pDC->IsPrinting() && start_addr == end_addr && start_addr >= line*rowsize_ - offset_ && start_addr < (line+1)*rowsize_ - offset_) { // Draw "shadow" cursor in the other area FILE_ADDRESS start = max(start_addr, line*rowsize_ - offset_); FILE_ADDRESS end = min(end_addr, (line+1)*rowsize_ - offset_); CRect rev(norm_rect); if (display_.edit_char) { ASSERT(display_.char_area); rev.right = rev.left + hex_pos(int(end - (line*rowsize_ - offset_))) + 2*text_width_; rev.left += hex_pos(int(start - (line*rowsize_ - offset_))); } else { ASSERT(display_.hex_area); rev.right = rev.left + char_pos(int(end - (line*rowsize_ - offset_))) + text_width_w_; rev.left += char_pos(int(start - (line*rowsize_ - offset_))); } if (neg_x) { rev.left = -rev.left; rev.right = -rev.right; } if (neg_y) { rev.top = -rev.top; rev.bottom = -rev.bottom; } pDC->PatBlt(rev.left, rev.top, rev.right-rev.left, rev.bottom-rev.top, PATINVERT); } else if (!has_focus && !pDC->IsPrinting() && start_addr == end_addr && start_addr >= line*rowsize_ - offset_ && start_addr < (line+1)*rowsize_ - offset_) { // Draw "shadow" for current byte when lost focus if (!display_.vert_display && display_.hex_area) { // Get rect for hex area FILE_ADDRESS start = max(start_addr, line*rowsize_ - offset_); FILE_ADDRESS end = min(end_addr, (line+1)*rowsize_ - offset_); CRect rev(norm_rect); rev.right = rev.left + hex_pos(int(end - (line*rowsize_ - offset_))) + 2*text_width_; rev.left += hex_pos(int(start - (line*rowsize_ - offset_))); if (neg_x) { rev.left = -rev.left; rev.right = -rev.right; } if (neg_y) { rev.top = -rev.top; rev.bottom = -rev.bottom; } pDC->PatBlt(rev.left, rev.top, rev.right-rev.left, rev.bottom-rev.top, PATINVERT); } if (display_.vert_display || display_.char_area) { // Get rect for char area or stacked mode FILE_ADDRESS start = max(start_addr, line*rowsize_ - offset_); FILE_ADDRESS end = min(end_addr, (line+1)*rowsize_ - offset_); CRect rev(norm_rect); rev.right = rev.left + char_pos(int(end - (line*rowsize_ - offset_))) + text_width_w_; rev.left += char_pos(int(start - (line*rowsize_ - offset_))); if (neg_x) { rev.left = -rev.left; rev.right = -rev.right; } if (neg_y) { rev.top = -rev.top; rev.bottom = -rev.bottom; } pDC->PatBlt(rev.left, rev.top, rev.right-rev.left, rev.bottom-rev.top, PATINVERT); } } } // for each display (text) line if (pDC->IsPrinting() && print_sel_ && dup_lines_) { curpage_ = -1; // signal that there is no more to print // Display any residual repeated lines count if (repeat_count > 0) { // Display how many times the line was repeated CString mess; if (repeat_count == 1) mess = "Repeated once"; else mess.Format("Repeated %d more times", repeat_count); CRect mess_rect = norm_rect; if (neg_x) { mess_rect.left = -mess_rect.left; mess_rect.right = -mess_rect.right; } if (neg_y) { mess_rect.top = -mess_rect.top; mess_rect.bottom = -mess_rect.bottom; } mess_rect.left += hex_pos(0, char_width); pDC->DrawText(mess, &mess_rect, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_SINGLELINE); } } if (!pDC->IsPrinting()) { ShowCaret(); } // move_dlgs(); } #ifdef RULER_ADJUST // Draws adjuster handles in the ruler void CHexEditView::draw_adjusters(CDC* pDC) { int xpos; // Set up pen and brush colours (all adjusters are the same colour) CPen pen(PS_SOLID, 0, RGB(0,0,0)); // black pen CPen pdash(PS_DOT, 0, RGB(0,0,0)); // for dashed black line CBrush bwhite(RGB(255,255,255)); // white brush CBrush bred(RGB(192,0,0)); // red brush CPen * psp = pDC->SelectObject(&pen); // ptr to saved pen CBrush * psb = pDC->SelectObject(&bwhite); // ptr to saved brush // Show rowsize_ in the ruler ASSERT(rowsize_ > 3); if (!display_.vert_display && display_.hex_area) { if (adjusting_rowsize_ == -1 || adjusting_rowsize_ == rowsize_) xpos = char_pos(0) - text_width_w_/2 - scrollpos_.x; else xpos = hex_pos(adjusting_rowsize_) - scrollpos_.x; if (display_.autofit) pDC->SelectObject(&bred); draw_rowsize(pDC, xpos-1); if (display_.autofit) pDC->SelectObject(&bwhite); if (adjusting_rowsize_ > -1) { (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos-1, bdr_top_); pDC->LineTo(xpos-1, 30000); (void)pDC->SelectObject(pen); } } else if (display_.vert_display || display_.char_area) { if (adjusting_rowsize_ == -1 || adjusting_rowsize_ == rowsize_) xpos = char_pos(rowsize_ - 1) + (3*text_width_w_)/2 - scrollpos_.x; else xpos = char_pos(adjusting_rowsize_) - scrollpos_.x; if (display_.autofit) pDC->SelectObject(&bred); draw_rowsize(pDC, xpos-1); if (display_.autofit) pDC->SelectObject(&bwhite); if (adjusting_rowsize_ > -1) { (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos-1, bdr_top_); pDC->LineTo(xpos-1, 30000); (void)pDC->SelectObject(pen); } } // Show position of "offset_" in the ruler (in hex and/or char areas) ASSERT(offset_ < rowsize_); if (!display_.vert_display && display_.hex_area) { if (adjusting_offset_ > -1) xpos = hex_pos(adjusting_offset_) - scrollpos_.x; else xpos = hex_pos(offset_) - scrollpos_.x; draw_offset(pDC, xpos-1); if (adjusting_offset_ > -1) { (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos-1, bdr_top_); pDC->LineTo(xpos-1, 30000); (void)pDC->SelectObject(pen); } } if (display_.vert_display || display_.char_area) { if (adjusting_offset_ > -1) xpos = char_pos(adjusting_offset_) - scrollpos_.x; else xpos = char_pos(offset_) - scrollpos_.x; if (display_.vert_display || !display_.hex_area) draw_offset(pDC, xpos-1); if (adjusting_offset_ > -1) { (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos-1, bdr_top_); pDC->LineTo(xpos-1, 30000); (void)pDC->SelectObject(pen); } } // Show current grouping if not adjusting (adjusting_group_by_ == -1) OR // current adjust column if not dragged past the edge (adjusting_group_by_ < 9999) if (adjusting_group_by_ == -1 && group_by_ < rowsize_ || adjusting_group_by_ > -1 && adjusting_group_by_ < rowsize_) { if (display_.vert_display) { if (adjusting_group_by_ > -1) xpos = char_pos(adjusting_group_by_) - scrollpos_.x; else xpos = char_pos(group_by_) - scrollpos_.x; if (display_.vert_display && (adjusting_group_by_ == -1 || adjusting_group_by_%group_by_ == 0)) xpos -= text_width_w_/2; draw_group_by(pDC, xpos); if (adjusting_group_by_ > -1) { // Draw vertical dashed line (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos, bdr_top_); pDC->LineTo(xpos, 30000); (void)pDC->SelectObject(pen); } } else if (display_.hex_area) { if (adjusting_group_by_ > -1) xpos = hex_pos(adjusting_group_by_) - 2 - scrollpos_.x; else xpos = hex_pos(group_by_) - 2 - scrollpos_.x; if (adjusting_group_by_ == -1 || adjusting_group_by_%group_by_ == 0) xpos -= (text_width_ - 1); draw_group_by(pDC, xpos); if (adjusting_group_by_ > -1) { (void)pDC->SelectObject(pdash); pDC->MoveTo(xpos, bdr_top_); pDC->LineTo(xpos, 30000); (void)pDC->SelectObject(pen); } } } (void)pDC->SelectObject(psp); (void)pDC->SelectObject(psb); } // Draws row size adjustment handle in the ruler void CHexEditView::draw_rowsize(CDC* pDC, int xpos) { pDC->BeginPath(); pDC->MoveTo(xpos + 2, bdr_top_ - 7); pDC->LineTo(xpos, bdr_top_ - 7); pDC->LineTo(xpos - 3, bdr_top_ - 4); pDC->LineTo(xpos, bdr_top_ - 1); pDC->LineTo(xpos + 2, bdr_top_ - 1); pDC->EndPath(); pDC->StrokeAndFillPath(); } // Draws offset handle in the ruler void CHexEditView::draw_offset(CDC* pDC, int xpos) { pDC->BeginPath(); pDC->MoveTo(xpos - 1, bdr_top_ - 6); pDC->LineTo(xpos - 1, bdr_top_ - 2); pDC->LineTo(xpos, bdr_top_ - 1); pDC->LineTo(xpos + 3, bdr_top_ - 4); pDC->LineTo(xpos, bdr_top_ - 7); pDC->EndPath(); pDC->StrokeAndFillPath(); } // Draws group by handle in the ruler void CHexEditView::draw_group_by(CDC* pDC, int xpos) { pDC->BeginPath(); pDC->MoveTo(xpos - 3, bdr_top_ - 7); pDC->LineTo(xpos - 3, bdr_top_ - 5); pDC->LineTo(xpos, bdr_top_ - 2); pDC->LineTo(xpos + 3, bdr_top_ - 5); pDC->LineTo(xpos + 3, bdr_top_ - 7); pDC->EndPath(); pDC->StrokeAndFillPath(); } #endif void CHexEditView::draw_bg(CDC* pDC, const CRectAp &doc_rect, bool neg_x, bool neg_y, int line_height, int char_width, int char_width_w, COLORREF clr, FILE_ADDRESS start_addr, FILE_ADDRESS end_addr, bool merge /*=true*/, int draw_height /*=-1*/) { if (end_addr < start_addr) return; if (draw_height > -1 && draw_height < 2) draw_height = 2; // make it at least 2 pixels (1 does not draw properly) int saved_rop = pDC->SetROP2(R2_NOTXORPEN); CPen pen(PS_SOLID, 0, clr); CPen * psaved_pen = pDC->SelectObject(&pen); CBrush brush(clr); CBrush * psaved_brush = pDC->SelectObject(&brush); FILE_ADDRESS start_line = (start_addr + offset_)/rowsize_; FILE_ADDRESS end_line = (end_addr + offset_)/rowsize_; int start_in_row = int((start_addr+offset_)%rowsize_); int end_in_row = int((end_addr+offset_)%rowsize_); CRect rct; if (start_line == end_line) { // Draw the block (all on one line) rct.bottom = int((start_line+1) * line_height - doc_rect.top + bdr_top_); rct.top = rct.bottom - (draw_height > 0 ? draw_height : line_height); if (neg_y) { rct.top = -rct.top; rct.bottom = -rct.bottom; } if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(start_in_row, char_width) - doc_rect.left + bdr_left_; rct.right = hex_pos(end_in_row - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (neg_x && rct.left > rct.right || !neg_x && rct.left < rct.right) { if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } } if (display_.vert_display || display_.char_area) { // rct.top = start_line * line_height; // rct.bottom = rct.top + line_height; rct.left = char_pos(start_in_row, char_width, char_width_w) - doc_rect.left + bdr_left_; rct.right = char_pos(end_in_row - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } pDC->SetROP2(saved_rop); pDC->SelectObject(psaved_pen); pDC->SelectObject(psaved_brush); return; // All on one line so that's it } // Block extends over (at least) 2 lines so draw the partial lines at each end rct.bottom = int((start_line+1) * line_height - doc_rect.top + bdr_top_); rct.top = rct.bottom - (draw_height > 0 ? draw_height : line_height); if (neg_y) { rct.top = -rct.top; rct.bottom = -rct.bottom; } if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(start_in_row, char_width) - doc_rect.left + bdr_left_; rct.right = hex_pos(rowsize_ - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } ASSERT(neg_x && rct.left > rct.right || !neg_x && rct.left < rct.right); if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } if (display_.vert_display || display_.char_area) { rct.left = char_pos(start_in_row, char_width, char_width_w) - doc_rect.left + bdr_left_; rct.right = char_pos(rowsize_ - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } // Last (partial) line rct.bottom = int((end_line+1) * line_height - doc_rect.top + bdr_top_); rct.top = rct.bottom - (draw_height > 0 ? draw_height : line_height); if (neg_y) { rct.top = -rct.top; rct.bottom = -rct.bottom; } if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(0, char_width) - doc_rect.left + bdr_left_; rct.right = hex_pos(end_in_row - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (neg_x && rct.left > rct.right || !neg_x && rct.left < rct.right) { if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } } if (display_.vert_display || display_.char_area) { rct.left = char_pos(0, char_width, char_width_w) - doc_rect.left + bdr_left_; rct.right = char_pos(end_in_row - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } // Now draw all the full lines if (draw_height > 0) { // Since we ar not doing a complete fill of the lines (eg underline) // we have to do each line of text individually for (++start_line; start_line < end_line; ++start_line) { rct.bottom = int((start_line+1) * line_height - doc_rect.top + bdr_top_); rct.top = rct.bottom - draw_height; if (neg_y) { rct.top = -rct.top; rct.bottom = -rct.bottom; } if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(0, char_width) - doc_rect.left + bdr_left_; rct.right = hex_pos(rowsize_ - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } ASSERT(neg_x && rct.left > rct.right || !neg_x && rct.left < rct.right); if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } if (display_.vert_display || display_.char_area) { rct.left = char_pos(0, char_width, char_width_w) - doc_rect.left + bdr_left_; rct.right = char_pos(rowsize_ - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } } } else if (start_line + 1 < end_line) { // Draw the complete lines as one block rct.top = int((start_line + 1) * line_height - doc_rect.top + bdr_top_); rct.bottom = int(end_line * line_height - doc_rect.top + bdr_top_); if (neg_y) { rct.top = -rct.top; rct.bottom = -rct.bottom; } if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(0, char_width) - doc_rect.left + bdr_left_; rct.right = hex_pos(rowsize_ - 1, char_width) + 2*char_width - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } ASSERT(neg_x && rct.left > rct.right || !neg_x && rct.left < rct.right); if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } if (display_.vert_display || display_.char_area) { rct.left = char_pos(0, char_width, char_width_w) - doc_rect.left + bdr_left_; rct.right = char_pos(rowsize_ - 1, char_width, char_width_w) + char_width_w - doc_rect.left + bdr_left_; if (neg_x) { rct.left = -rct.left; rct.right = -rct.right; } if (merge) pDC->Rectangle(&rct); else pDC->FillSolidRect(&rct, clr); } } pDC->SetROP2(saved_rop); pDC->SelectObject(psaved_pen); pDC->SelectObject(psaved_brush); return; } // recalc_display() - recalculates everything to do with the display // (and redraws it) if anything about how the window is drawn changes. // This includes font changed, window resized, document changed, display // options changed (address display, char display, autofit turned on etc). void CHexEditView::recalc_display() { // Stop re-entry (can cause inf. recursion) if (in_recalc_display) return; in_recalc_display = true; CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (GetScrollPastEnds() != theApp.scroll_past_ends_) { SetScrollPastEnds(theApp.scroll_past_ends_); SetScroll(GetScroll()); } SetAutoscroll(theApp.autoscroll_accel_); // Save info on the current font { TEXTMETRIC tm; CClientDC dc(this); OnPrepareDC(&dc); dc.GetTextMetrics(&tm); text_height_ = tm.tmHeight + tm.tmExternalLeading; // Height of font first_char_ = tm.tmFirstChar; // 1st valid char of font last_char_ = tm.tmLastChar; // last valid char of font // This causes problems when in IBM/OEM mode since these fonts have characters right down to zero // if (first_char_ < 32) first_char_ = 32; // Some fonts return 30 but 30,31 are nothing // The max char width returned by many fonts is much too big (seems to be bigger than any character in font!?) // text_width_ = tm.tmMaxCharWidth; // width of widest char in font CSize size; ::GetTextExtentPoint32(dc.m_hDC, "D", 1, &size); text_width_ = size.cx; // width of "D" ::GetTextExtentPoint32(dc.m_hDC, "W", 1, &size); text_width_w_ = size.cx; // width of "W" if (display_.vert_display) line_height_ = text_height_ * 3; else line_height_ = text_height_; } // Adjust border for ruler bdr_top_ = 0; if (theApp.ruler_) { if (display_.hex_addr) bdr_top_ += text_height_; // one row of text for hex offsets if (display_.decimal_addr || display_.line_nums) bdr_top_ += text_height_; // one row of text for dec offsets bdr_top_ += 5; // allow room for a thin line } #ifdef TEST_CLIPPING bdr_top_ += 40; #endif FILE_ADDRESS length = GetDocument()->length() + display_.addrbase1; hex_width_ = display_.hex_addr ? SigDigits(length, 16) : 0; dec_width_ = display_.decimal_addr ? SigDigits(length) : 0; num_width_ = 0; calc_addr_width(); if (display_.autofit && display_.line_nums) { // If autofit is on then rowsize_ and num_width_ are mutually dependent so // we have to handle this carefully. int prev_rowsize = 4; // Loop a few timres and see if the value converges for (int ii = 0; ii < 10; ++ii) { num_width_ = SigDigits(length/prev_rowsize); calc_addr_width(); calc_autofit(); if (rowsize_ == prev_rowsize) break; prev_rowsize = rowsize_; } // If it didn't converge then favour the larger value // (I think non-convergence only occurs when the row // size oscillates between 2 adjacent integer values.) if (rowsize_ < prev_rowsize) rowsize_ = prev_rowsize; } else if (display_.autofit) calc_autofit(); else if (display_.line_nums) { num_width_ = SigDigits(length/rowsize_); calc_addr_width(); } // Fit columns to window width? if (display_.autofit) { // Work out the current address of the caret/selection FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Set size before setting scroll/caret to avoid them being moved to "valid" pos if (display_.vert_display) SetTSize(CSizeAp(-1, ((GetDocument()->length() + offset_)/rowsize_ + 1)*3)); // 3 rows of text else SetTSize(CSizeAp(-1, (GetDocument()->length() + offset_)/rowsize_ + 1)); // Make sure scroll position is at left side // SetScroll(CPointAp(0, topleft/rowsize_ * line_height_)); SetScroll(CPointAp(0, GetScroll().y)); // Move the caret/selection to the where the same byte(s) as before SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); } else { if (display_.vert_display) SetTSize(CSizeAp(-1, ((GetDocument()->length() + offset_)/rowsize_ + 1)*3)); // 3 rows of text else SetTSize(CSizeAp(-1, (GetDocument()->length() + offset_)/rowsize_ + 1)); } // Make sure we know the width of the display area if (display_.vert_display || display_.char_area) SetSize(CSize(char_pos(rowsize_-1)+text_width_w_+text_width_w_/2+1, -1)); else { ASSERT(display_.hex_area); display_.hex_area = TRUE; // defensive SetSize(CSize(hex_pos(rowsize_-1)+2*text_width_+text_width_/2+1, -1)); } if (pcv_ != NULL) pcv_->recalc_display(); in_recalc_display = false; } /* recalc_display() */ void CHexEditView::calc_addr_width() { addr_width_ = hex_width_ + dec_width_ + num_width_; // Allow for separators (spaces and commas) if (theApp.nice_addr_) addr_width_ += (hex_width_-1)/4 + (dec_width_-1)/3 + (num_width_-1)/3; // Also add 1 for the colon addr_width_ += hex_width_ > 0 ? 1 : 0; addr_width_ += dec_width_ > 0 ? 1 : 0; addr_width_ += num_width_ > 0 ? 1 : 0; ++addr_width_; } // This is just called from recalc_display void CHexEditView::calc_autofit() { CRect cli; CRectAp rect; // Client rectangle in norm. coords GetDisplayRect(&cli); rect = ConvertFromDP(cli) - GetScroll(); ASSERT(rect.left == 0 && rect.top == 0); // Work out how many columns we can display across the window // NOTE: These calcs are directly related to the calcs in hex_pos and char_pos // Work out width of display area (total minus address area width) int daw = rect.right - addr_width_*text_width_ - text_width_/2 - 1; if (display_.vert_display) { int group_offset = (daw/text_width_w_)%(group_by_ + 1); if (group_offset == 0) group_offset = group_by_; rowsize_ = ((daw/text_width_w_ - 1)/(group_by_ + 1)) * group_by_ + group_offset; // Make sure scroll bars are not shown ASSERT(rowsize_ < 5 || rect.right >= char_pos(rowsize_-1)+text_width_w_); } else if (display_.char_area && display_.hex_area) { int sec_len = group_by_*(3*text_width_ + text_width_w_) + text_width_; int group_offset = (daw % sec_len)/(3*text_width_ + text_width_w_); if (group_offset == group_by_) group_offset = 0; rowsize_ = ((daw + text_width_) / sec_len) * group_by_ + group_offset; ASSERT(rowsize_ < 5 || rect.right >= char_pos(rowsize_-1)+text_width_w_); } else if (display_.char_area) { // This is easy as char area has no grouping rowsize_ = daw/text_width_w_; ASSERT(rowsize_ < 5 || rect.right >= char_pos(rowsize_-1)+text_width_w_); } else { ASSERT(display_.hex_area); display_.hex_area = TRUE; // defensive //rowsize_ = (daw - daw/(3*group_by_+1))/(3*text_width_); int group_offset = (daw/text_width_ - 2)%(3*group_by_ + 1); if (group_offset == 3*group_by_) group_offset--; rowsize_ = ((daw/text_width_ - 2)/(3*group_by_ + 1))*group_by_ + group_offset/3 + 1; ASSERT(rowsize_ < 5 || rect.right >= hex_pos(rowsize_-1)+2*text_width_); } // Must display at least 4 columns & no more than buffer can hold if (rowsize_ < 4) rowsize_ = 4; else if (rowsize_ > max_buf) rowsize_ = max_buf; // Ensure offset is within valid range if (real_offset_ < rowsize_) offset_ = real_offset_; else offset_ = rowsize_ - 1; } // Return doc position given a hex area column number // int CHexEditView::hex_pos(int column, int width) const; // Return closest hex area column given x display position // Inside determines the numbers returned for columns above rowsize_ // 1 (TRUE) will return a value from 0 to rowsize_ - 1 // 0 (FALSE) will return a value from 0 to rowsize_ // -1 will return value possibly greater than rowsize_ int CHexEditView::pos_hex(int pos, int inside) const { int col = pos - addr_width_*text_width_; col -= (col/(text_width_*(group_by_*3+1)))*text_width_; col = col/(3*text_width_); // Make sure col is within valid range if (col < 0) col = 0; else if (inside == 1 && col >= rowsize_) col = rowsize_ - 1; else if (inside == 0 && col > rowsize_) col = rowsize_; return col; } // Return display position given a char area column number // int CHexEditView::char_pos(int column, int width /* = 0 */) const; // Return closest char area column given display (X) coord // Inside determines the numbers returned for columns above rowsize_ // 1 (TRUE) will return a value from 0 to rowsize_ - 1 // 0 (FALSE) will return a value from 0 to rowsize_ // -1 will return value possibly greater than rowsize_ int CHexEditView::pos_char(int pos, int inside) const { int col; if (display_.vert_display) { col = (pos - addr_width_*text_width_)/text_width_w_; col -= col/(group_by_+1); } else if (display_.hex_area) col = (pos - addr_width_*text_width_ - rowsize_*3*text_width_ - ((rowsize_-1)/group_by_)*text_width_) / text_width_w_; else col = (pos - addr_width_*text_width_) / text_width_w_; // Make sure col is within valid range if (col < 0) col = 0; else if (inside == 1 && col >= rowsize_) col = rowsize_ - 1; else if (inside == 0 && col > rowsize_) col = rowsize_; return col; } void CHexEditView::DoInvalidate() { if (((CHexEditApp *)AfxGetApp())->refresh_off_) needs_refresh_ = true; else { if (pav_ != NULL) pav_->Invalidate(); if (pcv_ != NULL) pcv_->Invalidate(); CScrView::DoInvalidate(); } } // Always call this virtual wrapper of CWnd::InvalidateRect // necessary since InvalidateRect is not virtual. void CHexEditView::DoInvalidateRect(LPCRECT lpRect) { if (((CHexEditApp *)AfxGetApp())->refresh_off_) needs_refresh_ = true; else CScrView::DoInvalidateRect(lpRect); } void CHexEditView::DoInvalidateRgn(CRgn* pRgn) { if (((CHexEditApp *)AfxGetApp())->refresh_off_) needs_refresh_ = true; else CScrView::DoInvalidateRgn(pRgn); } void CHexEditView::DoScrollWindow(int xx, int yy) { if (((CHexEditApp *)AfxGetApp())->refresh_off_) needs_refresh_ = true; else { if (theApp.ruler_ && xx != 0) { // We need to scroll the ruler (as it's outside the scroll region) CRect rct; GetDisplayRect(&rct); rct.top = 0; rct.bottom = bdr_top_; ScrollWindow(xx, 0, &rct, &rct); // Also since we do not draw partial numbers at either end // we have to invalidate a bit more at either end than // is invalidated by ScrollWindow. if (xx > 0) rct.right = rct.left + xx + text_width_*3; else rct.left = rct.right + xx - text_width_*3; DoInvalidateRect(&rct); } CScrView::DoScrollWindow(xx, yy); if (yy < 0) { // We need to invalidate a bit of the address area near the top so that partial addresses are not drawn CRect rct; GetDisplayRect(&rct); rct.bottom = rct.top + line_height_; rct.top -= line_height_/4; rct.right = rct.left + addr_width_*text_width_; DoInvalidateRect(&rct); } else if (yy > 0) { // We need to invalidate a bit below the scrolled bit in the address area since // it may be blank when scrolling up (blank area avoids drawing partial address) CRect rct; GetDisplayRect(&rct); rct.top += yy; rct.bottom = rct.top + line_height_; rct.right = rct.left + addr_width_*text_width_; DoInvalidateRect(&rct); } } } void CHexEditView::AfterScroll(CPointAp newpos) { // If we have a compare view and we have synchronised scrolling then scroll to match if (pcv_ != NULL && display_.auto_scroll_comp) pcv_->SetScroll(newpos); } void CHexEditView::DoUpdateWindow() { if (!((CHexEditApp *)AfxGetApp())->refresh_off_) CScrView::DoUpdateWindow(); } void CHexEditView::DoHScroll(int total, int page, int pos) { if (((CHexEditApp *)AfxGetApp())->refresh_off_) { needs_hscroll_ = true; h_total_ = total; h_page_ = page; h_pos_ = pos; } else CScrView::DoHScroll(total, page, pos); } void CHexEditView::DoVScroll(int total, int page, int pos) { if (((CHexEditApp *)AfxGetApp())->refresh_off_) { needs_vscroll_ = true; v_total_ = total; v_page_ = page; v_pos_ = pos; } else CScrView::DoVScroll(total, page, pos); } void CHexEditView::DoUpdate() { if (needs_refresh_) { CScrView::DoInvalidate(); if (pav_ != NULL) pav_->Invalidate(); needs_refresh_ = false; CScrView::DoUpdateWindow(); } if (needs_hscroll_) { CScrView::DoHScroll(h_total_, h_page_, h_pos_); needs_hscroll_ = false; } if (needs_vscroll_) { CScrView::DoVScroll(v_total_, v_page_, v_pos_); needs_vscroll_ = false; } } // InvalidateRange - virtual function called from base class (CScrView) to cause redrawing of // the selection when it is changed due to mouse dragging or Shift+arrow keys. // When dragging with the mouse this function is called twice: // - once with f flag true and passing the whole selection // - once with f flag false and passing only the change in the selection void CHexEditView::InvalidateRange(CPointAp start, CPointAp end, bool f /*=false*/) { BOOL saved_edit_char = display_.edit_char; // Saved value of display_.edit_char FILE_ADDRESS start_addr, end_addr; // Range of addresses to invalidate // Work out what we are invalidating (hex or char area) if (display_.vert_display) ; // do nothing since edit_char does not affect pos2addr for vert_display else if (!display_.hex_area || (display_.char_area && pos_hex(start.x) == rowsize_ && pos_hex(end.x) == rowsize_)) display_.edit_char = TRUE; // Change display_.edit_char so pos2addr() works else display_.edit_char = FALSE; // Work out range to invalidate (WARNING: this relies on display_.edit_char) start_addr = pos2addr(start); end_addr = pos2addr(end); display_.edit_char = saved_edit_char; // Restore display_.edit_char if (theApp.show_other_) ++end_addr; else if (start_addr == end_addr) return; if (f) { // When dragging with the mouse the selected area in the hex view is only // invalidated in the part of the selection that actually changes - this // avoids the flickering which still occurs with kb (Shift+arrow) selection. // However, as the selectiop for the aerial view is drawn with a boundary // (marching ants) this leaves bits of the old boundary behind when increasing // the selection size by dragging the mouse. The f flag signals that the // whole of the selection (start_addr to end_addr) should be invalidated // in the aerial view. if (pav_ != NULL) pav_->InvalidateRange(start_addr, end_addr); } else { // Note: We need to invalidate an extra char backwards because in the hex // display area the white space to the right of the last byte selected is // not shown in reverse video. When the selection is extended towards the // end of file (causing InvalidateRange to be called) not only the newly // selected bytes need to be invalidated but also the previous one so that // the white area after the character is then drawn in reverse video. invalidate_hex_addr_range(start_addr-1, end_addr); // Also invalidate in aerial view so it can "undraw" the selection if it is smaller if (pav_ != NULL) pav_->InvalidateRange(start_addr, end_addr); } } // invalidate_addr_range is called when a part of the display may need redrawing: // - selection changed -> called from InvalidateRange // - focus lost/gained - so that selection can be drawn differently // - replacement of bytes in the document, perhaps in a different view // - insertion/deletion of bytes -> the changed bytes and those following need updating // - undo of changes // - background search finished -> occurrences need updating // - bookmark added or deleted, or bookmarks hidden/shown // - highlight added or highlights hidden/shown // - mark moved (including swap with cursor) -> old and new address // - undo of mark move, highlight etc // Invalidate all addresses in the range that are displayed in the hex view // and aerial view (if there is one). void CHexEditView::invalidate_addr_range(FILE_ADDRESS start_addr, FILE_ADDRESS end_addr) { if (pav_ != NULL) pav_->InvalidateRange(start_addr, end_addr); invalidate_hex_addr_range(start_addr, end_addr); } // Invalidate all of displayed addresses in hex view only void CHexEditView::invalidate_hex_addr_range(FILE_ADDRESS start_addr, FILE_ADDRESS end_addr) { CRect cli; // Client rectangle in device coords CRectAp inv; // The rectangle to actually invalidate (doc coords) CRectAp disp_rect; // Rectangle of display in our coords GetDisplayRect(&cli); disp_rect = ConvertFromDP(cli); // Work out the addresses of the first and (one past) the last byte in display FILE_ADDRESS start_disp = (disp_rect.top/line_height_)*rowsize_ - offset_; FILE_ADDRESS end_disp = (disp_rect.bottom/line_height_ + 1)*rowsize_ - offset_; // Reduce address range to relevant (displayed) area if (start_addr < start_disp) start_addr = start_disp; if (end_addr > end_disp) end_addr = end_disp; if (start_addr >= end_addr) return; // Nothing to invalidate or all outside display // Work out line range that needs invalidating FILE_ADDRESS start_line = (start_addr + offset_)/rowsize_; FILE_ADDRESS end_line = (end_addr + offset_)/rowsize_; // If start and end on the same line just invalidate between them if (start_line == end_line) { ASSERT(display_.hex_area || display_.char_area); if (!display_.vert_display && display_.hex_area) { // Note: (23/11/03) go back an extra text_width_ bytes to allow for // deletion mark (tracking changes) before the byte inv = CRectAp(hex_pos(int((start_addr+offset_)%rowsize_)) - text_width_, start_line * line_height_, hex_pos(int((end_addr+offset_)%rowsize_)) + 1, (start_line + 1) * line_height_ + 1); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); } if (display_.vert_display || display_.char_area) { // Note: (23/11/03) go back an extra 2 pixels to allow for // deletion mark (tracking changes) before the byte inv = CRectAp(char_pos(int((start_addr+offset_)%rowsize_)) - 2, start_line * line_height_, char_pos(int((end_addr+offset_)%rowsize_)) + 1, (start_line + 1) * line_height_ + 1); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); } return; } // Start line is before end line: invalidate partial lines at each end ASSERT(display_.hex_area || display_.char_area); if (!display_.vert_display && display_.hex_area) { // Hex area inv = CRectAp(hex_pos(int((start_addr+offset_)%rowsize_))-text_width_, start_line * line_height_, hex_pos(int(rowsize_)) + 1, (start_line + 1) * line_height_ + 1); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); inv = CRectAp(hex_pos(0)-text_width_, end_line * line_height_, hex_pos(int((end_addr+offset_)%rowsize_)) + 1, (end_line + 1) * line_height_ + 1); dev = ConvertToDP(inv); DoInvalidateRect(&dev); } if (display_.vert_display || display_.char_area) { // Char area or vert_display inv = CRectAp(char_pos(int((start_addr+offset_)%rowsize_))-2, start_line * line_height_, char_pos(int(rowsize_)), (start_line + 1) * line_height_); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); inv = CRectAp(char_pos(0)-2, end_line * line_height_, char_pos(int((end_addr+offset_)%rowsize_)), (end_line + 1) * line_height_); dev = ConvertToDP(inv); DoInvalidateRect(&dev); } // If more than one line between start and end then invalidate that block too if (start_line + 1 < end_line) { ASSERT(display_.hex_area || display_.char_area); if (!display_.vert_display && display_.hex_area) { inv = CRectAp(hex_pos(0)-text_width_, (start_line + 1) * line_height_, hex_pos(rowsize_) + 1, (end_line) * line_height_ + 1); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); } if (display_.vert_display || display_.char_area) { inv = CRectAp(char_pos(0)-2, (start_line + 1) * line_height_, char_pos(rowsize_) + 1, (end_line) * line_height_ + 1); CRect dev = ConvertToDP(inv); DoInvalidateRect(&dev); } } } // Override CScrView::ValidateScroll() void CHexEditView::ValidateScroll(CPointAp &pos, BOOL strict /* =FALSE */) { CScrView::ValidateScroll(pos, strict); // Get search occurrences currently in display area whenever we change the scroll posn - // this saves checking all addresses (could be millions) in OnDraw search_pair_.clear(); if (GetDocument()->CanDoSearch() && theApp.pboyer_ != NULL) { CHexEditDoc *pdoc = GetDocument(); CRect cli; CRectAp rct; GetDisplayRect(&cli); rct = ConvertFromDP(cli); FILE_ADDRESS start, end; // range of file addresses within display // Get all occurrences that are within the display - this includes those // that have an address before the start of display but extend into it. start = (pos.y/line_height_)*rowsize_ - offset_ // First addr in display - (theApp.pboyer_->length() - 1); // Length of current search string - 1 if (start < 0) start = 0; // Just in case (prob not nec.) end = ((pos.y+rct.Height())/line_height_ + 1)*rowsize_ - offset_; std::vector<FILE_ADDRESS> sf = pdoc->SearchAddresses(start, end); search_length_ = theApp.pboyer_->length(); std::vector<FILE_ADDRESS>::const_iterator pp = sf.begin(); std::vector<FILE_ADDRESS>::const_iterator pend = sf.end(); pair<FILE_ADDRESS, FILE_ADDRESS> good_pair; if (pp != pend) { good_pair.first = *pp; good_pair.second = *pp + search_length_; while (++pp != pend) { if (*pp >= good_pair.second) { search_pair_.push_back(good_pair); good_pair.first = *pp; } good_pair.second = *pp + search_length_; } search_pair_.push_back(good_pair); } } } // Override CScrView::ValidateCaret() void CHexEditView::ValidateCaret(CPointAp &pos, BOOL inside /*=true*/) { // Ensure pos is a valid caret position or move it to the closest such one FILE_ADDRESS address = pos2addr(pos, inside); if (address < 0) address = 0; else if (address > GetDocument()->length()) address = GetDocument()->length(); if (display_.vert_display) { pos = addr2pos(address, pos2row(pos)); // All the following is to avoid problem of dragging a selection within the same "line" but // up a "row" and forward a column. This caused no selection to be drawn and the selection // tip to show a negative selection length. CPointAp start, end; // Current selection CPointAp base; // Base of current selection (initial point clicked) if (GetSel(start, end)) base = end; else base = start; // If we have a non-zero selection if (mouse_down_ && pos != base) pos = addr2pos(address, pos2row(base)); // Make end selection row same as start selection row } else pos = addr2pos(address); } void CHexEditView::DisplayCaret(int char_width /*= -1*/) { // If no character width given default to width of hex or char area text if (char_width == -1 && (display_.edit_char || display_.vert_display)) char_width = text_width_w_; else if (char_width == -1) char_width = text_width_; CScrView::DisplayCaret(char_width); // Since the window may be scrolled without the mouse even moving we // have to make sure that the byte addr/ruler highlight byte is updated. CPoint pt; ::GetCursorPos(&pt); // get mouse location (screen coords) ScreenToClient(&pt); set_mouse_addr(address_at(pt)); move_dlgs(); // scrolling may also have moved caret under a dialog } // Move the modeless dialogs if visible and it/they obscure the caret void CHexEditView::move_dlgs() { // Get doc size so we know width of visible area CSizeAp tt, pp, ll; // Size of document total,page,line GetSize(tt, pp, ll); // Get the selection so we can work out a rectangle bounding the selection CPointAp start, end; // Points of start/end of selection GetSel(start, end); CRectAp selrect; // Rect enclosing selection + a bit if (start.y == end.y) // No selection or all on a single line? selrect = CRectAp(start.x - 2*ll.cx, start.y - ll.cy, end.x + 3*ll.cx, end.y + 2*ll.cy); else selrect = CRectAp(0, start.y - ll.cy, // multi-line selection tt.cx, end.y + 2*ll.cy); // Get display rectangle (also in doc coords) CRect cli; GetDisplayRect(&cli); CRectAp doc_rect = ConvertFromDP(cli); // See if any of the selection is visible (intersect selection & display) CRectAp sd_rect; // selection that is visible if (!sd_rect.IntersectRect(doc_rect, selrect)) return; // Selection not in display // Get rect (selection visible in display) in screen (device) coords CRect dev_rect = ConvertToDP(sd_rect); ClientToScreen(&dev_rect); HideCaret(); // Tell mainframe to move all its dialog bars if (theApp.dlg_move_) ((CMainFrame *)theApp.m_pMainWnd)->move_bars(dev_rect); ShowCaret(); } // Move scroll or caret position in response to a key press. // Note that this overrides CScrView::MovePos(). BOOL CHexEditView::MovePos(UINT nChar, UINT nRepCnt, BOOL control_down, BOOL shift_down, BOOL caret_on) { // CScrView::MovePos scrolling behaviour is OK if (!caret_on) return CScrView::MovePos(nChar, nRepCnt, control_down, shift_down, caret_on); CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (aa->recording_) { long vv = nChar; if (control_down) vv |= 0x10000; if (shift_down) vv |= 0x20000; for (UINT ii = 0; ii < nRepCnt; ++ii) aa->SaveToMacro(km_key, vv); } FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); // Is selection base at end of selection? int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); FILE_ADDRESS new_address; CString desc("Cursor key"); // Start with start of (or end of, if moving forwards) current selection if (shift_down) { // Work out which end of selection is being extended if (end_base) new_address = start_addr; else new_address = end_addr; ++shift_moves_; } else if (start_addr == end_addr ) new_address = start_addr; // No current selection else if (nChar == VK_DOWN || nChar == VK_NEXT) new_address = end_addr; // Move from char after selection else if (nChar == VK_RIGHT || nChar == VK_END) new_address = end_addr - 1; // Move from last char of selection else new_address = start_addr; // Move from start of selection CSizeAp tt, pp, ll; // Size of document total,page,line switch (nChar) { case VK_LEFT: if (control_down) { desc = "Ctrl + Left Arrow"; // Work out how many groups there are to start of file long gpr = (rowsize_ - 1)/group_by_ + 1; // groups per row FILE_ADDRESS groups = ((new_address+offset_)/rowsize_) * gpr + ((new_address+offset_)%rowsize_ + group_by_ - 1)/group_by_; // Calculate the group to move to and address of 1st byte groups -= nRepCnt; new_address = (groups/gpr) * rowsize_ - offset_ + (groups%gpr) * group_by_; } else { desc = "Left Arrow"; new_address -= nRepCnt; } break; case VK_RIGHT: if (control_down) { desc = "Ctrl + Right Arrow"; // First work out how many groups there are to start of file long gpr = (rowsize_ - 1)/group_by_ + 1; // groups per row FILE_ADDRESS groups = ((new_address+offset_)/rowsize_) * gpr + ((new_address+offset_)%rowsize_)/group_by_; // Calculate the group to move to groups += nRepCnt; new_address = (groups/gpr) * rowsize_ - offset_ + (groups%gpr) * group_by_; } else { desc = "Right Arrow"; new_address += nRepCnt; } break; case VK_UP: desc = "Up Arrow"; if (display_.vert_display && !shift_down) { new_address -= rowsize_ * ((2 - row + nRepCnt)/3); row = (3333 + row - nRepCnt)%3; // Add a large number div. by 3 to make sure % operand is +ve } else new_address -= rowsize_ * nRepCnt; break; case VK_DOWN: desc = "Down Arrow"; if (display_.vert_display && !shift_down) { new_address += rowsize_ * ((row + nRepCnt)/3); row = (row + nRepCnt)%3; } else new_address += rowsize_ * nRepCnt; break; case VK_HOME: if (control_down) { desc = "Ctrl + Home key "; // space at end means significant nav pt new_address = 0; } else { desc = "Home key"; new_address = ((new_address+offset_)/rowsize_) * rowsize_ - offset_; } break; case VK_END: if (control_down) { desc = "Ctrl + End key "; // space at end means significant nav pt new_address = GetDocument()->length(); } else { desc = "End key"; new_address = ((new_address+offset_)/rowsize_ + 1) * rowsize_ - offset_ - (shift_down ? 0 : 1); } break; case VK_PRIOR: desc = "Page Up"; GetSize(tt, pp, ll); new_address -= rowsize_ * (pp.cy/line_height_) * nRepCnt; break; case VK_NEXT: desc = "Page Down"; GetSize(tt, pp, ll); new_address += rowsize_ * (pp.cy/line_height_) * nRepCnt; break; default: return CScrView::MovePos(nChar, nRepCnt, control_down, shift_down, caret_on); } if (new_address < 0) { new_address = 0; row = 0; aa->mac_error_ = 2; } else if (new_address > GetDocument()->length()) { new_address = GetDocument()->length(); if (display_.vert_display && !shift_down) row = 2; aa->mac_error_ = 2; } // Scroll addresses into view if moved to left column of hex area or // left column of char area when no hex area displayed if ((new_address + offset_) % rowsize_ == 0 && (display_.vert_display || !display_.edit_char || !display_.hex_area)) SetScroll(CPointAp(0,-1)); if (shift_down && end_base) { MoveWithDesc("Shift + " + desc, end_addr, new_address); // Handle this when shift key released now (in OnKeyUp) // if (aa->highlight_) // add_highlight(new_address, end_addr, TRUE); } else if (shift_down) { MoveWithDesc("Shift + " + desc, start_addr, new_address); // Handle this when shift key released now (in OnKeyUp) // if (aa->highlight_) // add_highlight(start_addr, new_address, TRUE); } else MoveWithDesc(desc, new_address, -1, -1, -1, FALSE, FALSE, row); return TRUE; // Indicate that keystroke used } // Move the caret to new position (or as close as possible). // Returns the new position which may be diff to the requested position if // the requested position was invalid (past EOF). // Note: Does not update address in tool bar combo (use show_pos(GetPos()), // or make sure the caret within display, and does not save undo info. FILE_ADDRESS CHexEditView::GoAddress(FILE_ADDRESS start_addr, FILE_ADDRESS end_addr /*=-1*/) { // Get row from top 2 bits of start_address (vert_display mode) int row = int(start_addr>>62) & 0x3; start_addr &= 0x3fffFFFFffffFFFF; if (end_addr < 0 || end_addr > GetDocument()->length()) end_addr = start_addr; if (start_addr < 0 || start_addr > GetDocument()->length()) start_addr = end_addr = GetDocument()->length(); ASSERT(row == 0 || (row < 3 && display_.vert_display && start_addr == end_addr)); SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); return start_addr; } // Move the caret to new position updating everything: // - saves previous position in undo array (if caret is actually moved) // - updates the display address in the tool bar address edit controls // - Makes sure the caret is visible within display // - astart/aend = new selection (if aend = -1 or aend=astart then just sets caret) // - pstart/pend = previous selection to be saved in undo list (if they are // -1 it uses the current selection/caret) // - ptoo = when undo info saved combine it with previous operation (used if the move is part of a larger operation) // - no_dffd = don't sync DFFD view (if any) even in sync mode (avoids inf. mutually recursive calls) // - row = stacked mode row (0 to 2) - only important when setting caret not for block selection (includes all rows) // - desc = describes why a move was made (eg Bookmark, Search) so that info can be given in nav point list void CHexEditView::MoveToAddress(FILE_ADDRESS astart, FILE_ADDRESS aend /*=-1*/, FILE_ADDRESS pstart /*=-1*/, FILE_ADDRESS pend /*=-1*/, BOOL ptoo /*=FALSE*/, BOOL no_dffd /*=FALSE*/, int row /*=0*/, LPCTSTR desc /*=NULL*/) { ASSERT((astart & ~0x3fffFFFFffffFFFF) == 0); // Make sure top 2 bits not on ASSERT(pstart == -1 || (pstart & ~0x3fffFFFFffffFFFF) == 0); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing since caret moved if (astart < 0 || astart > GetDocument()->length()) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); char buf[128]; sprintf(buf, "Attempt to jump to invalid address %I64d\r" "Jump to EOF instead and continue?", __int64(astart)); if (AfxMessageBox(buf, MB_OKCANCEL) != IDOK) { aa->mac_error_ = 10; return; } else aa->mac_error_ = 1; astart = GetDocument()->length(); } if (aend < 0 || aend > GetDocument()->length()) aend = astart; ASSERT(pstart >= -1 && pstart <= GetDocument()->length()); ASSERT(pend >= pstart && pend <= GetDocument()->length()); int prow = 0; // Row of cursor if vert_display mode if (pstart < 0 || pstart > GetDocument()->length() || pend < pstart || pend > GetDocument()->length()) { GetSelAddr(pstart, pend); if (pstart == pend && display_.vert_display) prow = pos2row(GetCaret()); } // Is the caret/selection now in a different position if (astart != pstart || aend != pend || row != prow) { // Move the caret/selection (THIS IS THE IMPORTANT BIT) SetSel(addr2pos(astart, row), addr2pos(aend, row), true); // Now check if we are just reversing an operation and we should just remove previous undo if (theApp.intelligent_undo_ && // intelligent undo is turned on astart == aend && // not a selection undo_.size() > 0 && // there is an undo op on the stack undo_.back().utype == undo_move && // previous op was a move !undo_.back().previous_too && // and not part of another operation undo_.back().address == (astart | (FILE_ADDRESS(row)<<62))) // and same address/row { undo_.pop_back(); } else { undo_.push_back(view_undo(undo_move, ptoo)); // Save move in undo array undo_.back().address = pstart | (FILE_ADDRESS(prow)<<62); if (pstart != pend) { undo_.push_back(view_undo(undo_sel, ptoo)); // Save selection end in undo array undo_.back().address = pend; } } nav_save(astart, aend, desc); show_prop(); // Update prop modeless dlg show_calc(); show_pos(-1, no_dffd); // Update tool bar } DisplayCaret(); // Make sure caret is in the display } void CHexEditView::SetSel(CPointAp start, CPointAp end, bool base1 /*= false*/) { if (theApp.hl_caret_) { FILE_ADDRESS old_addr, end_addr, new_addr; BOOL end_base = GetSelAddr(old_addr, end_addr); // Get current caret before CScrView::SetSel moves it //if (end_base) old_addr = end_addr; CScrView::SetSel(start, end, base1); new_addr = pos2addr(start); if (old_addr != new_addr) { invalidate_addr(old_addr); invalidate_addr(new_addr); invalidate_ruler(old_addr); invalidate_ruler(new_addr); } } else CScrView::SetSel(start, end, base1); } void CHexEditView::set_mouse_addr(FILE_ADDRESS addr) { if (!theApp.hl_mouse_ || addr == mouse_addr_) return; // no change so do nothing FILE_ADDRESS old_addr = mouse_addr_; mouse_addr_ = addr; invalidate_addr(old_addr); invalidate_ruler(old_addr); invalidate_addr(addr); invalidate_ruler(addr); if (addr > - 1) track_mouse(TME_LEAVE); // make sure we get a leave event when the mouse is moved outside } // Invalidate part of ruler related to an address void CHexEditView::invalidate_ruler(FILE_ADDRESS addr) { if (!theApp.ruler_) return; int horz = bdr_left_ - GetScroll().x; // Offset of left side of doc from left side of window CRect rct; rct.top = 0; rct.bottom = bdr_top_; if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(int((addr+offset_)%rowsize_)) + horz; rct.right = hex_pos(int((addr+offset_)%rowsize_)+1) + horz; DoInvalidateRect(&rct); } if (display_.vert_display || display_.char_area) { rct.left = char_pos(int((addr+offset_)%rowsize_)) + horz; rct.right = char_pos(int((addr+offset_)%rowsize_)+1) + horz + 1; DoInvalidateRect(&rct); } } #ifdef RULER_ADJUST // Invalidate part of ruler related to an address void CHexEditView::invalidate_adjuster(int col) { if (col < 0) return; CRect rct(-1, 0, -1, 30000); if (!display_.vert_display && display_.hex_area) { rct.left = hex_pos(col) - scrollpos_.x; rct.right = rct.left + 4; rct.left -= 7; if (col%group_by_ == 0) rct.left -= text_width_; InvalidateRect(&rct); // DoInvalidateRect not nec. as we can't be in a macro?? } if (display_.vert_display || display_.char_area) { rct.left = char_pos(col) - scrollpos_.x; rct.right = rct.left + 4; rct.left -= 7; if (display_.vert_display && col%group_by_ == 0) rct.left -= text_width_w_/2; InvalidateRect(&rct); } } #endif // Invalidate address area based on an address void CHexEditView::invalidate_addr(FILE_ADDRESS addr) { CRect rct; GetDisplayRect(&rct); CRectAp doc_rect = ConvertFromDP(rct); CRect addr_rect; addr_rect.left = bdr_left_; addr_rect.right = bdr_left_ - doc_rect.left + addr_width_*text_width_ - text_width_/2; // If moved and the address area is visible ... if (addr_rect.right <= addr_rect.left) return; // Address area is off window to the left FILE_ADDRESS first_disp = (doc_rect.top/line_height_) * rowsize_ - offset_; FILE_ADDRESS last_disp = (doc_rect.bottom/line_height_ + 1) * rowsize_ - offset_; if (addr >= first_disp && addr < last_disp) { addr_rect.top = int(bdr_top_ - doc_rect.top + addr2pos(addr).y); addr_rect.bottom = addr_rect.top + text_height_; DoInvalidateRect(&addr_rect); } } void CHexEditView::nav_save(FILE_ADDRESS astart, FILE_ADDRESS aend, LPCTSTR desc) { if (theApp.navman_.InMove()) return; // Check if we have moved enough to store a nav pt bool save_nav = false; // Is this a significant enough move to record in nav stack? bool significant = desc != NULL && desc[strlen(desc)-1] == ' '; // Important nav pts have space at end of desc ++nav_moves_; // The number of rows to move before adding a new nav pt (for significant and insignificant events) FILE_ADDRESS significant_rows = 2; FILE_ADDRESS insignificant_rows = 20; //insignificant_rows = win_size_.cy / line_height_ / 2; // Note: The below checks if the caret has moved more than half a page AND the display has // scrolled. BUT if desc is not NULL (a description was supplied) then this is some sort of // significant event (search, jump to bookmark etc) so keep even if just moved > 2 lines. // Check if the start of selection has moved significantly FILE_ADDRESS curr_line = (astart + offset_)/rowsize_; FILE_ADDRESS prev_line = (nav_start_ + offset_)/rowsize_; if (!significant && mac_abs(curr_line - prev_line) > insignificant_rows || significant && mac_abs(curr_line - prev_line) > significant_rows) { save_nav = true; } // Now do the same test on selection end address curr_line = (aend + offset_)/rowsize_; prev_line = (nav_end_ + offset_)/rowsize_; if (!significant && mac_abs(curr_line - prev_line) > insignificant_rows || significant && mac_abs(curr_line - prev_line) > significant_rows) { save_nav = true; } // If we haven't scrolled vertically yet don't add nav point (unless significant) if (!significant && nav_scroll_ == (GetScroll().y/line_height_)*rowsize_ - offset_) save_nav = false; if (save_nav) { nav_start_ = astart; nav_end_ = aend; nav_scroll_ = (GetScroll().y/line_height_)*rowsize_ - offset_; // If no descripition given work out something from the file if (desc == NULL) desc = "Move"; // Save nav pt in the stack theApp.navman_.Add(desc, get_info(), this, nav_start_, nav_end_, nav_scroll_); } } // Get a bit of the file (as hex or text) to save with a nav point CString CHexEditView::get_info() { FILE_ADDRESS start = nav_start_; if (start >= GetDocument()->length()) { return CString("End\nof\r\nfile"); } if (display_.vert_display && pos2row(GetCaret()) == 0 || display_.edit_char) { // Take a sample of the file as text char buf[36]; char *pp = buf; FILE_ADDRESS aa, end; unsigned char cc = '\0'; end = start + 30; if (end > GetDocument()->length()) end = GetDocument()->length(); // Just use the selection if it is short enough if (start != nav_end_ && nav_end_ < end) end = nav_end_; for (aa = start; aa < end; ++aa) { GetDocument()->GetData(&cc, 1, aa); if (display_.char_set != CHARSET_EBCDIC) { if (isprint(cc)) *pp++ = cc; else goto hex_info; } else { if (e2a_tab[cc] != '\0') *pp++ = e2a_tab[cc]; else goto hex_info; } } *pp = '\0'; if (aa < GetDocument()->length()) strcat(pp, "..."); return CString(buf); } hex_info: { // Take a sample of the file as hex char buf[36]; char *pp = buf; FILE_ADDRESS aa, end; unsigned char cc = '\0'; end = start + 10; if (end > GetDocument()->length()) end = GetDocument()->length(); // Just use the selection if it is short enough if (start != nav_end_ && nav_end_ < end) end = nav_end_; for (aa = start; aa < end; ++aa) { GetDocument()->GetData(&cc, 1, aa); if (theApp.hex_ucase_) sprintf(pp, "%2.2X ", cc); else sprintf(pp, "%2.2x ", cc); pp += 3; } if (aa < GetDocument()->length()) strcat(pp, "..."); return CString(buf); } } #if 0 // This saves a move in the undo array for the caret position when focus // was last lost. This is used by the tool bar address edit controls to // add to the undo list when they move the address of the caret. void CHexEditView::SaveMove() { undo_.push_back(view_undo(undo_move)); undo_.back().address = saved_start_ | (FILE_ADDRESS(saved_row_)<<62); if (saved_start_ != saved_end_) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = saved_end_; } } #endif // Convert an address to a document position CPointAp CHexEditView::addr2pos(FILE_ADDRESS address, int row /*=0*/) const { ASSERT(row == 0 || (display_.vert_display && row < 3)); address += offset_; if (display_.vert_display) return CPointAp(char_pos(int(address%rowsize_)), (address/rowsize_) * line_height_ + row * text_height_); else if (display_.edit_char) return CPointAp(char_pos(int(address%rowsize_)), address/rowsize_ * line_height_); else if ((num_entered_ % 2) == 0) return CPointAp(hex_pos(int(address%rowsize_)), address/rowsize_ * line_height_); else return CPointAp(hex_pos(int(address%rowsize_)) + 2*text_width_, address/rowsize_ * line_height_); } FILE_ADDRESS CHexEditView::pos2addr(CPointAp pos, BOOL inside /*=true*/) const { FILE_ADDRESS address; address = (pos.y/line_height_)*rowsize_ - offset_; if (display_.vert_display || display_.edit_char) address += pos_char(pos.x, inside); else address += pos_hex(pos.x + text_width_/2, inside); return address; } // Given a point in doc coords returns which of the 3 rows of the line the point is in // Note that in vert_display mode row 0 = char, row 1 = top nybble, row 2 = bottom nybble int CHexEditView::pos2row(CPointAp pos) { ASSERT(display_.vert_display); ASSERT((pos.y%line_height_)/text_height_ < 3); return int((pos.y%line_height_)/text_height_); } // Update property display if visible // address = address of byte(s) to show properties of // = -1 to use the current cursor address // = -2 to update even when refresh off (using current cursor address) void CHexEditView::show_prop(FILE_ADDRESS address /*=-1*/) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (address != -2 && aa->refresh_off_) return; CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (address < 0) address = GetPos(); mm->m_wndProp.Update(this, address); } void CHexEditView::show_calc() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!aa->refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); } // Update hex and decimal address tools in edit bar // address = address to show in the address tools // = -1 to use the current cursor address // = -2 to update even when refresh off (using current cursor address) void CHexEditView::show_pos(FILE_ADDRESS address /*=-1*/, BOOL no_dffd /*=FALSE*/) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (address != -2 && aa->refresh_off_) return; CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); CString ss; // String to hold text of edit box FILE_ADDRESS end; if (address < 0) GetSelAddr(address, end); else end = address; #if 0 // BCG (this is handled by calls to AfxGetApp()->OnIdle(0) in searches/compares) // Set the hex address edit box if (aa->hex_ucase_) ss.Format("%lX", address); else ss.Format("%lx", address); mm->hec_hex_addr_.SetWindowText(ss); mm->hec_hex_addr_.add_spaces(); mm->hec_hex_addr_.UpdateWindow(); // Force immed. redraw // Set the decimal address edit box ss.Format("%lu", address); mm->dec_dec_addr_.SetWindowText(ss); mm->dec_dec_addr_.add_commas(); mm->dec_dec_addr_.UpdateWindow(); // Force immed. redraw #else // TRACE1("---- Address set to %ld\n", long(address)); ((CMainFrame *)AfxGetMainWnd())->SetAddress(address); // for ON_UPDATE_COMMAND_UI to fix displayed addresses #endif // Move to corresponding place in other views if sync on if (pdfv_ != NULL && !no_dffd && display_.auto_sync_dffd) pdfv_->SelectAt(address); if (pav_ != NULL && display_.auto_sync_aerial) pav_->ShowPos(address); if (pcv_ != NULL && display_.auto_sync_comp) pcv_->MoveToAddress(address, end); } ///////////////////////////////////////////////////////////////////////////// // CHexEditView diagnostics #ifdef _DEBUG void CHexEditView::AssertValid() const { CScrView::AssertValid(); } void CHexEditView::Dump(CDumpContext& dc) const { dc << "\nrowsize_ = " << rowsize_; dc << "\ntext_height_ = " << text_height_; dc << "\ntext_width_ = " << text_width_; dc << "\nmark_ = " << long(mark_); dc << " mark_char_ = " << display_.mark_char; dc << "\nedit_char_ = " << display_.edit_char; dc << "\novertype_ = " << display_.overtype; dc << "\nreadonly_ = " << display_.readonly; dc << "\nsaved_start_/end_ = " << long(saved_start_) << " " << long(saved_end_); std::vector <view_undo, allocator<view_undo> >::const_iterator pu; for (pu = undo_.begin(); pu != undo_.end(); ++pu) { dc << "\nutype = " << (*pu).utype; switch (pu->utype) { case undo_move: dc << " MOVE from " << long((*pu).address); break; case undo_sel: dc << " SELECTION to " << long((*pu).address); break; case undo_change: dc << " DOC CHANGE this view = " << (*pu).flag; dc << " index = " << (*pu).index; break; case undo_font: dc << " FONT CHANGE "; break; case undo_setmark: dc << " MARK SET address = " << long((*pu).address); break; case undo_rowsize: dc << " ROW SIZE = " << (*pu).rowsize; break; case undo_group_by: dc << " GROUP BY = " << (*pu).rowsize; break; case undo_offset: dc << " OFFSET = " << (*pu).rowsize; break; case undo_unknown: dc << " UNKNOWN"; break; default: dc << " NOT RECOGNISED"; break; } } CScrView::Dump(dc); } CHexEditDoc* CHexEditView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CHexEditDoc))); return (CHexEditDoc*)m_pDocument; } #endif //_DEBUG // Get child frame window of this view. This may be the parent if there are no splitters, // or it may be a more distant ancestor if the immediate parent is a splitter. // This could possibly return NULL but I'm not sure why. CChildFrame *CHexEditView::GetFrame() const { CWnd *pp = GetParent(); while (pp != NULL && !pp->IsKindOf(RUNTIME_CLASS(CChildFrame))) pp = pp->GetParent(); ASSERT_KINDOF(CChildFrame, pp); return (CChildFrame *)pp; } ///////////////////////////////////////////////////////////////////////////// // CHexEditView message handlers BOOL CHexEditView::OnEraseBkgnd(CDC* pDC) { if (bg_col_ == -1) return CScrView::OnEraseBkgnd(pDC); CRect rct; GetClientRect(rct); // Fill background with bg_col_ CBrush backBrush; backBrush.CreateSolidBrush(bg_col_); backBrush.UnrealizeObject(); pDC->FillRect(rct, &backBrush); // Get rect for address area rct.right = addr_width_*text_width_ - GetScroll().x - text_width_ + bdr_left_; // If address area is visible and address background is different to normal background ... if (rct.right > rct.left && addr_bg_col_ != bg_col_) { // Draw address background too CBrush addrBrush; addrBrush.CreateSolidBrush(addr_bg_col_); addrBrush.UnrealizeObject(); pDC->FillRect(rct, &addrBrush); } if (theApp.ruler_ && addr_bg_col_ != bg_col_) { // Ruler background GetClientRect(rct); rct.bottom = bdr_top_ - 4; CBrush addrBrush; addrBrush.CreateSolidBrush(addr_bg_col_); addrBrush.UnrealizeObject(); pDC->FillRect(rct, &addrBrush); } #ifdef _DEBUG // Draw the location of the borders to make sure nothing's drawn outside GetClientRect(rct); CPen *psaved, pen(PS_SOLID, 1, RGB(255,0,0)); psaved = pDC->SelectObject(&pen); CPoint pt; pt.x = rct.right - bdr_right_;pt.y = bdr_top_ - 1; pDC->MoveTo(pt); pt.y = rct.bottom - bdr_bottom_; pDC->LineTo(pt); pt.x = bdr_left_ - 1; pDC->LineTo(pt); pt.y = bdr_top_ - 1; pDC->LineTo(pt); pDC->SelectObject(psaved); #endif return TRUE; } void CHexEditView::OnSize(UINT nType, int cx, int cy) { if (cx == 0 && cy == 0 || in_recalc_display) { CScrView::OnSize(nType, cx, cy); return; } num_entered_ = num_del_ = num_bs_ = 0; // Can't be editing while mousing if (display_.autofit && text_height_ > 0) { if (pcv_ != NULL) pcv_->begin_change(); // This is to try to stay at the same part of the file when in // autofit mode and we get multiple consecutive resize events if (resize_start_addr_ == -1 || resize_curr_scroll_ != GetScroll().y) resize_start_addr_ = pos2addr(GetScroll()); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); recalc_display(); CPointAp pt = addr2pos(resize_start_addr_); pt.x = 0; SetScroll(pt); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); } else recalc_display(); CScrView::OnSize(nType, cx, cy); // Make sure we show all visible search occurrences for the new window size ValidateScroll(GetScroll()); resize_curr_scroll_ = GetScroll().y; // Save current pos so we can check if we are at the same place later } void CHexEditView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CScrView::OnHScroll(nSBCode, nPos, pScrollBar); if (nSBCode != SB_THUMBTRACK) ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_hscroll, (nSBCode << 16) | nPos); } void CHexEditView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CScrView::OnVScroll(nSBCode, nPos, pScrollBar); if (nSBCode != SB_THUMBTRACK) ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_vscroll, (nSBCode << 16) | nPos); } BOOL CHexEditView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { BOOL retval; // As the address under the mouse will probably change we need to get // rid of the tip window which shows info about the byte under the mouse. tip_.Hide(0); if (last_tip_addr_ != -1) { FILE_ADDRESS addr = last_tip_addr_; last_tip_addr_ = -1; invalidate_hex_addr_range(addr, addr+1); } #ifdef RULER_ADJUST ruler_tip_.Hide(0); #endif if ((nFlags & MK_CONTROL) != 0) { // Ctrl+ mouse wheel zooms in/out bool zoomIn = zDelta > 0; if (theApp.reverse_zoom_) zoomIn = !zoomIn; if (zoomIn) OnFontInc(); else OnFontDec(); retval = TRUE; } else retval = CScrView::OnMouseWheel(nFlags, zDelta, pt); if (theApp.hl_mouse_) { // Since the window may be scrolled without the mouse even moving we // have to make sure that the byte addr/ruler highlight byte is updated. CPoint point; ::GetCursorPos(&point); // get mouse location (screen coords) ScreenToClient(&point); set_mouse_addr(address_at(point)); } return retval; } void CHexEditView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { if (mouse_down_ && drag_bookmark_ > -1 && nChar == 27) { // Escape key aborts bookmark drag drag_bookmark_ = -1; mouse_down_ = false; invalidate_addr_range(drag_address_, drag_address_+1); // remove current drag position } else if ((nFlags & 0x2100) == 0) { for (UINT ii = 0; ii < nRepCnt; ++ii) do_char(nChar); } else CScrView::OnChar(nChar, nRepCnt, nFlags); } void CHexEditView::do_char(UINT nChar) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Test if edit key (not special key and not BS, ^\ or nul) // Note: nul byte is just ignored and ^\ is only used in debug version if (strchr("\b\034\0", nChar) == NULL) { unsigned char cc = '\0'; num_del_ = num_bs_ = 0; // We're not deleting // Warn of a number of different problems if (( display_.vert_display && row > 0 || !display_.vert_display && !display_.edit_char) && !isxdigit(nChar)) { // Non hex digit typed in hex area #ifdef SYS_SOUNDS if (!CSystemSound::Play("Invalid Character")) #endif ::Beep(5000,200); aa->mac_error_ = 5; return; } if (( display_.vert_display && row == 0 || !display_.vert_display && display_.edit_char) && display_.char_set == CHARSET_EBCDIC && (nChar > 128 || a2e_tab[nChar] == 0)) { AfxMessageBox("The key is not a valid EBCDIC character"); aa->mac_error_ = 10; return; } if (check_ro("edit")) return; if (display_.overtype && start_addr != end_addr) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("This will delete the current selection\r" "which is not allowed in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && start_addr == GetDocument()->length()) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("You can't extend this file while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 5; return; } else if (!do_insert()) return; } if ((num_entered_ % 2) == 0) DisplayCaret(); // Make sure start is visible // If there is a selection then delete it if (start_addr != end_addr) { ASSERT(start_addr >= 0 && end_addr <= GetDocument()->length() && start_addr < end_addr); GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); } if ( display_.vert_display && row == 0 || !display_.vert_display && display_.edit_char) { // In char area so insert/replace char at this curr locn if (display_.char_set == CHARSET_EBCDIC && nChar < 128) cc = a2e_tab[nChar]; else if (display_.char_set == CHARSET_EBCDIC) cc = '\0'; else cc = (unsigned char)nChar; GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this, start_addr != end_addr); // Move the caret to the next char ++start_addr; num_entered_ += 2; // One char == 2 nybbles } else if (display_.vert_display && row == 1) { ASSERT((num_entered_ % 2) == 0); // Convert to hex and store in top nybble cc = '\0'; if (start_addr < GetDocument()->length()) { // If not at end of doc then get nybble to shift size_t got = GetDocument()->GetData(&cc, 1, start_addr); ASSERT(got == 1); } cc = (cc & 0x0F) | ((isdigit(nChar) ? nChar - '0' : toupper(nChar) - 'A' + 10) << 4); GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this, start_addr != end_addr); // Move to bottom nybble row = 2; ++num_entered_; } else if (display_.vert_display && row == 2) { // Bottom nybble cc = '\0'; if (start_addr < GetDocument()->length()) { // If not at end of doc then get nybble to shift size_t got = GetDocument()->GetData(&cc, 1, start_addr); ASSERT(got == 1); // Check if started entering values on 2nd (bottom) nybble if (num_entered_ == 0) { // Fake entry of first (top nybble) GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this); ++num_entered_; } ASSERT((num_entered_ % 2) != 0); } cc = (cc & 0xF0) | (isdigit(nChar) ? nChar - '0' : toupper(nChar) - 'A' + 10); GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this); // Move to first nybble of next byte start_addr++; row = 1; ++num_entered_; } else if ((num_entered_ % 2) == 0) { // First nybble entered - convert hex to low nybble cc = isdigit(nChar) ? nChar - '0' : toupper(nChar) - 'A' + 10; GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this, start_addr != end_addr); ++num_entered_; } else { // 2nd nybble - shift over 1st nybble and add this nybble cc = '\0'; if (start_addr < GetDocument()->length()) { // If not at end of doc then get nybble to shift size_t got = GetDocument()->GetData(&cc, 1, start_addr); ASSERT(got == 1); } cc = (cc << 4) + (isdigit(nChar) ? nChar - '0' : toupper(nChar) - 'A' + 10); GetDocument()->Change( display_.overtype ? mod_replace : mod_insert, start_addr, 1, &cc, num_entered_, this); // Move the caret to the next byte ++start_addr; ++num_entered_; } SetCaret(addr2pos(start_addr, row)); show_prop(); // Current char under caret may have changed so update prop dlg show_calc(); show_pos(); // Update tool bar if ((num_entered_ % 2) == 0) DisplayCaret(); // Make sure end is visible } #if 0 else if (nChar == '\f') // ^L - centre caret and redraw { CRect cli; // Work out window height in logical units GetDisplayRect(&cli); CRectAp doc_rect = ConvertFromDP(cli); // Move display so that caret is centred vertically CPointAp pp = GetCaret(); pp.x = 0; // Scroll to left side (but see DisplayCaret() below) if ((pp.y -= (doc_rect.bottom-doc_rect.top)/2) < 0) pp.y = 0; SetScroll(pp); DoInvalidate(); // Also redraw display DisplayCaret(); // Make sure caret not off right side } else if (nChar == '\t' && !display_.vert_display && display_.char_area && display_.hex_area) { // Allow tab between hex and char areas if they are both visible num_entered_ = num_del_ = num_bs_ = 0; // Turn off any consec edits // TAB key swaps between hex and char areas FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); undo_.push_back(view_undo(undo_state)); undo_.back().disp_state = disp_state_; display_.edit_char = !display_.edit_char; if (end_base) SetSel(addr2pos(end_addr), addr2pos(start_addr), true); else SetSel(addr2pos(start_addr), addr2pos(end_addr)); DisplayCaret(); } else if (nChar == '\025') // ^U - scroll up { CPointAp pp = GetScroll(); pp.y -= text_height_; SetScroll(pp); } else if (nChar == '\004') // ^D - scroll down { CPointAp pp = GetScroll(); pp.y += text_height_; SetScroll(pp); } else if (nChar == '\r') { num_entered_ = num_del_ = num_bs_ = 0; // Turn off any consec edits FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Check if offset has actually changed if (real_offset_ != (rowsize_ - start_addr%rowsize_)%rowsize_) { undo_.push_back(view_undo(undo_offset)); undo_.back().rowsize = real_offset_; // Save previous offset for undo real_offset_ = offset_ = (rowsize_ - start_addr%rowsize_)%rowsize_; SetSel(addr2pos(start_addr), addr2pos(end_addr)); recalc_display(); DoInvalidate(); } else { ((CMainFrame *)AfxGetMainWnd())-> StatusBarText("Warning: offset not changed"); aa->mac_error_ = 1; } } #endif else if (nChar == '\b') // Back space { // Warn if view is read only if (check_ro("backspace")) return; if (start_addr != end_addr) { // There is a selection - back space just deletes it if (display_.overtype) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("This will delete the current selection\r" "which is not allowed in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 5; return; } else if (!do_insert()) return; } ASSERT(start_addr >= 0 && end_addr <= GetDocument()->length() && start_addr < end_addr); GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); } else { // Back space deletes/replaces previous byte if ((num_entered_ % 2) != 0) // Check if in middle of byte entry ++start_addr; if (start_addr < 1) // We can't back space at the start of file { aa->mac_error_ = 2; return; } start_addr--; // Work out the address of the byte to delete if (!display_.overtype) { // Delete previous char GetDocument()->Change(mod_delback, start_addr, 1, NULL, num_bs_, this); num_bs_ += 2; } else { // Replace previous char in OVR mode with space or nul byte unsigned char cc; if ( display_.vert_display && row == 0 || !display_.vert_display && display_.edit_char) { // Use EBCDIC or ASCII space cc = display_.char_set == CHARSET_EBCDIC ? 0x40 : 0x20; GetDocument()->Change(mod_repback, start_addr, 1, &cc, num_bs_, this); } else { ASSERT(display_.hex_area); cc = '\0'; GetDocument()->Change(mod_repback, start_addr, 1, &cc, num_bs_, this); } ++num_bs_; } } num_del_ = num_entered_ = 0; // turn off any byte entry // Move the caret SetCaret(addr2pos(start_addr)); show_prop(); // New char - check props show_calc(); show_pos(); // Update tool bar DisplayCaret(); // Make sure caret is visible } #ifdef _DEBUG else if (nChar == '\034') { // Just delay for 3 seconds timer tt(true); // This loop is (hopefully) not optimised away in debug mode (optimisations off) while (tt.elapsed () < 2) ; ((CMainFrame *)AfxGetMainWnd())->StatusBarText("Ctrl+\\"); } #endif aa->SaveToMacro(km_char, nChar); } void CHexEditView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { if (nChar >= VK_PRIOR && nChar <= VK_DELETE) { // Cursor movement - reset consec. entered count num_entered_ = num_del_ = num_bs_ = 0; CPointAp start, end; if (GetSel(start, end)) SetSel(end, start, true); else SetSel(start, end); // Calls ValidateCaret - causing caret selection to be moved to valid locations } CScrView::OnKeyDown(nChar, nRepCnt, nFlags); if (nChar == VK_SHIFT && (nFlags & 0x4000) == 0) { // Key down and not autorepeat reset_tip(); shift_moves_ = 0; } update_sel_tip(); // Also make sure info tip is hidden if (nChar != VK_SHIFT) { tip_.Hide(0); // hide immediately if (last_tip_addr_ != -1) { FILE_ADDRESS addr = last_tip_addr_; last_tip_addr_ = -1; invalidate_hex_addr_range(addr, addr+1); } } #ifdef RULER_ADJUST ruler_tip_.Hide(0); #endif } void CHexEditView::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { CScrView::OnKeyUp(nChar, nRepCnt, nFlags); if (nChar == VK_SHIFT) { update_sel_tip(); // Make sure window hidden when shift released if (theApp.highlight_ && shift_moves_) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); add_highlight(start_addr, end_addr, TRUE); } } } void CHexEditView::OnKillFocus(CWnd* pNewWnd) { if (pav_ != NULL && IsWindow(pav_->m_hWnd)) pav_->StopTimer(); // Turn off any animation in aerial view CScrView::OnKillFocus(pNewWnd); if (text_height_ == 0) return; // Save current address in case edit controls move caret GetSelAddr(saved_start_, saved_end_); // CScrView::OnKillFocus(pNewWnd); if (GetView() == NULL) { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); mm->m_wndProp.Update(NULL, -1); } // Invalidate the current selection so its drawn lighter in inactive window FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) ++end_addr; // if no selection invalidate current byte invalidate_hex_addr_range(start_addr, end_addr); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing } void CHexEditView::OnSetFocus(CWnd* pOldWnd) { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing if (pav_ != NULL && IsWindow(pav_->m_hWnd)) pav_->StartTimer(); // Turn on any animation in aerial view CScrView::OnSetFocus(pOldWnd); if (text_height_ < 1) return; #if 0 // Handled in CChildFrame::OnSetFocus now show_prop(); show_calc(); show_pos(); #endif move_dlgs(); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) ++end_addr; // if no selection invalidate the current byte invalidate_hex_addr_range(start_addr, end_addr); // Save nav info in case we need to create a nav pt here if (theApp.navman_.LastView() != this && !theApp.navman_.InMove()) { nav_start_ = start_addr; nav_end_ = end_addr; nav_scroll_ = (GetScroll().y/line_height_)*rowsize_ - offset_; theApp.navman_.Add("Change window", get_info(), this, nav_start_, nav_end_, nav_scroll_); nav_moves_ = 0; } // km_new now seems to get recorded before km_focus - so check if km_new_str is there // (which always follows km_new) and don't store km_focus if (!(theApp.recording_ && theApp.mac_.size() > 0 && (theApp.mac_.back()).ktype == km_new_str) && theApp.pview_ != this) { // We only want to store focus change in a macro, if the last CHexEditView that // got focus is different to this one. This allows us to ignore focus changes // when other things (find dialog, toolbar buttons etc) temp. get focus. // Also this macro entry may be deleted if followed by km_new, km_open, // km_win_new, km_childsys (next/prev win or win close) or km_win_next // since these implicitly change the focus, and setting it explicitly before // to a certain window may ruin their effect. ASSERT(GetFrame() != NULL); CString ss; GetFrame()->GetWindowText(ss); if (ss.Right(2) == " *") ss = ss.Left(ss.GetLength() - 2); // Ignore setfocus before frame has name if (ss.GetLength() > 0) theApp.SaveToMacro(km_focus, ss); } theApp.pview_ = this; } void CHexEditView::OnDestroy() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing if (pav_ != NULL) GetDocument()->RemoveAerialView(); if (pcv_ != NULL) GetDocument()->RemoveCompView(); CScrView::OnDestroy(); // If there are no more views active ... CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (GetView() == NULL) { // If this is the last window we need to make sure that all file // access buttons are disabled in the calculator (if visible) show_calc(); } } // Point is in window coordinates void CHexEditView::OnLButtonDblClk(UINT nFlags, CPoint point) { #if 0 if (point.x < hex_pos(0)) theApp.OnViewDoubleClick(this, IDR_CONTEXT_ADDRESS); else if (display_.vert_display) { CPointAp pp = ConvertFromDP(point); // Convert point to doc coords if (pp.y%line_height_ < text_height_) theApp.OnViewDoubleClick(this, IDR_CONTEXT_CHAR); // click on top (char) row else theApp.OnViewDoubleClick(this, IDR_CONTEXT_HEX); // click on one of bottom 2 rows } else if (!display_.char_area || point.x < char_pos(0)) theApp.OnViewDoubleClick(this, IDR_CONTEXT_HEX); else theApp.OnViewDoubleClick(this, IDR_CONTEXT_CHAR); #endif CPointAp doc_pt = ConvertFromDP(point); if (( (display_.vert_display || display_.char_area) && doc_pt.x >= char_pos(rowsize_)+text_width_ || !(display_.vert_display || display_.char_area) && doc_pt.x >= hex_pos(rowsize_) ) ) { // Don't do anything if off to right return; } if (doc_pt.x < hex_pos(0)) theApp.OnViewDoubleClick(this, IDR_CONTEXT_ADDRESS); else if (display_.vert_display) { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in char area FILE_ADDRESS addr = (doc_pt.y/line_height_)*rowsize_ - offset_ + pos_char(doc_pt.x); //if (addr >= start_addr && addr < end_addr) // theApp.OnViewDoubleClick(this, IDR_CONTEXT_SELECTION); //else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_BOOKMARKS); // click on bookmark else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_HIGHLIGHT); // click on highlight else if (pos2row(doc_pt) == 0) theApp.OnViewDoubleClick(this, IDR_CONTEXT_CHAR); // click on top (char) row else theApp.OnViewDoubleClick(this, IDR_CONTEXT_HEX); // click on one of bottom 2 rows } else if (!display_.char_area || doc_pt.x < char_pos(0)) { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in hex area FILE_ADDRESS addr = (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_hex(doc_pt.x); //if (addr >= start_addr && addr < end_addr) // theApp.OnViewDoubleClick(this, IDR_CONTEXT_SELECTION); //else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_BOOKMARKS); else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_HIGHLIGHT); // click on highlight else theApp.OnViewDoubleClick(this, IDR_CONTEXT_HEX); } else { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in char area FILE_ADDRESS addr = (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_char(doc_pt.x); //if (addr >= start_addr && addr < end_addr) // theApp.OnViewDoubleClick(this, IDR_CONTEXT_SELECTION); //else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_BOOKMARKS); else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) theApp.OnViewDoubleClick(this, IDR_CONTEXT_HIGHLIGHT); // click on highlight else theApp.OnViewDoubleClick(this, IDR_CONTEXT_CHAR); } } #ifdef RULER_ADJUST // Display a tip for an adjuster in the ruler void CHexEditView::add_ruler_tip(CPoint pt, CString ss, COLORREF colour) { CPoint tip_pt; tip_pt = pt + CSize(text_width_w_, text_height_/2); ClientToScreen(&tip_pt); ruler_tip_.Move(tip_pt, false); ruler_tip_.SetWindowText(ss); ruler_tip_.SetBgCol(colour); ruler_tip_.Show(); } // Check if a mouse point is over an adjuster bool CHexEditView::over_rowsize_adjuster(CPointAp pp) { int xpos; if (!display_.vert_display && display_.hex_area) { xpos = char_pos(0) - text_width_w_/2; if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } else if (display_.vert_display || (display_.char_area && !display_.hex_area)) { xpos = char_pos(rowsize_ - 1) + (3*text_width_w_)/2; if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } return false; } bool CHexEditView::over_offset_adjuster(CPointAp pp) { int xpos; if (!display_.vert_display && display_.hex_area) { xpos = hex_pos(offset_); if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } if (display_.vert_display || display_.char_area && !display_.hex_area) { xpos = char_pos(offset_); if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } return false; } bool CHexEditView::over_group_by_adjuster(CPointAp pp) { int xpos; if (display_.vert_display) { xpos = char_pos(group_by_) - text_width_w_/2; if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } else if (display_.hex_area) { xpos = hex_pos(group_by_) - text_width_; if (pp.x > xpos - 5 && pp.x < xpos + 5) return true; } return false; } #endif void CHexEditView::OnLButtonDown(UINT nFlags, CPoint point) { CPointAp pp = ConvertFromDP(point); // Point in our coord system // Click to right of everything is ignored, but click on address area (left side) // is now allowed to allow double-click in address area event to be handled if ( (display_.vert_display || display_.char_area) && pp.x >= char_pos(rowsize_)+text_width_ || !(display_.vert_display || display_.char_area) && pp.x >= hex_pos(rowsize_) ) { return; // Do nothing if off to right } GetSelAddr(prev_start_, prev_end_); prev_row_ = 0; if (prev_start_ == prev_end_ && display_.vert_display) prev_row_ = pos2row(GetCaret()); if (point.y < bdr_top_) // above top (ie in ruler) { #ifdef RULER_ADJUST // Ruler area - check if over any of the adjusters // Check if mouse down on row size adjuster adjusting_rowsize_ = -1; if (over_rowsize_adjuster(pp)) { if (pcv_ != NULL) pcv_->begin_change(); adjusting_rowsize_ = rowsize_; invalidate_adjuster(adjusting_rowsize_); SetCapture(); return; } // Check if the offset adjuster has been clicked adjusting_offset_ = -1; if (over_offset_adjuster(pp)) { if (pcv_ != NULL) pcv_->begin_change(); adjusting_offset_ = offset_; invalidate_adjuster(adjusting_offset_); SetCapture(); return; } adjusting_group_by_ = -1; if (over_group_by_adjuster(pp)) { if (pcv_ != NULL) pcv_->begin_change(); adjusting_group_by_ = group_by_; invalidate_adjuster(adjusting_group_by_); SetCapture(); return; } #endif return; // Don't allow any other select for click in ruler } shift_down_ = shift_down(); // Check if clicked on a bookmark if (!shift_down_ && (drag_bookmark_ = bookmark_at(address_at(point))) > -1) { tip_.Hide(0); if (last_tip_addr_ != -1) { FILE_ADDRESS addr = last_tip_addr_; last_tip_addr_ = -1; invalidate_hex_addr_range(addr, addr+1); } drag_address_ = GetDocument()->bm_posn_[drag_bookmark_]; // start at current bookmark addr mouse_down_ = true; return; // no selection wanted when dragging a bookmark } saved_state_ = disp_state_; // Keep the current state for saving in undo stack // Save some info that may be needed for macro recording dev_down_ = point; // Mouse down posn (device coords) doc_down_ = pp; // Mouse down posn (doc coords) FILE_ADDRESS swap_addr = -1; // caret addr before swap (or -1 if no swap) if (!shift_down_) { num_entered_ = num_del_ = num_bs_ = 0; // Can't be editing while mousing if (!display_.vert_display && display_.char_area && display_.hex_area) { // Allow user to move caret between hex and char areas // Which area did the user click in? // Note display_.edit_char must be set before ValidateCaret() is called while the // mouse button is held down so that the dragged selection is drawn correctly. display_.edit_char = pos_hex(pp.x, FALSE) >= rowsize_; if (saved_state_ != disp_state_) { if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); swap_addr = prev_start_; } } } CScrView::OnLButtonDown(nFlags, point); if (theApp.hl_caret_ && swap_addr > -1) invalidate_ruler(swap_addr); reset_tip(); show_prop(); show_calc(); show_pos(); mouse_down_ = true; // We saw left button down event } void CHexEditView::OnLButtonUp(UINT nFlags, CPoint point) { #ifdef RULER_ADJUST if (adjusting_rowsize_ > -1) { FILE_ADDRESS scroll_addr = pos2addr(GetScroll()); undo_.push_back(view_undo(undo_rowsize)); undo_.back().rowsize = rowsize_; if (display_.autofit) { undo_.push_back(view_undo(undo_autofit, TRUE)); display_.autofit = 0; } rowsize_ = adjusting_rowsize_; if (real_offset_ < rowsize_) offset_ = real_offset_; else offset_ = rowsize_ - 1; recalc_display(); // Fix scroll place so it's about the same even though the row length has changed CPointAp pt = addr2pos(scroll_addr); pt.x = 0; SetScroll(pt); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); ReleaseCapture(); adjusting_rowsize_ = -1; SetSel(addr2pos(prev_start_), addr2pos(prev_end_)); return; } if (adjusting_offset_ > -1) { undo_.push_back(view_undo(undo_offset)); undo_.back().rowsize = real_offset_; // Save previous offset for undo real_offset_ = offset_ = adjusting_offset_; if (real_offset_ >= rowsize_) offset_ = rowsize_ - 1; recalc_display(); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); ReleaseCapture(); adjusting_offset_ = -1; SetSel(addr2pos(prev_start_), addr2pos(prev_end_)); return; } if (adjusting_group_by_ > -1) { undo_.push_back(view_undo(undo_group_by)); undo_.back().rowsize = group_by_; // Save previous group_by for undo group_by_ = adjusting_group_by_; recalc_display(); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); ReleaseCapture(); adjusting_group_by_ = -1; SetSel(addr2pos(prev_start_), addr2pos(prev_end_)); return; } #endif if (mouse_down_ && drag_bookmark_ > -1) { FILE_ADDRESS prev = GetDocument()->bm_posn_[drag_bookmark_]; // Previous bm position if (drag_bookmark_ == bookmark_at(drag_address_)) { // Click on bookmark (or drag back to original location) - just set cursor address MoveToAddress(drag_address_); } else { // Move the bookmark to drag_address_ CBookmarkList *pbl = theApp.GetBookmarkList(); ASSERT(pbl != NULL); pbl->Move(GetDocument()->bm_index_[drag_bookmark_], int(drag_address_ - prev)); // move bm in global list GetDocument()->bm_posn_[drag_bookmark_] = drag_address_; // move in doc's bm list ((CMainFrame *)AfxGetMainWnd())->m_wndBookmarks.UpdateBookmark(GetDocument()->bm_index_[drag_bookmark_]); } drag_bookmark_ = -1; // signal that we are no longer dragging mouse_down_ = false; invalidate_addr_range(prev, prev+1); // force redraw to remove bookmark at old position invalidate_addr_range(drag_address_, drag_address_+1); // redraw bookmark at new position } else if (mouse_down_) { num_entered_ = num_del_ = num_bs_ = 0; // Can't be editing while mousing CScrView::OnLButtonUp(nFlags, point); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Save in undo array if position moved if (prev_start_ != start_addr || prev_end_ != end_addr || saved_state_ != disp_state_) { // Save the caret position (or start of selection) undo_.push_back(view_undo(undo_move)); undo_.back().address = prev_start_ | (FILE_ADDRESS(prev_row_)<<62); if (prev_start_ != prev_end_) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end_; } if (saved_state_ != disp_state_) { // Save the fact that we swapped between areas undo_.push_back(view_undo(undo_state, TRUE)); undo_.back().disp_state = saved_state_; } // Save info to keystroke macro (if recording) CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (aa->recording_) { mouse_sel ms; // Info for km_mouse/km_shift_mouse ms.dev_down = dev_down_; // Point in window where selection started CPointAp doc_up = ConvertFromDP(point); // Point where selection ended (doc coords) // ms.doc_dist = doc_up - doc_down_; // To avoid problems where a different number of rows are selected on play // for slightly different scroll positions we round up to mult. of text_height_. ms.doc_dist.cy = (doc_up.y/text_height_ - doc_down_.y/text_height_) * text_height_; // ms.doc_dist.cx = (doc_up.x/text_width_ - doc_down_.x/text_width_) * text_width_; if (shift_down_) aa->SaveToMacro(km_shift_mouse, &ms); else aa->SaveToMacro(km_mouse, &ms); } if (aa->highlight_) add_highlight(start_addr, end_addr, TRUE); nav_save(start_addr, end_addr, "Mouse Click "); } show_prop(); show_calc(); show_pos(); mouse_down_ = false; update_sel_tip(); // Make sure window hidden when mouse button up if (theApp.hl_caret_) { invalidate_addr(start_addr); invalidate_ruler(start_addr); } } } void CHexEditView::OnMouseMove(UINT nFlags, CPoint point) { #ifdef RULER_ADJUST CPointAp doc_pt = ConvertFromDP(point); if (adjusting_rowsize_ > -1) // Dragging row size adjuster? { CString ss; int old = adjusting_rowsize_; // save current so we can "undraw" it if (!display_.vert_display && display_.hex_area) { if (doc_pt.x < hex_pos(4)) adjusting_rowsize_ = 4; else adjusting_rowsize_ = pos_hex(doc_pt.x + text_width_, -1); } else if (display_.vert_display || display_.char_area) { if (doc_pt.x < char_pos(4)) adjusting_rowsize_ = 4; else adjusting_rowsize_ = pos_char(doc_pt.x + text_width_w_/2, -1); } if (adjusting_rowsize_ != old) { invalidate_adjuster(old); invalidate_adjuster(adjusting_rowsize_); } ss.Format("Columns: %d", adjusting_rowsize_); add_ruler_tip(point, ss, adjusting_rowsize_ != rowsize_ ? RGB(224,255,224) : ::GetSysColor(COLOR_INFOBK)); return; } if (adjusting_offset_ > -1) // Dragging offset adjuster? { CString ss; int old = adjusting_offset_; // save current so we can "undraw" it // Work out new offset from current dragged mouse posn if (display_.vert_display) { int left_side = char_pos(0); if (doc_pt.x < left_side - text_width_) adjusting_offset_ = rowsize_ - (left_side-doc_pt.x)/text_width_; else if (doc_pt.x >= char_pos(rowsize_)) adjusting_offset_ = 0; // Use 0 if dragged too far right else adjusting_offset_ = pos_char(doc_pt.x + text_width_w_/2, TRUE); } else if (display_.char_area && display_.hex_area && doc_pt.x < char_pos(0)) { int left_side = hex_pos(0); if (doc_pt.x < left_side - text_width_) adjusting_offset_ = rowsize_ - (left_side-doc_pt.x)/text_width_; else if (doc_pt.x >= hex_pos(rowsize_)) adjusting_offset_ = 0; else adjusting_offset_ = pos_hex(doc_pt.x + text_width_, TRUE); } else if (display_.char_area) { int left_side = char_pos(0); if (doc_pt.x < left_side - text_width_) adjusting_offset_ = rowsize_ - (left_side-doc_pt.x)/text_width_; else if (doc_pt.x >= char_pos(rowsize_)) adjusting_offset_ = 0; else adjusting_offset_ = pos_char(doc_pt.x + text_width_w_/2, TRUE); } else { int left_side = hex_pos(0); if (doc_pt.x < left_side - text_width_) adjusting_offset_ = rowsize_ - (left_side-doc_pt.x)/text_width_; else if (doc_pt.x >= hex_pos(rowsize_)) adjusting_offset_ = 0; else adjusting_offset_ = pos_hex(doc_pt.x + text_width_, TRUE); } if (adjusting_offset_ < 0) adjusting_offset_ = 0; if (adjusting_offset_ != old) { invalidate_adjuster(old); invalidate_adjuster(adjusting_offset_); } ss.Format("Offset: %d", adjusting_offset_); add_ruler_tip(point, ss, adjusting_offset_ != offset_ ? RGB(224,255,224) : ::GetSysColor(COLOR_INFOBK)); return; } if (adjusting_group_by_ > -1) // Dragging grouping adjuster? { CString ss; int old = adjusting_group_by_; // save current so we can "undraw" it // Work out new group_by_ from current dragged mouse posn if (display_.vert_display) { if (doc_pt.x < char_pos(2)) adjusting_group_by_ = 2; // Minimum //else if (doc_pt.x >= char_pos(rowsize_)) // adjusting_group_by_ = 9999; else adjusting_group_by_ = pos_char(doc_pt.x + text_width_w_/2, -1); } else if (display_.hex_area) { if (doc_pt.x < hex_pos(2)) adjusting_group_by_ = 2; //else if (doc_pt.x >= hex_pos(rowsize_)) // adjusting_group_by_ = 9999; else adjusting_group_by_ = pos_hex(doc_pt.x + text_width_, -1); } if (adjusting_group_by_ != old) { invalidate_adjuster(old); invalidate_adjuster(adjusting_group_by_); } ss.Format("Grouping: %d", adjusting_group_by_); add_ruler_tip(point, ss, adjusting_group_by_ != group_by_ ? RGB(224,255,224) : ::GetSysColor(COLOR_INFOBK)); return; } // Now check if we are hovering over a ruler handle. if (point.y < bdr_top_ && (over_rowsize_adjuster(doc_pt) || over_offset_adjuster(doc_pt) || over_group_by_adjuster(doc_pt)) ) { track_mouse(TME_HOVER); return; } if (!ruler_tip_.FadingOut()) ruler_tip_.Hide(300); // Not dragging or hovering over so hide it #endif FILE_ADDRESS addr = address_at(point); // Address of byte mouse is over (or -1) // If dragging a bookmark update the drag location if (mouse_down_ && drag_bookmark_ > -1) { if (addr < 0 || addr > GetDocument()->length()) return; // don't move to invalid pos FILE_ADDRESS prev = drag_address_; drag_address_ = addr; // we must change this before redraw invalidate_addr_range(prev, prev+1); // force redraw at previous drag position invalidate_addr_range(drag_address_, drag_address_+1); // redraw at new position return; } FILE_ADDRESS old_addr, end_addr, new_addr; if (mouse_down_) GetSelAddr(old_addr, end_addr); // Get current caret before moved CScrView::OnMouseMove(nFlags, point); if (mouse_down_) GetSelAddr(new_addr, end_addr); if (mouse_down_) { tip_.Hide(0); // Make sure there is no mouse tip while dragging move_dlgs(); update_sel_tip(200); // Update selection tip } else if (!tip_.IsWindowVisible()) { // Set a timer so that we can check if we want to display a tip window track_mouse(TME_HOVER); if (last_tip_addr_ != -1) { // Hide the box around the tip byte FILE_ADDRESS addr = last_tip_addr_; last_tip_addr_ = -1; invalidate_hex_addr_range(addr, addr+1); } } else if (addr != last_tip_addr_ && tip_.IsWindowVisible()) { // Hide the tip window since the mouse has moved away if (!tip_.FadingOut()) // Don't keep it alive if we have already told it to fade away tip_.Hide(300); } if (theApp.hl_mouse_) set_mouse_addr(addr); } /* void CHexEditView::OnTimer(UINT nIDEvent) { if (nIDEvent == timer_id_) { VERIFY(KillTimer(timer_id_)); timer_id_ = 0; CPoint pt; GetCursorPos(&pt); ScreenToClient(&pt); if (pt != last_mouse_) return; // Time to show a tip window if we are in the right place FILE_ADDRESS addr = address_at(pt); int bm; if (addr != -1 && (bm = bookmark_at(addr)) != -1) { last_tip_addr_ = addr; CBookmarkList *pbl = theApp.GetBookmarkList(); tip_.SetWindowText(pbl->name_[GetDocument()->bm_index_[bm]]); CPoint point = last_mouse_ + CSize(text_width_w_, text_height_); ClientToScreen(&point); tip_.Move(point, false); tip_.Show(); } } else CScrView::OnTimer(nIDEvent); } */ LRESULT CHexEditView::OnMouseHover(WPARAM, LPARAM lp) { CPoint pt(LOWORD(lp), HIWORD(lp)); // client window coords // Time to show a tip window if we are in the right place if (!mouse_down_ && !tip_.IsWindowVisible()) { FILE_ADDRESS addr = address_at(pt); if (addr != -1 && addr < GetDocument()->length() && update_tip(addr)) { CPoint tip_pt; tip_pt = pt + CSize(text_width_w_, text_height_); last_tip_addr_ = addr; invalidate_hex_addr_range(addr, addr+1); ClientToScreen(&tip_pt); tip_.Move(tip_pt, false); tip_.Show(); track_mouse(TME_LEAVE); return 0; } } #ifdef RULER_ADJUST if (pt.y < bdr_top_ && !ruler_tip_.IsWindowVisible()) { CPointAp pp = ConvertFromDP(pt); // Point in our coord system CString ss; if (over_rowsize_adjuster(pp)) ss.Format("Columns: %d%s", rowsize_, display_.autofit ? " (AutoFit)" : ""); else if (over_offset_adjuster(pp)) ss.Format("Offset: %d", offset_); else if (over_group_by_adjuster(pp)) ss.Format("Grouping: %d", group_by_); if (!ss.IsEmpty()) { add_ruler_tip(pt, ss, ::GetSysColor(COLOR_INFOBK)); track_mouse(TME_LEAVE); return 0; } } #endif return 1; } // Returns true if tip text was updated or false if there is nothing to show. // The parameter (addr) if the address about which we show information bool CHexEditView::update_tip(FILE_ADDRESS addr) { size_t ii; tip_addr_ = addr; ASSERT(theApp.tip_name_.size() > 0); // we should at least have bookmarks ASSERT(theApp.tip_on_ .size() == theApp.tip_name_.size()); ASSERT(theApp.tip_expr_ .size() == theApp.tip_name_.size()); ASSERT(theApp.tip_format_.size() == theApp.tip_name_.size()); tip_.Clear(); // Do desciptions for (ii = 0; ii < theApp.tip_name_.size(); ++ii) { if (theApp.tip_on_[ii]) { if (ii == 0) { // Special (hard-coded) bookmark tip ASSERT(theApp.tip_name_[ii] == "Bookmarks"); if (bookmark_at(addr) != -1) tip_.AddString("Bookmark: "); } // Add any more "hard-coded" tip types here ... else { ASSERT(ii >= FIRST_USER_TIP); tip_.AddString(theApp.tip_name_[ii] + ": "); } } } CPoint pt(0,0); CRect rct = tip_.GetTotalRect(); pt.x = rct.right; int idx = 0; for (ii = 0; ii < theApp.tip_name_.size(); ++ii) { if (theApp.tip_on_[ii]) { if (ii == 0) { // Special (hard-coded) bookmark tip ASSERT(theApp.tip_name_[ii] == "Bookmarks"); int bm; // Index into doc's bookmark list of bookmark under cursor if ((bm = bookmark_at(addr)) != -1) { rct = tip_.GetRect(idx); pt.y = rct.top; tip_.AddString(theApp.GetBookmarkList()->name_[GetDocument()->bm_index_[bm]], -1, &pt); ++idx; } } // Add any more "hard-coded" tip types here ... else { COLORREF col = -1; CString format = theApp.tip_format_[ii]; // Work out the colour of the text if (theApp.tip_expr_[ii].Find("address") != -1 || theApp.tip_expr_[ii].Find("cursor") != -1 || theApp.tip_expr_[ii].Find("sel_len") != -1 || theApp.tip_expr_[ii].Find("mark") != -1 || theApp.tip_expr_[ii].Find("eof") != -1) { // If no format given display as current address format if (format.IsEmpty()) format = DecAddresses() ? "dec" : "hex"; // Display addresses in the appropriate colour if (format.Left(3).CompareNoCase("hex") == 0 || format.Find('x') != -1 || format.Find('X') != -1) { col = GetHexAddrCol(); // display in hex address colour } else if (format.Left(3).CompareNoCase("dec") == 0 || format.Find('u') != -1 || format.Find('d') != -1) { col = GetDecAddrCol(); // display in decimal address colour } // else other int formats like octal, or non-int format such as: // octal, %o, bin, false (boolean), no, off, %s (string) etc } // Work out where to put it rct = tip_.GetRect(idx); pt.y = rct.top; int dummy; expr_eval::value_t val = expr_.evaluate(theApp.tip_expr_[ii], 0, dummy); tip_.AddString(val.GetDataString(format, expr_.GetSize(), expr_.GetUnsigned()), col, &pt); ++idx; } } } ASSERT(ii > 0); // This is mainly here for easier stepping in the debugger ASSERT(tip_.Count() == idx*2); // should have added 2 entries for every tip tip_.SetAlpha(theApp.tip_transparency_); return idx > 0; } LRESULT CHexEditView::OnMouseLeave(WPARAM, LPARAM lp) { tip_.Hide(300); #ifdef RULER_ADJUST ruler_tip_.Hide(300); #endif if (theApp.hl_mouse_) set_mouse_addr(-1); return 0; } void CHexEditView::OnSysColorChange() { CScrView::OnSysColorChange(); set_colours(); Invalidate(); } void CHexEditView::track_mouse(unsigned long flag) { TRACKMOUSEEVENT tme; tme.cbSize = sizeof(tme); tme.dwFlags = flag; tme.dwHoverTime = 0; tme.hwndTrack = m_hWnd; VERIFY(::_TrackMouseEvent(&tme)); } FILE_ADDRESS CHexEditView::address_at(CPoint pt) { if (pt.y < bdr_top_) return -1; // Above top border (ie in ruler) CPointAp doc_pt = ConvertFromDP(pt); // Mouse position (doc coords) if (doc_pt.x < hex_pos(0) || doc_pt.x > char_pos(rowsize_)+text_width_) return -1; // Left of hex area (ie in address area) else if ( (display_.vert_display || display_.char_area) && doc_pt.x >= char_pos(rowsize_)+text_width_ || !(display_.vert_display || display_.char_area) && doc_pt.x >= hex_pos(rowsize_) ) return -1; // Right of areas (ie in blank area) else if (display_.vert_display) return (doc_pt.y/line_height_)*rowsize_ - offset_ + pos_char(doc_pt.x, TRUE); else if (!display_.char_area || doc_pt.x < char_pos(0)) return (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_hex(doc_pt.x, TRUE); else return (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_char(doc_pt.x, TRUE); } // Returns the bookmark at file address or -1 if none int CHexEditView::bookmark_at(FILE_ADDRESS addr) { std::vector<FILE_ADDRESS>::const_iterator pp = std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr); if (pp != GetDocument()->bm_posn_.end()) return pp - GetDocument()->bm_posn_.begin(); else return -1; } void CHexEditView::OnHighlight() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (aa->highlight_) aa->highlight_ = FALSE; else if (start_addr != end_addr) add_highlight(start_addr, end_addr, FALSE); else aa->highlight_ = TRUE; aa->SaveToMacro(km_highlight, (unsigned __int64)1); } void CHexEditView::OnUpdateHighlight(CCmdUI* pCmdUI) { pCmdUI->SetCheck(dynamic_cast<CHexEditApp *>(AfxGetApp())->highlight_); } void CHexEditView::OnHighlightClear() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); aa->highlight_ = FALSE; if (!hl_set_.empty()) { undo_.push_back(view_undo(undo_highlight)); undo_.back().phl = new range_set<FILE_ADDRESS>(hl_set_); hl_set_.clear(); DoInvalidate(); } aa->SaveToMacro(km_highlight); } // Select the current highlight. // This is designed for associating with double-click on a highlight event. void CHexEditView::OnHighlightSelect() { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (hl_set_.range_.empty()) { AfxMessageBox("Nothing highlighted"); theApp.mac_error_ = 10; return; } else { range_set<FILE_ADDRESS>::range_t::const_iterator pp = lower_bound(hl_set_.range_.begin(), hl_set_.range_.end(), range_set<FILE_ADDRESS>::segment(start_addr+1, start_addr+1), segment_compare()); if (pp != hl_set_.range_.begin()) pp--; MoveWithDesc("Select Highlight ", pp->sfirst, pp->slast); theApp. SaveToMacro(km_highlight, (unsigned __int64)5); } } void CHexEditView::OnHighlightPrev() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (hl_set_.range_.empty()) { AfxMessageBox("Nothing highlighted"); aa->mac_error_ = 10; return; } else if (hl_set_.range_.front().sfirst >= start_addr) { AfxMessageBox("No highlight before start of file"); aa->mac_error_ = 10; return; } else { range_set<FILE_ADDRESS>::range_t::const_iterator pp = lower_bound(hl_set_.range_.begin(), hl_set_.range_.end(), range_set<FILE_ADDRESS>::segment(start_addr, end_addr), segment_compare()); ASSERT(pp != hl_set_.range_.begin()); pp--; // Get the previous elt MoveWithDesc("Previous Highlight ", pp->sfirst, pp->slast); aa->SaveToMacro(km_highlight, (unsigned __int64)2); } } void CHexEditView::OnUpdateHighlightPrev(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pCmdUI->Enable(!hl_set_.range_.empty() && hl_set_.range_.front().sfirst < start_addr); } void CHexEditView::OnHighlightNext() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (hl_set_.range_.empty()) { AfxMessageBox("Nothing highlighted"); aa->mac_error_ = 10; return; } else if (hl_set_.range_.back().sfirst <= start_addr) { AfxMessageBox("No highlight before end of file"); aa->mac_error_ = 10; return; } else { range_set<FILE_ADDRESS>::range_t::const_iterator pp = lower_bound(hl_set_.range_.begin(), hl_set_.range_.end(), range_set<FILE_ADDRESS>::segment(start_addr+1, end_addr+1), segment_compare()); ASSERT(pp != hl_set_.range_.end()); MoveWithDesc("Next Highlight ", pp->sfirst, pp->slast); aa->SaveToMacro(km_highlight, (unsigned __int64)3); } } void CHexEditView::OnUpdateHighlightNext(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pCmdUI->Enable(!hl_set_.range_.empty() && hl_set_.range_.back().sfirst > start_addr); } void CHexEditView::add_highlight(FILE_ADDRESS start, FILE_ADDRESS end, BOOL ptoo /*=FALSE*/) { if (start < end) { undo_.push_back(view_undo(undo_highlight, ptoo)); undo_.back().phl = new range_set<FILE_ADDRESS>(hl_set_); range_set<FILE_ADDRESS> tt = hl_set_; tt.insert_range(start, end); // If selected area is already part of highlighted area if (tt == hl_set_) hl_set_.erase_range(start, end); // Remove it from highlight else hl_set_.swap(tt); // else add it to highlight invalidate_addr_range(start, end); } #ifdef _DEBUG for (range_set<FILE_ADDRESS>::range_t::iterator pr = hl_set_.range_.begin(); pr != hl_set_.range_.end(); ++pr) { FILE_ADDRESS fa = pr->sfirst; fa = pr->slast; } #endif } void CHexEditView::OnHighlightHide() { begin_change(); display_.hide_highlight = !display_.hide_highlight; make_change(); end_change(); theApp.SaveToMacro(km_highlight, (unsigned __int64)4); } void CHexEditView::OnUpdateHighlightHide(CCmdUI* pCmdUI) { pCmdUI->SetCheck(display_.hide_highlight); } // We will try returning the bookmark above or -1 if there is none int CHexEditView::ClosestBookmark(FILE_ADDRESS &diff) { std::vector<FILE_ADDRESS>::const_iterator prev_bm = GetDocument()->bm_posn_.end(); diff = GetDocument()->length()+1; // Bigger than any possible difference between current & bookmark FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Find the bookmark that is closest but after the current address for (std::vector<FILE_ADDRESS>::const_iterator pbm = GetDocument()->bm_posn_.begin(); pbm != GetDocument()->bm_posn_.end(); ++pbm) { if (*pbm <= start_addr && start_addr - *pbm < diff) { diff = start_addr - *pbm; prev_bm = pbm; } } if (prev_bm == GetDocument()->bm_posn_.end()) return -1; else return GetDocument()->bm_index_[prev_bm - GetDocument()->bm_posn_.begin()]; } void CHexEditView::OnBookmarksClear() { GetDocument()->ClearBookmarks(); theApp.SaveToMacro(km_bookmarks); } void CHexEditView::OnUpdateBookmarksClear(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->bm_posn_.empty()); } void CHexEditView::OnBookmarksPrev() { std::vector<FILE_ADDRESS>::const_iterator prev_bm = GetDocument()->bm_posn_.end(); FILE_ADDRESS diff = GetDocument()->length()+1; // Bigger than any possible difference between current & bookmark FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Find the bookmark that is closest but after the current address for (std::vector<FILE_ADDRESS>::const_iterator pbm = GetDocument()->bm_posn_.begin(); pbm != GetDocument()->bm_posn_.end(); ++pbm) { if (*pbm < start_addr && start_addr - *pbm < diff) { diff = start_addr - *pbm; prev_bm = pbm; } } if (prev_bm == GetDocument()->bm_posn_.end()) { // No bookmarks found (presumably in macro playback) AfxMessageBox("No bookmarks found towards start of file"); theApp.mac_error_ = 10; return; } MoveWithDesc("Previous Bookmark ", *prev_bm, *prev_bm); theApp.SaveToMacro(km_bookmarks, (unsigned __int64)2); } void CHexEditView::OnUpdateBookmarksPrev(CCmdUI* pCmdUI) { std::vector<FILE_ADDRESS>::const_iterator prev_bm = GetDocument()->bm_posn_.end(); FILE_ADDRESS diff = GetDocument()->length()+1; // Bigger than any possible difference between current & bookmark FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Find the bookmark that is closest but after the current address for (std::vector<FILE_ADDRESS>::const_iterator pbm = GetDocument()->bm_posn_.begin(); pbm != GetDocument()->bm_posn_.end(); ++pbm) { if (*pbm < start_addr && start_addr - *pbm < diff) { diff = start_addr - *pbm; prev_bm = pbm; } } pCmdUI->Enable(prev_bm != GetDocument()->bm_posn_.end()); } void CHexEditView::OnBookmarksNext() { std::vector<FILE_ADDRESS>::const_iterator next_bm = GetDocument()->bm_posn_.end(); FILE_ADDRESS diff = GetDocument()->length()+1; // Bigger than any possible difference between current & bookmark FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Find the bookmark that is closest but after the current address for (std::vector<FILE_ADDRESS>::const_iterator pbm = GetDocument()->bm_posn_.begin(); pbm != GetDocument()->bm_posn_.end(); ++pbm) { if (*pbm > start_addr && *pbm - start_addr < diff) { diff = *pbm - start_addr; next_bm = pbm; } } if (next_bm == GetDocument()->bm_posn_.end()) { // No bookmarks found (presumably in macro playback) AfxMessageBox("No bookmarks before end of file"); theApp.mac_error_ = 10; return; } MoveWithDesc("Next Bookmark ", *next_bm, *next_bm); theApp.SaveToMacro(km_bookmarks, (unsigned __int64)3); } void CHexEditView::OnUpdateBookmarksNext(CCmdUI* pCmdUI) { std::vector<FILE_ADDRESS>::const_iterator next_bm = GetDocument()->bm_posn_.end(); FILE_ADDRESS diff = GetDocument()->length()+1; // Bigger than any possible difference between current & bookmark FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Find the bookmark that is closest but after the current address for (std::vector<FILE_ADDRESS>::const_iterator pbm = GetDocument()->bm_posn_.begin(); pbm != GetDocument()->bm_posn_.end(); ++pbm) { if (*pbm > end_addr && *pbm - end_addr < diff) { diff = *pbm - end_addr; next_bm = pbm; } } pCmdUI->Enable(next_bm != GetDocument()->bm_posn_.end()); } void CHexEditView::OnBookmarksHide() { begin_change(); display_.hide_bookmarks = !display_.hide_bookmarks; make_change(); end_change(); theApp.SaveToMacro(km_bookmarks, (unsigned __int64)4); } void CHexEditView::OnUpdateBookmarksHide(CCmdUI* pCmdUI) { pCmdUI->SetCheck(display_.hide_bookmarks); } void CHexEditView::OnBookmarkToggle() { if (GetDocument()->pfile1_ == NULL) { AfxMessageBox("Bookmarks can only be added to disk files.\r\n" "Please save the file to disk and try again."); ((CHexEditApp *)AfxGetApp())->mac_error_ = 5; return; } int index; CBookmarkList *pbl = theApp.GetBookmarkList(); // Test if there is already a bookmark at this location if ((index = GetDocument()->GetBookmarkAt(GetPos())) == -1) { // Add an unnamed bookmark here char *dv_name = "unnamed"; int dummy; long last = pbl->GetSetLast(dv_name, dummy); CString bm_name; bm_name.Format("%s%05ld", dv_name, long(last)); pbl->AddBookmark(bm_name, GetDocument()->pfile1_->GetFilePath(), GetPos(), NULL, GetDocument()); } else pbl->RemoveBookmark(index); // remove the bookmark theApp.SaveToMacro(km_bookmarks, (unsigned __int64)7); } void CHexEditView::reset_tip() { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); CPointAp pt(addr2pos(start_addr)); CPoint point = ConvertToDP(pt); point.x -= 24; ClientToScreen(&point); sel_tip_.Move(point); sel_tip_.Hide(); } void CHexEditView::update_sel_tip(int delay /*=0*/) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); if (theApp.sel_len_tip_ && (mouse_down_ || shift_down()) && start_addr != end_addr) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CString ss; __int64 len = __int64(end_addr - start_addr); if (!display_.hex_addr) { char buf[22]; // temp buf where we sprintf sprintf(buf, "%I64d", __int64(len)); ss = buf; AddCommas(ss); sel_tip_.SetTextCol(dec_addr_col_); // If there is a fair amount of contrast with standard tip background // colour then use it else use something else. if (abs(BRIGHTNESS(dec_addr_col_) - BRIGHTNESS(::GetSysColor(COLOR_INFOBK))) > 30) sel_tip_.SetBgCol(::GetSysColor(COLOR_INFOBK)); else if (BRIGHTNESS(dec_addr_col_) > 50) sel_tip_.SetBgCol(RGB(64,64,0)); // Light text so use dark "yellow" bg else sel_tip_.SetBgCol(RGB(255,255,224)); // Dark text so use light yellow bg } else { char buf[22]; // temp buf where we sprintf if (len < 10) sprintf(buf, "%I64x", __int64(len)); else if (aa->hex_ucase_) sprintf(buf, "%I64Xh", __int64(len)); else sprintf(buf, "%I64xh", __int64(len)); ss = buf; AddSpaces(ss); sel_tip_.SetTextCol(hex_addr_col_); // If there is a fair amount of contrast with standard tip background // colour then use it else use something else. if (abs(BRIGHTNESS(hex_addr_col_) - BRIGHTNESS(::GetSysColor(COLOR_INFOBK))) > 30) sel_tip_.SetBgCol(::GetSysColor(COLOR_INFOBK)); else if (BRIGHTNESS(hex_addr_col_) > 50) sel_tip_.SetBgCol(RGB(64,64,0)); // Light text so use dark "yellow" bg else sel_tip_.SetBgCol(RGB(255,255,224)); // Dark text so use light yellow bg } #if 0 // We used to indicate divisibility using colour if (len%8 == 0) sel_tip_.SetTextCol(RGB(0, 0, 128)); else if (len%4 == 0) sel_tip_.SetTextCol(RGB(128, 0, 128)); else if (len%2 == 0) sel_tip_.SetTextCol(RGB(128, 128, 0)); else sel_tip_.SetTextCol(RGB(128, 128, 128)); #endif if (theApp.sel_len_div2_ && len > 10) // User should know divisibility by 2,4 for numbers this small so don't show { int pow2; for (pow2 = 0; pow2 < 12; ++pow2) if (((len>>pow2) & 0x1) != 0) break; CString tmp; tmp.Format(" [%d]", 1<<pow2); ss += tmp; } // Don't update text if the string hasn't changed to avoid flicker CString strPrevious; sel_tip_.GetWindowText(strPrevious); if (strPrevious.Compare(ss) != 0) sel_tip_.SetWindowText(ss); // Check if tip window is too far from selection FILE_ADDRESS start_line = (start_addr + offset_)/rowsize_; FILE_ADDRESS end_line = (end_addr + offset_)/rowsize_ + 1; CRect rct; // Get bounding rectangle of selection (we only really need top and bottom) CRectAp bnd_rct; bnd_rct = CRectAp(0, start_line * line_height_, char_pos(rowsize_), end_line * line_height_); sel_tip_.GetWindowRect(&rct); ScreenToClient(&rct); CRectAp tip_rct = ConvertFromDP(rct); GetDisplayRect(&rct); CRectAp cli_rct = ConvertFromDP(rct); bnd_rct.top -= tip_rct.Height()/2; bnd_rct.bottom += tip_rct.Height()/2; // Restrict bounds rect to the visible selection if (bnd_rct.top < cli_rct.top - 10) { bnd_rct.top = cli_rct.top - 10; if (bnd_rct.bottom < bnd_rct.top + tip_rct.Height()) bnd_rct.bottom = bnd_rct.top + tip_rct.Height(); } if (bnd_rct.bottom > cli_rct.bottom + 10) { bnd_rct.bottom = cli_rct.bottom + 10; if (bnd_rct.top > bnd_rct.bottom - tip_rct.Height()) bnd_rct.top = bnd_rct.bottom - tip_rct.Height(); } if (bnd_rct.left < cli_rct.left) bnd_rct.left = cli_rct.left; if (bnd_rct.right > cli_rct.right) bnd_rct.right = cli_rct.right; // Move the rectangle for tip within bounds if (tip_rct.top < bnd_rct.top) { tip_rct.bottom += bnd_rct.top - tip_rct.top; tip_rct.top += bnd_rct.top - tip_rct.top; } else if (tip_rct.bottom > bnd_rct.bottom) { tip_rct.top += bnd_rct.bottom - tip_rct.bottom; tip_rct.bottom += bnd_rct.bottom - tip_rct.bottom; } if (tip_rct.left < bnd_rct.left) { tip_rct.right += bnd_rct.left - tip_rct.left; tip_rct.left += bnd_rct.left - tip_rct.left; } else if (tip_rct.right > bnd_rct.right) { tip_rct.left += bnd_rct.right - tip_rct.right; tip_rct.right += bnd_rct.right - tip_rct.right; } // Calculate centre of rect and move the tip window CPointAp pt((tip_rct.left + tip_rct.right)/2, (tip_rct.top + tip_rct.bottom)/2); CPoint point = ConvertToDP(pt); ClientToScreen(&point); sel_tip_.Move(point); sel_tip_.Show(100, delay); SetFocus(); } else { sel_tip_.Hide(); } } // This is here to implement the macro command km_mouse void CHexEditView::do_mouse(CPoint dev_down, CSizeAp doc_dist) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CPointAp doc_down = ConvertFromDP(dev_down); // Sel start point converted from device to doc coords CPointAp doc_up(doc_down); // Point where selection ends = start + doc_up += doc_dist; // ... distance of selection // Convert selection (doc coords) to addresses and make sure in valid range FILE_ADDRESS start_addr, end_addr; FILE_ADDRESS length = GetDocument()->length(); start_addr = pos2addr(doc_down); end_addr = pos2addr(doc_up); if (start_addr < 0) start_addr = 0; else if (start_addr > length) start_addr = length; if (end_addr < 0) end_addr = 0; else if (end_addr > length) end_addr = length; // Save undo information FILE_ADDRESS prev_start, prev_end; GetSelAddr(prev_start, prev_end); int prev_row = 0; if (prev_start == prev_end && display_.vert_display) prev_row = pos2row(GetCaret()); if (start_addr == prev_start && end_addr == prev_end) // exactly the same selection return; BOOL saved_area = display_.edit_char; if (!display_.vert_display && display_.char_area && display_.hex_area) // If both areas displayed ... display_.edit_char = pos_hex(doc_down.x, FALSE) >= rowsize_; // sel may swap between areas undo_.push_back(view_undo(undo_move)); undo_.back().address = prev_start | (FILE_ADDRESS(prev_row)<<62); if (prev_start != prev_end) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end; } if (display_.edit_char != saved_area) { // Allow more buffer if editing hex if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); // Save the fact that we swapped between areas undo_.push_back(view_undo(undo_state, TRUE)); undo_.back().disp_state = disp_state_; } SetSel(addr2pos(start_addr), addr2pos(end_addr), true); if (aa->highlight_) add_highlight(start_addr, end_addr, TRUE); nav_save(start_addr, end_addr, "Mouse Click (Play) "); } // This is here to implement the macro command km_shift_mouse void CHexEditView::do_shift_mouse(CPoint dev_down, CSizeAp doc_dist) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CPointAp doc_down = ConvertFromDP(dev_down); // Left down point converted from device to doc coords CPointAp doc_up(doc_down); // Point of left button up (doc coords) = ... doc_up += doc_dist; // ... doc_down + length of selection // Convert selection (doc coords) to addresses and make sure in valid range FILE_ADDRESS start_addr, end_addr; // New selection range FILE_ADDRESS prev_start, prev_end; // Previous selection range FILE_ADDRESS length = GetDocument()->length(); // GetSelAddr(start_addr, prev_end); if (GetSelAddr(prev_start, prev_end)) start_addr = prev_end; // Base of previous selection was end else start_addr = prev_start; end_addr = pos2addr(doc_up); if (start_addr < 0) start_addr = 0; else if (start_addr > length) start_addr = length; if (end_addr < 0) end_addr = 0; else if (end_addr > length) end_addr = length; if (end_addr != prev_end) { // Save the previous selection for undo undo_.push_back(view_undo(undo_move)); undo_.back().address = start_addr; undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end; // Extend the selection SetSel(addr2pos(start_addr), addr2pos(end_addr), true); if (aa->highlight_) add_highlight(start_addr, end_addr, TRUE); } nav_save(start_addr, end_addr, "Mouse Click (Play) "); } void CHexEditView::OnRButtonDown(UINT nFlags, CPoint point) { // Move the caret to where the user clicked so that context menu items // that depend on the current address use the address that was clicked on CPointAp pp = ConvertFromDP(point); // Point in our coord system if (( (display_.vert_display || display_.char_area) && pp.x >= char_pos(rowsize_)+text_width_ || !(display_.vert_display || display_.char_area) && pp.x >= hex_pos(rowsize_) ) ) { // Don't do anything if off to right return; } // Save current state, selection etc for undo GetSelAddr(prev_start_, prev_end_); saved_state_ = disp_state_; // Keep the current state for saving in undo stack prev_row_ = 0; if (prev_start_ == prev_end_ && display_.vert_display) prev_row_ = pos2row(GetCaret()); num_entered_ = num_del_ = num_bs_ = 0; // Can't be editing while mousing if (!display_.vert_display && display_.char_area && display_.hex_area) { // Allow user to move caret between hex and char areas display_.edit_char = pos_hex(pp.x, FALSE) >= rowsize_; if (saved_state_ != disp_state_) { // Sett approp. buffering to allow user to see the whole byte that they are editing if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); } } // Note: this relies on display_.edit_char having been set correctly above FILE_ADDRESS addr = pos2addr(pp); FILE_ADDRESS start_addr, end_addr; BOOL end_base = FALSE; // If we have not clicked inside the selection then ... if (addr < prev_start_ || addr >= prev_end_) { // Move the caret to where the user clicked ValidateCaret(pp, FALSE); SetCaret(pp); BOOL end_base = GetSelAddr(start_addr, end_addr); } else { // Don't move if clicked in selection start_addr = prev_start_; end_addr = prev_end_; } // Save in undo array if position moved if (prev_start_ != start_addr || prev_end_ != end_addr || saved_state_ != disp_state_) { // Save the caret position (or start of selection) undo_.push_back(view_undo(undo_move)); undo_.back().address = prev_start_ | (FILE_ADDRESS(prev_row_)<<62); if (prev_start_ != prev_end_) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end_; } if (saved_state_ != disp_state_) { // Save the fact that we swapped between areas undo_.push_back(view_undo(undo_state, TRUE)); undo_.back().disp_state = saved_state_; } if (end_base) SetSel(addr2pos(end_addr), addr2pos(start_addr), true); else SetSel(addr2pos(start_addr), addr2pos(end_addr)); DisplayCaret(); nav_save(start_addr, end_addr, "Right Mouse Click "); } // Update properties etc for new position show_prop(); show_calc(); show_pos(); #if 0 else if (saved_state_ != disp_state_) { // Save the fact that we swapped between areas undo_.push_back(view_undo(undo_state, FALSE)); undo_.back().disp_state = saved_state_; } -------- FILE_ADDRESS addr = pos2addr(pp); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Make sure we have NOT clicked inside the selection if (addr < start_addr || addr > end_addr) { // Move the caret to where the user clicked ValidateCaret(pp, FALSE); SetCaret(pp); // Update properties etc for new position show_prop(); show_calc(); show_pos(); } #endif CScrView::OnRButtonDown(nFlags, point); } void CHexEditView::OnContextMenu(CWnd* pWnd, CPoint point) { view_context(point); } BOOL CHexEditView::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // Only respond if in client area if (nHitTest == HTCLIENT) { // Get mouse location in window coords CPoint point; ::GetCursorPos(&point); ScreenToClient(&point); #ifdef RULER_ADJUST if (point.y < bdr_top_) { CPointAp pp = ConvertFromDP(point); // Point in our coord system if (point.y > bdr_top_ - 7 && (over_rowsize_adjuster(pp) || over_offset_adjuster(pp) || over_group_by_adjuster(pp)) ) { ::SetCursor(theApp.LoadStandardCursor(IDC_SIZEWE)); return TRUE; } return CScrView::OnSetCursor(pWnd, nHitTest, message); } #endif // Work out location of cursor in window and make sure it's // not over address area (on left) or past last chars (on right) CPointAp pt = ConvertFromDP(point); if (pt.x > (addr_width_ - 1)*text_width_ && (display_.vert_display && pt.x < char_pos(rowsize_)+text_width_w_ || !display_.vert_display && display_.char_area && pt.x < char_pos(rowsize_)+text_width_w_ || !display_.vert_display && !display_.char_area && pt.x < hex_pos(rowsize_) ) ) { // Over hex or char area if (drag_bookmark_ > -1 || bookmark_at(address_at(point)) > -1) ::SetCursor(theApp.LoadStandardCursor(IDC_SIZEALL)); // Indicate bookmark can be moved else if (theApp.highlight_) ::SetCursor(theApp.LoadCursor(IDC_HIGHLIGHT)); // Highlighter cursor else ::SetCursor(theApp.LoadStandardCursor(IDC_IBEAM)); // Text insertion cursor return TRUE; } } return CScrView::OnSetCursor(pWnd, nHitTest, message); } // Display views context menu // point is in screen coords void CHexEditView::view_context(CPoint point) { #if 0 // Changes for BCG context menus // Get the top level menu that contains the submenus used as popup menus CMenu top; BOOL ok = top.LoadMenu(IDR_CONTEXT); ASSERT(ok); if (!ok) return; CHECK_SECURITY(51); CMenu *ppop; if (point.x < hex_pos(0)) { // Context menu for address area ppop = top.GetSubMenu(1); } else if (display_.char_area && point.x >= char_pos(0)) { // Context menu for character area ppop = top.GetSubMenu(2); } else { // Context menu for hex area ppop = top.GetSubMenu(3); } ASSERT(ppop != NULL); if (ppop != NULL) { // Convert window coords to the required screen coords ClientToScreen(&point); VERIFY(ppop->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, GetFrame())); } top.DestroyMenu(); #else CContextMenuManager *pCMM = theApp.GetContextMenuManager(); CPoint cli_pt(point); // The point clicked in doc coords ScreenToClient(&cli_pt); CPointAp doc_pt = ConvertFromDP(cli_pt); if (( (display_.vert_display || display_.char_area) && doc_pt.x >= char_pos(rowsize_)+text_width_ || !(display_.vert_display || display_.char_area) && doc_pt.x >= hex_pos(rowsize_) ) ) { // Don't do anything if off to right return; } if (doc_pt.x < hex_pos(0)) pCMM->ShowPopupMenu(IDR_CONTEXT_ADDRESS, point.x, point.y, this); else if (display_.vert_display) { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in char area FILE_ADDRESS addr = (doc_pt.y/line_height_)*rowsize_ - offset_ + pos_char(doc_pt.x); if (addr >= start_addr && addr < end_addr) pCMM->ShowPopupMenu(IDR_CONTEXT_SELECTION, point.x, point.y, this); else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_BOOKMARKS, point.x, point.y, this); else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_HIGHLIGHT, point.x, point.y, this); else if (pos2row(doc_pt) == 0) pCMM->ShowPopupMenu(IDR_CONTEXT_CHAR, point.x, point.y, this); else pCMM->ShowPopupMenu(IDR_CONTEXT_HEX, point.x, point.y, this); } else if (!display_.char_area || doc_pt.x < char_pos(0)) { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in hex area FILE_ADDRESS addr = (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_hex(doc_pt.x); if (addr >= start_addr && addr < end_addr) pCMM->ShowPopupMenu(IDR_CONTEXT_SELECTION, point.x, point.y, this); else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_BOOKMARKS, point.x, point.y, this); else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_HIGHLIGHT, point.x, point.y, this); else pCMM->ShowPopupMenu(IDR_CONTEXT_HEX, point.x, point.y, this); } else { // Get selection address FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); // Get address clicked on in char area FILE_ADDRESS addr = (doc_pt.y/text_height_)*rowsize_ - offset_ + pos_char(doc_pt.x); if (addr >= start_addr && addr < end_addr) pCMM->ShowPopupMenu(IDR_CONTEXT_SELECTION, point.x, point.y, this); else if (!display_.hide_bookmarks && std::find(GetDocument()->bm_posn_.begin(), GetDocument()->bm_posn_.end(), addr) != GetDocument()->bm_posn_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_BOOKMARKS, point.x, point.y, this); else if (!display_.hide_highlight && hl_set_.find(addr) != hl_set_.end()) pCMM->ShowPopupMenu(IDR_CONTEXT_HIGHLIGHT, point.x, point.y, this); else pCMM->ShowPopupMenu(IDR_CONTEXT_CHAR, point.x, point.y, this); } #endif } ///////////////////////////////////////////////////////////////////////////// // CHexEditView command handlers void CHexEditView::OnRedraw() { CRect cli; // Work out window height in logical units GetDisplayRect(&cli); CRectAp doc_rect = ConvertFromDP(cli); // Move display so that caret is centred vertically CPointAp pp = GetCaret(); pp.x = 0; // Scroll to left side (but see DisplayCaret() below) if ((pp.y -= (doc_rect.bottom-doc_rect.top)/2) < 0) pp.y = 0; SetScroll(pp); DoInvalidate(); // Also redraw display DisplayCaret(); // Make sure caret not off right side ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_redraw); } void CHexEditView::OnScrollDown() { CPointAp pp = GetScroll(); pp.y += text_height_; SetScroll(pp); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_scroll_down); } void CHexEditView::OnScrollUp() { CPointAp pp = GetScroll(); pp.y -= text_height_; SetScroll(pp); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_scroll_up); } // Move current position to start of display line void CHexEditView::OnStartLine() { num_entered_ = num_del_ = num_bs_ = 0; // Turn off any consec edits FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Check if offset has actually changed if (real_offset_ != (rowsize_ - start_addr%rowsize_)%rowsize_) { undo_.push_back(view_undo(undo_offset)); undo_.back().rowsize = real_offset_; // Save previous offset for undo real_offset_ = offset_ = int((rowsize_ - start_addr%rowsize_)%rowsize_); SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); recalc_display(); DoInvalidate(); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_start_line); } else { ((CMainFrame *)AfxGetMainWnd())->StatusBarText("Warning: offset not changed"); ((CHexEditApp *)AfxGetApp())->mac_error_ = 1; } } void CHexEditView::OnSwap() { if (display_.vert_display) return; CHECK_SECURITY(32); if (display_.char_area && display_.hex_area) { num_entered_ = num_del_ = num_bs_ = 0; // Turn off any consec edits // Swap between hex and char areas FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); undo_.push_back(view_undo(undo_state)); undo_.back().disp_state = disp_state_; display_.edit_char = !display_.edit_char; if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); if (end_base) SetSel(addr2pos(end_addr), addr2pos(start_addr), true); else SetSel(addr2pos(start_addr), addr2pos(end_addr)); DisplayCaret(); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_swap_areas); } else { AfxMessageBox("Cannot swap to character area - not displayed"); ((CHexEditApp *)AfxGetApp())->mac_error_ = 5; } } void CHexEditView::OnUpdateSwap(CCmdUI* pCmdUI) { pCmdUI->Enable(display_.char_area && display_.hex_area); // disallow swap if both areas not displayed } void CHexEditView::OnDel() { num_entered_ = 0; // Not entering but deleting CPointAp pt_start, pt_end; if (GetSel(pt_start, pt_end)) SetSel(pt_end, pt_start, true); else SetSel(pt_start, pt_end); // Calls ValidateCaret - causing caret selection to be moved to valid locations if (check_ro("delete")) return; if (display_.overtype) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("You can't delete while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) return; else if (!do_insert()) return; } // Handle deletion of chars at caret or selection FILE_ADDRESS start, end; GetSelAddr(start, end); // address = pos2addr(GetCaret()); CHECK_SECURITY(190); if (start == end) { // if ((long)nRepCnt > GetDocument()->length() - start) // nRepCnt = (UINT)(GetDocument()->length() - start); // if (nRepCnt > 0) // GetDocument()->Change(mod_delforw, start, nRepCnt, // NULL, num_del_, this); // num_del_ += nRepCnt*2; if (start >= GetDocument()->length()) { ((CHexEditApp *)AfxGetApp())->mac_error_ = 2; return; } GetDocument()->Change(mod_delforw, start, 1, NULL, num_del_, this); num_del_ += 2; } else { GetDocument()->Change(mod_delforw, start, end-start, NULL, 0, this); num_del_ = 0; // Make sure this is separate deletion } DisplayCaret(); // Make sure caret is visible ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_del); } void CHexEditView::OnSelectAll() { num_entered_ = num_del_ = num_bs_ = 0; // Can't be editing while mousing GetSelAddr(prev_start_, prev_end_); prev_row_ = 0; if (prev_start_ == prev_end_ && display_.vert_display) prev_row_ = pos2row(GetCaret()); SetSel(addr2pos(0), addr2pos(GetDocument()->length())); show_prop(); show_calc(); show_pos(); // Save in undo array if position moved if (prev_start_ != 0 || prev_end_ != GetDocument()->length()) { // Save the caret position (or start of selection) undo_.push_back(view_undo(undo_move)); undo_.back().address = prev_start_ | (FILE_ADDRESS(prev_row_)<<62); if (prev_start_ != prev_end_) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end_; } nav_save(0, GetDocument()->length(), "Select All "); } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_sel_all); } void CHexEditView::OnSelectLine() { num_entered_ = num_del_ = num_bs_ = 0; GetSelAddr(prev_start_, prev_end_); prev_row_ = 0; if (prev_start_ == prev_end_ && display_.vert_display) prev_row_ = pos2row(GetCaret()); FILE_ADDRESS new_start = ((prev_start_+offset_)/rowsize_) * rowsize_ - offset_; FILE_ADDRESS new_end = ((prev_end_+offset_)/rowsize_ + 1) * rowsize_ - offset_; ASSERT(new_end > new_start); SetSel(addr2pos(new_start), addr2pos(new_end)); show_prop(); show_calc(); show_pos(); // Save in undo array if position moved if (prev_start_ != new_start || prev_end_ != new_end) { // Save the caret position (or start of selection) undo_.push_back(view_undo(undo_move)); undo_.back().address = prev_start_ | (FILE_ADDRESS(prev_row_)<<62); if (prev_start_ != prev_end_) { // Save the previous selection undo_.push_back(view_undo(undo_sel)); undo_.back().address = prev_end_; } nav_save(new_start, new_end, "Select Line "); } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_sel_line); } void CHexEditView::OnInsertBlock() { CNewFile dlg(this, true); if (dlg.DoModal() == IDOK) { const char *data_str = NULL; dlg.fill_.create_on_disk = 0; // Make sure we are not creating a new file switch (dlg.fill_.type) { default: ASSERT(0); // fall through case CNewFile::FILL_HEX: // count hex digits data_str = dlg.fill_hex_value_; break; case CNewFile::FILL_STRING: // string data_str = dlg.fill_string_value_; break; case CNewFile::FILL_CLIPBOARD: // clipboard break; case CNewFile::FILL_RANDOM: // random - default to one byte data_str = dlg.fill_random_range_; break; case CNewFile::FILL_NUMBER: // number - get size from type data_str = dlg.fill_number_value_; break; } do_insert_block(dlg.fill_state_, data_str); } } void CHexEditView::do_insert_block(_int64 params, const char *data_str) { // Can't modify the file if view is read only or in overtype mode if (check_ro("insert block")) return; if (display_.overtype) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("You can't insert a block while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 5; return; } else if (!do_insert()) return; } num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing FILE_ADDRESS addr = GetPos(); // Current caret (address to insert file) FILE_ADDRESS len = GetDocument()->insert_block(addr, params, data_str, this); if (len > -1) { SetSel(addr2pos(addr), addr2pos(addr+len)); DisplayCaret(); theApp.SaveToMacro(km_insert, params); theApp.SaveToMacro(km_insert_str, data_str); } } void CHexEditView::OnUpdateInsertBlock(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); // disallow insert if file is read only } // Get file name, insert into document and select inserted bytes void CHexEditView::OnReadFile() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Get name of file to read CHexFileDialog dlgFile("ReadFileDlg", HIDD_FILE_READ, TRUE, NULL, aa->current_read_, OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_DONTADDTORECENT, aa->GetCurrentFilters(), "Read", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Insert File"; if (dlgFile.DoModal() == IDOK) { aa->current_read_ = dlgFile.GetPathName(); CHECK_SECURITY(23); do_read(aa->current_read_); } } // Actually open and read the file and select the inserted bytes void CHexEditView::do_read(CString file_name) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Can't modify the file if view is read only or in overtype mode if (check_ro("insert file")) return; if (display_.overtype) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("You can't insert a file while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 5; return; } else if (!do_insert()) return; } num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing FILE_ADDRESS addr = GetPos(); // Current caret (address to insert file) FILE_ADDRESS data_len = CFile64::GetSize(file_name); if (data_len == 0) { // No need to insert a zero length file ((CMainFrame *)AfxGetMainWnd())->StatusBarText("File is empty: nothing inserted"); aa->mac_error_ = 1; return; } int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) if (data_len > (16*1024*1024) && (idx = GetDocument()->AddDataFile(file_name)) != -1) { // Use the file in situ GetDocument()->Change(mod_insert_file, addr, data_len, NULL, idx, this); } else { if (data_len > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files \n" "and cannot open such a large file. \n" "Please save the file to free \n" "temporary file handles and try again.\n", MB_OK); return; } if (data_len > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and opening such a large file may \n" "cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) return; } // Open the file for reading CFile ff; // Don't make this CFile64 as we don't want to read > 2Gbytes into memory CFileException fe; // Used to receive file error information if (!ff.Open(file_name, CFile::modeRead|CFile::shareDenyWrite|CFile::typeBinary, &fe) ) { // Display info about why the open failed CString mess(file_name); CFileStatus fs; switch (fe.m_cause) { case CFileException::fileNotFound: mess += "\rdoes not exist"; break; case CFileException::badPath: mess += "\ris an invalid file name or the drive/path does not exist"; break; case CFileException::tooManyOpenFiles: mess += "\r- too many files already open"; break; case CFileException::accessDenied: if (!CFile::GetStatus(file_name, fs)) mess += "\rdoes not exist"; else { if (fs.m_attribute & CFile::directory) mess += "\ris a directory"; else if (fs.m_attribute & (CFile::volume|CFile::hidden|CFile::system)) mess += "\ris a special file"; else mess += "\rcannot be used (reason unknown)"; } break; case CFileException::sharingViolation: case CFileException::lockViolation: mess += "\ris in use"; break; case CFileException::hardIO: mess += "\r- hardware error"; break; default: mess += "\rcould not be opened (reason unknown)"; break; } AfxMessageBox(mess); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) // If the user tries to insert a huge file we might run out of memory so catch this try { // Get memory to read all of the file unsigned char *file_data = new unsigned char[size_t(data_len)]; // Read the file into memory if (ff.Read((void *)file_data, (UINT)data_len) != data_len) { AfxMessageBox("Not all of the file could be read"); aa->mac_error_ = 10; return; } ff.Close(); // Make the memory part of the document GetDocument()->Change(mod_insert, addr, data_len, file_data, 0, this); delete[] file_data; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); aa->mac_error_ = 10; return; } } ASSERT(data_len > 0); SetSel(addr2pos(addr), addr2pos(addr+data_len)); DisplayCaret(); aa->SaveToMacro(km_read_file, file_name); } void CHexEditView::OnUpdateReadFile(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); // disallow insert if file is read only } void CHexEditView::OnEditWriteFile() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start == end) { // Nothing selected, presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("Nothing selected to write to file!"); aa->mac_error_ = 10; return; } // Get the file name to write the selection to CHexFileDialog dlgFile("WriteFileDlg", HIDD_FILE_WRITE, FALSE, NULL, aa->current_write_, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_SHOWHELP | OFN_NOCHANGEDIR, aa->GetCurrentFilters(), "Write", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Save Selection As"; // if (!aa->current_write_.IsEmpty()) // dlgFile.m_ofn.lpstrInitialDir = aa->current_write_; if (dlgFile.DoModal() != IDOK) { aa->mac_error_ = 2; return; } aa->current_write_ = dlgFile.GetPathName(); CHECK_SECURITY(25); // Write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) if (GetDocument()->WriteData(aa->current_write_, start, end)) aa->SaveToMacro(km_write_file); else aa->current_write_.Empty(); } void CHexEditView::OnEditAppendFile() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start == end) { // Nothing selected, presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("Nothing selected to append to file!"); aa->mac_error_ = 10; return; } // Get the file name to write the selection to CHexFileDialog dlgFile("WriteFileDlg", HIDD_FILE_APPEND, TRUE, NULL, aa->current_write_, OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_DONTADDTORECENT, aa->GetCurrentFilters(), "Append", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Append Selection To"; if (dlgFile.DoModal() != IDOK) { aa->mac_error_ = 2; return; } CHECK_SECURITY(15); aa->current_write_ = dlgFile.GetPathName(); // Write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) if (GetDocument()->WriteData(aa->current_write_, start, end, TRUE)) aa->SaveToMacro(km_append_file); else aa->current_write_.Empty(); } void CHexEditView::OnEditAppendSameFile() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); CHECK_SECURITY(25); if (start == end) { // Nothing selected, presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("Nothing selected to append to file!"); aa->mac_error_ = 10; return; } // Write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) if (GetDocument()->WriteData(aa->current_write_, start, end, TRUE)) aa->SaveToMacro(km_append_same_file); else aa->current_write_.Empty(); } void CHexEditView::OnUpdateEditAppendSameFile(CCmdUI* pCmdUI) { if (theApp.current_write_.IsEmpty()) pCmdUI->Enable(FALSE); else OnUpdateClipboard(pCmdUI); } void CHexEditView::OnExportSRecord(UINT nID) { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); // If no selection and no highlight there is nothing to do if (start == end && hl_set_.empty()) { AfxMessageBox("Nothing to export!"); theApp.mac_error_ = 10; return; } // Get the file name to write to (plus discontinuous setting) CExportDialog dlgFile(theApp.current_export_, HIDD_FILE_EXPORT_MOTOROLA, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_SHOWHELP | OFN_NOCHANGEDIR, "Motorola S Files (*.s)|*.s|"+theApp.GetCurrentFilters(), this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Export S Records"; if (dlgFile.DoModal() != IDOK) { theApp.mac_error_ = 2; return; } theApp.current_export_ = dlgFile.GetPathName(); CHECK_SECURITY(25); if (theApp.import_discon_) { if (hl_set_.empty()) { AfxMessageBox("Nothing highlighted to export!"); theApp.mac_error_ = 10; return; } // Set start and end to the range of highlighted bytes start = *hl_set_.begin(); // First highlighted byte end = *hl_set_.rbegin(); // Last highlighted byte } else { if (start == end) { // Nothing selected AfxMessageBox("Nothing selected to export!"); theApp.mac_error_ = 10; return; } } // Check the range of exported addresses to check that they are valid FILE_ADDRESS last_S_address; // Byte past the last address to be written out int stype = 3; // Type of data records to write (S1, S2, or S3) if (theApp.export_base_addr_ < 0) last_S_address = end; else last_S_address = end - start + theApp.export_base_addr_; // Check that end address is not too big for S Record if (nID == ID_EXPORT_S1) { // Addresses must be within 16 bit range if (last_S_address > 0x10000) { AfxMessageBox("Addresses too big for S1 export!"); theApp.mac_error_ = 10; return; } stype = 1; } else if (nID == ID_EXPORT_S2) { // Addresses must be within 24 bit range if (last_S_address > 0x1000000) { AfxMessageBox("Addresses too big for S2 export!"); theApp.mac_error_ = 10; return; } stype = 2; } else if (nID == ID_EXPORT_S3) { // Addresses must be within 32 bit range if (last_S_address > 0x100000000) { AfxMessageBox("Addresses too big for S3 export!"); theApp.mac_error_ = 10; return; } ASSERT(stype == 3); } // Get ready to write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) CWriteSRecord wsr(theApp.current_export_, theApp.export_base_addr_ >= 0 ? theApp.export_base_addr_ : long(start), stype, theApp.export_line_len_); if (!wsr.Error().IsEmpty()) { AfxMessageBox(wsr.Error()); theApp.mac_error_ = 10; theApp.current_export_.Empty(); return; } unsigned char *buf = new unsigned char[4096]; size_t len; if (theApp.import_discon_) { unsigned long base_address = 0; if (theApp.export_base_addr_ >= 0) base_address = unsigned long(theApp.export_base_addr_ - start); // This puts 1st rec at export address of zero range_set<FILE_ADDRESS>::range_t::iterator pp; for (pp = hl_set_.range_.begin(); pp != hl_set_.range_.end(); ++pp) for (FILE_ADDRESS curr = pp->sfirst; curr < pp->slast; curr += len) { len = int(min(4096, pp->slast - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); wsr.Put(buf, len, unsigned long(base_address + curr)); if (!wsr.Error().IsEmpty()) { AfxMessageBox(wsr.Error()); theApp.mac_error_ = 10; theApp.current_export_.Empty(); goto export_end; } } } else { FILE_ADDRESS curr; for (curr = start; curr < end; curr += len) { len = min(4096, int(end - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); wsr.Put(buf, len); if (!wsr.Error().IsEmpty()) { AfxMessageBox(wsr.Error()); theApp.mac_error_ = 10; theApp.current_export_.Empty(); goto export_end; } } ASSERT(curr == end); } export_end: delete[] buf; if (theApp.mac_error_ < 10) theApp.SaveToMacro(km_write_file, stype); // stype == 1,2, or 3 } void CHexEditView::OnUpdateExportSRecord(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start == end) { // We can still export based on highlights if (hl_set_.empty()) { pCmdUI->Enable(FALSE); return; } FILE_ADDRESS hl_start, hl_end; hl_start = *hl_set_.begin(); // First highlighted byte hl_end = *hl_set_.rbegin(); // Last highlighted byte // Not quite right but should prevent valid export cmds from being disabled if (hl_start > start) start = hl_start; if (hl_end < end) end = hl_end; } // Work out the last address that needs to be exported if (theApp.export_base_addr_ >= 0) end = end - start + theApp.export_base_addr_; if (pCmdUI->m_nID == ID_EXPORT_S1) { // Addresses must be within 16 bit range pCmdUI->Enable(end <= 0x10000); } else if (pCmdUI->m_nID == ID_EXPORT_S2) { // Addresses must be within 24 bit range pCmdUI->Enable(end <= 0x1000000); } else if (pCmdUI->m_nID == ID_EXPORT_S3) { // Addresses must be within 32 bit range pCmdUI->Enable(end <= 0x100000000); } } void CHexEditView::OnImportMotorolaS() { // Get name of file to import // CFileDialog dlgFile(TRUE, NULL, theApp.current_import_, // OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, // theApp.GetCurrentFilters(), this); CImportDialog dlgFile(theApp.current_import_, HIDD_FILE_IMPORT_MOTOROLA, OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_DONTADDTORECENT, "Motorola S Files (*.s)|*.s|"+theApp.GetCurrentFilters(), this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Import Motorola S Records"; if (dlgFile.DoModal() == IDOK) { theApp.current_import_ = dlgFile.GetPathName(); do_motorola(theApp.current_import_); } } void CHexEditView::do_motorola(CString file_name) { if (check_ro("import file")) return; if (!theApp.import_discon_ && display_.overtype) { if (AfxMessageBox("You can't import (non-adjoining) while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 5; return; } else if (!do_insert()) return; } num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CWaitCursor wait; // Turn on wait cursor (hourglass) CHECK_SECURITY(33); if (theApp.import_discon_) { BOOL ptoo = FALSE; // First change is new undo op, thence merged with it if (theApp.import_highlight_ && !hl_set_.empty()) { undo_.push_back(view_undo(undo_highlight)); undo_.back().phl = new range_set<FILE_ADDRESS>(hl_set_); hl_set_.clear(); DoInvalidate(); ptoo = TRUE; } CReadSRecord rsr(file_name, TRUE); if (!rsr.Error().IsEmpty()) { AfxMessageBox(rsr.Error()); theApp.mac_error_ = 10; return; } // Read int count, skipped; // Total records read and ignored size_t data_len = 1024; unsigned char *file_data = new unsigned char[data_len]; // one S record unsigned long address; int len; // length of data from one S record for (count = skipped = 0; (len = rsr.Get(file_data, data_len, address)) > 0; ++count) { if (address + len > GetDocument()->length()) { ++skipped; continue; } if (theApp.import_highlight_) { // Highlight the record add_highlight(address, address+len, ptoo); ptoo = TRUE; } GetDocument()->Change(mod_replace, FILE_ADDRESS(address), FILE_ADDRESS(len), file_data, 0, this, ptoo); ptoo = TRUE; // force subsequent changes to be merged into same undo operation } delete[] file_data; if (!rsr.Error().IsEmpty()) AfxMessageBox(rsr.Error()); CString mess; if (skipped > 0) mess.Format("Wrote %ld records\r\nIgnored %ld records\r\nimporting \"%s\"", long(count - skipped), long(skipped), file_name); else mess.Format("Wrote %ld records importing \"%s\"", long(count), file_name); AfxMessageBox(mess); theApp.SaveToMacro(km_import_motorola, file_name); } else { CReadSRecord rsr(file_name); if (!rsr.Error().IsEmpty()) { AfxMessageBox(rsr.Error()); theApp.mac_error_ = 10; return; } // We need to store the data in fairly large chunks otherwise the doc undo // stack becomes very full and slows things down size_t data_len = 32768; unsigned char *file_data = new unsigned char[data_len]; // work buffer unsigned char *pp = file_data; // Ptr into file_data where we are currently storing unsigned long address; // Import S record address (ignored) int len; // length of data from one S record bool first(true); // is this the first S record read from the file FILE_ADDRESS start_addr, end_addr, curr_addr = -1; GetSelAddr(start_addr, end_addr); // Get the current selection for (;;) { len = rsr.Get(pp, data_len - (pp - file_data), address); if (len <= 0 || (pp - file_data) + len > (int(data_len) - 256)) { // The buffer is almost full or we're finished reading the file - so save buffer if (first) { curr_addr = start_addr; if (start_addr < end_addr) { // Delete current selection and insert new data GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this, TRUE); } else GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this); first = false; } else { ASSERT(curr_addr != -1); GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this, TRUE); } curr_addr += pp - file_data + len; pp = file_data; } else pp += len; if (len <= 0) break; } delete[] file_data; if (!rsr.Error().IsEmpty()) AfxMessageBox(rsr.Error()); theApp.SaveToMacro(km_import_motorola, file_name); SetSel(addr2pos(start_addr), addr2pos(curr_addr)); DisplayCaret(); } } void CHexEditView::OnUpdateImportMotorolaS(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); // disallow insert if file is read only } void CHexEditView::OnImportIntel() { // Get name of file to import // CFileDialog dlgFile(TRUE, NULL, theApp.current_import_, // OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, // theApp.GetCurrentFilters(), this); CImportDialog dlgFile(theApp.current_import_, HIDD_FILE_IMPORT_INTEL, OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_DONTADDTORECENT, "Intel Hex Files (*,hex, *.ihx)|*.hex;*.ihx|"+theApp.GetCurrentFilters(), this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Import Intel Hex File"; if (dlgFile.DoModal() == IDOK) { theApp.current_import_ = dlgFile.GetPathName(); do_intel(theApp.current_import_); } } void CHexEditView::do_intel(CString file_name) { if (check_ro("import Intel hex file")) return; if (!theApp.import_discon_ && display_.overtype) { if (AfxMessageBox("You can't import (non-adjoining) while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 5; return; } else if (!do_insert()) return; } num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHECK_SECURITY(32); CWaitCursor wait; // Turn on wait cursor (hourglass) if (theApp.import_discon_) { BOOL ptoo = FALSE; // First change is new undo op, thence merged with it if (theApp.import_highlight_ && !hl_set_.empty()) { undo_.push_back(view_undo(undo_highlight)); undo_.back().phl = new range_set<FILE_ADDRESS>(hl_set_); hl_set_.clear(); DoInvalidate(); ptoo = TRUE; } CReadIntelHex rih(file_name, TRUE); if (!rih.Error().IsEmpty()) { AfxMessageBox(rih.Error()); theApp.mac_error_ = 10; return; } // Read int count, skipped; // Total records read and ignored size_t data_len = 1024; unsigned char *file_data = new unsigned char[data_len]; // one S record unsigned long address; int len; // length of data from one S record for (count = skipped = 0; (len = rih.Get(file_data, data_len, address)) > 0; ++count) { if (address + len > GetDocument()->length()) { ++skipped; continue; } if (theApp.import_highlight_) { // Highlight the record add_highlight(address, address+len, ptoo); ptoo = TRUE; } GetDocument()->Change(mod_replace, FILE_ADDRESS(address), FILE_ADDRESS(len), file_data, 0, this, ptoo); ptoo = TRUE; // force subsequent changes to be merged into same undo operation } delete[] file_data; if (!rih.Error().IsEmpty()) AfxMessageBox(rih.Error()); CString mess; if (skipped > 0) mess.Format("Wrote %ld records\r\nIgnored %ld records\r\nimporting \"%s\"", long(count - skipped), long(skipped), file_name); else mess.Format("Wrote %ld records importing \"%s\"", long(count), file_name); AfxMessageBox(mess); theApp.SaveToMacro(km_import_intel, file_name); } else { CReadIntelHex rih(file_name); if (!rih.Error().IsEmpty()) { AfxMessageBox(rih.Error()); theApp.mac_error_ = 10; return; } // We need to store the data in fairly large chunks otherwise the doc undo // stack becomes very full and slows things down size_t data_len = 32768; unsigned char *file_data = new unsigned char[data_len]; // work buffer unsigned char *pp = file_data; // Ptr into file_data where we are currently storing int len; // length of data from one S record unsigned long address; // Import record address (ignored) bool first(true); // is this the first S record read from the file FILE_ADDRESS start_addr, end_addr, curr_addr = -1; GetSelAddr(start_addr, end_addr); // Get the current selection for (;;) { len = rih.Get(pp, data_len - (pp - file_data), address); if (len <= 0 || (pp - file_data) + len > (int(data_len) - 256)) { // The buffer is almost full or we're finished reading the file - so save buffer if (first) { curr_addr = start_addr; if (start_addr < end_addr) { // Delete current selection and insert new data GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this, TRUE); } else GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this); first = false; } else { ASSERT(curr_addr != -1); GetDocument()->Change(mod_insert, curr_addr, pp - file_data + len, file_data, 0, this, TRUE); } curr_addr += pp - file_data + len; pp = file_data; } else pp += len; if (len <= 0) break; } delete[] file_data; if (!rih.Error().IsEmpty()) AfxMessageBox(rih.Error()); theApp.SaveToMacro(km_import_intel, file_name); SetSel(addr2pos(start_addr), addr2pos(curr_addr)); DisplayCaret(); } } void CHexEditView::OnUpdateImportIntel(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); // disallow insert if file is read only } void CHexEditView::OnExportIntel() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start == end) { // Nothing selected, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("Nothing selected to export!"); theApp.mac_error_ = 10; return; } FILE_ADDRESS last_address; // Byte past the last address to be written out if (theApp.export_base_addr_ < 0) last_address = end; else last_address = end - start + theApp.export_base_addr_; // Check that end address is not too big for Intel Hex Record // Addresses must be within 16 bit range if (last_address > 0x10000) { ASSERT(theApp.playing_); AfxMessageBox("End address too big for Intel hex address field!"); theApp.mac_error_ = 10; return; } // Get the file name to write the selection to CHexFileDialog dlgFile("ExportFileDlg", HIDD_FILE_EXPORT_INTEL, FALSE, NULL, theApp.current_export_, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_SHOWHELP | OFN_NOCHANGEDIR, theApp.GetCurrentFilters(), "Export", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Export Intel Hex"; if (dlgFile.DoModal() != IDOK) { theApp.mac_error_ = 2; return; } theApp.current_export_ = dlgFile.GetPathName(); // Write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) CWriteIntelHex wih(theApp.current_export_, theApp.export_base_addr_ >= 0 ? theApp.export_base_addr_ : long(start), theApp.export_line_len_); if (!wih.Error().IsEmpty()) { AfxMessageBox(wih.Error()); theApp.mac_error_ = 10; theApp.current_export_.Empty(); } else { unsigned char *buf = new unsigned char[4096]; size_t len; CHECK_SECURITY(16); FILE_ADDRESS curr; for (curr = start; curr < end; curr += len) { len = min(4096, int(end - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); wih.Put(buf, len); if (!wih.Error().IsEmpty()) { AfxMessageBox(wih.Error()); theApp.mac_error_ = 10; theApp.current_export_.Empty(); break; } } delete[] buf; ASSERT(curr == end); if (theApp.mac_error_ < 10) theApp.SaveToMacro(km_write_file, 7); } } void CHexEditView::OnUpdateExportIntel(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start >= end) { // We can't export if there is no selection at all pCmdUI->Enable(FALSE); return; } // Work out the last address that needs to be exported if (theApp.export_base_addr_ >= 0) end = end - start + theApp.export_base_addr_; // Addresses must be within 16 bit range pCmdUI->Enable(end <= 0x10000); } void CHexEditView::OnImportHexText() { // Get name of file to import CHexFileDialog dlgFile("ImportFileDlg", HIDD_FILE_IMPORT_HEX, TRUE, NULL, theApp.current_import_, OFN_HIDEREADONLY | OFN_SHOWHELP | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_DONTADDTORECENT, theApp.GetCurrentFilters(), "Import", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Import Hex Text File"; if (dlgFile.DoModal() == IDOK) { theApp.current_import_ = dlgFile.GetPathName(); do_hex_text(theApp.current_import_); } } void CHexEditView::do_hex_text(CString file_name) { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (check_ro("import hex text file")) return; if (display_.overtype) { if (AfxMessageBox("You can't import while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 5; return; } else if (!do_insert()) return; } num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHECK_SECURITY(30); CWaitCursor wait; // Turn on wait cursor (hourglass) CStdioFile ff; // Text file we are reading from CFileException fe; // Stores file exception info // Open the text (input) file if (!ff.Open(file_name, CFile::modeRead|CFile::shareDenyWrite|CFile::typeText, &fe)) { AfxMessageBox(::FileErrorMessage(&fe, CFile::modeRead)); theApp.mac_error_ = 10; return; } __int64 file_len = CFile64::GetSize(file_name); __int64 file_done = 0; // amt of file read so far // Set up handling of a large input hex file by writing result to one of our temp files CFile64 fout; // output file (only used if input file is big) char temp_file[_MAX_PATH]; temp_file[0] = '\0'; // Test if the file is very big if (file_len > (3*16*1024*1024) && GetDocument()->DataFileSlotFree()) // assuming 3 chars/byte ~= 16 Mb { // Create a file to store the bytes char temp_dir[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); if (!fout.Open(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary, &fe)) { AfxMessageBox(::FileErrorMessage(&fe, CFile::modeWrite)); theApp.mac_error_ = 10; return; } } else if (file_len > 3*128*1024*1024) { // Warn of possible memory shortage if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and reading such a large file \n" "may cause memory exhaustion. Please click NO \n" "and save the active file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } // Input buffer (read from hex text file) char buffer[520]; // Where read string is stored char *pp; // Ptr into read string long line_no = 0; // Current text line read // We need to store the data in fairly large chunks otherwise the doc undo // stack becomes very full and slows things down size_t data_len = 32768; unsigned char *file_data = NULL; // work buffer try { file_data = new unsigned char[data_len]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } unsigned char *pout = file_data; // Ptr into file_data where we are currently storing bool first(true); // is this the first line read from the file FILE_ADDRESS start_addr, end_addr, curr_addr = -1; GetSelAddr(start_addr, end_addr); // Get the current selection buffer[0] = '\0'; pp = buffer; for (;;) // loop on output bytes (one or two input hecx digits) { // Skip whitespace/unused characters etc while (*pp != '\0' && !isalpha(*pp) && !isdigit(*pp)) ++pp; // If at end of string get the next line from the file while (*pp == '\0') // skip strings till we get a non-empty one { file_done += pp - buffer + 2; try { pp = ff.ReadString(buffer, sizeof(buffer)-1); ++line_no; } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeRead)); pfe->Delete(); goto error_return; } if (pp == NULL) goto end_file; // EOF // Skip leading whitespace/unused characters etc while (*pp != '\0' && !isalpha(*pp) && !isdigit(*pp)) ++pp; } if (!isxdigit(*pp)) { CString ss; ss.Format("Unexpected alpha characters in hex text file at line %ld", long(line_no)); AfxMessageBox(ss); goto error_return; } if (isdigit(*pp)) *pout = *pp - '0'; else if (isupper(*pp)) *pout = *pp - 'A' + 10; else *pout = *pp - 'a' + 10; ++pp; // If pair of hex digits read as 2 nybbles of a byte if (isxdigit(*pp)) { if (isdigit(*pp)) *pout = (*pout << 4) | (*pp - '0'); else if (isupper(*pp)) *pout = (*pout << 4) | (*pp - 'A' + 10); else *pout = (*pout << 4) | (*pp - 'a' + 10); ++pp; } // Check if the output buffer is full if (++pout >= file_data + data_len) { ASSERT(pout == file_data + data_len); // The buffer is almost full or we're finished reading the file - so save buffer if (fout.GetHandle() != INVALID_HANDLE_VALUE) { // Writing to temp file try { fout.Write(file_data, data_len); } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); fout.Close(); remove(temp_file); goto error_return; } if (AbortKeyPress() && AfxMessageBox("Abort hex import?", MB_YESNO) == IDYES) { fout.Close(); remove(temp_file); goto error_return; } mm->Progress(int((file_done*100)/file_len)); } else if (first) { // First in memory block to be stored - may replace the current selection ASSERT(curr_addr == -1); curr_addr = start_addr; if (start_addr < end_addr) { // Delete current selection and insert new data GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this, TRUE); } else GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this); first = false; } else { // Next in memory block - just insert it ASSERT(curr_addr != -1); GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this, TRUE); } curr_addr += pout - file_data; pout = file_data; } } end_file: // Write out any partial buffer at end if (pout > file_data) { if (fout.GetHandle() != INVALID_HANDLE_VALUE) { // Writing to temp file try { fout.Write(file_data, pout - file_data); } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); fout.Close(); remove(temp_file); goto error_return; } } else if (first) { ASSERT(curr_addr == -1); curr_addr = start_addr; if (start_addr < end_addr) { // Delete current selection and insert new data GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this, TRUE); } else GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this); first = false; } else { ASSERT(curr_addr != -1); GetDocument()->Change(mod_insert, curr_addr, pout - file_data, file_data, 0, this, TRUE); } curr_addr += pout - file_data; } if (fout.GetHandle() != INVALID_HANDLE_VALUE) { FILE_ADDRESS fout_len = fout.GetLength(); fout.Close(); // close the file so we can use it // Add the temp file to the document int idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); if (start_addr < end_addr) { // Delete current selection and insert new data GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert_file, start_addr, fout_len, NULL, idx, this, TRUE); } else GetDocument()->Change(mod_insert_file, start_addr, fout_len, NULL, idx, this); // NOTE: curr_data is not used when writing to temp file except below (in selecting // the inserted data) - so we have to set it here. curr_addr = start_addr + fout_len; } delete[] file_data; mm->Progress(-1); // disable progress bar SetSel(addr2pos(start_addr), addr2pos(curr_addr)); DisplayCaret(); theApp.SaveToMacro(km_import_text, file_name); return; error_return: delete[] file_data; mm->Progress(-1); // disable progress bar theApp.mac_error_ = 10; } void CHexEditView::OnUpdateImportHexText(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); // disallow insert if file is read only } void CHexEditView::OnExportHexText() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the selection FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); ASSERT(start_addr >= 0 && start_addr <= end_addr && end_addr <= GetDocument()->length()); if (start_addr >= end_addr) { // Nothing selected, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("Nothing selected to export!"); theApp.mac_error_ = 10; return; } // Get the file name to write the selection to CHexFileDialog dlgFile("ExportFileDlg", HIDD_FILE_EXPORT_HEX, FALSE, NULL, theApp.current_export_, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_SHOWHELP | OFN_NOCHANGEDIR, theApp.GetCurrentFilters(), "Export", this); // Set up the title of the dialog dlgFile.m_ofn.lpstrTitle = "Export Hex Text"; if (dlgFile.DoModal() != IDOK) { theApp.mac_error_ = 2; return; } theApp.current_export_ = dlgFile.GetPathName(); // Now write to the file CWaitCursor wait; // Turn on wait cursor (hourglass) CHECK_SECURITY(48); CFile64 ff; CFileException fe; // Stores file exception info // Open the file to export to if (!ff.Open(theApp.current_export_, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary, &fe)) { AfxMessageBox(::FileErrorMessage(&fe, CFile::modeWrite)); theApp.mac_error_ = 10; theApp.current_export_.Empty(); return; } // This could be perhaps 2 or 3 times faster by buffering more than a line of text at a time // Buffer used to hold bits of the binary file to convert unsigned char *buf = NULL; // Buffer to hold some input char *out = NULL; // Buffer for output of one line of text unsigned char *pin; FILE_ADDRESS curr; size_t len; try { buf = new unsigned char[theApp.export_line_len_]; out = new char[3*theApp.export_line_len_ + 5]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } const char *hex; if (theApp.hex_ucase_) hex = "0123456789ABCDEF?"; else hex = "0123456789abcdef?"; clock_t last_checked = clock(); for (curr = start_addr; curr < end_addr; curr += len) { // Get the data bytes len = size_t(min(FILE_ADDRESS(theApp.export_line_len_), end_addr - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); // Convert to hex text char *pout = out; for(pin = buf; pin < buf+len; ++pin) { *pout++ = hex[(*pin>>4)&0xF]; *pout++ = hex[*pin&0xF]; *pout++ = ' '; } *pout++ = '\r'; *pout++ = '\n'; // Write the string to the file try { ff.Write(out, pout - out); } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); theApp.mac_error_ = 10; goto func_return; } if (AbortKeyPress() && AfxMessageBox("Abort exporting as hex?", MB_YESNO) == IDYES) { theApp.mac_error_ = 10; goto func_return; } if (double(clock() - last_checked)/CLOCKS_PER_SEC > 3) // update every 3 secs { mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); last_checked = clock(); } } ASSERT(curr == end_addr); func_return: ff.Close(); mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; if (out != NULL) delete[] out; if (theApp.mac_error_ < 5) theApp.SaveToMacro(km_write_file, 10); } void CHexEditView::OnUpdateExportHexText(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); pCmdUI->Enable(start < end); } // This is here only so we can put it in context menu for view void CHexEditView::OnEditFind() { ((CMainFrame *)AfxGetMainWnd())->OnEditFind(); } // This is here only so we can put it in context menu for view void CHexEditView::OnEditReplace() { ((CMainFrame *)AfxGetMainWnd())->OnEditReplace(); } // This is here only so we can put it in context menu for view void CHexEditView::OnEditGoto() { ((CMainFrame *)AfxGetMainWnd())->OnEditGoto(); } void CHexEditView::OnCalcSel() { ((CMainFrame *)AfxGetMainWnd())->OnCalcSel(); } void CHexEditView::OnUpdateCalcSel(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); pCmdUI->Enable(end_addr - start_addr < 9); } void CHexEditView::OnEditCut() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar // Can't delete if view is read only or in overtype mode if (check_ro("cut to the clipboard")) return; if (display_.overtype) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("You can't cut while in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 5; return; } else if (!do_insert()) return; } // Copy the selection to the clipboard and then delete it if (!CopyToClipboard()) { ASSERT(aa->mac_error_ > 0); // There must have been an error return; } // Handle deletion of chars at caret or selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start < end && end <= GetDocument()->length()); GetDocument()->Change(mod_delforw, start, end-start, NULL, 0, this); DisplayCaret(); // Make sure caret is visible CHECK_SECURITY(101); aa->SaveToMacro(km_cut); } void CHexEditView::OnUpdateEditCut(CCmdUI* pCmdUI) { if (GetDocument()->read_only()) pCmdUI->Enable(FALSE); // disallow cut if file is read only else OnUpdateClipboard(pCmdUI); } void CHexEditView::OnEditCopy() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar if (CopyToClipboard()) aa->SaveToMacro(km_copy); } // Update handler that turns on certain user interface options (Copy etc) if there // is a selection -- ie. there is something available to be placed on the clipboard void CHexEditView::OnUpdateClipboard(CCmdUI* pCmdUI) { // Is there any text selected? CPointAp start, end; GetSel(start, end); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start != end ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(start != end); } bool CHexEditView::CopyToClipboard() { // Get the addresses of the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); // Clipboard setup and error checking if (!copy2cb_init(start, end)) return false; // Work out which format(s) to put on the clipboard. Generally, we place // both binary data ("BinaryData") and text (either the text chars if valid // characters or binary data as hex digits), but if the data is too big // it may just be stored in a temp binary file ("HexEditLargeDataTempFile"). cb_text_type cb_text = cb_text_chars; bool use_file = false; // Use our own special format if too big for clipboard CString strTemp; // name of temp file is used if (end - start > MAX_CLIPBOARD) { use_file = true; } else if (cb_text == cb_text_auto) { cb_text = is_binary(start, end) ? cb_text_hextext : cb_text_chars; } CWaitCursor wait; // Turn on wait cursor (hourglass) bool some_succeeded = false, some_failed = false; if (!use_file) { // Now put text data onto the clipboard if (cb_text == cb_text_hextext) { // Text is hex text (eg 3 chars "ABC" -> " 61 62 63") if (copy2cb_hextext(start, end)) some_succeeded = true; else some_failed = true; } else { // Text as actual chars (if valid) including char set conversion if (copy2cb_text(start, end)) some_succeeded = true; else some_failed = true; } // And also as binary if (copy2cb_binary(start, end)) some_succeeded = true; else use_file = true; // Possibly too big error - so use temp file format } if (use_file) { // Store all the data as binary in a (semi) temporary file. strTemp = copy2cb_file(start, end); if (!strTemp.IsEmpty()) some_succeeded = true; else some_failed = true; } ASSERT(some_succeeded || some_failed); if (some_succeeded) theApp.ClipBoardAdd(end - start, strTemp); if (!::CloseClipboard() || some_failed) { theApp.mac_error_ = 20; return false; } return true; } // Copy to clipboard as hex text void CHexEditView::OnCopyHex() { // Get the addresses of the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); // Clipboard setup and error checking if (!copy2cb_init(start, end)) return; CWaitCursor wait; // Turn on wait cursor (hourglass) bool ok = copy2cb_hextext(start, end); if (::CloseClipboard() && ok) { theApp.ClipBoardAdd((end - start)*3); theApp.SaveToMacro(km_copy_hex); } else theApp.mac_error_ = 20; } // Set up clipboard ready for having data added to it. // start,end = the part of the file to save (ie the selection) // If there is any problem it returns false after // displaying an error message and setting macro error level. bool CHexEditView::copy2cb_init(FILE_ADDRESS start, FILE_ADDRESS end) { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Check for problems with selection size if (start == end) { ASSERT(theApp.playing_); // Macro might have recorded Copy but when played there is no selection // Copy to clipboard while nothing selected, presumably in macro playback AfxMessageBox("Nothing selected to place on clipboard!"); theApp.mac_error_ = 10; return false; } if (end-start > 4000000L) { CString ss; ss.Format("Do you really want to put %sbytes on\n" "the clipboard? This may take some time.", NumScale(double(end-start))); if (AfxMessageBox(ss, MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return false; } } // Now open and empty the clipboard ready for copying data into if (!OpenClipboard()) { AfxMessageBox("The clipboard is in use!"); theApp.mac_error_ = 10; return false; } if (!::EmptyClipboard()) { AfxMessageBox("Could not delete previous contents of the clipboard!"); ::CloseClipboard(); theApp.mac_error_ = 10; return false; } return true; } // Copy selection to clipboard as text which can be pasted into a text editor etc. // Invalid text characters (eg nul byte) are not copied. // If current display mode is EBCDIC then the characters are converted from // EBCDIC to ASCII as they are added. bool CHexEditView::copy2cb_text(FILE_ADDRESS start, FILE_ADDRESS end) { // Get windows memory to allow data to be put on clipboard HANDLE hh; // Windows handle for memory unsigned char *p_cb, *pp; // Ptrs to + within the clipboard mem if ((hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, size_t(end-start+1))) == NULL || (p_cb = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) == NULL) { AfxMessageBox("Not enough memory to add text to clipboard"); theApp.mac_error_ = 10; return false; } // Copy the data from the document to the global memory unsigned char * buf = new unsigned char[clipboard_buf_len]; size_t len; pp = p_cb; FILE_ADDRESS curr; for (curr = start; curr < end; curr += len) { len = min(clipboard_buf_len, int(end - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); // Copy all characters in buffer to clipboard memory (unless nul) unsigned char *end_buf = buf + len; if (display_.char_set != CHARSET_EBCDIC) { for (unsigned char *ss = buf; ss < end_buf; ++ss) if (*ss != '\0') *pp++ = *ss; } else { for (unsigned char *ss = buf; ss < end_buf; ++ss) if (e2a_tab[*ss] != '\0') *pp++ = e2a_tab[*ss]; } } ASSERT(curr == end); delete[] buf; // If pp has not been incremented then no valid characters were copied if (pp == p_cb) { theApp.mac_error_ = 1; ((CMainFrame *)AfxGetMainWnd())-> StatusBarText("Warning: no valid text bytes - no text placed on clipboard"); } *pp ='\0'; if (::SetClipboardData(CF_TEXT, hh) == NULL) { ::GlobalFree(hh); AfxMessageBox("Could not place text data on clipboard"); theApp.mac_error_ = 10; return false; } // Note: the clipboard now owns the memory so ::GlobalFree(hh) should not be called ::GlobalUnlock(hh); return true; } // Copy to the clipboard in our own custom format "HexEditLargeDataTempFile". // This creates a Windows temporary file with all the data and just // puts the file name onto the clipboard. (The temp file is deleted // later when the clipboard changes or when HexEdit exits.) // It returns the name of the temp file or an empty string if there is // some sort of error, the most likely being a file error. CString CHexEditView::copy2cb_file(FILE_ADDRESS start, FILE_ADDRESS end) { CString TempFileName; // Create a temp file and write the data to it. { char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); TempFileName = temp_file; } if (!GetDocument()->WriteData(TempFileName, start, end)) { //AfxMessageBox("Error writing clipboard to disk"); theApp.mac_error_ = 10; return CString(); } HANDLE hh; // Windows handle for memory unsigned char *pp; // Actual pointer to the memory // Create the custom clipboard format (or get it if it already exists) // and get the memory to store the file name. UINT temp_format; if ((temp_format = ::RegisterClipboardFormat(CHexEditApp::temp_format_name)) == 0 || (hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, size_t(TempFileName.GetLength()+4))) == NULL || (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) == NULL) { AfxMessageBox("Not enough memory to add binary data to clipboard"); theApp.mac_error_ = 10; return CString(); } // Put the length of the file name long *pl = reinterpret_cast<long *>(pp); *pl = TempFileName.GetLength(); // Put the filename memcpy(pp+4, TempFileName.GetBuffer(), TempFileName.GetLength()); if (::SetClipboardData(temp_format, hh) == NULL) { ::GlobalFree(hh); AfxMessageBox("Could not place custom data on clipboard"); theApp.mac_error_ = 10; return CString(); } // Note: the clipboard now owns the memory so ::GlobalFree(hh) should not be called ::GlobalUnlock(hh); return TempFileName; } // Copy the selection to the clipboard in custom "BinaryData" format. // This is the same format as used by the Visual Studio hex editor, // simply consisting of a length (32-bit integer) followed by the bytes. // May return false due to errors such as insufficient memory, whence // a message has been shown to the user and mac_error_ has been set. bool CHexEditView::copy2cb_binary(FILE_ADDRESS start, FILE_ADDRESS end) { HANDLE hh; // Windows handle for memory unsigned char *pp; // Actual pointer to the memory // Create the "BinaryData" clipboard format (or get it if it already exists) // then get windows memory to allow binary data to be put on clipboard // then lock the memory UINT bin_format; if ((bin_format = ::RegisterClipboardFormat(CHexEditApp::bin_format_name)) == 0 || (hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, size_t(end-start+4))) == NULL || (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) == NULL) { AfxMessageBox("Not enough memory to add binary data to clipboard"); theApp.mac_error_ = 10; return false; } // Add the binary data length to first 4 bytes of BinaryData clipboard memory long *pl = reinterpret_cast<long *>(pp); *pl = long(end - start); // Copy the data from the document to the global memory VERIFY(GetDocument()->GetData(pp+4, size_t(end - start), start) == end - start); if (::SetClipboardData(bin_format, hh) == NULL) { ::GlobalFree(hh); AfxMessageBox("Could not place binary data on clipboard"); theApp.mac_error_ = 10; return false; } // Note: the clipboard now owns the memory so ::GlobalFree(hh) should not be called ::GlobalUnlock(hh); return true; } // Copy to clipboard as hex text, ie, each byte is stored as // 2 hex digits + also includes spaces etc. bool CHexEditView::copy2cb_hextext(FILE_ADDRESS start, FILE_ADDRESS end) { // Work out the amount of memory needed (may be slightly more than needed). FILE_ADDRESS mem_needed = hex_text_size(start, end); // Get windows memory to allow data to be put on clipboard HANDLE hh; // Windows handle for memory char *p_cb, *pp; // Ptr to start and within the clipboard text if ((hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, DWORD(mem_needed))) == NULL || (p_cb = reinterpret_cast<char *>(::GlobalLock(hh))) == NULL) { AfxMessageBox("Not enough memory to add hex text to clipboard"); theApp.mac_error_ = 10; return false; } unsigned char cc; const char *hex; if (theApp.hex_ucase_) hex = "0123456789ABCDEF?"; else hex = "0123456789abcdef?"; pp = p_cb; FILE_ADDRESS curr; for (curr = start; curr < end; ) { VERIFY(GetDocument()->GetData(&cc, 1, curr) == 1); *pp++ = hex[(cc>>4)&0xF]; *pp++ = hex[cc&0xF]; *pp++ = ' '; if ((++curr + offset_)%rowsize_ == 0) { *pp++ = '\r'; *pp++ = '\n'; } } if ((curr + offset_)%rowsize_ != 0) { // Add line termination at end *pp++ = '\r'; *pp++ = '\n'; } *pp ='\0'; if (::SetClipboardData(CF_TEXT, hh) == NULL) { ::GlobalFree(hh); AfxMessageBox("Could not place hex text data on clipboard"); theApp.mac_error_ = 10; return false; } // Note: the clipboard now owns the memory so ::GlobalFree(hh) should not be called ::GlobalUnlock(hh); return true; } bool CHexEditView::is_binary(FILE_ADDRESS start, FILE_ADDRESS end) { unsigned char buf[8192]; size_t len; for (FILE_ADDRESS curr = start; curr < end; curr += len) { // Get the next buffer full from the document len = size_t(min(sizeof(buf), end - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); // For now we only consider data with a null byte to be binary // since the clipboard can actually have any other character // added to it in text format. However, it may make sense to be // more restrictive later. if (memchr(buf, '\0', len) != NULL) return true; } return false; } // Copy to cipboard as C source (characters stored as hex ints) void CHexEditView::OnCopyCchar() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Get the addresses of the selection FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); if (start == end) { // Copy to clipboard while nothing selected, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("Nothing selected to place on clipboard!"); theApp.mac_error_ = 10; return; } CCopyCSrc dlg; if (dlg.DoModal() == IDOK) { do_copy_src(dlg.type_, dlg.type_ == CCopyCSrc::FLOAT ? dlg.float_size_ : dlg.int_size_, dlg.int_type_, dlg.big_endian_, dlg.show_address_, dlg.indent_); } } // do_copy_src: creates text on the clipboard from the current selection based on parameters passed // src_type = CCopyCSrc::STRING, CCopyCSrc::CHAR, CCopyCSrc::INT, or CCopyCSrc::FLOAT // src_size = 0,1,2,3 for 4 sizes of int, or 0,1 for 2 sizes of float // int_type = 0,1,2,3 for how the ints are to be output // big_endian = determines the byte order for ints and floats void CHexEditView::do_copy_src(int src_type, int src_size, int int_type, BOOL big_endian, BOOL show_address, int indent) { FILE_ADDRESS start, end; GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= GetDocument()->length()); // Clipboard setup and error checking if (!copy2cb_init(start, end)) return; // // Work out the amount of memory needed (may be slightly more than needed). // // Allow 6 chars for every byte ("0x" + 2 hex digits + comma + space), plus // // 7 ("/**/ "+CR+LF) + addr_width_ chars per line, + 1 trailing nul byte. // FILE_ADDRESS mem_needed = (end-start)*6+((end-start)/rowsize_+2)*(7+addr_width_)+1; FILE_ADDRESS mem_needed; switch (src_type) { default: ASSERT(0); // fall through case CCopyCSrc::STRING: // Max 4 chars per byte + 9 bytes for each line (/**/ ""\r\n) + address for each line + terminator mem_needed = (end-start)*4 + ((end-start)/rowsize_+2)*(indent+9+addr_width_) + 2; break; case CCopyCSrc::CHAR: case CCopyCSrc::INT: case CCopyCSrc::FLOAT: // Max 8 chars per byte + 7 bytes per line (/**/ \r\n) + address per line + terminator mem_needed = (end-start)*8 + ((end-start)/rowsize_+2)*(indent+7+addr_width_) + 2; break; } CWaitCursor wait; // Turn on wait cursor (hourglass) { // Get windows memory to allow data to be put on clipboard HANDLE hh; // Windows handle for memory char *p_cb, *pp; // Ptr to start and within the clipboard text size_t slen; // Number of characters added to ouput buffer by sprintf call if ((hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, DWORD(mem_needed))) == NULL || (p_cb = reinterpret_cast<char *>(::GlobalLock(hh))) == NULL) { AfxMessageBox("Insufficient memory for clipboard data"); ::CloseClipboard(); theApp.mac_error_ = 10; return; } p_cb[mem_needed-1] = '\xCD'; // Add marker char at end so we can check if buffer was overflowed // string containing 128 spaces const char *spaces = " " " "; const char *hex; // string containing hex digits (in current selected case) if (theApp.hex_ucase_) hex = "0123456789ABCDEF?"; else hex = "0123456789abcdef?"; pp = p_cb; // Add any indenting ASSERT(indent < 128); slen = sprintf(pp, "%.*s", indent, spaces); pp += slen; if (show_address) { // Add initial address *pp++ = '/'; *pp++ = '*'; if (hex_width_ > 0) { slen = sprintf(pp, theApp.hex_ucase_ ? "%0*I64X:" : "%0*I64x:", hex_width_, start + display_.addrbase1); pp += slen; } if (dec_width_ > 0) { slen = sprintf(pp, "%*I64d:", dec_width_, start + display_.addrbase1); pp += slen; } // xxx also line numbers (num_width_) *pp++ = '*'; *pp++ = '/'; *pp++ = ' '; } if (src_type == CCopyCSrc::STRING) *pp++ = '"'; FILE_ADDRESS curr = start; // Address of current byte being worked on FILE_ADDRESS line_end; // Address of byte at end of current line line_end = ((start + offset_)/rowsize_ + 1)*rowsize_ - offset_; // Work out how many bytes in each chunk size_t get_len; // Size of each chunk (1,2,4, or 8) switch (src_type) { default: ASSERT(0); // fall through case CCopyCSrc::STRING: case CCopyCSrc::CHAR: get_len = 1; break; case CCopyCSrc::INT: switch (src_size) { default: ASSERT(0); // fall through case CCopyCSrc::INT_32: get_len = 4; break; case CCopyCSrc::INT_8: get_len = 1; break; case CCopyCSrc::INT_16: get_len = 2; break; case CCopyCSrc::INT_64: get_len = 8; break; } break; case CCopyCSrc::FLOAT: switch (src_size) { default: ASSERT(0); // fall through case CCopyCSrc::FLOAT_64: get_len = 8; break; case CCopyCSrc::FLOAT_32: get_len = 4; break; case CCopyCSrc::REAL_48: get_len = 6; break; } break; } for (curr = start; curr + get_len <= end; ) { unsigned char buf[8]; // Largest is 64 bit int/float (8 bytes) VERIFY(GetDocument()->GetData(buf, get_len, curr) == get_len); switch (src_type) { default: ASSERT(0); // fall through case CCopyCSrc::STRING: // if (isprint(buf[0])) // isprint seems to return true for ANSI chars too if (buf[0] >= ' ' && buf[0] < 127) { // Backslash (\) and double-quote (") must be escaped and also do question // mark (?) to avoid accidentally creating a trigraph sequence (??=, etc) if (strchr("\\\"\?", buf[0])) *pp++ = '\\'; *pp++ = buf[0]; } else { // Control char or non-ASCII char - display as escape char or in hex const char *check = "\a\b\f\n\r\t\v"; // used in search for escape char const char *display = "abfnrtv0"; const char *ps; // Note we output a nul byte as hex just in case it is followed by another // digit. Since strchr includes the terminating nul byte in the search // we have to explicitly check for it. if (buf[0] != '\0' && (ps = strchr(check, buf[0])) != NULL) { // Ouput C/C++ escape sequence *pp++ = '\\'; *pp++ = display[ps-check]; } else { // Output using hex escape sequence *pp++ = '\\'; *pp++ = 'x'; *pp++ = hex[(buf[0]>>4)&0xF]; *pp++ = hex[buf[0]&0xF]; ASSERT(get_len == 1); // If not at end of line we have to watch that the following char is not a hex digit if (curr + get_len < line_end && curr + get_len < end) { // Not at EOL so get the next character into buf[1] VERIFY(GetDocument()->GetData(buf+1, 1, curr + get_len) == 1); if (isxdigit(buf[1])) { // Terminate the string and start a new one so that the following char // does not become concatenated with the 2 hex digits already output *pp++ = '"'; *pp++ = ' '; *pp++ = '"'; } } } } break; case CCopyCSrc::CHAR: *pp++ = '\''; // put in single quotes // if (isprint(buf[0])) if (buf[0] >= ' ' && buf[0] < 127) { // Backslash (\) and apostrophe or single quote (') must be escaped if (strchr("\\'", buf[0])) *pp++ = '\\'; *pp++ = buf[0]; } else { // Control char or non-ASCII char - display as escape char or in hex const char *check = "\a\b\f\n\r\t\v\0"; const char *display = "abfnrtv0"; const char *ps; if ((ps = strchr(check, buf[0])) != NULL) { // Ouput C/C++ escape sequence *pp++ = '\\'; *pp++ = display[ps-check]; } else { // Output using hex escape sequence *pp++ = '\\'; *pp++ = 'x'; *pp++ = hex[(buf[0]>>4)&0xF]; *pp++ = hex[buf[0]&0xF]; } } *pp++ = '\''; // trailing single quote *pp++ = ','; *pp++ = ' '; break; case CCopyCSrc::INT: if (big_endian) flip_bytes(buf, get_len); switch (src_size) { default: ASSERT(0); // fall through case CCopyCSrc::INT_32: switch (int_type) { default: ASSERT(0); // fall through case CCopyCSrc::INT_UNSIGNED: slen = sprintf(pp, "%10u, ", *(long *)buf); break; case CCopyCSrc::INT_SIGNED: slen = sprintf(pp, "%11d, ", *(long *)buf); break; case CCopyCSrc::INT_OCTAL: slen = sprintf(pp, "%012o, ", *(long *)buf); // octal with leading zeroes break; case CCopyCSrc::INT_HEX: if (theApp.hex_ucase_) slen = sprintf(pp, "0x%08X, ", *(long *)buf); // 0x then leading zeroes else slen = sprintf(pp, "0x%08x, ", *(long *)buf); break; } break; case CCopyCSrc::INT_8: switch (int_type) { default: ASSERT(0); // fall through case CCopyCSrc::INT_UNSIGNED: slen = sprintf(pp, "%3u, ", buf[0]); break; case CCopyCSrc::INT_SIGNED: slen = sprintf(pp, "%4d, ", (signed char)buf[0]); break; case CCopyCSrc::INT_OCTAL: slen = sprintf(pp, "%04o, ", buf[0]); break; case CCopyCSrc::INT_HEX: if (theApp.hex_ucase_) slen = sprintf(pp, "0x%02.2X, ", buf[0]); else slen = sprintf(pp, "0x%02.2x, ", buf[0]); break; } break; case CCopyCSrc::INT_16: switch (int_type) { default: ASSERT(0); // fall through case CCopyCSrc::INT_UNSIGNED: slen = sprintf(pp, "%5hu, ", *(short *)buf); break; case CCopyCSrc::INT_SIGNED: slen = sprintf(pp, "%6hd, ", *(short *)buf); break; case CCopyCSrc::INT_OCTAL: slen = sprintf(pp, "%07ho, ", *(short *)buf); break; case CCopyCSrc::INT_HEX: if (theApp.hex_ucase_) slen = sprintf(pp, "0x%04.4hX, ", *(short *)buf); else slen = sprintf(pp, "0x%04.4hx, ", *(short *)buf); break; } break; case CCopyCSrc::INT_64: switch (int_type) { default: ASSERT(0); // fall through case CCopyCSrc::INT_UNSIGNED: slen = sprintf(pp, "%20I64u, ", *(__int64 *)buf); break; case CCopyCSrc::INT_SIGNED: slen = sprintf(pp, "%20I64d, ", *(__int64 *)buf); break; case CCopyCSrc::INT_OCTAL: slen = sprintf(pp, "%023I64o, ", *(__int64 *)buf); break; case CCopyCSrc::INT_HEX: if (theApp.hex_ucase_) slen = sprintf(pp, "0x%016I64X, ", *(__int64 *)buf); else slen = sprintf(pp, "0x%016I64x, ", *(__int64 *)buf); break; } break; } pp += slen; ASSERT(*(pp-1) == ' '); // Checks that slen was correct and trailing space added break; case CCopyCSrc::FLOAT: if (big_endian) flip_bytes(buf, get_len); switch (src_size) { default: ASSERT(0); // fall through case CCopyCSrc::FLOAT_64: slen = sprintf(pp, "%22.15g, ", *(double *)buf); break; case CCopyCSrc::FLOAT_32: slen = sprintf(pp, "%14.7g, ", *(float *)buf); break; case CCopyCSrc::REAL_48: slen = sprintf(pp, "%19.12g, ", real48(buf)); break; } pp += slen; ASSERT(*(pp-1) == ' '); break; } // Check if we need to start a new line if ((curr += get_len) >= line_end || curr >= end) { // Terminate previous line if (src_type == CCopyCSrc::STRING) *pp++ = '"'; // terminate string on this line *pp++ = '\r'; *pp++ = '\n'; // If this is not the last line if (curr < end) { // Add any indenting slen = sprintf(pp, "%.*s", indent, spaces); pp += slen; if (show_address) { // Output address (in comments) at the start of the line *pp++ = '/'; *pp++ = '*'; if (hex_width_ > 0) { slen = sprintf(pp, theApp.hex_ucase_ ? "%0*I64X:" : "%0*I64x:", hex_width_, curr + display_.addrbase1); pp += slen; } if (dec_width_ > 0) { slen = sprintf(pp, "%*I64d:", dec_width_, curr + display_.addrbase1); pp += slen; } // xxx also line numbers (num_width_) *pp++ = '*'; *pp++ = '/'; *pp++ = ' '; } if (src_type == CCopyCSrc::STRING) *pp++ = '"'; // start new string on this new line } // Work out where this next line ends line_end += rowsize_; } } *pp ='\0'; ASSERT(pp-p_cb < mem_needed); ASSERT(p_cb[mem_needed-1] == '\xCD'); // Check if buffer was overflowed if (::SetClipboardData(CF_TEXT, hh) == NULL) { ASSERT(0); ::GlobalFree(hh); AfxMessageBox("Could not place data on clipboard"); ::CloseClipboard(); theApp.mac_error_ = 10; return; } theApp.ClipBoardAdd(pp - p_cb); // Note: the clipboard now owns the memory so ::GlobalFree(hh) should not be called ::GlobalUnlock(hh); } if (!::CloseClipboard()) theApp.mac_error_ = 20; else theApp.SaveToMacro(km_copy_cchar, src_type | (src_size<<3) | (int_type<<6) | (big_endian ? 0x0200 : 0) | (show_address ? 0 : 0x0400) | /* bit off means show */ (__int64(indent&0x7F)<<11)); } // start+end define the bytes to be replaced // pp points to the new bytes and len is the number of new bytes void CHexEditView::do_replace(FILE_ADDRESS start, FILE_ADDRESS end, unsigned char *pp, size_t len) { // Can't replace if view is read only if (check_ro("replace")) return; num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing ASSERT(start < end && end <= GetDocument()->length()); if (display_.overtype && end-start != len) { // xxx direct warning if GetDocument()->IsDevice()? if (AfxMessageBox("This replacement requires insert mode..\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { theApp.mac_error_ = 10; return; } else if (!do_insert()) return; } if (display_.overtype || end-start == len) { GetDocument()->Change(mod_replace, start, len, pp, 0, this); } else { GetDocument()->Change(mod_delforw, start, end-start, NULL, 0, this); if (len > 0) GetDocument()->Change(mod_insert, start, len, pp, 0, this, TRUE); } int row = 0; if (display_.vert_display) row = pos2row(GetCaret()); SetSel(addr2pos(start+len, row), addr2pos(start+len, row)); DisplayCaret(); show_prop(); // Make sure dialogs don't obscure our changes show_calc(); show_pos(); // Update tool bar } void CHexEditView::OnEditPaste() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar // Can't paste if view is read only if (check_ro("paste")) return; num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing UINT ff = 0; // Clipboard format number HANDLE hh; // Handle to clipboard memory unsigned char *pp; // Pointer to actual data if (!OpenClipboard()) { ASSERT(0); AfxMessageBox("The clipboard is in use!"); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) // Check if there is a "BinaryData" format (added by us or DevStudio) while ((ff = EnumClipboardFormats(ff)) != 0) { CString tt; char name[16]; size_t nlen = ::GetClipboardFormatName(ff, name, 15); name[nlen] = '\0'; if (strcmp(name, CHexEditApp::bin_format_name) == 0) { // BINARY DATA if ((hh = ::GetClipboardData(ff)) != NULL && (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) != NULL) { long *pl = reinterpret_cast<long *>(pp); FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + *pl > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) { ::CloseClipboard(); return; } } else if (display_.overtype && end_addr-start_addr != *pl) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) { ::CloseClipboard(); return; } break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; ::CloseClipboard(); return; } } // OK make the change if (display_.overtype || end_addr-start_addr == *pl) GetDocument()->Change(mod_replace, start_addr, *pl, pp+4, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, *pl, pp+4, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, *pl, pp+4, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr+*pl)); SetSel(addr2pos(start_addr+*pl, row), addr2pos(start_addr+*pl, row)); DisplayCaret(); show_prop(); // New char - check props show_calc(); show_pos(); // Update tool bar aa->SaveToMacro(km_paste); } else aa->mac_error_ = 20; // It's there but couldn't get it ::CloseClipboard(); return; } else if (strcmp(name, CHexEditApp::temp_format_name) == 0) { // Binary data in temp file if ((hh = ::GetClipboardData(ff)) != NULL && (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) != NULL) { // Get the temp file name CString strTemp; long *pl = reinterpret_cast<long *>(pp); memcpy(strTemp.GetBuffer(*pl), pp+4, *pl); strTemp.ReleaseBuffer(*pl); // adds null byte at end ::CloseClipboard(); // We have got everything from the cb memory // Make sure there is a temp file handle available. (We are going to // use mod_insert_file to access data directly from the temp file // as we don't want to read the whole (large} file into memory.) int idx = GetDocument()->AddDataFile(strTemp); if (idx == -1) { AfxMessageBox("HexEdit is out of temporary files and\n" "cannot paste from a temporary clipboard file. \n" "Please save your file to free \n" "temporary file handles and try again.\n", MB_OK); aa->mac_error_ = 10; return; } // Get the file's length so we know how much is being pasted CFileStatus fs; VERIFY(CFile64::GetStatus(strTemp, fs)); // Get selection so we can replace it (and also to restore caret later) FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Do some file mode checks and fixes as specified by the user if (display_.overtype && start_addr + fs.m_size > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != fs.m_size) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // Insert/replace with temp data file if (display_.overtype) { // Effectively replace using the file length GetDocument()->Change(mod_delforw, start_addr, fs.m_size, NULL, 0, this); GetDocument()->Change(mod_insert_file, start_addr, fs.m_size, NULL, idx, this, TRUE); } else { // Wipe out any current selection then insert the data if (start_addr < end_addr) GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert_file, start_addr, fs.m_size, NULL, idx, this, TRUE); } // Restore caret and update everything due to possible new data at the caret SetSel(addr2pos(start_addr+fs.m_size, row), addr2pos(start_addr+fs.m_size, row)); DisplayCaret(); show_prop(); // New current char - check props show_calc(); show_pos(); // Update tool bar aa->SaveToMacro(km_paste); } else aa->mac_error_ = 20; // It's there but couldn't get it return; } } // BinaryData format not found so just use text format if ((hh = ::GetClipboardData(CF_TEXT)) != NULL && (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) != NULL) { size_t len = strlen(reinterpret_cast<char *>(pp)); if (len > 0 && display_.char_set != CHARSET_EBCDIC) // Bugs in other apps (eg Hedit) might cause len == 0 { // TEXT DATA SAVED AS ASCII FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + len > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != len) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // OK make the change if (display_.overtype || end_addr-start_addr == len) GetDocument()->Change(mod_replace, start_addr, len, pp, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, len, pp, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, len, pp, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr+len)); SetSel(addr2pos(start_addr+len, row), addr2pos(start_addr+len, row)); DisplayCaret(); } else if (len > 0) { // TEXT DATA SAVED AS EBCDIC // Copy from clipboard to temp buffer converting to EBCDIC unsigned char *buf = new unsigned char[len]; size_t newlen = 0; for (size_t ii = 0; ii < len; ++ii) if (a2e_tab[pp[ii]] != '\0') buf[newlen++] = a2e_tab[pp[ii]]; if (newlen > 0) { // Insert the EBCDIC characters FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + newlen > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != newlen) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // OK make the change if (display_.overtype || end_addr-start_addr == newlen) GetDocument()->Change(mod_replace, start_addr, newlen, buf, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, newlen, buf, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, newlen, buf, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr+newlen)); SetSel(addr2pos(start_addr+newlen, row), addr2pos(start_addr+newlen, row)); DisplayCaret(); } else { AfxMessageBox("No valid EBCDIC characters to paste"); aa->mac_error_ = 2; } delete[] buf; } else { AfxMessageBox("Text on clipboard is not valid ASCII text!"); aa->mac_error_ = 10; // Invalid text on clipboard? } } else { // Paste when nothing to paste, presumably in macro AfxMessageBox("There is nothing on the clipboard to paste"); aa->mac_error_ = 10; } CHECK_SECURITY(49); ::CloseClipboard(); // This actually records even when there were some errors & probably shouldn't show_prop(); // New char - check props show_calc(); show_pos(); // Update tool bar aa->SaveToMacro(km_paste); } void CHexEditView::OnPasteAscii() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Can't insert text if view is read only or in overtype mode if (check_ro("paste (ASCII)")) return; num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing HANDLE hh; // Handle to clipboard memory unsigned char *pp; // Pointer to actual data if (!OpenClipboard()) { ASSERT(0); AfxMessageBox("The clipboard is in use!"); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) if ((hh = ::GetClipboardData(CF_TEXT)) != NULL && (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) != NULL) { size_t len = strlen(reinterpret_cast<char *>(pp)); if (len > 0) // Bugs in other apps (eg Hedit) might cause len == 0 { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + len > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != len) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // OK make the change if (display_.overtype || end_addr-start_addr == len) GetDocument()->Change(mod_replace, start_addr, len, pp, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, len, pp, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, len, pp, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr+len)); SetSel(addr2pos(start_addr+len, row), addr2pos(start_addr+len, row)); DisplayCaret(); } else aa->mac_error_ = 20; } else { // Paste when nothing to paste, presumably in macro AfxMessageBox("There is nothing on the clipboard to paste"); aa->mac_error_ = 10; } ::CloseClipboard(); // This actually records even when there were some errors & probably shouldn't aa->SaveToMacro(km_paste_ascii); } void CHexEditView::OnPasteEbcdic() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Can't insert text if view is read only or in overtype mode if (check_ro("paste (EBCDIC)")) return; num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing HANDLE hh; // Handle to clipboard memory unsigned char *pp; // Pointer to actual data if (!OpenClipboard()) { ASSERT(0); AfxMessageBox("The clipboard is in use!"); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) if ((hh = ::GetClipboardData(CF_TEXT)) != NULL && (pp = reinterpret_cast<unsigned char *>(::GlobalLock(hh))) != NULL) { size_t len = strlen(reinterpret_cast<char *>(pp)); if (len > 0) // Bugs in other apps (eg Hedit) might cause len == 0 { // Copy from clipboard to temp buffer converting to EBCDIC unsigned char *buf = new unsigned char[len]; size_t newlen = 0; for (size_t ii = 0; ii < len; ++ii) if (pp[ii] < 128 && a2e_tab[pp[ii]] != '\0') buf[newlen++] = a2e_tab[pp[ii]]; if (newlen > 0) { // Insert the EBCDIC characters FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + newlen > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != newlen) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // OK make the change if (display_.overtype || end_addr-start_addr == newlen) GetDocument()->Change(mod_replace, start_addr, newlen, buf, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, newlen, buf, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, newlen, buf, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr+newlen)); SetSel(addr2pos(start_addr+newlen, row), addr2pos(start_addr+newlen, row)); DisplayCaret(); } delete[] buf; } else aa->mac_error_ = 20; } else { // Paste when nothing to paste, presumably in macro AfxMessageBox("There is nothing on the clipboard to paste"); aa->mac_error_ = 10; } ::CloseClipboard(); aa->SaveToMacro(km_paste_ebcdic); // Don't record if error (mac_error_ > 3)??? } // Update handler that turns on user interface options (Paste etc) if there is // text on the clipboard -- ie. there is text that can be pasted into the document void CHexEditView::OnUpdateTextPaste(CCmdUI* pCmdUI) { BOOL bEnable = !GetDocument()->read_only() && ::IsClipboardFormatAvailable(CF_TEXT); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (bEnable ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(bEnable); // if (GetDocument()->read_only()) // pCmdUI->Enable(FALSE); // Disallow paste if file is read only // else // pCmdUI->Enable(::IsClipboardFormatAvailable(CF_TEXT)); } void CHexEditView::OnPasteUnicode() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Can't insert text if view is read only or in overtype mode if (check_ro("paste (Unicode)")) return; num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing HANDLE hh; // Handle to clipboard memory wchar_t *pp; // Pointer to actual data if (!OpenClipboard()) { ASSERT(0); AfxMessageBox("The clipboard is in use!"); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) if ((hh = ::GetClipboardData(CF_UNICODETEXT)) != NULL && (pp = reinterpret_cast<wchar_t *>(::GlobalLock(hh))) != NULL) { size_t len = wcslen(reinterpret_cast<wchar_t *>(pp)); if (len > 0) // Bugs in other apps (eg Hedit) might cause len == 0 { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // FILE_ADDRESS addr = GetPos(); if (display_.overtype && start_addr + 2*len > GetDocument()->length()) { if (AfxMessageBox("The paste operation extends past EOF\n" "which is illegal in overtype mode.\n" "Do you want to turn on insert mode?", MB_OKCANCEL) != IDOK) { ::CloseClipboard(); aa->mac_error_ = 10; return; } else if (!do_insert()) return; } else if (display_.overtype && end_addr-start_addr != 2*len) { switch (AfxMessageBox("Pasting in overtype mode will overwrite data!\r" "Do you want to turn on insert mode?", MB_YESNOCANCEL)) { case IDYES: if (!do_insert()) return; break; case IDNO: break; /* do nothing */ default: aa->mac_error_ = 5; return; } } // OK make the change if (display_.overtype || end_addr-start_addr == 2*len) GetDocument()->Change(mod_replace, start_addr, 2*len, (unsigned char *)pp, 0, this); else if (start_addr == end_addr) GetDocument()->Change(mod_insert, start_addr, 2*len, (unsigned char *)pp, 0, this); else { GetDocument()->Change(mod_delforw, start_addr, end_addr-start_addr, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, 2*len, (unsigned char *)pp, 0, this, TRUE); } // SetSel(addr2pos(start_addr), addr2pos(start_addr + 2*len)); SetSel(addr2pos(start_addr + 2*len, row), addr2pos(start_addr + 2*len, row)); DisplayCaret(); } else aa->mac_error_ = 20; } else { // Paste when nothing to paste, presumably in macro AfxMessageBox("There is nothing on the clipboard to paste"); aa->mac_error_ = 10; } ::CloseClipboard(); // This actually records even when there were some errors & probably shouldn't aa->SaveToMacro(km_paste_unicode); } void CHexEditView::OnUpdateUnicodePaste(CCmdUI* pCmdUI) { BOOL bEnable = !GetDocument()->read_only() && ::IsClipboardFormatAvailable(CF_UNICODETEXT); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (bEnable ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(bEnable); // if (GetDocument()->read_only()) // pCmdUI->Enable(FALSE); // else // pCmdUI->Enable(::IsClipboardFormatAvailable(CF_UNICODETEXT)); } // Reset all options to the current defaults void CHexEditView::OnDisplayReset() { // Change search type in find modeless dlg if open CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (theApp.open_display_.char_set != display_.char_set) { // Character set is to be changed - so update find dlg to match if (theApp.open_display_.char_set == CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_EBCDIC); else mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); } begin_change(); // Change font undo_.push_back(view_undo(undo_font)); if (display_.FontRequired() == FONT_OEM) { undo_.back().plf = new LOGFONT; *(undo_.back().plf) = oem_lf_; if (theApp.open_oem_plf_ != NULL) oem_lf_ = *theApp.open_oem_plf_; else { memset((void *)&oem_lf_, '\0', sizeof(oem_lf_)); _tcscpy(oem_lf_.lfFaceName, _T("Terminal")); // The only certain OEM font? oem_lf_.lfHeight = 18; oem_lf_.lfCharSet = OEM_CHARSET; // Only allow OEM/IBM character set fonts } } else { undo_.back().plf = new LOGFONT; *(undo_.back().plf) = lf_; if (theApp.open_plf_ != NULL) lf_ = *theApp.open_plf_; else { memset((void *)&lf_, '\0', sizeof(lf_)); _tcscpy(lf_.lfFaceName, _T("Courier")); // A nice fixed (no-proportional) font lf_.lfHeight = 16; lf_.lfCharSet = ANSI_CHARSET; // Only allow ANSI character set fonts } } // Change autofit undo_.push_back(view_undo(undo_autofit, TRUE)); if (!display_.autofit) undo_.back().rowsize = rowsize_; else undo_.back().rowsize = 0; // Note: we don't use disp_state_ = theApp.disp_state_ as this loses edit_char and mark_char settings display_.hex_area = theApp.open_display_.hex_area; display_.char_area = theApp.open_display_.char_area; display_.char_set = theApp.open_display_.char_set; display_.control = theApp.open_display_.control; display_.autofit = theApp.open_display_.autofit; display_.dec_addr = theApp.open_display_.dec_addr; // remove now or later? display_.decimal_addr = theApp.open_display_.decimal_addr; display_.hex_addr = theApp.open_display_.hex_area; display_.line_nums = theApp.open_display_.line_nums; display_.addrbase1 = theApp.open_display_.addrbase1; // addresses start at 1 (not 0) display_.readonly = theApp.open_display_.readonly; display_.overtype = theApp.open_display_.overtype; display_.vert_display = theApp.open_display_.vert_display; display_.borders = theApp.open_display_.borders; if (GetDocument()->IsDevice()) { display_.overtype = 1; // INS not allowed display_.borders = 1; // Always display borders for devices by default } // Make sure that caret and mark are not in hidden area ASSERT(display_.char_area || display_.hex_area); if (!display_.hex_area) { display_.edit_char = TRUE; display_.mark_char = TRUE; } else if (!display_.char_area) { display_.edit_char = FALSE; display_.mark_char = FALSE; } make_change(TRUE); if (rowsize_ != theApp.open_rowsize_) { undo_.push_back(view_undo(undo_rowsize, TRUE)); undo_.back().rowsize = rowsize_; // Save previous rowsize for undo rowsize_ = theApp.open_rowsize_; } if (real_offset_ != theApp.open_offset_) { undo_.push_back(view_undo(undo_offset, TRUE)); undo_.back().rowsize = real_offset_; // Save previous offset for undo real_offset_ = offset_ = theApp.open_offset_; if (real_offset_ >= rowsize_) offset_ = rowsize_ - 1; } undo_.push_back(view_undo(undo_group_by, TRUE)); undo_.back().rowsize = group_by_; // Save previous group_by for undo group_by_ = theApp.open_group_by_; undo_.push_back(view_undo(undo_scheme, TRUE)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = scheme_name_; scheme_name_ = ""; // Force scheme reset set_colours(); end_change(); theApp.SaveToMacro(km_display_reset, unsigned __int64(0)); // Store zero to allow for future additions } void CHexEditView::OnEditUndo() { CWaitCursor wait; // Turn on wait cursor (hourglass) // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing BOOL more = TRUE; while (more) { ASSERT(undo_.size() > 0 || theApp.playing_); more = undo_.back().previous_too; if (!do_undo()) { theApp.mac_error_ = 10; return; } } theApp.SaveToMacro(km_undo); } void CHexEditView::OnUpdateEditUndo(CCmdUI* pCmdUI) { pCmdUI->Enable(undo_.size() > 0); } void CHexEditView::OnUndoChanges() { CWaitCursor wait; // Turn on wait cursor (hourglass) num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing BOOL more; BOOL last_change = is_last_change(); do { ASSERT(undo_.size() > 0 || theApp.playing_); more = undo_.back().previous_too; if (!do_undo()) { theApp.mac_error_ = 10; return; } } while (undo_.size() > 0 && (more || !(last_change || is_last_change()))); // } while ((more || (last_change == is_last_change() && undo_.size() > 0)); theApp.SaveToMacro(km_undo_changes); } // Check if the top "operation" on the undo stack is a file change. Note that an operation // consists of all elts on the stack back until one without the previous_too flag set. BOOL CHexEditView::is_last_change() { #ifdef _DEBUG { // Why can't the debugger look into STL containers? int undo_size = undo_.size(); for (std::vector<view_undo>::reverse_iterator rr = undo_.rbegin(); rr != undo_.rend(); ++rr) { view_undo undo_elt = *rr; } } #endif // Check if the last thing on undo stack is a change for (std::vector<view_undo>::reverse_iterator pp = undo_.rbegin(); pp != undo_.rend(); ++pp) { if (pp->utype == undo_change) return TRUE; // Top undo op is a change if (!pp->previous_too) break; // End of top undo operation } return FALSE; } void CHexEditView::OnUpdateUndoChanges(CCmdUI* pCmdUI) { BOOL change_present = FALSE; // Check if the last thing on undo stack is a change for (std::vector<view_undo>::iterator pp = undo_.begin(); pp != undo_.end(); ++pp) { if (pp->utype == undo_change) { change_present = TRUE; // There is a change break; } } pCmdUI->Enable(change_present); } BOOL CHexEditView::do_undo() { // The string 'mess' is used to display a message in the status // bar if it is not obvious what has been undone. CString mess, tmp; CMainFrame *mm = dynamic_cast<CMainFrame *>(AfxGetMainWnd()); BOOL caret_displayed = CaretDisplayed(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); CHECK_SECURITY(191); if (undo_.size() == 0) { // This can only (presumably) happen during a macro AfxMessageBox("There is nothing to undo"); return FALSE; } switch (undo_.back().utype) { case undo_move: GoAddress(undo_.back().address); show_prop(); show_calc(); show_pos(); DisplayCaret(); // Make sure move visible break; case undo_sel: end_addr = undo_.back().address; // Now go back to previous undo (which should be undo_move) undo_.pop_back(); ASSERT(undo_.size() > 0); ASSERT(undo_.back().utype == undo_move); GoAddress(undo_.back().address, end_addr); show_prop(); show_calc(); show_pos(); DisplayCaret(); // Make sure move visible break; case undo_change: #if 0 if (display_.readonly) { if (AfxMessageBox("You can't undo changes while the window is read only.\r" "Do you want to turn off read only mode?", MB_OKCANCEL) == IDCANCEL) return FALSE; else allow_mods(); } #endif // Note: flag == TRUE if this view originally made the change. if (!undo_.back().flag) mess += "Undo: changes made in different window undone "; #ifndef NDEBUG if (!GetDocument()->Undo(this, undo_.back().index, undo_.back().flag)) return FALSE; #else if (!GetDocument()->Undo(this, 0, undo_.back().flag)) return FALSE; #endif break; case undo_state: disp_state_ = undo_.back().disp_state; redo_font(); recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display DoInvalidate(); { // Make sure calculator big-endian checkbox is correct CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!theApp.refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); } break; case undo_overtype: ASSERT(!GetDocument()->IsDevice()); display_.overtype = undo_.back().flag; if (GetDocument()->length() == 0) DoInvalidate(); if (display_.overtype) mess += "Undo: overtype now ON "; else mess += "Undo: overtype now OFF "; break; case undo_readonly: display_.readonly = undo_.back().flag; if (display_.readonly) mess += "Undo: read only now ON "; else mess += "Undo: read only now OFF "; break; case undo_font: if (display_.FontRequired() == FONT_OEM) oem_lf_ = *(undo_.back().plf); else lf_ = *(undo_.back().plf); if (pcv_ != NULL) pcv_->begin_change(); redo_font(); // Calculate new position based on new font size recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); mess += "Undo: font restored "; break; case undo_scheme: tmp = scheme_name_; scheme_name_ = *(undo_.back()).pscheme_name; if (set_colours()) DoInvalidate(); else { scheme_name_ = tmp; if (::IsUs()) AfxMessageBox("Previous color scheme not found.\n" "The operation could not be undone."); else AfxMessageBox("Previous colour scheme not found.\n" "The operation could not be undone."); } break; case undo_rowsize: { FILE_ADDRESS scroll_addr = pos2addr(GetScroll()); if (pcv_ != NULL) pcv_->begin_change(); rowsize_ = undo_.back().rowsize; offset_ = real_offset_; if (offset_ >= rowsize_) offset_ = rowsize_ - 1; recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); // Fix scroll place so it's about the same even though the row length has changed CPointAp pt = addr2pos(scroll_addr); pt.x = 0; SetScroll(pt); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); } break; case undo_group_by: if (pcv_ != NULL) pcv_->begin_change(); group_by_ = undo_.back().rowsize; recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); break; case undo_offset: if (pcv_ != NULL) pcv_->begin_change(); real_offset_ = offset_ = undo_.back().rowsize; if (real_offset_ >= rowsize_) offset_ = rowsize_ - 1; recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); break; case undo_autofit: { FILE_ADDRESS scroll_addr = pos2addr(GetScroll()); if (pcv_ != NULL) pcv_->begin_change(); // If rowsize has been specified then autofit is now off (undo turn on) display_.autofit = undo_.back().rowsize == 0; if (!display_.autofit) { mess += "Undo: auto fit now OFF "; rowsize_ = undo_.back().rowsize; offset_ = real_offset_; if (offset_ >= rowsize_) offset_ = rowsize_ - 1; } recalc_display(); // Fix scroll place so it's about the same even though the row length has changed CPointAp pt = addr2pos(scroll_addr); pt.x = 0; SetScroll(pt); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); } break; case undo_setmark: invalidate_addr_range(mark_, mark_ + 1); mark_ = undo_.back().address; if (theApp.align_rel_ && mark_ != GetDocument()->base_addr_) { GetDocument()->StopSearch(); GetDocument()->base_addr_ = GetSearchBase(); GetDocument()->StartSearch(); } invalidate_addr_range(mark_, mark_ + 1); show_calc(); // Status of some buttons may have changed when mark_ moves break; case undo_highlight: hl_set_ = *(undo_.back().phl); DoInvalidate(); break; case undo_unknown: default: ASSERT(0); mess += " Unknown undo! "; } undo_.pop_back(); mm->StatusBarText(mess); return TRUE; } void CHexEditView::OnAddrToggle() { begin_change(); display_.decimal_addr = display_.hex_addr; // Display decimal addr if currently displaying hex or both display_.hex_addr = !display_.decimal_addr; make_change(); end_change(); theApp.SaveToMacro(km_addr); } void CHexEditView::OnUpdateAddrToggle(CCmdUI* pCmdUI) { pCmdUI->SetCheck(!display_.hex_addr); } void CHexEditView::OnGraphicToggle() { if (!display_.char_area || display_.char_set == CHARSET_EBCDIC) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Can't toggle graphic chars, presumably in macro playback ASSERT(aa->playing_); if (!display_.char_area) AfxMessageBox("You can't display graphic characters without the char area"); else AfxMessageBox("Graphic characters are not supported for EBCDIC"); aa->mac_error_ = 2; return; } begin_change(); if (display_.char_set == CHARSET_ASCII) display_.char_set = CHARSET_ANSI; else display_.char_set = CHARSET_ASCII; make_change(); end_change(); CHECK_SECURITY(22); theApp.SaveToMacro(km_graphic); } void CHexEditView::OnUpdateGraphicToggle(CCmdUI* pCmdUI) { pCmdUI->Enable(display_.char_area && display_.char_set != CHARSET_EBCDIC); pCmdUI->SetCheck(display_.char_set == CHARSET_ANSI || display_.char_set == CHARSET_OEM); } void CHexEditView::OnCharToggle() { do_chartoggle(); } void CHexEditView::do_chartoggle(int state /*=-1*/) { if (display_.vert_display) { AfxMessageBox("You can't toggle char area in stacked mode"); theApp.mac_error_ = 2; return; } CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); begin_change(); // Change state of char area flag if (state == -1) display_.char_area = !display_.char_area; else if (state != display_.char_area) display_.char_area = state; // Make sure things are kept consistent if (!display_.char_area && display_.edit_char) { display_.edit_char = FALSE; SetHorzBufferZone(2); // Allow more room in hex area } if (!display_.char_area && !display_.hex_area) { display_.hex_area = TRUE; } make_change(); end_change(); aa->SaveToMacro(km_char_area, state); } void CHexEditView::OnUpdateCharToggle(CCmdUI* pCmdUI) { pCmdUI->Enable(!display_.vert_display); pCmdUI->SetCheck(display_.char_area); } void CHexEditView::do_hextoggle(int state /*=-1*/) { if (display_.vert_display) { AfxMessageBox("You can't toggle hex area in stacked mode"); theApp.mac_error_ = 2; return; } begin_change(); if (state == -1) display_.hex_area = !display_.hex_area; else if (state != display_.hex_area) display_.hex_area = state; // Save previous value of display hex for undo and also swap edit area if nec. if (!display_.hex_area && !display_.edit_char) { display_.edit_char = TRUE; SetHorzBufferZone(1); } if (!display_.hex_area && !display_.char_area) { display_.char_area = TRUE; } make_change(); end_change(); theApp.SaveToMacro(km_hex_area, state); } void CHexEditView::OnOemToggle() { if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { // Can't toggle OEM chars, presumably in macro playback ASSERT(theApp.playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display OEM/ANSI graphic characters without the char area"); else if (display_.char_set == CHARSET_EBCDIC) AfxMessageBox("Graphic characters are not supported for EBCDIC"); theApp.mac_error_ = 2; return; } begin_change(); if (display_.char_set == CHARSET_OEM) display_.char_set = CHARSET_ANSI; else display_.char_set = CHARSET_OEM; make_change(); end_change(); theApp.SaveToMacro(km_oem); } void CHexEditView::OnUpdateOemToggle(CCmdUI* pCmdUI) { pCmdUI->Enable((display_.vert_display || display_.char_area) && display_.char_set != CHARSET_EBCDIC); pCmdUI->SetCheck(display_.char_set == CHARSET_OEM); } void CHexEditView::OnFontInc() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing if (pcv_ != NULL) pcv_->begin_change(); // Save font for undo LOGFONT *plf = new LOGFONT; *plf = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; for ( ; ; ) { // Increase font size by one pixel CPoint convert(plf->lfWidth, plf->lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.LPtoDP(&convert); if (convert.y < max_font_size) ++convert.y; else { ((CMainFrame *)AfxGetMainWnd())-> StatusBarText("Warning: Font size too big - not increased"); aa->mac_error_ = 2; return; } dc.DPtoLP(&convert); plf->lfHeight = convert.y; plf->lfWidth = 0; // Calced from height CFont font; font.CreateFontIndirect(plf); // if (display_.char_area && !display_.ebcdic && display_.graphic && display_.oem) // { // oem_lf_.lfHeight = convert.y; // oem_lf_.lfWidth = 0; // Calced from height // font.CreateFontIndirect(&oem_lf_); // } // else // { // lf_.lfHeight = convert.y; // lf_.lfWidth = 0; // Calced from height // font.CreateFontIndirect(&lf_); // } TEXTMETRIC tm; CFont *tf = dc.SelectObject(&font); dc.GetTextMetrics(&tm); dc.SelectObject(tf); // Deselect font before it is destroyed if (tm.tmHeight + tm.tmExternalLeading > text_height_) { if (display_.FontRequired() == FONT_OEM) oem_lf_.lfHeight = convert.y; else lf_.lfHeight = convert.y; break; } } BOOL caret_displayed = CaretDisplayed(); // FILE_ADDRESS address = pos2addr(GetCaret()); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Create and install the new font redo_font(); // Calculate new position (and new total size) based on change in font size recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); undo_.push_back(view_undo(undo_font)); // Allow undo of font change undo_.back().plf = plf; aa->SaveToMacro(km_inc_font); } void CHexEditView::OnUpdateFontInc(CCmdUI* pCmdUI) { // Create a large (max_font_size) font and see if the current font is // displayed at the same size on screen. If so we can't increase the size LOGFONT logfont; logfont = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; // Get font the same as current ... { CPoint convert(0, max_font_size); // ... but very big CClientDC dc(this); OnPrepareDC(&dc); dc.DPtoLP(&convert); logfont.lfHeight = convert.y; } logfont.lfWidth = 0; // Width calced from height // Create font, put into DC, and see what size it would be on screen CFont font; font.CreateFontIndirect(&logfont); { TEXTMETRIC tm; CClientDC dc(this); OnPrepareDC(&dc); CFont *tf = dc.SelectObject(&font); dc.GetTextMetrics(&tm); dc.SelectObject(tf); if (tm.tmHeight + tm.tmExternalLeading == text_height_) pCmdUI->Enable(FALSE); // Already at smallest displayable font } } void CHexEditView::OnFontDec() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing if (pcv_ != NULL) pcv_->begin_change(); // Save font for undo LOGFONT *plf = new LOGFONT; *plf = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; for ( ; ; ) { // Decrease font size by one pixel CPoint convert(plf->lfWidth, plf->lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.LPtoDP(&convert); if (convert.y > 1) convert.y--; else { ((CMainFrame *)AfxGetMainWnd())-> StatusBarText("Warning: Font size already at minimum - not decreased"); aa->mac_error_ = 2; return; } dc.DPtoLP(&convert); plf->lfHeight = convert.y; plf->lfWidth = 0; // Calced from height CFont font; font.CreateFontIndirect(plf); // if (display_.char_area && !display_.ebcdic && display_.graphic && display_.oem) // { // oem_lf_.lfHeight = convert.y; // oem_lf_.lfWidth = 0; // Calced from height // font.CreateFontIndirect(&oem_lf_); // } // else // { // lf_.lfHeight = convert.y; // lf_.lfWidth = 0; // Calced from height // font.CreateFontIndirect(&lf_); // } TEXTMETRIC tm; CFont *tf = dc.SelectObject(&font); dc.GetTextMetrics(&tm); dc.SelectObject(tf); // Deselect font before it is destroyed if (tm.tmHeight + tm.tmExternalLeading < text_height_) { if (display_.FontRequired() == FONT_OEM) oem_lf_.lfHeight = convert.y; else lf_.lfHeight = convert.y; break; } } BOOL caret_displayed = CaretDisplayed(); // FILE_ADDRESS address = pos2addr(GetCaret()); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Create and install the new font redo_font(); // Calculate new position (and new total size) based on change in font size recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); undo_.push_back(view_undo(undo_font)); // Allow undo of font change undo_.back().plf = plf; aa->SaveToMacro(km_dec_font); } void CHexEditView::OnUpdateFontDec(CCmdUI* pCmdUI) { // If we create a very small font then see what the text height is when that // font is used. If this height is the same as the current text height then the // font size can not be decreased any more. LOGFONT logfont; logfont = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; // Get font the same as current ... { CPoint convert(0, 1); // ... but just one pixel high CClientDC dc(this); OnPrepareDC(&dc); dc.DPtoLP(&convert); logfont.lfHeight = convert.y; } logfont.lfWidth = 0; // Width calced from height // Create font, put into DC, and see what size it would be on screen CFont font; font.CreateFontIndirect(&logfont); { TEXTMETRIC tm; CClientDC dc(this); OnPrepareDC(&dc); CFont *tf = dc.SelectObject(&font); dc.GetTextMetrics(&tm); dc.SelectObject(tf); if (tm.tmHeight + tm.tmExternalLeading == text_height_) pCmdUI->Enable(FALSE); // Already at smallest displayable font } } void CHexEditView::OnFont() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing LOGFONT logfont = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; // Convert font size to units that user can relate to { CPoint convert(logfont.lfWidth, logfont.lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.LPtoDP(&convert); logfont.lfWidth = convert.x; logfont.lfHeight = convert.y; } CFontDialog dlg; dlg.m_cf.lpLogFont = &logfont; dlg.m_cf.Flags |= CF_INITTOLOGFONTSTRUCT | CF_SHOWHELP; dlg.m_cf.Flags &= ~(CF_EFFECTS); // Disable selection of strikethrough, colours etc if (dlg.DoModal() == IDOK) { // Convert font size back to logical units dlg.GetCurrentFont(&logfont); if (logfont.lfHeight < 0) logfont.lfHeight = -logfont.lfHeight; { CPoint convert(logfont.lfWidth, logfont.lfHeight); CClientDC dc(this); OnPrepareDC(&dc); dc.DPtoLP(&convert); logfont.lfWidth = convert.x; logfont.lfHeight = convert.y; } do_font(&logfont); } else { ((CHexEditApp *)AfxGetApp())->mac_error_ = 2; } } void CHexEditView::OnFontName() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHexEditFontCombo* pSrcCombo = (CHexEditFontCombo*)CMFCToolBarComboBoxButton::GetByCmd(IDC_FONTNAME, TRUE); if (pSrcCombo == NULL) { OnFont(); return; } LOGFONT logfont = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; CString str = pSrcCombo->GetText(); if (pSrcCombo->SetFont(str)) { const CMFCFontInfo *pDesc = pSrcCombo->GetFontDesc(); ASSERT_VALID(pDesc); ASSERT(pDesc->m_strName.GetLength() < LF_FACESIZE); strncpy(logfont.lfFaceName, pDesc->m_strName, LF_FACESIZE); logfont.lfCharSet = pDesc->m_nCharSet; logfont.lfPitchAndFamily = pDesc->m_nPitchAndFamily; do_font(&logfont); } } void CHexEditView::OnUpdateFontName(CCmdUI* pCmdUI) { CObList listButtons; static int last_font_required = -1; bool font_list_changed = last_font_required != display_.FontRequired(); if (CMFCToolBar::GetCommandButtons (IDC_FONTNAME, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition (); posCombo != NULL; ) { CHexEditFontCombo * pCombo = DYNAMIC_DOWNCAST(CHexEditFontCombo, listButtons.GetNext (posCombo)); if (pCombo != NULL && !pCombo->HasFocus ()) { if (display_.FontRequired() == FONT_OEM) { if (font_list_changed) pCombo->FixFontList(OEM_CHARSET); CString ss = pCombo->GetText(); if (ss != oem_lf_.lfFaceName) pCombo->SetText(oem_lf_.lfFaceName); } else { if (font_list_changed) pCombo->FixFontList(ANSI_CHARSET); CString ss = pCombo->GetText(); if (ss != lf_.lfFaceName) pCombo->SetText(lf_.lfFaceName); } } } } last_font_required = display_.FontRequired(); // remeber the font set we are now using } void CHexEditView::OnFontSize() { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHexEditFontSizeCombo* pSrcCombo = (CHexEditFontSizeCombo*)CMFCToolBarComboBoxButton::GetByCmd(IDC_FONTSIZE, TRUE); if (pSrcCombo == NULL) { OnFont(); return; } LOGFONT logfont = display_.FontRequired() == FONT_OEM ? oem_lf_ : lf_; int nSize = pSrcCombo->GetTwipSize(); if (nSize == -2 || (nSize >= 0 && nSize < 20) || nSize > 32760) { AfxMessageBox("Invalid font size."); } else if (nSize > 0) { CClientDC dc(this); OnPrepareDC(&dc); logfont.lfHeight = int((nSize * dc.GetDeviceCaps(LOGPIXELSX)) / 1440.0 + 0.5); do_font(&logfont); // Store the exact font size (due to rounding probs do_font (SetFont) calc may be slightly off) fontsize_.Format("%d", nSize/20); } } void CHexEditView::OnUpdateFontSize(CCmdUI* pCmdUI) { CObList listButtons; if (CMFCToolBar::GetCommandButtons (IDC_FONTSIZE, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition (); posCombo != NULL;) { CMFCToolBarFontSizeComboBox * pCombo = DYNAMIC_DOWNCAST(CMFCToolBarFontSizeComboBox, listButtons.GetNext (posCombo)); if (pCombo != NULL && !pCombo->HasFocus ()) { static CString savedFontName; CString fontName; if (display_.FontRequired() == FONT_OEM) fontName = oem_lf_.lfFaceName; else fontName = lf_.lfFaceName; if (!fontName.IsEmpty() && (pCombo->GetCount() == 0 || fontName != savedFontName)) { savedFontName = fontName; pCombo->RebuildFontSizes(fontName); } int nSize = atoi(fontsize_)*20; if (nSize == -2 || (nSize >= 0 && nSize < 20) || nSize > 32760) nSize = 20*12; pCombo->SetTwipSize(nSize); // Store the exact font size (due to rounding probs do_font (SetFont) calc may be slightly off) fontsize_.Format("%d", nSize/20); CString ss = pCombo->GetText(); if (ss != fontsize_) pCombo->SetText(fontsize_); } } } } void CHexEditView::do_font(LOGFONT *plf) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (pcv_ != NULL) pcv_->begin_change(); // Save current LOGFONT for undo LOGFONT *prev_lf = new LOGFONT; if (display_.FontRequired() == FONT_OEM) { // We can't switch to an ANSI char set because we are displaying OEM graphics if (plf->lfCharSet == ANSI_CHARSET) { mm->StatusBarText("Can't switch to ANSI font when displaying IBM/OEM graphics chars"); aa->mac_error_ = 2; return; } *prev_lf = oem_lf_; oem_lf_ = *plf; } else { // We can't switch to an OEM char set if (plf->lfCharSet == OEM_CHARSET) { mm->StatusBarText("Can't switch to this font unless displaying IBM/OEM graphics chars"); aa->mac_error_ = 2; return; } *prev_lf = lf_; lf_ = *plf; } // Set new LOGFONT BOOL caret_displayed = CaretDisplayed(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); CHECK_SECURITY(9); // Create and install the new font redo_font(); // Calculate new position (and new total size) based on change in font size recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); undo_.push_back(view_undo(undo_font)); // Allow undo of font change undo_.back().plf = prev_lf; ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_font, display_.FontRequired() == FONT_OEM ? &oem_lf_ : &lf_); } void CHexEditView::change_rowsize(int rowsize) { if (rowsize != rowsize_) { if (pcv_ != NULL) pcv_->begin_change(); FILE_ADDRESS scroll_addr = pos2addr(GetScroll()); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); undo_.push_back(view_undo(undo_rowsize)); undo_.back().rowsize = rowsize_; // Save previous rowsize for undo rowsize_ = rowsize; recalc_display(); // Fix scroll place so it's about the same even though the row length has changed CPointAp pt = addr2pos(scroll_addr); pt.x = 0; SetScroll(pt); // Fix selection if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_rowsize, rowsize); } void CHexEditView::change_group_by(int group_by) { if (group_by != group_by_) { if (pcv_ != NULL) pcv_->begin_change(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); undo_.push_back(view_undo(undo_group_by)); undo_.back().rowsize = group_by_; // Save previous group_by for undo group_by_ = group_by; recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_group_by, group_by); } void CHexEditView::change_offset(int offset) { if (offset != real_offset_) { if (pcv_ != NULL) pcv_->begin_change(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); undo_.push_back(view_undo(undo_offset)); undo_.back().rowsize = real_offset_; // Save previous offset for undo real_offset_ = offset_ = offset; recalc_display(); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_offset, offset); } void CHexEditView::OnAutoFit() { do_autofit(); } // Change autofit mode to state (0 or 1). If state is -1 then toggle autofit. void CHexEditView::do_autofit(int state /*=-1*/) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (pcv_ != NULL) pcv_->begin_change(); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing BOOL caret_displayed = CaretDisplayed(); FILE_ADDRESS scroll_addr = pos2addr(GetScroll()); // FILE_ADDRESS address = pos2addr(GetCaret()); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); if (state == -1) display_.autofit = !display_.autofit; else if ((BOOL)state == display_.autofit) return; // No change - do nothing else display_.autofit = (BOOL)state; undo_.push_back(view_undo(undo_autofit)); if (display_.autofit) undo_.back().rowsize = rowsize_; else undo_.back().rowsize = 0; if (!display_.autofit && real_offset_ != offset_) { // If autofit turned off but offset has been squeezed then save so it's undone undo_.push_back(view_undo(undo_offset, TRUE)); undo_.back().rowsize = real_offset_; // Save previous offset for undo } recalc_display(); // Fix scroll place so it's about the same even though the row length has changed CPointAp pt = addr2pos(scroll_addr); pt.x = 0; SetScroll(pt); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (caret_displayed) DisplayCaret(); // Keep caret within display if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); aa->SaveToMacro(km_autofit, state); CHECK_SECURITY(19); } void CHexEditView::OnUpdateAutofit(CCmdUI* pCmdUI) { pCmdUI->SetCheck(display_.autofit); } void CHexEditView::OnColumnDec() { if (rowsize_ > 4) { if (pcv_ != NULL) pcv_->begin_change(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Try to stay at the same place when multiple column adjustments are made if (resize_start_addr_ == -1 || resize_curr_scroll_ != GetScroll().y) resize_start_addr_ = pos2addr(GetScroll()); undo_.push_back(view_undo(undo_rowsize)); undo_.back().rowsize = rowsize_; // Save previous rowsize for undo rowsize_ = rowsize_ - 1; recalc_display(); // Adjust scroll so that about the same row is visible CPointAp pt = addr2pos(resize_start_addr_); pt.x = 0; SetScroll(pt); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); resize_curr_scroll_ = GetScroll().y; // Save current pos so we can check if we are at the same place later } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_rowsize, -1); } void CHexEditView::OnUpdateColumnDec(CCmdUI* pCmdUI) { pCmdUI->Enable(!display_.autofit && rowsize_ > 4); } void CHexEditView::OnColumnInc() { if (rowsize_ < max_buf) { if (pcv_ != NULL) pcv_->begin_change(); FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // Try to stay at the same place when multiple column adjustments are made if (resize_start_addr_ == -1 || resize_curr_scroll_ != GetScroll().y) resize_start_addr_ = pos2addr(GetScroll()); undo_.push_back(view_undo(undo_rowsize)); undo_.back().rowsize = rowsize_; // Save previous rowsize for undo rowsize_ = rowsize_ + 1; recalc_display(); // Adjust scroll so that about the same row is visible CPointAp pt = addr2pos(resize_start_addr_); pt.x = 0; SetScroll(pt); if (end_base) SetSel(addr2pos(end_addr, row), addr2pos(start_addr, row), true); else SetSel(addr2pos(start_addr, row), addr2pos(end_addr, row)); if (pcv_ != NULL) pcv_->end_change(); DoInvalidate(); resize_curr_scroll_ = GetScroll().y; // Save current pos so we can check if we are at the same place later } ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_rowsize, -2); } void CHexEditView::OnUpdateColumnInc(CCmdUI* pCmdUI) { pCmdUI->Enable(!display_.autofit && rowsize_ < max_buf); } void CHexEditView::redo_font() { CFont *tf = pfont_; pfont_ = new CFont; pfont_->CreateFontIndirect(display_.FontRequired() == FONT_OEM ? &oem_lf_ : &lf_); SetFont(pfont_); if (pcv_ != NULL) pcv_->SetFont(pfont_); if (tf != NULL) delete tf; // Delete old font after it's deselected } void CHexEditView::begin_change() { ASSERT(previous_state_ == 0); previous_caret_displayed_ = CaretDisplayed(); previous_end_base_ = GetSelAddr(previous_start_addr_, previous_end_addr_); previous_row_ = 0; if (previous_start_addr_ == previous_end_addr_ && display_.vert_display) previous_row_ = pos2row(GetCaret()); num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHECK_SECURITY(21); previous_state_ = disp_state_; if (pcv_ != NULL) pcv_->begin_change(); } // Return ptoo or TRUE if it added to the undo stack BOOL CHexEditView::make_change(BOOL ptoo /*=FALSE*/) { if (previous_state_ != disp_state_) { if (theApp.intelligent_undo_ && // intelligent undo is turned on undo_.size() > 0 && // there is an undo op on the stack undo_.back().utype == undo_state && // previous op was a state change !undo_.back().previous_too && // and not part of another operation undo_.back().disp_state == disp_state_) // and same state { ASSERT(!ptoo); // if part of larger op then previous utype should not have been undo_state undo_.pop_back(); } else { undo_.push_back(view_undo(undo_state, ptoo)); undo_.back().disp_state = previous_state_; ptoo = TRUE; } } return ptoo; } void CHexEditView::end_change() { redo_font(); recalc_display(); if (!display_.vert_display) previous_row_ = 0; // If vert mode turned off make sure row is zero if (previous_end_base_) SetSel(addr2pos(previous_end_addr_, previous_row_), addr2pos(previous_start_addr_, previous_row_), true); else SetSel(addr2pos(previous_start_addr_, previous_row_), addr2pos(previous_end_addr_, previous_row_)); if (previous_caret_displayed_) DisplayCaret(); // Keep caret within display DoInvalidate(); if (pcv_ != NULL) pcv_->end_change(); // Make sure calculator big-endian checkbox is correct CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!theApp.refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); previous_state_ = 0; // Used to make sure begin_change/end_change are in pairs } void CHexEditView::OnDisplayHex() { // Change the current state (storing previous state in undo vector if changed) begin_change(); display_.hex_area = TRUE; display_.char_area = FALSE; display_.edit_char = FALSE; display_.vert_display = FALSE; SetHorzBufferZone(2); make_change(); end_change(); theApp.SaveToMacro(km_area, 1); } void CHexEditView::OnUpdateDisplayHex(CCmdUI *pCmdUI) { pCmdUI->SetCheck(!display_.vert_display && display_.hex_area && !display_.char_area); } void CHexEditView::OnDisplayChar() { // Change the current state (storing previous state in undo vector if changed) begin_change(); display_.hex_area = FALSE; display_.char_area = TRUE; display_.edit_char = TRUE; display_.vert_display = FALSE; SetHorzBufferZone(1); make_change(); end_change(); theApp.SaveToMacro(km_area, 2); } void CHexEditView::OnUpdateDisplayChar(CCmdUI *pCmdUI) { pCmdUI->SetCheck(!display_.vert_display && !display_.hex_area && display_.char_area); } void CHexEditView::OnDisplayBoth() { // Change the current state (storing previous state in undo vector if changed) begin_change(); CHECK_SECURITY(50); display_.hex_area = TRUE; display_.char_area = TRUE; display_.vert_display = FALSE; if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); make_change(); end_change(); theApp.SaveToMacro(km_area, 3); } void CHexEditView::OnUpdateDisplayBoth(CCmdUI *pCmdUI) { pCmdUI->SetCheck(!display_.vert_display && display_.hex_area && display_.char_area); } void CHexEditView::OnDisplayStacked() { // Change the current state (storing previous state in undo vector if changed) begin_change(); display_.vert_display = TRUE; if (GetVertBufferZone() < 2) SetVertBufferZone(2); // Make sure we can always see the other 2 rows at the same address SetHorzBufferZone(1); make_change(); end_change(); CHECK_SECURITY(30); theApp.SaveToMacro(km_area, 4); } void CHexEditView::OnUpdateDisplayStacked(CCmdUI *pCmdUI) { pCmdUI->SetCheck(display_.vert_display); } void CHexEditView::OnCharsetAscii() { bool std_scheme = false; if (!(display_.vert_display || display_.char_area)) { ASSERT(theApp.playing_); AfxMessageBox("You can't change characters sets without the char area"); theApp.mac_error_ = 2; return; } // Change search type in find modeless dlg CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (display_.char_set == CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); if (scheme_name_ == ANSI_NAME && display_.char_set == CHARSET_ANSI || scheme_name_ == OEM_NAME && display_.char_set == CHARSET_OEM || scheme_name_ == EBCDIC_NAME && display_.char_set == CHARSET_EBCDIC ) { std_scheme = true; } begin_change(); display_.char_set = CHARSET_ASCII; BOOL ptoo = make_change(); if (std_scheme) { undo_.push_back(view_undo(undo_scheme, ptoo)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = scheme_name_; scheme_name_ = ASCII_NAME; set_colours(); } end_change(); CHECK_SECURITY(51); theApp.SaveToMacro(km_charset, unsigned __int64(0)); } void CHexEditView::OnUpdateCharsetAscii(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area)); pCmdUI->SetCheck(display_.char_set == CHARSET_ASCII); } } void CHexEditView::OnCharsetAnsi() { bool std_scheme = false; if (!(display_.vert_display || display_.char_area)) { ASSERT(theApp.playing_); AfxMessageBox("You can't change characters sets without the char area"); theApp.mac_error_ = 2; return; } // Change search type in find modeless dlg CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); ASSERT(mm != NULL); if (display_.char_set == CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); if (scheme_name_ == ASCII_NAME && display_.char_set == CHARSET_ASCII || scheme_name_ == OEM_NAME && display_.char_set == CHARSET_OEM || scheme_name_ == EBCDIC_NAME && display_.char_set == CHARSET_EBCDIC) { std_scheme = true; } begin_change(); display_.char_set = CHARSET_ANSI; BOOL ptoo = make_change(); if (std_scheme) { undo_.push_back(view_undo(undo_scheme, ptoo)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = scheme_name_; scheme_name_ = ANSI_NAME; set_colours(); } end_change(); theApp.SaveToMacro(km_charset, 1); } void CHexEditView::OnUpdateCharsetAnsi(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area)); pCmdUI->SetCheck(display_.char_set == CHARSET_ANSI); } } void CHexEditView::OnCharsetOem() { bool std_scheme = false; if (!(display_.vert_display || display_.char_area)) { ASSERT(theApp.playing_); AfxMessageBox("You can't change characters sets without the char area"); theApp.mac_error_ = 2; return; } // Change search type in find modeless dlg CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); ASSERT(mm != NULL); if (display_.char_set == CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); if (scheme_name_ == ASCII_NAME && display_.char_set == CHARSET_ASCII || scheme_name_ == ANSI_NAME && display_.char_set == CHARSET_ANSI || scheme_name_ == EBCDIC_NAME && display_.char_set == CHARSET_EBCDIC) { std_scheme = true; } begin_change(); display_.char_set = CHARSET_OEM; BOOL ptoo = make_change(); if (std_scheme) { undo_.push_back(view_undo(undo_scheme, ptoo)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = scheme_name_; scheme_name_ = OEM_NAME; set_colours(); } end_change(); theApp.SaveToMacro(km_charset, 2); } void CHexEditView::OnUpdateCharsetOem(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area)); pCmdUI->SetCheck(display_.char_set == CHARSET_OEM); } } void CHexEditView::OnCharsetEbcdic() { bool std_scheme = false; if (!(display_.vert_display || display_.char_area)) { ASSERT(theApp.playing_); AfxMessageBox("You can't change characters sets without the char area"); theApp.mac_error_ = 2; return; } // Change search type in find modeless dlg CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); ASSERT(mm != NULL); if (display_.char_set != CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_EBCDIC); if (scheme_name_ == ASCII_NAME && display_.char_set == CHARSET_ASCII || scheme_name_ == ANSI_NAME && display_.char_set == CHARSET_ANSI || scheme_name_ == OEM_NAME && display_.char_set == CHARSET_OEM ) { std_scheme = true; } begin_change(); display_.char_set = CHARSET_EBCDIC; BOOL ptoo = make_change(); if (std_scheme) { undo_.push_back(view_undo(undo_scheme, ptoo)); // Allow undo of scheme change undo_.back().pscheme_name = new CString; *undo_.back().pscheme_name = scheme_name_; scheme_name_ = EBCDIC_NAME; set_colours(); } end_change(); theApp.SaveToMacro(km_charset, 3); } void CHexEditView::OnUpdateCharsetEbcdic(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area)); pCmdUI->SetCheck(display_.char_set == CHARSET_EBCDIC); } } void CHexEditView::OnControlNone() { if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { ASSERT(theApp.playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display control characters without the char area"); else if (display_.char_set == CHARSET_EBCDIC) AfxMessageBox("You can't display control characters in EBCDIC"); theApp.mac_error_ = 2; return; } // Change the current state (storing previous state in undo vector if changed) begin_change(); display_.control = 0; make_change(); end_change(); theApp.SaveToMacro(km_control, 1); } void CHexEditView::OnUpdateControlNone(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI)); pCmdUI->SetCheck(display_.control == 0); } } void CHexEditView::OnControlAlpha() { if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { ASSERT(theApp.playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display control characters without the char area"); else if (display_.char_set == CHARSET_EBCDIC) AfxMessageBox("You can't display control characters in EBCDIC"); theApp.mac_error_ = 2; return; } begin_change(); display_.control = 1; make_change(); end_change(); theApp.SaveToMacro(km_control, 2); } void CHexEditView::OnUpdateControlAlpha(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI)); pCmdUI->SetCheck(display_.control == 1); } } void CHexEditView::OnControlC() { if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { ASSERT(theApp.playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display control characters without the char area"); else if (display_.char_set == CHARSET_EBCDIC) AfxMessageBox("You can't display control characters in EBCDIC"); theApp.mac_error_ = 2; return; } begin_change(); display_.control = 2; make_change(); end_change(); theApp.SaveToMacro(km_control, 3); } void CHexEditView::OnUpdateControlC(CCmdUI *pCmdUI) { if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | ((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI) ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else { pCmdUI->Enable((display_.vert_display || display_.char_area) && (display_.char_set == CHARSET_ASCII || display_.char_set == CHARSET_ANSI)); pCmdUI->SetCheck(display_.control == 2); } } void CHexEditView::OnAscEbc() { if (!(display_.vert_display || display_.char_area)) { // Can't display EBCDIC, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("You can't display EBCDIC without the char area"); theApp.mac_error_ = 2; return; } // Change search type in find modeless dlg CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); ASSERT(mm != NULL); if (display_.char_set == CHARSET_EBCDIC) mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); else mm->m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_EBCDIC); begin_change(); if (display_.char_set == CHARSET_EBCDIC) display_.char_set = CHARSET_ANSI; else display_.char_set = CHARSET_EBCDIC; make_change(); end_change(); theApp.SaveToMacro(km_ebcdic); } void CHexEditView::OnUpdateAscEbc(CCmdUI* pCmdUI) { pCmdUI->Enable((display_.vert_display || display_.char_area)); pCmdUI->SetCheck(display_.char_set == CHARSET_EBCDIC); } void CHexEditView::OnControl() { CHECK_SECURITY(18); CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { // Can't toggle control chars, presumably in macro playback ASSERT(aa->playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display control characters without the char area"); else AfxMessageBox("Control character display is not supported for EBCDIC"); aa->mac_error_ = 2; return; } begin_change(); display_.control = (display_.control + 1)%3; make_change(); end_change(); aa->SaveToMacro(km_control, unsigned __int64(0)); } void CHexEditView::OnControlToggle() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (!(display_.vert_display || display_.char_area) || display_.char_set == CHARSET_EBCDIC) { // Can't toggle control chars, presumably in macro playback ASSERT(aa->playing_); if (!(display_.vert_display || display_.char_area)) AfxMessageBox("You can't display control characters without the char area"); else AfxMessageBox("Control character display is not supported for EBCDIC"); aa->mac_error_ = 2; return; } begin_change(); // This is called as a result of menu item which has only 2 states (unlike // dialog bar button handled by OnControl() above which has 3) if (display_.control > 0) display_.control = 0; else display_.control = 1; make_change(); end_change(); aa->SaveToMacro(km_control, 99); } void CHexEditView::OnUpdateControl(CCmdUI* pCmdUI) { pCmdUI->Enable((display_.vert_display || display_.char_area) && display_.char_set != CHARSET_EBCDIC); pCmdUI->SetCheck(display_.control != 0); } void CHexEditView::OnMark() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar SetMark(GetPos()); // Keep track whether mark is in hex or char area (if char area on) if (display_.vert_display) { // If cursor is in char row set mark to be in char area if (pos2row(GetCaret()) == 0) display_.mark_char = TRUE; else display_.mark_char = FALSE; } else if (display_.char_area && display_.hex_area) display_.mark_char = display_.edit_char; else if (display_.char_area) display_.mark_char = TRUE; else if (display_.hex_area) display_.mark_char = FALSE; aa->SaveToMacro(km_mark_pos); } void CHexEditView::SetMark(FILE_ADDRESS new_mark) { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing // Invalidate where mark was to change colours invalidate_addr_range(mark_, mark_ + 1); // Save current mark and move mark_ undo_.push_back(view_undo(undo_setmark)); undo_.back().address = mark_; undo_.push_back(view_undo(undo_state, TRUE)); undo_.back().disp_state = disp_state_; mark_ = new_mark; if (theApp.align_rel_ && mark_ != GetDocument()->base_addr_) { GetDocument()->StopSearch(); GetDocument()->base_addr_ = GetSearchBase(); GetDocument()->StartSearch(); } // Invalidate where mark now is to change background colour invalidate_addr_range(mark_, mark_ + 1); CHECK_SECURITY(41); show_calc(); // Some button enablement depends on mark_ position (eg. @ Mark) } void CHexEditView::OnGotoMark() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing if (!display_.vert_display && display_.char_area && display_.hex_area && display_.edit_char != display_.mark_char) { // Going to mark also entails swapping between hex and char areas FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); undo_.push_back(view_undo(undo_state)); undo_.back().disp_state = disp_state_; display_.edit_char = display_.mark_char; if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); // We need to specify the previous address since otherwise MoveToAddress // will use the current selection which is now in the wrong area. MoveWithDesc("Jump to Mark ", mark_, mark_, start_addr, end_addr, TRUE); // space at end means significant nav pt // Need to call SetSel in case MoveToAddress did not, due to no move (only area swap) SetSel(addr2pos(mark_, row), addr2pos(mark_, row), true); } else MoveWithDesc("Jump to Mark ", mark_); // space at end means significant nav pt aa->SaveToMacro(km_goto_mark); } void CHexEditView::OnExtendToMark() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); if ((end_base && mark_ == end_addr) || (!end_base && mark_ == start_addr)) { // There is nothing to do aa->mac_error_ = 1; return; } // Move the non-base end of the selection to the mark (MoveToAddress saves undo info) if (end_base) MoveToAddress(mark_, end_addr); else MoveWithDesc("Extend to Mark ", start_addr, mark_); // space at end means significant nav pt aa->SaveToMacro(km_extendto_mark); } // Swap the current caret position with the mark void CHexEditView::OnSwapMark() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing FILE_ADDRESS start_addr, end_addr; BOOL end_base = GetSelAddr(start_addr, end_addr); int row = 0; if (start_addr == end_addr && display_.vert_display) row = pos2row(GetCaret()); // If same address and mark/caret are in same areas (both in hex or both in char area) return if (mark_ == start_addr && start_addr == end_addr && (display_.vert_display || !display_.char_area || !display_.hex_area || display_.edit_char == display_.mark_char)) { // There is nothing to do aa->mac_error_ = 1; return; } // If the caret and the mark are in different areas we have to swap them if (!display_.vert_display && display_.char_area && display_.hex_area && display_.edit_char != display_.mark_char) { undo_.push_back(view_undo(undo_state)); // save undo for edit_char_ and mark_char_ undo_.back().disp_state = disp_state_; display_.edit_char = !display_.edit_char; display_.mark_char = !display_.mark_char; if (display_.edit_char) SetHorzBufferZone(1); else SetHorzBufferZone(2); // We need to specify the previous address since otherwise MoveToAddress // will use the current selection which is now in the wrong area since // display_.edit_char has changed. MoveWithDesc("Swap Cursor with Mark ", mark_, mark_, start_addr, end_addr, TRUE); // Need to call SetSel in case MoveToAddress did not due to no move (only area swap) SetSel(addr2pos(mark_), addr2pos(mark_), true); } else MoveWithDesc("Swap Cursor with Mark ", mark_, -1, -1, -1, FALSE, FALSE, row); // Move the mark undo_.push_back(view_undo(undo_setmark, TRUE)); // save undo for move mark undo_.back().address = mark_; invalidate_addr_range(mark_, mark_ + 1); // force undraw of mark mark_ = start_addr; invalidate_addr_range(mark_, mark_ + 1); // force draw of new mark if (theApp.align_rel_ && mark_ != GetDocument()->base_addr_) { GetDocument()->StopSearch(); GetDocument()->base_addr_ = GetSearchBase(); GetDocument()->StartSearch(); } show_calc(); aa->SaveToMacro(km_swap_mark); } void CHexEditView::OnJumpDec() // message from BCG edit bar combo { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); CString addr_str, err_str; FILE_ADDRESS address = mm->GetDecAddress(addr_str, err_str); if (address == -1) { CString ss; ss.Format("Invalid expression\r\r%s\r\r%s", addr_str, err_str); AfxMessageBox(ss); return; } // If recording macro indicate jump & store address jumped to aa->SaveToMacro(km_address_dec, addr_str); #if 0 // Try to go to the address requested FILE_ADDRESS actual; if ((actual = GoAddress(address)) != address) { // Could not go to the requested address - tell user AfxMessageBox("Invalid address entered. Address set to EOF"); } SaveMove(); // Save prev pos in undo array DisplayCaret(); #else MoveWithDesc("Jump (Decimal Jump Tool) ", address); // space at end means significant nav pt #endif } void CHexEditView::OnJumpHex() // message from BCG edit bar combo { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); CString addr_str, err_str; FILE_ADDRESS address = mm->GetHexAddress(addr_str, err_str); if (address == -1) { CString ss; ss.Format("Invalid hex expression\r\r%s\r\r%s", addr_str, err_str); AfxMessageBox(ss); return; } // If recording macro indicate jump & store address jumped to theApp.SaveToMacro(km_address_hex, addr_str); MoveWithDesc("Jump (Hex Jump Tool) ", address); // space at end means significant nav pt } void CHexEditView::OnJumpHexAddr() // Alt-J { num_entered_ = num_del_ = num_bs_ = 0; // Stop any editing CHexEditControl::BeginJump(); } void CHexEditView::OnInsert() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; if (!do_insert()) return; aa->SaveToMacro(km_ovr_ins); } bool CHexEditView::do_insert() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (display_.readonly) { AfxMessageBox("Attempt to toggle OVR/INS in read only mode"); aa->mac_error_ = 10; return false; } if (GetDocument()->IsDevice()) { AfxMessageBox("You cannot use INS mode for devices (logical volumes and physical disks)"); aa->mac_error_ = 10; return false; } display_.overtype = !display_.overtype; undo_.push_back(view_undo(undo_overtype)); undo_.back().flag = !display_.overtype; if (GetDocument()->length() == 0) { DoInvalidate(); if (display_.overtype) ScrollMode(); else { CaretMode(); SetCaret(addr2pos(0)); // very start of file } } return true; } void CHexEditView::OnUpdateInsert(CCmdUI* pCmdUI) { pCmdUI->Enable(!display_.readonly && !GetDocument()->IsDevice()); pCmdUI->SetCheck(!display_.overtype); } void CHexEditView::OnAllowMods() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // if (!aa->playing_ && GetFocus() != this) SetFocus(); // Ensure focus does not stay in DlgBar num_entered_ = num_del_ = num_bs_ = 0; allow_mods(); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); // Make sure calc buttons reflect modifiability of file if (!aa->refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); #if 0 // Obviated by BCG // Change the toolbar button mm->bb_allow_mods_.LoadBitmaps(display_.readonly ? IDB_MODSU : IDB_MODSS, IDB_MODSD,0,IDB_MODSX); mm->bb_allow_mods_.Invalidate(); #endif aa->SaveToMacro(km_ro_rw); } void CHexEditView::allow_mods() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (display_.readonly && GetDocument()->read_only()) { AfxMessageBox("This file cannot be modified"); aa->mac_error_ = 10; return; } display_.readonly = !display_.readonly; undo_.push_back(view_undo(undo_readonly)); undo_.back().flag = !display_.readonly; show_prop(); // things may be changeable now } void CHexEditView::OnUpdateAllowMods(CCmdUI* pCmdUI) { pCmdUI->Enable(!GetDocument()->read_only()); pCmdUI->SetCheck(!display_.readonly); } void CHexEditView::OnToggleEndian() { begin_change(); display_.big_endian = !display_.big_endian; make_change(); end_change(); // Make calculator big endian check box reflects this file's big endian status CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!theApp.refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); theApp.SaveToMacro(km_big_endian, (__int64)-1); // -1 = toggle } void CHexEditView::OnUpdateToggleEndian(CCmdUI* pCmdUI) { pCmdUI->SetCheck(display_.big_endian); } void CHexEditView::OnBigEndian() { begin_change(); display_.big_endian = 1; make_change(); end_change(); // Make calculator big endian check box reflects this file's big endian status CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!theApp.refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); theApp.SaveToMacro(km_big_endian, (__int64)1); // 1 = big endian on } void CHexEditView::OnUpdateBigEndian(CCmdUI* pCmdUI) { pCmdUI->SetCheck(display_.big_endian); } void CHexEditView::OnLittleEndian() { begin_change(); display_.big_endian = 0; make_change(); end_change(); // Make calculator big endian check box reflects this file's big endian status CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (!theApp.refresh_off_ && mm->m_paneCalc.IsWindowVisible()) mm->m_wndCalc.update_controls(); theApp.SaveToMacro(km_big_endian, unsigned __int64(0)); // 0 = big endian off (ie little-endian) } void CHexEditView::OnUpdateLittleEndian(CCmdUI* pCmdUI) { pCmdUI->SetCheck(!display_.big_endian); } void CHexEditView::OnTrackChanges() { begin_change(); if (display_.hide_replace && display_.hide_insert && display_.hide_delete) { // All off - so turn them all on display_.hide_replace = display_.hide_insert = display_.hide_delete = 0; } else { // Turn them all off display_.hide_replace = display_.hide_insert = display_.hide_delete = 1; } make_change(); end_change(); theApp.SaveToMacro(km_track_changes, (__int64)-1); // -1 = toggle } void CHexEditView::OnUpdateTrackChanges(CCmdUI* pCmdUI) { pCmdUI->SetCheck(!(display_.hide_replace && display_.hide_insert && display_.hide_delete)); } void CHexEditView::OnDffdAutoSync() { if (pdfv_ == NULL) { AfxMessageBox("No DFFD tree view is displayed"); theApp.mac_error_ = 10; return; } begin_change(); display_.auto_sync_dffd = !display_.auto_sync_dffd; make_change(); end_change(); // If has been turned on then sync now if (display_.auto_sync_dffd) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pdfv_->SelectAt(start_addr); } theApp.SaveToMacro(km_dffd_sync, 2); } void CHexEditView::OnUpdateDffdAutoSync(CCmdUI* pCmdUI) { pCmdUI->Enable(pdfv_ != NULL); pCmdUI->SetCheck(display_.auto_sync_dffd); } void CHexEditView::OnDffdSync() { if (pdfv_ == NULL) { AfxMessageBox("No DFFD tree view is displayed"); theApp.mac_error_ = 10; return; } FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pdfv_->SelectAt(start_addr); pdfv_->SetFocus(); theApp.SaveToMacro(km_dffd_sync, 255); } void CHexEditView::OnUpdateDffdSync(CCmdUI* pCmdUI) { // Don't allow manual sync if auto sync is on pCmdUI->Enable(pdfv_ != NULL && !display_.auto_sync_dffd); } void CHexEditView::OnSearchHex() // Alt-L, F6 { CSearchEditControl::BeginSearch(CSearchEditControl::mode_hex); } void CHexEditView::OnSearchAscii() // F5 { CSearchEditControl::BeginSearch(CSearchEditControl::mode_char); } void CHexEditView::OnSearchIcase() // F4 { CSearchEditControl::BeginSearch(CSearchEditControl::mode_icase); } // CChildFrame *CHexEditView::comp_window() { CMainFrame *mm = dynamic_cast<CMainFrame *>(AfxGetMainWnd()); CChildFrame *nextc; // Loops through all MDI child frames CChildFrame *compc = NULL; // Frame of view available to compare with BOOL got_one; // Have we gound an appropriate view? // Get the currently active child MDI window nextc = dynamic_cast<CChildFrame *>(mm->MDIGetActive()); ASSERT(nextc != NULL); ASSERT(nextc->GetHexEditView() == this); // Search for another (non-iconized) window for (got_one = FALSE, nextc = dynamic_cast<CChildFrame *>(nextc->GetWindow(GW_HWNDNEXT)); nextc != NULL; nextc = dynamic_cast<CChildFrame *>(nextc->GetWindow(GW_HWNDNEXT)) ) { if (!nextc->IsIconic()) { // More than one found - use which one? if (got_one) { // Can't display message when used in OnUpdateEditCompare call // AfxMessageBox("Comparison not performed\r" // "- more than two (non-iconized) windows"); return NULL; } got_one = TRUE; compc = nextc; } } // If we didn't find a non-iconized window search for iconized one if (compc == NULL) { nextc = dynamic_cast<CChildFrame *>(mm->MDIGetActive()); // Search for an iconized window for (got_one = FALSE, nextc = dynamic_cast<CChildFrame *>(nextc->GetWindow(GW_HWNDNEXT)); nextc != NULL; nextc = dynamic_cast<CChildFrame *>(nextc->GetWindow(GW_HWNDNEXT)) ) { ASSERT(nextc->IsIconic()); // else compc != NULL // If more than one window - use which one? if (got_one) { // Can't display message when used in OnUpdateEditCompare call // AfxMessageBox("Comparison not performed\r" // "- more than two windows found"); return NULL; } got_one = TRUE; compc = nextc; } } return compc; } void CHexEditView::OnEditCompare() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = dynamic_cast<CMainFrame *>(AfxGetMainWnd()); CChildFrame *origc; // Pointer to MDI child frame of current view // Save the currently active child MDI window origc = dynamic_cast<CChildFrame *>(mm->MDIGetActive()); ASSERT(origc != NULL); ASSERT(origc->GetHexEditView() == this); // Restore current window if iconized if (origc->IsIconic()) { WINDOWPLACEMENT wp; origc->GetWindowPlacement(&wp); wp.showCmd = SW_RESTORE; origc->SetWindowPlacement(&wp); } // Get MDI child frame of compare window CChildFrame *compc = comp_window(); // If we found nothing to compare with, display message and return if (compc == NULL) { AfxMessageBox("Comparison not performed\r" "- two non-minimized windows required"); aa->mac_error_ = 10; return; } // Get view to compare with - active view of compc. (Actually the // active view should be the only view since we don't have splitters.) CHexEditView *compv = dynamic_cast<CHexEditView *>(compc->GetHexEditView()); if (compv == NULL) { AfxMessageBox("Cannot compare with this type of window"); aa->mac_error_ = 10; return; } ASSERT_KINDOF(CHexEditView, compv); CString orig_title, comp_title; // Title of the windows to be compared origc->GetWindowText(orig_title); compc->GetWindowText(comp_title); CHexEditDoc *origd, *compd; // Documents of the compared views origd = GetDocument(); compd = compv->GetDocument(); // Now compare the data from each view starting at END of current selection CString mess; // Message for user when problem encountered FILE_ADDRESS dummy; // Not used - start address of selection FILE_ADDRESS start_addr; // Start address in current view FILE_ADDRESS orig_addr, comp_addr; // Current comp location in both views GetSelAddr(dummy, start_addr); orig_addr = start_addr; compv->GetSelAddr(dummy, comp_addr); // start_addr = orig_addr = GetPos(); // comp_addr = compv->pos2addr(compv->GetCaret()); #ifndef _DEBUG // Allow self-compare for testing purposes // If same doc and same address then we aren't doing anything useful if (origd == compd && orig_addr == comp_addr) { mess.Format("Comparing data with itself in windows\r%s and %s", (const char *)orig_title, (const char *)comp_title); AfxMessageBox(mess); aa->mac_error_ = 10; return; } #endif size_t orig_got, comp_got; // How many bytes obtained from docs FILE_ADDRESS show_inc = 0x80000; // How far between showing addresses FILE_ADDRESS next_show = (orig_addr/show_inc + 1)*show_inc; // Next address to show FILE_ADDRESS slow_show = ((orig_addr+0x800000)/0x800000 + 1)*0x800000; // When we slow showing FILE_ADDRESS comp_length = min(origd->length() - orig_addr, compd->length() - comp_addr); // Get memory for compare buffers unsigned char *orig_buf = new unsigned char[compare_buf_len]; unsigned char *comp_buf = new unsigned char[compare_buf_len]; CWaitCursor wait; aa->SaveToMacro(km_compare); while (1) { if (orig_addr > next_show) { if (AbortKeyPress() && AfxMessageBox("Abort comparison?", MB_YESNO) == IDYES) { delete[] orig_buf; delete[] comp_buf; mm->Progress(-1); ((CMainFrame *)AfxGetMainWnd()) ->StatusBarText("Comparison aborted"); aa->mac_error_ = 10; show_pos(); return; } show_pos(next_show); // If we've been showing the current address for awhile then show // less often (and show progress) to avoid slowing down the actual compare if (next_show >= slow_show) { mm->Progress(int(((next_show-start_addr)*100)/comp_length)); show_inc = 0x800000; } AfxGetApp()->OnIdle(0); // Force display of updated address next_show += show_inc; } orig_got = origd->GetData(orig_buf, compare_buf_len, orig_addr); comp_got = compd->GetData(comp_buf, compare_buf_len, comp_addr); size_t comp_len = min(orig_got, comp_got); if (comp_len == 0) // EOF of one or both files break; if (memcmp(orig_buf, comp_buf, comp_len) != 0) { // Difference found size_t pos; for (pos = 0; pos < comp_len; ++pos) if (orig_buf[pos] != comp_buf[pos]) break; ASSERT(pos < comp_len); #ifdef SYS_SOUNDS CSystemSound::Play("Comparison Difference Found"); #endif // mess.Format("Difference found after $%I64X (decimal %I64d) bytes\r" // "%s at address $%I64X (decimal %I64d)\r%s at address $%I64X (decimal %I64d)", // __int64(orig_addr + pos - start_addr), __int64(orig_addr + pos - start_addr), // orig_title, __int64(orig_addr + pos), __int64(orig_addr + pos), // comp_title, __int64(comp_addr + pos), __int64(comp_addr + pos)); // AfxMessageBox(mess); mm->Progress(-1); char buf[32]; sprintf(buf, "%I64d", __int64(orig_addr + pos - start_addr)); mess = CString("Difference found after ") + buf + CString(" bytes"); mm->StatusBarText(mess); // Move to where diff found and select that byte in both views // (Selecting the byte allows the differences to be seen in both // windows without flipping between them, and allows another // compare immediately starting at the byte after.) compv->MoveWithDesc("Comparison Difference Found ", comp_addr + pos, comp_addr + pos + 1); MoveWithDesc("Comparison Difference Found ", orig_addr + pos, orig_addr + pos + 1); if (aa->highlight_) { compv->add_highlight(comp_addr + pos, comp_addr + pos + 1, TRUE); add_highlight(orig_addr + pos, orig_addr + pos + 1, TRUE); } delete[] orig_buf; delete[] comp_buf; return; } if (orig_got != comp_got) break; orig_addr += orig_got; comp_addr += comp_got; } mm->Progress(-1); // If we got here then we hit EOF on one or both files if (orig_got == comp_got && orig_addr + orig_got - start_addr == 0) { #ifdef SYS_SOUNDS CSystemSound::Play("Comparison Difference Not Found"); #endif mess = "Both files are at EOF"; if (aa->playing_) mm->StatusBarText(mess); else AfxMessageBox(mess); } else if (orig_got == comp_got) { #ifdef SYS_SOUNDS CSystemSound::Play("Comparison Difference Not Found"); #endif // EOF (both files) encountered ASSERT(orig_got == 0); show_pos(orig_addr); // Display message box when no differences found so that user sees that // something happened -- the caret is not moved and they may not notice // a message in the status bar (or the status bar may be invisible). // (On the other hand if a difference is found then the caret of both views // is moved and we just display a message in the status bar -- putting up // a dialog would just be annoying.) CString sdec, shex; char buf[22]; // temp buf where we sprintf sprintf(buf, "%I64d", __int64(orig_addr + orig_got - start_addr)); sdec = buf; AddCommas(sdec); if (aa->hex_ucase_) sprintf(buf, "%I64X", __int64(orig_addr + orig_got - start_addr)); else sprintf(buf, "%I64x", __int64(orig_addr + orig_got - start_addr)); shex = buf; AddSpaces(shex); mess.Format("No differences found after\r" "%s (%sh) bytes.", sdec, shex); // mess.Format("No differences found\r" // "after %lX (hex) or\r" // "%ld (decimal) bytes.", // orig_addr + orig_got - start_addr, // orig_addr + orig_got - start_addr); if (aa->playing_) mm->StatusBarText(mess); else AfxMessageBox(mess); aa->mac_error_ = 1; } else if (orig_got < comp_got) { #ifdef SYS_SOUNDS CSystemSound::Play("Comparison Difference Found"); #endif // EOF on orig file before EOF on comp file // mess.Format("Difference found after $%I64X (decimal %I64d) bytes\r" // "%s at EOF - address $%I64X (decimal %I64d)\r%s at address $%I64X (decimal %I64d)", // __int64(orig_addr + orig_got - start_addr), __int64(orig_addr + orig_got - start_addr), // orig_title, __int64(orig_addr + orig_got), __int64(orig_addr + orig_got), // comp_title, __int64(comp_addr + orig_got), __int64(comp_addr + orig_got)); // AfxMessageBox(mess); char buf[32]; sprintf(buf, "%I64d", __int64(orig_addr + orig_got - start_addr)); mess.Format("EOF on \"%s\" after %s bytes", orig_title, buf); mm->StatusBarText(mess); compv->MoveWithDesc("Comparison Difference Found ", comp_addr + orig_got, comp_addr + orig_got + 1); if (aa->highlight_) compv->add_highlight(comp_addr + orig_got, comp_addr + orig_got + 1, TRUE); MoveWithDesc("EOF in Comparison ", orig_addr + orig_got); } else { #ifdef SYS_SOUNDS CSystemSound::Play("Comparison Difference Found"); #endif // EOF on comp file before EOF on orig file // mess.Format("Difference found after $%lX (decimal %ld) bytes\r" // "%s at address $%lX (decimal %ld)\r%s at EOF - address $%lX (decimal %ld)", // orig_addr + comp_got - start_addr, orig_addr + comp_got - start_addr, // orig_title, orig_addr + comp_got, orig_addr + comp_got, // comp_title, comp_addr + comp_got, comp_addr + comp_got); // AfxMessageBox(mess); char buf[32]; sprintf(buf, "%I64d", __int64(orig_addr + comp_got - start_addr)); mess.Format("EOF on \"%s\" after %s bytes", comp_title, buf); mm->StatusBarText(mess); compv->MoveWithDesc("EOF in Comparison ", comp_addr + comp_got); MoveWithDesc("Comparison Difference Found ", orig_addr + comp_got, orig_addr + comp_got + 1); if (aa->highlight_) add_highlight(orig_addr + comp_got, orig_addr + comp_got + 1, TRUE); } delete[] orig_buf; delete[] comp_buf; } void CHexEditView::OnUpdateEditCompare(CCmdUI* pCmdUI) { pCmdUI->Enable(comp_window() != NULL); } // Activate next window void CHexEditView::OnWindowNext() { #if 0 // This was changed for consistency with km_win_next in macros. // The problem is to make sure all windows are cycled through when // Window/Next is used whether or not in a macro (and in the same order). // - next window in macro does not change focus now (for speed) but just keeps track of active view // - if focus is set Windows changes order of windows (Z order) returned by GetWindow(GW_HWNDNEXT) // - the MDI functions (MDINext etc) seem to use some sort of list where order does not change with focus change // - but MDINext changes focus and there appears to be no way to get at the list without changing focus // For the above reasons and for consistency the next window command both // in and not in macros uses the new NextView function below. // Activate next window that is not a print preview window and is not minimized CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = dynamic_cast<CMainFrame *>(::AfxGetMainWnd()); CChildFrame *currc; // Currently active MDI child frame CChildFrame *nextc; // Loops through all MDI child frames // Save the currently active child MDI window currc = dynamic_cast<CChildFrame *>(mm->MDIGetActive()); ASSERT(currc != NULL); ASSERT(currc->GetHexEditView() == this); while (mm->MDINext(), (nextc = dynamic_cast<CChildFrame *>(mm->MDIGetActive())) != currc) { // Don't change to iconized windows if (!nextc->IsIconic()) { // Make sure it's a CHexEditView (don't change to print preview windows) CHexEditView *pview = dynamic_cast<CHexEditView *>(nextc->GetHexEditView()); if (pview != NULL && pview->IsKindOf(RUNTIME_CLASS(CHexEditView))) { nextc->SetActiveView(pview); if (aa->recording_ && aa->mac_.size() > 0 && (aa->mac_.back()).ktype == km_focus) { // We don't want focus change recorded (see CHexEditView::OnSetFocus) aa->mac_.pop_back(); } aa->SaveToMacro(km_win_next); return; } } } ((CMainFrame *)AfxGetMainWnd())-> StatusBarText("Warning: no other non-minimized windows found"); aa->mac_error_ = 2; #endif // Get the next window CHexEditView *pnext = NextView(); if (pnext == NULL) { AfxMessageBox("Warning: no other non-minimized windows found"); theApp.mac_error_ = 2; return; } // Make new view active pnext->GetFrame()->MDIActivate(); // Activate next frame pnext->GetFrame()->SetActiveView(pnext); // Make sure active view is normal (hex) view ASSERT(pnext == GetView()); // Make sure it is now the active view if (theApp.recording_ && theApp.mac_.size() > 0 && (theApp.mac_.back()).ktype == km_focus) { // We don't want focus change recorded (see CHexEditView::OnSetFocus) theApp.mac_.pop_back(); } theApp.SaveToMacro(km_win_next); } // Return next view in list non-minimised view or NULL if none. // Cycles through the list in reverse order so repeated calls // and focus changes still return all the non-minimised frames. CHexEditView * CHexEditView::NextView() const { CChildFrame *currc = dynamic_cast<CChildFrame *>(GetFrame()); ASSERT(currc != NULL); CChildFrame *nextc = currc; do { nextc = dynamic_cast<CChildFrame *>(nextc->GetWindow(GW_HWNDPREV)); // If reached the top of the list go to the end if (nextc == NULL) nextc = dynamic_cast<CChildFrame *>(currc->GetWindow(GW_HWNDLAST)); } while (nextc != NULL && nextc != currc && nextc->IsIconic()); if (nextc == NULL || nextc == currc) return NULL; else return nextc->GetHexEditView(); } void CHexEditView::OnAscii2Ebcdic() { DoConversion(CONVERT_ASC2EBC, "convert ASCII to EBCDIC"); } void CHexEditView::OnEbcdic2Ascii() { DoConversion(CONVERT_EBC2ASC, "convert EBCDIC to ASCII"); } void CHexEditView::OnAnsi2Ibm() { DoConversion(CONVERT_ANSI2IBM, "convert ANSI to IBM/OEM"); } void CHexEditView::OnIbm2Ansi() { DoConversion(CONVERT_IBM2ANSI, "convert IBM/OEM to ANSI"); } void CHexEditView::OnUppercase() { DoConversion(CONVERT_UPPER, "convert to upper case"); } void CHexEditView::OnLowercase() { DoConversion(CONVERT_LOWER, "convert to lower case"); } // Performs particular conversions on a memory buffer void CHexEditView::ProcConversion(unsigned char *buf, size_t count, convert_type op) { // Operate on all the selected values for (size_t ii = 0; ii < count; ++ii) { switch (op) { case CONVERT_ASC2EBC: if (buf[ii] < 128) buf[ii] = a2e_tab[buf[ii]]; else buf[ii] = '\0'; break; case CONVERT_EBC2ASC: buf[ii] = e2a_tab[buf[ii]]; break; case CONVERT_ANSI2IBM: if (buf[ii] > 128) buf[ii] = a2i_tab[buf[ii]&0x7F]; break; case CONVERT_IBM2ANSI: if (buf[ii] > 128) buf[ii] = i2a_tab[buf[ii]&0x7F]; break; case CONVERT_UPPER: if (EbcdicMode()) { if (buf[ii] >= 0x81 && buf[ii] <= 0x89 || buf[ii] >= 0x91 && buf[ii] <= 0x99 || buf[ii] >= 0xA2 && buf[ii] <= 0xA9 ) { buf[ii] += 0x40; } } else if (ANSIMode() || buf[ii] < 128) buf[ii] = toupper(buf[ii]); break; case CONVERT_LOWER: if (EbcdicMode()) { if (buf[ii] >= 0xC1 && buf[ii] <= 0xC9 || buf[ii] >= 0xD1 && buf[ii] <= 0xD9 || buf[ii] >= 0xE2 && buf[ii] <= 0xE9 ) { buf[ii] -= 0x40; } } else if (ANSIMode() || buf[ii] < 128) buf[ii] = tolower(buf[ii]); break; default: ASSERT(0); } } } // This handles conversion operations (everything except for the actual data // convert operation - see ProcConversion) including getting the selection // and allocating memory buffers to store the result (or temp file for // really big selections) and updating the document. // It also updates progress in the status bar and allows user abort. void CHexEditView::DoConversion(convert_type op, LPCSTR desc) { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; if (check_ro(desc)) return; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); // Make sure there is a selection if (start_addr >= end_addr) { ASSERT(theApp.playing_); CString mess; mess.Format("There is no selection to %s", desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } ASSERT(start_addr < end_addr && end_addr <= GetDocument()->length()); // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && GetDocument()->DataFileSlotFree()) { int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) // Create a file to store the resultant data // (Temp file used by the document until it is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); // Get data buffer size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); if (op != unary_at) // We don't need to get old value if assigning VERIFY(GetDocument()->GetData(buf, len, curr) == len); ProcConversion(buf, len, op); ff.Write(buf, len); if (AbortKeyPress()) { CString mess; mess.Format("Abort %s?", desc); if (AfxMessageBox(mess, MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the unprocessed block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); // Add the temp file to the document idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); GetDocument()->Change(mod_insert_file, start_addr, end_addr - start_addr, NULL, idx, this, TRUE); } else { // Allocate memory block and process it // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot convert such a large selection. \n" "Please save the file to deallocate \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and converting such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) try { buf = new unsigned char[size_t(end_addr - start_addr)]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } size_t got = GetDocument()->GetData(buf, size_t(end_addr - start_addr), start_addr); ASSERT(got == size_t(end_addr - start_addr)); ProcConversion(buf, got, op); GetDocument()->Change(mod_replace, start_addr, got, (unsigned char *)buf, 0, this); } DisplayCaret(); theApp.SaveToMacro(km_convert, op); func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } // Make sure there is a selection before doing conversion void CHexEditView::OnUpdateConvert(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start_addr < end_addr ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(start_addr < end_addr); } void CHexEditView::OnEncrypt() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (check_ro("encrypt")) return; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); // Make sure there is a selection if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("There is no selection to encrypt"); aa->mac_error_ = 10; return; } if (aa->password_.IsEmpty()) { CPassword dlg; dlg.m_password = aa->password_; if (dlg.DoModal() == IDOK) { aa->password_ = dlg.m_password; // Create encryption key with new password if (aa->algorithm_ > 0) { ASSERT(aa->algorithm_ - 1 < (int)aa->crypto_.GetNum()); aa->crypto_.SetPassword(aa->algorithm_-1, aa->password_); } } else return; } else if (aa->algorithm_ > 0 && aa->crypto_.NeedsPassword(aa->algorithm_-1)) { // We have a password but somehow it has not been set for this alg ASSERT(aa->algorithm_ - 1 < (int)aa->crypto_.GetNum()); aa->crypto_.SetPassword(aa->algorithm_-1, aa->password_); } unsigned char *buf = NULL; if (aa->algorithm_ > 0) { if (display_.overtype && aa->crypto_.needed(aa->algorithm_-1, 256) != 256) { if (AfxMessageBox("Encrypting with this algorithm will increase the\r" "the length of the current (unencrypted) selection.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 10; return; } else if (!do_insert()) return; } // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && GetDocument()->DataFileSlotFree()) { CWaitCursor wait; // Turn on wait cursor (hourglass) // Get input and output buffers size_t inbuflen = 32768; size_t outbuflen = aa->crypto_.needed(aa->algorithm_-1, inbuflen); FILE_ADDRESS total_out = 0; try { buf = new unsigned char[outbuflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } // Create a "temp" file to store the encrypted data // (This file stores the data until the document is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); size_t len; // size of data to be encrypted for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(inbuflen, end_addr - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); // Encrypt and write it size_t outlen = aa->crypto_.encrypt(aa->algorithm_-1, buf, len, outbuflen, curr + len == end_addr); ff.Write(buf, outlen); total_out += outlen; if (AbortKeyPress() && AfxMessageBox("Abort encryption?", MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the unencrypted block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); // Add the temp file to the document int idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); GetDocument()->Change(mod_insert_file, start_addr, total_out, NULL, idx, this, TRUE); // If length changed update the selection and makde sure it is undoable if (total_out != end_addr - start_addr) { // Select encrypted data SetSel(addr2pos(start_addr), addr2pos(start_addr + total_out)); // Inform the user in case they don't notice the selection has been increased CString mess; mess.Format("Encryption increased the selection length by %ld bytes", long(total_out - (end_addr - start_addr))); ((CMainFrame *)AfxGetMainWnd())->StatusBarText(mess); } } else { // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot encrypt such a large selection. \n" "Please save the file to free \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // More than 128 Mb may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and encrypting such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) size_t len = size_t(end_addr - start_addr); // Length of selection size_t outlen = aa->crypto_.needed(aa->algorithm_-1, len); // Get memory for selection and read it from the document try { buf = new unsigned char[outlen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); aa->mac_error_ = 10; return; } VERIFY(GetDocument()->GetData(buf, len, start_addr) == len); if (aa->crypto_.encrypt(aa->algorithm_-1, buf, len, outlen) != outlen) { ASSERT(0); AfxMessageBox("Encryption error"); aa->mac_error_ = 10; goto func_return; } if (len != outlen) { ASSERT(outlen > len); // Since the encrypted text is bigger we must delete then insert GetDocument()->Change(mod_delforw, start_addr, len, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, outlen, buf, 0, this, TRUE); ASSERT(undo_.back().utype == undo_change); undo_.back().previous_too = true; // Merge changes (at least in this view) // Select encrypted data and save undo of selection SetSel(addr2pos(start_addr), addr2pos(start_addr+outlen)); // Inform the user in case they don't notice the selection has been increased CString mess; mess.Format("Encryption increased the selection length by %ld bytes", long(outlen-len)); ((CMainFrame *)AfxGetMainWnd())->StatusBarText(mess); } else GetDocument()->Change(mod_replace, start_addr, len, buf, 0, this); } } else { // Note that CryptoAPI algs (above) the key is set when password // or alg is changed (more efficient) but for internal we set it here // in case other internal use (security) has changed the current key ::set_key(aa->password_, aa->password_.GetLength()); // Make sure selection is right size if ((end_addr-start_addr)%8 != 0) { // Presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("The selection is not a multiple of 8 (encryption block length)"); aa->mac_error_ = 10; return; } size_t len; // Length of selection // Note: for internal alg. we don't break the encryption up and write // to temp file in order to handle huge selections as above (yet?) // Get memory for selection and read it from the document try { if (end_addr - start_addr > UINT_MAX) throw std::bad_alloc(); len = size_t(end_addr - start_addr); buf = new unsigned char[len]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory - selection too large"); aa->mac_error_ = 10; return; } VERIFY(GetDocument()->GetData(buf, len, start_addr) == len); ::encrypt(buf, len); GetDocument()->Change(mod_replace, start_addr, len, buf, 0, this); } DisplayCaret(); aa->SaveToMacro(km_encrypt, 1); // 1 == encrypt (2 == decrypt) func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnDecrypt() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (aa->algorithm_ < 0 || check_ro("decrypt")) return; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); // Make sure there is a selection if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("There is no selection to decrypt"); aa->mac_error_ = 10; return; } if (aa->password_.IsEmpty()) { CPassword dlg; dlg.m_password = aa->password_; if (dlg.DoModal() == IDOK) { aa->password_ = dlg.m_password; // Create encryption key with new password if (aa->algorithm_ > 0) { ASSERT(aa->algorithm_ - 1 < (int)aa->crypto_.GetNum()); aa->crypto_.SetPassword(aa->algorithm_-1, aa->password_); } } else return; } else if (aa->algorithm_ > 0 && aa->crypto_.NeedsPassword(aa->algorithm_-1)) { // We have a password but somehow it has not been set for this alg ASSERT(aa->algorithm_ - 1 < (int)aa->crypto_.GetNum()); aa->crypto_.SetPassword(aa->algorithm_-1, aa->password_); } unsigned char *buf = NULL; if (aa->algorithm_ > 0) { int blen = aa->crypto_.GetBlockLength(aa->algorithm_-1); if (blen == -1) { AfxMessageBox("Encryption block length error"); aa->mac_error_ = 10; return; } if (blen != 0 && display_.overtype) { if (AfxMessageBox("Decrypting with this algorithm may decrease \r" "the length of the current (encrypted) selection.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { aa->mac_error_ = 10; return; } else if (!do_insert()) return; } ASSERT(blen%8 == 0); // Should be multiple of number of bits/byte if (blen == 0) blen = 1; // Stream cipher - don't restrict selection length else blen = blen/8; // Convert bits to bytes // Make sure selection is right size if ((end_addr-start_addr)%blen != 0) { // Presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("The selection is not a multiple of encryption block length"); aa->mac_error_ = 10; return; } // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && GetDocument()->DataFileSlotFree()) { CWaitCursor wait; // Turn on wait cursor (hourglass) size_t len, buflen = 32768; ASSERT(buflen % blen == 0); // buffer length must be multiple of cipher block length FILE_ADDRESS total_out = 0; try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } // Create a "temp" file to store the decrypted data // (This file stores the data until the document is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); size_t outlen = aa->crypto_.decrypt(aa->algorithm_-1, buf, len, curr + len == end_addr); if (outlen == size_t(-1)) { AfxMessageBox(CString("Could not decrypt using:\n") + aa->crypto_.GetName(aa->algorithm_-1)); ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } ff.Write(buf, outlen); total_out += outlen; if (AbortKeyPress() && AfxMessageBox("Abort decryption?", MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the original encrypted block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); // Add the temp file to the document int idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); GetDocument()->Change(mod_insert_file, start_addr, total_out, NULL, idx, this, TRUE); if (total_out != end_addr - start_addr) { // Select the decrypted data SetSel(addr2pos(start_addr), addr2pos(start_addr + total_out)); // Inform the user in case they don't notice the selection has been increased CString mess; mess.Format("Decryption decreased the selection length by %ld bytes", long(end_addr - start_addr - total_out)); ((CMainFrame *)AfxGetMainWnd())->StatusBarText(mess); } } else { // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot decrypt such a large selection. \n" "Please save the file to free \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and decrypting such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } size_t len = size_t(end_addr - start_addr); // Length of selection size_t outlen; // Size of decrypted text (may be less than encrypted) // Get memory for selection and read it from the document try { buf = new unsigned char[len]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); aa->mac_error_ = 10; return; } VERIFY(GetDocument()->GetData(buf, len, start_addr) == len); outlen = aa->crypto_.decrypt(aa->algorithm_-1, buf, len); if (outlen == size_t(-1)) { AfxMessageBox(CString("Could not decrypt using:\n") + aa->crypto_.GetName(aa->algorithm_-1)); aa->mac_error_ = 10; goto func_return; } if (len != outlen) { ASSERT(outlen < len); // Since the decrypted text is smaller we must delete then insert GetDocument()->Change(mod_delforw, start_addr, len, NULL, 0, this); GetDocument()->Change(mod_insert, start_addr, outlen, buf, 0, this, TRUE); ASSERT(undo_.back().utype == undo_change); undo_.back().previous_too = true; // Merge changes (at least in this view) // Select encrypted data and save undo of selection SetSel(addr2pos(start_addr), addr2pos(start_addr+outlen)); // Inform the user in case they don't notice the selection has been decreased CString mess; mess.Format("Decryption decreased the selection length by %ld bytes", long(len-outlen)); ((CMainFrame *)AfxGetMainWnd())->StatusBarText(mess); } else GetDocument()->Change(mod_replace, start_addr, len, buf, 0, this); } } else { // Note that CryptoAPI algs (above) the key is set when password // or alg is changed (more efficient) but for internal we set it here // in case other internal use (security) has changed the current key ::set_key(aa->password_, aa->password_.GetLength()); // Make sure selection is right size if ((end_addr-start_addr)%8 != 0) { // Presumably in macro playback ASSERT(aa->playing_); AfxMessageBox("The selection is not a multiple of 8 (encryption block length)"); aa->mac_error_ = 10; return; } CWaitCursor wait; // Turn on wait cursor (hourglass) size_t len; // Length of selection // Note: for internal alg. we don't break the decryption up and write // to temp file to handle huge selections as above (yet?) // Get memory for selection and read it from the document try { if (end_addr - start_addr > UINT_MAX) throw std::bad_alloc(); len = size_t(end_addr - start_addr); buf = new unsigned char[len]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); aa->mac_error_ = 10; return; } VERIFY(GetDocument()->GetData(buf, len, start_addr) == len); ::decrypt(buf, len); GetDocument()->Change(mod_replace, start_addr, len, buf, 0, this); } DisplayCaret(); aa->SaveToMacro(km_encrypt, 2); // 2 == decrypt (1 == encrypt) func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnUpdateEncrypt(CCmdUI* pCmdUI) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) pCmdUI->Enable(FALSE); else if (aa->algorithm_ == 0) { // Internal algorithm must encrypt mult. of 8 bytes (Blow Fish has 64 bit block length) pCmdUI->Enable((end_addr-start_addr)%8 == 0); } } void CHexEditView::OnCompress() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *in_data = NULL; unsigned char *out_data = NULL; // Check if file is read-only and ask user if they want to turn this off if (check_ro("compress")) return; // Check if in OVR mode and ask the user if they want to turn this off if (display_.overtype) { if (AfxMessageBox("Compression will change the selection length\r" "which is not allowed in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 10; return; } else if (!do_insert()) return; } // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); // Make sure there is a selection if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("There is no selection to compress"); theApp.mac_error_ = 10; return; } // Initialise structure used to communicate with the zlib routines z_stream zs; int level = Z_DEFAULT_COMPRESSION; if (theApp.GetProfileInt("Options", "ZlibCompressionDVLevel", 1) == 0) level = theApp.GetProfileInt("Options", "ZlibCompressionLevel", level); ASSERT(level == Z_DEFAULT_COMPRESSION || (level >= 1 && level <= 9)); int windowBits = 15; if (theApp.GetProfileInt("Options", "ZlibCompressionDVWindow", 1) == 0) windowBits = theApp.GetProfileInt("Options", "ZlibCompressionWindow", windowBits); ASSERT(windowBits >= 8 && windowBits <= 15); switch (theApp.GetProfileInt("Options", "ZlibCompressionHeaderType", 1)) { case 0: // raw (no header) windowBits = - windowBits; break; case 2: // gzip header windowBits += 16; break; default: ASSERT(0); case 1: break; } int memLevel = 8; if (theApp.GetProfileInt("Options", "ZlibCompressionDVMemory", 1) == 0) memLevel = theApp.GetProfileInt("Options", "ZlibCompressionMemory", memLevel); ASSERT(memLevel >= 1 && memLevel <= 9); int strategy = theApp.GetProfileInt("Options", "ZlibCompressionStrategy", Z_DEFAULT_STRATEGY); ASSERT( strategy == Z_DEFAULT_STRATEGY || strategy == Z_FILTERED || strategy == Z_HUFFMAN_ONLY || strategy == Z_RLE || strategy == Z_FIXED ); zs.zalloc = (alloc_func)0; zs.zfree = (free_func)0; zs.opaque = (voidpf)0; // VERIFY(deflateInit(&zs, Z_DEFAULT_COMPRESSION) == Z_OK); VERIFY(deflateInit2(&zs, level, Z_DEFLATED, // only method currently supported by zlib windowBits, memLevel, strategy ) == Z_OK); // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && GetDocument()->DataFileSlotFree()) { CWaitCursor wait; // Turn on wait cursor (hourglass) int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) // Create a "temp" file to store the compressed data // (This file stores the compressed data until the document is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); // Get input and output buffers size_t len, inbuflen = size_t(min(32768, end_addr - start_addr)), outbuflen = max(inbuflen/2, 256); // Work out no of input blocks per sync int sync_every = (theApp.GetProfileInt("Options", "ZlibCompressionSync", 0)*1024)/inbuflen; FILE_ADDRESS total_out = 0; int err; try { in_data = new unsigned char[inbuflen]; out_data = new unsigned char[outbuflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { int flush; if (sync_every > 0 && (curr - start_addr)/inbuflen % sync_every == sync_every - 1) // time to sync? flush = Z_FULL_FLUSH; else flush = Z_NO_FLUSH; // Get the next buffer full from the document len = size_t(min(inbuflen, end_addr - curr)); VERIFY(GetDocument()->GetData(in_data, len, curr) == len); // Compress this buffer zs.next_in = in_data; zs.avail_in = len; do { zs.next_out = out_data; zs.avail_out = outbuflen; err = deflate(&zs, flush); ASSERT(err == Z_OK); // Write to "temp" file ff.Write(out_data, outbuflen - zs.avail_out); total_out += outbuflen - zs.avail_out; // we need to keep track of this ourselves since zs.total_out can overflow } while (zs.avail_out == 0); ASSERT(zs.avail_in == 0); if (AbortKeyPress() && AfxMessageBox("Abort compression?", MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } // Process any residual data do { zs.next_out = out_data; zs.avail_out = outbuflen; err = deflate(&zs, Z_FINISH); ASSERT(err == Z_OK || err == Z_STREAM_END); ff.Write(out_data, outbuflen - zs.avail_out); total_out += outbuflen - zs.avail_out; } while (err == Z_OK); ASSERT(err == Z_STREAM_END); } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the uncompressed block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); // Add the temp file to the document idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); GetDocument()->Change(mod_insert_file, start_addr, total_out, NULL, idx, this, TRUE); // Select compressed data SetSel(addr2pos(start_addr), addr2pos(start_addr + total_out)); // Inform the user about the amount of compression CString mess; mess.Format("Compressed %d%%", int((1.0 - double(total_out)/(end_addr - start_addr))*100.0 + 0.5)); mm->StatusBarText(mess); } else { // Allocate memory block and compress into it // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot compress such a large selection. \n" "Please save the file to free \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and compressing such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) try { // Get buffer for data, get the data, and get buffer for compressed data in_data = new unsigned char[size_t(end_addr - start_addr)]; size_t got = GetDocument()->GetData(in_data, size_t(end_addr - start_addr), start_addr); ASSERT(got == size_t(end_addr - start_addr)); // Remove uncompressed data from the document GetDocument()->Change(mod_delforw, start_addr, got, NULL, 0, this); size_t outbuflen = max(got/2, 256); out_data = new unsigned char[outbuflen]; FILE_ADDRESS curr = start_addr; int err; // return value from inflate (normally Z_OK or Z_STREAM_END) zs.next_in = in_data; zs.avail_in = got; do { zs.next_out = out_data; zs.avail_out = outbuflen; err = deflate(&zs, Z_FINISH); ASSERT(err == Z_OK || err == Z_STREAM_END); // Replace the selection with the compressed data if (outbuflen - zs.avail_out > 0) GetDocument()->Change(mod_insert, curr, outbuflen - zs.avail_out, out_data, 0, this, TRUE); curr += outbuflen - zs.avail_out; } while (err == Z_OK); ASSERT(err == Z_STREAM_END); // Select compressed block SetSel(addr2pos(start_addr), addr2pos(start_addr+zs.total_out)); // Inform the user about the amount of compression CString mess; mess.Format("Compressed %d%%", int((1.0 - double(zs.total_out)/got)*100.0 + 0.5)); mm->StatusBarText(mess); } catch (std::bad_alloc) { // Note: this exception may come from ZLIB AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; // Undo changes already made (but make sure we don't record undo in macros) OnEditUndo(); if (theApp.recording_ && theApp.mac_.size() > 0 && (theApp.mac_.back()).ktype == km_undo) theApp.mac_.pop_back(); goto func_return; } } VERIFY(deflateEnd(&zs) == Z_OK); DisplayCaret(); theApp.SaveToMacro(km_compress, 1); // 1 = compress (2 = decompress) func_return: mm->Progress(-1); // disable progress bar if (in_data != NULL) delete[] in_data; if (out_data != NULL) delete[] out_data; } void CHexEditView::OnDecompress() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *in_data = NULL; unsigned char *out_data = NULL; // Check if file is read-only and ask user if they want to turn this off if (check_ro("decompress")) return; // Check if in OVR mode and ask the user if they want to turn this off if (display_.overtype) { if (AfxMessageBox("Decompression will change the selection length\r" "which is not allowed in overtype mode.\r" "Do you want to turn off overtype mode?", MB_OKCANCEL) == IDCANCEL) { theApp.mac_error_ = 10; return; } else if (!do_insert()) return; } // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); // Make sure there is a selection if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("There is no selection to decompress"); theApp.mac_error_ = 10; return; } // Initialise structure used to communicate with the zlib routines z_stream zs; zs.zalloc = (alloc_func)0; zs.zfree = (free_func)0; zs.opaque = (voidpf)0; zs.next_in = (Bytef*)0; zs.avail_in = 0; // VERIFY(inflateInit(&zs) == Z_OK); int windowBits = 15; if (theApp.GetProfileInt("Options", "ZlibCompressionDVWindow", 1) == 0) windowBits = theApp.GetProfileInt("Options", "ZlibCompressionWindow", windowBits); ASSERT(windowBits >= 8 && windowBits <= 15); switch (theApp.GetProfileInt("Options", "ZlibCompressionHeaderType", 1)) { case 0: // raw (no header) windowBits = - windowBits; // assume no header break; default: ASSERT(0); case 1: case 2: windowBits += 32; // auto detect header type break; } VERIFY(inflateInit2(&zs, windowBits ) == Z_OK); // Test if selection is too big to do in memory (Note that even a small selection can expand greatly) if (end_addr - start_addr > (2*1024*1024) && GetDocument()->DataFileSlotFree()) { CWaitCursor wait; // Turn on wait cursor (hourglass) int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) // Create a "temp" file to store the compressed data // (This file stores the compressed data until the document is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); // Get input and output buffers size_t len, outbuflen = size_t(min(32768, end_addr - start_addr)), inbuflen = max(outbuflen/4, 256); FILE_ADDRESS total_out = 0; int err = Z_OK; try { in_data = new unsigned char[inbuflen]; out_data = new unsigned char[outbuflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); // For each chunk of the currently selected block for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(inbuflen, end_addr - curr)); VERIFY(GetDocument()->GetData(in_data, len, curr) == len); zs.next_in = in_data; zs.avail_in = len; do { // Prepare output buffer zs.next_out = out_data; zs.avail_out = outbuflen; if (err == Z_DATA_ERROR) { // We must still be trying to sync from previously encountered data error err = inflateSync(&zs); } else { err = inflate(&zs, Z_NO_FLUSH); ASSERT(err == Z_OK || err == Z_STREAM_END || err == Z_DATA_ERROR || err == Z_BUF_ERROR); // Note Z_BUF_ERROR can occur when zs.avail_out == 0 (and zs.avail_in after previous call was zero). // This is not a fatal error and according to the docs we should continue looping while zs.avail_in == 0. if (err == Z_DATA_ERROR) { theApp.mac_error_ = 5; if (AfxMessageBox("The compression data is corrupted. \n" "HexEdit can save the data decompressed \n" "so far and attempt to recover from \n" "this error but some data will be lost. \n\n" "Do you want to continue?", MB_YESNO) != IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Continue reading the data checking for sync point (see inflateSync call above) } ff.Write(out_data, outbuflen - zs.avail_out); // write all that we got total_out += outbuflen - zs.avail_out; // we need to keep track of this ourselves since zs.total_out can overflow } } while (zs.avail_out == 0 || zs.avail_in != 0); // if output buffer is full there may be more if (AbortKeyPress() && AfxMessageBox("Abort decompression?", MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } ASSERT(err == Z_STREAM_END || err == Z_DATA_ERROR); ASSERT(ff.GetLength() == total_out); if (err == Z_DATA_ERROR) { AfxMessageBox("HexEdit did not recover from \n" "the compression data error. "); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } if (total_out == 0) { // This could happen if there were data errors remove(temp_file); theApp.mac_error_ = 5; goto func_return; } // Delete the input (compressed) block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, this); // Add the temp file to the document idx = GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); GetDocument()->Change(mod_insert_file, start_addr, total_out, NULL, idx, this, TRUE); // Select uncompressed block SetSel(addr2pos(start_addr), addr2pos(start_addr + total_out)); // Inform the user about the amount of compression CString mess; mess.Format("Expanded by %d%%", int((double(total_out)/(end_addr - start_addr) - 1.0)*100.0 + 0.5)); mm->StatusBarText(mess); } else { // Allocate memory block and decompress into it // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot decompress such a large selection. \n" "Please save the file to free \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and decompressing such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) try { // Get buffer for input data, get the data, and get buffer for output (decompressed) data in_data = new unsigned char[size_t(end_addr - start_addr)]; size_t got = GetDocument()->GetData(in_data, size_t(end_addr - start_addr), start_addr); ASSERT(got == size_t(end_addr - start_addr)); // Remove input (compressed) block from the document GetDocument()->Change(mod_delforw, start_addr, got, NULL, 0, this); size_t outbuflen = max(4*got, 256); out_data = new unsigned char[outbuflen]; FILE_ADDRESS curr = start_addr; // Current output address int err = Z_OK; // return value from inflate or inflateSync zs.next_in = in_data; zs.avail_in = got; do { zs.next_out = out_data; zs.avail_out = outbuflen; if (err == Z_DATA_ERROR) { // We must still be trying to sync from previously encountered data error err = inflateSync(&zs); } if (err != Z_DATA_ERROR) { err = inflate(&zs, Z_NO_FLUSH); ASSERT(err == Z_OK || err == Z_STREAM_END || err == Z_BUF_ERROR || err == Z_DATA_ERROR); if (err == Z_DATA_ERROR) { if (AfxMessageBox("The compression data is corrupted. \n" "HexEdit can attempt to recover from \n" "this error but some data will be lost. \n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 10; // Undo changes already (but make sure we don't record undo in macros) OnEditUndo(); if (theApp.recording_ && theApp.mac_.size() > 0 && (theApp.mac_.back()).ktype == km_undo) theApp.mac_.pop_back(); goto func_return; } } // Add the decompressed data block to the file if (outbuflen - zs.avail_out > 0) GetDocument()->Change(mod_insert, curr, outbuflen - zs.avail_out, out_data, 0, this, TRUE); curr += outbuflen - zs.avail_out; } } while (zs.avail_out == 0 || zs.avail_in != 0); ASSERT(err == Z_STREAM_END); // Select uncompressed block SetSel(addr2pos(start_addr), addr2pos(start_addr+zs.total_out)); // Inform the user about the amount of compression CString mess; mess.Format("Expanded by %d%%", int((double(zs.total_out)/got - 1.0)*100.0 + 0.5)); mm->StatusBarText(mess); } catch (std::bad_alloc) { // Note this exception may come from ZLIB AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; // Undo changes already made (but make sure we don't record undo in macros) OnEditUndo(); if (theApp.recording_ && theApp.mac_.size() > 0 && (theApp.mac_.back()).ktype == km_undo) theApp.mac_.pop_back(); goto func_return; } } VERIFY(inflateEnd(&zs) == Z_OK); DisplayCaret(); theApp.SaveToMacro(km_compress, 2); // 2 = decompress (1 = compress) func_return: mm->Progress(-1); // disable progress bar if (in_data != NULL) delete[] in_data; if (out_data != NULL) delete[] out_data; } // Enable commands that depend simply on a non-zero selection void CHexEditView::OnUpdateSelNZ(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); pCmdUI->Enable(start_addr < end_addr); } // The following functions are used as update handlers // They enable their corresponding UI handlers if there are // enough bytes between the current address and the end of file void CHexEditView::OnUpdateByte(CCmdUI* pCmdUI) { pCmdUI->Enable(GetPos() < GetDocument()->length()); } void CHexEditView::OnUpdate16bit(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) // No selection so only enable if enough before EOF (2 bytes) pCmdUI->Enable(start_addr + 1 < GetDocument()->length()); else // Else make sure selection is multiple of 2 pCmdUI->Enable((end_addr - start_addr)%2 == 0); } void CHexEditView::OnUpdate32bit(CCmdUI* pCmdUI) { // pCmdUI->Enable(GetPos() + 3 < GetDocument()->length()); FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) // No selection so only enable if enough before EOF (4 bytes) pCmdUI->Enable(start_addr + 3 < GetDocument()->length()); else // Else make sure selection is multiple of 4 pCmdUI->Enable((end_addr - start_addr)%4 == 0); } void CHexEditView::OnUpdate64bit(CCmdUI* pCmdUI) { // pCmdUI->Enable(GetPos() + 7 < GetDocument()->length()); FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) // No selection so only enable if enough before EOF (8 bytes) pCmdUI->Enable(start_addr + 7 < GetDocument()->length()); else // Else make sure selection is multiple of 8 pCmdUI->Enable((end_addr - start_addr)%8 == 0); } // These update handlers are similar to the above but for binary operations // As binary operations use the current value from the calculator we also need // to ensure that the current operand size in the calculator is not too big. void CHexEditView::OnUpdateByteBinary(CCmdUI* pCmdUI) { if (((CMainFrame *)AfxGetMainWnd())->m_wndCalc.ByteSize() > 1) { pCmdUI->Enable(FALSE); return; } OnUpdateByte(pCmdUI); } void CHexEditView::OnUpdate16bitBinary(CCmdUI* pCmdUI) { if (((CMainFrame *)AfxGetMainWnd())->m_wndCalc.ByteSize() > 2) { pCmdUI->Enable(FALSE); return; } OnUpdate16bit(pCmdUI); } void CHexEditView::OnUpdate32bitBinary(CCmdUI* pCmdUI) { if (((CMainFrame *)AfxGetMainWnd())->m_wndCalc.ByteSize() > 4) { pCmdUI->Enable(FALSE); return; } OnUpdate32bit(pCmdUI); } void CHexEditView::OnUpdate64bitBinary(CCmdUI* pCmdUI) { if (((CMainFrame *)AfxGetMainWnd())->m_wndCalc.ByteSize() > 8) { ASSERT(0); // Max size is 8 at present pCmdUI->Enable(FALSE); return; } OnUpdate64bit(pCmdUI); } template<class T> void DoChecksum(CHexEditView *pv, checksum_type op, LPCSTR desc) { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection pv->GetSelAddr(start_addr, end_addr); if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(theApp.playing_); CString mess; mess.Format("There is no selection to calculate %s on", desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } if (op >= CHECKSUM_8 && op < 10 && (end_addr - start_addr)%sizeof(T) != 0) { // Selection is wrong length, presumably in macro playback ASSERT(theApp.playing_); CString mess; mess.Format("The selection must be a multiple of %d for %s", sizeof(T), desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } ASSERT(start_addr < pv->GetDocument()->length()); // Get a buffer - fairly large for efficiency size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } ASSERT(buf != NULL); T val; void * hh; switch (op) { case CHECKSUM_CRC16: hh = crc_16_init(); break; case CHECKSUM_CRC_CCITT: hh = crc_ccitt_init(); break; case CHECKSUM_CRC_CCITT_B: hh = crc_ccitt_b_init(); break; case CHECKSUM_CRC_XMODEM: hh = crc_xmodem_init(); break; case CHECKSUM_CRC32: hh = crc_32_init(); break; case CHECKSUM_8: case CHECKSUM_16: case CHECKSUM_32: case CHECKSUM_64: val = 0; break; default: ASSERT(0); } for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); VERIFY(pv->GetDocument()->GetData(buf, len, curr) == len); switch (op) { case CHECKSUM_8: case CHECKSUM_16: case CHECKSUM_32: case CHECKSUM_64: ASSERT(len % sizeof(T) == 0); { T *pp, *endp = (T *)(buf + len); for (pp = (T *)buf; pp < endp; ++pp) val += *pp; } break; case CHECKSUM_CRC16: crc_16_update(hh, buf, len); break; case CHECKSUM_CRC_CCITT: crc_ccitt_update(hh, buf, len); break; case CHECKSUM_CRC_CCITT_B: crc_ccitt_b_update(hh, buf, len); break; case CHECKSUM_CRC_XMODEM: crc_xmodem_update(hh, buf, len); break; case CHECKSUM_CRC32: crc_32_update(hh, buf, len); break; } if (AbortKeyPress() && AfxMessageBox("Abort calculation?", MB_YESNO) == IDYES) { theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } switch (op) { case CHECKSUM_CRC16: val = T(crc_16_final(hh)); break; case CHECKSUM_CRC_CCITT: val = T(crc_ccitt_final(hh)); break; case CHECKSUM_CRC_CCITT_B: val = T(crc_ccitt_b_final(hh)); break; case CHECKSUM_CRC_XMODEM: val = T(crc_xmodem_final(hh)); break; case CHECKSUM_CRC32: val = T(crc_32_final(hh)); break; } // Get final CRC and store it in the calculator if (((CMainFrame *)AfxGetMainWnd())->m_wndCalc.ByteSize() < sizeof(T)) ((CMainFrame *)AfxGetMainWnd())->m_wndCalc.change_bits(sizeof(T)*8); ((CMainFrame *)AfxGetMainWnd())->m_wndCalc.Set(val); dynamic_cast<CMainFrame *>(::AfxGetMainWnd())->show_calc(); // make sure calc is displayed theApp.SaveToMacro(km_checksum, op); func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnChecksum8() { DoChecksum<unsigned char>(this, CHECKSUM_8, "8 bit Checksum"); } void CHexEditView::OnChecksum16() { DoChecksum<unsigned short>(this, CHECKSUM_16, "16 bit Checksum"); } void CHexEditView::OnChecksum32() { DoChecksum<unsigned long>(this, CHECKSUM_32, "32 bit Checksum"); } void CHexEditView::OnChecksum64() { DoChecksum<unsigned __int64>(this, CHECKSUM_64, "64 bit Checksum"); } void CHexEditView::OnCrc16() { DoChecksum<unsigned short>(this, CHECKSUM_CRC16, "CRC 16"); } void CHexEditView::OnCrcCcitt() { DoChecksum<unsigned short>(this, CHECKSUM_CRC_CCITT, "CRC CCITT"); } void CHexEditView::OnCrcCcittB() { DoChecksum<unsigned short>(this, CHECKSUM_CRC_CCITT_B, "CRC CCITT B"); } void CHexEditView::OnCrcXmodem() { DoChecksum<unsigned short>(this, CHECKSUM_CRC_XMODEM, "CRC XMODEM"); } void CHexEditView::OnCrc32() { DoChecksum<DWORD>(this, CHECKSUM_CRC32, "CRC 32"); } void CHexEditView::OnMd5() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("There is no selection to calculate MD5 on"); theApp.mac_error_ = 10; return; } ASSERT(start_addr < GetDocument()->length()); // Get a buffer - fairly large for efficiency size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } ASSERT(buf != NULL); struct MD5Context ctx; MD5Init(&ctx); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); MD5Update(&ctx, buf, len); if (AbortKeyPress() && AfxMessageBox("Abort MD5 calculation?", MB_YESNO) == IDYES) { theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } unsigned char digest[16]; MD5Final(digest, &ctx); { // Display MD5 value (when calculator can handle 128 bits we will put it there instead) CString ss, fmt; if (theApp.hex_ucase_) fmt = "MD5: %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X"; else fmt = "MD5: %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x"; ss.Format(fmt, digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]); AfxMessageBox(ss); } // Record in macro since we did it successfully theApp.SaveToMacro(km_checksum, CHECKSUM_MD5); func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnSha1() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection GetSelAddr(start_addr, end_addr); if (start_addr >= end_addr) { // No selection, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("There is no selection to calculate SHA1 on"); theApp.mac_error_ = 10; return; } ASSERT(start_addr < GetDocument()->length()); // Get a buffer - fairly large for efficiency size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; return; } ASSERT(buf != NULL); sha1_context ctx; sha1_starts(&ctx); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); VERIFY(GetDocument()->GetData(buf, len, curr) == len); sha1_update(&ctx, buf, len); if (AbortKeyPress() && AfxMessageBox("Abort SHA1 calculation?", MB_YESNO) == IDYES) { theApp.mac_error_ = 10; goto func_return; } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } unsigned char digest[20]; sha1_finish(&ctx, digest); { // Display SHA1 value (when calculator can handle 128 bits we will put it there instead) CString ss, fmt; if (theApp.hex_ucase_) fmt = "SHA1: %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X %2.2X%2.2X"; else fmt = "SHA1: %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x %2.2x%2.2x"; ss.Format(fmt, digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15], digest[16], digest[17], digest[18], digest[19]); AfxMessageBox(ss); } // Record in macro since we did it successfully theApp.SaveToMacro(km_checksum, CHECKSUM_SHA1); func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnUpdateByteNZ(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start_addr < end_addr ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else // ??? is start_addr < end_addr then pos must be less than EOF ??? pCmdUI->Enable(start_addr < end_addr && GetPos() < GetDocument()->length()); } void CHexEditView::OnUpdate16bitNZ(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start_addr < end_addr ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(end_addr > start_addr && (end_addr - start_addr)%2 == 0); } void CHexEditView::OnUpdate32bitNZ(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start_addr < end_addr ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(end_addr > start_addr && (end_addr - start_addr)%4 == 0); } void CHexEditView::OnUpdate64bitNZ(CCmdUI* pCmdUI) { FILE_ADDRESS start_addr, end_addr; // Current selection GetSelAddr(start_addr, end_addr); if (pCmdUI->m_pSubMenu != NULL) { // This happens when popup menu itself is drawn pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex, MF_BYPOSITION | (start_addr < end_addr ? MF_ENABLED : (MF_DISABLED | MF_GRAYED))); } else pCmdUI->Enable(end_addr > start_addr && (end_addr - start_addr)%8 == 0); } template<class T> void ProcBinary(CHexEditView *pv, T val, T *buf, size_t count, binop_type op, int &div0) { for (size_t ii = 0; ii < count; ++ii) { // Reverse byte order if using big-endian if (pv->BigEndian()) ::flip_bytes((unsigned char *)&buf[ii], sizeof(T)); switch (op) { case binop_add: buf[ii] += val; break; case binop_subtract: buf[ii] -= val; break; case binop_subtract_x: buf[ii] = val - buf[ii]; break; case binop_multiply: buf[ii] *= val; break; case binop_divide: ASSERT(val != 0); buf[ii] /= val; break; case binop_divide_x: if (buf[ii] != 0) buf[ii] = val / buf[ii]; else ++div0; break; case binop_mod: ASSERT(val != 0); buf[ii] %= val; break; case binop_mod_x: if (buf[ii] != 0) buf[ii] = val % buf[ii]; else ++div0; break; case binop_and: buf[ii] &= val; break; case binop_or: buf[ii] |= val; break; case binop_xor: buf[ii] ^= val; break; // Signed/unsigned comparisons are differentiated by type of T passed to the template function case binop_gtr: case binop_gtr_unsigned: if (val > buf[ii]) buf[ii] = val; break; case binop_less: case binop_less_unsigned: if (val < buf[ii]) buf[ii] = val; break; case binop_rol: // T must be unsigned type for zero fill in >> { int tmp = int(val) % (sizeof(T)*8); buf[ii] = (buf[ii] << tmp) | (buf[ii] >> (sizeof(T)*8 - tmp)); } break; case binop_ror: // T must be unsigned type for zero fill in >> { int tmp = int(val) % (sizeof(T)*8); buf[ii] = (buf[ii] >> tmp) | (buf[ii] << (sizeof(T)*8 - tmp)); } break; case binop_lsl: buf[ii] <<= int(val); break; case binop_lsr: // T must be unsigned type for zero fill case binop_asr: // T must be signed type for sign to be extended buf[ii] >>= int(val); break; default: ASSERT(0); } // Reverse byte order back again before putting back to the file if (pv->BigEndian()) ::flip_bytes((unsigned char *)&buf[ii], sizeof(T)); } } // Perform binary operations (where the 2nd operand is taken from the calculator). // [This is used to replace numerous other functions (OnAddByte, OnXor64Bit etc).] // T = template parameter specifying size of operand (1,2,4 or 8 byte integer) // pv = pointer to the view (we had to do this as VC6 does not support member templates) // op = operation to perform // desc = describes the operations and operand size for use in error messages // dummy = determines template operand type (should not be nec. except for VC6 template bugs) template<class T> void OnOperateBinary(CHexEditView *pv, binop_type op, LPCSTR desc, T dummy) { (void)dummy; // The dummy param. makes sure we get the right template (VC++ 6 bug) CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; ASSERT(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8); if (pv->check_ro(desc)) return; if (mm->m_wndCalc.ByteSize() > sizeof(T)) { ASSERT(theApp.playing_); // This should only happen during playback since commands are disabled otherwise CString mess; mess.Format("Can't %s unless operand (calculator) is %d bytes or less", desc, sizeof(T)); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } // Get current address of selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection pv->GetSelAddr(start_addr, end_addr); // If no selection just do one if (start_addr >= end_addr) { end_addr = start_addr + sizeof(T); if (end_addr > pv->GetDocument()->length()) { // Not enough bytes before EOF, presumably in macro playback ASSERT(theApp.playing_); CString mess; mess.Format("Insufficient bytes before EOF to %s", desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } } // Make sure selection is a multiple of the data type length if ((end_addr - start_addr) % sizeof(T) != 0) { ASSERT(theApp.playing_); CString mess; mess.Format("Selection must be a multiple of %d bytes to %s", sizeof(T), desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } ASSERT(start_addr < end_addr && end_addr <= pv->GetDocument()->length()); // Get the other operand from the calculator T val = T(mm->m_wndCalc.GetValue()); // Check for calculator val of zero causing divide by zero if (val == 0 && (op == binop_divide || op == binop_mod)) { CString mess; mess.Format("Calculator value is zero (causing divide by 0) while performing %s", desc); AfxMessageBox(mess); theApp.mac_error_ = 5; return; } int div0 = 0; // Count of divide by zero errors (for binop_divide_x and binop_mod_x) // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && pv->GetDocument()->DataFileSlotFree()) { int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) // Create a file to store the resultant data // (Temp file used by the document until it is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); // Get data buffer size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); VERIFY(pv->GetDocument()->GetData(buf, len, curr) == len); ProcBinary(pv, val, (T *)buf, len/sizeof(T), op, div0); ff.Write(buf, len); if (AbortKeyPress()) { CString mess; mess.Format("Abort %s operation?", desc); if (AfxMessageBox(mess, MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the unprocessed block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. pv->GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, pv); // Add the temp file to the document idx = pv->GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); pv->GetDocument()->Change(mod_insert_file, start_addr, end_addr - start_addr, NULL, idx, pv, TRUE); } else { // Allocate memory block and process it // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot operate on such a large selection. \n" "Please save the file to deallocate \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and operating on such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) try { buf = new unsigned char[size_t(end_addr - start_addr)]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } size_t got = pv->GetDocument()->GetData(buf, size_t(end_addr - start_addr), start_addr); ASSERT(got == size_t(end_addr - start_addr)); ProcBinary(pv, val, (T *)buf, got/sizeof(T), op, div0); pv->GetDocument()->Change(mod_replace, start_addr, got, (unsigned char *)buf, 0, pv); } if (div0 > 0) { // Tell the user about divide by zero errors CString mess; mess.Format("There were %d divide by zero errors while performing %s", int(div0), desc); AfxMessageBox(mess); theApp.mac_error_ = 5; } pv->DisplayCaret(); { static int bit_pos[8] = {0, 1, -1, 2, -1, -1, -1, 3}; ASSERT(sizeof(T)-1 < 8 && bit_pos[sizeof(T)-1] != -1); // size must be 1,2,4,8 giving bit_pos of 0,1,2,3 theApp.SaveToMacro(km_op_binary, (op<<8)|bit_pos[sizeof(T)-1]); } func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnAddByte() { ::OnOperateBinary<char>(this, binop_add, "Add bytes", char(0)); } void CHexEditView::OnAdd16bit() { ::OnOperateBinary<short>(this, binop_add, "Add words", short(0)); } void CHexEditView::OnAdd32bit() { ::OnOperateBinary<long>(this, binop_add, "Add double words", long(0)); } void CHexEditView::OnAdd64bit() { ::OnOperateBinary<__int64>(this, binop_add, "Add quad words", __int64(0)); } void CHexEditView::OnSubtractByte() { ::OnOperateBinary<char>(this, binop_subtract, "Subtract bytes", char(0)); } void CHexEditView::OnSubtract16bit() { ::OnOperateBinary<short>(this, binop_subtract, "Subtract words", short(0)); } void CHexEditView::OnSubtract32bit() { ::OnOperateBinary<long>(this, binop_subtract, "Subtract double words", long(0)); } void CHexEditView::OnSubtract64bit() { ::OnOperateBinary<__int64>(this, binop_subtract, "Subtract quad words", __int64(0)); } void CHexEditView::OnAndByte() { ::OnOperateBinary<char>(this, binop_and, "AND bytes", char(0)); } void CHexEditView::OnAnd16bit() { ::OnOperateBinary<short>(this, binop_and, "AND words", short(0)); } void CHexEditView::OnAnd32bit() { ::OnOperateBinary<long>(this, binop_and, "AND double words", long(0)); } void CHexEditView::OnAnd64bit() { ::OnOperateBinary<__int64>(this, binop_and, "AND quad words", __int64(0)); } void CHexEditView::OnOrByte() { ::OnOperateBinary<char>(this, binop_or, "OR bytes", char(0)); } void CHexEditView::OnOr16bit() { ::OnOperateBinary<short>(this, binop_or, "OR words", short(0)); } void CHexEditView::OnOr32bit() { ::OnOperateBinary<long>(this, binop_or, "OR double words", long(0)); } void CHexEditView::OnOr64bit() { ::OnOperateBinary<__int64>(this, binop_or, "OR quad words", __int64(0)); } void CHexEditView::OnXorByte() { ::OnOperateBinary<char>(this, binop_xor, "XOR bytes", char(0)); } void CHexEditView::OnXor16bit() { ::OnOperateBinary<short>(this, binop_xor, "XOR words", short(0)); } void CHexEditView::OnXor32bit() { ::OnOperateBinary<long>(this, binop_xor, "XOR double words", long(0)); } void CHexEditView::OnXor64bit() { ::OnOperateBinary<__int64>(this, binop_xor, "XOR quad words", __int64(0)); } void CHexEditView::OnMulByte() { ::OnOperateBinary<unsigned char>(this, binop_multiply, "multiply bytes", unsigned char(0)); } void CHexEditView::OnMul16bit() { ::OnOperateBinary<unsigned short>(this, binop_multiply, "multiply words", unsigned short(0)); } void CHexEditView::OnMul32bit() { ::OnOperateBinary<unsigned long>(this, binop_multiply, "multiply double words", unsigned long(0)); } void CHexEditView::OnMul64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_multiply, "multiply quad words", unsigned __int64(0)); } void CHexEditView::OnDivByte() { ::OnOperateBinary<unsigned char>(this, binop_divide, "divide bytes", unsigned char(0)); } void CHexEditView::OnDiv16bit() { ::OnOperateBinary<unsigned short>(this, binop_divide, "divide words", unsigned short(0)); } void CHexEditView::OnDiv32bit() { ::OnOperateBinary<unsigned long>(this, binop_divide, "divide double words", unsigned long(0)); } void CHexEditView::OnDiv64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_divide, "divide quad words", unsigned __int64(0)); } void CHexEditView::OnModByte() { ::OnOperateBinary<unsigned char>(this, binop_mod, "modulus bytes", unsigned char(0)); } void CHexEditView::OnMod16bit() { ::OnOperateBinary<unsigned short>(this, binop_mod, "modulus words", unsigned short(0)); } void CHexEditView::OnMod32bit() { ::OnOperateBinary<unsigned long>(this, binop_mod, "modulus double words", unsigned long(0)); } void CHexEditView::OnMod64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_mod, "modulus quad words", unsigned __int64(0)); } void CHexEditView::OnSubtractXByte() { ::OnOperateBinary<char>(this, binop_subtract_x, "Subtract bytes", char(0)); } void CHexEditView::OnSubtractX16bit() { ::OnOperateBinary<short>(this, binop_subtract_x, "Subtract words", short(0)); } void CHexEditView::OnSubtractX32bit() { ::OnOperateBinary<long>(this, binop_subtract_x, "Subtract double words", long(0)); } void CHexEditView::OnSubtractX64bit() { ::OnOperateBinary<__int64>(this, binop_subtract_x, "Subtract quad words", __int64(0)); } void CHexEditView::OnDivXByte() { ::OnOperateBinary<unsigned char>(this, binop_divide_x, "divide bytes", unsigned char(0)); } void CHexEditView::OnDivX16bit() { ::OnOperateBinary<unsigned short>(this, binop_divide_x, "divide words", unsigned short(0)); } void CHexEditView::OnDivX32bit() { ::OnOperateBinary<unsigned long>(this, binop_divide_x, "divide double words", unsigned long(0)); } void CHexEditView::OnDivX64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_divide_x, "divide quad words", unsigned __int64(0)); } void CHexEditView::OnModXByte() { ::OnOperateBinary<unsigned char>(this, binop_mod_x, "modulus bytes", unsigned char(0)); } void CHexEditView::OnModX16bit() { ::OnOperateBinary<unsigned short>(this, binop_mod_x, "modulus words", unsigned short(0)); } void CHexEditView::OnModX32bit() { ::OnOperateBinary<unsigned long>(this, binop_mod_x, "modulus double words", unsigned long(0)); } void CHexEditView::OnModX64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_mod_x, "modulus quad words", unsigned __int64(0)); } void CHexEditView::OnGtrByte() { ::OnOperateBinary<signed char>(this, binop_gtr, "finding greater of bytes", signed char(0)); } void CHexEditView::OnGtr16bit() { ::OnOperateBinary<short>(this, binop_gtr, "finding greater of words", short(0)); } void CHexEditView::OnGtr32bit() { ::OnOperateBinary<long>(this, binop_gtr, "finding greater of double words", long(0)); } void CHexEditView::OnGtr64bit() { ::OnOperateBinary<__int64>(this, binop_gtr, "finding greater of quad words", __int64(0)); } void CHexEditView::OnLessByte() { ::OnOperateBinary<signed char>(this, binop_less, "finding lesser of bytes", signed char(0)); } void CHexEditView::OnLess16bit() { ::OnOperateBinary<short>(this, binop_less, "finding lesser of words", short(0)); } void CHexEditView::OnLess32bit() { ::OnOperateBinary<long>(this, binop_less, "finding lesser of double words", long(0)); } void CHexEditView::OnLess64bit() { ::OnOperateBinary<__int64>(this, binop_less, "finding lesser of quad words", __int64(0)); } void CHexEditView::OnGtrUByte() { ::OnOperateBinary<unsigned char>(this, binop_gtr_unsigned, "finding unsigned greater of bytes", unsigned char(0)); } void CHexEditView::OnGtrU16bit() { ::OnOperateBinary<unsigned short>(this, binop_gtr_unsigned, "finding unsigned greater of words", unsigned short(0)); } void CHexEditView::OnGtrU32bit() { ::OnOperateBinary<unsigned long>(this, binop_gtr_unsigned, "finding unsigned greater of double words", unsigned long(0)); } void CHexEditView::OnGtrU64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_gtr_unsigned, "finding unsigned greater of quad words", unsigned __int64(0)); } void CHexEditView::OnLessUByte() { ::OnOperateBinary<unsigned char>(this, binop_less_unsigned, "finding unsigned lesser of bytes", unsigned char(0)); } void CHexEditView::OnLessU16bit() { ::OnOperateBinary<unsigned short>(this, binop_less_unsigned, "finding unsigned lesser of words", unsigned short(0)); } void CHexEditView::OnLessU32bit() { ::OnOperateBinary<unsigned long>(this, binop_less_unsigned, "finding unsigned lesser of double words", unsigned long(0)); } void CHexEditView::OnLessU64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_less_unsigned, "finding unsigned lesser of quad words", unsigned __int64(0)); } void CHexEditView::OnRolByte() { ::OnOperateBinary<unsigned char>(this, binop_rol, "rotate left bytes", unsigned char(0)); } void CHexEditView::OnRol16bit() { ::OnOperateBinary<unsigned short>(this, binop_rol, "rotate left words", unsigned short(0)); } void CHexEditView::OnRol32bit() { ::OnOperateBinary<unsigned long>(this, binop_rol, "rotate left double words", unsigned long(0)); } void CHexEditView::OnRol64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_rol, "rotate left quad words", unsigned __int64(0)); } void CHexEditView::OnRorByte() { ::OnOperateBinary<unsigned char>(this, binop_ror, "rotate right bytes", unsigned char(0)); } void CHexEditView::OnRor16bit() { ::OnOperateBinary<unsigned short>(this, binop_ror, "rotate right words", unsigned short(0)); } void CHexEditView::OnRor32bit() { ::OnOperateBinary<unsigned long>(this, binop_ror, "rotate right double words", unsigned long(0)); } void CHexEditView::OnRor64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_ror, "rotate right quad words", unsigned __int64(0)); } void CHexEditView::OnLslByte() { ::OnOperateBinary<char>(this, binop_lsl, "shift left bytes", char(0)); } void CHexEditView::OnLsl16bit() { ::OnOperateBinary<short>(this, binop_lsl, "shift left words", short(0)); } void CHexEditView::OnLsl32bit() { ::OnOperateBinary<long>(this, binop_lsl, "shift left double words", long(0)); } void CHexEditView::OnLsl64bit() { ::OnOperateBinary<__int64>(this, binop_lsl, "shift left quad words", __int64(0)); } void CHexEditView::OnLsrByte() { ::OnOperateBinary<unsigned char>(this, binop_lsr, "shift right bytes", unsigned char(0)); } void CHexEditView::OnLsr16bit() { ::OnOperateBinary<unsigned short>(this, binop_lsr, "shift right words", unsigned short(0)); } void CHexEditView::OnLsr32bit() { ::OnOperateBinary<unsigned long>(this, binop_lsr, "shift right double words", unsigned long(0)); } void CHexEditView::OnLsr64bit() { ::OnOperateBinary<unsigned __int64>(this, binop_lsr, "shift right quad words", unsigned __int64(0)); } void CHexEditView::OnAsrByte() { ::OnOperateBinary<signed char>(this, binop_asr, "arithmetic shift right bytes", signed char(0)); } void CHexEditView::OnAsr16bit() { ::OnOperateBinary<short>(this, binop_asr, "arithmetic shift right words", short(0)); } void CHexEditView::OnAsr32bit() { ::OnOperateBinary<long>(this, binop_asr, "arithmetic shift right double words", long(0)); } void CHexEditView::OnAsr64bit() { ::OnOperateBinary<__int64>(this, binop_asr, "arithmetic shift right quad words", __int64(0)); } template<class T> void ProcUnary(CHexEditView *pv, T val, T *buf, size_t count, unary_type op) { // Operate on all the selected values for (size_t ii = 0; ii < count; ++ii) { // Reverse if big endian and the operation calls for it. if (pv->BigEndian() && op != unary_flip) ::flip_bytes((unsigned char *)&buf[ii], sizeof(T)); switch (op) { case unary_at: buf[ii] = val; break; case unary_sign: buf[ii] = -buf[ii]; break; case unary_inc: ++buf[ii]; if (buf[ii] == 0) { ((CMainFrame *)AfxGetMainWnd())->StatusBarText("Warning: Increment wrapped around to zero"); theApp.mac_error_ = 1; // Signal warning on wrap } break; case unary_dec: buf[ii]--; if (buf[ii] == -1) { ((CMainFrame *)AfxGetMainWnd())->StatusBarText("Warning: Decrement wrapped past zero"); theApp.mac_error_ = 1; // Signal warning on wrap } break; case unary_not: ASSERT(sizeof(T) == 1); // Only need to perform NOT on bytes buf[ii] = ~buf[ii]; break; case unary_flip: ASSERT(sizeof(T) > 1); // No point in flipping a single byte // Do nothing here (let ::flip_bytes below handle it) break; case unary_rev: { T result = 0; T tmp = buf[ii]; for (int jj = 0; jj < sizeof(T)*8; ++jj) { result <<= 1; // Make room for the next bit if (tmp & 0x1) result |= 0x1; tmp >>= 1; // Move bits down to test the next } buf[ii] = result; } break; case unary_rand: ASSERT(sizeof(T) == 1); // Only really need random bytes buf[ii] = T(::rand_good()>>16); break; case unary_rand_fast: ASSERT(sizeof(T) == 1); // Only really need random bytes buf[ii] = T(::rand()>>7); break; default: ASSERT(0); } if (pv->BigEndian() || op == unary_flip) ::flip_bytes((unsigned char *)&buf[ii], sizeof(T)); } } // Perform unary operations on the selection // [This is used to replace numerous other functions (OnIncByte, OnFlip64Bit etc).] // T = template parameter specifying size of operand (1,2,4 or 8 byte integer) // op = operation to perform // desc = describes the operations and operand size for use in error messages template<class T> void OnOperateUnary(CHexEditView *pv, unary_type op, LPCSTR desc, T dummy) { (void)dummy; // The dummy param. makes sure we get the right template (VC++ 6 bug) CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); unsigned char *buf = NULL; ASSERT(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8); if (pv->check_ro(desc)) return; T val = 0; // For assign operation we get the value from calc if (op == unary_at) { val = T(mm->m_wndCalc.GetValue()); // prefetch the value // Make sure the operand is not too big if (mm->m_wndCalc.ByteSize() > sizeof(T)) { ASSERT(theApp.playing_); // This should only happen during playback since commands are disabled otherwise CString mess; mess.Format("Can't %s unless operand (calculator) is %d bytes or less", desc, sizeof(T)); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } } // Get current address or selection FILE_ADDRESS start_addr, end_addr; // Start and end of selection pv->GetSelAddr(start_addr, end_addr); // If no selection just do one if (start_addr >= end_addr) { end_addr = start_addr + sizeof(T); if (end_addr > pv->GetDocument()->length()) { // Not enough bytes before EOF, presumably in macro playback ASSERT(theApp.playing_); CString mess; mess.Format("Insufficient bytes before EOF to %s", desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } } // Make sure selection is a multiple of the data type length if ((end_addr - start_addr) % sizeof(T) != 0) { ASSERT(theApp.playing_); CString mess; mess.Format("Selection must be a multiple of %d bytes to %s", sizeof(T), desc); AfxMessageBox(mess); theApp.mac_error_ = 10; return; } ASSERT(start_addr < end_addr && end_addr <= pv->GetDocument()->length()); // Test if selection is too big to do in memory if (end_addr - start_addr > (16*1024*1024) && pv->GetDocument()->DataFileSlotFree()) { int idx = -1; // Index into docs data_file_ array (or -1 if no slots avail.) // Create a file to store the resultant data // (Temp file used by the document until it is closed or written to disk.) char temp_dir[_MAX_PATH]; char temp_file[_MAX_PATH]; ::GetTempPath(sizeof(temp_dir), temp_dir); ::GetTempFileName(temp_dir, _T("_HE"), 0, temp_file); // Get data buffer size_t len, buflen = size_t(min(4096, end_addr - start_addr)); try { buf = new unsigned char[buflen]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } try { CFile64 ff(temp_file, CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary); for (FILE_ADDRESS curr = start_addr; curr < end_addr; curr += len) { // Get the next buffer full from the document len = size_t(min(buflen, end_addr - curr)); if (op != unary_at) // We don't need to get old value if assigning VERIFY(pv->GetDocument()->GetData(buf, len, curr) == len); ProcUnary(pv, val, (T *)buf, len/sizeof(T), op); ff.Write(buf, len); if (AbortKeyPress()) { CString mess; mess.Format("Abort %s operation?", desc); if (AfxMessageBox(mess, MB_YESNO) == IDYES) { ff.Close(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } } mm->Progress(int(((curr - start_addr)*100)/(end_addr - start_addr))); } } catch (CFileException *pfe) { AfxMessageBox(::FileErrorMessage(pfe, CFile::modeWrite)); pfe->Delete(); remove(temp_file); theApp.mac_error_ = 10; goto func_return; } // Delete the unprocessed block that is to be replaced // Note: this must be done before AddDataFile otherwise Change() (via regenerate()) will delete the temp file. pv->GetDocument()->Change(mod_delforw, start_addr, end_addr - start_addr, NULL, 0, pv); // Add the temp file to the document idx = pv->GetDocument()->AddDataFile(temp_file, TRUE); ASSERT(idx != -1); pv->GetDocument()->Change(mod_insert_file, start_addr, end_addr - start_addr, NULL, idx, pv, TRUE); } else { // Allocate memory block and process it // Error if ran out of temp file handles and file is too big if (end_addr - start_addr > UINT_MAX) // why is there no SIZE_T_MAX? { AfxMessageBox("HexEdit is out of temporary files and \n" "cannot operate on such a large selection. \n" "Please save the file to deallocate \n" "temporary file handles and try again.\n", MB_OK); theApp.mac_error_ = 10; return; } // Warn if we might cause memory exhaustion if (end_addr - start_addr > 128*1024*1024) // 128 Mb file may be too big { if (AfxMessageBox("WARNING: HexEdit is out of temporary file \n" "handles and operating on such a large selection \n" "may cause memory exhaustion. Please click NO \n" "and save the file to free handles. \n" "Or, click YES to continue.\n\n" "Do you want to continue?", MB_YESNO) != IDYES) { theApp.mac_error_ = 5; return; } } CWaitCursor wait; // Turn on wait cursor (hourglass) try { buf = new unsigned char[size_t(end_addr - start_addr)]; } catch (std::bad_alloc) { AfxMessageBox("Insufficient memory"); theApp.mac_error_ = 10; goto func_return; } size_t got; if (op != unary_at) // We don't need to get old value if assigning { got = pv->GetDocument()->GetData(buf, size_t(end_addr - start_addr), start_addr); ASSERT(got == size_t(end_addr - start_addr)); } else got = size_t(end_addr - start_addr); ProcUnary(pv, val, (T *)buf, got/sizeof(T), op); pv->GetDocument()->Change(mod_replace, start_addr, got, (unsigned char *)buf, 0, pv); } pv->DisplayCaret(); { static int bit_pos[8] = {0, 1, -1, 2, -1, -1, -1, 3}; ASSERT(sizeof(T)-1 < 8 && bit_pos[sizeof(T)-1] != -1); // size must be 1,2,4,8 giving bit_pos of 0,1,2,3 theApp.SaveToMacro(km_op_unary, (op<<8)|bit_pos[sizeof(T)-1]); } func_return: mm->Progress(-1); // disable progress bar if (buf != NULL) delete[] buf; } void CHexEditView::OnIncByte() { ::OnOperateUnary<char>(this, unary_inc, "increment bytes", char(0)); } void CHexEditView::OnInc16bit() { ::OnOperateUnary<short>(this, unary_inc, "increment words", short(0)); } void CHexEditView::OnInc32bit() { ::OnOperateUnary<long>(this, unary_inc, "increment double words", long(0)); } void CHexEditView::OnInc64bit() { ::OnOperateUnary<__int64>(this, unary_inc, "increment quad words", __int64(0)); } void CHexEditView::OnDecByte() { ::OnOperateUnary<char>(this, unary_dec, "decrement bytes", char(0)); } void CHexEditView::OnDec16bit() { ::OnOperateUnary<short>(this, unary_dec, "decrement words", short(0)); } void CHexEditView::OnDec32bit() { ::OnOperateUnary<long>(this, unary_dec, "decrement double words", long(0)); } void CHexEditView::OnDec64bit() { ::OnOperateUnary<__int64>(this, unary_dec, "decrement quad words", __int64(0)); } void CHexEditView::OnRevByte() { ::OnOperateUnary<char>(this, unary_rev, "reverse bits of bytes", char(0)); } void CHexEditView::OnRev16bit() { ::OnOperateUnary<short>(this, unary_rev, "reverse bits of words", short(0)); } void CHexEditView::OnRev32bit() { ::OnOperateUnary<long>(this, unary_rev, "reverse bits of double words", long(0)); } void CHexEditView::OnRev64bit() { ::OnOperateUnary<__int64>(this, unary_rev, "reverse bits of quad words", __int64(0)); } // There is NO OnFlipByte (since it would not do anything) void CHexEditView::OnFlip16bit() { ::OnOperateUnary<short>(this, unary_flip, "flip bytes of words", short(0)); } void CHexEditView::OnFlip32bit() { ::OnOperateUnary<long>(this, unary_flip, "flip bytes of double words", long(0)); } void CHexEditView::OnFlip64bit() { ::OnOperateUnary<__int64>(this, unary_flip, "flip bytes of quad words", __int64(0)); } void CHexEditView::OnInvert() { ::OnOperateUnary<char>(this, unary_not, "invert bits", char(0)); } void CHexEditView::OnNegByte() { ::OnOperateUnary<signed char>(this, unary_sign, "negate bytes", signed char(0)); } void CHexEditView::OnNeg16bit() { ::OnOperateUnary<short>(this, unary_sign, "negate words", short(0)); } void CHexEditView::OnNeg32bit() { ::OnOperateUnary<long>(this, unary_sign, "negate double words", long(0)); } void CHexEditView::OnNeg64bit() { ::OnOperateUnary<__int64>(this, unary_sign, "negate quad words", __int64(0)); } void CHexEditView::OnAssignByte() { ::OnOperateUnary<char>(this, unary_at, "assign bytes", char(0)); } void CHexEditView::OnAssign16bit() { ::OnOperateUnary<short>(this, unary_at, "assign words", short(0)); } void CHexEditView::OnAssign32bit() { ::OnOperateUnary<long>(this, unary_at, "assign double words", long(0)); } void CHexEditView::OnAssign64bit() { ::OnOperateUnary<__int64>(this, unary_at, "assign quad words", __int64(0)); } void CHexEditView::OnSeedCalc() { unsigned long seed = unsigned long(((CMainFrame *)AfxGetMainWnd())->m_wndCalc.GetValue()); srand(seed); // Seed compiler PRNG (simple one) rand_good_seed(seed); // Seed our own PRNG theApp.SaveToMacro(km_seed, 1); } void CHexEditView::OnSeedRandom() { unsigned long seed = ::GetTickCount(); srand(seed); // Seed compiler PRNG (simple fast one) rand_good_seed(seed); // Seed our own PRNG theApp.SaveToMacro(km_seed); } void CHexEditView::OnRandByte() { ::OnOperateUnary<char>(this, unary_rand, "randomize bytes", char(0)); } void CHexEditView::OnRandFast() { ::OnOperateUnary<char>(this, unary_rand_fast, "fast randomize bytes", char(0)); } // The display of views in tabs and split windows is complicated, mainly because the BCG tab view class // behaves very differently from a splitter (eg is derived from CView). // Currently we need to show 3 types of views: CHexEditView (normal hex view), CDataFormatView (template), // and CAerialView (bitmap overview). There is also a CHexTabView that just contains one or more other views. // * The child frame has a splitter called "splitter_" // - there is always at least one pane so at least one view // - if there is only one pane then it contains the tab view // * One of the splits is always a tab view called "ptv_" in the child frame // - if the window has not been split this is the only view // - this may be the 2nd split (since the first one can be template view) // * The tab view always contains the hex view but may also have tabs for the other views // - the left most tab is always the hex view // - the tabs are not shown if there is just one view (the hex view) // * The template and aerial views are either not shown, in a pane of the splitter or in a tab view // // In the code below we often store the index of a view in the splitter or in the tab view using this convention: // snum_t = index of tab view in the splitter (currently only 0 or 1) // snum_d = index of DFFD (template) view in the left splitter (currently only 0 or -1) // snum_a = index of aerial view in the right splitter (currently only 1, 2 or -1) // tnum_d = index of DFFD (template) view in the tab view (currently -1, 1 or 2) // tnum_a = index of aerial view in the tab view (currently -1, 1 or 2) // where -1 indicates the view is not present // Note tnum_h is not required as the hex view is always the left (0) view in the tab view void CHexEditView::ShowDffd() { if (pdfv_ == NULL) OnDffdSplit(); } void CHexEditView::OnDffdHide() { if (pdfv_ == NULL) return; // already hidden int snum_d = GetFrame()->splitter_.FindViewColumn(pdfv_->GetSafeHwnd()); int tnum_d = GetFrame()->ptv_->FindTab(pdfv_->GetSafeHwnd()); ASSERT(snum_d > -1 || tnum_d > -1); // It must be open in tab or splitter pdfv_ = NULL; if (snum_d > -1) // splitter? { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_d, split_width_d_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_d, TRUE)); GetFrame()->splitter_.RecalcLayout(); } else if (tnum_d > -1) // tab? { GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing tree view VERIFY(GetFrame()->ptv_->RemoveView(tnum_d)); } } void CHexEditView::OnUpdateDffdHide(CCmdUI* pCmdUI) { //pCmdUI->Enable(TRUE); pCmdUI->SetCheck(TemplateViewType() == 0); } void CHexEditView::OnDffdSplit() { if (DoDffdSplit()) pdfv_->SendMessage(WM_INITIALUPDATE); } bool CHexEditView::DoDffdSplit() { //if (pdfv_ == GetFrame()->splitter_.GetPane(0, 0)) if (TemplateViewType() == 1) return false; // already open in splitter // If open then it is open in a tab - close it if (pdfv_ != NULL) { int tnum_d = GetFrame()->ptv_->FindTab(pdfv_->GetSafeHwnd()); ASSERT(tnum_d > -1); pdfv_ = NULL; GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing tree view if (tnum_d > -1) VERIFY(GetFrame()->ptv_->RemoveView(tnum_d)); } // Reopen in the splitter CCreateContext ctxt; ctxt.m_pNewViewClass = RUNTIME_CLASS(CDataFormatView); ctxt.m_pCurrentDoc = GetDocument(); ctxt.m_pLastView = this; ctxt.m_pCurrentFrame = GetFrame(); CHexEditSplitter *psplitter = &(GetFrame()->splitter_); ASSERT(psplitter->m_hWnd != 0); // Make sure width of splitter window is OK CRect rr; GetFrame()->GetClientRect(&rr); if (split_width_d_ < 10 || split_width_d_ > rr.Width()) { split_width_d_ = rr.Width()/3; if (split_width_d_ < 10) split_width_d_ = 10; } // Add tree view in left splitter column VERIFY(psplitter->InsColumn(0, split_width_d_, 10, RUNTIME_CLASS(CDataFormatView), &ctxt)); psplitter->SetActivePane(0, 1); // make hex (tab) view active = now in col 1 pdfv_ = (CDataFormatView *)psplitter->GetPane(0, 0); ASSERT_KINDOF(CDataFormatView, pdfv_); // Make sure dataformat view knows which hex view it is assoc. with pdfv_->phev_ = this; psplitter->RecalcLayout(); AdjustColumns(); return true; } void CHexEditView::OnUpdateDffdSplit(CCmdUI* pCmdUI) { pCmdUI->SetCheck(TemplateViewType() == 1); pCmdUI->Enable(GetDocument()->ptree_ != NULL); } void CHexEditView::OnDffdTab() { if (DoDffdTab()) pdfv_->SendMessage(WM_INITIALUPDATE); } bool CHexEditView::DoDffdTab() { if (TemplateViewType() == 2) return false; // already open in tab // Close DFFD view in split window if there is one if (pdfv_ != NULL) { int snum_d = GetFrame()->splitter_.FindViewColumn(pdfv_->GetSafeHwnd()); ASSERT(snum_d > -1); pdfv_ = NULL; if (snum_d > -1) { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_d, split_width_d_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_d, TRUE)); GetFrame()->splitter_.RecalcLayout(); } } // Reopen in the tab CHexTabView *ptv = GetFrame()->ptv_; int tnum_d = ptv->AddView(RUNTIME_CLASS (CDataFormatView), _T("Template (Tree) View")); ptv->SetActiveView(tnum_d); pdfv_ = (CDataFormatView *)ptv->GetActiveView(); ASSERT_KINDOF(CDataFormatView, pdfv_); // Make sure dataformat view knows which hex view it is assoc. with pdfv_->phev_ = this; ptv->SetActiveView(0); return true; } void CHexEditView::OnUpdateDffdTab(CCmdUI* pCmdUI) { pCmdUI->SetCheck(TemplateViewType() == 2); pCmdUI->Enable(GetDocument()->ptree_ != NULL); } // public function that just says how the template is displayed int CHexEditView::TemplateViewType() const { if (pdfv_ == NULL) return 0; else if (GetFrame()->splitter_.FindViewColumn(pdfv_->GetSafeHwnd()) > -1) return 1; else if (GetFrame()->ptv_->FindTab(pdfv_->GetSafeHwnd()) > -1) return 2; else { ASSERT(FALSE); return 0; } } // Aerial View commands void CHexEditView::OnAerialHide() { if (pav_ == NULL) return; // already hidden int snum_a = GetFrame()->splitter_.FindViewColumn(pav_->GetSafeHwnd()); int tnum_a = GetFrame()->ptv_->FindTab(pav_->GetSafeHwnd()); ASSERT(snum_a > -1 || tnum_a > -1); // It must be open in tab or splitter // Set pav_ to NULL now to avoid the view getting messages while invalid pav_ = NULL; GetDocument()->RemoveAerialView(); if (snum_a > -1) // splitter? { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_a, split_width_a_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_a, TRUE)); GetFrame()->splitter_.RecalcLayout(); } else if (tnum_a > -1) // tab? { GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing aerial view VERIFY(GetFrame()->ptv_->RemoveView(tnum_a)); } } void CHexEditView::OnUpdateAerialHide(CCmdUI* pCmdUI) { //pCmdUI->Enable(TRUE); pCmdUI->SetCheck(AerialViewType() == 0); } void CHexEditView::OnAerialSplit() { DoAerialSplit(); } bool CHexEditView::DoAerialSplit(bool init /*=true*/) { int snum_a; if (pav_ != NULL && (snum_a = GetFrame()->splitter_.FindViewColumn(pav_->GetSafeHwnd())) > -1) { if (GetFrame()->splitter_.ColWidth(snum_a) < 8) AdjustColumns(); return false; // already open in splitter } CAerialView * pSaved = pav_; // Save this so we can delete tab view after open in split view pav_ = NULL; // Reopen in the splitter CCreateContext ctxt; ctxt.m_pNewViewClass = RUNTIME_CLASS(CAerialView); ctxt.m_pCurrentDoc = GetDocument(); ctxt.m_pLastView = this; ctxt.m_pCurrentFrame = GetFrame(); CHexEditSplitter *psplitter = &(GetFrame()->splitter_); ASSERT(psplitter->m_hWnd != 0); // Make sure width of splitter window is OK CRect rr; GetFrame()->GetClientRect(&rr); if (split_width_a_ < 8 || split_width_a_ > rr.Width()) { split_width_a_ = rr.Width()/3; if (split_width_a_ < 8) split_width_a_ = 8; } // Add aerial view column to the right of hex (tab) view column int snum_t = GetFrame()->splitter_.FindViewColumn(GetFrame()->ptv_->GetSafeHwnd()); VERIFY(psplitter->InsColumn(snum_t + 1, split_width_a_, 8, RUNTIME_CLASS(CAerialView), &ctxt)); psplitter->SetActivePane(0, snum_t); // make hex view active pav_ = (CAerialView *)psplitter->GetPane(0, snum_t + 1); ASSERT_KINDOF(CAerialView, pav_); // Make sure aerial view knows which hex view it is assoc. with pav_->phev_ = this; psplitter->SetColumnInfo(snum_t, rr.Width() - split_width_a_, 10); psplitter->RecalcLayout(); AdjustColumns(); if (init) pav_->SendMessage(WM_INITIALUPDATE); // If open then it is open in a tab - close it if (pSaved != NULL) { int tnum_a = GetFrame()->ptv_->FindTab(pSaved->GetSafeHwnd()); ASSERT(tnum_a > -1); GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing aerial view if (tnum_a > -1) VERIFY(GetFrame()->ptv_->RemoveView(tnum_a)); GetDocument()->RemoveAerialView(); } return true; } void CHexEditView::OnUpdateAerialSplit(CCmdUI* pCmdUI) { pCmdUI->SetCheck(AerialViewType() == 1); } void CHexEditView::OnAerialTab() { DoAerialTab(); } bool CHexEditView::DoAerialTab(bool init /*=true*/) { if (pav_ != NULL && GetFrame()->ptv_->FindTab(pav_->GetSafeHwnd()) > -1) return false; CAerialView *pSaved = pav_; // Save this so we can delete the tab view after open in split view pav_ = NULL; // Reopen in the tab CHexTabView *ptv = GetFrame()->ptv_; int tnum_a = ptv->AddView(RUNTIME_CLASS (CAerialView), _T("Aerial View")); ASSERT(tnum_a > 0); if (tnum_a == -1) return false; ptv->SetActiveView(tnum_a); pav_ = (CAerialView *)ptv->GetActiveView(); ASSERT_KINDOF(CAerialView, pav_); // Make sure aerial view knows which hex view it is assoc. with pav_->phev_ = this; ptv->SetActiveView(0); if (init) pav_->SendMessage(WM_INITIALUPDATE); // Close Aerial view in split window if there is one if (pSaved != NULL) { int snum_a = GetFrame()->splitter_.FindViewColumn(pSaved->GetSafeHwnd()); ASSERT(snum_a > 0); // Should be there (not -1) and not the left one (not 0) if (snum_a > -1) { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_a, split_width_a_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_a, TRUE)); GetFrame()->splitter_.RecalcLayout(); GetDocument()->RemoveAerialView(); } } return true; } void CHexEditView::OnUpdateAerialTab(CCmdUI* pCmdUI) { pCmdUI->SetCheck(AerialViewType() == 2); } // public functiom that just says how we are displaying the aerial view int CHexEditView::AerialViewType() const { if (pav_ == NULL) return 0; else if (GetFrame()->splitter_.FindViewColumn(pav_->GetSafeHwnd()) > -1) return 1; else if (GetFrame()->ptv_->FindTab(pav_->GetSafeHwnd()) > -1) return 2; else { ASSERT(FALSE); return 0; } } // Compare View commands void CHexEditView::OnCompHide() { if (pcv_ == NULL) return; // already hidden int snum_c = GetFrame()->splitter_.FindViewColumn(pcv_->GetSafeHwnd()); int tnum_c = GetFrame()->ptv_->FindTab(pcv_->GetSafeHwnd()); pcv_ = NULL; // Clear it now to avoid getting errors by trying to use it when dead GetDocument()->RemoveCompView(); // compare window is detroyed directly (no WM_CLOSE) so we need this here ASSERT(snum_c > -1 || tnum_c > -1); // It must be open in tab or splitter if (snum_c > -1) // splitter? { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_c, split_width_c_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_c, TRUE)); GetFrame()->splitter_.RecalcLayout(); } else if (tnum_c > -1) // tab? { GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing compare view VERIFY(GetFrame()->ptv_->RemoveView(tnum_c)); } } void CHexEditView::OnUpdateCompHide(CCmdUI* pCmdUI) { //pCmdUI->Enable(TRUE); pCmdUI->SetCheck(CompViewType() == 0); } void CHexEditView::OnCompSplit() { DoCompSplit(); } bool CHexEditView::DoCompSplit(bool init /*=true*/) { int snum_c; if (pcv_ != NULL && (snum_c = GetFrame()->splitter_.FindViewColumn(pcv_->GetSafeHwnd())) > -1) { if (GetFrame()->splitter_.ColWidth(snum_c) < 8) AdjustColumns(); return false; // already open in splitter } // Make sure we have the name of the compare file to open if (!GetDocument()->GetCompareFile()) return false; // Save current view so we can close it later CCompareView * pSaved = pcv_; pcv_ = NULL; // Reopen in the splitter CCreateContext ctxt; ctxt.m_pNewViewClass = RUNTIME_CLASS(CCompareView); ctxt.m_pCurrentDoc = GetDocument(); ctxt.m_pLastView = this; ctxt.m_pCurrentFrame = GetFrame(); CHexEditSplitter *psplitter = &(GetFrame()->splitter_); ASSERT(psplitter->m_hWnd != 0); // Make sure width of splitter window is OK CRect rr; GetFrame()->GetClientRect(&rr); if (split_width_c_ < 8 || split_width_c_ > rr.Width()) { split_width_c_ = rr.Width()/3; if (split_width_c_ < 8) split_width_c_ = 8; } // Add compare view column to the right of hex (tab) view column int snum_t = GetFrame()->splitter_.FindViewColumn(GetFrame()->ptv_->GetSafeHwnd()); VERIFY(psplitter->InsColumn(snum_t + 1, split_width_c_, 8, RUNTIME_CLASS(CCompareView), &ctxt)); psplitter->SetActivePane(0, snum_t); // make hex view active pcv_ = (CCompareView *)psplitter->GetPane(0, snum_t + 1); ASSERT_KINDOF(CCompareView, pcv_); pcv_->phev_ = this; psplitter->SetColumnInfo(snum_t, rr.Width() - split_width_c_, 10); psplitter->RecalcLayout(); AdjustColumns(); // Make sure compare view knows which hex view it is assoc. with if (init) pcv_->SendMessage(WM_INITIALUPDATE); // If it was open in the tabbed view close that view if (pSaved != NULL) { int tnum_c = GetFrame()->ptv_->FindTab(pSaved->GetSafeHwnd()); ASSERT(tnum_c > -1); GetFrame()->ptv_->SetActiveView(0); // Make sure hex view (always view 0) is active before removing compare view if (tnum_c > -1) VERIFY(GetFrame()->ptv_->RemoveView(tnum_c)); GetDocument()->RemoveCompView(); // compare window is detroyed directly (no WM_CLOSE) so we need this here } return true; } void CHexEditView::OnUpdateCompSplit(CCmdUI* pCmdUI) { pCmdUI->SetCheck(CompViewType() == 1); } void CHexEditView::OnCompTab() { DoCompTab(); } bool CHexEditView::DoCompTab(bool init /*=true*/) { if (pcv_ != NULL && GetFrame()->ptv_->FindTab(pcv_->GetSafeHwnd()) > -1) return false; // already open in tab // Save current view so we can close it later CCompareView * pSaved = pcv_; pcv_ = NULL; // Make sure we have the name of the compare file to open if (!GetDocument()->GetCompareFile()) return false; // Reopen in the tab CHexTabView *ptv = GetFrame()->ptv_; int tnum_c = ptv->AddView(RUNTIME_CLASS (CCompareView), _T("Compare View")); ASSERT(tnum_c > 0); if (tnum_c == -1) return false; ptv->SetActiveView(tnum_c); pcv_ = (CCompareView *)ptv->GetActiveView(); ASSERT_KINDOF(CCompareView, pcv_); // Make sure compare view knows which hex view it is assoc. with pcv_->phev_ = this; ptv->SetActiveView(0); if (init) pcv_->SendMessage(WM_INITIALUPDATE); // Close Compare view in split window if there is one if (pSaved != NULL) { int snum_c = GetFrame()->splitter_.FindViewColumn(pSaved->GetSafeHwnd()); ASSERT(snum_c > 0); // Should be there (not -1) and not the left one (not 0) if (snum_c > -1) { int dummy; GetFrame()->splitter_.GetColumnInfo(snum_c, split_width_c_, dummy); // save split window width in case it is reopened VERIFY(GetFrame()->splitter_.DelColumn(snum_c, TRUE)); GetFrame()->splitter_.RecalcLayout(); GetDocument()->RemoveCompView(); // compare window is detroyed directly (no WM_CLOSE) so we need this here } } return true; } void CHexEditView::OnUpdateCompTab(CCmdUI* pCmdUI) { pCmdUI->SetCheck(CompViewType() == 2); } int CHexEditView::CompViewType() const { if (pcv_ == NULL) return 0; else if (GetFrame()->splitter_.FindViewColumn(pcv_->GetSafeHwnd()) > -1) return 1; else if (GetFrame()->ptv_->FindTab(pcv_->GetSafeHwnd()) > -1) return 2; else { ASSERT(FALSE); return 0; } } // private function which hopefully makes sure all the splitter columns are obvious (ie a min width) void CHexEditView::AdjustColumns() { int d, t, a, c, min; // Current width of dffd, tab, aerial, and compare columns d = t = a = c = -1; int snum_d, snum_t, snum_a, snum_c; snum_d = snum_t = snum_a = snum_c = -1; // Get current column widths CHexEditSplitter *psplitter = &(GetFrame()->splitter_); if (pdfv_ != NULL) snum_d = psplitter->FindViewColumn(pdfv_->GetSafeHwnd()); snum_t = psplitter->FindViewColumn(GetFrame()->ptv_->GetSafeHwnd()); // We always have a tab column since it contains the hex view if (pav_ != NULL) snum_a = psplitter->FindViewColumn(pav_->GetSafeHwnd()); if (pcv_ != NULL) snum_c = psplitter->FindViewColumn(pcv_->GetSafeHwnd()); if (snum_d > -1) psplitter->GetColumnInfo(snum_d, d, min); if (snum_t > -1) psplitter->GetColumnInfo(snum_t, t, min); if (snum_a > -1) psplitter->GetColumnInfo(snum_a, a, min); if (snum_c > -1) psplitter->GetColumnInfo(snum_c, c, min); // Make ideal widths slightly smaller but not less than a minimum bool adjust = false; d -= 20; if (snum_d > -1 && d < 20) { d = 20; adjust = true; } t -= 30; if (snum_t > -1 && t < 30) { t = 30; adjust = true; } a -= 10; if (snum_a > -1 && a < 10) { a = 10; adjust = true; } c -= 10; if (snum_c > -1 && c < 10) { c = 10; adjust = true; } if (adjust) { if (snum_d > -1) psplitter->SetColumnInfo(snum_d, d, 10); if (snum_t > -1) psplitter->SetColumnInfo(snum_t, t, 10); if (snum_a > -1) psplitter->SetColumnInfo(snum_a, a, 8); if (snum_c > -1) psplitter->SetColumnInfo(snum_c, c, 8); psplitter->RecalcLayout(); } if (snum_d > -1) psplitter->GetColumnInfo(snum_d, split_width_d_, min); if (snum_a > -1) psplitter->GetColumnInfo(snum_a, split_width_a_, min); if (snum_c > -1) psplitter->GetColumnInfo(snum_c, split_width_c_, min); } // Command to go to first recent difference in compare view void CHexEditView::OnCompFirst() { if (GetDocument()->CompareDifferences() > 0) { FILE_ADDRESS addr; int len; GetDocument()->GetOrigDiff(0, 0, addr, len); MoveToAddress(addr, addr+len); } } void CHexEditView::OnUpdateCompFirst(CCmdUI* pCmdUI) { pCmdUI->Enable(GetDocument()->CompareDifferences() > 0); } // Command to go to previous recent difference in compare view void CHexEditView::OnCompPrev() { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); int idx = GetDocument()->FirstDiffAt(false, 0, start - 1); if (idx > 0) { FILE_ADDRESS addr; int len; GetDocument()->GetOrigDiff(0, idx - 1, addr, len); MoveToAddress(addr, addr+len); } } void CHexEditView::OnUpdateCompPrev(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); pCmdUI->Enable(GetDocument()->CompareDifferences() >= 0 && GetDocument()->FirstDiffAt(false, 0, start - 1) > 0); } // Command to go to next recent difference in compare view void CHexEditView::OnCompNext() { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); int idx = GetDocument()->FirstDiffAt(false, 0, start); if (idx < GetDocument()->CompareDifferences(0)) { FILE_ADDRESS addr; int len; GetDocument()->GetOrigDiff(0, idx, addr, len); MoveToAddress(addr, addr+len); } } void CHexEditView::OnUpdateCompNext(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); pCmdUI->Enable(GetDocument()->CompareDifferences() >= 0 && GetDocument()->FirstDiffAt(false, 0, start) < GetDocument()->CompareDifferences()); } // Command to go to last recent difference in compare view void CHexEditView::OnCompLast() { int count = GetDocument()->CompareDifferences(); if (count > 0) { FILE_ADDRESS addr; int len; GetDocument()->GetOrigDiff(0, count - 1, addr, len); MoveToAddress(addr, addr+len); } } void CHexEditView::OnUpdateCompLast(CCmdUI* pCmdUI) { pCmdUI->Enable(GetDocument()->CompareDifferences() > 0); } // Command to go to first of all differences (not just recent) in compare view void CHexEditView::OnCompAllFirst() { FILE_ADDRESS addr; int len; GetDocument()->GetFirstDiffAll(addr, len); if (addr > -1) MoveToAddress(addr, addr+len); } void CHexEditView::OnUpdateCompAllFirst(CCmdUI* pCmdUI) { FILE_ADDRESS addr; int len; GetDocument()->GetFirstDiffAll(addr, len); pCmdUI->Enable(addr > -1); } void CHexEditView::OnCompAllPrev() { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); FILE_ADDRESS addr; int len; GetDocument()->GetPrevDiffAll(start - 1, addr, len); if (addr > -1) MoveToAddress(addr, addr+len); } void CHexEditView::OnUpdateCompAllPrev(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); FILE_ADDRESS addr; int len; GetDocument()->GetPrevDiffAll(start - 1, addr, len); pCmdUI->Enable(addr > -1); } void CHexEditView::OnCompAllNext() { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); FILE_ADDRESS addr; int len; GetDocument()->GetNextDiffAll(end, addr, len); if (addr > -1) MoveToAddress(addr, addr+len); } void CHexEditView::OnUpdateCompAllNext(CCmdUI* pCmdUI) { FILE_ADDRESS start, end; // current selection GetSelAddr(start, end); FILE_ADDRESS addr; int len; GetDocument()->GetNextDiffAll(end, addr, len); pCmdUI->Enable(addr > -1); } void CHexEditView::OnCompAllLast() { FILE_ADDRESS addr; int len; GetDocument()->GetLastDiffAll(addr, len); if (addr > -1) MoveToAddress(addr, addr+len); } void CHexEditView::OnUpdateCompAllLast(CCmdUI* pCmdUI) { FILE_ADDRESS addr; int len; GetDocument()->GetLastDiffAll(addr, len); pCmdUI->Enable(addr > -1); } void CHexEditView::OnCompAutoSync() { if (pcv_ == NULL) { AfxMessageBox("No Compare is available"); theApp.mac_error_ = 10; return; } begin_change(); display_.auto_sync_comp = !display_.auto_sync_comp; make_change(); end_change(); // If has been turned on then sync now if (display_.auto_sync_comp) { FILE_ADDRESS start_addr, end_addr; GetSelAddr(start_addr, end_addr); pcv_->MoveToAddress(start_addr, end_addr); } theApp.SaveToMacro(km_comp_sync, 2); } void CHexEditView::OnUpdateCompAutoSync(CCmdUI* pCmdUI) { pCmdUI->Enable(pcv_ != NULL); pCmdUI->SetCheck(display_.auto_sync_comp); } void CHexEditView::OnCompAutoScroll() { if (pcv_ == NULL) { AfxMessageBox("No Compare is available"); theApp.mac_error_ = 10; return; } begin_change(); display_.auto_scroll_comp = !display_.auto_scroll_comp; make_change(); end_change(); // If has been turned on then scroll now if (display_.auto_scroll_comp) pcv_->SetScroll(GetScroll()); theApp.SaveToMacro(km_comp_sync, 3); } void CHexEditView::OnUpdateCompAutoScroll(CCmdUI* pCmdUI) { pCmdUI->Enable(pcv_ != NULL); pCmdUI->SetCheck(display_.auto_scroll_comp); } // This is connected to Ctrl+T and is used for testing new dialogs etc void CHexEditView::OnViewtest() { // for testing new commands double dd = 65535.0; NumScale(dd); } CTipExpr::value_t CTipExpr::find_symbol(const char *sym, value_t parent, size_t index, int *pac, __int64 &sym_size, __int64 &sym_address, CString &) { ASSERT(pview_ != NULL); ASSERT(parent.typ == TYPE_NONE); // Parent is not used here value_t retval; retval.typ = TYPE_NONE; // Default to symbol not found retval.error = false; retval.int64 = 0; sym_address = pview_->tip_addr_; unsigned_ = false; CString sym_str(sym); if (sym_str.CompareNoCase("address") == 0) { retval.typ = TYPE_INT; // Just return the address retval.int64 = sym_address; sym_size = 4; // Addresses can be up to 8 but this restricts display to 32-bits (and if bigger then extra bits are shown) unsigned_ = true; } else if (sym_str.CompareNoCase("cursor") == 0) { FILE_ADDRESS start, end; pview_->GetSelAddr(start, end); retval.typ = TYPE_INT; retval.int64 = start; sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("sel_len") == 0) { FILE_ADDRESS start, end; pview_->GetSelAddr(start, end); retval.typ = TYPE_INT; retval.int64 = end - start; sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("mark") == 0) { retval.typ = TYPE_INT; retval.int64 = pview_->GetMark(); sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("eof") == 0) { retval.typ = TYPE_INT; retval.int64 = pview_->GetDocument()->length(); sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("sector") == 0) { retval.typ = TYPE_INT; // current sector int seclen = pview_->GetDocument()->GetSectorSize(); if (seclen > 0) retval.int64 = sym_address / seclen; else retval.int64 = 0; sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("offset") == 0) { retval.typ = TYPE_INT; // offset within current sector int seclen = pview_->GetDocument()->GetSectorSize(); if (seclen > 0) retval.int64 = sym_address % seclen; else retval.int64 = 0; sym_size = 4; unsigned_ = true; } else if (sym_str.CompareNoCase("sbyte") == 0) { signed char val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { retval.typ = TYPE_INT; // Just return the current byte retval.int64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("byte") == 0) { unsigned char val; if (pview_->GetDocument()->GetData(&val, sizeof(val), sym_address) == sizeof(val)) { retval.typ = TYPE_INT; // Just return the current byte retval.int64 = val; sym_size = sizeof(val); unsigned_ = true; } } else if (sym_str.CompareNoCase("word") == 0) { short val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("uword") == 0) { unsigned short val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); unsigned_ = true; } } else if (sym_str.CompareNoCase("dword") == 0) { long val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("udword") == 0) { unsigned long val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); unsigned_ = true; } } else if (sym_str.CompareNoCase("qword") == 0) { __int64 val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("uqword") == 0) { unsigned __int64 val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_INT; retval.int64 = val; sym_size = sizeof(val); unsigned_ = true; } } else if (sym_str.CompareNoCase("ieee32") == 0) { float val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_REAL; retval.real64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("ieee64") == 0) { double val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_REAL; retval.real64 = val; sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("ibm32") == 0) { unsigned char val[4]; if (pview_->GetDocument()->GetData(val, sizeof(val), sym_address) == sizeof(val)) { retval.typ = TYPE_REAL; retval.real64 = ::ibm_fp32(val, NULL, NULL, !pview_->BigEndian()); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("ibm64") == 0) { unsigned char val[8]; if (pview_->GetDocument()->GetData(val, sizeof(val), sym_address) == sizeof(val)) { retval.typ = TYPE_REAL; retval.real64 = ::ibm_fp64(val, NULL, NULL, !pview_->BigEndian()); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("real48") == 0) { unsigned char val[6]; if (pview_->GetDocument()->GetData(val, sizeof(val), sym_address) == sizeof(val)) { retval.typ = TYPE_REAL; retval.real64 = ::real48(val, NULL, NULL, pview_->BigEndian() == TRUE); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("time_t") == 0) { time_t val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_DATE; retval.date = FromTime_t(val); sym_size = sizeof(val); } } #ifdef TIME64_T else if (sym_str.CompareNoCase("time64_t") == 0) { __int64 val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_DATE; retval.date = FromTime_t(val); sym_size = sizeof(val); } } #endif else if (sym_str.CompareNoCase("time_t_80") == 0) // MSC 5.1 time_t { long val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_DATE; retval.date = FromTime_t_80(val); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("time_t_1899") == 0) // MSC 7 time_t { unsigned long val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_DATE; retval.date = FromTime_t_1899(val); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("time_t_mins") == 0) // MSC 7 time_t { long val; if (pview_->GetDocument()->GetData((unsigned char *)&val, sizeof(val), sym_address) == sizeof(val)) { if (pview_->BigEndian()) flip_bytes((unsigned char *)&val, sizeof(val)); retval.typ = TYPE_DATE; retval.date = FromTime_t_mins(val); sym_size = sizeof(val); } } else if (sym_str.CompareNoCase("astring") == 0) { char buf[256]; size_t len = pview_->GetDocument()->GetData((unsigned char *)buf, sizeof(buf)-1, sym_address); buf[len] = '\0'; retval.typ = TYPE_STRING; retval.pstr = new ExprStringType((LPCTSTR)buf); } size_ = int(sym_size); // Remember size of the symbol we encountered return retval; }
/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qqmlextensionplugin.h" QT_BEGIN_NAMESPACE /*! \since 4.7 \class QQmlExtensionPlugin \brief The QQmlExtensionPlugin class provides an abstract base for custom QML extension plugins. \ingroup plugins QQmlExtensionPlugin is a plugin interface that makes it possible to create QML extensions that can be loaded dynamically into QML applications. These extensions allow custom QML types to be made available to the QML engine. To write a QML extension plugin: \list \li Subclass QQmlExtensionPlugin, implement registerTypes() method to register types using qmlRegisterType(), and export the class using the Q_EXPORT_PLUGIN2() macro \li Write an appropriate project file for the plugin \li Create a \l{Writing a qmldir file}{qmldir file} to describe the plugin \endlist QML extension plugins can be used to provide either application-specific or library-like plugins. Library plugins should limit themselves to registering types, as any manipulation of the engine's root context may cause conflicts or other issues in the library user's code. \section1 An example Suppose there is a new \c TimeModel C++ class that should be made available as a new QML element. It provides the current time through \c hour and \c minute properties, like this: \snippet examples/declarative/cppextensions/plugins/plugin.cpp 0 \dots To make this class available as a QML type, create a plugin that registers this type with a specific \l {QML Modules}{module} using qmlRegisterType(). For this example the plugin module will be named \c com.nokia.TimeExample (as defined in the project file further below). \snippet examples/declarative/cppextensions/plugins/plugin.cpp plugin \codeline \snippet examples/declarative/cppextensions/plugins/plugin.cpp export This registers the \c TimeModel class with the 1.0 version of this plugin library, as a QML type called \c Time. The Q_ASSERT statement ensures the module is imported correctly by any QML components that use this plugin. The project file defines the project as a plugin library and specifies it should be built into the \c com/nokia/TimeExample directory: \code TEMPLATE = lib CONFIG += qt plugin QT += declarative DESTDIR = com/nokia/TimeExample TARGET = qmlqtimeexampleplugin ... \endcode Finally, a \l{Writing a qmldir file}{qmldir file} is required in the \c com/nokia/TimeExample directory that describes the plugin. This directory includes a \c Clock.qml file that should be bundled with the plugin, so it needs to be specified in the \c qmldir file: \quotefile examples/declarative/cppextensions/plugins/com/nokia/TimeExample/qmldir Once the project is built and installed, the new \c Time element can be used by any QML component that imports the \c com.nokia.TimeExample module: \snippet examples/declarative/cppextensions/plugins/plugins.qml 0 The full source code is available in the \l {declarative/cppextensions/plugins}{plugins example}. The \l {Tutorial: Writing QML extensions with C++} also contains a chapter on creating QML plugins. \sa QQmlEngine::importPlugin(), {How to Create Qt Plugins} */ /*! \fn void QQmlExtensionPlugin::registerTypes(const char *uri) Registers the QML types in the given \a uri. Subclasses should implement this to call qmlRegisterType() for all types which are provided by the extension plugin. The \a uri is an identifier for the plugin generated by the QML engine based on the name and path of the extension's plugin library. */ /*! Constructs a QML extension plugin with the given \a parent. Note that this constructor is invoked automatically by the Q_EXPORT_PLUGIN2() macro, so there is no need for calling it explicitly. */ QQmlExtensionPlugin::QQmlExtensionPlugin(QObject *parent) : QObject(parent) { } /*! \internal */ QQmlExtensionPlugin::~QQmlExtensionPlugin() { } /*! \fn void QQmlExtensionPlugin::initializeEngine(QQmlEngine *engine, const char *uri) Initializes the extension from the \a uri using the \a engine. Here an application plugin might, for example, expose some data or objects to QML, as context properties on the engine's root context. */ void QQmlExtensionPlugin::initializeEngine(QQmlEngine *engine, const char *uri) { Q_UNUSED(engine); Q_UNUSED(uri); } QT_END_NAMESPACE Remove refence to declarative in the docs Change-Id: I328edc6deee302440cf65de9f87e6b68c93f42b7 Reviewed-by: Martin Jones <d1da02505c7f228af82a23235becb435f45569f5@nokia.com> /**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qqmlextensionplugin.h" QT_BEGIN_NAMESPACE /*! \since 4.7 \class QQmlExtensionPlugin \brief The QQmlExtensionPlugin class provides an abstract base for custom QML extension plugins. \ingroup plugins QQmlExtensionPlugin is a plugin interface that makes it possible to create QML extensions that can be loaded dynamically into QML applications. These extensions allow custom QML types to be made available to the QML engine. To write a QML extension plugin: \list \li Subclass QQmlExtensionPlugin, implement registerTypes() method to register types using qmlRegisterType(), and export the class using the Q_EXPORT_PLUGIN2() macro \li Write an appropriate project file for the plugin \li Create a \l{Writing a qmldir file}{qmldir file} to describe the plugin \endlist QML extension plugins can be used to provide either application-specific or library-like plugins. Library plugins should limit themselves to registering types, as any manipulation of the engine's root context may cause conflicts or other issues in the library user's code. \section1 An example Suppose there is a new \c TimeModel C++ class that should be made available as a new QML element. It provides the current time through \c hour and \c minute properties, like this: \snippet examples/declarative/cppextensions/plugins/plugin.cpp 0 \dots To make this class available as a QML type, create a plugin that registers this type with a specific \l {QML Modules}{module} using qmlRegisterType(). For this example the plugin module will be named \c com.nokia.TimeExample (as defined in the project file further below). \snippet examples/declarative/cppextensions/plugins/plugin.cpp plugin \codeline \snippet examples/declarative/cppextensions/plugins/plugin.cpp export This registers the \c TimeModel class with the 1.0 version of this plugin library, as a QML type called \c Time. The Q_ASSERT statement ensures the module is imported correctly by any QML components that use this plugin. The project file defines the project as a plugin library and specifies it should be built into the \c com/nokia/TimeExample directory: \code TEMPLATE = lib CONFIG += qt plugin QT += qml DESTDIR = com/nokia/TimeExample TARGET = qmlqtimeexampleplugin ... \endcode Finally, a \l{Writing a qmldir file}{qmldir file} is required in the \c com/nokia/TimeExample directory that describes the plugin. This directory includes a \c Clock.qml file that should be bundled with the plugin, so it needs to be specified in the \c qmldir file: \quotefile examples/declarative/cppextensions/plugins/com/nokia/TimeExample/qmldir Once the project is built and installed, the new \c Time element can be used by any QML component that imports the \c com.nokia.TimeExample module: \snippet examples/declarative/cppextensions/plugins/plugins.qml 0 The full source code is available in the \l {declarative/cppextensions/plugins}{plugins example}. The \l {Tutorial: Writing QML extensions with C++} also contains a chapter on creating QML plugins. \sa QQmlEngine::importPlugin(), {How to Create Qt Plugins} */ /*! \fn void QQmlExtensionPlugin::registerTypes(const char *uri) Registers the QML types in the given \a uri. Subclasses should implement this to call qmlRegisterType() for all types which are provided by the extension plugin. The \a uri is an identifier for the plugin generated by the QML engine based on the name and path of the extension's plugin library. */ /*! Constructs a QML extension plugin with the given \a parent. Note that this constructor is invoked automatically by the Q_EXPORT_PLUGIN2() macro, so there is no need for calling it explicitly. */ QQmlExtensionPlugin::QQmlExtensionPlugin(QObject *parent) : QObject(parent) { } /*! \internal */ QQmlExtensionPlugin::~QQmlExtensionPlugin() { } /*! \fn void QQmlExtensionPlugin::initializeEngine(QQmlEngine *engine, const char *uri) Initializes the extension from the \a uri using the \a engine. Here an application plugin might, for example, expose some data or objects to QML, as context properties on the engine's root context. */ void QQmlExtensionPlugin::initializeEngine(QQmlEngine *engine, const char *uri) { Q_UNUSED(engine); Q_UNUSED(uri); } QT_END_NAMESPACE
#include "vtkExodusIIReader.h" #include "vtkExodusIICache.h" #include "vtkCellData.h" #include "vtkCellType.h" #include "vtkDataArray.h" #include "vtkDoubleArray.h" #include "vtkExodusModel.h" #include "vtkFloatArray.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkIntArray.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkSortDataArray.h" #include "vtkStdString.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkUnstructuredGrid.h" #include "vtkXMLParser.h" #include <vtkstd/algorithm> #include <vtkstd/vector> #include <vtkstd/map> #include "vtksys/SystemTools.hxx" #include "vtksys/RegularExpression.hxx" #include "exodusII.h" #include <stdio.h> #include <stdlib.h> /* for free() */ #include <string.h> /* for memset() */ #include <ctype.h> /* for toupper(), isgraph() */ #include <math.h> /* for cos() */ #ifdef EXODUSII_HAVE_MALLOC_H # include <malloc.h> #endif /* EXODUSII_HAVE_MALLOC_H */ #if defined(_WIN32) && !defined(__CYGWIN__) # define SNPRINTF _snprintf #else # define SNPRINTF snprintf #endif /// Define this to get printouts summarizing array glomming process #undef VTK_DBG_GLOM #define VTK_EXO_BLKSETID_NAME "BlockId" #define VTK_EXO_FUNC(funcall,errmsg)\ if ( (funcall) < 0 ) \ { \ vtkErrorMacro( errmsg ); \ return 1; \ } // ------------------------------------------------------------------- CONSTANTS static int obj_types[] = { EX_EDGE_BLOCK, EX_FACE_BLOCK, EX_ELEM_BLOCK, EX_NODE_SET, EX_EDGE_SET, EX_FACE_SET, EX_SIDE_SET, EX_ELEM_SET, EX_NODE_MAP, EX_EDGE_MAP, EX_FACE_MAP, EX_ELEM_MAP }; static int num_obj_types = (int)(sizeof(obj_types)/sizeof(obj_types[0])); static int obj_sizes[] = { EX_INQ_EDGE_BLK, EX_INQ_FACE_BLK, EX_INQ_ELEM_BLK, EX_INQ_NODE_SETS, EX_INQ_EDGE_SETS, EX_INQ_FACE_SETS, EX_INQ_SIDE_SETS, EX_INQ_ELEM_SETS, EX_INQ_NODE_MAP, EX_INQ_EDGE_MAP, EX_INQ_FACE_MAP, EX_INQ_ELEM_MAP, }; static const char* objtype_names[] = { "Edge block", "Face block", "Element block", "Node set", "Edge set", "Face set", "Side set", "Element set", "Node map", "Edge map", "Face map", "Element map" }; static const char* obj_typestr[] = { "L", "F", "E", "M", "D", "A", "S", "T", 0, /* maps have no result variables */ 0, 0, 0, }; #define OBJTYPE_IS_BLOCK(i) ((i>=0)&&(i<3)) #define OBJTYPE_IS_SET(i) ((i>2)&&(i<8)) #define OBJTYPE_IS_MAP(i) ((i>7)&&(i<12)) // Unlike obj* items above: // - conn* arrays only reference objects that generate connectivity information // - conn* arrays are ordered the way users expect the output (*not* the same as above) static int conn_types[] = { vtkExodusIIReader::ELEM_BLOCK_ELEM_CONN, vtkExodusIIReader::FACE_BLOCK_CONN, vtkExodusIIReader::EDGE_BLOCK_CONN, vtkExodusIIReader::ELEM_SET_CONN, vtkExodusIIReader::SIDE_SET_CONN, vtkExodusIIReader::FACE_SET_CONN, vtkExodusIIReader::EDGE_SET_CONN, vtkExodusIIReader::NODE_SET_CONN }; static int num_conn_types = (int)(sizeof(conn_types)/sizeof(conn_types[0])); // Given a conn_type index, what is its matching obj_type index? static int conn_obj_idx_cvt[] = { 2, 1, 0, 7, 6, 5, 4, 3 }; #define CONNTYPE_IS_BLOCK(i) ((i>=0)&&(i<3)) #define CONNTYPE_IS_SET(i) ((i>2)&&(i<8)) static const char* glomTypeNames[] = { "Scalar", "Vector2", "Vector3", "Symmetric Tensor", "Integration Point Values" }; // used to store pointer to ex_get_node_num_map or ex_get_elem_num_map: extern "C" { typedef int (*vtkExodusIIGetMapFunc)( int, int* ); } // ------------------------------------------------------------ XML PARSER CLASS class vtkExodusIIXMLParser : public vtkXMLParser { protected: vtkExodusIIReaderPrivate* Metadata; int InMaterialAssignment; public: static vtkExodusIIXMLParser* New(); vtkTypeRevisionMacro(vtkExodusIIXMLParser,vtkXMLParser); void Go( const char* xmlFileName, vtkExodusIIReaderPrivate* metadata ) { this->InMaterialAssignment = 0; if ( ! xmlFileName || ! metadata ) { vtkErrorMacro( "Must have a valid filename and metadata object to open XML file." ); } else { this->Metadata = metadata; //this->Metadata->Register( this ); this->SetFileName( xmlFileName ); this->Parse(); this->Metadata = 0; } } virtual vtkStdString GetPartNumber(int block) { return this->BlockIDToPartNumber[block]; } virtual vtkStdString GetPartDescription(int block) { return this->PartDescriptions[this->BlockIDToPartNumber[block]]; } virtual vtkStdString GetMaterialDescription(int block) { return this->MaterialDescriptions[this->BlockIDToPartNumber[block]]; } virtual vtkStdString GetMaterialSpecification(int block) { return this->MaterialSpecifications[this->BlockIDToPartNumber[block]]; } virtual vtkstd::vector<vtkStdString> GetAssemblyNumbers(int block) { return this->PartNumberToAssemblyNumbers[this->BlockIDToPartNumber[block]]; } virtual vtkstd::vector<vtkStdString> GetAssemblyDescriptions(int block) { return this->PartNumberToAssemblyDescriptions[this->BlockIDToPartNumber[block]]; } virtual int GetNumberOfHierarchyEntries() { return this->apbList.size(); } virtual vtkStdString GetHierarchyEntry(int num) { //since it's an STL list, we need to get the correct entry vtkstd::list<vtkStdString>::iterator iter=this->apbList.begin(); for(int i=0;i<num;i++) { iter++; } return (*iter); } virtual vtkstd::vector<int> GetBlocksForEntry(int num) { return this->apbToBlocks[this->GetHierarchyEntry(num)]; } virtual vtkstd::vector<int> GetBlocksForEntry(vtkStdString entry) { return this->apbToBlocks[entry]; } protected: vtkExodusIIXMLParser() { this->Metadata = 0; this->InMaterialAssignment = 0; } virtual ~vtkExodusIIXMLParser() { //this->Metadata->UnRegister( this ); } virtual void StartElement( const char* tagName, const char** attrs ) { (void)attrs; //FIXME: Useme const char* name = strrchr( tagName, ':' ); name = name ? name + 1 : tagName; // If tag name has xml namespace separator, get rid of namespace. vtkStdString tName( name ); if ( tName == "assembly" ) { //this->Metadata->AddAssembly( tName, this->ParentAssembly ); cout << name << "\n"; const char* assemblyNumber=this->GetValue("number",attrs); if (assemblyNumber) { this->CurrentAssemblyNumbers.push_back(vtkStdString(assemblyNumber)); } const char* assemblyDescription=this->GetValue("description",attrs); if (assemblyDescription) { this->CurrentAssemblyDescriptions.push_back(vtkStdString(assemblyDescription)); } //make the entry for the hierarchical list vtkStdString result=vtkStdString(""); for (vtkstd::vector<int>::size_type i=0; i<this->CurrentAssemblyNumbers.size()-1; i++) { result+=vtkStdString(" "); } result+=vtkStdString("Assembly: ")+ assemblyDescription+vtkStdString(" (")+ assemblyNumber+vtkStdString(")"); apbList.push_back(result); //record the indent level, used when we add blocks apbIndents[result]=this->CurrentAssemblyNumbers.size()-1; //make the blocks array apbToBlocks[result]=vtkstd::vector<int>(); } else if ( tName == "part" ) { //this->Metadata->AddPart( pnum, inst, curAssy ); cout << name << "\n"; const char* instance=this->GetValue("instance",attrs); vtkStdString instanceString=vtkStdString(""); if (instance) { instanceString=vtkStdString(instance); } const char* partString=this->GetValue("number",attrs); if (partString) { this->PartNumber=vtkStdString(partString)+ vtkStdString(" Instance: ")+ instanceString; } const char* partDescString=this->GetValue("description",attrs); if (partDescString && this->PartNumber!="") { this->PartDescriptions[this->PartNumber]= partDescString; } //copy the current assemblies to the assemblies list for this part. this->PartNumberToAssemblyNumbers[this->PartNumber]= vtkstd::vector<vtkStdString>(this->CurrentAssemblyNumbers); this->PartNumberToAssemblyDescriptions[this->PartNumber]= vtkstd::vector<vtkStdString>(this->CurrentAssemblyDescriptions); //make the hierarchical display entry vtkStdString result=vtkStdString(""); for (vtkstd::vector<int>::size_type i=0; i<this->CurrentAssemblyNumbers.size(); i++) { result+=vtkStdString(" "); } result+=vtkStdString("Part: ")+ partDescString+vtkStdString(" (")+ partString+vtkStdString(")")+vtkStdString(" Instance: ")+ instanceString; apbList.push_back(result); //record the indent level apbIndents[result]=this->CurrentAssemblyNumbers.size(); apbToBlocks[result]=vtkstd::vector<int>(); } else if ( tName == "material-specification" ) { //matl = this->Metadata->AddMatl( matname ); //this->Metadata->SetPartMaterial( this->CurrentPart, inst, matl ); cout << name << "\n"; if (this->PartNumber!="") { const char * materialDescriptionString= GetValue("description",attrs); if (materialDescriptionString) { this->MaterialDescriptions[this->PartNumber]= vtkStdString(materialDescriptionString); } const char * materialSpecificationString= GetValue("specification",attrs); if (materialSpecificationString) { this->MaterialSpecifications[this->PartNumber]= vtkStdString(materialSpecificationString); } } } else if ( tName == "blocks" ) { /* this->Metadata->AddPartBlock( pnum, blocktype, block id ); if ( this->InMaterialAssignment ) { this->Metadata->SetPartMaterial( this->CurrentPart, inst, matl ); } */ cout << name << "\n"; const char* instance=this->GetValue("part-instance",attrs); vtkStdString instanceString=vtkStdString(""); if (instance) { this->InstanceNumber=vtkStdString(instance); } const char* partString=this->GetValue("part-number",attrs); if (partString) { this->PartNumber=vtkStdString(partString); } } else if ( tName == "block" ) { //this->Metadata->SetBlockName( this->GetBlockType( attrs ), blockid ); cout << name << "\n"; const char* blockString=this->GetValue("id",attrs); int id=-1; if (blockString) { id=atoi(blockString); } if (this->PartNumber!="" && id>=0) { this->BlockIDToPartNumber[id]=this->PartNumber+ vtkStdString(" Instance: ")+this->InstanceNumber; //first insert block entry into apblist vtkStdString apbIndexString=this->PartNumber+ vtkStdString(") Instance: ")+this->InstanceNumber; vtkStdString partEntry=findEntry(this->apbList,apbIndexString); vtkStdString blockEntry=vtkStdString(""); if (partEntry!=vtkStdString("")) { //insert into apbList vtkstd::list<vtkStdString>::iterator pos= vtkstd::find(this->apbList.begin(),this->apbList.end(),partEntry); pos++; vtkStdString result=vtkStdString(""); for (int i=0;i<apbIndents[partEntry]+1;i++) { result+=vtkStdString(" "); } result+=vtkStdString("Block: ")+vtkStdString(blockString); blockEntry=result; this->apbList.insert(pos,result); apbToBlocks[result]=vtkstd::vector<int>(); } if (partEntry!=vtkStdString("") && blockEntry!=vtkStdString("")) { //update mapping //we know block number, so can get part number to update that. //using part number, we can update assembly mappings vtkStdString partIndexString=this->PartNumber+ vtkStdString(" Instance: ")+this->InstanceNumber; //we know the part entry //add block ID to block entry apbToBlocks[blockEntry].push_back(id); //add block ID to part apbToBlocks[partEntry].push_back(id); //get the assemblies vtkstd::vector<vtkStdString> assemblies= this->PartNumberToAssemblyNumbers[partIndexString]; //add block ID to assemblies for (vtkstd::vector<vtkStdString>::size_type j=0;j<assemblies.size();j++) { vtkStdString assemblyEntry=findEntry(this->apbList,assemblies[j]); apbToBlocks[assemblyEntry].push_back(id); } } } //parse material information if this block tag is part of a //material-assignments tag if (this->ParseMaterials==1 && id>=0) { const char* tmaterialName=this->GetValue("material-name",attrs); if (tmaterialName) { this->BlockIDToMaterial[id]=vtkStdString(tmaterialName); } } } else if ( tName == "material-assignments" ) { this->InMaterialAssignment = 1; cout << name << "\n"; this->ParseMaterials=1; } else if ( tName == "material" ) { cout << name << "\n"; const char* material=this->GetValue("name",attrs); const char* spec=this->GetValue("specification",attrs); const char* desc=this->GetValue("description",attrs); if (material && spec) { this->MaterialSpecificationsBlocks[vtkStdString(material)]=vtkStdString(spec); } if (material && desc) { this->MaterialDescriptionsBlocks[vtkStdString(material)]=vtkStdString(desc); } } } //returns the first string that contains sstring virtual vtkStdString findEntry(vtkstd::list<vtkStdString> slist, vtkStdString sstring){ for (vtkstd::list<vtkStdString>::iterator i=slist.begin(); i!=slist.end(); i++) { if ((*i).find(sstring)!=vtkStdString::npos) { return (*i); } } return vtkStdString(""); } virtual void EndElement(const char* tname) { const char* name=strrchr(tname,':'); if (!name) { name=tname; } else { name++; } if (strcmp(name,"assembly")==0) { this->CurrentAssemblyNumbers.pop_back(); this->CurrentAssemblyDescriptions.pop_back(); } else if (strcmp(name,"blocks")==0) { this->PartNumber=""; } else if (strcmp(name,"material-assignments")==0) { this->ParseMaterials=0; } } virtual int ParsingComplete() { //if we have as-tested materials, overwrite MaterialDescriptions //and MaterialSpecifications if (this->BlockIDToMaterial.size()>0) { this->MaterialSpecifications.clear(); this->MaterialDescriptions.clear(); for (vtkstd::map<int,vtkStdString>::iterator i=this->BlockIDToPartNumber.begin();i!=this->BlockIDToPartNumber.end();i++) { int blockID=(*i).first; this->MaterialSpecifications[this->BlockIDToPartNumber[blockID]]= this->MaterialSpecificationsBlocks[this->BlockIDToMaterial[blockID]]; this->MaterialDescriptions[this->BlockIDToPartNumber[blockID]]= this->MaterialDescriptionsBlocks[this->BlockIDToMaterial[blockID]]; } } //if we have no assembly information, we need to generate a bunch //of items from the BlockIDToPartNumber array if (this->apbList.size()==0) { for (vtkstd::map<int,vtkStdString>::iterator i=this->BlockIDToPartNumber.begin();i!=this->BlockIDToPartNumber.end();i++) { int id=(*i).first; vtkStdString part=(*i).second; vtkStdString partSpec=vtkStdString(""); vtkStdString instance=vtkStdString(""); //get part spec and instance from part int pos=part.find(" Instance: "); if (pos!=(int)vtkStdString::npos) { partSpec.assign(part,0,pos); instance.assign(part,pos+11,part.size()-(pos+11)); } this->PartDescriptions[part]=vtkStdString("None"); //convert id to a string char buffer[20]; sprintf(buffer,"%d",id); //find the Part entry in the apbList vtkStdString apbPartEntry=vtkStdString("Part: None (")+partSpec+vtkStdString(") Instance: ")+instance; vtkStdString apbBlockEntry=vtkStdString(" ")+vtkStdString("Block: ")+vtkStdString(buffer); vtkStdString foundEntry=this->findEntry(this->apbList,apbPartEntry); if (foundEntry==vtkStdString("")) { this->apbList.push_back(apbPartEntry); this->apbToBlocks[apbPartEntry]=vtkstd::vector<int>(); this->apbToBlocks[apbPartEntry].push_back(id); this->AssemblyDescriptions[apbPartEntry]=vtkStdString("None"); } //insert into apbList vtkstd::list<vtkStdString>::iterator positer= vtkstd::find(this->apbList.begin(),this->apbList.end(),apbPartEntry); positer++; this->apbList.insert(positer,apbBlockEntry); this->apbToBlocks[apbBlockEntry]=vtkstd::vector<int>(); this->apbToBlocks[apbBlockEntry].push_back(id); } } return vtkXMLParser::ParsingComplete(); } virtual const char* GetValue(const char* attr,const char** attrs) { int i; for (i=0;attrs[i];i+=2) { const char* name=strrchr(attrs[i],':'); if (!name) { name=attrs[i]; } else { name++; } if (strcmp(attr,name)==0) { return attrs[i+1]; } } return NULL; } private: vtkstd::map<vtkStdString,vtkStdString> MaterialSpecifications; vtkstd::map<vtkStdString,vtkStdString> MaterialDescriptions; vtkstd::map<vtkStdString,vtkStdString> PartDescriptions; vtkStdString PartNumber; vtkStdString InstanceNumber; int ParseMaterials; vtkstd::map<int,vtkStdString> BlockIDToPartNumber; vtkstd::map<vtkStdString,vtkstd::vector<vtkStdString> > PartNumberToAssemblyNumbers; vtkstd::map<vtkStdString,vtkstd::vector<vtkStdString> > PartNumberToAssemblyDescriptions; vtkstd::map<vtkStdString,vtkStdString> AssemblyDescriptions; vtkstd::vector<vtkStdString> CurrentAssemblyNumbers; vtkstd::vector<vtkStdString> CurrentAssemblyDescriptions; //mappings for as-tested materials vtkstd::map<vtkStdString,vtkStdString> MaterialSpecificationsBlocks; //maps material name to spec vtkstd::map<vtkStdString,vtkStdString> MaterialDescriptionsBlocks; //maps material name to desc vtkstd::map<int,vtkStdString> BlockIDToMaterial; //maps block id to material //hierarchical list mappings vtkstd::list<vtkStdString> apbList; vtkstd::map<vtkStdString,vtkstd::vector<int> > apbToBlocks; vtkstd::map<vtkStdString,int> apbIndents; }; vtkStandardNewMacro(vtkExodusIIXMLParser); vtkCxxRevisionMacro(vtkExodusIIXMLParser,"1.18"); // --------------------------------------------------- PRIVATE CLASS DECLARATION /** This class holds metadata for an Exodus file. * */ class vtkExodusIIReaderPrivate : public vtkObject { public: static vtkExodusIIReaderPrivate* New(); void PrintData( ostream& os, vtkIndent indent ); vtkTypeRevisionMacro(vtkExodusIIReaderPrivate,vtkObject); /// Open an ExodusII file for reading. Returns 0 on success. int OpenFile( const char* filename ); /// Close any ExodusII file currently open for reading. Returns 0 on success. int CloseFile(); /// Get metadata for an open file with handle \a exoid. int RequestInformation(); /// Read requested data and store in unstructured grid. int RequestData( vtkIdType timeStep, vtkUnstructuredGrid* output ); /// Reset the class so that another file may be read. void Reset(); /** Return the number of time steps in the open file. * You must have called RequestInformation() before invoking this member function. */ int GetNumberOfTimeSteps() { return (int) this->Times.size(); } /// Return the current time step vtkGetMacro(TimeStep,int); /// Set the current time step for subsequent calls to RequestData(). vtkSetMacro(TimeStep,int); /// Return whether subsequent RequestData() calls will produce the minimal point set required to represent the output. vtkGetMacro(SqueezePoints,int); /// Set whether subsequent RequestData() calls will produce the minimal point set required to represent the output. void SetSqueezePoints( int sp ); /// Convenience routines that for producing (or not) the minimal point set required to represent the output. vtkBooleanMacro(SqueezePoints,int); /// Return the number of nodes in the output (depends on SqueezePoints) int GetNumberOfNodes(); /** Returns the number of objects of a given type (e.g., EX_ELEM_BLOCK, EX_NODE_SET, ...). * You must have called RequestInformation before invoking this member function. */ int GetNumberOfObjectsOfType( int otype ); /** Returns the number of arrays defined over objects of a given type (e.g., EX_ELEM_BLOCK, EX_NODE_SET, ...). * You must have called RequestInformation before invoking this member function. * * N.B.: This method will eventually disappear. Really, what we should be providing is an interface to * query the arrays defined on a particular object, not a class of objects. However, until the reader * outputs multiblock datasets, we can't be that specific. */ int GetNumberOfObjectArraysOfType( int otype ); /** For a given object type, returns the name of the i-th object. * You must have called RequestInformation before invoking this member function. */ const char* GetObjectName( int otype, int i ); /** For a given object type, return the user-assigned ID of the i-th object. * You must have called RequestInformation before invoking this member function. */ int GetObjectId( int otype, int i ); /** For a given object type, return the size of the i-th object. * The size is the number of entries. * As an example, for an element block, it is the number of elements. * You must have called RequestInformation before invoking this member function. */ int GetObjectSize( int otype, int i ); /** For a given object type, returns the status of the i-th object. * You must have called RequestInformation before invoking this member function. */ int GetObjectStatus( int otype, int i ); /** For a given object type, returns the status of the i-th object, where i is * an index into the unsorted object array. * You must have called RequestInformation before invoking this member function. */ int GetUnsortedObjectStatus( int otype, int i ); /** For a given object type, sets the status of the i-th object. * You must have called RequestInformation before invoking this member function. */ void SetObjectStatus( int otype, int i, int stat ); /** For a given object type, sets the status of the i-th object, * where i is an index into the *unsorted* object array. * You must have called RequestInformation before invoking this member function. */ void SetUnsortedObjectStatus( int otype, int i, int stat ); /** For a given object type, returns the name of the i-th array. * You must have called RequestInformation before invoking this member function. */ const char* GetObjectArrayName( int otype, int i ); /** For a given object type, returns the number of components of the i-th array. * You must have called RequestInformation before invoking this member function. */ int GetNumberOfObjectArrayComponents( int otype, int i ); /** For a given object type, returns the status of the i-th array. * You must have called RequestInformation before invoking this member function. */ int GetObjectArrayStatus( int otype, int i ); /** For a given object type, sets the status of the i-th array. * You must have called RequestInformation before invoking this member function. */ void SetObjectArrayStatus( int otype, int i, int stat ); /** Unlike object arrays, attributes are only defined over blocks (not sets) * and are defined on a per-block (not a per-block-type) basis. * In other words, there is no truth table for attributes. * This means the interface is different because each block can have a different number of attributes with * different names. */ int GetNumberOfObjectAttributes( int objectType, int objectIndex ); const char* GetObjectAttributeName( int objectType, int objectIndex, int attributeIndex ); int GetObjectAttributeIndex( int objectType, int objectIndex, const char* attribName ); int GetObjectAttributeStatus( int objectType, int objectIndex, int attribIndex ); void SetObjectAttributeStatus( int objectType, int objectIndex, int attribIndex, int status ); /// Generate an array containing the block or set ID associated with each cell. vtkGetMacro(GenerateObjectIdArray,int); vtkSetMacro(GenerateObjectIdArray,int); const char* GetObjectIdArrayName() { return "ObjectId"; } vtkSetMacro(GenerateGlobalElementIdArray,int); vtkGetMacro(GenerateGlobalElementIdArray,int); static const char *GetGlobalElementIdArrayName() { return "GlobalElementId"; } vtkSetMacro(GenerateGlobalNodeIdArray,int); vtkGetMacro(GenerateGlobalNodeIdArray,int); static const char *GetGlobalNodeIdArrayName() { return "GlobalNodeId"; } virtual void SetApplyDisplacements( int d ); vtkGetMacro(ApplyDisplacements,int); virtual void SetDisplacementMagnitude( double s ); vtkGetMacro(DisplacementMagnitude,double); vtkSetMacro(HasModeShapes,int); vtkGetMacro(HasModeShapes,int); vtkSetMacro(ModeShapeTime,double); vtkGetMacro(ModeShapeTime,double); vtkDataArray* FindDisplacementVectors( int timeStep ); const struct ex_init_params* GetModelParams() const { return &this->ModelParameters; } /// A struct to hold information about time-varying arrays struct ArrayInfoType { /// The name of the array vtkStdString Name; /// The number of components in the array int Components; /** The type of "glomming" performed. * Glomming is the process of aggregating one or more results variable names * from the Exodus files into a single VTK result variable name with one or more * components. * One of: scalar, vector(2), vector(3), symtensor(6), integrationpoint. */ int GlomType; /// Storage type of array (a type that can be passed to vtkDataArray::Create()) int StorageType; /// The source of the array (Result or Attribute) int Source; /// Whether or not the array should be loaded by RequestData int Status; /// The name of each component of the array as defined by the Exodus file. Empty for generated arrays. vtkstd::vector<vtkStdString> OriginalNames; /// The index of each component of the array as ordered by the Exodus file. Empty for generated arrays. vtkstd::vector<int> OriginalIndices; /** A map describing which objects the variable is defined on. * Each key (a pair<int,int>) is a block/set type and integer * offset into the corresponding BlockInfo or SetInfo. * Its value is true when the variable is defined on the * block/set indicated by the key. * Otherwise (if the key is absent from the map or present with a * false value), the variable is not defined on that block/set. */ vtkstd::vector<int> ObjectTruth; /// Clear all the structure members. void Reset(); }; /// A struct to hold information about Exodus objects (blocks, sets, maps) struct ObjectInfoType { /// Number of entries in this block. int Size; /// Should the reader load this block? int Status; /// User-assigned identification number int Id; /// User-assigned name vtkStdString Name; }; /// A struct to hold information about Exodus maps struct MapInfoType : public ObjectInfoType { }; /// A struct to hold information about Exodus blocks or sets (they have some members in common) struct BlockSetInfoType : public ObjectInfoType { /// Id (1-based) of first entry in file-local list across all blocks in file vtkIdType FileOffset; /// Id (0-based) of first entry in the vtkUnstructuredGrid containing all blocks with Status != 0 vtkIdType GridOffset; }; /// A struct to hold information about Exodus blocks struct BlockInfoType : public BlockSetInfoType { vtkStdString TypeName; int BdsPerEntry[3]; // number of boundaries per entry. The index is the dimensionality of the entry. 0=node, 1=edge, 2=face int AttributesPerEntry; vtkstd::vector<vtkStdString> AttributeNames; vtkstd::vector<int> AttributeStatus; int CellType; // VTK cell type (a function of TypeName and BdsPerEntry...) int PointsPerCell; // Number of points per cell as used by VTK -- not what's in the file (i.e., BdsPerEntry[0] >= PointsPerCell) }; /// A struct to hold information about Exodus blocks struct PartInfoType : public ObjectInfoType { vtkstd::vector<int> BlockIndices; }; struct AssemblyInfoType : public ObjectInfoType { vtkstd::vector<int> BlockIndices; }; struct MaterialInfoType : public ObjectInfoType { vtkstd::vector<int> BlockIndices; }; /// A struct to hold information about Exodus sets struct SetInfoType : public BlockSetInfoType { int DistFact; // Number of distribution factors (for the entire block, not per array or entry) }; /// Tags to indicate how single-component Exodus arrays are glommed (aggregated) into multi-component VTK arrays. enum GlomTypes { Scalar=0, //!< The array is a scalar Vector2=1, //!< The array is a 2-D vector Vector3=2, //!< The array is a 3-D vector SymmetricTensor=3, //!< The array is a symmetric tensor (order xx, yy, zz, xy, yz, zx) IntegrationPoint=4 //!< The array is a set of integration point values }; /// Tags to indicate the source of values for an array. enum ArraySourceTypes { Result=0, //!< The array is composed of results variables (that vary over time) Attribute=1, //!< The array is composed of attributes (constants over time) Map=2, //!< The array has a corresponding entry in MapInfo Generated=3 //!< The array is procedurally generated (e.g., BlockId) }; /// Time stamp from last time we were in RequestInformation vtkTimeStamp InformationTimeStamp; friend class vtkExodusIIReader; virtual void SetParser( vtkExodusIIXMLParser* ); vtkGetObjectMacro(Parser,vtkExodusIIXMLParser); // Because Parts, Materials, and assemblies are not stored as arrays, // but rather as maps to the element blocks they make up, // we cannot use the Get|SetObject__() methods directly. int GetNumberOfParts(); const char* GetPartName(int idx); const char* GetPartBlockInfo(int idx); int GetPartStatus(int idx); int GetPartStatus(vtkStdString name); void SetPartStatus(int idx, int on); void SetPartStatus(vtkStdString name, int flag); int GetNumberOfMaterials(); const char* GetMaterialName(int idx); int GetMaterialStatus(int idx); int GetMaterialStatus(vtkStdString name); void SetMaterialStatus(int idx, int on); void SetMaterialStatus(vtkStdString name, int flag); int GetNumberOfAssemblies(); const char* GetAssemblyName(int idx); int GetAssemblyStatus(int idx); int GetAssemblyStatus(vtkStdString name); void SetAssemblyStatus(int idx, int on); void SetAssemblyStatus(vtkStdString name, int flag); protected: vtkExodusIIReaderPrivate(); ~vtkExodusIIReaderPrivate(); /// Any time the Status member of a block or set changes, this function must be called. void ComputeGridOffsets(); /// Returns true when order and text of names are consistent with integration points. Called from GlomArrayNames(). int VerifyIntegrationPointGlom( int nn, char** np, vtksys::RegularExpression& re, vtkStdString& field, vtkStdString& ele ); /// Aggregate Exodus array names into VTK arrays with multiple components void GlomArrayNames( int i, int num_obj, int num_vars, char** var_names, int* truth_tab ); /// Add generated array information to array info lists. void PrepareGeneratedArrayInfo(); /** Read connectivity information and populate an unstructured grid with cells. * If the connectivity hasn't changed since the last time RequestData was called, * this copies a cache to the output. * * Otherwise, this routine iterates over all block and set types. * For each type, it iterates over all objects of that type. * For each object whose status is 1, it reads that object's connectivity entries from * cache or disk and inserts cells into CachedConnectivity. * If SqueezePoints is on, then connectivity entries are translated as required and * PointMap is populated. * Finally, CachedConnectivity is shallow-copied to the output. * * AssembleOutputConnectivity returns 1 if cache was used, 0 otherwise. */ int AssembleOutputConnectivity( vtkIdType timeStep, vtkUnstructuredGrid* output ); /** Fill the output grid's point coordinates array. * Returns 1 on success, 0 on failure. * Failure occurs when the Exodus library is unable to read the point * coordindates array. This can be caused when there is not enough memory * or there is a file I/O problem. */ int AssembleOutputPoints( vtkIdType timeStep, vtkUnstructuredGrid* output ); /** Add the requested arrays to the output grid's point data. * This adds time-varying results arrays to the grid's vtkPointData object. */ int AssembleOutputPointArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ); /** Add the requested arrays to the output grid's cell data. * This adds time-varying results arrays to the grid's vtkCellData object. * Each array added may not be defined on all blocks of cells, so zero-padding will be used where required. */ int AssembleOutputCellArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ); /** Add maps to an output mesh. * Maps are special integer arrays that may serve as GlobalId fields in vtkDataSetAttributes objects. * Maps will only be zero-padded when cells representing set entries exist; * also, maps may be procedurally generated if no map is contained in a file. * Maps are not time-varying. */ int AssembleOutputPointMaps( vtkIdType timeStep, vtkUnstructuredGrid* output ); int AssembleOutputCellMaps( vtkIdType timeStep, vtkUnstructuredGrid* output ); /** Add procedurally generated arrays to an output mesh. * Currently, the only array that is procedurally generated is the object id array. * Others may be added in the future. */ int AssembleOutputProceduralArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ); /// Insert cells from a specified block into a mesh void InsertBlockCells( int otyp, int obj, int conn_type, int timeStep, vtkUnstructuredGrid* output ); /// Insert cells from a specified set into a mesh void InsertSetCells( int otyp, int obj, int conn_type, int timeStep, vtkUnstructuredGrid* output ); /// Add a point array to an output grid's point data, squeezing if necessary void AddPointArray( vtkDataArray* src, vtkUnstructuredGrid* output ); /// Insert cells referenced by a node set. void InsertSetNodeCopies( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ); /// Insert cells referenced by an edge, face, or element set. void InsertSetCellCopies( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ); /// Insert cells referenced by a side set. void InsertSetSides( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ); /** Return an array for the specified cache key. If the array was not cached, read it from the file. * This function can still return 0 if you are foolish enough to request an array not present in the file, grasshopper. */ vtkDataArray* GetCacheOrRead( vtkExodusIICacheKey ); /** Return the index of an object type (in a private list of all object types). * This returns a 0-based index if the object type was found and -1 if it was not. */ int GetConnTypeIndexFromConnType( int ctyp ); /** Return the index of an object type (in a private list of all object types). * This returns a 0-based index if the object type was found and -1 if it was not. */ int GetObjectTypeIndexFromObjectType( int otyp ); /** Return the number of objects of the given type. * The integer typeIndex is not the type of the object (e.g., EX_ELEM_BLOCK), but * is rather the index into the list of all object types (see obj_types in vtkExodusIIReader.cxx). */ int GetNumberOfObjectsAtTypeIndex( int typeIndex ); /** Return a pointer to the ObjectInfo of the specified type and index. * The integer typeIndex is not the type of the object (e.g., EX_ELEM_BLOCK), but * is rather the index into the list of all object types (see obj_types in vtkExodusIIReader.cxx). * The integer objectIndex is not the ID of the object (i.e., the ID stored in the Exodus file), * but is rather the index into the list of all objects of the given type. */ ObjectInfoType* GetObjectInfo( int typeIndex, int objectIndex ); /** Return a pointer to the ObjectInfo of the specified type and index, but using indices sorted by object ID. * This is the same as GetObjectInfo() except that it uses the SortedObjectIndices member to permute * the requested \a objectIndex and it takes an object type (e.g., EX_ELEM_BLOCK) rather than an object type index. */ ObjectInfoType* GetSortedObjectInfo( int objectType, int objectIndex ); /** Return a pointer to the ObjectInfo of the specified type and index, but using indices sorted by object ID. * This is the same as GetSortedObjectInfo() except that \a objectIndex directly indexes the object info array * rather SortedObjectIndices, and it takes an object type (e.g., EX_ELEM_BLOCK) rather than an object type index. */ ObjectInfoType* GetUnsortedObjectInfo( int objectType, int objectIndex ); /** Get the index of the block containing the entity referenced by the specified file-global ID. * In this case, an entity is an edge, face, or element. */ int GetBlockIndexFromFileGlobalId( int otyp, int refId ); /** Get the block containing the entity referenced by the specified file-global ID. * In this case, an entity is an edge, face, or element. */ BlockInfoType* GetBlockFromFileGlobalId( int otyp, int refId ); /// Find or create a new SqueezePoint ID (unique sequential list of points referenced by cells in blocks/sets with Status == 1) vtkIdType GetSqueezePointId( int i ); /// Determine the VTK cell type for a given edge/face/element block void DetermineVtkCellType( BlockInfoType& binfo ); /// Find an ArrayInfo object for a specific object type using the name as a key. ArrayInfoType* FindArrayInfoByName( int otyp, const char* name ); /// Does the specified object type match? Avoid using these... they aren't robust against new types being implemented. int IsObjectTypeBlock( int otyp ); int IsObjectTypeSet( int otyp ); int IsObjectTypeMap( int otyp ); /// Given a map type (NODE_MAP, EDGE_MAP, ...) return the associated object type (NODAL, EDGE_BLOCK, ...) or vice-versa. int GetObjectTypeFromMapType( int mtyp ); int GetMapTypeFromObjectType( int otyp ); /// Given a set connectivity type (NODE_SET_CONN, ...), return the associated object type (NODE_SET, ...) or vice-versa. int GetSetTypeFromSetConnType( int sctyp ); /// Given a block type (EDGE_BLOCK, ...), return the associated block connectivity type (EDGE_BLOCK_CONN, ...) or vice-versa. int GetBlockConnTypeFromBlockType( int btyp ); /// Get/Set the cached connectivity data vtkGetObjectMacro(CachedConnectivity,vtkUnstructuredGrid); virtual void SetCachedConnectivity( vtkUnstructuredGrid* mesh ); /** Function to trim space from names retrieved with ex_get_var_names. * This was added because some meshes had displacement arrays named "DISPX ", "DISPY ", "DISPZ " (note trailing spaces), * which prevented glomming and use of the vector field for displacements. */ void RemoveBeginningAndTrailingSpaces( int len, char **names ); // The next vtk ID to use for a connectivity entry when point squeezing is on and no point ID exists. vtkIdType NextSqueezePoint; /// Maps a block type (EX_ELEM_BLOCK, EX_FACE_BLOCK, ...) to a list of blocks of that type. vtkstd::map<int,vtkstd::vector<BlockInfoType> > BlockInfo; /// Maps a set type (EX_ELEM_SET, ..., EX_NODE_SET) to a list of sets of that type. vtkstd::map<int,vtkstd::vector<SetInfoType> > SetInfo; /** Maps a map type (EX_ELEM_MAP, ..., EX_NODE_MAP) to a list of maps of that type. * In old-style files, the only entries will be a single node and a single element map * which have no specified ID number or name. In that case, an ID of 0 and a name of * "Default" will be given to both. */ vtkstd::map<int,vtkstd::vector<MapInfoType> > MapInfo; vtkstd::vector<PartInfoType> PartInfo; vtkstd::vector<MaterialInfoType> MaterialInfo; vtkstd::vector<AssemblyInfoType> AssemblyInfo; /** Maps an object type to vector of indices that reorder objects of that type by their IDs. * This is used by the user interface to access blocks, sets, and maps in ascending order. * It is not used internally. */ vtkstd::map<int,vtkstd::vector<int> > SortedObjectIndices; /// Maps an object type (EX_ELEM_BLOCK, EX_NODE_SET, ...) to a list of arrays defined on that type. vtkstd::map<int,vtkstd::vector<ArrayInfoType> > ArrayInfo; /// These aren't the variables you're looking for. int AppWordSize; int DiskWordSize; /// The version of Exodus that wrote the currently open file (or a negative number otherwise). float ExodusVersion; /// The handle of the currently open file. int Exoid; /// Parameters describing the currently open Exodus file. struct ex_init_params ModelParameters; /// A list of time steps for which results variables are stored. vtkstd::vector<double> Times; /// The current time step int TimeStep; /// The time value. This is used internally when HasModeShapes is true and ignored otherwise. double ModeShapeTime; int GenerateObjectIdArray; int GenerateGlobalIdArray; /// A least-recently-used cache to hold raw arrays. vtkExodusIICache* Cache; /// Cache assembled connectivity separately because there's no way to SetLinks() on a vtkUnstructuredGrid. vtkUnstructuredGrid* CachedConnectivity; int GenerateGlobalElementIdArray; int GenerateGlobalNodeIdArray; int ApplyDisplacements; float DisplacementMagnitude; int HasModeShapes; /** Should the reader output only points used by elements in the output mesh, or all the points. * Outputting all the points is much faster since the point array can be read straight from * disk and the mesh connectivity need not be altered. * Squeezing the points down to the minimum set needed to produce the output mesh is useful for * glyphing and other point-based operations. On large parallel datasets, loading all the points * implies loading all the points on all processes and performing subsequent filtering on a much * larger set. * * By default, SqueezePoints is true for backwards compatability. */ int SqueezePoints; /// The total number of cells in the mesh given the current block and set Status values. vtkIdType NumberOfCells; /// The total number of points in the mesh given the SqueezePoints setting (and possibly the block and set Status values). //vtkIdType NumberOfPoints; /// A map from nodal IDs in an Exodus file to nodal IDs in the output mesh. vtkstd::vector<vtkIdType> PointMap; /// Pointer to owning reader... this is not registered in order to avoid circular references. vtkExodusIIReader* Parent; vtkExodusIIXMLParser *Parser; private: vtkExodusIIReaderPrivate( const vtkExodusIIReaderPrivate& ); // Not implemented. void operator = ( const vtkExodusIIReaderPrivate& ); // Not implemented. }; // ------------------------------------------------------------ UTILITY ROUTINES static int glomIntegrationPointElementDimension( vtkStdString& eleType ) { vtksys::RegularExpression reQuad( "[Qq][Uu][Aa][Dd]" ); vtksys::RegularExpression reHex( "[Hh][Ee][Xx]" ); vtksys::RegularExpression reTet( "[Tt][Ee][Tt]" ); vtksys::RegularExpression reTri( "[Tt][Rr][Ii]" ); vtksys::RegularExpression reWedge( "[Ww][Ee][Dd][Gg][Ee]" ); vtksys::RegularExpression rePyramid( "[Pp][Yy][Rr]" ); if ( reHex.find( eleType ) ) return 3; else if ( reTet.find( eleType ) ) return 3; else if ( reWedge.find( eleType ) ) return 3; else if ( rePyramid.find( eleType ) ) return 3; else if ( reQuad.find( eleType ) ) return 2; else if ( reTri.find( eleType ) ) return 2; return -1; } static int glomTruthTabMatch( int num_obj, int num_vars, int* truth_tab, vtkExodusIIReaderPrivate::ArrayInfoType& ainfo ) { // This returns 1 when all objects have the same values // in truth_tab for all original variable indices in // ainfo (and 0 otherwise). // It creates an entry in ainfo.ObjectTruth for each object // based on the values in truth_tab. int num_comp = (int)ainfo.OriginalIndices.size(); if ( num_comp < 1 ) return 0; int obj; int ttObj; // truth table entry for variable idx on object obj. int idx = ainfo.OriginalIndices[0] - 1; for ( obj = 0; obj < num_obj; ++obj ) { ttObj = truth_tab[ idx + obj * num_vars ]; ainfo.ObjectTruth.push_back( ttObj ); } if ( num_comp < 2 ) return 1; int comp; for ( comp = 1; comp < num_comp; ++comp ) { // Get truth table entry for 0-th variable of object obj: for ( obj = 0; obj < num_obj; ++obj ) { if ( truth_tab[ ainfo.OriginalIndices[comp] - 1 + obj * num_vars ] != truth_tab[ idx + obj * num_vars ] ) { // At least one object has a different truth table entry for variable ii. return 0; } } } return 1; // All objects define variable ii over the same subset of objects. } static void printBlock( ostream& os, vtkIndent indent, int btyp, vtkExodusIIReaderPrivate::BlockInfoType& binfo ) { int b = 0; while ( obj_types[b] >= 0 && obj_types[b] != btyp ) ++b; const char* btypnam = objtype_names[b]; os << indent << btypnam << " " << binfo.Id << " \"" << binfo.Name.c_str() << "\" (" << binfo.Size << ")\n"; os << indent << " FileOffset: " << binfo.FileOffset << "\n"; os << indent << " GridOffset: " << binfo.GridOffset << " (" << binfo.Status << ")\n"; os << indent << " Type: " << binfo.TypeName.c_str() << "\n"; os << indent << " Bounds per entry, Node: " << binfo.BdsPerEntry[0] << " Edge: " << binfo.BdsPerEntry[1] << " Face: " << binfo.BdsPerEntry[2] << "\n"; os << indent << " Attributes (" << binfo.AttributesPerEntry << "):"; int a; for ( a = 0; a < binfo.AttributesPerEntry; ++a ) { os << " \"" << binfo.AttributeNames[a].c_str() << "\"(" << binfo.AttributeStatus[a] << ")"; } os << "\n"; } static void printSet( ostream& os, vtkIndent indent, int styp, vtkExodusIIReaderPrivate::SetInfoType& sinfo ) { int s = 0; while ( obj_types[s] >= 0 && obj_types[s] != styp ) ++s; const char* stypnam = objtype_names[s]; os << indent << stypnam << " " << sinfo.Id << " \"" << sinfo.Name.c_str() << "\" (" << sinfo.Size << ")\n"; os << indent << " FileOffset: " << sinfo.FileOffset << "\n"; os << indent << " GridOffset: " << sinfo.GridOffset << " (" << sinfo.Status << ")\n"; os << indent << " DistFact: " << sinfo.DistFact << "\n"; } static void printMap( ostream& os, vtkIndent indent, int mtyp, vtkExodusIIReaderPrivate::MapInfoType& minfo ) { int m = 0; while ( obj_types[m] >= 0 && obj_types[m] != mtyp ) ++m; const char* mtypnam = objtype_names[m]; os << indent << mtypnam << " " << minfo.Id << " \"" << minfo.Name.c_str() << "\" (" << minfo.Size << ")\n"; os << indent << " Status: " << minfo.Status << "\n"; } static void printArray( ostream& os, vtkIndent indent, int atyp, vtkExodusIIReaderPrivate::ArrayInfoType& ainfo ) { (void)atyp; os << indent << " " << ainfo.Name.c_str() << " [" << ainfo.Status << "] ( " << ainfo.Components << " = { "; os << ainfo.OriginalIndices[0] << " \"" << ainfo.OriginalNames[0] << "\""; int i; for ( i = 1; i < (int) ainfo.OriginalIndices.size(); ++i ) { os << ", " << ainfo.OriginalIndices[i] << " \"" << ainfo.OriginalNames[i] << "\""; } os << " } )\n"; os << indent << " " << glomTypeNames[ ainfo.GlomType ] << " Truth:"; for ( i = 0; i < (int)ainfo.ObjectTruth.size(); ++i ) { os << " " << ainfo.ObjectTruth[i]; } os << "\n"; } // ---------------------------------------------------- PRIVATE SUBCLASS MEMBERS void vtkExodusIIReaderPrivate::ArrayInfoType::Reset() { if ( ! this->Name.empty() ) { this->Name.erase( this->Name.begin(), this->Name.end() ); } this->Components = 0; this->GlomType = -1; this->Status = 0; this->Source = -1; this->OriginalNames.clear(); this->OriginalIndices.clear(); this->ObjectTruth.clear(); } // ------------------------------------------------------- PRIVATE CLASS MEMBERS vtkCxxRevisionMacro(vtkExodusIIReaderPrivate,"1.18"); vtkStandardNewMacro(vtkExodusIIReaderPrivate); vtkCxxSetObjectMacro(vtkExodusIIReaderPrivate,CachedConnectivity,vtkUnstructuredGrid); vtkCxxSetObjectMacro(vtkExodusIIReaderPrivate,Parser,vtkExodusIIXMLParser); vtkExodusIIReaderPrivate::vtkExodusIIReaderPrivate() { this->Exoid = -1; this->ExodusVersion = -1.; this->AppWordSize = 8; this->DiskWordSize = 8; this->Cache = vtkExodusIICache::New(); this->TimeStep = 0; this->HasModeShapes = 0; this->ModeShapeTime = -1.; this->GenerateObjectIdArray = 1; this->GenerateGlobalElementIdArray = 0; this->GenerateGlobalNodeIdArray = 0; this->ApplyDisplacements = 1; this->DisplacementMagnitude = 1.; this->NumberOfCells = 0; this->SqueezePoints = 1; this->NextSqueezePoint = 0; this->CachedConnectivity = 0; this->Parser = 0; memset( (void*)&this->ModelParameters, 0, sizeof(this->ModelParameters) ); } vtkExodusIIReaderPrivate::~vtkExodusIIReaderPrivate() { this->CloseFile(); this->Cache->Delete(); this->SetCachedConnectivity( 0 ); if(this->Parser) { this->Parser->Delete(); this->Parser = 0; } } void vtkExodusIIReaderPrivate::ComputeGridOffsets() { vtkIdType startCell = 0; // Order cells in the grid in a way the user expects: // - blocks first, then sets. // - elements first, then faces, then edges. int conntypidx; for ( conntypidx = 0; conntypidx < num_conn_types; ++conntypidx ) { int otyp = obj_types[conn_obj_idx_cvt[conntypidx]]; int obj; int objNum; if ( CONNTYPE_IS_BLOCK( conntypidx ) ) { objNum = (int) this->BlockInfo[otyp].size(); for ( obj = 0; obj < objNum; ++obj ) { BlockInfoType* binfop = &this->BlockInfo[otyp][this->SortedObjectIndices[otyp][obj]]; if ( binfop->Status ) { binfop->GridOffset = startCell; startCell += binfop->Size; } } } else { // Must be a set... objNum = (int) this->SetInfo[otyp].size(); for ( obj = 0; obj < objNum; ++obj ) { SetInfoType* sinfop = &this->SetInfo[otyp][this->SortedObjectIndices[otyp][obj]]; if ( sinfop->Status ) { sinfop->GridOffset = startCell; startCell += sinfop->Size; } } } } this->NumberOfCells = startCell; } int vtkExodusIIReaderPrivate::VerifyIntegrationPointGlom( int nn, char** np, vtksys::RegularExpression& re, vtkStdString& field, vtkStdString& ele ) { vtkstd::vector<vtkstd::vector<int> > gpId; int max[3] = { 0, 0, 0 }; int dim = glomIntegrationPointElementDimension( ele ); for ( int i = 0; i < nn; ++i ) { gpId.push_back( vtkstd::vector<int>() ); re.find( np[i] ); vtkStdString gpIdStr = re.match(3); int d = 0; for ( vtkStdString::iterator it = gpIdStr.begin(); it != gpIdStr.end(); ++it, ++d ) { gpId[i].push_back( *it - '0' ); } if ( dim < 0 ) { dim = d; if ( dim > 3 ) { vtkWarningMacro( "Field \"" << np[i] << "\" has integration dimension " << d << " > 3." ); return false; } } else if ( dim != d ) { vtkWarningMacro( "Field \"" << np[i] << "\" has integration dimension " << d << " != " << dim << "." ); return false; } else { for ( int j = 0; j < dim; ++j ) if ( gpId[i][j] > max[j] ) max[j] = gpId[i][j]; } } #ifdef VTK_DBG_GLOM cout << " Integration points are " << dim << "-dimensional.\n"; for ( int i = 0; i < dim; ++i ) { cout << " " << (max[i]+1) << " integration points along " << char('r' + i) << ".\n"; } #endif // VTK_DBG_GLOM int npt = 1; for ( int i = 0; i < dim; ++i ) { npt *= max[i] + 1; } bool bad = false; if ( npt != nn ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" has " << nn << " entries, but I expected " << npt << " given the integration order." ); bad = true; } int e; int ef = -1; int cnt; bool found; if ( dim == 2 ) { for ( int r = 0; r <= max[0]; ++r ) { for ( int s = 0; s <= max[1]; ++s ) { found = false; cnt = 0; for ( e = 0; e < nn; ++e ) { if ( gpId[e][0] == r && gpId[e][1] == s ) { found = true; ef = e; ++cnt; } } if ( !found ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" is missing Gauss point (" << r << ", " << s << ")." ); } else if ( cnt > 1 ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" has " << (cnt-1) << " duplicate(s) of Gauss point (" << r << ", " << s << ")." ); } else if ( npt == nn && (ef != s + r * (max[1]+1) ) ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" has misplaced Gauss point (" << r << ", " << s << ")." ); bad = true; } } } } else if ( dim == 3 ) { for ( int r = 0; r <= max[0]; ++r ) { for ( int s = 0; s <= max[1]; ++s ) { for ( int t = 0; t <= max[2]; ++t ) { found = false; cnt = 0; for ( e = 0; e < nn; ++e ) { if ( gpId[e][0] == r && gpId[e][1] == s && gpId[e][2] == t ) { found = true; ef = e; ++cnt; } } if ( !found ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" is missing Gauss point (" << r << ", " << s << ", " << t << ")." ); bad = true; } else if ( cnt > 1 ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" has " << (cnt-1) << " duplicate(s) of Gauss point (" << r << ", " << s << ", " << t << ")." ); bad = true; } else if ( npt == nn && (ef != t + (max[2]+1) * ( s + r * (max[1]+1) )) ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" has misplaced Gauss point (" << r << ", " << s << ", " << t << ")." ); bad = true; } } } } } return ! bad; } void vtkExodusIIReaderPrivate::GlomArrayNames( int objtyp, int num_obj, int num_vars, char** var_names, int* truth_tab ) { vtksys::RegularExpression reTensor( "(.*)[XxYyZz][XxYyZz]$" ); vtksys::RegularExpression reVector( "(.*)[XxYyZz]$" ); vtksys::RegularExpression reGaussP( "(.*)_([^_]*)_GP([0-9]+)$" ); ArrayInfoType ainfo; for ( int i = 0; i < num_vars; ++i ) { char* srcName = var_names[i]; bool didGlom = true; ainfo.Source = vtkExodusIIReaderPrivate::Result; if ( reTensor.find( srcName ) ) { if ( i + 1 < num_vars ) { int ii = i; int sl = (int)strlen(var_names[i]) - 2; while ( ii < num_vars ) { if ( ! reTensor.find( var_names[ii] ) || strncmp( var_names[ii], var_names[i], sl ) ) break; ainfo.OriginalNames.push_back( var_names[ii] ); ainfo.OriginalIndices.push_back( ii + 1 ); ++ii; } ainfo.Components = ii - i; if ( ! ainfo.Components || ! glomTruthTabMatch( num_obj, num_vars, truth_tab, ainfo ) ) { didGlom = false; } else { reTensor.find( srcName ); //cout << "Tensor \"" << reTensor.match(1) << "\" has " << (ii-i) << " components\n"; ainfo.Name = reTensor.match(1); ainfo.GlomType = vtkExodusIIReaderPrivate::SymmetricTensor; ainfo.Status = 0; ainfo.StorageType = VTK_DOUBLE; this->ArrayInfo[ objtyp ].push_back( ainfo ); i = ii - 1; // advance to end of glom } ainfo.Reset(); } else { didGlom = false; } } else if ( reVector.find( srcName ) ) { if ( i+1 < num_vars ) { int ii = i; while ( ii < num_vars ) { int sl = (int)strlen(var_names[ii]) - 1; // Require the strings to be identical except for the final XYZ at the end. if ( ! toupper(var_names[ii][sl]) == ('X' + (ii-i)) || strncmp( var_names[ii], var_names[i], sl ) ) break; ainfo.OriginalNames.push_back( var_names[ii] ); ainfo.OriginalIndices.push_back( ii + 1 ); ++ii; } ainfo.Components = ii - i; if ( ainfo.Components < 2 || ! glomTruthTabMatch( num_obj, num_vars, truth_tab, ainfo ) ) { didGlom = false; } else { //cout << "Vector \"" << reVector.match(1) << "\" has " << (ii - i) << " components\n"; ainfo.Name = reVector.match(1); ainfo.GlomType = ainfo.Components == 2 ? vtkExodusIIReaderPrivate::Vector2 : vtkExodusIIReaderPrivate::Vector3; ainfo.Status = 0; ainfo.StorageType = VTK_DOUBLE; this->ArrayInfo[ objtyp ].push_back( ainfo ); i = ii - 1; // advance to end of glom } ainfo.Reset(); } else { didGlom = false; } } else if ( reGaussP.find( srcName ) ) { if ( i + 1 < num_vars ) { int ii = i; vtkStdString field = reGaussP.match( 1 ); vtkStdString ele = reGaussP.match( 2 ); while ( ii < num_vars && reGaussP.find( var_names[ii] ) && (reGaussP.match( 1 ) == field) && (reGaussP.match( 2 ) == ele) ) { ainfo.OriginalNames.push_back( var_names[ii] ); ainfo.OriginalIndices.push_back( ii + 1 ); ++ii; } ainfo.Components = ii - i; // Check that the names are consistent (i.e., there aren't missing Gauss points, they all have the same dim, etc.) if ( this->VerifyIntegrationPointGlom( ii - i, var_names + i, reGaussP, field, ele ) && glomTruthTabMatch( num_obj, num_vars, truth_tab, ainfo ) ) { //cout << "Gauss Points for \"" << field << "\" on " << ele << "-shaped elements has " << (ii-i) << " components\n"; ainfo.Name = field; ainfo.GlomType = vtkExodusIIReaderPrivate::IntegrationPoint; ainfo.Status = 0; ainfo.StorageType = VTK_DOUBLE; this->ArrayInfo[ objtyp ].push_back( ainfo ); i = ii - 1; // advance to end of glom } else { ainfo.Reset(); for ( ; i < ii; ++i ) { //cout << "Scalar \"" << var_names[i] << "\"\n"; ainfo.Name = var_names[i]; ainfo.Source = Result; ainfo.Components = 1; ainfo.OriginalIndices.push_back( i + 1 ); ainfo.OriginalNames.push_back( var_names[i] ); ainfo.GlomType = vtkExodusIIReaderPrivate::Scalar; ainfo.StorageType = VTK_DOUBLE; ainfo.Status = 0; glomTruthTabMatch( num_obj, num_vars, truth_tab, ainfo ); // fill in ainfo.ObjectTruth this->ArrayInfo[ objtyp ].push_back( ainfo ); } } ainfo.Reset(); } else { didGlom = false; } } else { didGlom = false; } if ( ! didGlom ) { //cout << "Scalar \"" << srcName << "\"\n"; ainfo.Name = srcName; ainfo.Source = Result; ainfo.Components = 1; ainfo.OriginalIndices.push_back( i + 1 ); ainfo.OriginalNames.push_back( var_names[i] ); ainfo.GlomType = vtkExodusIIReaderPrivate::Scalar; ainfo.StorageType = VTK_DOUBLE; ainfo.Status = 0; glomTruthTabMatch( num_obj, num_vars, truth_tab, ainfo ); // fill in ainfo.ObjectTruth this->ArrayInfo[ objtyp ].push_back( ainfo ); ainfo.Reset(); } } } int vtkExodusIIReaderPrivate::AssembleOutputConnectivity( vtkIdType timeStep, vtkUnstructuredGrid* output ) { output->Reset(); // FIXME: Don't think I need this, since we ShallowCopy over it... right? if ( this->CachedConnectivity ) { output->ShallowCopy( this->CachedConnectivity ); return 1; } // OK, we needed to remake the cache... this->CachedConnectivity = vtkUnstructuredGrid::New(); this->CachedConnectivity->Allocate( this->NumberOfCells ); if ( this->SqueezePoints ) { this->NextSqueezePoint = 0; this->PointMap.clear(); this->PointMap.reserve( this->ModelParameters.num_nodes ); for ( int i = 0; i < this->ModelParameters.num_nodes; ++i ) { this->PointMap.push_back( -1 ); } } // Need to assemble connectivity array from smaller ones. // Call GetCacheOrRead() for each smaller array // Might want to experiment with the effectiveness of caching connectivity... set up the // ExodusIICache class with the ability to never cache some key types. // Might also want to experiment with policies other than LRU, especially applied to // arrays that are not time-varying. During animations, they will most likely get // dropped even though that might not be wise. // Loop over all the block and set types which could generate connectivity information // in an order that the user expects (element blocks first, blocks ordered by block ID, // not file order). int conntypidx; int nbl = 0; for ( conntypidx = 0; conntypidx < num_conn_types; ++conntypidx ) { int otyp = obj_types[conn_obj_idx_cvt[conntypidx]]; // Loop over all blocks/sets of this type int numObj = this->GetNumberOfObjectsOfType( otyp ); int obj; int sortIdx; for ( sortIdx = 0; sortIdx < numObj; ++sortIdx ) { if ( ! this->GetObjectStatus( otyp, sortIdx ) ) continue; obj = this->SortedObjectIndices[otyp][sortIdx]; // Preserve the "sorted" order when concatenating if ( CONNTYPE_IS_BLOCK(conntypidx) ) { this->InsertBlockCells( otyp, obj, conn_types[conntypidx], timeStep, this->CachedConnectivity ); } else if ( CONNTYPE_IS_SET(conntypidx) ) { this->InsertSetCells( otyp, obj, conn_types[conntypidx], timeStep, this->CachedConnectivity ); } else { vtkErrorMacro( "Bad connectivity object type. Harass the responsible programmer." ); } ++nbl; } } // OK, now copy our cache to the output... output->ShallowCopy( this->CachedConnectivity ); //this->CachedConnectivity->ShallowCopy( output ); if ( this->SqueezePoints ) { vtkDebugMacro( << "Squeezed down to " << this->NextSqueezePoint << " points\n" ); } return 0; } int vtkExodusIIReaderPrivate::AssembleOutputPoints( vtkIdType timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; vtkPoints* pts = output->GetPoints(); if ( ! pts ) { pts = vtkPoints::New(); output->SetPoints( pts ); pts->FastDelete(); } else { pts->Reset(); } int ts = -1; // If we don't have displacements, only cache the array under one key. if ( this->ApplyDisplacements && this->FindDisplacementVectors( timeStep ) ) { // Otherwise, each time step's array will be different. ts = timeStep; } vtkDataArray* arr = this->GetCacheOrRead( vtkExodusIICacheKey( ts, vtkExodusIIReader::NODAL_COORDS, 0, 0 ) ); if ( ! arr ) { vtkErrorMacro( "Unable to read points from file." ); return 0; } if ( this->SqueezePoints ) { vtkIdType exoPtId; pts->SetNumberOfPoints( this->NextSqueezePoint ); for ( exoPtId = 0; exoPtId < this->ModelParameters.num_nodes; ++exoPtId ) { vtkIdType outPtId = this->PointMap[exoPtId]; if ( outPtId >= 0 ) { pts->SetPoint( outPtId, arr->GetTuple( exoPtId ) ); } } } else { pts->SetData( arr ); } return 1; } int vtkExodusIIReaderPrivate::AssembleOutputPointArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ) { int status = 1; vtkstd::vector<ArrayInfoType>::iterator ai; int aidx = 0; for ( ai = this->ArrayInfo[ vtkExodusIIReader::NODAL ].begin(); ai != this->ArrayInfo[ vtkExodusIIReader::NODAL ].end(); ++ai, ++aidx ) { if ( ! ai->Status ) continue; // Skip arrays we don't want. vtkExodusIICacheKey key( timeStep, vtkExodusIIReader::NODAL, 0, aidx ); vtkDataArray* src = this->GetCacheOrRead( key ); if ( !src ) { vtkWarningMacro( "Unable to read point array " << ai->Name.c_str() << " at time step " << timeStep ); status = 0; continue; } this->AddPointArray( src, output ); } return status; } int vtkExodusIIReaderPrivate::AssembleOutputCellArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ) { // Need to assemble arrays from smaller per-block/set arrays. // Call GetCacheOrRead() for each smaller array // Step 1. Create the large arrays and fill them (but don't pad them). vtkCellData* cd = output->GetCellData(); vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator ami; for ( ami = this->ArrayInfo.begin(); ami != this->ArrayInfo.end(); ++ami ) { if ( ami->first == vtkExodusIIReader::NODAL || ami->first == vtkExodusIIReader::NODE_MAP ) continue; // we handle nodal arrays in AssembleOutputPointArrays // See if any objects of this type are turned on (Status != 0) int obj; int numObjOn = 0; int numObj = this->GetNumberOfObjectsOfType( ami->first ); for ( obj = 0; obj < numObj; ++obj ) { if ( this->GetObjectStatus( ami->first, obj ) ) { ++numObjOn; } } if ( numObjOn == 0 ) continue; // this array may be on, but no objects of this type are active... skip it. vtkstd::vector<ArrayInfoType>::iterator ai; int aidx = 0; for ( ai = ami->second.begin(); ai != ami->second.end(); ++ai, ++aidx ) { if ( ! ai->Status ) continue; vtkDataArray* arr = cd->GetArray( ai->Name.c_str() ); if ( arr ) { // OK, we've already created this array for some other type of object, // so now we have to make sure the arrays are consistent. If not, we // turn off the second one we encounter. The user can disable the first // and re-enable the second if required. if ( arr->GetDataType() != ai->StorageType ) { vtkErrorMacro( "Cell array \"" << ai->Name.c_str() << "\" has conflicting types across blocks/sets." ); ai->Status = 0; // Don't load this block's/set's version. User must disable other block/set before loading this one. arr = 0; } if ( arr && (arr->GetNumberOfComponents() != ai->Components) ) { vtkErrorMacro( "Cell array \"" << ai->Name.c_str() << "\" has different number of components across blocks/sets." ); ai->Status = 0; // Don't load this block's/set's version. User must disable other block/set before loading this one. arr = 0; } } else { // Re-use an existing or create a new array vtkExodusIICacheKey key( ai->Source == Result ? timeStep : -1, vtkExodusIIReader::GLOBAL, ami->first, aidx ); arr = this->Cache->Find( key ); if ( arr ) { // Existing array was in cache cd->AddArray( arr ); continue; } arr = vtkDataArray::CreateDataArray( ai->StorageType ); arr->SetName( ai->Name.c_str() ); arr->SetNumberOfComponents( ai->Components ); arr->SetNumberOfTuples( this->NumberOfCells ); cd->AddArray( arr ); this->Cache->Insert( key, arr ); arr->FastDelete(); } if ( ! arr ) { continue; } // OK, the array exists and has the correct number of tuples. Loop over all objects of // this type and insert their values into the global cell array according to their GridOffset. int otypidx = this->GetObjectTypeIndexFromObjectType( ami->first ); BlockSetInfoType* bsinfop; vtkDataArray* src; for ( obj = 0; obj < numObj; ++obj ) { if ( ! ai->ObjectTruth[obj] ) { // skip blocks for which this array doesn't exist. continue; } src = 0; if ( OBJTYPE_IS_BLOCK( otypidx ) ) { BlockInfoType* binfop = &this->BlockInfo[ami->first][obj]; bsinfop = (BlockSetInfoType*) binfop; if ( binfop->Status ) { src = this->GetCacheOrRead( vtkExodusIICacheKey( timeStep, ami->first, obj, aidx ) ); if ( src ) { vtkIdType c; for ( c = 0; c < binfop->Size; ++c ) { cd->CopyTuple( src, arr, c, c + binfop->GridOffset ); } } } } else if ( OBJTYPE_IS_SET( otypidx ) ) { SetInfoType* sinfop = &this->SetInfo[ami->first][obj]; bsinfop = (BlockSetInfoType*) sinfop; if ( sinfop->Status ) { src = this->GetCacheOrRead( vtkExodusIICacheKey( timeStep, ami->first, obj, aidx ) ); if ( src ) { vtkIdType c; for ( c = 0; c < sinfop->Size; ++c ) { cd->CopyTuple( src, arr, c, c + sinfop->GridOffset ); } } } } else { vtkErrorMacro( "Array defined for an unknown type of object: " << ami->first << " with index: " << otypidx << ". Skipping." ); continue; } if ( ! src && bsinfop && bsinfop->Status ) { vtkErrorMacro( "Cell array \"" << ai->Name.c_str() << "\" not defined on " << objtype_names[otypidx] << " " << bsinfop->Id << " but truth table claimed it was. Fixing truth table in memory (not in file)."); ai->ObjectTruth[obj] = 0; } } } } // Step 2. Now that we have very carefully created an array with a storage // type and number of components that match the arrays whose status is 1, // loop over the objects whose status is 1 but that do not have an // an array status of 1 or who have truth table set to 0. These objects // need to pad the arrays with zeros. int otypidx; for ( otypidx = 0; obj_types[otypidx] != vtkExodusIIReader::NODE_MAP; ++otypidx ) { int otyp = obj_types[otypidx]; int obj; int numObj = this->GetNumberOfObjectsOfType( otyp ); int ai; for ( ai = 0; ai < cd->GetNumberOfArrays(); ++ai ) { vtkDataArray* arr = cd->GetArray( ai ); ArrayInfoType* ainfop = this->FindArrayInfoByName( otyp, arr->GetName() ); for ( obj = 0; obj < numObj; ++obj ) { BlockSetInfoType* bsinfop = (BlockSetInfoType*) this->GetObjectInfo( otypidx, obj ); if ( bsinfop && bsinfop->Status && ( !ainfop || ! ainfop->Status || ( ainfop->Status && ! ainfop->ObjectTruth[obj] ) ) ) { vtkstd::vector<double> zedTuple( arr->GetNumberOfComponents(), 0. ); // an empty tuple used to pad arrays vtkIdType i; vtkIdType c = bsinfop->GridOffset; vtkDebugMacro( << arr->GetName() << ": Padding " << bsinfop->Size << " cells at " << c << "\n" ); for ( i = 0; i < bsinfop->Size; ++i, ++c ) { arr->SetTuple( c, &zedTuple[0] ); } } } } } return 1; } int vtkExodusIIReaderPrivate::AssembleOutputPointMaps( vtkIdType timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; int status = 1; vtkstd::vector<MapInfoType>::iterator mi; int midx = 0; for ( mi = this->MapInfo[ vtkExodusIIReader::NODE_MAP ].begin(); mi != this->MapInfo[ vtkExodusIIReader::NODE_MAP ].end(); ++mi, ++midx ) { if ( ! mi->Status ) continue; // Skip arrays we don't want. vtkExodusIICacheKey key( -1, vtkExodusIIReader::NODE_MAP, 0, midx ); vtkDataArray* src = this->GetCacheOrRead( key ); if ( !src ) { vtkWarningMacro( "Unable to read point map array \"" << mi->Name.c_str() << "\" (" << midx << ")" ); status = 0; continue; } this->AddPointArray( src, output ); } return status; } int vtkExodusIIReaderPrivate::AssembleOutputCellMaps( vtkIdType timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; // Step 1. Create the large arrays and fill them (but don't pad them). vtkCellData* cd = output->GetCellData(); vtkstd::map<int,vtkstd::vector<MapInfoType> >::iterator mmi; for ( mmi = this->MapInfo.begin(); mmi != this->MapInfo.end(); ++mmi ) { if ( mmi->first == vtkExodusIIReader::NODAL || mmi->first == vtkExodusIIReader::NODE_MAP ) continue; // we handle nodal arrays in AssembleOutputPointMaps // See if any maps of this type are turned on (Status != 0) int obj; int numObjOn = 0; int numObj = this->GetNumberOfObjectsOfType( mmi->first ); for ( obj = 0; obj < numObj; ++obj ) { if ( this->GetObjectStatus( mmi->first, obj ) ) { ++numObjOn; break; // know we know we need the array } } if ( numObjOn == 0 ) continue; // this array may be on, but no objects of this type are active... skip it. vtkstd::vector<MapInfoType>::iterator mi; int midx = 0; for ( mi = mmi->second.begin(); mi != mmi->second.end(); ++mi, ++midx ) { if ( ! mi->Status ) continue; vtkDataArray* arr = cd->GetArray( mi->Name.c_str() ); if ( arr ) { // OK, we've already created this array for some other type of object, // so now we have to make sure the arrays are consistent. If not, we // turn off the second one we encounter. The user can disable the first // and re-enable the second if required. if ( arr->GetDataType() != VTK_ID_TYPE ) { vtkErrorMacro( "Cell array \"" << mi->Name.c_str() << "\" has conflicting types." ); mi->Status = 0; // Don't load this map. User must disable other array before loading this one. arr = 0; } if ( arr && (arr->GetNumberOfComponents() != 1) ) { vtkErrorMacro( "Cell array \"" << mi->Name.c_str() << "\" has different number of components than map requires." ); mi->Status = 0; // Don't load this block's/set's version. User must disable other block/set before loading this one. arr = 0; } } else { // Create the array arr = vtkIdTypeArray::New(); arr->SetName( mi->Name.c_str() ); arr->SetNumberOfComponents( 1 ); arr->SetNumberOfTuples( this->NumberOfCells ); // Eliminate the second pass that pads cells by initializing the entire array here. memset( arr->GetVoidPointer(0), 0, this->NumberOfCells * sizeof(vtkIdType) ); cd->AddArray( arr ); arr->FastDelete(); } if ( ! arr ) { continue; } // OK, the array exists and has the correct number of tuples. Loop over all objects of // this type and insert their values into the global cell array according to their GridOffset. int otyp = this->GetObjectTypeFromMapType( mmi->first ); BlockInfoType* binfop; vtkDataArray* src; int numBlk = (int) this->BlockInfo[otyp].size(); int blk; src = this->GetCacheOrRead( vtkExodusIICacheKey( -1, mmi->first, 0, midx ) ); if ( src ) { for ( blk = 0; blk < numBlk; ++blk ) { binfop = &this->BlockInfo[otyp][blk]; if ( ! binfop->Status ) continue; vtkIdType c; for ( c = 0; c < binfop->Size; ++c ) { cd->CopyTuple( src, arr, c + binfop->FileOffset - 1, c + binfop->GridOffset ); } } } // === } } return 1; } int vtkExodusIIReaderPrivate::AssembleOutputProceduralArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; int status = 7; if ( this->GenerateObjectIdArray ) { vtkExodusIICacheKey key( -1, vtkExodusIIReader::GLOBAL_OBJECT_ID, 0, 0 ); vtkDataArray* arr = this->GetCacheOrRead( key ); vtkCellData* cd = output->GetCellData(); if ( arr ) { cd->AddArray( arr ); status -= 1; } } if ( this->GenerateGlobalElementIdArray ) { // This retrieves the first new-style map, or if that is not present, // the solitary old-style map (which always exists but may be // procedurally generated if it is not stored with the file). vtkExodusIICacheKey key( -1, vtkExodusIIReader::GLOBAL_ELEMENT_ID, 0, 0 ); vtkDataArray* arr = this->GetCacheOrRead( key ); vtkCellData* cd = output->GetCellData(); if ( arr ) { vtkDataArray* ped = vtkIdTypeArray::New(); ped->DeepCopy( arr ); ped->SetName( vtkExodusIIReader::GetPedigreeElementIdArrayName() ); cd->AddArray( ped ); cd->SetGlobalIds( arr ); ped->FastDelete(); status -= 2; } } if ( this->GenerateGlobalNodeIdArray ) { // This retrieves the first new-style map, or if that is not present, // the solitary old-style map (which always exists but may be // procedurally generated if it is not stored with the file). vtkExodusIICacheKey key( -1, vtkExodusIIReader::GLOBAL_NODE_ID, 0, 0 ); vtkDataArray* arr = this->GetCacheOrRead( key ); vtkPointData* pd = output->GetPointData(); if ( arr ) { vtkDataArray* ped = vtkIdTypeArray::New(); ped->DeepCopy( arr ); ped->SetName( vtkExodusIIReader::GetPedigreeNodeIdArrayName() ); pd->AddArray( ped ); pd->SetGlobalIds( arr ); ped->FastDelete(); status -= 4; } } return status; } void vtkExodusIIReaderPrivate::InsertBlockCells( int otyp, int obj, int conn_type, int timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; BlockInfoType* binfo = &this->BlockInfo[otyp][obj]; if ( binfo->Size == 0 ) { // No entries in this block. // This happens in parallel filesets when all elements are distributed to other files. // Silently ignore. return; } vtkIntArray* arr; arr = vtkIntArray::SafeDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, conn_type, obj, 0 ) ) ); if ( ! arr ) { vtkWarningMacro( "Block wasn't present in file? Working around it. Expect trouble." ); binfo->Status = 0; this->ComputeGridOffsets(); return; } if ( this->SqueezePoints ) { vtkstd::vector<vtkIdType> cellIds; cellIds.resize( binfo->PointsPerCell ); int* srcIds = arr->GetPointer( 0 ); for ( int i = 0; i < binfo->Size; ++i ) { for ( int p = 0; p < binfo->PointsPerCell; ++p ) { cellIds[p] = this->GetSqueezePointId( srcIds[p] ); //cout << " " << srcIds[p] << "(" << cellIds[p] << ")"; } //cout << "\n"; //cout << " " << output->InsertNextCell( binfo->CellType, binfo->PointsPerCell, &cellIds[0] ); srcIds += binfo->PointsPerCell; } //cout << "\n"; } else { #ifdef VTK_USE_64BIT_IDS vtkstd::vector<vtkIdType> cellIds; cellIds.resize( binfo->PointsPerCell ); int* srcIds = arr->GetPointer( 0 ); for ( int i = 0; i < binfo->Size; ++i ) { for ( int p = 0; p < binfo->PointsPerCell; ++p ) { cellIds[p] = srcIds[p]; //cout << " " << srcIds[p]; } //cout << "\n"; output->InsertNextCell( binfo->CellType, binfo->PointsPerCell, &cellIds[0] ); srcIds += binfo->PointsPerCell; } #else // VTK_USE_64BIT_IDS vtkIdType* srcIds = (vtkIdType*) arr->GetPointer( 0 ); for ( int i = 0; i < binfo->Size; ++i ) { output->InsertNextCell( binfo->CellType, binfo->PointsPerCell, srcIds ); srcIds += binfo->PointsPerCell; //for ( int k = 0; k < binfo->PointsPerCell; ++k ) //cout << " " << srcIds[k]; //cout << "\n"; } #endif // VTK_USE_64BIT_IDS } } void vtkExodusIIReaderPrivate::InsertSetCells( int otyp, int obj, int conn_type, int timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; SetInfoType* sinfo = &this->SetInfo[otyp][obj]; if ( sinfo->Size == 0 ) { // No entries in this set. // This happens in parallel filesets when all elements are distributed to other files. // Silently ignore. return; } vtkIntArray* arr = vtkIntArray::SafeDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, conn_type, obj, 0 ) ) ); if ( ! arr ) { vtkWarningMacro( "Set wasn't present in file? Working around it. Expect trouble." ); sinfo->Status = 0; this->ComputeGridOffsets(); return; } switch ( otyp ) { case vtkExodusIIReader::NODE_SET: // Easy this->InsertSetNodeCopies( arr, otyp, obj, output ); break; case vtkExodusIIReader::EDGE_SET: // Not so fun. We must copy cells from possibly many edge blocks. this->InsertSetCellCopies( arr, vtkExodusIIReader::EDGE_BLOCK, obj, output ); break; case vtkExodusIIReader::FACE_SET: // Not so fun. We must copy cells from possibly many face blocks. this->InsertSetCellCopies( arr, vtkExodusIIReader::FACE_BLOCK, obj, output ); break; case vtkExodusIIReader::SIDE_SET: // Way hard even when we let Exodus do a lot for us. this->InsertSetSides( arr, otyp, obj, output ); break; case vtkExodusIIReader::ELEM_SET: // Not so fun. We must copy cells from possibly many element blocks. this->InsertSetCellCopies( arr, vtkExodusIIReader::ELEM_BLOCK, obj, output ); break; } } void vtkExodusIIReaderPrivate::AddPointArray( vtkDataArray* src, vtkUnstructuredGrid* output ) { vtkPointData* pd = output->GetPointData(); if ( this->SqueezePoints ) { // subset the array using PointMap vtkDataArray* dest = vtkDataArray::CreateDataArray( src->GetDataType() ); dest->SetName( src->GetName() ); dest->SetNumberOfComponents( src->GetNumberOfComponents() ); dest->SetNumberOfTuples( this->NextSqueezePoint ); vtkIdType exoPtId; for ( exoPtId = 0; exoPtId < this->ModelParameters.num_nodes; ++exoPtId ) { vtkIdType outPtId = this->PointMap[exoPtId]; if ( outPtId >= 0 ) { pd->CopyTuple( src, dest, exoPtId, outPtId ); } } pd->AddArray( dest ); dest->FastDelete(); } else { pd->AddArray( src ); } } void vtkExodusIIReaderPrivate::InsertSetNodeCopies( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ) { (void)otyp; (void)obj; // Insert a "VERTEX" cell for each node in the set. vtkIdType ref; vtkIdType tmp; int* iptr = refs->GetPointer( 0 ); if ( this->SqueezePoints ) { // this loop is separated out to handle case (stride > 1 && pref[1] < 0 && this->SqueezePoints) for ( ref = 0; ref < refs->GetNumberOfTuples(); ++ref, ++iptr ) { tmp = *iptr; vtkIdType* x = &this->PointMap[tmp]; if ( *x < 0 ) { *x = this->NextSqueezePoint++; } output->InsertNextCell( VTK_VERTEX, 1, x ); } } else { for ( ref = 0; ref < refs->GetNumberOfTuples(); ++ref, ++iptr ) { tmp = *iptr; output->InsertNextCell( VTK_VERTEX, 1, &tmp ); } } } void vtkExodusIIReaderPrivate::InsertSetCellCopies( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ) { (void)obj; // First, sort the set by entry number (element, face, or edge ID) // so that we can refer to each block just once as we process cells. vtkSortDataArray::SortArrayByComponent( refs, 0 ); refs->Register( this ); // Don't let the cache delete this array when we fetch others... vtkIdType nrefs = refs->GetNumberOfTuples(); vtkIdType ref = 0; vtkIdType bnum = -1; vtkIdType lastBlockEntry = -1; int* pref = refs->GetPointer( 0 ); int stride = refs->GetNumberOfComponents(); BlockInfoType* binfop = 0; //&this->BlockInfo[otyp][bnum]; int* nodeconn = 0; vtkIdType* cellConn; int nnpe = 0; vtkIntArray* nconn; vtkstd::vector<vtkIdType> tmpTuple; while ( ref < nrefs ) { int loadNewBlk = 0; while ( pref[0] >= lastBlockEntry ) { // advance to the next block (always true first time through parent loop) ++bnum; if ( bnum >= (int) this->BlockInfo[otyp].size() ) return; binfop = &this->BlockInfo[otyp][bnum]; lastBlockEntry = binfop->FileOffset + binfop->Size - 1; loadNewBlk = 1; } if ( loadNewBlk ) { nconn = vtkIntArray::SafeDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, this->GetBlockConnTypeFromBlockType( otyp ), bnum, 0 ) ) ); if ( ! nconn ) { vtkErrorMacro( "Unable to read block \"" << binfop->Name.c_str() << "\" (" << binfop->Id << ")" ); break; } nodeconn = nconn->GetPointer( 0 ); nnpe = nconn->GetNumberOfComponents(); if ( stride > 1 || this->SqueezePoints ) { tmpTuple.resize( nnpe ); } } if ( stride > 1 && pref[1] < 0 ) { // negative orientation => reverse cell connectivity vtkIdType off = (pref[0] + 2 - binfop->FileOffset) * nnpe - 1; for ( int k = 0; k < nnpe; ++k ) tmpTuple[k] = nodeconn[off-k]; cellConn = &tmpTuple[0]; } else #ifndef VTK_USE_64BIT_IDS if ( this->SqueezePoints ) #endif // VTK_USE_64BIT_IDS { vtkIdType off = (pref[0] + 1 - binfop->FileOffset) * nnpe; for ( int k = 0; k < nnpe; ++k ) tmpTuple[k] = nodeconn[off+k]; cellConn = &tmpTuple[0]; } #ifndef VTK_USE_64BIT_IDS else { cellConn = (int*)nodeconn + (pref[0] + 1 - binfop->FileOffset) * nnpe; } #endif // VTK_USE_64BIT_IDS if ( this->SqueezePoints ) { // this loop is separated out to handle case (stride > 1 && pref[1] < 0 && this->SqueezePoints) for ( int k = 0; k < nnpe; ++k ) { vtkIdType* x = &this->PointMap[cellConn[k]]; if ( *x < 0 ) { *x = this->NextSqueezePoint++; } cellConn[k] = *x; } } output->InsertNextCell( binfop->CellType, nnpe, cellConn ); pref += stride; ++ref; } refs->UnRegister( this ); } void vtkExodusIIReaderPrivate::InsertSetSides( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ) { static const int sideCellTypes[] = { VTK_EMPTY_CELL, // don't support any cells with 0 nodes per side VTK_VERTEX, VTK_LINE, VTK_TRIANGLE, VTK_QUAD, VTK_EMPTY_CELL, // don't support any cells with 5 nodes per side VTK_QUADRATIC_TRIANGLE, VTK_EMPTY_CELL, // don't support any cells with 7 nodes per side VTK_QUADRATIC_QUAD, VTK_BIQUADRATIC_QUAD }; int numSides = this->SetInfo[otyp][obj].Size; int* nodesPerSide = refs->GetPointer( 0 ); int* sideNodes = nodesPerSide + numSides; vtkstd::vector<vtkIdType> cellConn; cellConn.resize( 9 ); if ( this->SqueezePoints ) { int nnpe; for ( int side = 0; side < numSides; ++side ) { nnpe = nodesPerSide[side]; for ( int k = 0; k < nnpe; ++k ) { vtkIdType* x = &this->PointMap[sideNodes[k]]; if ( *x < 0 ) { *x = this->NextSqueezePoint++; } cellConn[k] = *x; } output->InsertNextCell( sideCellTypes[nnpe], nnpe, &cellConn[0] ); sideNodes += nnpe; } } else { int nnpe; for ( int side = 0; side < numSides; ++side ) { nnpe = nodesPerSide[side]; #ifdef VTK_USE_64BIT_IDS for ( int k = 0; k < nnpe; ++k ) { cellConn[k] = sideNodes[k]; } output->InsertNextCell( sideCellTypes[nnpe], nnpe, &cellConn[0] ); #else // VTK_USE_64BIT_IDS output->InsertNextCell( sideCellTypes[nnpe], nnpe, sideNodes ); #endif // VTK_USE_64BIT_IDS sideNodes += nnpe; } } } vtkDataArray* vtkExodusIIReaderPrivate::GetCacheOrRead( vtkExodusIICacheKey key ) { vtkDataArray* arr; // Never cache points deflected for a mode shape animation... doubles don't make good keys. if ( this->HasModeShapes && key.ObjectType == vtkExodusIIReader::NODAL_COORDS ) { arr = 0; } else { arr = this->Cache->Find( key ); } if ( arr ) { // return arr; } int exoid = this->Exoid; // If array is NULL, try reading it from file. if ( key.ObjectType == vtkExodusIIReader::GLOBAL ) { // need to assemble result array from smaller ones. // call GetCacheOrRead() for each smaller array // pay attention to SqueezePoints } else if ( key.ObjectType == vtkExodusIIReader::NODAL ) { // read nodal array ArrayInfoType* ainfop = &this->ArrayInfo[vtkExodusIIReader::NODAL][key.ArrayId]; arr = vtkDataArray::CreateDataArray( ainfop->StorageType ); arr->SetName( ainfop->Name.c_str() ); arr->SetNumberOfComponents( ainfop->Components ); arr->SetNumberOfTuples( this->ModelParameters.num_nodes ); if ( ainfop->Components == 1 ) { if ( ex_get_var( exoid, key.Time + 1, key.ObjectType, ainfop->OriginalIndices[0], 0, arr->GetNumberOfTuples(), arr->GetVoidPointer( 0 ) ) < 0 ) { vtkErrorMacro( "Could not read nodal result variable " << ainfop->Name.c_str() << "." ); arr->Delete(); arr = 0; } } else { // Exodus doesn't support reading with a stride, so we have to manually interleave the arrays. Bleh. vtkstd::vector<vtkstd::vector<double> > tmpVal; tmpVal.resize( ainfop->Components ); int c; for ( c = 0; c < ainfop->Components; ++c ) { vtkIdType N = this->ModelParameters.num_nodes; tmpVal[c].resize( N ); if ( ex_get_var( exoid, key.Time + 1, key.ObjectType, ainfop->OriginalIndices[c], 0, arr->GetNumberOfTuples(), &tmpVal[c][0] ) < 0) { vtkErrorMacro( "Could not read nodal result variable " << ainfop->OriginalNames[c].c_str() << "." ); arr->Delete(); arr = 0; return 0; } } int t; vtkstd::vector<double> tmpTuple; tmpTuple.resize( ainfop->Components ); for ( t = 0; t < arr->GetNumberOfTuples(); ++t ) { for ( c = 0; c < ainfop->Components; ++c ) { tmpTuple[c] = tmpVal[c][t]; } arr->SetTuple( t, &tmpTuple[0] ); } } } else if ( key.ObjectType == vtkExodusIIReader::EDGE_BLOCK || key.ObjectType == vtkExodusIIReader::FACE_BLOCK || key.ObjectType == vtkExodusIIReader::ELEM_BLOCK || key.ObjectType == vtkExodusIIReader::NODE_SET || key.ObjectType == vtkExodusIIReader::EDGE_SET || key.ObjectType == vtkExodusIIReader::FACE_SET || key.ObjectType == vtkExodusIIReader::SIDE_SET || key.ObjectType == vtkExodusIIReader::ELEM_SET ) { int otypidx = this->GetObjectTypeIndexFromObjectType( key.ObjectType ); ArrayInfoType* ainfop = &this->ArrayInfo[key.ObjectType][key.ArrayId]; ObjectInfoType* oinfop = this->GetObjectInfo( otypidx, key.ObjectId ); arr = vtkDataArray::CreateDataArray( ainfop->StorageType ); arr->SetName( ainfop->Name.c_str() ); arr->SetNumberOfComponents( ainfop->Components ); arr->SetNumberOfTuples( oinfop->Size ); if ( ainfop->Components == 1 ) { if ( ex_get_var( exoid, key.Time + 1, key.ObjectType, ainfop->OriginalIndices[0], oinfop->Id, arr->GetNumberOfTuples(), arr->GetVoidPointer( 0 ) ) < 0) { vtkErrorMacro( "Could not read result variable " << ainfop->Name.c_str() << " for " << objtype_names[otypidx] << " " << oinfop->Id << "." ); arr->Delete(); arr = 0; } } else { // Exodus doesn't support reading with a stride, so we have to manually interleave the arrays. Bleh. vtkstd::vector<vtkstd::vector<double> > tmpVal; tmpVal.resize( ainfop->Components ); int c; for ( c = 0; c < ainfop->Components; ++c ) { vtkIdType N = arr->GetNumberOfTuples(); tmpVal[c].resize( N ); if ( ex_get_var( exoid, key.Time + 1, key.ObjectType, ainfop->OriginalIndices[c], oinfop->Id, arr->GetNumberOfTuples(), &tmpVal[c][0] ) < 0) { vtkErrorMacro( "Could not read result variable " << ainfop->OriginalNames[c].c_str() << " for " << objtype_names[otypidx] << " " << oinfop->Id << "." ); arr->Delete(); arr = 0; } } int t; vtkstd::vector<double> tmpTuple; tmpTuple.resize( ainfop->Components ); for ( t = 0; t < arr->GetNumberOfTuples(); ++t ) { for ( c = 0; c < ainfop->Components; ++c ) { tmpTuple[c] = tmpVal[c][t]; } arr->SetTuple( t, &tmpTuple[0] ); } } } else if ( key.ObjectType == vtkExodusIIReader::NODE_MAP || key.ObjectType == vtkExodusIIReader::EDGE_MAP || key.ObjectType == vtkExodusIIReader::FACE_MAP || key.ObjectType == vtkExodusIIReader::ELEM_MAP ) { MapInfoType* minfop = &this->MapInfo[key.ObjectType][key.ArrayId]; vtkIdTypeArray* iarr = vtkIdTypeArray::New(); arr = iarr; arr->SetName( minfop->Name.c_str() ); arr->SetNumberOfComponents( 1 ); switch ( key.ObjectType ) { case vtkExodusIIReader::NODE_MAP: arr->SetNumberOfTuples( this->ModelParameters.num_nodes ); break; case vtkExodusIIReader::EDGE_MAP: arr->SetNumberOfTuples( this->ModelParameters.num_edge ); break; case vtkExodusIIReader::FACE_MAP: arr->SetNumberOfTuples( this->ModelParameters.num_face ); break; case vtkExodusIIReader::ELEM_MAP: arr->SetNumberOfTuples( this->ModelParameters.num_elem ); break; } #ifdef VTK_USE_64BIT_IDS { vtkstd::vector<int> tmpMap( arr->GetNumberOfTuples() ); if ( ex_get_num_map( exoid, key.ObjectType, minfop->Id, &tmpMap[0] ) < 0 ) { vtkErrorMacro( "Could not read map \"" << minfop->Name.c_str() << "\" (" << minfop->Id << ") from disk." ); arr->Delete(); arr = 0; return 0; } for ( vtkIdType i = 0; i < arr->GetNumberOfTuples(); ++i ) { iarr->SetValue( i, tmpMap[i] ); } } #else if ( ex_get_num_map( exoid, key.ObjectType, minfop->Id, (int*)arr->GetVoidPointer( 0 ) ) < 0 ) { vtkErrorMacro( "Could not read nodal map variable " << minfop->Name.c_str() << "." ); arr->Delete(); arr = 0; } #endif // VTK_USE_64BIT_IDS } else if ( key.ObjectType == vtkExodusIIReader::GLOBAL_ELEMENT_ID ) { // subset the ELEMENT_ID array choosing only entries for blocks that have Status ON vtkIdTypeArray* src = vtkIdTypeArray::SafeDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, vtkExodusIIReader::ELEMENT_ID, 0, 0 ) ) ); if ( ! src ) { arr = 0; return 0; } vtkIdTypeArray* iarr = vtkIdTypeArray::New(); iarr->SetName( vtkExodusIIReader::GetGlobalElementIdArrayName() ); iarr->SetNumberOfComponents( 1 ); iarr->SetNumberOfTuples( this->NumberOfCells ); vtkIdType* gloIds = iarr->GetPointer( 0 ); vtkIdType* srcIds = src->GetPointer( 0 ); memset( (void*)gloIds, 0, sizeof(vtkIdType) * this->NumberOfCells ); vtkstd::vector<BlockInfoType>::iterator bi; for ( bi = this->BlockInfo[vtkExodusIIReader::ELEM_BLOCK].begin(); bi != this->BlockInfo[vtkExodusIIReader::ELEM_BLOCK].end(); ++bi ) { if ( ! bi->Status ) continue; vtkIdType x; for ( x = 0; x < bi->Size; ++x ) { gloIds[x + bi->GridOffset] = srcIds[x + bi->FileOffset - 1]; } } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::GLOBAL_NODE_ID ) { // subset the NODE_ID array choosing only entries for nodes in output grid (using PointMap) vtkIdTypeArray* src = vtkIdTypeArray::SafeDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, vtkExodusIIReader::NODE_ID, 0, 0 ) ) ); if ( ! src ) { arr = 0; return 0; } vtkIdTypeArray* iarr = vtkIdTypeArray::New(); iarr->SetName( vtkExodusIIReader::GetGlobalNodeIdArrayName() ); iarr->SetNumberOfComponents( 1 ); iarr->SetNumberOfTuples( this->NextSqueezePoint ); vtkIdType* gloIds = iarr->GetPointer( 0 ); vtkIdType* srcIds = src->GetPointer( 0 ); vtkIdType pt; for ( pt = 0; pt < this->ModelParameters.num_nodes; ++pt ) { vtkIdType x = this->PointMap[pt]; if ( x >= 0 ) { gloIds[x] = srcIds[pt]; } } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::ELEMENT_ID || key.ObjectType == vtkExodusIIReader::NODE_ID ) { vtkIdTypeArray* iarr; int nMaps; vtkIdType mapSize; vtkExodusIICacheKey ktmp; vtkExodusIIGetMapFunc getMapFunc; if ( key.ObjectType == vtkExodusIIReader::ELEMENT_ID ) { nMaps = this->ModelParameters.num_elem_maps; mapSize = this->ModelParameters.num_elem; ktmp = vtkExodusIICacheKey( -1, vtkExodusIIReader::ELEM_MAP, 0, 0 ); getMapFunc = ex_get_elem_num_map; } else // ( key.ObjectType == vtkExodusIIReader::NODE_ID ) { nMaps = this->ModelParameters.num_node_maps; mapSize = this->ModelParameters.num_nodes; ktmp = vtkExodusIICacheKey( -1, vtkExodusIIReader::NODE_MAP, 0, 0 ); getMapFunc = ex_get_node_num_map; } // If there are no new-style maps, get the old-style map (which creates a default if nothing is stored on disk). if ( nMaps < 1 || ! (iarr = vtkIdTypeArray::SafeDownCast(this->GetCacheOrRead( ktmp ))) ) { iarr = vtkIdTypeArray::New(); iarr->SetNumberOfComponents( 1 ); iarr->SetNumberOfTuples( mapSize ); if ( mapSize ) { #ifdef VTK_USE_64BIT_IDS vtkstd::vector<int> tmpMap( iarr->GetNumberOfTuples() ); if ( getMapFunc( exoid, &tmpMap[0] ) < 0 ) { vtkErrorMacro( "Could not read old-style node or element map." ); iarr->Delete(); iarr = 0; } else { for ( vtkIdType i = 0; i < iarr->GetNumberOfTuples(); ++i ) { iarr->SetValue( i, tmpMap[i] ); } } #else if ( getMapFunc( exoid, (int*)iarr->GetPointer( 0 ) ) < 0 ) { vtkErrorMacro( "Could not read old-style node or element map." ); iarr->Delete(); iarr = 0; } #endif // VTK_USE_64BIT_IDS } } else { // FastDelete will be called below (because we are assumed to have created the array with New()). // So we must reference the array one extra time here to account for the extra delete... iarr->Register( this ); } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::GLOBAL_CONN ) { vtkErrorMacro( "Global connectivity is created in AssembleOutputConnectivity since it can't be cached\n" "with a single vtkDataArray. Who told you to call this routine to get it?" ); } else if ( key.ObjectType == vtkExodusIIReader::ELEM_BLOCK_ELEM_CONN || key.ObjectType == vtkExodusIIReader::FACE_BLOCK_CONN || key.ObjectType == vtkExodusIIReader::EDGE_BLOCK_CONN ) { int ctypidx = this->GetConnTypeIndexFromConnType( key.ObjectType ); int otypidx = conn_obj_idx_cvt[ctypidx]; int otyp = obj_types[ otypidx ]; BlockInfoType* binfop = (BlockInfoType*) this->GetObjectInfo( otypidx, key.ObjectId ); vtkIntArray* iarr = vtkIntArray::New(); iarr->SetNumberOfComponents( binfop->BdsPerEntry[0] ); iarr->SetNumberOfTuples( binfop->Size ); if ( ex_get_conn( exoid, otyp, binfop->Id, iarr->GetPointer(0), 0, 0 ) < 0 ) { vtkErrorMacro( "Unable to read " << objtype_names[otypidx] << " " << binfop->Id << " (index " << key.ObjectId << ") nodal connectivity." ); iarr->Delete(); iarr = 0; } vtkIdType c; int* ptr = iarr->GetPointer( 0 ); if ( binfop->CellType == VTK_QUADRATIC_HEXAHEDRON || binfop->CellType == VTK_TRIQUADRATIC_HEXAHEDRON ) { // Edge order for VTK is different than Exodus edge order. for ( c = 0; c < iarr->GetNumberOfTuples(); ++c ) { int k; int itmp[4]; for ( k = 0; k < 12; ++k, ++ptr) *ptr = *ptr - 1; for ( k = 0; k < 4; ++k, ++ptr) { itmp[k] = *ptr; *ptr = ptr[4] - 1; } for ( k = 0; k < 4; ++k, ++ptr ) *ptr = itmp[k] - 1; if ( binfop->CellType == VTK_TRIQUADRATIC_HEXAHEDRON ) { for ( k = 0; k < 4; ++k, ++ptr ) *ptr = *ptr - 1; } } ptr += binfop->BdsPerEntry[0] - binfop->PointsPerCell; } else { for ( c = 0; c <= iarr->GetMaxId(); ++c, ++ptr ) { *ptr = *ptr - 1; } } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::ELEM_BLOCK_FACE_CONN ) { // FIXME: Call ex_get_conn with non-NULL face conn pointer // This won't be needed until the Exodus reader outputs multiblock data with vtkGenericDataSet blocks for higher order meshes. arr = 0; } else if ( key.ObjectType == vtkExodusIIReader::ELEM_BLOCK_EDGE_CONN ) { // FIXME: Call ex_get_conn with non-NULL edge conn pointer // This won't be needed until the Exodus reader outputs multiblock data with vtkGenericDataSet blocks for higher order meshes. arr = 0; } else if ( key.ObjectType == vtkExodusIIReader::NODE_SET_CONN || key.ObjectType == vtkExodusIIReader::ELEM_SET_CONN ) { int otyp = this->GetSetTypeFromSetConnType( key.ObjectType ); int otypidx = this->GetObjectTypeIndexFromObjectType( otyp ); SetInfoType* sinfop = &this->SetInfo[otyp][key.ObjectId]; vtkIntArray* iarr = vtkIntArray::New(); iarr->SetNumberOfComponents( 1 ); iarr->SetNumberOfTuples( sinfop->Size ); int* iptr = iarr->GetPointer( 0 ); if ( ex_get_set( exoid, otyp, sinfop->Id, iptr, 0 ) < 0 ) { vtkErrorMacro( "Unable to read " << objtype_names[otypidx] << " " << sinfop->Id << " (index " << key.ObjectId << ") nodal connectivity." ); iarr->Delete(); iarr = 0; } vtkIdType id; for ( id = 0; id < sinfop->Size; ++id, ++iptr ) { // VTK uses 0-based indexing, unlike Exodus: --(*iptr); } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::EDGE_SET_CONN || key.ObjectType == vtkExodusIIReader::FACE_SET_CONN ) { int otyp = this->GetSetTypeFromSetConnType( key.ObjectType ); int otypidx = this->GetObjectTypeIndexFromObjectType( otyp ); SetInfoType* sinfop = &this->SetInfo[otyp][key.ObjectId]; vtkIntArray* iarr = vtkIntArray::New(); iarr->SetNumberOfComponents( 2 ); iarr->SetNumberOfTuples( sinfop->Size ); vtkstd::vector<int> tmpOrient; // hold the edge/face orientation information until we can interleave it. tmpOrient.resize( sinfop->Size ); if ( ex_get_set( exoid, otyp, sinfop->Id, iarr->GetPointer(0), &tmpOrient[0] ) < 0 ) { vtkErrorMacro( "Unable to read " << objtype_names[otypidx] << " " << sinfop->Id << " (index " << key.ObjectId << ") nodal connectivity." ); iarr->Delete(); iarr = 0; return 0; } int* iap = iarr->GetPointer( 0 ); vtkIdType c; for ( c = sinfop->Size - 1; c >= 0; --c ) { iap[2*c] = iap[c] - 1; // VTK uses 0-based indexing iap[2*c + 1] = tmpOrient[c]; } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::SIDE_SET_CONN ) { // Stick all of side_set_node_list and side_set_node_count and side_set_nodes_per_side in one array // let InsertSetSides() figure it all out. Except for 0-based indexing SetInfoType* sinfop = &this->SetInfo[vtkExodusIIReader::SIDE_SET][key.ObjectId]; int ssnllen; // side set node list length if ( ex_get_side_set_node_list_len( exoid, sinfop->Id, &ssnllen ) < 0 ) { vtkErrorMacro( "Unable to fetch side set \"" << sinfop->Name.c_str() << "\" (" << sinfop->Id << ") node list length" ); arr = 0; return 0; } vtkIntArray* iarr = vtkIntArray::New(); vtkIdType ilen = ssnllen + sinfop->Size; iarr->SetNumberOfComponents( 1 ); iarr->SetNumberOfTuples( ilen ); int* dat = iarr->GetPointer( 0 ); if ( ex_get_side_set_node_list( exoid, sinfop->Id, dat, dat + sinfop->Size ) < 0 ) { vtkErrorMacro( "Unable to fetch side set \"" << sinfop->Name.c_str() << "\" (" << sinfop->Id << ") node list" ); iarr->Delete(); arr = 0; return 0; } while ( ilen > sinfop->Size ) { // move to 0-based indexing on nodes, don't touch nodes/side counts at head of array --dat[--ilen]; } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::NODAL_COORDS ) { // read node coords vtkDataArray* displ = 0; if ( this->ApplyDisplacements && key.Time >= 0 ) { displ = this->FindDisplacementVectors( key.Time ); } vtkstd::vector<double> coordTmp; vtkDoubleArray* darr = vtkDoubleArray::New(); arr = darr; arr->SetNumberOfComponents( 3 ); arr->SetNumberOfTuples( this->ModelParameters.num_nodes ); int dim = this->ModelParameters.num_dim; int c; vtkIdType t; double* xc = 0; double* yc = 0; double* zc = 0; coordTmp.resize( this->ModelParameters.num_nodes ); for ( c = 0; c < dim; ++c ) { switch ( c ) { case 0: xc = &coordTmp[0]; break; case 1: yc = xc; xc = 0; break; case 2: zc = yc; yc = 0; break; default: vtkErrorMacro( "Bad coordinate index " << c << " when reading point coordinates." ); xc = yc = zc = 0; } if ( ex_get_coord( exoid, xc, yc, zc ) < 0 ) { vtkErrorMacro( "Unable to read node coordinates for index " << c << "." ); arr->Delete(); arr = 0; break; } double* cptr = darr->GetPointer( c ); for ( t = 0; t < this->ModelParameters.num_nodes; ++t ) { *cptr = coordTmp[t]; cptr += 3; } } if ( dim < 3 ) { double* cptr = darr->GetPointer( 2 ); for ( t = 0; t < this->ModelParameters.num_nodes; ++t, cptr += 3 ) { *cptr = 0.; } } if ( displ ) { double* coords = darr->GetPointer( 0 ); if ( this->HasModeShapes ) { for ( vtkIdType idx = 0; idx < displ->GetNumberOfTuples(); ++idx ) { double* dispVal = displ->GetTuple3( idx ); for ( c = 0; c < 3; ++c ) coords[c] += dispVal[c] * this->DisplacementMagnitude * cos( 2. * vtkMath::DoublePi() * this->ModeShapeTime ); coords += 3; } } else { for ( vtkIdType idx = 0; idx < displ->GetNumberOfTuples(); ++idx ) { double* dispVal = displ->GetTuple3( idx ); for ( c = 0; c < 3; ++c ) coords[c] += dispVal[c] * this->DisplacementMagnitude; coords += 3; } } } } else if ( key.ObjectType == vtkExodusIIReader::GLOBAL_OBJECT_ID ) { arr = vtkIntArray::New(); arr->SetName( this->GetObjectIdArrayName() ); arr->SetNumberOfComponents( 1 ); arr->SetNumberOfTuples( this->NumberOfCells ); int conntypidx; for ( conntypidx = 0; conntypidx < num_conn_types; ++conntypidx ) { int otypidx = conn_obj_idx_cvt[conntypidx]; int obj; int numObj = this->GetNumberOfObjectsAtTypeIndex( otypidx ); BlockSetInfoType* bsinfop; for ( obj = 0; obj < numObj; ++obj ) { bsinfop = (BlockSetInfoType*) this->GetObjectInfo( otypidx, obj ); if ( ! bsinfop->Status ) continue; vtkIdType c; for ( c = 0; c < bsinfop->Size; ++c ) { arr->SetTuple1( c + bsinfop->GridOffset, bsinfop->Id ); } } } } else if ( key.ObjectType == vtkExodusIIReader::ELEM_BLOCK_ATTRIB || key.ObjectType == vtkExodusIIReader::FACE_BLOCK_ATTRIB || key.ObjectType == vtkExodusIIReader::EDGE_BLOCK_ATTRIB ) { BlockInfoType* binfop = &this->BlockInfo[key.ObjectType][key.ObjectId]; vtkDoubleArray* darr = vtkDoubleArray::New(); arr = darr; darr->SetName( binfop->AttributeNames[key.ArrayId].c_str() ); darr->SetNumberOfComponents( 1 ); darr->SetNumberOfTuples( binfop->Size ); if ( ex_get_one_attr( exoid, key.ObjectType, key.ObjectId, key.ArrayId, darr->GetVoidPointer( 0 ) ) < 0 ) { // NB: The error message references the file-order object id, not the numerically sorted index presented to users. vtkErrorMacro( "Unable to read attribute " << key.ArrayId << " for object " << key.ObjectId << " of type " << key.ObjectType << "." ); arr->Delete(); arr = 0; } } else { vtkWarningMacro( "You requested an array for objects of type " << key.ObjectType << " which I know nothing about" ); arr = 0; } // Even if the array is larger than the allowable cache size, it will keep the most recent insertion. // So, we delete our reference knowing that the Cache will keep the object "alive" until whatever // called GetCacheOrRead() references the array. But, once you get an array from GetCacheOrRead(), // you better start running! if ( arr ) { this->Cache->Insert( key, arr ); arr->FastDelete(); } return arr; } int vtkExodusIIReaderPrivate::GetConnTypeIndexFromConnType( int ctyp ) { int i; for ( i = 0; i < num_conn_types; ++i ) { if ( conn_types[i] == ctyp ) { return i; } } return -1; } int vtkExodusIIReaderPrivate::GetObjectTypeIndexFromObjectType( int otyp ) { int i; for ( i = 0; i < num_obj_types; ++i ) { if ( obj_types[i] == otyp ) { return i; } } return -1; } int vtkExodusIIReaderPrivate::GetNumberOfObjectsAtTypeIndex( int typeIndex ) { if ( typeIndex < 0 ) { return 0; } else if ( typeIndex < 3 ) { return (int) this->BlockInfo[obj_types[typeIndex]].size(); } else if ( typeIndex < 8 ) { return (int) this->SetInfo[obj_types[typeIndex]].size(); } else if ( typeIndex < 12 ) { return (int) this->MapInfo[obj_types[typeIndex]].size(); } return 0; } vtkExodusIIReaderPrivate::ObjectInfoType* vtkExodusIIReaderPrivate::GetObjectInfo( int typeIndex, int objectIndex ) { if ( typeIndex < 0 ) { return 0; } else if ( typeIndex < 3 ) { return &this->BlockInfo[obj_types[typeIndex]][objectIndex]; } else if ( typeIndex < 8 ) { return &this->SetInfo[obj_types[typeIndex]][objectIndex]; } else if ( typeIndex < 12 ) { return &this->MapInfo[obj_types[typeIndex]][objectIndex]; } return 0; } vtkExodusIIReaderPrivate::ObjectInfoType* vtkExodusIIReaderPrivate::GetSortedObjectInfo( int otyp, int k ) { int i = this->GetObjectTypeIndexFromObjectType( otyp ); if ( i < 0 ) { vtkWarningMacro( "Could not find collection of objects with type " << otyp << "." ); return 0; } int N = this->GetNumberOfObjectsAtTypeIndex( i ); if ( k < 0 || k >= N ) { const char* otname = i >= 0 ? objtype_names[i] : "object"; vtkWarningMacro( "You requested " << otname << " " << k << " in a collection of only " << N << " objects." ); return 0; } return this->GetObjectInfo( i, this->SortedObjectIndices[otyp][k] ); } vtkExodusIIReaderPrivate::ObjectInfoType* vtkExodusIIReaderPrivate::GetUnsortedObjectInfo( int otyp, int k ) { int i = this->GetObjectTypeIndexFromObjectType( otyp ); if ( i < 0 ) { vtkWarningMacro( "Could not find collection of objects with type " << otyp << "." ); return 0; } int N = this->GetNumberOfObjectsAtTypeIndex( i ); if ( k < 0 || k >= N ) { const char* otname = i >= 0 ? objtype_names[i] : "object"; vtkWarningMacro( "You requested " << otname << " " << k << " in a collection of only " << N << " objects." ); return 0; } return this->GetObjectInfo( i, k ); } int vtkExodusIIReaderPrivate::GetBlockIndexFromFileGlobalId( int otyp, int refId ) { vtkstd::vector<BlockInfoType>::iterator bi; int i = 0; for ( bi = this->BlockInfo[otyp].begin(); bi != this->BlockInfo[otyp].end(); ++bi, ++i ) { if ( refId >= bi->FileOffset && refId <= bi->FileOffset + bi->Size ) return i; } return -1; } vtkExodusIIReaderPrivate::BlockInfoType* vtkExodusIIReaderPrivate::GetBlockFromFileGlobalId( int otyp, int refId ) { int blk = this->GetBlockIndexFromFileGlobalId( otyp, refId ); if ( blk >= 0 ) { return &this->BlockInfo[otyp][blk]; } return 0; } vtkIdType vtkExodusIIReaderPrivate::GetSqueezePointId( int i ) { vtkIdType* x = &this->PointMap[i]; if ( *x < 0 ) { *x = this->NextSqueezePoint++; } return *x; } void vtkExodusIIReaderPrivate::DetermineVtkCellType( BlockInfoType& binfo ) { vtkStdString elemType( vtksys::SystemTools::UpperCase( binfo.TypeName ) ); // Check for quadratic elements if ((elemType.substr(0,3) == "TRI") && (binfo.BdsPerEntry[0] == 6)) { binfo.CellType=VTK_QUADRATIC_TRIANGLE; binfo.PointsPerCell = 6; } else if ((elemType.substr(0,3) == "SHE") && (binfo.BdsPerEntry[0] == 8)) { binfo.CellType=VTK_QUADRATIC_QUAD; binfo.PointsPerCell = 8; } else if ((elemType.substr(0,3) == "SHE") && (binfo.BdsPerEntry[0] == 9)) { binfo.CellType=VTK_QUADRATIC_QUAD; binfo.PointsPerCell = 8; } else if ((elemType.substr(0,3) == "TET") && (binfo.BdsPerEntry[0] == 10)) { binfo.CellType=VTK_QUADRATIC_TETRA; binfo.PointsPerCell = 10; } else if ((elemType.substr(0,3) == "TET") && (binfo.BdsPerEntry[0] == 11)) { binfo.CellType=VTK_QUADRATIC_TETRA; binfo.PointsPerCell = 10; } else if ((elemType.substr(0,3) == "HEX") && (binfo.BdsPerEntry[0] == 20)) { binfo.CellType=VTK_QUADRATIC_HEXAHEDRON; binfo.PointsPerCell = 20; } else if ((elemType.substr(0,3) == "HEX") && (binfo.BdsPerEntry[0] == 21)) { binfo.CellType=VTK_QUADRATIC_HEXAHEDRON; binfo.PointsPerCell = 20; } else if ((elemType.substr(0,3) == "HEX") && (binfo.BdsPerEntry[0] == 27)) { binfo.CellType=VTK_TRIQUADRATIC_HEXAHEDRON; binfo.PointsPerCell = 27; } else if ((elemType.substr(0,3) == "QUA") && (binfo.BdsPerEntry[0] == 8)) { binfo.CellType=VTK_QUADRATIC_QUAD; binfo.PointsPerCell = 8; } else if ((elemType.substr(0,3) == "QUA") && (binfo.BdsPerEntry[0] == 9)) { binfo.CellType=VTK_BIQUADRATIC_QUAD; binfo.PointsPerCell = 9; } else if ((elemType.substr(0,3) == "TRU") && (binfo.BdsPerEntry[0] == 3)) { binfo.CellType=VTK_QUADRATIC_EDGE; binfo.PointsPerCell = 3; } else if ((elemType.substr(0,3) == "BEA") && (binfo.BdsPerEntry[0] == 3)) { binfo.CellType=VTK_QUADRATIC_EDGE; binfo.PointsPerCell = 3; } else if ((elemType.substr(0,3) == "BAR") && (binfo.BdsPerEntry[0] == 3)) { binfo.CellType=VTK_QUADRATIC_EDGE; binfo.PointsPerCell = 3; } else if ((elemType.substr(0,3) == "EDG") && (binfo.BdsPerEntry[0] == 3)) { binfo.CellType=VTK_QUADRATIC_EDGE; binfo.PointsPerCell = 3; } // Check for regular elements else if ((elemType.substr(0,3) == "CIR")) { binfo.CellType = VTK_VERTEX; binfo.PointsPerCell = 1; } else if ((elemType.substr(0,3) == "SPH")) { binfo.CellType = VTK_VERTEX; binfo.PointsPerCell = 1; } else if ((elemType.substr(0,3) == "BAR")) { binfo.CellType = VTK_LINE; binfo.PointsPerCell = 2; } else if ((elemType.substr(0,3) == "TRU")) { binfo.CellType = VTK_LINE; binfo.PointsPerCell = 2; } else if ((elemType.substr(0,3) == "BEA")) { binfo.CellType = VTK_LINE; binfo.PointsPerCell = 2; } else if ((elemType.substr(0,3) == "EDG")) { binfo.CellType = VTK_LINE; binfo.PointsPerCell = 2; } else if ((elemType.substr(0,3) == "TRI")) { binfo.CellType = VTK_TRIANGLE; binfo.PointsPerCell = 3; } else if ((elemType.substr(0,3) == "QUA")) { binfo.CellType = VTK_QUAD; binfo.PointsPerCell = 4; } else if ((elemType.substr(0,3) == "TET")) { binfo.CellType = VTK_TETRA; binfo.PointsPerCell = 4; } else if ((elemType.substr(0,3) == "PYR")) { binfo.CellType = VTK_PYRAMID; binfo.PointsPerCell = 5; } else if ((elemType.substr(0,3) == "WED")) { binfo.CellType = VTK_WEDGE; binfo.PointsPerCell = 6; } else if ((elemType.substr(0,3) == "HEX")) { binfo.CellType = VTK_HEXAHEDRON; binfo.PointsPerCell = 8; } else if ((elemType.substr(0,3) == "SHE") && (binfo.BdsPerEntry[0] == 3)) { binfo.CellType = VTK_TRIANGLE; binfo.PointsPerCell = 3; } else if ((elemType.substr(0,3) == "SHE") && (binfo.BdsPerEntry[0] == 4)) { binfo.CellType = VTK_QUAD; binfo.PointsPerCell = 4; } else if ((elemType.substr(0,8) == "STRAIGHT") && (binfo.BdsPerEntry[0] == 2 )) { binfo.CellType = VTK_LINE; binfo.PointsPerCell = 2; } else if ((elemType.substr(0,8) == "NULL") && (binfo.Size == 0)) { (void)binfo; // silently ignore empty element blocks } else { vtkErrorMacro("Unsupported element type: " << elemType.c_str()); } //cell types not currently handled //quadratic wedge - 15,16 nodes //quadratic pyramid - 13 nodes } vtkExodusIIReaderPrivate::ArrayInfoType* vtkExodusIIReaderPrivate::FindArrayInfoByName( int otyp, const char* name ) { vtkstd::vector<ArrayInfoType>::iterator ai; for ( ai = this->ArrayInfo[otyp].begin(); ai != this->ArrayInfo[otyp].end(); ++ai ) { if ( ai->Name == name ) return &(*ai); } return 0; } int vtkExodusIIReaderPrivate::IsObjectTypeBlock( int otyp ) { return (otyp == vtkExodusIIReader::ELEM_BLOCK || otyp == vtkExodusIIReader::EDGE_BLOCK || otyp == vtkExodusIIReader::FACE_BLOCK); } int vtkExodusIIReaderPrivate::IsObjectTypeSet( int otyp ) { return (otyp == vtkExodusIIReader::ELEM_SET || otyp == vtkExodusIIReader::EDGE_SET || otyp == vtkExodusIIReader::FACE_SET || otyp == vtkExodusIIReader::NODE_SET || otyp == vtkExodusIIReader::SIDE_SET); } int vtkExodusIIReaderPrivate::IsObjectTypeMap( int otyp ) { return (otyp == vtkExodusIIReader::ELEM_MAP || otyp == vtkExodusIIReader::EDGE_MAP || otyp == vtkExodusIIReader::FACE_MAP || otyp == vtkExodusIIReader::NODE_MAP); } int vtkExodusIIReaderPrivate::GetObjectTypeFromMapType( int mtyp ) { switch (mtyp) { case vtkExodusIIReader::ELEM_MAP: return vtkExodusIIReader::ELEM_BLOCK; case vtkExodusIIReader::FACE_MAP: return vtkExodusIIReader::FACE_BLOCK; case vtkExodusIIReader::EDGE_MAP: return vtkExodusIIReader::EDGE_BLOCK; case vtkExodusIIReader::NODE_MAP: return vtkExodusIIReader::NODAL; } return -1; } int vtkExodusIIReaderPrivate::GetMapTypeFromObjectType( int otyp ) { switch (otyp) { case vtkExodusIIReader::ELEM_BLOCK: return vtkExodusIIReader::ELEM_MAP; case vtkExodusIIReader::FACE_BLOCK: return vtkExodusIIReader::FACE_MAP; case vtkExodusIIReader::EDGE_BLOCK: return vtkExodusIIReader::EDGE_MAP; case vtkExodusIIReader::NODAL: return vtkExodusIIReader::NODE_MAP; } return -1; } int vtkExodusIIReaderPrivate::GetSetTypeFromSetConnType( int sctyp ) { switch ( sctyp ) { case vtkExodusIIReader::NODE_SET_CONN: return vtkExodusIIReader::NODE_SET; case vtkExodusIIReader::EDGE_SET_CONN: return vtkExodusIIReader::EDGE_SET; case vtkExodusIIReader::FACE_SET_CONN: return vtkExodusIIReader::FACE_SET; case vtkExodusIIReader::SIDE_SET_CONN: return vtkExodusIIReader::SIDE_SET; case vtkExodusIIReader::ELEM_SET_CONN: return vtkExodusIIReader::ELEM_SET; } return -1; } int vtkExodusIIReaderPrivate::GetBlockConnTypeFromBlockType( int btyp ) { switch ( btyp ) { case vtkExodusIIReader::EDGE_BLOCK: return vtkExodusIIReader::EDGE_BLOCK_CONN; case vtkExodusIIReader::FACE_BLOCK: return vtkExodusIIReader::FACE_BLOCK_CONN; case vtkExodusIIReader::ELEM_BLOCK: return vtkExodusIIReader::ELEM_BLOCK_ELEM_CONN; } return -1; } void vtkExodusIIReaderPrivate::RemoveBeginningAndTrailingSpaces( int len, char **names ) { int i, j; for (i=0; i<len; i++) { char *c = names[i]; int nmlen = (int)strlen(c); char *cbegin = c; char *cend = c + nmlen - 1; // remove spaces or non-printing character from start and end for (j=0; j<nmlen; j++) { if (!isgraph(*cbegin)) cbegin++; else break; } for (j=0; j<nmlen; j++) { if (!isgraph(*cend)) cend--; else break; } if (cend < cbegin) { sprintf(names[i], "null_%d", i); continue; } int newlen = cend - cbegin + 1; if (newlen < nmlen) { for (j=0; j<newlen; j++) { *c++ = *cbegin++; } *c = '\0'; } } } int vtkExodusIIReaderPrivate::GetNumberOfParts() { return this->PartInfo.size(); } const char* vtkExodusIIReaderPrivate::GetPartName(int idx) { return this->PartInfo[idx].Name.c_str(); } const char* vtkExodusIIReaderPrivate::GetPartBlockInfo(int idx) { char buffer[80]; vtkStdString blocks; vtkstd::vector<int> blkIndices = this->PartInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { sprintf(buffer,"%d, ",blkIndices[i]); blocks += buffer; } blocks.erase(blocks.size()-2,blocks.size()-1); return blocks.c_str(); } int vtkExodusIIReaderPrivate::GetPartStatus(int idx) { //a part is only active if all its blocks are active vtkstd::vector<int> blkIndices = this->PartInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { if (!this->GetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK,blkIndices[i])) { return 0; } } return 1; } int vtkExodusIIReaderPrivate::GetPartStatus(vtkStdString name) { for (unsigned int i=0;i<this->PartInfo.size();i++) { if (this->PartInfo[i].Name==name) { return this->GetPartStatus(i); } } return -1; } void vtkExodusIIReaderPrivate::SetPartStatus(int idx, int on) { //update the block status for all the blocks in this part vtkstd::vector<int> blkIndices = this->PartInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { this->SetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK, blkIndices[i], on); } } void vtkExodusIIReaderPrivate::SetPartStatus(vtkStdString name, int flag) { for(unsigned int idx=0; idx<this->PartInfo.size(); ++idx) { if ( name == this->PartInfo[idx].Name ) { this->SetPartStatus(idx,flag); return; } } } int vtkExodusIIReaderPrivate::GetNumberOfMaterials() { return this->MaterialInfo.size(); } const char* vtkExodusIIReaderPrivate::GetMaterialName(int idx) { return this->MaterialInfo[idx].Name.c_str(); } int vtkExodusIIReaderPrivate::GetMaterialStatus(int idx) { vtkstd::vector<int> blkIndices = this->MaterialInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { if (!this->GetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK,blkIndices[i])) { return 0; } } return 1; } int vtkExodusIIReaderPrivate::GetMaterialStatus(vtkStdString name) { for (unsigned int i=0;i<this->MaterialInfo.size();i++) { if (this->MaterialInfo[i].Name==name) { return this->GetMaterialStatus(i); } } return -1; } void vtkExodusIIReaderPrivate::SetMaterialStatus(int idx, int on) { //update the block status for all the blocks in this material vtkstd::vector<int> blkIndices = this->MaterialInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { this->SetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK,blkIndices[i],on); } } void vtkExodusIIReaderPrivate::SetMaterialStatus(vtkStdString name, int flag) { for(unsigned int idx=0; idx<this->MaterialInfo.size(); ++idx) { if ( name == this->MaterialInfo[idx].Name ) { this->SetMaterialStatus(idx,flag); return; } } } int vtkExodusIIReaderPrivate::GetNumberOfAssemblies() { return this->AssemblyInfo.size(); } const char* vtkExodusIIReaderPrivate::GetAssemblyName(int idx) { return this->AssemblyInfo[idx].Name.c_str(); } int vtkExodusIIReaderPrivate::GetAssemblyStatus(int idx) { vtkstd::vector<int> blkIndices = this->AssemblyInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { if (!this->GetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK,blkIndices[i])) { return 0; } } return 1; } int vtkExodusIIReaderPrivate::GetAssemblyStatus(vtkStdString name) { for (unsigned int i=0;i<this->AssemblyInfo.size();i++) { if (this->AssemblyInfo[i].Name==name) { return this->GetAssemblyStatus(i); } } return -1; } void vtkExodusIIReaderPrivate::SetAssemblyStatus(int idx, int on) { vtkstd::vector<int> blkIndices = this->AssemblyInfo[idx].BlockIndices; //update the block status for all the blocks in this material for (unsigned int i=0;i<blkIndices.size();i++) { this->SetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK,blkIndices[i],on); } } void vtkExodusIIReaderPrivate::SetAssemblyStatus(vtkStdString name, int flag) { for(unsigned int idx=0; idx<this->AssemblyInfo.size(); ++idx) { if ( name == this->AssemblyInfo[idx].Name ) { this->SetAssemblyStatus(idx,flag); return; } } } // Normally, this would be below with all the other vtkExodusIIReader member definitions, // but the Tcl PrintSelf test script is really lame. void vtkExodusIIReader::PrintSelf( ostream& os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); os << indent << "FileName: " << ( this->FileName ? this->FileName : "(null)" ) << "\n"; os << indent << "XMLFileName: " << ( this->XMLFileName ? this->XMLFileName : "(null)" ) << "\n"; os << indent << "DisplayType: " << this->DisplayType << "\n"; os << indent << "TimeStep: " << this->TimeStep << "\n"; os << indent << "TimeStepRange: [" << this->TimeStepRange[0] << ", " << this->TimeStepRange[1] << "]\n"; os << indent << "ExodusModelMetadata: " << (this->ExodusModelMetadata ? "ON" : "OFF" ) << "\n"; os << indent << "PackExodusModelOntoOutput: " << (this->PackExodusModelOntoOutput ? "ON" : "OFF" ) << "\n"; os << indent << "ExodusModel: " << this->ExodusModel << "\n"; if ( this->Metadata ) { os << indent << "Metadata:\n"; this->Metadata->PrintData( os, indent.GetNextIndent() ); } else { os << indent << "Metadata: (null)\n"; } } void vtkExodusIIReaderPrivate::PrintData( ostream& os, vtkIndent indent ) { //this->Superclass::Print Self( os, indent ); os << indent << "Exoid: " << this->Exoid << "\n"; os << indent << "AppWordSize: " << this->AppWordSize << "\n"; os << indent << "DiskWordSize: " << this->DiskWordSize << "\n"; os << indent << "ExodusVersion: " << this->ExodusVersion << "\n"; os << indent << "ModelParameters:\n"; vtkIndent inden2 = indent.GetNextIndent(); os << inden2 << "Title: " << this->ModelParameters.title << "\n"; os << inden2 << "Dimension: " << this->ModelParameters.num_dim << "\n"; os << inden2 << "Nodes: " << this->ModelParameters.num_nodes << "\n"; os << inden2 << "Edges: " << this->ModelParameters.num_edge << "\n"; os << inden2 << "Faces: " << this->ModelParameters.num_face << "\n"; os << inden2 << "Elements: " << this->ModelParameters.num_elem << "\n"; os << inden2 << "Edge Blocks: " << this->ModelParameters.num_edge_blk << "\n"; os << inden2 << "Face Blocks: " << this->ModelParameters.num_face_blk << "\n"; os << inden2 << "Element Blocks: " << this->ModelParameters.num_elem_blk << "\n"; os << inden2 << "Node Sets: " << this->ModelParameters.num_node_sets << "\n"; os << inden2 << "Edge Sets: " << this->ModelParameters.num_edge_sets << "\n"; os << inden2 << "Face Sets: " << this->ModelParameters.num_face_sets << "\n"; os << inden2 << "Side Sets: " << this->ModelParameters.num_side_sets << "\n"; os << inden2 << "Element Sets: " << this->ModelParameters.num_elem_sets << "\n"; os << inden2 << "Node Maps: " << this->ModelParameters.num_node_maps << "\n"; os << inden2 << "Edge Maps: " << this->ModelParameters.num_edge_maps << "\n"; os << inden2 << "Face Maps: " << this->ModelParameters.num_face_maps << "\n"; os << inden2 << "Element Maps: " << this->ModelParameters.num_elem_maps << "\n"; os << indent << "Time steps (" << this->Times.size() << "):"; int i; for ( i = 0; i < (int)this->Times.size(); ++i ) { os << " " << this->Times[i]; } os << "\n"; os << indent << "TimeStep: " << this->TimeStep << "\n"; os << indent << "HasModeShapes: " << this->HasModeShapes << "\n"; os << indent << "ModeShapeTime: " << this->ModeShapeTime << "\n"; // Print nodal variables if ( this->ArrayInfo[ vtkExodusIIReader::NODAL ].size() > 0 ) { os << indent << "Nodal Arrays:\n"; vtkstd::vector<ArrayInfoType>::iterator ai; for ( ai = this->ArrayInfo[ vtkExodusIIReader::NODAL ].begin(); ai != this->ArrayInfo[ vtkExodusIIReader::NODAL ].end(); ++ai ) { printArray( os, indent, vtkExodusIIReader::NODAL, *ai ); } } // Print blocks os << indent << "Blocks:\n"; vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator bti; for ( bti = this->BlockInfo.begin(); bti != this->BlockInfo.end(); ++bti ) { vtkstd::vector<BlockInfoType>::iterator bi; for ( bi = bti->second.begin(); bi != bti->second.end(); ++bi ) { printBlock( os, indent.GetNextIndent(), bti->first, *bi ); } if ( this->ArrayInfo[ bti->first ].size() > 0 ) { os << indent << " Results variables:\n"; vtkstd::vector<ArrayInfoType>::iterator ai; for ( ai = this->ArrayInfo[ bti->first ].begin(); ai != this->ArrayInfo[ bti->first ].end(); ++ai ) { printArray( os, indent.GetNextIndent(), bti->first, *ai ); } } } // Print sets os << indent << "Sets:\n"; vtkstd::map<int,vtkstd::vector<SetInfoType> >::iterator sti; for ( sti = this->SetInfo.begin(); sti != this->SetInfo.end(); ++sti ) { vtkstd::vector<SetInfoType>::iterator si; for ( si = sti->second.begin(); si != sti->second.end(); ++si ) { printSet( os, indent.GetNextIndent(), sti->first, *si ); } if ( this->ArrayInfo[ sti->first ].size() > 0 ) { os << indent << " Results variables:\n"; vtkstd::vector<ArrayInfoType>::iterator ai; for ( ai = this->ArrayInfo[ sti->first ].begin(); ai != this->ArrayInfo[ sti->first ].end(); ++ai ) { printArray( os, indent.GetNextIndent(), sti->first, *ai ); } } } // Print maps os << indent << "Maps:\n"; vtkstd::map<int,vtkstd::vector<MapInfoType> >::iterator mti; for ( mti = this->MapInfo.begin(); mti != this->MapInfo.end(); ++mti ) { vtkstd::vector<MapInfoType>::iterator mi; for ( mi = mti->second.begin(); mi != mti->second.end(); ++mi ) { printMap( os, indent.GetNextIndent(), mti->first, *mi ); } } os << indent << "Array Cache:\n"; this->Cache->PrintSelf( os, inden2 ); os << indent << "Number of output cells: " << this->NumberOfCells << "\n"; os << indent << "SqueezePoints: " << this->SqueezePoints << "\n"; os << indent << "NextSqueezePoint: " << this->NextSqueezePoint << "\n"; os << indent << "ApplyDisplacements: " << this->ApplyDisplacements << "\n"; os << indent << "DisplacementMagnitude: " << this->DisplacementMagnitude << "\n"; os << indent << "GenerateObjectIdArray: " << this->GenerateObjectIdArray << "\n"; } int vtkExodusIIReaderPrivate::OpenFile( const char* filename ) { if ( ! filename || ! strlen( filename ) ) { vtkErrorMacro( "Exodus filename pointer was NULL or pointed to an empty string." ); return 0; } if ( this->Exoid >= 0 ) { this->CloseFile(); } this->Exoid = ex_open( filename, EX_READ, &this->AppWordSize, &this->DiskWordSize, &this->ExodusVersion ); if ( this->Exoid <= 0 ) { vtkErrorMacro( "Unable to open \"" << filename << "\" for reading" ); return 0; } return 1; } int vtkExodusIIReaderPrivate::CloseFile() { if ( this->Exoid >= 0 ) { VTK_EXO_FUNC( ex_close( this->Exoid ), "Could not close an open file (" << this->Exoid << ")" ); this->Exoid = -1; } return 0; } int vtkExodusIIReaderPrivate::RequestInformation() { int exoid = this->Exoid; int itmp[5]; int* ids; int nids; int obj; int i, j; int num_timesteps; char** obj_names; char** obj_typenames = 0; char** var_names = 0; int have_var_names; int num_vars = 0; /* number of variables per object */ //int num_entries; /* number of values per variable per object */ char tmpName[256]; tmpName[255] = '\0'; this->InformationTimeStamp.Modified(); // Update MTime so that it will be newer than parent's FileNameMTime VTK_EXO_FUNC( ex_get_init_ext( exoid, &this->ModelParameters ), "Unable to read database parameters." ); VTK_EXO_FUNC( ex_inquire( exoid, EX_INQ_TIME, itmp, 0, 0 ), "Inquire for EX_INQ_TIME failed" ); num_timesteps = itmp[0]; vtkstd::vector<BlockInfoType> bitBlank; vtkstd::vector<SetInfoType> sitBlank; vtkstd::vector<MapInfoType> mitBlank; vtkstd::vector<ArrayInfoType> aitBlank; this->Times.clear(); if ( num_timesteps > 0 ) { this->Times.reserve( num_timesteps ); this->Times.resize( num_timesteps ); VTK_EXO_FUNC( ex_get_all_times( this->Exoid, &this->Times[0] ), "Could not retrieve time values." ); } this->NumberOfCells = 0; for ( i = 0; i < num_obj_types; ++i ) { vtkIdType blockEntryFileOffset = 1; vtkIdType setEntryFileOffset = 1; vtkIdType blockEntryGridOffset = 0; vtkIdType setEntryGridOffset = 0; vtkstd::map<int,int> sortedObjects; int* truth_tab = 0; have_var_names = 0; VTK_EXO_FUNC( ex_inquire( exoid, obj_sizes[i], &nids, 0, 0 ), "Object ID list size could not be determined." ); if ( nids ) { ids = (int*) malloc( nids * sizeof(int) ); obj_names = (char**) malloc( nids * sizeof(char*) ); for ( obj = 0; obj < nids; ++obj ) obj_names[obj] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); if ( OBJTYPE_IS_BLOCK(i) ) { obj_typenames = (char**) malloc( nids * sizeof(char*) ); for ( obj = 0; obj < nids; ++obj ) { obj_typenames[obj] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); obj_typenames[obj][0] = '\0'; } } } else { ids = 0; obj_names = 0; obj_typenames = 0; } if ( nids == 0 && ! OBJTYPE_IS_MAP(i) ) continue; if ( nids ) { VTK_EXO_FUNC( ex_get_ids( exoid, obj_types[i], ids ), "Could not read object ids." ); VTK_EXO_FUNC( ex_get_names( exoid, obj_types[i], obj_names ), "Could not read object names." ); } BlockInfoType binfo; SetInfoType sinfo; MapInfoType minfo; if ( OBJTYPE_IS_BLOCK(i) ) { this->BlockInfo[obj_types[i]] = bitBlank; this->BlockInfo[obj_types[i]].reserve( nids ); } else if ( OBJTYPE_IS_SET(i) ) { this->SetInfo[obj_types[i]] = sitBlank; this->SetInfo[obj_types[i]].reserve( nids ); } else { this->MapInfo[obj_types[i]] = mitBlank; this->MapInfo[obj_types[i]].reserve( nids ); } if ( (OBJTYPE_IS_BLOCK(i)) || (OBJTYPE_IS_SET(i)) ) { VTK_EXO_FUNC( ex_get_var_param( exoid, obj_typestr[i], &num_vars ), "Could not read number of variables." ); if ( num_vars && num_timesteps > 0 ) { truth_tab = (int*) malloc( num_vars * nids * sizeof(int) ); VTK_EXO_FUNC( ex_get_var_tab( exoid, obj_typestr[i], nids, num_vars, truth_tab ), "Could not read truth table." ); var_names = (char**) malloc( num_vars * sizeof(char*) ); for ( j = 0; j < num_vars; ++j ) var_names[j] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); VTK_EXO_FUNC( ex_get_var_names( exoid, obj_typestr[i], num_vars, var_names ), "Could not read variable names." ); this->RemoveBeginningAndTrailingSpaces( num_vars, var_names ); have_var_names = 1; } } if ( ! have_var_names ) var_names = 0; for ( obj = 0; obj < nids; ++obj ) { if ( OBJTYPE_IS_BLOCK(i) ) { binfo.Name = obj_names[obj]; binfo.Id = ids[obj]; if ( obj_types[i] == vtkExodusIIReader::ELEM_BLOCK ) { VTK_EXO_FUNC( ex_get_block( exoid, obj_types[i], ids[obj], obj_typenames[obj], &binfo.Size, &binfo.BdsPerEntry[0], &binfo.BdsPerEntry[1], &binfo.BdsPerEntry[2], &binfo.AttributesPerEntry ), "Could not read block params." ); binfo.Status = 1; // load element blocks by default binfo.TypeName = obj_typenames[obj]; } else { VTK_EXO_FUNC( ex_get_block( exoid, obj_types[i], ids[obj], obj_typenames[obj], &binfo.Size, &binfo.BdsPerEntry[0], &binfo.BdsPerEntry[1], &binfo.BdsPerEntry[2], &binfo.AttributesPerEntry ), "Could not read block params." ); binfo.Status = 0; // don't load edge/face blocks by default binfo.TypeName = obj_typenames[obj]; binfo.BdsPerEntry[1] = binfo.BdsPerEntry[2] = 0; } //num_entries = binfo.Size; binfo.FileOffset = blockEntryFileOffset; blockEntryFileOffset += binfo.Size; if ( binfo.Status ) { binfo.GridOffset = blockEntryGridOffset; blockEntryGridOffset += binfo.Size; this->NumberOfCells += binfo.Size; } else { binfo.GridOffset = -1; } if ( binfo.Name.length() == 0 ) { SNPRINTF( tmpName, 255, "Unnamed block ID: %d Type: %s Size: %d", ids[obj], binfo.TypeName.length() ? binfo.TypeName.c_str() : "NULL", binfo.Size ); binfo.Name = tmpName; } this->DetermineVtkCellType( binfo ); if ( binfo.AttributesPerEntry ) { char** attr_names; attr_names = (char**) malloc( binfo.AttributesPerEntry * sizeof(char*) ); for ( j = 0; j < binfo.AttributesPerEntry; ++j ) attr_names[j] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); VTK_EXO_FUNC( ex_get_attr_names( exoid, obj_types[i], ids[obj], attr_names ), "Could not read attributes names." ); for ( j = 0; j < binfo.AttributesPerEntry; ++j ) { binfo.AttributeNames.push_back( attr_names[j] ); binfo.AttributeStatus.push_back( 0 ); // don't load attributes by default } for ( j = 0; j < binfo.AttributesPerEntry; ++j ) free( attr_names[j] ); free( attr_names ); } // Check to see if there is metadata that defines what part, material, // and assembly(ies) this block belongs to. if(this->Parser && this->Parser->GetPartDescription(ids[i])!="") { // First construct the names for the block, part, assembly, and // material using the parsed XML metadata. vtkstd::vector<vtkStdString> assemblyNumbers= this->Parser->GetAssemblyNumbers(binfo.Id); vtkstd::vector<vtkStdString> assemblyDescriptions= this->Parser->GetAssemblyDescriptions(binfo.Id); vtkstd::vector<vtkStdString> localAssemblyNames; for (vtkstd::vector<int>::size_type j=0;j<assemblyNumbers.size();j++) { localAssemblyNames.push_back(assemblyDescriptions[j]+vtkStdString(" (")+ assemblyNumbers[j]+vtkStdString(")")); } vtkStdString blockName, partName, materialName; char block_name_buffer[80]; sprintf(block_name_buffer,"Block: %d (%s) %s",binfo.Id, this->Parser->GetPartDescription(binfo.Id).c_str(), this->Parser->GetPartNumber(binfo.Id).c_str()); blockName = block_name_buffer; partName = this->Parser->GetPartDescription(binfo.Id)+ " (" + this->Parser->GetMaterialDescription(binfo.Id)+")" + " : " + this->Parser->GetPartNumber(binfo.Id); materialName = this->Parser->GetMaterialDescription(binfo.Id) + " : " + this->Parser->GetMaterialSpecification(binfo.Id); // Override the existing block name with the new one binfo.Name = blockName; int blockIdx = this->BlockInfo[obj_types[i]].size(); // Add this block to our parts, materials, and assemblies collections unsigned int k; int found = 0; // Look to see if this part has already been created for (k=0;k<this->PartInfo.size();k++) { if (this->PartInfo[k].Name==partName) { //binfo.PartId = k; this->PartInfo[k].BlockIndices.push_back(blockIdx); found=1; } } if (!found) { PartInfoType pinfo; pinfo.Name = partName; pinfo.Id = this->PartInfo.size(); //binfo.PartId = k; pinfo.BlockIndices.push_back(blockIdx); this->PartInfo.push_back(pinfo); } found=0; for (k=0;k<this->MaterialInfo.size();k++) { if (this->MaterialInfo[k].Name==materialName) { //binfo.MaterialId = k; this->MaterialInfo[k].BlockIndices.push_back(blockIdx); found=1; } } if (!found) { MaterialInfoType matinfo; matinfo.Name = materialName; matinfo.Id = this->MaterialInfo.size(); //binfo.MaterialId = k; matinfo.BlockIndices.push_back(blockIdx); this->MaterialInfo.push_back(matinfo); } for (k=0;k<localAssemblyNames.size();k++) { vtkStdString assemblyName=localAssemblyNames[k]; found=0; for (unsigned int j=0;j<this->AssemblyInfo.size();j++) { if (this->AssemblyInfo[j].Name==assemblyName){ //binfo.AssemblyIds.push_back(j); this->AssemblyInfo[j].BlockIndices.push_back(blockIdx); found=1; } } if (!found) { AssemblyInfoType ainfo; ainfo.Name = assemblyName; ainfo.Id = this->AssemblyInfo.size(); //binfo.AssemblyIds.push_back(k); ainfo.BlockIndices.push_back(blockIdx); this->AssemblyInfo.push_back(ainfo); } } } sortedObjects[binfo.Id] = (int) this->BlockInfo[obj_types[i]].size(); this->BlockInfo[obj_types[i]].push_back( binfo ); } else if ( OBJTYPE_IS_SET(i) ) { sinfo.Name = obj_names[obj]; sinfo.Status = 0; sinfo.Id = ids[obj]; VTK_EXO_FUNC( ex_get_set_param( exoid, obj_types[i], ids[obj], &sinfo.Size, &sinfo.DistFact ), "Could not read set parameters." ); //num_entries = sinfo.Size; sinfo.FileOffset = setEntryFileOffset; setEntryFileOffset += sinfo.Size; if ( sinfo.Status ) { sinfo.GridOffset = setEntryGridOffset; setEntryGridOffset += sinfo.Size; } else { sinfo.GridOffset = -1; } if ( sinfo.Name.length() == 0 ) { SNPRINTF( tmpName, 255, "Unnamed set ID: %d Size: %d", ids[obj], sinfo.Size ); sinfo.Name = tmpName; } sortedObjects[sinfo.Id] = (int) this->SetInfo[obj_types[i]].size(); this->SetInfo[obj_types[i]].push_back( sinfo ); } else { /* object is map */ minfo.Id = ids[obj]; minfo.Status = obj == 0 ? 1 : 0; // only load the first map by default switch (obj_types[i]) { case vtkExodusIIReader::NODE_MAP: //num_entries = this->ModelParameters.num_nodes; minfo.Size = this->ModelParameters.num_nodes; break; case vtkExodusIIReader::EDGE_MAP: //num_entries = this->ModelParameters.num_edge; minfo.Size = this->ModelParameters.num_edge; break; case vtkExodusIIReader::FACE_MAP: //num_entries = this->ModelParameters.num_face; minfo.Size = this->ModelParameters.num_face; break; case vtkExodusIIReader::ELEM_MAP: //num_entries = this->ModelParameters.num_elem; minfo.Size = this->ModelParameters.num_elem; break; default: minfo.Size = 0; } minfo.Name = obj_names[obj]; if ( minfo.Name.length() == 0 ) { // make up a name. FIXME: Possible buffer overflow w/ sprintf SNPRINTF( tmpName, 255, "Unnamed map ID: %d", ids[obj] ); minfo.Name = tmpName; } sortedObjects[minfo.Id] = (int) this->MapInfo[obj_types[i]].size(); this->MapInfo[obj_types[i]].push_back( minfo ); } } // end of loop over all object ids // Now that we have all objects of that type in the sortedObjects, we can // iterate over it to fill in the SortedObjectIndices (the map is a *sorted* // associative container) vtkstd::map<int,int>::iterator soit; for ( soit = sortedObjects.begin(); soit != sortedObjects.end(); ++soit ) { this->SortedObjectIndices[obj_types[i]].push_back( soit->second ); } if ( ((OBJTYPE_IS_BLOCK(i)) || (OBJTYPE_IS_SET(i))) && num_vars && num_timesteps > 0 ) { this->ArrayInfo[obj_types[i]] = aitBlank; // Fill in ArrayInfo entries, combining array names into vectors/tensors where appropriate: this->GlomArrayNames( obj_types[i], nids, num_vars, var_names, truth_tab ); } if ( var_names ) { for ( j = 0; j < num_vars; ++j ) free( var_names[j] ); free( var_names ); } if ( truth_tab ) free( truth_tab ); if ( nids ) { free( ids ); for ( obj = 0; obj < nids; ++obj ) free( obj_names[obj] ); free( obj_names ); if ( OBJTYPE_IS_BLOCK(i) ) { for ( obj = 0; obj < nids; ++obj ) free( obj_typenames[obj] ); free( obj_typenames ); } } } // end of loop over all object types this->ComputeGridOffsets(); // Now read information for nodal arrays VTK_EXO_FUNC( ex_get_var_param( exoid, "n", &num_vars ), "Unable to read number of nodal variables." ); if ( num_vars > 0 ) { ArrayInfoType ainfo; var_names = (char**) malloc( num_vars * sizeof(char*) ); for ( j = 0; j < num_vars; ++j ) var_names[j] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); VTK_EXO_FUNC( ex_get_var_names( exoid, "n", num_vars, var_names ), "Could not read nodal variable names." ); this->RemoveBeginningAndTrailingSpaces( num_vars, var_names ); nids = 1; vtkstd::vector<int> dummy_truth; dummy_truth.reserve( num_vars ); for ( j = 0; j < num_vars; ++j ) { dummy_truth.push_back( 1 ); } this->GlomArrayNames( vtkExodusIIReader::NODAL, nids, num_vars, var_names, &dummy_truth[0] ); for ( j = 0; j < num_vars; ++j ) { free( var_names[j] ); } free( var_names ); var_names = 0; } return 0; } int vtkExodusIIReaderPrivate::RequestData( vtkIdType timeStep, vtkUnstructuredGrid* output ) { // The work done here depends on several conditions: // - Has connectivity changed (i.e., has block/set status changed)? // - If so, AND if point "squeeze" turned on, must reload points and re-squeeze. // - If so, must re-assemble all arrays // - Must recreate block/set id array. // - Has requested time changed? // - If so, AND if "deflect mesh" turned on, must load new deflections and compute new points. // - If so, must assemble all time-varying arrays for new time. // - Has array status changed? // - If so, must delete old and/or load new arrays. // Obviously, many of these tasks overlap. For instance, it would be // foolish to re-assemble all the arrays when the connectivity has // changed and then toss them out in order to load arrays for a // different time step. // Caching strategy: use GLOBAL "object type" for assembled arrays. // If connectivity hasn't changed, then these arrays can be used; // otherwise, "raw" arrays must be used. // Pro: // - single cache == easier bookkeeping (two caches would require us to decide how to equitably split avail mem between them) // - many different operations are accelerated: // - just changing which variables are loaded // - changing which blocks are in output (doesn't require disk access if cache hit) // - possible extension to single-node/cell over time // Con: // - higher memory consumption for caching the same set of arrays (or, holding cache size fixed: fewer arrays fit) if ( ! output ) { vtkErrorMacro( "You must specify an output mesh" ); } // Connectivity first. Either from the cache or reassembled. // Connectivity isn't allowed to change with time step so this should only re-read // from disk when block/set status changes. And it might not even re-read then if // the cache contains all the requested block/set entries. this->AssembleOutputConnectivity( timeStep, output ); // Now prepare points. // These shouldn't change unless the connectivity has changed. // This function doesn't apply displacements because we don't have the displacement vectors yet. this->AssembleOutputPoints( timeStep, output ); // Finally, add the desired arrays from cache (or disk) // Point and cell arrays are handled differently because they have different problems // to solve. Point arrays must use the PointMap index to subset values while cell arrays // must be padded with zeros for cells in blocks/sets that do not contain the given arrays. this->AssembleOutputPointArrays( timeStep, output ); this->AssembleOutputCellArrays( timeStep, output ); this->AssembleOutputProceduralArrays( timeStep, output ); this->AssembleOutputPointMaps( timeStep, output ); this->AssembleOutputCellMaps( timeStep, output ); this->CloseFile(); return 0; } void vtkExodusIIReaderPrivate::Reset() { this->CloseFile(); this->BlockInfo.clear(); this->SetInfo.clear(); this->MapInfo.clear(); this->PartInfo.clear(); this->MaterialInfo.clear(); this->AssemblyInfo.clear(); this->SortedObjectIndices.clear(); this->ArrayInfo.clear(); this->ExodusVersion = -1.; this->Times.clear(); this->TimeStep = 0; this->HasModeShapes = 0; this->ModeShapeTime = -1.; this->NumberOfCells = 0; this->SqueezePoints = 1; this->PointMap.clear(); this->Cache->Clear(); this->ApplyDisplacements = 1; this->DisplacementMagnitude = 1.; memset( (void*)&this->ModelParameters, 0, sizeof(this->ModelParameters) ); this->Cache->SetCacheCapacity( 0. ); // FIXME: Perhaps Cache should have a Reset and a Clear method? this->Cache->SetCacheCapacity( 128. ); // FIXME: Perhaps Cache should have a Reset and a Clear method? this->SetCachedConnectivity( 0 ); this->NextSqueezePoint = 0; this->GenerateGlobalElementIdArray = 0; this->GenerateGlobalNodeIdArray = 0; this->GenerateObjectIdArray = 1; this->Modified(); } void vtkExodusIIReaderPrivate::SetSqueezePoints( int sp ) { if ( this->SqueezePoints == sp ) return; this->SqueezePoints = sp; this->Modified(); // Invalidate global "topology" cache this->SetCachedConnectivity( 0 ); // The point map should be invalidated this->PointMap.clear(); this->NextSqueezePoint = 0; } int vtkExodusIIReaderPrivate::GetNumberOfNodes() { if ( this->SqueezePoints ) return this->NextSqueezePoint; return this->ModelParameters.num_nodes; } int vtkExodusIIReaderPrivate::GetNumberOfObjectsOfType( int otyp ) { int i = this->GetObjectTypeIndexFromObjectType( otyp ); if ( i < 0 ) { // Could signal warning here, but might not want it if file simply doesn't have objects of some obscure type (e.g., edge sets) return 0; } return this->GetNumberOfObjectsAtTypeIndex( i ); } int vtkExodusIIReaderPrivate::GetNumberOfObjectArraysOfType( int otyp ) { vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( otyp ); if ( it != this->ArrayInfo.end() ) { return (int) it->second.size(); } // Could signal warning here, but might not want it if file simply doesn't have objects of some obscure type (e.g., edge sets) return 0; } const char* vtkExodusIIReaderPrivate::GetObjectName( int otyp, int k ) { ObjectInfoType* oinfop = this->GetSortedObjectInfo( otyp, k ); return oinfop ? oinfop->Name.c_str() : 0; } int vtkExodusIIReaderPrivate::GetObjectId( int otyp, int k ) { ObjectInfoType* oinfop = this->GetSortedObjectInfo( otyp, k ); return oinfop ? oinfop->Id : -1; } int vtkExodusIIReaderPrivate::GetObjectSize( int otyp, int k ) { ObjectInfoType* oinfop = this->GetSortedObjectInfo( otyp, k ); return oinfop ? oinfop->Size : 0; } int vtkExodusIIReaderPrivate::GetObjectStatus( int otyp, int k ) { ObjectInfoType* oinfop = this->GetSortedObjectInfo( otyp, k ); return oinfop ? oinfop->Status : 0; } int vtkExodusIIReaderPrivate::GetUnsortedObjectStatus( int otyp, int k ) { ObjectInfoType* oinfop = this->GetUnsortedObjectInfo( otyp, k ); return oinfop ? oinfop->Status : 0; } void vtkExodusIIReaderPrivate::SetObjectStatus( int otyp, int k, int stat ) { stat = (stat != 0); // Force stat to be either 0 or 1 // OK, found the object ObjectInfoType* oinfop = this->GetSortedObjectInfo( otyp, k ); if ( ! oinfop ) { // error message will have been generated by GetSortedObjectInfo() return; } if ( oinfop->Status == stat ) { // no change => do nothing return; } oinfop->Status = stat; this->ComputeGridOffsets(); // Invalidate connectivity this->SetCachedConnectivity( 0 ); // Invalidate global cell arrays vtkExodusIICacheKey pattern( 0, 1, 0, 0 ); this->Cache->Invalidate( vtkExodusIICacheKey( 0, vtkExodusIIReader::GLOBAL, 0, 0 ), pattern ); pattern = vtkExodusIICacheKey( 1, 1, 0, 0 ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_OBJECT_ID, 0, 0 ), pattern ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_ELEMENT_ID, 0, 0 ), pattern ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_NODE_ID, 0, 0 ), pattern ); this->Modified(); } void vtkExodusIIReaderPrivate::SetUnsortedObjectStatus( int otyp, int k, int stat ) { stat = (stat != 0); // Force stat to be either 0 or 1 // OK, found the object ObjectInfoType* oinfop = this->GetUnsortedObjectInfo( otyp, k ); if ( ! oinfop ) { // error message will have been generated by GetSortedObjectInfo() return; } if ( oinfop->Status == stat ) { // no change => do nothing return; } oinfop->Status = stat; this->ComputeGridOffsets(); // Invalidate connectivity this->SetCachedConnectivity( 0 ); // Invalidate global cell arrays vtkExodusIICacheKey pattern( 0, 1, 0, 0 ); this->Cache->Invalidate( vtkExodusIICacheKey( 0, vtkExodusIIReader::GLOBAL, 0, 0 ), pattern ); pattern = vtkExodusIICacheKey( 1, 1, 0, 0 ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_OBJECT_ID, 0, 0 ), pattern ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_ELEMENT_ID, 0, 0 ), pattern ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_NODE_ID, 0, 0 ), pattern ); this->Modified(); } const char* vtkExodusIIReaderPrivate::GetObjectArrayName( int otyp, int i ) { vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( otyp ); if ( it != this->ArrayInfo.end() ) { int N = (int) it->second.size(); if ( i < 0 || i >= N ) { vtkWarningMacro( "You requested array " << i << " in a collection of only " << N << " arrays." ); return 0; } return it->second[i].Name.c_str(); } vtkWarningMacro( "Could not find collection of arrays for objects of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } int vtkExodusIIReaderPrivate::GetNumberOfObjectArrayComponents( int otyp, int i ) { vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( otyp ); if ( it != this->ArrayInfo.end() ) { int N = (int) it->second.size(); if ( i < 0 || i >= N ) { vtkWarningMacro( "You requested array " << i << " in a collection of only " << N << " arrays." ); return 0; } return it->second[i].Components; } vtkWarningMacro( "Could not find collection of arrays for objects of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } int vtkExodusIIReaderPrivate::GetObjectArrayStatus( int otyp, int i ) { vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( otyp ); if ( it != this->ArrayInfo.end() ) { int N = (int) it->second.size(); if ( i < 0 || i >= N ) { vtkWarningMacro( "You requested array " << i << " in a collection of only " << N << " arrays." ); return 0; } return it->second[i].Status; } vtkWarningMacro( "Could not find collection of arrays for objects of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } void vtkExodusIIReaderPrivate::SetObjectArrayStatus( int otyp, int i, int stat ) { stat = ( stat != 0 ); // Force stat to be either 0 or 1 vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( otyp ); if ( it != this->ArrayInfo.end() ) { int N = (int) it->second.size(); if ( i < 0 || i >= N ) { vtkWarningMacro( "You requested array " << i << " in a collection of only " << N << " arrays." ); return; } if ( it->second[i].Status == stat ) { // no change => do nothing return; } it->second[i].Status = stat; this->Modified(); // FIXME: Mark something so we know what's changed since the last RequestData?! // For the "global" (assembled) array, this is tricky because we really only want // to invalidate a range of the total array... For now, we'll just force the "global" // array to be reassembled even if it does mean a lot more copying -- it's not like // it was any faster before. //vtkExodusIICacheKey key( 0, GLOBAL, 0, i ); //vtkExodusIICacheKey pattern( 0, 1, 0, 1 ); this->Cache->Invalidate( vtkExodusIICacheKey( 0, vtkExodusIIReader::GLOBAL, otyp, i ), vtkExodusIICacheKey( 0, 1, 1, 1 ) ); } else { vtkWarningMacro( "Could not find collection of arrays for objects of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); } } int vtkExodusIIReaderPrivate::GetNumberOfObjectAttributes( int otyp, int oi ) { vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator it = this->BlockInfo.find( otyp ); if ( it != this->BlockInfo.end() ) { int N = (int) it->second.size(); if ( oi < 0 || oi >= N ) { int otypIdx = this->GetObjectTypeIndexFromObjectType(otyp); const char* btname = otypIdx >= 0 ? objtype_names[otypIdx] : "block"; vtkWarningMacro( "You requested " << btname << " " << oi << " in a collection of only " << N << " blocks." ); return 0; } oi = this->SortedObjectIndices[otyp][oi]; // index into sorted list of objects (block order, not file order) return (int) it->second[oi].AttributeNames.size(); } vtkWarningMacro( "Could not find collection of blocks of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } const char* vtkExodusIIReaderPrivate::GetObjectAttributeName( int otyp, int oi, int ai ) { vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator it = this->BlockInfo.find( otyp ); if ( it != this->BlockInfo.end() ) { int N = (int) it->second.size(); if ( oi < 0 || oi >= N ) { vtkWarningMacro( "You requested block " << oi << " in a collection of only " << N << " blocks." ); return 0; } oi = this->SortedObjectIndices[otyp][oi]; // index into sorted list of objects (block order, not file order) N = (int) it->second[oi].AttributeNames.size(); if ( ai < 0 || ai >= N ) { vtkWarningMacro( "You requested attribute " << ai << " in a collection of only " << N << " attributes." ); return 0; } else { return it->second[oi].AttributeNames[ai].c_str(); } } vtkWarningMacro( "Could not find collection of blocks of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } int vtkExodusIIReaderPrivate::GetObjectAttributeIndex( int otyp, int oi, const char* attribName ) { vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator it = this->BlockInfo.find( otyp ); if ( it != this->BlockInfo.end() ) { int N = (int) it->second.size(); if ( oi < 0 || oi >= N ) { vtkWarningMacro( "You requested block " << oi << " in a collection of only " << N << " blocks." ); return -1; } oi = this->SortedObjectIndices[otyp][oi]; // index into sorted list of objects (block order, not file order) N = (int) it->second[oi].AttributeNames.size(); int ai; for ( ai = 0; ai < N; ++ai ) { if ( it->second[oi].AttributeNames[ai] == attribName ) { return ai; } } return -1; } vtkWarningMacro( "Could not find collection of blocks of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return -1; } int vtkExodusIIReaderPrivate::GetObjectAttributeStatus( int otyp, int oi, int ai ) { vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator it = this->BlockInfo.find( otyp ); if ( it != this->BlockInfo.end() ) { int N = (int) it->second.size(); if ( oi < 0 || oi >= N ) { vtkWarningMacro( "You requested block " << oi << " in a collection of only " << N << " blocks." ); return 0; } oi = this->SortedObjectIndices[otyp][oi]; // index into sorted list of objects (block order, not file order) N = (int) it->second[oi].AttributeStatus.size(); if ( ai < 0 || ai >= N ) { vtkWarningMacro( "You requested attribute " << ai << " in a collection of only " << N << " attributes." ); return 0; } else { return it->second[oi].AttributeStatus[ai]; } } vtkWarningMacro( "Could not find collection of blocks of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } void vtkExodusIIReaderPrivate::SetObjectAttributeStatus( int otyp, int oi, int ai, int status ) { status = status ? 1 : 0; vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator it = this->BlockInfo.find( otyp ); if ( it != this->BlockInfo.end() ) { int N = (int) it->second.size(); if ( oi < 0 || oi >= N ) { vtkWarningMacro( "You requested block " << oi << " in a collection of only " << N << " blocks." ); return; } oi = this->SortedObjectIndices[otyp][oi]; // index into sorted list of objects (block order, not file order) N = (int) it->second[oi].AttributeStatus.size(); if ( ai < 0 || ai >= N ) { vtkWarningMacro( "You requested attribute " << ai << " in a collection of only " << N << " attribute." ); return; } else { if ( it->second[oi].AttributeStatus[ai] == status ) { return; } it->second[oi].AttributeStatus[ai] = status; this->Modified(); } } vtkWarningMacro( "Could not find collection of blocks of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); } void vtkExodusIIReaderPrivate::SetApplyDisplacements( int d ) { if ( this->ApplyDisplacements == d ) return; this->ApplyDisplacements = d; this->Modified(); // Require the coordinates to be recomputed: this->Cache->Invalidate( vtkExodusIICacheKey( 0, vtkExodusIIReader::NODAL_COORDS, 0, 0 ), vtkExodusIICacheKey( 0, 1, 0, 0 ) ); } void vtkExodusIIReaderPrivate::SetDisplacementMagnitude( double s ) { if ( this->DisplacementMagnitude == s ) return; this->DisplacementMagnitude = s; this->Modified(); // Require the coordinates to be recomputed: this->Cache->Invalidate( vtkExodusIICacheKey( 0, vtkExodusIIReader::NODAL_COORDS, 0, 0 ), vtkExodusIICacheKey( 0, 1, 0, 0 ) ); } vtkDataArray* vtkExodusIIReaderPrivate::FindDisplacementVectors( int timeStep ) { vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( vtkExodusIIReader::NODAL ); if ( it != this->ArrayInfo.end() ) { int N = (int) it->second.size(); for ( int i = 0; i < N; ++i ) { vtkstd::string upperName = vtksys::SystemTools::UpperCase( it->second[i].Name.substr( 0, 3 ) ); if ( upperName == "DIS" && it->second[i].Components == 3 ) { return this->GetCacheOrRead( vtkExodusIICacheKey( timeStep, vtkExodusIIReader::NODAL, 0, i ) ); } } } return 0; } // -------------------------------------------------------- PUBLIC CLASS MEMBERS vtkCxxRevisionMacro(vtkExodusIIReader,"1.18"); vtkStandardNewMacro(vtkExodusIIReader); vtkCxxSetObjectMacro(vtkExodusIIReader,Metadata,vtkExodusIIReaderPrivate); vtkCxxSetObjectMacro(vtkExodusIIReader,ExodusModel,vtkExodusModel); vtkExodusIIReader::vtkExodusIIReader() { this->FileName = 0; this->XMLFileName = 0; this->Metadata = vtkExodusIIReaderPrivate::New(); this->Metadata->Parent = this; this->TimeStep = 0; this->TimeStepRange[0] = 0; this->TimeStepRange[1] = 0; this->ExodusModelMetadata = 0; this->PackExodusModelOntoOutput = 1; this->ExodusModel = 0; this->DisplayType = 0; this->SetNumberOfInputPorts( 0 ); } vtkExodusIIReader::~vtkExodusIIReader() { this->SetXMLFileName( 0 ); this->SetFileName( 0 ); this->SetMetadata( 0 ); this->SetExodusModel( 0 ); } // Normally, vtkExodusIIReader::PrintSelf would be here. // But it's above to prevent PrintSelf-Hybrid from failing because it assumes // the first PrintSelf method is the one for the class declared in the header file. int vtkExodusIIReader::CanReadFile( const char* fname ) { int exoid; int appWordSize = 8; int diskWordSize = 8; float version; if ( (exoid = ex_open( fname, EX_READ, &appWordSize, &diskWordSize, &version )) == 0 ) { return 0; } if ( ex_close( exoid ) != 0 ) { vtkWarningMacro( "Unable to close \"" << fname << "\" opened for testing." ); return 0; } return 1; } unsigned long vtkExodusIIReader::GetMTime() { unsigned long mtime1, mtime2; unsigned long readerMTime = this->MTime.GetMTime(); unsigned long privateMTime = this->Metadata->GetMTime(); unsigned long fileNameMTime = this->FileNameMTime.GetMTime(); unsigned long xmlFileNameMTime = this->XMLFileNameMTime.GetMTime(); mtime1 = privateMTime > readerMTime ? privateMTime : readerMTime; mtime2 = fileNameMTime > xmlFileNameMTime ? fileNameMTime : xmlFileNameMTime; return mtime1 > mtime2 ? mtime1 : mtime2; } unsigned long vtkExodusIIReader::GetMetadataMTime() { return this->Metadata->InformationTimeStamp < this->Metadata->GetMTime() ? this->Metadata->InformationTimeStamp : this->Metadata->GetMTime(); } #define vtkSetStringMacroBody(propName,fname) \ int modified = 0; \ if ( fname == this->propName ) \ return; \ if ( fname && this->propName && !strcmp( fname, this->propName ) ) \ return; \ modified = 1; \ if ( this->propName ) \ delete [] this->propName; \ if ( fname ) \ { \ size_t fnl = strlen( fname ) + 1; \ char* dst = new char[fnl]; \ const char* src = fname; \ this->propName = dst; \ do { *dst++ = *src++; } while ( --fnl ); \ } \ else \ { \ this->propName = 0; \ } void vtkExodusIIReader::SetFileName( const char* fname ) { vtkSetStringMacroBody(FileName,fname); if ( modified ) { this->Metadata->Reset(); this->FileNameMTime.Modified(); } } void vtkExodusIIReader::SetXMLFileName( const char* fname ) { vtkSetStringMacroBody(XMLFileName,fname); if ( modified ) { this->XMLFileNameMTime.Modified(); } } int vtkExodusIIReader::RequestInformation( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector ) { int newMetadata = 0; vtkInformation* outInfo = outputVector->GetInformationObject(0); // If the metadata is older than the filename if ( this->GetMetadataMTime() < this->FileNameMTime ) { if ( this->Metadata->OpenFile( this->FileName ) ) { // We need to initialize the XML parser before calling RequestInformation // on the metadata if ( this->FindXMLFile() ) { vtkExodusIIXMLParser *parser = vtkExodusIIXMLParser::New(); this->Metadata->SetParser(parser); // Now overwrite any names in the exodus file with names from XML file. parser->Go( this->XMLFileName, this->Metadata ); parser->Delete(); } this->Metadata->RequestInformation(); this->Metadata->CloseFile(); newMetadata = 1; } else { vtkErrorMacro( "Unable to open file \"" << (this->FileName ? this->FileName : "(null)") << "\" to read metadata" ); return 0; } } if ( ! this->GetHasModeShapes() ) { int nTimes = (int) this->Metadata->Times.size(); double timeRange[2]; if ( nTimes ) { timeRange[0] = this->Metadata->Times[0]; timeRange[1] = this->Metadata->Times[nTimes - 1]; outInfo->Set( vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &this->Metadata->Times[0], nTimes ); outInfo->Set( vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2 ); this->TimeStepRange[0] = 0; this->TimeStepRange[1] = nTimes - 1; } } else { outInfo->Remove( vtkStreamingDemandDrivenPipeline::TIME_STEPS() ); static double timeRange[] = { 0, 1 }; outInfo->Set( vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2 ); } if ( newMetadata ) { // update ExodusModelMetadata } return 1; } int vtkExodusIIReader::RequestData( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector ) { if ( ! this->FileName || ! this->Metadata->OpenFile( this->FileName ) ) { vtkErrorMacro( "Unable to open file \"" << (this->FileName ? this->FileName : "(null)") << "\" to read data" ); return 0; } vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast( outInfo->Get( vtkDataObject::DATA_OBJECT() ) ); // Check if a particular time was requested. int timeStep = this->TimeStep; if ( outInfo->Has( vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS() ) ) { // Get the requested time step. We only support requests of a single time step in this reader right now double* requestedTimeSteps = outInfo->Get( vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS() ); // Save the time value in the output data information. int length = outInfo->Length( vtkStreamingDemandDrivenPipeline::TIME_STEPS() ); double* steps = outInfo->Get( vtkStreamingDemandDrivenPipeline::TIME_STEPS() ); if ( ! this->GetHasModeShapes() ) { // find the highest time step with a time value that is smaller than the requested time. timeStep = 0; while (timeStep < length - 1 && steps[timeStep] < requestedTimeSteps[0]) { timeStep++; } this->TimeStep = timeStep; output->GetInformation()->Set( vtkDataObject::DATA_TIME_STEPS(), steps + timeStep, 1 ); } else { // Let the metadata know the time value so that the Metadata->RequestData call below will generate // the animated mode shape properly. this->Metadata->ModeShapeTime = requestedTimeSteps[0]; output->GetInformation()->Set( vtkDataObject::DATA_TIME_STEPS(), &this->Metadata->ModeShapeTime, 1 ); //output->GetInformation()->Remove( vtkDataObject::DATA_TIME_STEPS() ); } } //cout << "Requesting step " << timeStep << " for output " << output << "\n"; this->Metadata->RequestData( timeStep, output ); return 1; } void vtkExodusIIReader::SetGenerateObjectIdCellArray( int x ) { this->Metadata->SetGenerateObjectIdArray( x ); } int vtkExodusIIReader::GetGenerateObjectIdCellArray() { return this->Metadata->GetGenerateObjectIdArray(); } void vtkExodusIIReader::SetGenerateGlobalElementIdArray( int x ) { this->Metadata->SetGenerateGlobalElementIdArray( x ); } int vtkExodusIIReader::GetGenerateGlobalElementIdArray() { return this->Metadata->GetGenerateGlobalElementIdArray(); } void vtkExodusIIReader::SetGenerateGlobalNodeIdArray( int x ) { this->Metadata->SetGenerateGlobalNodeIdArray( x ); } int vtkExodusIIReader::GetGenerateGlobalNodeIdArray() { return this->Metadata->GetGenerateGlobalNodeIdArray(); } // FIXME: Implement the four functions that return ID_NOT_FOUND below. int vtkExodusIIReader::GetGlobalElementID( vtkDataSet* data, int localID ) { return GetGlobalElementID( data, localID, SEARCH_TYPE_ELEMENT_THEN_NODE ); } int vtkExodusIIReader::GetGlobalElementID ( vtkDataSet* data, int localID, int searchType ) { (void)data; (void)localID; (void)searchType; return ID_NOT_FOUND; } int vtkExodusIIReader::GetGlobalFaceID( vtkDataSet* data, int localID ) { return GetGlobalFaceID( data, localID, SEARCH_TYPE_ELEMENT_THEN_NODE ); } int vtkExodusIIReader::GetGlobalFaceID ( vtkDataSet* data, int localID, int searchType ) { (void)data; (void)localID; (void)searchType; return ID_NOT_FOUND; } int vtkExodusIIReader::GetGlobalEdgeID( vtkDataSet* data, int localID ) { return GetGlobalEdgeID( data, localID, SEARCH_TYPE_ELEMENT_THEN_NODE ); } int vtkExodusIIReader::GetGlobalEdgeID ( vtkDataSet* data, int localID, int searchType ) { (void)data; (void)localID; (void)searchType; return ID_NOT_FOUND; } int vtkExodusIIReader::GetGlobalNodeID( vtkDataSet* data, int localID ) { return GetGlobalNodeID( data, localID, SEARCH_TYPE_NODE_THEN_ELEMENT ); } int vtkExodusIIReader::GetGlobalNodeID( vtkDataSet* data, int localID, int searchType ) { (void)data; (void)localID; (void)searchType; return ID_NOT_FOUND; } void vtkExodusIIReader::SetApplyDisplacements( int d ) { this->Metadata->SetApplyDisplacements( d ); } int vtkExodusIIReader::GetApplyDisplacements() { return this->Metadata->GetApplyDisplacements(); } void vtkExodusIIReader::SetDisplacementMagnitude( float s ) { this->Metadata->SetDisplacementMagnitude( s ); } float vtkExodusIIReader::GetDisplacementMagnitude() { return this->Metadata->GetDisplacementMagnitude(); } void vtkExodusIIReader::SetHasModeShapes( int ms ) { this->Metadata->SetHasModeShapes(ms); } int vtkExodusIIReader::GetHasModeShapes() { return this->Metadata->GetHasModeShapes(); } void vtkExodusIIReader::SetModeShapeTime( double phase ) { double x = phase < 0. ? 0. : ( phase > 1. ? 1. : phase ); if ( this->Metadata->ModeShapeTime == x ) { return; } this->Metadata->SetModeShapeTime( x ); } double vtkExodusIIReader::GetModeShapeTime() { return this->Metadata->GetModeShapeTime(); } const char* vtkExodusIIReader::GetTitle() { return this->Metadata->ModelParameters.title; } int vtkExodusIIReader::GetDimensionality() { return this->Metadata->ModelParameters.num_dim; } int vtkExodusIIReader::GetNumberOfTimeSteps() { return (int) this->Metadata->Times.size(); } int vtkExodusIIReader::GetNumberOfNodesInFile() { return this->Metadata->ModelParameters.num_nodes; } int vtkExodusIIReader::GetNumberOfEdgesInFile() { return this->Metadata->ModelParameters.num_edge; } int vtkExodusIIReader::GetNumberOfFacesInFile() { return this->Metadata->ModelParameters.num_face; } int vtkExodusIIReader::GetNumberOfElementsInFile() { return this->Metadata->ModelParameters.num_elem; } int vtkExodusIIReader::GetNumberOfObjects( int objectType ) { return this->Metadata->GetNumberOfObjectsOfType( objectType ); } int vtkExodusIIReader::GetObjectTypeFromName( const char* name ) { vtkStdString tname( name ); if ( tname == "edge" ) return EDGE_BLOCK; else if ( tname == "face" ) return FACE_BLOCK; else if ( tname == "element" ) return ELEM_BLOCK; else if ( tname == "node set" ) return NODE_SET; else if ( tname == "edge set" ) return EDGE_SET; else if ( tname == "face set" ) return FACE_SET; else if ( tname == "side set" ) return SIDE_SET; else if ( tname == "element set" ) return ELEM_SET; else if ( tname == "node map" ) return NODE_MAP; else if ( tname == "edge map" ) return EDGE_MAP; else if ( tname == "face map" ) return FACE_MAP; else if ( tname == "element map" ) return ELEM_MAP; else if ( tname == "grid" ) return GLOBAL; else if ( tname == "node" ) return NODAL; else if ( tname == "assembly" ) return ASSEMBLY; else if ( tname == "part" ) return PART; else if ( tname == "material" ) return MATERIAL; else if ( tname == "hierarchy" ) return HIERARCHY; else if ( tname == "cell" ) return GLOBAL_CONN; else if ( tname == "element block cell" ) return ELEM_BLOCK_ELEM_CONN; else if ( tname == "element block face" ) return ELEM_BLOCK_FACE_CONN; else if ( tname == "element block edge" ) return ELEM_BLOCK_EDGE_CONN; else if ( tname == "face block cell" ) return FACE_BLOCK_CONN; else if ( tname == "edge block cell" ) return EDGE_BLOCK_CONN; else if ( tname == "element set cell" ) return ELEM_SET_CONN; else if ( tname == "side set cell" ) return SIDE_SET_CONN; else if ( tname == "face set cell" ) return FACE_SET_CONN; else if ( tname == "edge set cell" ) return EDGE_SET_CONN; else if ( tname == "node set cell" ) return NODE_SET_CONN; else if ( tname == "nodal coordinates" ) return NODAL_COORDS; else if ( tname == "object id" ) return GLOBAL_OBJECT_ID; else if ( tname == "global element id" ) return GLOBAL_ELEMENT_ID; else if ( tname == "global node id" ) return GLOBAL_NODE_ID; else if ( tname == "element id" ) return ELEMENT_ID; else if ( tname == "node id" ) return NODE_ID; else if ( tname == "pointmap" ) return NODAL_SQUEEZEMAP; return -1; } const char* vtkExodusIIReader::GetObjectTypeName( int otyp ) { switch ( otyp ) { case EDGE_BLOCK: return "edge"; case FACE_BLOCK: return "face"; case ELEM_BLOCK: return "element"; case NODE_SET: return "node set"; case EDGE_SET: return "edge set"; case FACE_SET: return "face set"; case SIDE_SET: return "side set"; case ELEM_SET: return "element set"; case NODE_MAP: return "node map"; case EDGE_MAP: return "edge map"; case FACE_MAP: return "face map"; case ELEM_MAP: return "element map"; case GLOBAL: return "grid"; case NODAL: return "node"; case ASSEMBLY: return "assembly"; case PART: return "part"; case MATERIAL: return "material"; case HIERARCHY: return "hierarchy"; case GLOBAL_CONN: return "cell"; case ELEM_BLOCK_ELEM_CONN: return "element block cell"; case ELEM_BLOCK_FACE_CONN: return "element block face"; case ELEM_BLOCK_EDGE_CONN: return "element block edge"; case FACE_BLOCK_CONN: return "face block cell"; case EDGE_BLOCK_CONN: return "edge block cell"; case ELEM_SET_CONN: return "element set cell"; case SIDE_SET_CONN: return "side set cell"; case FACE_SET_CONN: return "face set cell"; case EDGE_SET_CONN: return "edge set cell"; case NODE_SET_CONN: return "node set cell"; case NODAL_COORDS: return "nodal coordinates"; case GLOBAL_OBJECT_ID: return "object id"; case GLOBAL_ELEMENT_ID: return "global element id"; case GLOBAL_NODE_ID: return "global node id"; case ELEMENT_ID: return "element id"; case NODE_ID: return "node id"; case NODAL_SQUEEZEMAP: return "pointmap"; } return 0; } int vtkExodusIIReader::GetNumberOfNodes() { return this->Metadata->GetNumberOfNodes(); } int vtkExodusIIReader::GetNumberOfEntriesInObject( int objectType, int objectIndex ) { return this->Metadata->GetObjectSize( objectType, objectIndex ); } int vtkExodusIIReader::GetObjectId( int objectType, int objectIndex ) { return this->Metadata->GetObjectId( objectType, objectIndex ); } int vtkExodusIIReader::GetObjectStatus( int objectType, int objectIndex ) { return this->Metadata->GetObjectStatus( objectType, objectIndex ); } void vtkExodusIIReader::SetObjectStatus( int objectType, int objectIndex, int status ) { this->Metadata->SetObjectStatus( objectType, objectIndex, status ); } const char* vtkExodusIIReader::GetObjectName( int objectType, int objectIndex ) { return this->Metadata->GetObjectName( objectType, objectIndex ); } int vtkExodusIIReader::GetObjectIndex( int objectType, const char* objectName ) { if ( ! objectName ) { vtkErrorMacro( "You must specify a non-NULL name" ); return -1; } int nObj = this->GetNumberOfObjects( objectType ); if ( nObj == 0 ) { vtkWarningMacro( "No objects of that type (" << objectType << ") to find index for given name " << objectName << "." ); return -1; } for ( int obj = 0; obj < nObj; ++obj ) { if ( !strcmp( objectName, this->GetObjectName( objectType, obj ) ) ) { return obj; } } vtkWarningMacro( "No objects named \"" << objectName << "\" of the specified type (" << objectType << ")." ); return -1; } int vtkExodusIIReader::GetObjectIndex( int objectType, int id ) { int nObj = this->GetNumberOfObjects( objectType ); if ( nObj == 0 ) { vtkWarningMacro( "No objects of that type (" << objectType << ") to find index for given id " << id << "." ); return -1; } for ( int obj = 0; obj < nObj; ++obj ) { if ( this->GetObjectId( objectType, obj ) == id) { return obj; } } vtkWarningMacro( "No objects with id \"" << id << "\" of the specified type (" << objectType << ")." ); return -1; } int vtkExodusIIReader::GetNumberOfObjectArrays( int objectType ) { return this->Metadata->GetNumberOfObjectArraysOfType( objectType ); } const char* vtkExodusIIReader::GetObjectArrayName( int objectType, int arrayIndex ) { return this->Metadata->GetObjectArrayName( objectType, arrayIndex ); } int vtkExodusIIReader::GetNumberOfObjectArrayComponents( int objectType, int arrayIndex ) { return this->Metadata->GetNumberOfObjectArrayComponents( objectType, arrayIndex ); } int vtkExodusIIReader::GetObjectArrayStatus( int objectType, int arrayIndex ) { return this->Metadata->GetObjectArrayStatus( objectType, arrayIndex ); } void vtkExodusIIReader::SetObjectArrayStatus( int objectType, int arrayIndex, int status ) { this->Metadata->SetObjectArrayStatus( objectType, arrayIndex, status ); } int vtkExodusIIReader::GetNumberOfObjectAttributes( int objectType, int objectIndex ) { return this->Metadata->GetNumberOfObjectAttributes( objectType, objectIndex ); } const char* vtkExodusIIReader::GetObjectAttributeName( int objectType, int objectIndex, int attribIndex ) { return this->Metadata->GetObjectAttributeName( objectType, objectIndex, attribIndex ); } int vtkExodusIIReader::GetObjectAttributeIndex( int objectType, int objectIndex, const char* attribName ) { return this->Metadata->GetObjectAttributeIndex( objectType, objectIndex, attribName ); } int vtkExodusIIReader::GetObjectAttributeStatus( int objectType, int objectIndex, int attribIndex ) { return this->Metadata->GetObjectAttributeStatus( objectType, objectIndex, attribIndex ); } void vtkExodusIIReader::SetObjectAttributeStatus( int objectType, int objectIndex, int attribIndex, int status ) { this->Metadata->SetObjectAttributeStatus( objectType, objectIndex, attribIndex, status ); } int vtkExodusIIReader::GetObjectArrayIndex( int objectType, const char* arrayName ) { if ( ! arrayName ) { vtkErrorMacro( "You must specify a non-NULL name" ); return -1; } int nObj = this->GetNumberOfObjectArrays( objectType ); if ( nObj == 0 ) { vtkWarningMacro( "No objects of that type (" << objectType << ") to find index for given array " << arrayName << "." ); return -1; } for ( int obj = 0; obj < nObj; ++obj ) { if ( !strcmp( arrayName, this->GetObjectArrayName( objectType, obj ) ) ) { return obj; } } vtkWarningMacro( "No arrays named \"" << arrayName << "\" of the specified type (" << objectType << ")." ); return -1; } int vtkExodusIIReader::GetTotalNumberOfNodes() { return this->Metadata->GetModelParams()->num_nodes; } int vtkExodusIIReader::GetTotalNumberOfEdges() { return this->Metadata->GetModelParams()->num_edge; } int vtkExodusIIReader::GetTotalNumberOfFaces() { return this->Metadata->GetModelParams()->num_face; } int vtkExodusIIReader::GetTotalNumberOfElements() { return this->Metadata->GetModelParams()->num_elem; } // %--------------------------------------------------------------------------- int vtkExodusIIReader::GetNumberOfPartArrays() { return this->Metadata->GetNumberOfParts(); } const char* vtkExodusIIReader::GetPartArrayName( int arrayIdx ) { return this->Metadata->GetPartName(arrayIdx); } int vtkExodusIIReader::GetPartArrayID( const char *name ) { int numArrays = this->GetNumberOfPartArrays(); for ( int i=0;i<numArrays;i++ ) { if ( strcmp( name, this->GetPartArrayName( i ) ) == 0 ) { return i; } } return -1; } const char* vtkExodusIIReader::GetPartBlockInfo( int arrayIdx ) { return this->Metadata->GetPartBlockInfo(arrayIdx); } void vtkExodusIIReader::SetPartArrayStatus( int index, int flag ) { // Only modify if we are 'out of sync' if (this->Metadata->GetPartStatus(index) != flag) { this->Metadata->SetPartStatus(index, flag); // Because which parts are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } void vtkExodusIIReader::SetPartArrayStatus( const char* name, int flag ) { // Only modify if we are 'out of sync' if (this->Metadata->GetPartStatus(name) != flag) { this->Metadata->SetPartStatus(name, flag); // Because which parts are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } int vtkExodusIIReader::GetPartArrayStatus( int index ) { return this->Metadata->GetPartStatus(index); } int vtkExodusIIReader::GetPartArrayStatus( const char* part ) { return this->Metadata->GetPartStatus(part); } int vtkExodusIIReader::GetNumberOfMaterialArrays() { return this->Metadata->GetNumberOfMaterials(); } const char* vtkExodusIIReader::GetMaterialArrayName( int arrayIdx ) { return this->Metadata->GetMaterialName(arrayIdx); } int vtkExodusIIReader::GetMaterialArrayID( const char* matl ) { (void)matl; return 0; } void vtkExodusIIReader::SetMaterialArrayStatus( int index, int flag ) { // Only modify if we are 'out of sync' if (this->Metadata->GetMaterialStatus(index) != flag) { this->Metadata->SetMaterialStatus(index, flag); // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } void vtkExodusIIReader::SetMaterialArrayStatus( const char* matl, int flag ) { // Only modify if we are 'out of sync' if (this->Metadata->GetMaterialStatus(matl) != flag) { this->Metadata->SetMaterialStatus(matl, flag); // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } int vtkExodusIIReader::GetMaterialArrayStatus( int index ) { return this->Metadata->GetMaterialStatus(index); } int vtkExodusIIReader::GetMaterialArrayStatus( const char* matl ) { return this->Metadata->GetMaterialStatus(matl); } int vtkExodusIIReader::GetNumberOfAssemblyArrays() { return this->Metadata->GetNumberOfAssemblies(); } const char* vtkExodusIIReader::GetAssemblyArrayName( int arrayIdx ) { return this->Metadata->GetAssemblyName(arrayIdx); } int vtkExodusIIReader::GetAssemblyArrayID( const char* name ) { int numArrays = this->GetNumberOfAssemblyArrays(); for ( int i=0;i<numArrays;i++ ) { if ( strcmp( name, this->GetAssemblyArrayName( i ) ) == 0 ) { return i; } } return -1; } void vtkExodusIIReader::SetAssemblyArrayStatus(int index, int flag) { // Only modify if we are 'out of sync' if (this->Metadata->GetAssemblyStatus(index) != flag) { this->Metadata->SetAssemblyStatus(index, flag); // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } void vtkExodusIIReader::SetAssemblyArrayStatus(const char* name, int flag) { // Only modify if we are 'out of sync' if (this->Metadata->GetAssemblyStatus(name) != flag) { this->Metadata->SetAssemblyStatus(name, flag); // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } int vtkExodusIIReader::GetAssemblyArrayStatus(int index) { return this->Metadata->GetAssemblyStatus(index); } int vtkExodusIIReader::GetAssemblyArrayStatus(const char* name) { return this->Metadata->GetAssemblyStatus(name); } int vtkExodusIIReader::GetNumberOfHierarchyArrays() { if (this->Metadata->Parser) { return this->Metadata->Parser->GetNumberOfHierarchyEntries(); } return 0; } const char* vtkExodusIIReader::GetHierarchyArrayName(int arrayIdx) { if (this->Metadata->Parser) { //MEMORY LEAK - without copying the result, the list does not appear on SGI's char* result=new char[512]; sprintf(result,"%s",this->Metadata->Parser->GetHierarchyEntry(arrayIdx).c_str()); return result; //return this->Metadata->Parser->GetHierarchyEntry(arrayIdx).c_str(); } return "Should not see this"; } void vtkExodusIIReader::SetHierarchyArrayStatus(int index, int flag) { // Only modify if we are 'out of sync' //if (this->GetHierarchyArrayStatus(index) != flag) // { if (this->Metadata->Parser) { vtkstd::vector<int> blocksIds = this->Metadata->Parser->GetBlocksForEntry(index); for (vtkstd::vector<int>::size_type i=0;i<blocksIds.size();i++) { this->Metadata->SetObjectStatus(vtkExodusIIReader::ELEM_BLOCK, this->GetObjectIndex(ELEM_BLOCK,blocksIds[i]),flag); } // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } void vtkExodusIIReader::SetHierarchyArrayStatus(const char* name, int flag) { // Only modify if we are 'out of sync' //if (this->GetHierarchyArrayStatus(name) != flag) //{ if (this->Metadata->Parser) { vtkstd::vector<int> blocksIds=this->Metadata->Parser->GetBlocksForEntry (vtkStdString(name)); for (vtkstd::vector<int>::size_type i=0;i<blocksIds.size();i++) { //cout << "turning block " << blocks[i] << " " << flag << endl; this->Metadata->SetObjectStatus(vtkExodusIIReader::ELEM_BLOCK, this->GetObjectIndex(ELEM_BLOCK,blocksIds[i]),flag); } // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } int vtkExodusIIReader::GetHierarchyArrayStatus(int index) { if (this->Metadata->Parser) { vtkstd::vector<int> blocksIds=this->Metadata->Parser->GetBlocksForEntry(index); for (vtkstd::vector<int>::size_type i=0;i<blocksIds.size();i++) { if (this->Metadata->GetObjectStatus(vtkExodusIIReader::ELEM_BLOCK, this->GetObjectIndex(ELEM_BLOCK,blocksIds[i]))==0) return 0; } } return 1; } int vtkExodusIIReader::GetHierarchyArrayStatus(const char* name) { if (this->Metadata->Parser) { vtkstd::vector<int> blocksIds=this->Metadata->Parser->GetBlocksForEntry(name); for (vtkstd::vector<int>::size_type i=0;i<blocksIds.size();i++) { if (this->Metadata->GetObjectStatus(vtkExodusIIReader::ELEM_BLOCK, this->GetObjectIndex(ELEM_BLOCK,blocksIds[i]))==0) return 0; } } return 1; } void vtkExodusIIReader::SetDisplayType( int typ ) { if ( typ == this->DisplayType || typ < 0 || typ > 2 ) return; this->DisplayType = typ; this->Modified(); } int vtkExodusIIReader::IsValidVariable( const char *type, const char *name ) { return (this->GetVariableID( type, name ) >= 0); } int vtkExodusIIReader::GetVariableID( const char *type, const char *name ) { int otyp = this->GetObjectTypeFromName( type ); if ( otyp < 0 ) { return 0; } switch ( otyp ) { case NODAL: case EDGE_BLOCK: case FACE_BLOCK: case ELEM_BLOCK: case NODE_SET: case EDGE_SET: case FACE_SET: case SIDE_SET: case ELEM_SET: return this->GetObjectArrayIndex( otyp, name ); case ASSEMBLY: return this->GetAssemblyArrayID( name ); case HIERARCHY: return -1; // FIXME: There is no this->GetHierarchyArrayID( name ) and it's not clear there should be. case MATERIAL: return this->GetMaterialArrayID( name ); case PART: return this->GetPartArrayID( name ); default: return -1; } } int vtkExodusIIReader::GetTimeSeriesData( int ID, const char* vName, const char* vType, vtkFloatArray* result ) { (void)ID; (void)vName; (void)vType; (void)result; return -1; } void vtkExodusIIReader::SetAllArrayStatus( int otyp, int status ) { int numObj; int i; switch ( otyp ) { case EDGE_BLOCK_CONN: case FACE_BLOCK_CONN: case ELEM_BLOCK_ELEM_CONN: case NODE_SET_CONN: case EDGE_SET_CONN: case FACE_SET_CONN: case SIDE_SET_CONN: case ELEM_SET_CONN: numObj = this->GetNumberOfObjects( otyp ); for ( i = 0; i < numObj; ++i ) { this->SetObjectStatus( otyp, i, status ); } break; case NODAL: case EDGE_BLOCK: case FACE_BLOCK: case ELEM_BLOCK: case NODE_SET: case EDGE_SET: case FACE_SET: case SIDE_SET: case ELEM_SET: numObj = this->GetNumberOfObjectArrays( otyp ); for ( i = 0; i < numObj; ++i ) { this->SetObjectArrayStatus( otyp, i, status ); } break; // --------------------- case ASSEMBLY: numObj = this->GetNumberOfAssemblyArrays(); for ( i = 0; i < numObj; ++i ) { this->SetAssemblyArrayStatus( i, status ); } case PART: numObj = this->GetNumberOfPartArrays(); for ( i = 0; i < numObj; ++i ) { this->SetPartArrayStatus( i, status ); } case MATERIAL: numObj = this->GetNumberOfMaterialArrays(); for ( i = 0; i < numObj; ++i ) { this->SetMaterialArrayStatus( i, status ); } case HIERARCHY: numObj = this->GetNumberOfHierarchyArrays(); for ( i = 0; i < numObj; ++i ) { this->SetHierarchyArrayStatus( i, status ); } default: ; break; } } void vtkExodusIIReader::NewExodusModel() { // These arrays are required by the Exodus II writer: this->GenerateGlobalElementIdArrayOn(); this->GenerateGlobalNodeIdArrayOn(); this->GenerateObjectIdCellArrayOn(); if ( this->ExodusModel ) { this->ExodusModel->Reset(); return; } this->ExodusModel = vtkExodusModel::New(); } void vtkExodusIIReader::Dump() { vtkIndent indent; this->PrintSelf( cout, indent ); } bool vtkExodusIIReader::FindXMLFile() { // If the XML filename exists and is newer than any existing parser (or there is no parser), reread XML file. if ( ( this->Metadata->Parser && this->Metadata->Parser->GetMTime() < this->XMLFileNameMTime && this->XMLFileName ) || ( ! Metadata->Parser ) ) { if ( Metadata->Parser ) { Metadata->Parser->Delete(); Metadata->Parser = 0; } if ( ! this->XMLFileName || ! vtksys::SystemTools::FileExists( this->XMLFileName ) ) { if ( this->FileName ) { vtkStdString baseName( vtksys::SystemTools::GetFilenameWithoutExtension( this->FileName ) ); vtkStdString xmlExt( baseName + ".xml" ); if ( vtksys::SystemTools::FileExists( xmlExt ) ) { this->SetXMLFileName( xmlExt.c_str() ); return true; } vtkStdString dartExt( baseName + ".dart" ); if ( vtksys::SystemTools::FileExists( dartExt ) ) { this->SetXMLFileName( dartExt.c_str() ); return true; } vtkStdString baseDir( vtksys::SystemTools::GetFilenamePath( this->FileName ) ); vtkStdString artifact( baseDir + "/artifact.dta" ); if ( vtksys::SystemTools::FileExists( artifact ) ) { this->SetXMLFileName( artifact.c_str() ); return true; } // Catch the case where filename was non-NULL but didn't exist. this->SetXMLFileName( 0 ); } } else { return true; } } return false; } COMP: Fix warnings #include "vtkExodusIIReader.h" #include "vtkExodusIICache.h" #include "vtkCellData.h" #include "vtkCellType.h" #include "vtkDataArray.h" #include "vtkDoubleArray.h" #include "vtkExodusModel.h" #include "vtkFloatArray.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkIntArray.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkSortDataArray.h" #include "vtkStdString.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkUnstructuredGrid.h" #include "vtkXMLParser.h" #include <vtkstd/algorithm> #include <vtkstd/vector> #include <vtkstd/map> #include "vtksys/SystemTools.hxx" #include "vtksys/RegularExpression.hxx" #include "exodusII.h" #include <stdio.h> #include <stdlib.h> /* for free() */ #include <string.h> /* for memset() */ #include <ctype.h> /* for toupper(), isgraph() */ #include <math.h> /* for cos() */ #ifdef EXODUSII_HAVE_MALLOC_H # include <malloc.h> #endif /* EXODUSII_HAVE_MALLOC_H */ #if defined(_WIN32) && !defined(__CYGWIN__) # define SNPRINTF _snprintf #else # define SNPRINTF snprintf #endif /// Define this to get printouts summarizing array glomming process #undef VTK_DBG_GLOM #define VTK_EXO_BLKSETID_NAME "BlockId" #define VTK_EXO_FUNC(funcall,errmsg)\ if ( (funcall) < 0 ) \ { \ vtkErrorMacro( errmsg ); \ return 1; \ } // ------------------------------------------------------------------- CONSTANTS static int obj_types[] = { EX_EDGE_BLOCK, EX_FACE_BLOCK, EX_ELEM_BLOCK, EX_NODE_SET, EX_EDGE_SET, EX_FACE_SET, EX_SIDE_SET, EX_ELEM_SET, EX_NODE_MAP, EX_EDGE_MAP, EX_FACE_MAP, EX_ELEM_MAP }; static int num_obj_types = (int)(sizeof(obj_types)/sizeof(obj_types[0])); static int obj_sizes[] = { EX_INQ_EDGE_BLK, EX_INQ_FACE_BLK, EX_INQ_ELEM_BLK, EX_INQ_NODE_SETS, EX_INQ_EDGE_SETS, EX_INQ_FACE_SETS, EX_INQ_SIDE_SETS, EX_INQ_ELEM_SETS, EX_INQ_NODE_MAP, EX_INQ_EDGE_MAP, EX_INQ_FACE_MAP, EX_INQ_ELEM_MAP, }; static const char* objtype_names[] = { "Edge block", "Face block", "Element block", "Node set", "Edge set", "Face set", "Side set", "Element set", "Node map", "Edge map", "Face map", "Element map" }; static const char* obj_typestr[] = { "L", "F", "E", "M", "D", "A", "S", "T", 0, /* maps have no result variables */ 0, 0, 0, }; #define OBJTYPE_IS_BLOCK(i) ((i>=0)&&(i<3)) #define OBJTYPE_IS_SET(i) ((i>2)&&(i<8)) #define OBJTYPE_IS_MAP(i) ((i>7)&&(i<12)) // Unlike obj* items above: // - conn* arrays only reference objects that generate connectivity information // - conn* arrays are ordered the way users expect the output (*not* the same as above) static int conn_types[] = { vtkExodusIIReader::ELEM_BLOCK_ELEM_CONN, vtkExodusIIReader::FACE_BLOCK_CONN, vtkExodusIIReader::EDGE_BLOCK_CONN, vtkExodusIIReader::ELEM_SET_CONN, vtkExodusIIReader::SIDE_SET_CONN, vtkExodusIIReader::FACE_SET_CONN, vtkExodusIIReader::EDGE_SET_CONN, vtkExodusIIReader::NODE_SET_CONN }; static int num_conn_types = (int)(sizeof(conn_types)/sizeof(conn_types[0])); // Given a conn_type index, what is its matching obj_type index? static int conn_obj_idx_cvt[] = { 2, 1, 0, 7, 6, 5, 4, 3 }; #define CONNTYPE_IS_BLOCK(i) ((i>=0)&&(i<3)) #define CONNTYPE_IS_SET(i) ((i>2)&&(i<8)) static const char* glomTypeNames[] = { "Scalar", "Vector2", "Vector3", "Symmetric Tensor", "Integration Point Values" }; // used to store pointer to ex_get_node_num_map or ex_get_elem_num_map: extern "C" { typedef int (*vtkExodusIIGetMapFunc)( int, int* ); } // ------------------------------------------------------------ XML PARSER CLASS class vtkExodusIIXMLParser : public vtkXMLParser { protected: vtkExodusIIReaderPrivate* Metadata; int InMaterialAssignment; public: static vtkExodusIIXMLParser* New(); vtkTypeRevisionMacro(vtkExodusIIXMLParser,vtkXMLParser); void Go( const char* xmlFileName, vtkExodusIIReaderPrivate* metadata ) { this->InMaterialAssignment = 0; if ( ! xmlFileName || ! metadata ) { vtkErrorMacro( "Must have a valid filename and metadata object to open XML file." ); } else { this->Metadata = metadata; //this->Metadata->Register( this ); this->SetFileName( xmlFileName ); this->Parse(); this->Metadata = 0; } } virtual vtkStdString GetPartNumber(int block) { return this->BlockIDToPartNumber[block]; } virtual vtkStdString GetPartDescription(int block) { return this->PartDescriptions[this->BlockIDToPartNumber[block]]; } virtual vtkStdString GetMaterialDescription(int block) { return this->MaterialDescriptions[this->BlockIDToPartNumber[block]]; } virtual vtkStdString GetMaterialSpecification(int block) { return this->MaterialSpecifications[this->BlockIDToPartNumber[block]]; } virtual vtkstd::vector<vtkStdString> GetAssemblyNumbers(int block) { return this->PartNumberToAssemblyNumbers[this->BlockIDToPartNumber[block]]; } virtual vtkstd::vector<vtkStdString> GetAssemblyDescriptions(int block) { return this->PartNumberToAssemblyDescriptions[this->BlockIDToPartNumber[block]]; } virtual int GetNumberOfHierarchyEntries() { return this->apbList.size(); } virtual vtkStdString GetHierarchyEntry(int num) { //since it's an STL list, we need to get the correct entry vtkstd::list<vtkStdString>::iterator iter=this->apbList.begin(); for(int i=0;i<num;i++) { iter++; } return (*iter); } virtual vtkstd::vector<int> GetBlocksForEntry(int num) { return this->apbToBlocks[this->GetHierarchyEntry(num)]; } virtual vtkstd::vector<int> GetBlocksForEntry(vtkStdString entry) { return this->apbToBlocks[entry]; } protected: vtkExodusIIXMLParser() { this->Metadata = 0; this->InMaterialAssignment = 0; } virtual ~vtkExodusIIXMLParser() { //this->Metadata->UnRegister( this ); } virtual void StartElement( const char* tagName, const char** attrs ) { (void)attrs; //FIXME: Useme const char* name = strrchr( tagName, ':' ); name = name ? name + 1 : tagName; // If tag name has xml namespace separator, get rid of namespace. vtkStdString tName( name ); if ( tName == "assembly" ) { //this->Metadata->AddAssembly( tName, this->ParentAssembly ); cout << name << "\n"; const char* assemblyNumber=this->GetValue("number",attrs); if (assemblyNumber) { this->CurrentAssemblyNumbers.push_back(vtkStdString(assemblyNumber)); } const char* assemblyDescription=this->GetValue("description",attrs); if (assemblyDescription) { this->CurrentAssemblyDescriptions.push_back(vtkStdString(assemblyDescription)); } //make the entry for the hierarchical list vtkStdString result=vtkStdString(""); for (vtkstd::vector<int>::size_type i=0; i<this->CurrentAssemblyNumbers.size()-1; i++) { result+=vtkStdString(" "); } result+=vtkStdString("Assembly: ")+ assemblyDescription+vtkStdString(" (")+ assemblyNumber+vtkStdString(")"); apbList.push_back(result); //record the indent level, used when we add blocks apbIndents[result]=this->CurrentAssemblyNumbers.size()-1; //make the blocks array apbToBlocks[result]=vtkstd::vector<int>(); } else if ( tName == "part" ) { //this->Metadata->AddPart( pnum, inst, curAssy ); cout << name << "\n"; const char* instance=this->GetValue("instance",attrs); vtkStdString instanceString=vtkStdString(""); if (instance) { instanceString=vtkStdString(instance); } const char* partString=this->GetValue("number",attrs); if (partString) { this->PartNumber=vtkStdString(partString)+ vtkStdString(" Instance: ")+ instanceString; } const char* partDescString=this->GetValue("description",attrs); if (partDescString && this->PartNumber!="") { this->PartDescriptions[this->PartNumber]= partDescString; } //copy the current assemblies to the assemblies list for this part. this->PartNumberToAssemblyNumbers[this->PartNumber]= vtkstd::vector<vtkStdString>(this->CurrentAssemblyNumbers); this->PartNumberToAssemblyDescriptions[this->PartNumber]= vtkstd::vector<vtkStdString>(this->CurrentAssemblyDescriptions); //make the hierarchical display entry vtkStdString result=vtkStdString(""); for (vtkstd::vector<int>::size_type i=0; i<this->CurrentAssemblyNumbers.size(); i++) { result+=vtkStdString(" "); } result+=vtkStdString("Part: ")+ partDescString+vtkStdString(" (")+ partString+vtkStdString(")")+vtkStdString(" Instance: ")+ instanceString; apbList.push_back(result); //record the indent level apbIndents[result]=this->CurrentAssemblyNumbers.size(); apbToBlocks[result]=vtkstd::vector<int>(); } else if ( tName == "material-specification" ) { //matl = this->Metadata->AddMatl( matname ); //this->Metadata->SetPartMaterial( this->CurrentPart, inst, matl ); cout << name << "\n"; if (this->PartNumber!="") { const char * materialDescriptionString= GetValue("description",attrs); if (materialDescriptionString) { this->MaterialDescriptions[this->PartNumber]= vtkStdString(materialDescriptionString); } const char * materialSpecificationString= GetValue("specification",attrs); if (materialSpecificationString) { this->MaterialSpecifications[this->PartNumber]= vtkStdString(materialSpecificationString); } } } else if ( tName == "blocks" ) { /* this->Metadata->AddPartBlock( pnum, blocktype, block id ); if ( this->InMaterialAssignment ) { this->Metadata->SetPartMaterial( this->CurrentPart, inst, matl ); } */ cout << name << "\n"; const char* instance=this->GetValue("part-instance",attrs); vtkStdString instanceString=vtkStdString(""); if (instance) { this->InstanceNumber=vtkStdString(instance); } const char* partString=this->GetValue("part-number",attrs); if (partString) { this->PartNumber=vtkStdString(partString); } } else if ( tName == "block" ) { //this->Metadata->SetBlockName( this->GetBlockType( attrs ), blockid ); cout << name << "\n"; const char* blockString=this->GetValue("id",attrs); int id=-1; if (blockString) { id=atoi(blockString); } if (this->PartNumber!="" && id>=0) { this->BlockIDToPartNumber[id]=this->PartNumber+ vtkStdString(" Instance: ")+this->InstanceNumber; //first insert block entry into apblist vtkStdString apbIndexString=this->PartNumber+ vtkStdString(") Instance: ")+this->InstanceNumber; vtkStdString partEntry=findEntry(this->apbList,apbIndexString); vtkStdString blockEntry=vtkStdString(""); if (partEntry!=vtkStdString("")) { //insert into apbList vtkstd::list<vtkStdString>::iterator pos= vtkstd::find(this->apbList.begin(),this->apbList.end(),partEntry); pos++; vtkStdString result=vtkStdString(""); for (int i=0;i<apbIndents[partEntry]+1;i++) { result+=vtkStdString(" "); } result+=vtkStdString("Block: ")+vtkStdString(blockString); blockEntry=result; this->apbList.insert(pos,result); apbToBlocks[result]=vtkstd::vector<int>(); } if (partEntry!=vtkStdString("") && blockEntry!=vtkStdString("")) { //update mapping //we know block number, so can get part number to update that. //using part number, we can update assembly mappings vtkStdString partIndexString=this->PartNumber+ vtkStdString(" Instance: ")+this->InstanceNumber; //we know the part entry //add block ID to block entry apbToBlocks[blockEntry].push_back(id); //add block ID to part apbToBlocks[partEntry].push_back(id); //get the assemblies vtkstd::vector<vtkStdString> assemblies= this->PartNumberToAssemblyNumbers[partIndexString]; //add block ID to assemblies for (vtkstd::vector<vtkStdString>::size_type j=0;j<assemblies.size();j++) { vtkStdString assemblyEntry=findEntry(this->apbList,assemblies[j]); apbToBlocks[assemblyEntry].push_back(id); } } } //parse material information if this block tag is part of a //material-assignments tag if (this->ParseMaterials==1 && id>=0) { const char* tmaterialName=this->GetValue("material-name",attrs); if (tmaterialName) { this->BlockIDToMaterial[id]=vtkStdString(tmaterialName); } } } else if ( tName == "material-assignments" ) { this->InMaterialAssignment = 1; cout << name << "\n"; this->ParseMaterials=1; } else if ( tName == "material" ) { cout << name << "\n"; const char* material=this->GetValue("name",attrs); const char* spec=this->GetValue("specification",attrs); const char* desc=this->GetValue("description",attrs); if (material && spec) { this->MaterialSpecificationsBlocks[vtkStdString(material)]=vtkStdString(spec); } if (material && desc) { this->MaterialDescriptionsBlocks[vtkStdString(material)]=vtkStdString(desc); } } } //returns the first string that contains sstring virtual vtkStdString findEntry(vtkstd::list<vtkStdString> slist, vtkStdString sstring){ for (vtkstd::list<vtkStdString>::iterator i=slist.begin(); i!=slist.end(); i++) { if ((*i).find(sstring)!=vtkStdString::npos) { return (*i); } } return vtkStdString(""); } virtual void EndElement(const char* tname) { const char* name=strrchr(tname,':'); if (!name) { name=tname; } else { name++; } if (strcmp(name,"assembly")==0) { this->CurrentAssemblyNumbers.pop_back(); this->CurrentAssemblyDescriptions.pop_back(); } else if (strcmp(name,"blocks")==0) { this->PartNumber=""; } else if (strcmp(name,"material-assignments")==0) { this->ParseMaterials=0; } } virtual int ParsingComplete() { //if we have as-tested materials, overwrite MaterialDescriptions //and MaterialSpecifications if (this->BlockIDToMaterial.size()>0) { this->MaterialSpecifications.clear(); this->MaterialDescriptions.clear(); for (vtkstd::map<int,vtkStdString>::iterator i=this->BlockIDToPartNumber.begin();i!=this->BlockIDToPartNumber.end();i++) { int blockID=(*i).first; this->MaterialSpecifications[this->BlockIDToPartNumber[blockID]]= this->MaterialSpecificationsBlocks[this->BlockIDToMaterial[blockID]]; this->MaterialDescriptions[this->BlockIDToPartNumber[blockID]]= this->MaterialDescriptionsBlocks[this->BlockIDToMaterial[blockID]]; } } //if we have no assembly information, we need to generate a bunch //of items from the BlockIDToPartNumber array if (this->apbList.size()==0) { for (vtkstd::map<int,vtkStdString>::iterator i=this->BlockIDToPartNumber.begin();i!=this->BlockIDToPartNumber.end();i++) { int id=(*i).first; vtkStdString part=(*i).second; vtkStdString partSpec=vtkStdString(""); vtkStdString instance=vtkStdString(""); //get part spec and instance from part int pos=part.find(" Instance: "); if (pos!=(int)vtkStdString::npos) { partSpec.assign(part,0,pos); instance.assign(part,pos+11,part.size()-(pos+11)); } this->PartDescriptions[part]=vtkStdString("None"); //convert id to a string char buffer[20]; sprintf(buffer,"%d",id); //find the Part entry in the apbList vtkStdString apbPartEntry=vtkStdString("Part: None (")+partSpec+vtkStdString(") Instance: ")+instance; vtkStdString apbBlockEntry=vtkStdString(" ")+vtkStdString("Block: ")+vtkStdString(buffer); vtkStdString foundEntry=this->findEntry(this->apbList,apbPartEntry); if (foundEntry==vtkStdString("")) { this->apbList.push_back(apbPartEntry); this->apbToBlocks[apbPartEntry]=vtkstd::vector<int>(); this->apbToBlocks[apbPartEntry].push_back(id); this->AssemblyDescriptions[apbPartEntry]=vtkStdString("None"); } //insert into apbList vtkstd::list<vtkStdString>::iterator positer= vtkstd::find(this->apbList.begin(),this->apbList.end(),apbPartEntry); positer++; this->apbList.insert(positer,apbBlockEntry); this->apbToBlocks[apbBlockEntry]=vtkstd::vector<int>(); this->apbToBlocks[apbBlockEntry].push_back(id); } } return vtkXMLParser::ParsingComplete(); } virtual const char* GetValue(const char* attr,const char** attrs) { int i; for (i=0;attrs[i];i+=2) { const char* name=strrchr(attrs[i],':'); if (!name) { name=attrs[i]; } else { name++; } if (strcmp(attr,name)==0) { return attrs[i+1]; } } return NULL; } private: vtkstd::map<vtkStdString,vtkStdString> MaterialSpecifications; vtkstd::map<vtkStdString,vtkStdString> MaterialDescriptions; vtkstd::map<vtkStdString,vtkStdString> PartDescriptions; vtkStdString PartNumber; vtkStdString InstanceNumber; int ParseMaterials; vtkstd::map<int,vtkStdString> BlockIDToPartNumber; vtkstd::map<vtkStdString,vtkstd::vector<vtkStdString> > PartNumberToAssemblyNumbers; vtkstd::map<vtkStdString,vtkstd::vector<vtkStdString> > PartNumberToAssemblyDescriptions; vtkstd::map<vtkStdString,vtkStdString> AssemblyDescriptions; vtkstd::vector<vtkStdString> CurrentAssemblyNumbers; vtkstd::vector<vtkStdString> CurrentAssemblyDescriptions; //mappings for as-tested materials vtkstd::map<vtkStdString,vtkStdString> MaterialSpecificationsBlocks; //maps material name to spec vtkstd::map<vtkStdString,vtkStdString> MaterialDescriptionsBlocks; //maps material name to desc vtkstd::map<int,vtkStdString> BlockIDToMaterial; //maps block id to material //hierarchical list mappings vtkstd::list<vtkStdString> apbList; vtkstd::map<vtkStdString,vtkstd::vector<int> > apbToBlocks; vtkstd::map<vtkStdString,int> apbIndents; }; vtkStandardNewMacro(vtkExodusIIXMLParser); vtkCxxRevisionMacro(vtkExodusIIXMLParser,"1.19"); // --------------------------------------------------- PRIVATE CLASS DECLARATION /** This class holds metadata for an Exodus file. * */ class vtkExodusIIReaderPrivate : public vtkObject { public: static vtkExodusIIReaderPrivate* New(); void PrintData( ostream& os, vtkIndent indent ); vtkTypeRevisionMacro(vtkExodusIIReaderPrivate,vtkObject); /// Open an ExodusII file for reading. Returns 0 on success. int OpenFile( const char* filename ); /// Close any ExodusII file currently open for reading. Returns 0 on success. int CloseFile(); /// Get metadata for an open file with handle \a exoid. int RequestInformation(); /// Read requested data and store in unstructured grid. int RequestData( vtkIdType timeStep, vtkUnstructuredGrid* output ); /// Reset the class so that another file may be read. void Reset(); /** Return the number of time steps in the open file. * You must have called RequestInformation() before invoking this member function. */ int GetNumberOfTimeSteps() { return (int) this->Times.size(); } /// Return the current time step vtkGetMacro(TimeStep,int); /// Set the current time step for subsequent calls to RequestData(). vtkSetMacro(TimeStep,int); /// Return whether subsequent RequestData() calls will produce the minimal point set required to represent the output. vtkGetMacro(SqueezePoints,int); /// Set whether subsequent RequestData() calls will produce the minimal point set required to represent the output. void SetSqueezePoints( int sp ); /// Convenience routines that for producing (or not) the minimal point set required to represent the output. vtkBooleanMacro(SqueezePoints,int); /// Return the number of nodes in the output (depends on SqueezePoints) int GetNumberOfNodes(); /** Returns the number of objects of a given type (e.g., EX_ELEM_BLOCK, EX_NODE_SET, ...). * You must have called RequestInformation before invoking this member function. */ int GetNumberOfObjectsOfType( int otype ); /** Returns the number of arrays defined over objects of a given type (e.g., EX_ELEM_BLOCK, EX_NODE_SET, ...). * You must have called RequestInformation before invoking this member function. * * N.B.: This method will eventually disappear. Really, what we should be providing is an interface to * query the arrays defined on a particular object, not a class of objects. However, until the reader * outputs multiblock datasets, we can't be that specific. */ int GetNumberOfObjectArraysOfType( int otype ); /** For a given object type, returns the name of the i-th object. * You must have called RequestInformation before invoking this member function. */ const char* GetObjectName( int otype, int i ); /** For a given object type, return the user-assigned ID of the i-th object. * You must have called RequestInformation before invoking this member function. */ int GetObjectId( int otype, int i ); /** For a given object type, return the size of the i-th object. * The size is the number of entries. * As an example, for an element block, it is the number of elements. * You must have called RequestInformation before invoking this member function. */ int GetObjectSize( int otype, int i ); /** For a given object type, returns the status of the i-th object. * You must have called RequestInformation before invoking this member function. */ int GetObjectStatus( int otype, int i ); /** For a given object type, returns the status of the i-th object, where i is * an index into the unsorted object array. * You must have called RequestInformation before invoking this member function. */ int GetUnsortedObjectStatus( int otype, int i ); /** For a given object type, sets the status of the i-th object. * You must have called RequestInformation before invoking this member function. */ void SetObjectStatus( int otype, int i, int stat ); /** For a given object type, sets the status of the i-th object, * where i is an index into the *unsorted* object array. * You must have called RequestInformation before invoking this member function. */ void SetUnsortedObjectStatus( int otype, int i, int stat ); /** For a given object type, returns the name of the i-th array. * You must have called RequestInformation before invoking this member function. */ const char* GetObjectArrayName( int otype, int i ); /** For a given object type, returns the number of components of the i-th array. * You must have called RequestInformation before invoking this member function. */ int GetNumberOfObjectArrayComponents( int otype, int i ); /** For a given object type, returns the status of the i-th array. * You must have called RequestInformation before invoking this member function. */ int GetObjectArrayStatus( int otype, int i ); /** For a given object type, sets the status of the i-th array. * You must have called RequestInformation before invoking this member function. */ void SetObjectArrayStatus( int otype, int i, int stat ); /** Unlike object arrays, attributes are only defined over blocks (not sets) * and are defined on a per-block (not a per-block-type) basis. * In other words, there is no truth table for attributes. * This means the interface is different because each block can have a different number of attributes with * different names. */ int GetNumberOfObjectAttributes( int objectType, int objectIndex ); const char* GetObjectAttributeName( int objectType, int objectIndex, int attributeIndex ); int GetObjectAttributeIndex( int objectType, int objectIndex, const char* attribName ); int GetObjectAttributeStatus( int objectType, int objectIndex, int attribIndex ); void SetObjectAttributeStatus( int objectType, int objectIndex, int attribIndex, int status ); /// Generate an array containing the block or set ID associated with each cell. vtkGetMacro(GenerateObjectIdArray,int); vtkSetMacro(GenerateObjectIdArray,int); const char* GetObjectIdArrayName() { return "ObjectId"; } vtkSetMacro(GenerateGlobalElementIdArray,int); vtkGetMacro(GenerateGlobalElementIdArray,int); static const char *GetGlobalElementIdArrayName() { return "GlobalElementId"; } vtkSetMacro(GenerateGlobalNodeIdArray,int); vtkGetMacro(GenerateGlobalNodeIdArray,int); static const char *GetGlobalNodeIdArrayName() { return "GlobalNodeId"; } virtual void SetApplyDisplacements( int d ); vtkGetMacro(ApplyDisplacements,int); virtual void SetDisplacementMagnitude( double s ); vtkGetMacro(DisplacementMagnitude,double); vtkSetMacro(HasModeShapes,int); vtkGetMacro(HasModeShapes,int); vtkSetMacro(ModeShapeTime,double); vtkGetMacro(ModeShapeTime,double); vtkDataArray* FindDisplacementVectors( int timeStep ); const struct ex_init_params* GetModelParams() const { return &this->ModelParameters; } /// A struct to hold information about time-varying arrays struct ArrayInfoType { /// The name of the array vtkStdString Name; /// The number of components in the array int Components; /** The type of "glomming" performed. * Glomming is the process of aggregating one or more results variable names * from the Exodus files into a single VTK result variable name with one or more * components. * One of: scalar, vector(2), vector(3), symtensor(6), integrationpoint. */ int GlomType; /// Storage type of array (a type that can be passed to vtkDataArray::Create()) int StorageType; /// The source of the array (Result or Attribute) int Source; /// Whether or not the array should be loaded by RequestData int Status; /// The name of each component of the array as defined by the Exodus file. Empty for generated arrays. vtkstd::vector<vtkStdString> OriginalNames; /// The index of each component of the array as ordered by the Exodus file. Empty for generated arrays. vtkstd::vector<int> OriginalIndices; /** A map describing which objects the variable is defined on. * Each key (a pair<int,int>) is a block/set type and integer * offset into the corresponding BlockInfo or SetInfo. * Its value is true when the variable is defined on the * block/set indicated by the key. * Otherwise (if the key is absent from the map or present with a * false value), the variable is not defined on that block/set. */ vtkstd::vector<int> ObjectTruth; /// Clear all the structure members. void Reset(); }; /// A struct to hold information about Exodus objects (blocks, sets, maps) struct ObjectInfoType { /// Number of entries in this block. int Size; /// Should the reader load this block? int Status; /// User-assigned identification number int Id; /// User-assigned name vtkStdString Name; }; /// A struct to hold information about Exodus maps struct MapInfoType : public ObjectInfoType { }; /// A struct to hold information about Exodus blocks or sets (they have some members in common) struct BlockSetInfoType : public ObjectInfoType { /// Id (1-based) of first entry in file-local list across all blocks in file vtkIdType FileOffset; /// Id (0-based) of first entry in the vtkUnstructuredGrid containing all blocks with Status != 0 vtkIdType GridOffset; }; /// A struct to hold information about Exodus blocks struct BlockInfoType : public BlockSetInfoType { vtkStdString TypeName; int BdsPerEntry[3]; // number of boundaries per entry. The index is the dimensionality of the entry. 0=node, 1=edge, 2=face int AttributesPerEntry; vtkstd::vector<vtkStdString> AttributeNames; vtkstd::vector<int> AttributeStatus; int CellType; // VTK cell type (a function of TypeName and BdsPerEntry...) int PointsPerCell; // Number of points per cell as used by VTK -- not what's in the file (i.e., BdsPerEntry[0] >= PointsPerCell) }; /// A struct to hold information about Exodus blocks struct PartInfoType : public ObjectInfoType { vtkstd::vector<int> BlockIndices; }; struct AssemblyInfoType : public ObjectInfoType { vtkstd::vector<int> BlockIndices; }; struct MaterialInfoType : public ObjectInfoType { vtkstd::vector<int> BlockIndices; }; /// A struct to hold information about Exodus sets struct SetInfoType : public BlockSetInfoType { int DistFact; // Number of distribution factors (for the entire block, not per array or entry) }; /// Tags to indicate how single-component Exodus arrays are glommed (aggregated) into multi-component VTK arrays. enum GlomTypes { Scalar=0, //!< The array is a scalar Vector2=1, //!< The array is a 2-D vector Vector3=2, //!< The array is a 3-D vector SymmetricTensor=3, //!< The array is a symmetric tensor (order xx, yy, zz, xy, yz, zx) IntegrationPoint=4 //!< The array is a set of integration point values }; /// Tags to indicate the source of values for an array. enum ArraySourceTypes { Result=0, //!< The array is composed of results variables (that vary over time) Attribute=1, //!< The array is composed of attributes (constants over time) Map=2, //!< The array has a corresponding entry in MapInfo Generated=3 //!< The array is procedurally generated (e.g., BlockId) }; /// Time stamp from last time we were in RequestInformation vtkTimeStamp InformationTimeStamp; friend class vtkExodusIIReader; virtual void SetParser( vtkExodusIIXMLParser* ); vtkGetObjectMacro(Parser,vtkExodusIIXMLParser); // Because Parts, Materials, and assemblies are not stored as arrays, // but rather as maps to the element blocks they make up, // we cannot use the Get|SetObject__() methods directly. int GetNumberOfParts(); const char* GetPartName(int idx); const char* GetPartBlockInfo(int idx); int GetPartStatus(int idx); int GetPartStatus(vtkStdString name); void SetPartStatus(int idx, int on); void SetPartStatus(vtkStdString name, int flag); int GetNumberOfMaterials(); const char* GetMaterialName(int idx); int GetMaterialStatus(int idx); int GetMaterialStatus(vtkStdString name); void SetMaterialStatus(int idx, int on); void SetMaterialStatus(vtkStdString name, int flag); int GetNumberOfAssemblies(); const char* GetAssemblyName(int idx); int GetAssemblyStatus(int idx); int GetAssemblyStatus(vtkStdString name); void SetAssemblyStatus(int idx, int on); void SetAssemblyStatus(vtkStdString name, int flag); protected: vtkExodusIIReaderPrivate(); ~vtkExodusIIReaderPrivate(); /// Any time the Status member of a block or set changes, this function must be called. void ComputeGridOffsets(); /// Returns true when order and text of names are consistent with integration points. Called from GlomArrayNames(). int VerifyIntegrationPointGlom( int nn, char** np, vtksys::RegularExpression& re, vtkStdString& field, vtkStdString& ele ); /// Aggregate Exodus array names into VTK arrays with multiple components void GlomArrayNames( int i, int num_obj, int num_vars, char** var_names, int* truth_tab ); /// Add generated array information to array info lists. void PrepareGeneratedArrayInfo(); /** Read connectivity information and populate an unstructured grid with cells. * If the connectivity hasn't changed since the last time RequestData was called, * this copies a cache to the output. * * Otherwise, this routine iterates over all block and set types. * For each type, it iterates over all objects of that type. * For each object whose status is 1, it reads that object's connectivity entries from * cache or disk and inserts cells into CachedConnectivity. * If SqueezePoints is on, then connectivity entries are translated as required and * PointMap is populated. * Finally, CachedConnectivity is shallow-copied to the output. * * AssembleOutputConnectivity returns 1 if cache was used, 0 otherwise. */ int AssembleOutputConnectivity( vtkIdType timeStep, vtkUnstructuredGrid* output ); /** Fill the output grid's point coordinates array. * Returns 1 on success, 0 on failure. * Failure occurs when the Exodus library is unable to read the point * coordindates array. This can be caused when there is not enough memory * or there is a file I/O problem. */ int AssembleOutputPoints( vtkIdType timeStep, vtkUnstructuredGrid* output ); /** Add the requested arrays to the output grid's point data. * This adds time-varying results arrays to the grid's vtkPointData object. */ int AssembleOutputPointArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ); /** Add the requested arrays to the output grid's cell data. * This adds time-varying results arrays to the grid's vtkCellData object. * Each array added may not be defined on all blocks of cells, so zero-padding will be used where required. */ int AssembleOutputCellArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ); /** Add maps to an output mesh. * Maps are special integer arrays that may serve as GlobalId fields in vtkDataSetAttributes objects. * Maps will only be zero-padded when cells representing set entries exist; * also, maps may be procedurally generated if no map is contained in a file. * Maps are not time-varying. */ int AssembleOutputPointMaps( vtkIdType timeStep, vtkUnstructuredGrid* output ); int AssembleOutputCellMaps( vtkIdType timeStep, vtkUnstructuredGrid* output ); /** Add procedurally generated arrays to an output mesh. * Currently, the only array that is procedurally generated is the object id array. * Others may be added in the future. */ int AssembleOutputProceduralArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ); /// Insert cells from a specified block into a mesh void InsertBlockCells( int otyp, int obj, int conn_type, int timeStep, vtkUnstructuredGrid* output ); /// Insert cells from a specified set into a mesh void InsertSetCells( int otyp, int obj, int conn_type, int timeStep, vtkUnstructuredGrid* output ); /// Add a point array to an output grid's point data, squeezing if necessary void AddPointArray( vtkDataArray* src, vtkUnstructuredGrid* output ); /// Insert cells referenced by a node set. void InsertSetNodeCopies( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ); /// Insert cells referenced by an edge, face, or element set. void InsertSetCellCopies( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ); /// Insert cells referenced by a side set. void InsertSetSides( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ); /** Return an array for the specified cache key. If the array was not cached, read it from the file. * This function can still return 0 if you are foolish enough to request an array not present in the file, grasshopper. */ vtkDataArray* GetCacheOrRead( vtkExodusIICacheKey ); /** Return the index of an object type (in a private list of all object types). * This returns a 0-based index if the object type was found and -1 if it was not. */ int GetConnTypeIndexFromConnType( int ctyp ); /** Return the index of an object type (in a private list of all object types). * This returns a 0-based index if the object type was found and -1 if it was not. */ int GetObjectTypeIndexFromObjectType( int otyp ); /** Return the number of objects of the given type. * The integer typeIndex is not the type of the object (e.g., EX_ELEM_BLOCK), but * is rather the index into the list of all object types (see obj_types in vtkExodusIIReader.cxx). */ int GetNumberOfObjectsAtTypeIndex( int typeIndex ); /** Return a pointer to the ObjectInfo of the specified type and index. * The integer typeIndex is not the type of the object (e.g., EX_ELEM_BLOCK), but * is rather the index into the list of all object types (see obj_types in vtkExodusIIReader.cxx). * The integer objectIndex is not the ID of the object (i.e., the ID stored in the Exodus file), * but is rather the index into the list of all objects of the given type. */ ObjectInfoType* GetObjectInfo( int typeIndex, int objectIndex ); /** Return a pointer to the ObjectInfo of the specified type and index, but using indices sorted by object ID. * This is the same as GetObjectInfo() except that it uses the SortedObjectIndices member to permute * the requested \a objectIndex and it takes an object type (e.g., EX_ELEM_BLOCK) rather than an object type index. */ ObjectInfoType* GetSortedObjectInfo( int objectType, int objectIndex ); /** Return a pointer to the ObjectInfo of the specified type and index, but using indices sorted by object ID. * This is the same as GetSortedObjectInfo() except that \a objectIndex directly indexes the object info array * rather SortedObjectIndices, and it takes an object type (e.g., EX_ELEM_BLOCK) rather than an object type index. */ ObjectInfoType* GetUnsortedObjectInfo( int objectType, int objectIndex ); /** Get the index of the block containing the entity referenced by the specified file-global ID. * In this case, an entity is an edge, face, or element. */ int GetBlockIndexFromFileGlobalId( int otyp, int refId ); /** Get the block containing the entity referenced by the specified file-global ID. * In this case, an entity is an edge, face, or element. */ BlockInfoType* GetBlockFromFileGlobalId( int otyp, int refId ); /// Find or create a new SqueezePoint ID (unique sequential list of points referenced by cells in blocks/sets with Status == 1) vtkIdType GetSqueezePointId( int i ); /// Determine the VTK cell type for a given edge/face/element block void DetermineVtkCellType( BlockInfoType& binfo ); /// Find an ArrayInfo object for a specific object type using the name as a key. ArrayInfoType* FindArrayInfoByName( int otyp, const char* name ); /// Does the specified object type match? Avoid using these... they aren't robust against new types being implemented. int IsObjectTypeBlock( int otyp ); int IsObjectTypeSet( int otyp ); int IsObjectTypeMap( int otyp ); /// Given a map type (NODE_MAP, EDGE_MAP, ...) return the associated object type (NODAL, EDGE_BLOCK, ...) or vice-versa. int GetObjectTypeFromMapType( int mtyp ); int GetMapTypeFromObjectType( int otyp ); /// Given a set connectivity type (NODE_SET_CONN, ...), return the associated object type (NODE_SET, ...) or vice-versa. int GetSetTypeFromSetConnType( int sctyp ); /// Given a block type (EDGE_BLOCK, ...), return the associated block connectivity type (EDGE_BLOCK_CONN, ...) or vice-versa. int GetBlockConnTypeFromBlockType( int btyp ); /// Get/Set the cached connectivity data vtkGetObjectMacro(CachedConnectivity,vtkUnstructuredGrid); virtual void SetCachedConnectivity( vtkUnstructuredGrid* mesh ); /** Function to trim space from names retrieved with ex_get_var_names. * This was added because some meshes had displacement arrays named "DISPX ", "DISPY ", "DISPZ " (note trailing spaces), * which prevented glomming and use of the vector field for displacements. */ void RemoveBeginningAndTrailingSpaces( int len, char **names ); // The next vtk ID to use for a connectivity entry when point squeezing is on and no point ID exists. vtkIdType NextSqueezePoint; /// Maps a block type (EX_ELEM_BLOCK, EX_FACE_BLOCK, ...) to a list of blocks of that type. vtkstd::map<int,vtkstd::vector<BlockInfoType> > BlockInfo; /// Maps a set type (EX_ELEM_SET, ..., EX_NODE_SET) to a list of sets of that type. vtkstd::map<int,vtkstd::vector<SetInfoType> > SetInfo; /** Maps a map type (EX_ELEM_MAP, ..., EX_NODE_MAP) to a list of maps of that type. * In old-style files, the only entries will be a single node and a single element map * which have no specified ID number or name. In that case, an ID of 0 and a name of * "Default" will be given to both. */ vtkstd::map<int,vtkstd::vector<MapInfoType> > MapInfo; vtkstd::vector<PartInfoType> PartInfo; vtkstd::vector<MaterialInfoType> MaterialInfo; vtkstd::vector<AssemblyInfoType> AssemblyInfo; /** Maps an object type to vector of indices that reorder objects of that type by their IDs. * This is used by the user interface to access blocks, sets, and maps in ascending order. * It is not used internally. */ vtkstd::map<int,vtkstd::vector<int> > SortedObjectIndices; /// Maps an object type (EX_ELEM_BLOCK, EX_NODE_SET, ...) to a list of arrays defined on that type. vtkstd::map<int,vtkstd::vector<ArrayInfoType> > ArrayInfo; /// These aren't the variables you're looking for. int AppWordSize; int DiskWordSize; /// The version of Exodus that wrote the currently open file (or a negative number otherwise). float ExodusVersion; /// The handle of the currently open file. int Exoid; /// Parameters describing the currently open Exodus file. struct ex_init_params ModelParameters; /// A list of time steps for which results variables are stored. vtkstd::vector<double> Times; /// The current time step int TimeStep; /// The time value. This is used internally when HasModeShapes is true and ignored otherwise. double ModeShapeTime; int GenerateObjectIdArray; int GenerateGlobalIdArray; /// A least-recently-used cache to hold raw arrays. vtkExodusIICache* Cache; /// Cache assembled connectivity separately because there's no way to SetLinks() on a vtkUnstructuredGrid. vtkUnstructuredGrid* CachedConnectivity; int GenerateGlobalElementIdArray; int GenerateGlobalNodeIdArray; int ApplyDisplacements; float DisplacementMagnitude; int HasModeShapes; /** Should the reader output only points used by elements in the output mesh, or all the points. * Outputting all the points is much faster since the point array can be read straight from * disk and the mesh connectivity need not be altered. * Squeezing the points down to the minimum set needed to produce the output mesh is useful for * glyphing and other point-based operations. On large parallel datasets, loading all the points * implies loading all the points on all processes and performing subsequent filtering on a much * larger set. * * By default, SqueezePoints is true for backwards compatability. */ int SqueezePoints; /// The total number of cells in the mesh given the current block and set Status values. vtkIdType NumberOfCells; /// The total number of points in the mesh given the SqueezePoints setting (and possibly the block and set Status values). //vtkIdType NumberOfPoints; /// A map from nodal IDs in an Exodus file to nodal IDs in the output mesh. vtkstd::vector<vtkIdType> PointMap; /// Pointer to owning reader... this is not registered in order to avoid circular references. vtkExodusIIReader* Parent; vtkExodusIIXMLParser *Parser; private: vtkExodusIIReaderPrivate( const vtkExodusIIReaderPrivate& ); // Not implemented. void operator = ( const vtkExodusIIReaderPrivate& ); // Not implemented. }; // ------------------------------------------------------------ UTILITY ROUTINES static int glomIntegrationPointElementDimension( vtkStdString& eleType ) { vtksys::RegularExpression reQuad( "[Qq][Uu][Aa][Dd]" ); vtksys::RegularExpression reHex( "[Hh][Ee][Xx]" ); vtksys::RegularExpression reTet( "[Tt][Ee][Tt]" ); vtksys::RegularExpression reTri( "[Tt][Rr][Ii]" ); vtksys::RegularExpression reWedge( "[Ww][Ee][Dd][Gg][Ee]" ); vtksys::RegularExpression rePyramid( "[Pp][Yy][Rr]" ); if ( reHex.find( eleType ) ) return 3; else if ( reTet.find( eleType ) ) return 3; else if ( reWedge.find( eleType ) ) return 3; else if ( rePyramid.find( eleType ) ) return 3; else if ( reQuad.find( eleType ) ) return 2; else if ( reTri.find( eleType ) ) return 2; return -1; } static int glomTruthTabMatch( int num_obj, int num_vars, int* truth_tab, vtkExodusIIReaderPrivate::ArrayInfoType& ainfo ) { // This returns 1 when all objects have the same values // in truth_tab for all original variable indices in // ainfo (and 0 otherwise). // It creates an entry in ainfo.ObjectTruth for each object // based on the values in truth_tab. int num_comp = (int)ainfo.OriginalIndices.size(); if ( num_comp < 1 ) return 0; int obj; int ttObj; // truth table entry for variable idx on object obj. int idx = ainfo.OriginalIndices[0] - 1; for ( obj = 0; obj < num_obj; ++obj ) { ttObj = truth_tab[ idx + obj * num_vars ]; ainfo.ObjectTruth.push_back( ttObj ); } if ( num_comp < 2 ) return 1; int comp; for ( comp = 1; comp < num_comp; ++comp ) { // Get truth table entry for 0-th variable of object obj: for ( obj = 0; obj < num_obj; ++obj ) { if ( truth_tab[ ainfo.OriginalIndices[comp] - 1 + obj * num_vars ] != truth_tab[ idx + obj * num_vars ] ) { // At least one object has a different truth table entry for variable ii. return 0; } } } return 1; // All objects define variable ii over the same subset of objects. } static void printBlock( ostream& os, vtkIndent indent, int btyp, vtkExodusIIReaderPrivate::BlockInfoType& binfo ) { int b = 0; while ( obj_types[b] >= 0 && obj_types[b] != btyp ) ++b; const char* btypnam = objtype_names[b]; os << indent << btypnam << " " << binfo.Id << " \"" << binfo.Name.c_str() << "\" (" << binfo.Size << ")\n"; os << indent << " FileOffset: " << binfo.FileOffset << "\n"; os << indent << " GridOffset: " << binfo.GridOffset << " (" << binfo.Status << ")\n"; os << indent << " Type: " << binfo.TypeName.c_str() << "\n"; os << indent << " Bounds per entry, Node: " << binfo.BdsPerEntry[0] << " Edge: " << binfo.BdsPerEntry[1] << " Face: " << binfo.BdsPerEntry[2] << "\n"; os << indent << " Attributes (" << binfo.AttributesPerEntry << "):"; int a; for ( a = 0; a < binfo.AttributesPerEntry; ++a ) { os << " \"" << binfo.AttributeNames[a].c_str() << "\"(" << binfo.AttributeStatus[a] << ")"; } os << "\n"; } static void printSet( ostream& os, vtkIndent indent, int styp, vtkExodusIIReaderPrivate::SetInfoType& sinfo ) { int s = 0; while ( obj_types[s] >= 0 && obj_types[s] != styp ) ++s; const char* stypnam = objtype_names[s]; os << indent << stypnam << " " << sinfo.Id << " \"" << sinfo.Name.c_str() << "\" (" << sinfo.Size << ")\n"; os << indent << " FileOffset: " << sinfo.FileOffset << "\n"; os << indent << " GridOffset: " << sinfo.GridOffset << " (" << sinfo.Status << ")\n"; os << indent << " DistFact: " << sinfo.DistFact << "\n"; } static void printMap( ostream& os, vtkIndent indent, int mtyp, vtkExodusIIReaderPrivate::MapInfoType& minfo ) { int m = 0; while ( obj_types[m] >= 0 && obj_types[m] != mtyp ) ++m; const char* mtypnam = objtype_names[m]; os << indent << mtypnam << " " << minfo.Id << " \"" << minfo.Name.c_str() << "\" (" << minfo.Size << ")\n"; os << indent << " Status: " << minfo.Status << "\n"; } static void printArray( ostream& os, vtkIndent indent, int atyp, vtkExodusIIReaderPrivate::ArrayInfoType& ainfo ) { (void)atyp; os << indent << " " << ainfo.Name.c_str() << " [" << ainfo.Status << "] ( " << ainfo.Components << " = { "; os << ainfo.OriginalIndices[0] << " \"" << ainfo.OriginalNames[0] << "\""; int i; for ( i = 1; i < (int) ainfo.OriginalIndices.size(); ++i ) { os << ", " << ainfo.OriginalIndices[i] << " \"" << ainfo.OriginalNames[i] << "\""; } os << " } )\n"; os << indent << " " << glomTypeNames[ ainfo.GlomType ] << " Truth:"; for ( i = 0; i < (int)ainfo.ObjectTruth.size(); ++i ) { os << " " << ainfo.ObjectTruth[i]; } os << "\n"; } // ---------------------------------------------------- PRIVATE SUBCLASS MEMBERS void vtkExodusIIReaderPrivate::ArrayInfoType::Reset() { if ( ! this->Name.empty() ) { this->Name.erase( this->Name.begin(), this->Name.end() ); } this->Components = 0; this->GlomType = -1; this->Status = 0; this->Source = -1; this->OriginalNames.clear(); this->OriginalIndices.clear(); this->ObjectTruth.clear(); } // ------------------------------------------------------- PRIVATE CLASS MEMBERS vtkCxxRevisionMacro(vtkExodusIIReaderPrivate,"1.19"); vtkStandardNewMacro(vtkExodusIIReaderPrivate); vtkCxxSetObjectMacro(vtkExodusIIReaderPrivate,CachedConnectivity,vtkUnstructuredGrid); vtkCxxSetObjectMacro(vtkExodusIIReaderPrivate,Parser,vtkExodusIIXMLParser); vtkExodusIIReaderPrivate::vtkExodusIIReaderPrivate() { this->Exoid = -1; this->ExodusVersion = -1.; this->AppWordSize = 8; this->DiskWordSize = 8; this->Cache = vtkExodusIICache::New(); this->TimeStep = 0; this->HasModeShapes = 0; this->ModeShapeTime = -1.; this->GenerateObjectIdArray = 1; this->GenerateGlobalElementIdArray = 0; this->GenerateGlobalNodeIdArray = 0; this->ApplyDisplacements = 1; this->DisplacementMagnitude = 1.; this->NumberOfCells = 0; this->SqueezePoints = 1; this->NextSqueezePoint = 0; this->CachedConnectivity = 0; this->Parser = 0; memset( (void*)&this->ModelParameters, 0, sizeof(this->ModelParameters) ); } vtkExodusIIReaderPrivate::~vtkExodusIIReaderPrivate() { this->CloseFile(); this->Cache->Delete(); this->SetCachedConnectivity( 0 ); if(this->Parser) { this->Parser->Delete(); this->Parser = 0; } } void vtkExodusIIReaderPrivate::ComputeGridOffsets() { vtkIdType startCell = 0; // Order cells in the grid in a way the user expects: // - blocks first, then sets. // - elements first, then faces, then edges. int conntypidx; for ( conntypidx = 0; conntypidx < num_conn_types; ++conntypidx ) { int otyp = obj_types[conn_obj_idx_cvt[conntypidx]]; int obj; int objNum; if ( CONNTYPE_IS_BLOCK( conntypidx ) ) { objNum = (int) this->BlockInfo[otyp].size(); for ( obj = 0; obj < objNum; ++obj ) { BlockInfoType* binfop = &this->BlockInfo[otyp][this->SortedObjectIndices[otyp][obj]]; if ( binfop->Status ) { binfop->GridOffset = startCell; startCell += binfop->Size; } } } else { // Must be a set... objNum = (int) this->SetInfo[otyp].size(); for ( obj = 0; obj < objNum; ++obj ) { SetInfoType* sinfop = &this->SetInfo[otyp][this->SortedObjectIndices[otyp][obj]]; if ( sinfop->Status ) { sinfop->GridOffset = startCell; startCell += sinfop->Size; } } } } this->NumberOfCells = startCell; } int vtkExodusIIReaderPrivate::VerifyIntegrationPointGlom( int nn, char** np, vtksys::RegularExpression& re, vtkStdString& field, vtkStdString& ele ) { vtkstd::vector<vtkstd::vector<int> > gpId; int max[3] = { 0, 0, 0 }; int dim = glomIntegrationPointElementDimension( ele ); for ( int i = 0; i < nn; ++i ) { gpId.push_back( vtkstd::vector<int>() ); re.find( np[i] ); vtkStdString gpIdStr = re.match(3); int d = 0; for ( vtkStdString::iterator it = gpIdStr.begin(); it != gpIdStr.end(); ++it, ++d ) { gpId[i].push_back( *it - '0' ); } if ( dim < 0 ) { dim = d; if ( dim > 3 ) { vtkWarningMacro( "Field \"" << np[i] << "\" has integration dimension " << d << " > 3." ); return false; } } else if ( dim != d ) { vtkWarningMacro( "Field \"" << np[i] << "\" has integration dimension " << d << " != " << dim << "." ); return false; } else { for ( int j = 0; j < dim; ++j ) if ( gpId[i][j] > max[j] ) max[j] = gpId[i][j]; } } #ifdef VTK_DBG_GLOM cout << " Integration points are " << dim << "-dimensional.\n"; for ( int i = 0; i < dim; ++i ) { cout << " " << (max[i]+1) << " integration points along " << char('r' + i) << ".\n"; } #endif // VTK_DBG_GLOM int npt = 1; for ( int i = 0; i < dim; ++i ) { npt *= max[i] + 1; } bool bad = false; if ( npt != nn ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" has " << nn << " entries, but I expected " << npt << " given the integration order." ); bad = true; } int e; int ef = -1; int cnt; bool found; if ( dim == 2 ) { for ( int r = 0; r <= max[0]; ++r ) { for ( int s = 0; s <= max[1]; ++s ) { found = false; cnt = 0; for ( e = 0; e < nn; ++e ) { if ( gpId[e][0] == r && gpId[e][1] == s ) { found = true; ef = e; ++cnt; } } if ( !found ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" is missing Gauss point (" << r << ", " << s << ")." ); } else if ( cnt > 1 ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" has " << (cnt-1) << " duplicate(s) of Gauss point (" << r << ", " << s << ")." ); } else if ( npt == nn && (ef != s + r * (max[1]+1) ) ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" has misplaced Gauss point (" << r << ", " << s << ")." ); bad = true; } } } } else if ( dim == 3 ) { for ( int r = 0; r <= max[0]; ++r ) { for ( int s = 0; s <= max[1]; ++s ) { for ( int t = 0; t <= max[2]; ++t ) { found = false; cnt = 0; for ( e = 0; e < nn; ++e ) { if ( gpId[e][0] == r && gpId[e][1] == s && gpId[e][2] == t ) { found = true; ef = e; ++cnt; } } if ( !found ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" is missing Gauss point (" << r << ", " << s << ", " << t << ")." ); bad = true; } else if ( cnt > 1 ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" has " << (cnt-1) << " duplicate(s) of Gauss point (" << r << ", " << s << ", " << t << ")." ); bad = true; } else if ( npt == nn && (ef != t + (max[2]+1) * ( s + r * (max[1]+1) )) ) { vtkWarningMacro( "Field \"" << field.c_str() << "\" has misplaced Gauss point (" << r << ", " << s << ", " << t << ")." ); bad = true; } } } } } return ! bad; } void vtkExodusIIReaderPrivate::GlomArrayNames( int objtyp, int num_obj, int num_vars, char** var_names, int* truth_tab ) { vtksys::RegularExpression reTensor( "(.*)[XxYyZz][XxYyZz]$" ); vtksys::RegularExpression reVector( "(.*)[XxYyZz]$" ); vtksys::RegularExpression reGaussP( "(.*)_([^_]*)_GP([0-9]+)$" ); ArrayInfoType ainfo; for ( int i = 0; i < num_vars; ++i ) { char* srcName = var_names[i]; bool didGlom = true; ainfo.Source = vtkExodusIIReaderPrivate::Result; if ( reTensor.find( srcName ) ) { if ( i + 1 < num_vars ) { int ii = i; int sl = (int)strlen(var_names[i]) - 2; while ( ii < num_vars ) { if ( ! reTensor.find( var_names[ii] ) || strncmp( var_names[ii], var_names[i], sl ) ) break; ainfo.OriginalNames.push_back( var_names[ii] ); ainfo.OriginalIndices.push_back( ii + 1 ); ++ii; } ainfo.Components = ii - i; if ( ! ainfo.Components || ! glomTruthTabMatch( num_obj, num_vars, truth_tab, ainfo ) ) { didGlom = false; } else { reTensor.find( srcName ); //cout << "Tensor \"" << reTensor.match(1) << "\" has " << (ii-i) << " components\n"; ainfo.Name = reTensor.match(1); ainfo.GlomType = vtkExodusIIReaderPrivate::SymmetricTensor; ainfo.Status = 0; ainfo.StorageType = VTK_DOUBLE; this->ArrayInfo[ objtyp ].push_back( ainfo ); i = ii - 1; // advance to end of glom } ainfo.Reset(); } else { didGlom = false; } } else if ( reVector.find( srcName ) ) { if ( i+1 < num_vars ) { int ii = i; while ( ii < num_vars ) { int sl = (int)strlen(var_names[ii]) - 1; // Require the strings to be identical except for the final XYZ at the end. if ( ! toupper(var_names[ii][sl]) == ('X' + (ii-i)) || strncmp( var_names[ii], var_names[i], sl ) ) break; ainfo.OriginalNames.push_back( var_names[ii] ); ainfo.OriginalIndices.push_back( ii + 1 ); ++ii; } ainfo.Components = ii - i; if ( ainfo.Components < 2 || ! glomTruthTabMatch( num_obj, num_vars, truth_tab, ainfo ) ) { didGlom = false; } else { //cout << "Vector \"" << reVector.match(1) << "\" has " << (ii - i) << " components\n"; ainfo.Name = reVector.match(1); ainfo.GlomType = ainfo.Components == 2 ? vtkExodusIIReaderPrivate::Vector2 : vtkExodusIIReaderPrivate::Vector3; ainfo.Status = 0; ainfo.StorageType = VTK_DOUBLE; this->ArrayInfo[ objtyp ].push_back( ainfo ); i = ii - 1; // advance to end of glom } ainfo.Reset(); } else { didGlom = false; } } else if ( reGaussP.find( srcName ) ) { if ( i + 1 < num_vars ) { int ii = i; vtkStdString field = reGaussP.match( 1 ); vtkStdString ele = reGaussP.match( 2 ); while ( ii < num_vars && reGaussP.find( var_names[ii] ) && (reGaussP.match( 1 ) == field) && (reGaussP.match( 2 ) == ele) ) { ainfo.OriginalNames.push_back( var_names[ii] ); ainfo.OriginalIndices.push_back( ii + 1 ); ++ii; } ainfo.Components = ii - i; // Check that the names are consistent (i.e., there aren't missing Gauss points, they all have the same dim, etc.) if ( this->VerifyIntegrationPointGlom( ii - i, var_names + i, reGaussP, field, ele ) && glomTruthTabMatch( num_obj, num_vars, truth_tab, ainfo ) ) { //cout << "Gauss Points for \"" << field << "\" on " << ele << "-shaped elements has " << (ii-i) << " components\n"; ainfo.Name = field; ainfo.GlomType = vtkExodusIIReaderPrivate::IntegrationPoint; ainfo.Status = 0; ainfo.StorageType = VTK_DOUBLE; this->ArrayInfo[ objtyp ].push_back( ainfo ); i = ii - 1; // advance to end of glom } else { ainfo.Reset(); for ( ; i < ii; ++i ) { //cout << "Scalar \"" << var_names[i] << "\"\n"; ainfo.Name = var_names[i]; ainfo.Source = Result; ainfo.Components = 1; ainfo.OriginalIndices.push_back( i + 1 ); ainfo.OriginalNames.push_back( var_names[i] ); ainfo.GlomType = vtkExodusIIReaderPrivate::Scalar; ainfo.StorageType = VTK_DOUBLE; ainfo.Status = 0; glomTruthTabMatch( num_obj, num_vars, truth_tab, ainfo ); // fill in ainfo.ObjectTruth this->ArrayInfo[ objtyp ].push_back( ainfo ); } } ainfo.Reset(); } else { didGlom = false; } } else { didGlom = false; } if ( ! didGlom ) { //cout << "Scalar \"" << srcName << "\"\n"; ainfo.Name = srcName; ainfo.Source = Result; ainfo.Components = 1; ainfo.OriginalIndices.push_back( i + 1 ); ainfo.OriginalNames.push_back( var_names[i] ); ainfo.GlomType = vtkExodusIIReaderPrivate::Scalar; ainfo.StorageType = VTK_DOUBLE; ainfo.Status = 0; glomTruthTabMatch( num_obj, num_vars, truth_tab, ainfo ); // fill in ainfo.ObjectTruth this->ArrayInfo[ objtyp ].push_back( ainfo ); ainfo.Reset(); } } } int vtkExodusIIReaderPrivate::AssembleOutputConnectivity( vtkIdType timeStep, vtkUnstructuredGrid* output ) { output->Reset(); // FIXME: Don't think I need this, since we ShallowCopy over it... right? if ( this->CachedConnectivity ) { output->ShallowCopy( this->CachedConnectivity ); return 1; } // OK, we needed to remake the cache... this->CachedConnectivity = vtkUnstructuredGrid::New(); this->CachedConnectivity->Allocate( this->NumberOfCells ); if ( this->SqueezePoints ) { this->NextSqueezePoint = 0; this->PointMap.clear(); this->PointMap.reserve( this->ModelParameters.num_nodes ); for ( int i = 0; i < this->ModelParameters.num_nodes; ++i ) { this->PointMap.push_back( -1 ); } } // Need to assemble connectivity array from smaller ones. // Call GetCacheOrRead() for each smaller array // Might want to experiment with the effectiveness of caching connectivity... set up the // ExodusIICache class with the ability to never cache some key types. // Might also want to experiment with policies other than LRU, especially applied to // arrays that are not time-varying. During animations, they will most likely get // dropped even though that might not be wise. // Loop over all the block and set types which could generate connectivity information // in an order that the user expects (element blocks first, blocks ordered by block ID, // not file order). int conntypidx; int nbl = 0; for ( conntypidx = 0; conntypidx < num_conn_types; ++conntypidx ) { int otyp = obj_types[conn_obj_idx_cvt[conntypidx]]; // Loop over all blocks/sets of this type int numObj = this->GetNumberOfObjectsOfType( otyp ); int obj; int sortIdx; for ( sortIdx = 0; sortIdx < numObj; ++sortIdx ) { if ( ! this->GetObjectStatus( otyp, sortIdx ) ) continue; obj = this->SortedObjectIndices[otyp][sortIdx]; // Preserve the "sorted" order when concatenating if ( CONNTYPE_IS_BLOCK(conntypidx) ) { this->InsertBlockCells( otyp, obj, conn_types[conntypidx], timeStep, this->CachedConnectivity ); } else if ( CONNTYPE_IS_SET(conntypidx) ) { this->InsertSetCells( otyp, obj, conn_types[conntypidx], timeStep, this->CachedConnectivity ); } else { vtkErrorMacro( "Bad connectivity object type. Harass the responsible programmer." ); } ++nbl; } } // OK, now copy our cache to the output... output->ShallowCopy( this->CachedConnectivity ); //this->CachedConnectivity->ShallowCopy( output ); if ( this->SqueezePoints ) { vtkDebugMacro( << "Squeezed down to " << this->NextSqueezePoint << " points\n" ); } return 0; } int vtkExodusIIReaderPrivate::AssembleOutputPoints( vtkIdType timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; vtkPoints* pts = output->GetPoints(); if ( ! pts ) { pts = vtkPoints::New(); output->SetPoints( pts ); pts->FastDelete(); } else { pts->Reset(); } int ts = -1; // If we don't have displacements, only cache the array under one key. if ( this->ApplyDisplacements && this->FindDisplacementVectors( timeStep ) ) { // Otherwise, each time step's array will be different. ts = timeStep; } vtkDataArray* arr = this->GetCacheOrRead( vtkExodusIICacheKey( ts, vtkExodusIIReader::NODAL_COORDS, 0, 0 ) ); if ( ! arr ) { vtkErrorMacro( "Unable to read points from file." ); return 0; } if ( this->SqueezePoints ) { vtkIdType exoPtId; pts->SetNumberOfPoints( this->NextSqueezePoint ); for ( exoPtId = 0; exoPtId < this->ModelParameters.num_nodes; ++exoPtId ) { vtkIdType outPtId = this->PointMap[exoPtId]; if ( outPtId >= 0 ) { pts->SetPoint( outPtId, arr->GetTuple( exoPtId ) ); } } } else { pts->SetData( arr ); } return 1; } int vtkExodusIIReaderPrivate::AssembleOutputPointArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ) { int status = 1; vtkstd::vector<ArrayInfoType>::iterator ai; int aidx = 0; for ( ai = this->ArrayInfo[ vtkExodusIIReader::NODAL ].begin(); ai != this->ArrayInfo[ vtkExodusIIReader::NODAL ].end(); ++ai, ++aidx ) { if ( ! ai->Status ) continue; // Skip arrays we don't want. vtkExodusIICacheKey key( timeStep, vtkExodusIIReader::NODAL, 0, aidx ); vtkDataArray* src = this->GetCacheOrRead( key ); if ( !src ) { vtkWarningMacro( "Unable to read point array " << ai->Name.c_str() << " at time step " << timeStep ); status = 0; continue; } this->AddPointArray( src, output ); } return status; } int vtkExodusIIReaderPrivate::AssembleOutputCellArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ) { // Need to assemble arrays from smaller per-block/set arrays. // Call GetCacheOrRead() for each smaller array // Step 1. Create the large arrays and fill them (but don't pad them). vtkCellData* cd = output->GetCellData(); vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator ami; for ( ami = this->ArrayInfo.begin(); ami != this->ArrayInfo.end(); ++ami ) { if ( ami->first == vtkExodusIIReader::NODAL || ami->first == vtkExodusIIReader::NODE_MAP ) continue; // we handle nodal arrays in AssembleOutputPointArrays // See if any objects of this type are turned on (Status != 0) int obj; int numObjOn = 0; int numObj = this->GetNumberOfObjectsOfType( ami->first ); for ( obj = 0; obj < numObj; ++obj ) { if ( this->GetObjectStatus( ami->first, obj ) ) { ++numObjOn; } } if ( numObjOn == 0 ) continue; // this array may be on, but no objects of this type are active... skip it. vtkstd::vector<ArrayInfoType>::iterator ai; int aidx = 0; for ( ai = ami->second.begin(); ai != ami->second.end(); ++ai, ++aidx ) { if ( ! ai->Status ) continue; vtkDataArray* arr = cd->GetArray( ai->Name.c_str() ); if ( arr ) { // OK, we've already created this array for some other type of object, // so now we have to make sure the arrays are consistent. If not, we // turn off the second one we encounter. The user can disable the first // and re-enable the second if required. if ( arr->GetDataType() != ai->StorageType ) { vtkErrorMacro( "Cell array \"" << ai->Name.c_str() << "\" has conflicting types across blocks/sets." ); ai->Status = 0; // Don't load this block's/set's version. User must disable other block/set before loading this one. arr = 0; } if ( arr && (arr->GetNumberOfComponents() != ai->Components) ) { vtkErrorMacro( "Cell array \"" << ai->Name.c_str() << "\" has different number of components across blocks/sets." ); ai->Status = 0; // Don't load this block's/set's version. User must disable other block/set before loading this one. arr = 0; } } else { // Re-use an existing or create a new array vtkExodusIICacheKey key( ai->Source == Result ? timeStep : -1, vtkExodusIIReader::GLOBAL, ami->first, aidx ); arr = this->Cache->Find( key ); if ( arr ) { // Existing array was in cache cd->AddArray( arr ); continue; } arr = vtkDataArray::CreateDataArray( ai->StorageType ); arr->SetName( ai->Name.c_str() ); arr->SetNumberOfComponents( ai->Components ); arr->SetNumberOfTuples( this->NumberOfCells ); cd->AddArray( arr ); this->Cache->Insert( key, arr ); arr->FastDelete(); } if ( ! arr ) { continue; } // OK, the array exists and has the correct number of tuples. Loop over all objects of // this type and insert their values into the global cell array according to their GridOffset. int otypidx = this->GetObjectTypeIndexFromObjectType( ami->first ); BlockSetInfoType* bsinfop; vtkDataArray* src; for ( obj = 0; obj < numObj; ++obj ) { if ( ! ai->ObjectTruth[obj] ) { // skip blocks for which this array doesn't exist. continue; } src = 0; if ( OBJTYPE_IS_BLOCK( otypidx ) ) { BlockInfoType* binfop = &this->BlockInfo[ami->first][obj]; bsinfop = (BlockSetInfoType*) binfop; if ( binfop->Status ) { src = this->GetCacheOrRead( vtkExodusIICacheKey( timeStep, ami->first, obj, aidx ) ); if ( src ) { vtkIdType c; for ( c = 0; c < binfop->Size; ++c ) { cd->CopyTuple( src, arr, c, c + binfop->GridOffset ); } } } } else if ( OBJTYPE_IS_SET( otypidx ) ) { SetInfoType* sinfop = &this->SetInfo[ami->first][obj]; bsinfop = (BlockSetInfoType*) sinfop; if ( sinfop->Status ) { src = this->GetCacheOrRead( vtkExodusIICacheKey( timeStep, ami->first, obj, aidx ) ); if ( src ) { vtkIdType c; for ( c = 0; c < sinfop->Size; ++c ) { cd->CopyTuple( src, arr, c, c + sinfop->GridOffset ); } } } } else { vtkErrorMacro( "Array defined for an unknown type of object: " << ami->first << " with index: " << otypidx << ". Skipping." ); continue; } if ( ! src && bsinfop && bsinfop->Status ) { vtkErrorMacro( "Cell array \"" << ai->Name.c_str() << "\" not defined on " << objtype_names[otypidx] << " " << bsinfop->Id << " but truth table claimed it was. Fixing truth table in memory (not in file)."); ai->ObjectTruth[obj] = 0; } } } } // Step 2. Now that we have very carefully created an array with a storage // type and number of components that match the arrays whose status is 1, // loop over the objects whose status is 1 but that do not have an // an array status of 1 or who have truth table set to 0. These objects // need to pad the arrays with zeros. int otypidx; for ( otypidx = 0; obj_types[otypidx] != vtkExodusIIReader::NODE_MAP; ++otypidx ) { int otyp = obj_types[otypidx]; int obj; int numObj = this->GetNumberOfObjectsOfType( otyp ); int ai; for ( ai = 0; ai < cd->GetNumberOfArrays(); ++ai ) { vtkDataArray* arr = cd->GetArray( ai ); ArrayInfoType* ainfop = this->FindArrayInfoByName( otyp, arr->GetName() ); for ( obj = 0; obj < numObj; ++obj ) { BlockSetInfoType* bsinfop = (BlockSetInfoType*) this->GetObjectInfo( otypidx, obj ); if ( bsinfop && bsinfop->Status && ( !ainfop || ! ainfop->Status || ( ainfop->Status && ! ainfop->ObjectTruth[obj] ) ) ) { vtkstd::vector<double> zedTuple( arr->GetNumberOfComponents(), 0. ); // an empty tuple used to pad arrays vtkIdType i; vtkIdType c = bsinfop->GridOffset; vtkDebugMacro( << arr->GetName() << ": Padding " << bsinfop->Size << " cells at " << c << "\n" ); for ( i = 0; i < bsinfop->Size; ++i, ++c ) { arr->SetTuple( c, &zedTuple[0] ); } } } } } return 1; } int vtkExodusIIReaderPrivate::AssembleOutputPointMaps( vtkIdType timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; int status = 1; vtkstd::vector<MapInfoType>::iterator mi; int midx = 0; for ( mi = this->MapInfo[ vtkExodusIIReader::NODE_MAP ].begin(); mi != this->MapInfo[ vtkExodusIIReader::NODE_MAP ].end(); ++mi, ++midx ) { if ( ! mi->Status ) continue; // Skip arrays we don't want. vtkExodusIICacheKey key( -1, vtkExodusIIReader::NODE_MAP, 0, midx ); vtkDataArray* src = this->GetCacheOrRead( key ); if ( !src ) { vtkWarningMacro( "Unable to read point map array \"" << mi->Name.c_str() << "\" (" << midx << ")" ); status = 0; continue; } this->AddPointArray( src, output ); } return status; } int vtkExodusIIReaderPrivate::AssembleOutputCellMaps( vtkIdType timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; // Step 1. Create the large arrays and fill them (but don't pad them). vtkCellData* cd = output->GetCellData(); vtkstd::map<int,vtkstd::vector<MapInfoType> >::iterator mmi; for ( mmi = this->MapInfo.begin(); mmi != this->MapInfo.end(); ++mmi ) { if ( mmi->first == vtkExodusIIReader::NODAL || mmi->first == vtkExodusIIReader::NODE_MAP ) continue; // we handle nodal arrays in AssembleOutputPointMaps // See if any maps of this type are turned on (Status != 0) int obj; int numObjOn = 0; int numObj = this->GetNumberOfObjectsOfType( mmi->first ); for ( obj = 0; obj < numObj; ++obj ) { if ( this->GetObjectStatus( mmi->first, obj ) ) { ++numObjOn; break; // know we know we need the array } } if ( numObjOn == 0 ) continue; // this array may be on, but no objects of this type are active... skip it. vtkstd::vector<MapInfoType>::iterator mi; int midx = 0; for ( mi = mmi->second.begin(); mi != mmi->second.end(); ++mi, ++midx ) { if ( ! mi->Status ) continue; vtkDataArray* arr = cd->GetArray( mi->Name.c_str() ); if ( arr ) { // OK, we've already created this array for some other type of object, // so now we have to make sure the arrays are consistent. If not, we // turn off the second one we encounter. The user can disable the first // and re-enable the second if required. if ( arr->GetDataType() != VTK_ID_TYPE ) { vtkErrorMacro( "Cell array \"" << mi->Name.c_str() << "\" has conflicting types." ); mi->Status = 0; // Don't load this map. User must disable other array before loading this one. arr = 0; } if ( arr && (arr->GetNumberOfComponents() != 1) ) { vtkErrorMacro( "Cell array \"" << mi->Name.c_str() << "\" has different number of components than map requires." ); mi->Status = 0; // Don't load this block's/set's version. User must disable other block/set before loading this one. arr = 0; } } else { // Create the array arr = vtkIdTypeArray::New(); arr->SetName( mi->Name.c_str() ); arr->SetNumberOfComponents( 1 ); arr->SetNumberOfTuples( this->NumberOfCells ); // Eliminate the second pass that pads cells by initializing the entire array here. memset( arr->GetVoidPointer(0), 0, this->NumberOfCells * sizeof(vtkIdType) ); cd->AddArray( arr ); arr->FastDelete(); } if ( ! arr ) { continue; } // OK, the array exists and has the correct number of tuples. Loop over all objects of // this type and insert their values into the global cell array according to their GridOffset. int otyp = this->GetObjectTypeFromMapType( mmi->first ); BlockInfoType* binfop; vtkDataArray* src; int numBlk = (int) this->BlockInfo[otyp].size(); int blk; src = this->GetCacheOrRead( vtkExodusIICacheKey( -1, mmi->first, 0, midx ) ); if ( src ) { for ( blk = 0; blk < numBlk; ++blk ) { binfop = &this->BlockInfo[otyp][blk]; if ( ! binfop->Status ) continue; vtkIdType c; for ( c = 0; c < binfop->Size; ++c ) { cd->CopyTuple( src, arr, c + binfop->FileOffset - 1, c + binfop->GridOffset ); } } } // === } } return 1; } int vtkExodusIIReaderPrivate::AssembleOutputProceduralArrays( vtkIdType timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; int status = 7; if ( this->GenerateObjectIdArray ) { vtkExodusIICacheKey key( -1, vtkExodusIIReader::GLOBAL_OBJECT_ID, 0, 0 ); vtkDataArray* arr = this->GetCacheOrRead( key ); vtkCellData* cd = output->GetCellData(); if ( arr ) { cd->AddArray( arr ); status -= 1; } } if ( this->GenerateGlobalElementIdArray ) { // This retrieves the first new-style map, or if that is not present, // the solitary old-style map (which always exists but may be // procedurally generated if it is not stored with the file). vtkExodusIICacheKey key( -1, vtkExodusIIReader::GLOBAL_ELEMENT_ID, 0, 0 ); vtkDataArray* arr = this->GetCacheOrRead( key ); vtkCellData* cd = output->GetCellData(); if ( arr ) { vtkDataArray* ped = vtkIdTypeArray::New(); ped->DeepCopy( arr ); ped->SetName( vtkExodusIIReader::GetPedigreeElementIdArrayName() ); cd->AddArray( ped ); cd->SetGlobalIds( arr ); ped->FastDelete(); status -= 2; } } if ( this->GenerateGlobalNodeIdArray ) { // This retrieves the first new-style map, or if that is not present, // the solitary old-style map (which always exists but may be // procedurally generated if it is not stored with the file). vtkExodusIICacheKey key( -1, vtkExodusIIReader::GLOBAL_NODE_ID, 0, 0 ); vtkDataArray* arr = this->GetCacheOrRead( key ); vtkPointData* pd = output->GetPointData(); if ( arr ) { vtkDataArray* ped = vtkIdTypeArray::New(); ped->DeepCopy( arr ); ped->SetName( vtkExodusIIReader::GetPedigreeNodeIdArrayName() ); pd->AddArray( ped ); pd->SetGlobalIds( arr ); ped->FastDelete(); status -= 4; } } return status; } void vtkExodusIIReaderPrivate::InsertBlockCells( int otyp, int obj, int conn_type, int timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; BlockInfoType* binfo = &this->BlockInfo[otyp][obj]; if ( binfo->Size == 0 ) { // No entries in this block. // This happens in parallel filesets when all elements are distributed to other files. // Silently ignore. return; } vtkIntArray* arr; arr = vtkIntArray::SafeDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, conn_type, obj, 0 ) ) ); if ( ! arr ) { vtkWarningMacro( "Block wasn't present in file? Working around it. Expect trouble." ); binfo->Status = 0; this->ComputeGridOffsets(); return; } if ( this->SqueezePoints ) { vtkstd::vector<vtkIdType> cellIds; cellIds.resize( binfo->PointsPerCell ); int* srcIds = arr->GetPointer( 0 ); for ( int i = 0; i < binfo->Size; ++i ) { for ( int p = 0; p < binfo->PointsPerCell; ++p ) { cellIds[p] = this->GetSqueezePointId( srcIds[p] ); //cout << " " << srcIds[p] << "(" << cellIds[p] << ")"; } //cout << "\n"; //cout << " " << output->InsertNextCell( binfo->CellType, binfo->PointsPerCell, &cellIds[0] ); srcIds += binfo->PointsPerCell; } //cout << "\n"; } else { #ifdef VTK_USE_64BIT_IDS vtkstd::vector<vtkIdType> cellIds; cellIds.resize( binfo->PointsPerCell ); int* srcIds = arr->GetPointer( 0 ); for ( int i = 0; i < binfo->Size; ++i ) { for ( int p = 0; p < binfo->PointsPerCell; ++p ) { cellIds[p] = srcIds[p]; //cout << " " << srcIds[p]; } //cout << "\n"; output->InsertNextCell( binfo->CellType, binfo->PointsPerCell, &cellIds[0] ); srcIds += binfo->PointsPerCell; } #else // VTK_USE_64BIT_IDS vtkIdType* srcIds = (vtkIdType*) arr->GetPointer( 0 ); for ( int i = 0; i < binfo->Size; ++i ) { output->InsertNextCell( binfo->CellType, binfo->PointsPerCell, srcIds ); srcIds += binfo->PointsPerCell; //for ( int k = 0; k < binfo->PointsPerCell; ++k ) //cout << " " << srcIds[k]; //cout << "\n"; } #endif // VTK_USE_64BIT_IDS } } void vtkExodusIIReaderPrivate::InsertSetCells( int otyp, int obj, int conn_type, int timeStep, vtkUnstructuredGrid* output ) { (void)timeStep; SetInfoType* sinfo = &this->SetInfo[otyp][obj]; if ( sinfo->Size == 0 ) { // No entries in this set. // This happens in parallel filesets when all elements are distributed to other files. // Silently ignore. return; } vtkIntArray* arr = vtkIntArray::SafeDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, conn_type, obj, 0 ) ) ); if ( ! arr ) { vtkWarningMacro( "Set wasn't present in file? Working around it. Expect trouble." ); sinfo->Status = 0; this->ComputeGridOffsets(); return; } switch ( otyp ) { case vtkExodusIIReader::NODE_SET: // Easy this->InsertSetNodeCopies( arr, otyp, obj, output ); break; case vtkExodusIIReader::EDGE_SET: // Not so fun. We must copy cells from possibly many edge blocks. this->InsertSetCellCopies( arr, vtkExodusIIReader::EDGE_BLOCK, obj, output ); break; case vtkExodusIIReader::FACE_SET: // Not so fun. We must copy cells from possibly many face blocks. this->InsertSetCellCopies( arr, vtkExodusIIReader::FACE_BLOCK, obj, output ); break; case vtkExodusIIReader::SIDE_SET: // Way hard even when we let Exodus do a lot for us. this->InsertSetSides( arr, otyp, obj, output ); break; case vtkExodusIIReader::ELEM_SET: // Not so fun. We must copy cells from possibly many element blocks. this->InsertSetCellCopies( arr, vtkExodusIIReader::ELEM_BLOCK, obj, output ); break; } } void vtkExodusIIReaderPrivate::AddPointArray( vtkDataArray* src, vtkUnstructuredGrid* output ) { vtkPointData* pd = output->GetPointData(); if ( this->SqueezePoints ) { // subset the array using PointMap vtkDataArray* dest = vtkDataArray::CreateDataArray( src->GetDataType() ); dest->SetName( src->GetName() ); dest->SetNumberOfComponents( src->GetNumberOfComponents() ); dest->SetNumberOfTuples( this->NextSqueezePoint ); vtkIdType exoPtId; for ( exoPtId = 0; exoPtId < this->ModelParameters.num_nodes; ++exoPtId ) { vtkIdType outPtId = this->PointMap[exoPtId]; if ( outPtId >= 0 ) { pd->CopyTuple( src, dest, exoPtId, outPtId ); } } pd->AddArray( dest ); dest->FastDelete(); } else { pd->AddArray( src ); } } void vtkExodusIIReaderPrivate::InsertSetNodeCopies( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ) { (void)otyp; (void)obj; // Insert a "VERTEX" cell for each node in the set. vtkIdType ref; vtkIdType tmp; int* iptr = refs->GetPointer( 0 ); if ( this->SqueezePoints ) { // this loop is separated out to handle case (stride > 1 && pref[1] < 0 && this->SqueezePoints) for ( ref = 0; ref < refs->GetNumberOfTuples(); ++ref, ++iptr ) { tmp = *iptr; vtkIdType* x = &this->PointMap[tmp]; if ( *x < 0 ) { *x = this->NextSqueezePoint++; } output->InsertNextCell( VTK_VERTEX, 1, x ); } } else { for ( ref = 0; ref < refs->GetNumberOfTuples(); ++ref, ++iptr ) { tmp = *iptr; output->InsertNextCell( VTK_VERTEX, 1, &tmp ); } } } void vtkExodusIIReaderPrivate::InsertSetCellCopies( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ) { (void)obj; // First, sort the set by entry number (element, face, or edge ID) // so that we can refer to each block just once as we process cells. vtkSortDataArray::SortArrayByComponent( refs, 0 ); refs->Register( this ); // Don't let the cache delete this array when we fetch others... vtkIdType nrefs = refs->GetNumberOfTuples(); vtkIdType ref = 0; vtkIdType bnum = -1; vtkIdType lastBlockEntry = -1; int* pref = refs->GetPointer( 0 ); int stride = refs->GetNumberOfComponents(); BlockInfoType* binfop = 0; //&this->BlockInfo[otyp][bnum]; int* nodeconn = 0; vtkIdType* cellConn; int nnpe = 0; vtkIntArray* nconn; vtkstd::vector<vtkIdType> tmpTuple; while ( ref < nrefs ) { int loadNewBlk = 0; while ( pref[0] >= lastBlockEntry ) { // advance to the next block (always true first time through parent loop) ++bnum; if ( bnum >= (int) this->BlockInfo[otyp].size() ) return; binfop = &this->BlockInfo[otyp][bnum]; lastBlockEntry = binfop->FileOffset + binfop->Size - 1; loadNewBlk = 1; } if ( loadNewBlk ) { nconn = vtkIntArray::SafeDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, this->GetBlockConnTypeFromBlockType( otyp ), bnum, 0 ) ) ); if ( ! nconn ) { vtkErrorMacro( "Unable to read block \"" << binfop->Name.c_str() << "\" (" << binfop->Id << ")" ); break; } nodeconn = nconn->GetPointer( 0 ); nnpe = nconn->GetNumberOfComponents(); if ( stride > 1 || this->SqueezePoints ) { tmpTuple.resize( nnpe ); } } if ( stride > 1 && pref[1] < 0 ) { // negative orientation => reverse cell connectivity vtkIdType off = (pref[0] + 2 - binfop->FileOffset) * nnpe - 1; for ( int k = 0; k < nnpe; ++k ) tmpTuple[k] = nodeconn[off-k]; cellConn = &tmpTuple[0]; } else #ifndef VTK_USE_64BIT_IDS if ( this->SqueezePoints ) #endif // VTK_USE_64BIT_IDS { vtkIdType off = (pref[0] + 1 - binfop->FileOffset) * nnpe; for ( int k = 0; k < nnpe; ++k ) tmpTuple[k] = nodeconn[off+k]; cellConn = &tmpTuple[0]; } #ifndef VTK_USE_64BIT_IDS else { cellConn = (int*)nodeconn + (pref[0] + 1 - binfop->FileOffset) * nnpe; } #endif // VTK_USE_64BIT_IDS if ( this->SqueezePoints ) { // this loop is separated out to handle case (stride > 1 && pref[1] < 0 && this->SqueezePoints) for ( int k = 0; k < nnpe; ++k ) { vtkIdType* x = &this->PointMap[cellConn[k]]; if ( *x < 0 ) { *x = this->NextSqueezePoint++; } cellConn[k] = *x; } } output->InsertNextCell( binfop->CellType, nnpe, cellConn ); pref += stride; ++ref; } refs->UnRegister( this ); } void vtkExodusIIReaderPrivate::InsertSetSides( vtkIntArray* refs, int otyp, int obj, vtkUnstructuredGrid* output ) { static const int sideCellTypes[] = { VTK_EMPTY_CELL, // don't support any cells with 0 nodes per side VTK_VERTEX, VTK_LINE, VTK_TRIANGLE, VTK_QUAD, VTK_EMPTY_CELL, // don't support any cells with 5 nodes per side VTK_QUADRATIC_TRIANGLE, VTK_EMPTY_CELL, // don't support any cells with 7 nodes per side VTK_QUADRATIC_QUAD, VTK_BIQUADRATIC_QUAD }; int numSides = this->SetInfo[otyp][obj].Size; int* nodesPerSide = refs->GetPointer( 0 ); int* sideNodes = nodesPerSide + numSides; vtkstd::vector<vtkIdType> cellConn; cellConn.resize( 9 ); if ( this->SqueezePoints ) { int nnpe; for ( int side = 0; side < numSides; ++side ) { nnpe = nodesPerSide[side]; for ( int k = 0; k < nnpe; ++k ) { vtkIdType* x = &this->PointMap[sideNodes[k]]; if ( *x < 0 ) { *x = this->NextSqueezePoint++; } cellConn[k] = *x; } output->InsertNextCell( sideCellTypes[nnpe], nnpe, &cellConn[0] ); sideNodes += nnpe; } } else { int nnpe; for ( int side = 0; side < numSides; ++side ) { nnpe = nodesPerSide[side]; #ifdef VTK_USE_64BIT_IDS for ( int k = 0; k < nnpe; ++k ) { cellConn[k] = sideNodes[k]; } output->InsertNextCell( sideCellTypes[nnpe], nnpe, &cellConn[0] ); #else // VTK_USE_64BIT_IDS output->InsertNextCell( sideCellTypes[nnpe], nnpe, sideNodes ); #endif // VTK_USE_64BIT_IDS sideNodes += nnpe; } } } vtkDataArray* vtkExodusIIReaderPrivate::GetCacheOrRead( vtkExodusIICacheKey key ) { vtkDataArray* arr; // Never cache points deflected for a mode shape animation... doubles don't make good keys. if ( this->HasModeShapes && key.ObjectType == vtkExodusIIReader::NODAL_COORDS ) { arr = 0; } else { arr = this->Cache->Find( key ); } if ( arr ) { // return arr; } int exoid = this->Exoid; // If array is NULL, try reading it from file. if ( key.ObjectType == vtkExodusIIReader::GLOBAL ) { // need to assemble result array from smaller ones. // call GetCacheOrRead() for each smaller array // pay attention to SqueezePoints } else if ( key.ObjectType == vtkExodusIIReader::NODAL ) { // read nodal array ArrayInfoType* ainfop = &this->ArrayInfo[vtkExodusIIReader::NODAL][key.ArrayId]; arr = vtkDataArray::CreateDataArray( ainfop->StorageType ); arr->SetName( ainfop->Name.c_str() ); arr->SetNumberOfComponents( ainfop->Components ); arr->SetNumberOfTuples( this->ModelParameters.num_nodes ); if ( ainfop->Components == 1 ) { if ( ex_get_var( exoid, key.Time + 1, key.ObjectType, ainfop->OriginalIndices[0], 0, arr->GetNumberOfTuples(), arr->GetVoidPointer( 0 ) ) < 0 ) { vtkErrorMacro( "Could not read nodal result variable " << ainfop->Name.c_str() << "." ); arr->Delete(); arr = 0; } } else { // Exodus doesn't support reading with a stride, so we have to manually interleave the arrays. Bleh. vtkstd::vector<vtkstd::vector<double> > tmpVal; tmpVal.resize( ainfop->Components ); int c; for ( c = 0; c < ainfop->Components; ++c ) { vtkIdType N = this->ModelParameters.num_nodes; tmpVal[c].resize( N ); if ( ex_get_var( exoid, key.Time + 1, key.ObjectType, ainfop->OriginalIndices[c], 0, arr->GetNumberOfTuples(), &tmpVal[c][0] ) < 0) { vtkErrorMacro( "Could not read nodal result variable " << ainfop->OriginalNames[c].c_str() << "." ); arr->Delete(); arr = 0; return 0; } } int t; vtkstd::vector<double> tmpTuple; tmpTuple.resize( ainfop->Components ); for ( t = 0; t < arr->GetNumberOfTuples(); ++t ) { for ( c = 0; c < ainfop->Components; ++c ) { tmpTuple[c] = tmpVal[c][t]; } arr->SetTuple( t, &tmpTuple[0] ); } } } else if ( key.ObjectType == vtkExodusIIReader::EDGE_BLOCK || key.ObjectType == vtkExodusIIReader::FACE_BLOCK || key.ObjectType == vtkExodusIIReader::ELEM_BLOCK || key.ObjectType == vtkExodusIIReader::NODE_SET || key.ObjectType == vtkExodusIIReader::EDGE_SET || key.ObjectType == vtkExodusIIReader::FACE_SET || key.ObjectType == vtkExodusIIReader::SIDE_SET || key.ObjectType == vtkExodusIIReader::ELEM_SET ) { int otypidx = this->GetObjectTypeIndexFromObjectType( key.ObjectType ); ArrayInfoType* ainfop = &this->ArrayInfo[key.ObjectType][key.ArrayId]; ObjectInfoType* oinfop = this->GetObjectInfo( otypidx, key.ObjectId ); arr = vtkDataArray::CreateDataArray( ainfop->StorageType ); arr->SetName( ainfop->Name.c_str() ); arr->SetNumberOfComponents( ainfop->Components ); arr->SetNumberOfTuples( oinfop->Size ); if ( ainfop->Components == 1 ) { if ( ex_get_var( exoid, key.Time + 1, key.ObjectType, ainfop->OriginalIndices[0], oinfop->Id, arr->GetNumberOfTuples(), arr->GetVoidPointer( 0 ) ) < 0) { vtkErrorMacro( "Could not read result variable " << ainfop->Name.c_str() << " for " << objtype_names[otypidx] << " " << oinfop->Id << "." ); arr->Delete(); arr = 0; } } else { // Exodus doesn't support reading with a stride, so we have to manually interleave the arrays. Bleh. vtkstd::vector<vtkstd::vector<double> > tmpVal; tmpVal.resize( ainfop->Components ); int c; for ( c = 0; c < ainfop->Components; ++c ) { vtkIdType N = arr->GetNumberOfTuples(); tmpVal[c].resize( N ); if ( ex_get_var( exoid, key.Time + 1, key.ObjectType, ainfop->OriginalIndices[c], oinfop->Id, arr->GetNumberOfTuples(), &tmpVal[c][0] ) < 0) { vtkErrorMacro( "Could not read result variable " << ainfop->OriginalNames[c].c_str() << " for " << objtype_names[otypidx] << " " << oinfop->Id << "." ); arr->Delete(); arr = 0; } } int t; vtkstd::vector<double> tmpTuple; tmpTuple.resize( ainfop->Components ); for ( t = 0; t < arr->GetNumberOfTuples(); ++t ) { for ( c = 0; c < ainfop->Components; ++c ) { tmpTuple[c] = tmpVal[c][t]; } arr->SetTuple( t, &tmpTuple[0] ); } } } else if ( key.ObjectType == vtkExodusIIReader::NODE_MAP || key.ObjectType == vtkExodusIIReader::EDGE_MAP || key.ObjectType == vtkExodusIIReader::FACE_MAP || key.ObjectType == vtkExodusIIReader::ELEM_MAP ) { MapInfoType* minfop = &this->MapInfo[key.ObjectType][key.ArrayId]; vtkIdTypeArray* iarr = vtkIdTypeArray::New(); arr = iarr; arr->SetName( minfop->Name.c_str() ); arr->SetNumberOfComponents( 1 ); switch ( key.ObjectType ) { case vtkExodusIIReader::NODE_MAP: arr->SetNumberOfTuples( this->ModelParameters.num_nodes ); break; case vtkExodusIIReader::EDGE_MAP: arr->SetNumberOfTuples( this->ModelParameters.num_edge ); break; case vtkExodusIIReader::FACE_MAP: arr->SetNumberOfTuples( this->ModelParameters.num_face ); break; case vtkExodusIIReader::ELEM_MAP: arr->SetNumberOfTuples( this->ModelParameters.num_elem ); break; } #ifdef VTK_USE_64BIT_IDS { vtkstd::vector<int> tmpMap( arr->GetNumberOfTuples() ); if ( ex_get_num_map( exoid, key.ObjectType, minfop->Id, &tmpMap[0] ) < 0 ) { vtkErrorMacro( "Could not read map \"" << minfop->Name.c_str() << "\" (" << minfop->Id << ") from disk." ); arr->Delete(); arr = 0; return 0; } for ( vtkIdType i = 0; i < arr->GetNumberOfTuples(); ++i ) { iarr->SetValue( i, tmpMap[i] ); } } #else if ( ex_get_num_map( exoid, key.ObjectType, minfop->Id, (int*)arr->GetVoidPointer( 0 ) ) < 0 ) { vtkErrorMacro( "Could not read nodal map variable " << minfop->Name.c_str() << "." ); arr->Delete(); arr = 0; } #endif // VTK_USE_64BIT_IDS } else if ( key.ObjectType == vtkExodusIIReader::GLOBAL_ELEMENT_ID ) { // subset the ELEMENT_ID array choosing only entries for blocks that have Status ON vtkIdTypeArray* src = vtkIdTypeArray::SafeDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, vtkExodusIIReader::ELEMENT_ID, 0, 0 ) ) ); if ( ! src ) { arr = 0; return 0; } vtkIdTypeArray* iarr = vtkIdTypeArray::New(); iarr->SetName( vtkExodusIIReader::GetGlobalElementIdArrayName() ); iarr->SetNumberOfComponents( 1 ); iarr->SetNumberOfTuples( this->NumberOfCells ); vtkIdType* gloIds = iarr->GetPointer( 0 ); vtkIdType* srcIds = src->GetPointer( 0 ); memset( (void*)gloIds, 0, sizeof(vtkIdType) * this->NumberOfCells ); vtkstd::vector<BlockInfoType>::iterator bi; for ( bi = this->BlockInfo[vtkExodusIIReader::ELEM_BLOCK].begin(); bi != this->BlockInfo[vtkExodusIIReader::ELEM_BLOCK].end(); ++bi ) { if ( ! bi->Status ) continue; vtkIdType x; for ( x = 0; x < bi->Size; ++x ) { gloIds[x + bi->GridOffset] = srcIds[x + bi->FileOffset - 1]; } } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::GLOBAL_NODE_ID ) { // subset the NODE_ID array choosing only entries for nodes in output grid (using PointMap) vtkIdTypeArray* src = vtkIdTypeArray::SafeDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, vtkExodusIIReader::NODE_ID, 0, 0 ) ) ); if ( ! src ) { arr = 0; return 0; } vtkIdTypeArray* iarr = vtkIdTypeArray::New(); iarr->SetName( vtkExodusIIReader::GetGlobalNodeIdArrayName() ); iarr->SetNumberOfComponents( 1 ); iarr->SetNumberOfTuples( this->NextSqueezePoint ); vtkIdType* gloIds = iarr->GetPointer( 0 ); vtkIdType* srcIds = src->GetPointer( 0 ); vtkIdType pt; for ( pt = 0; pt < this->ModelParameters.num_nodes; ++pt ) { vtkIdType x = this->PointMap[pt]; if ( x >= 0 ) { gloIds[x] = srcIds[pt]; } } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::ELEMENT_ID || key.ObjectType == vtkExodusIIReader::NODE_ID ) { vtkIdTypeArray* iarr; int nMaps; vtkIdType mapSize; vtkExodusIICacheKey ktmp; vtkExodusIIGetMapFunc getMapFunc; if ( key.ObjectType == vtkExodusIIReader::ELEMENT_ID ) { nMaps = this->ModelParameters.num_elem_maps; mapSize = this->ModelParameters.num_elem; ktmp = vtkExodusIICacheKey( -1, vtkExodusIIReader::ELEM_MAP, 0, 0 ); getMapFunc = ex_get_elem_num_map; } else // ( key.ObjectType == vtkExodusIIReader::NODE_ID ) { nMaps = this->ModelParameters.num_node_maps; mapSize = this->ModelParameters.num_nodes; ktmp = vtkExodusIICacheKey( -1, vtkExodusIIReader::NODE_MAP, 0, 0 ); getMapFunc = ex_get_node_num_map; } // If there are no new-style maps, get the old-style map (which creates a default if nothing is stored on disk). if ( nMaps < 1 || ! (iarr = vtkIdTypeArray::SafeDownCast(this->GetCacheOrRead( ktmp ))) ) { iarr = vtkIdTypeArray::New(); iarr->SetNumberOfComponents( 1 ); iarr->SetNumberOfTuples( mapSize ); if ( mapSize ) { #ifdef VTK_USE_64BIT_IDS vtkstd::vector<int> tmpMap( iarr->GetNumberOfTuples() ); if ( getMapFunc( exoid, &tmpMap[0] ) < 0 ) { vtkErrorMacro( "Could not read old-style node or element map." ); iarr->Delete(); iarr = 0; } else { for ( vtkIdType i = 0; i < iarr->GetNumberOfTuples(); ++i ) { iarr->SetValue( i, tmpMap[i] ); } } #else if ( getMapFunc( exoid, (int*)iarr->GetPointer( 0 ) ) < 0 ) { vtkErrorMacro( "Could not read old-style node or element map." ); iarr->Delete(); iarr = 0; } #endif // VTK_USE_64BIT_IDS } } else { // FastDelete will be called below (because we are assumed to have created the array with New()). // So we must reference the array one extra time here to account for the extra delete... iarr->Register( this ); } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::GLOBAL_CONN ) { vtkErrorMacro( "Global connectivity is created in AssembleOutputConnectivity since it can't be cached\n" "with a single vtkDataArray. Who told you to call this routine to get it?" ); } else if ( key.ObjectType == vtkExodusIIReader::ELEM_BLOCK_ELEM_CONN || key.ObjectType == vtkExodusIIReader::FACE_BLOCK_CONN || key.ObjectType == vtkExodusIIReader::EDGE_BLOCK_CONN ) { int ctypidx = this->GetConnTypeIndexFromConnType( key.ObjectType ); int otypidx = conn_obj_idx_cvt[ctypidx]; int otyp = obj_types[ otypidx ]; BlockInfoType* binfop = (BlockInfoType*) this->GetObjectInfo( otypidx, key.ObjectId ); vtkIntArray* iarr = vtkIntArray::New(); iarr->SetNumberOfComponents( binfop->BdsPerEntry[0] ); iarr->SetNumberOfTuples( binfop->Size ); if ( ex_get_conn( exoid, otyp, binfop->Id, iarr->GetPointer(0), 0, 0 ) < 0 ) { vtkErrorMacro( "Unable to read " << objtype_names[otypidx] << " " << binfop->Id << " (index " << key.ObjectId << ") nodal connectivity." ); iarr->Delete(); iarr = 0; } vtkIdType c; int* ptr = iarr->GetPointer( 0 ); if ( binfop->CellType == VTK_QUADRATIC_HEXAHEDRON || binfop->CellType == VTK_TRIQUADRATIC_HEXAHEDRON ) { // Edge order for VTK is different than Exodus edge order. for ( c = 0; c < iarr->GetNumberOfTuples(); ++c ) { int k; int itmp[4]; for ( k = 0; k < 12; ++k, ++ptr) *ptr = *ptr - 1; for ( k = 0; k < 4; ++k, ++ptr) { itmp[k] = *ptr; *ptr = ptr[4] - 1; } for ( k = 0; k < 4; ++k, ++ptr ) *ptr = itmp[k] - 1; if ( binfop->CellType == VTK_TRIQUADRATIC_HEXAHEDRON ) { for ( k = 0; k < 4; ++k, ++ptr ) *ptr = *ptr - 1; } } ptr += binfop->BdsPerEntry[0] - binfop->PointsPerCell; } else { for ( c = 0; c <= iarr->GetMaxId(); ++c, ++ptr ) { *ptr = *ptr - 1; } } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::ELEM_BLOCK_FACE_CONN ) { // FIXME: Call ex_get_conn with non-NULL face conn pointer // This won't be needed until the Exodus reader outputs multiblock data with vtkGenericDataSet blocks for higher order meshes. arr = 0; } else if ( key.ObjectType == vtkExodusIIReader::ELEM_BLOCK_EDGE_CONN ) { // FIXME: Call ex_get_conn with non-NULL edge conn pointer // This won't be needed until the Exodus reader outputs multiblock data with vtkGenericDataSet blocks for higher order meshes. arr = 0; } else if ( key.ObjectType == vtkExodusIIReader::NODE_SET_CONN || key.ObjectType == vtkExodusIIReader::ELEM_SET_CONN ) { int otyp = this->GetSetTypeFromSetConnType( key.ObjectType ); int otypidx = this->GetObjectTypeIndexFromObjectType( otyp ); SetInfoType* sinfop = &this->SetInfo[otyp][key.ObjectId]; vtkIntArray* iarr = vtkIntArray::New(); iarr->SetNumberOfComponents( 1 ); iarr->SetNumberOfTuples( sinfop->Size ); int* iptr = iarr->GetPointer( 0 ); if ( ex_get_set( exoid, otyp, sinfop->Id, iptr, 0 ) < 0 ) { vtkErrorMacro( "Unable to read " << objtype_names[otypidx] << " " << sinfop->Id << " (index " << key.ObjectId << ") nodal connectivity." ); iarr->Delete(); iarr = 0; } vtkIdType id; for ( id = 0; id < sinfop->Size; ++id, ++iptr ) { // VTK uses 0-based indexing, unlike Exodus: --(*iptr); } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::EDGE_SET_CONN || key.ObjectType == vtkExodusIIReader::FACE_SET_CONN ) { int otyp = this->GetSetTypeFromSetConnType( key.ObjectType ); int otypidx = this->GetObjectTypeIndexFromObjectType( otyp ); SetInfoType* sinfop = &this->SetInfo[otyp][key.ObjectId]; vtkIntArray* iarr = vtkIntArray::New(); iarr->SetNumberOfComponents( 2 ); iarr->SetNumberOfTuples( sinfop->Size ); vtkstd::vector<int> tmpOrient; // hold the edge/face orientation information until we can interleave it. tmpOrient.resize( sinfop->Size ); if ( ex_get_set( exoid, otyp, sinfop->Id, iarr->GetPointer(0), &tmpOrient[0] ) < 0 ) { vtkErrorMacro( "Unable to read " << objtype_names[otypidx] << " " << sinfop->Id << " (index " << key.ObjectId << ") nodal connectivity." ); iarr->Delete(); iarr = 0; return 0; } int* iap = iarr->GetPointer( 0 ); vtkIdType c; for ( c = sinfop->Size - 1; c >= 0; --c ) { iap[2*c] = iap[c] - 1; // VTK uses 0-based indexing iap[2*c + 1] = tmpOrient[c]; } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::SIDE_SET_CONN ) { // Stick all of side_set_node_list and side_set_node_count and side_set_nodes_per_side in one array // let InsertSetSides() figure it all out. Except for 0-based indexing SetInfoType* sinfop = &this->SetInfo[vtkExodusIIReader::SIDE_SET][key.ObjectId]; int ssnllen; // side set node list length if ( ex_get_side_set_node_list_len( exoid, sinfop->Id, &ssnllen ) < 0 ) { vtkErrorMacro( "Unable to fetch side set \"" << sinfop->Name.c_str() << "\" (" << sinfop->Id << ") node list length" ); arr = 0; return 0; } vtkIntArray* iarr = vtkIntArray::New(); vtkIdType ilen = ssnllen + sinfop->Size; iarr->SetNumberOfComponents( 1 ); iarr->SetNumberOfTuples( ilen ); int* dat = iarr->GetPointer( 0 ); if ( ex_get_side_set_node_list( exoid, sinfop->Id, dat, dat + sinfop->Size ) < 0 ) { vtkErrorMacro( "Unable to fetch side set \"" << sinfop->Name.c_str() << "\" (" << sinfop->Id << ") node list" ); iarr->Delete(); arr = 0; return 0; } while ( ilen > sinfop->Size ) { // move to 0-based indexing on nodes, don't touch nodes/side counts at head of array --dat[--ilen]; } arr = iarr; } else if ( key.ObjectType == vtkExodusIIReader::NODAL_COORDS ) { // read node coords vtkDataArray* displ = 0; if ( this->ApplyDisplacements && key.Time >= 0 ) { displ = this->FindDisplacementVectors( key.Time ); } vtkstd::vector<double> coordTmp; vtkDoubleArray* darr = vtkDoubleArray::New(); arr = darr; arr->SetNumberOfComponents( 3 ); arr->SetNumberOfTuples( this->ModelParameters.num_nodes ); int dim = this->ModelParameters.num_dim; int c; vtkIdType t; double* xc = 0; double* yc = 0; double* zc = 0; coordTmp.resize( this->ModelParameters.num_nodes ); for ( c = 0; c < dim; ++c ) { switch ( c ) { case 0: xc = &coordTmp[0]; break; case 1: yc = xc; xc = 0; break; case 2: zc = yc; yc = 0; break; default: vtkErrorMacro( "Bad coordinate index " << c << " when reading point coordinates." ); xc = yc = zc = 0; } if ( ex_get_coord( exoid, xc, yc, zc ) < 0 ) { vtkErrorMacro( "Unable to read node coordinates for index " << c << "." ); arr->Delete(); arr = 0; break; } double* cptr = darr->GetPointer( c ); for ( t = 0; t < this->ModelParameters.num_nodes; ++t ) { *cptr = coordTmp[t]; cptr += 3; } } if ( dim < 3 ) { double* cptr = darr->GetPointer( 2 ); for ( t = 0; t < this->ModelParameters.num_nodes; ++t, cptr += 3 ) { *cptr = 0.; } } if ( displ ) { double* coords = darr->GetPointer( 0 ); if ( this->HasModeShapes ) { for ( vtkIdType idx = 0; idx < displ->GetNumberOfTuples(); ++idx ) { double* dispVal = displ->GetTuple3( idx ); for ( c = 0; c < 3; ++c ) coords[c] += dispVal[c] * this->DisplacementMagnitude * cos( 2. * vtkMath::DoublePi() * this->ModeShapeTime ); coords += 3; } } else { for ( vtkIdType idx = 0; idx < displ->GetNumberOfTuples(); ++idx ) { double* dispVal = displ->GetTuple3( idx ); for ( c = 0; c < 3; ++c ) coords[c] += dispVal[c] * this->DisplacementMagnitude; coords += 3; } } } } else if ( key.ObjectType == vtkExodusIIReader::GLOBAL_OBJECT_ID ) { arr = vtkIntArray::New(); arr->SetName( this->GetObjectIdArrayName() ); arr->SetNumberOfComponents( 1 ); arr->SetNumberOfTuples( this->NumberOfCells ); int conntypidx; for ( conntypidx = 0; conntypidx < num_conn_types; ++conntypidx ) { int otypidx = conn_obj_idx_cvt[conntypidx]; int obj; int numObj = this->GetNumberOfObjectsAtTypeIndex( otypidx ); BlockSetInfoType* bsinfop; for ( obj = 0; obj < numObj; ++obj ) { bsinfop = (BlockSetInfoType*) this->GetObjectInfo( otypidx, obj ); if ( ! bsinfop->Status ) continue; vtkIdType c; for ( c = 0; c < bsinfop->Size; ++c ) { arr->SetTuple1( c + bsinfop->GridOffset, bsinfop->Id ); } } } } else if ( key.ObjectType == vtkExodusIIReader::ELEM_BLOCK_ATTRIB || key.ObjectType == vtkExodusIIReader::FACE_BLOCK_ATTRIB || key.ObjectType == vtkExodusIIReader::EDGE_BLOCK_ATTRIB ) { BlockInfoType* binfop = &this->BlockInfo[key.ObjectType][key.ObjectId]; vtkDoubleArray* darr = vtkDoubleArray::New(); arr = darr; darr->SetName( binfop->AttributeNames[key.ArrayId].c_str() ); darr->SetNumberOfComponents( 1 ); darr->SetNumberOfTuples( binfop->Size ); if ( ex_get_one_attr( exoid, key.ObjectType, key.ObjectId, key.ArrayId, darr->GetVoidPointer( 0 ) ) < 0 ) { // NB: The error message references the file-order object id, not the numerically sorted index presented to users. vtkErrorMacro( "Unable to read attribute " << key.ArrayId << " for object " << key.ObjectId << " of type " << key.ObjectType << "." ); arr->Delete(); arr = 0; } } else { vtkWarningMacro( "You requested an array for objects of type " << key.ObjectType << " which I know nothing about" ); arr = 0; } // Even if the array is larger than the allowable cache size, it will keep the most recent insertion. // So, we delete our reference knowing that the Cache will keep the object "alive" until whatever // called GetCacheOrRead() references the array. But, once you get an array from GetCacheOrRead(), // you better start running! if ( arr ) { this->Cache->Insert( key, arr ); arr->FastDelete(); } return arr; } int vtkExodusIIReaderPrivate::GetConnTypeIndexFromConnType( int ctyp ) { int i; for ( i = 0; i < num_conn_types; ++i ) { if ( conn_types[i] == ctyp ) { return i; } } return -1; } int vtkExodusIIReaderPrivate::GetObjectTypeIndexFromObjectType( int otyp ) { int i; for ( i = 0; i < num_obj_types; ++i ) { if ( obj_types[i] == otyp ) { return i; } } return -1; } int vtkExodusIIReaderPrivate::GetNumberOfObjectsAtTypeIndex( int typeIndex ) { if ( typeIndex < 0 ) { return 0; } else if ( typeIndex < 3 ) { return (int) this->BlockInfo[obj_types[typeIndex]].size(); } else if ( typeIndex < 8 ) { return (int) this->SetInfo[obj_types[typeIndex]].size(); } else if ( typeIndex < 12 ) { return (int) this->MapInfo[obj_types[typeIndex]].size(); } return 0; } vtkExodusIIReaderPrivate::ObjectInfoType* vtkExodusIIReaderPrivate::GetObjectInfo( int typeIndex, int objectIndex ) { if ( typeIndex < 0 ) { return 0; } else if ( typeIndex < 3 ) { return &this->BlockInfo[obj_types[typeIndex]][objectIndex]; } else if ( typeIndex < 8 ) { return &this->SetInfo[obj_types[typeIndex]][objectIndex]; } else if ( typeIndex < 12 ) { return &this->MapInfo[obj_types[typeIndex]][objectIndex]; } return 0; } vtkExodusIIReaderPrivate::ObjectInfoType* vtkExodusIIReaderPrivate::GetSortedObjectInfo( int otyp, int k ) { int i = this->GetObjectTypeIndexFromObjectType( otyp ); if ( i < 0 ) { vtkWarningMacro( "Could not find collection of objects with type " << otyp << "." ); return 0; } int N = this->GetNumberOfObjectsAtTypeIndex( i ); if ( k < 0 || k >= N ) { const char* otname = i >= 0 ? objtype_names[i] : "object"; vtkWarningMacro( "You requested " << otname << " " << k << " in a collection of only " << N << " objects." ); return 0; } return this->GetObjectInfo( i, this->SortedObjectIndices[otyp][k] ); } vtkExodusIIReaderPrivate::ObjectInfoType* vtkExodusIIReaderPrivate::GetUnsortedObjectInfo( int otyp, int k ) { int i = this->GetObjectTypeIndexFromObjectType( otyp ); if ( i < 0 ) { vtkWarningMacro( "Could not find collection of objects with type " << otyp << "." ); return 0; } int N = this->GetNumberOfObjectsAtTypeIndex( i ); if ( k < 0 || k >= N ) { const char* otname = i >= 0 ? objtype_names[i] : "object"; vtkWarningMacro( "You requested " << otname << " " << k << " in a collection of only " << N << " objects." ); return 0; } return this->GetObjectInfo( i, k ); } int vtkExodusIIReaderPrivate::GetBlockIndexFromFileGlobalId( int otyp, int refId ) { vtkstd::vector<BlockInfoType>::iterator bi; int i = 0; for ( bi = this->BlockInfo[otyp].begin(); bi != this->BlockInfo[otyp].end(); ++bi, ++i ) { if ( refId >= bi->FileOffset && refId <= bi->FileOffset + bi->Size ) return i; } return -1; } vtkExodusIIReaderPrivate::BlockInfoType* vtkExodusIIReaderPrivate::GetBlockFromFileGlobalId( int otyp, int refId ) { int blk = this->GetBlockIndexFromFileGlobalId( otyp, refId ); if ( blk >= 0 ) { return &this->BlockInfo[otyp][blk]; } return 0; } vtkIdType vtkExodusIIReaderPrivate::GetSqueezePointId( int i ) { vtkIdType* x = &this->PointMap[i]; if ( *x < 0 ) { *x = this->NextSqueezePoint++; } return *x; } void vtkExodusIIReaderPrivate::DetermineVtkCellType( BlockInfoType& binfo ) { vtkStdString elemType( vtksys::SystemTools::UpperCase( binfo.TypeName ) ); // Check for quadratic elements if ((elemType.substr(0,3) == "TRI") && (binfo.BdsPerEntry[0] == 6)) { binfo.CellType=VTK_QUADRATIC_TRIANGLE; binfo.PointsPerCell = 6; } else if ((elemType.substr(0,3) == "SHE") && (binfo.BdsPerEntry[0] == 8)) { binfo.CellType=VTK_QUADRATIC_QUAD; binfo.PointsPerCell = 8; } else if ((elemType.substr(0,3) == "SHE") && (binfo.BdsPerEntry[0] == 9)) { binfo.CellType=VTK_QUADRATIC_QUAD; binfo.PointsPerCell = 8; } else if ((elemType.substr(0,3) == "TET") && (binfo.BdsPerEntry[0] == 10)) { binfo.CellType=VTK_QUADRATIC_TETRA; binfo.PointsPerCell = 10; } else if ((elemType.substr(0,3) == "TET") && (binfo.BdsPerEntry[0] == 11)) { binfo.CellType=VTK_QUADRATIC_TETRA; binfo.PointsPerCell = 10; } else if ((elemType.substr(0,3) == "HEX") && (binfo.BdsPerEntry[0] == 20)) { binfo.CellType=VTK_QUADRATIC_HEXAHEDRON; binfo.PointsPerCell = 20; } else if ((elemType.substr(0,3) == "HEX") && (binfo.BdsPerEntry[0] == 21)) { binfo.CellType=VTK_QUADRATIC_HEXAHEDRON; binfo.PointsPerCell = 20; } else if ((elemType.substr(0,3) == "HEX") && (binfo.BdsPerEntry[0] == 27)) { binfo.CellType=VTK_TRIQUADRATIC_HEXAHEDRON; binfo.PointsPerCell = 27; } else if ((elemType.substr(0,3) == "QUA") && (binfo.BdsPerEntry[0] == 8)) { binfo.CellType=VTK_QUADRATIC_QUAD; binfo.PointsPerCell = 8; } else if ((elemType.substr(0,3) == "QUA") && (binfo.BdsPerEntry[0] == 9)) { binfo.CellType=VTK_BIQUADRATIC_QUAD; binfo.PointsPerCell = 9; } else if ((elemType.substr(0,3) == "TRU") && (binfo.BdsPerEntry[0] == 3)) { binfo.CellType=VTK_QUADRATIC_EDGE; binfo.PointsPerCell = 3; } else if ((elemType.substr(0,3) == "BEA") && (binfo.BdsPerEntry[0] == 3)) { binfo.CellType=VTK_QUADRATIC_EDGE; binfo.PointsPerCell = 3; } else if ((elemType.substr(0,3) == "BAR") && (binfo.BdsPerEntry[0] == 3)) { binfo.CellType=VTK_QUADRATIC_EDGE; binfo.PointsPerCell = 3; } else if ((elemType.substr(0,3) == "EDG") && (binfo.BdsPerEntry[0] == 3)) { binfo.CellType=VTK_QUADRATIC_EDGE; binfo.PointsPerCell = 3; } // Check for regular elements else if ((elemType.substr(0,3) == "CIR")) { binfo.CellType = VTK_VERTEX; binfo.PointsPerCell = 1; } else if ((elemType.substr(0,3) == "SPH")) { binfo.CellType = VTK_VERTEX; binfo.PointsPerCell = 1; } else if ((elemType.substr(0,3) == "BAR")) { binfo.CellType = VTK_LINE; binfo.PointsPerCell = 2; } else if ((elemType.substr(0,3) == "TRU")) { binfo.CellType = VTK_LINE; binfo.PointsPerCell = 2; } else if ((elemType.substr(0,3) == "BEA")) { binfo.CellType = VTK_LINE; binfo.PointsPerCell = 2; } else if ((elemType.substr(0,3) == "EDG")) { binfo.CellType = VTK_LINE; binfo.PointsPerCell = 2; } else if ((elemType.substr(0,3) == "TRI")) { binfo.CellType = VTK_TRIANGLE; binfo.PointsPerCell = 3; } else if ((elemType.substr(0,3) == "QUA")) { binfo.CellType = VTK_QUAD; binfo.PointsPerCell = 4; } else if ((elemType.substr(0,3) == "TET")) { binfo.CellType = VTK_TETRA; binfo.PointsPerCell = 4; } else if ((elemType.substr(0,3) == "PYR")) { binfo.CellType = VTK_PYRAMID; binfo.PointsPerCell = 5; } else if ((elemType.substr(0,3) == "WED")) { binfo.CellType = VTK_WEDGE; binfo.PointsPerCell = 6; } else if ((elemType.substr(0,3) == "HEX")) { binfo.CellType = VTK_HEXAHEDRON; binfo.PointsPerCell = 8; } else if ((elemType.substr(0,3) == "SHE") && (binfo.BdsPerEntry[0] == 3)) { binfo.CellType = VTK_TRIANGLE; binfo.PointsPerCell = 3; } else if ((elemType.substr(0,3) == "SHE") && (binfo.BdsPerEntry[0] == 4)) { binfo.CellType = VTK_QUAD; binfo.PointsPerCell = 4; } else if ((elemType.substr(0,8) == "STRAIGHT") && (binfo.BdsPerEntry[0] == 2 )) { binfo.CellType = VTK_LINE; binfo.PointsPerCell = 2; } else if ((elemType.substr(0,8) == "NULL") && (binfo.Size == 0)) { (void)binfo; // silently ignore empty element blocks } else { vtkErrorMacro("Unsupported element type: " << elemType.c_str()); } //cell types not currently handled //quadratic wedge - 15,16 nodes //quadratic pyramid - 13 nodes } vtkExodusIIReaderPrivate::ArrayInfoType* vtkExodusIIReaderPrivate::FindArrayInfoByName( int otyp, const char* name ) { vtkstd::vector<ArrayInfoType>::iterator ai; for ( ai = this->ArrayInfo[otyp].begin(); ai != this->ArrayInfo[otyp].end(); ++ai ) { if ( ai->Name == name ) return &(*ai); } return 0; } int vtkExodusIIReaderPrivate::IsObjectTypeBlock( int otyp ) { return (otyp == vtkExodusIIReader::ELEM_BLOCK || otyp == vtkExodusIIReader::EDGE_BLOCK || otyp == vtkExodusIIReader::FACE_BLOCK); } int vtkExodusIIReaderPrivate::IsObjectTypeSet( int otyp ) { return (otyp == vtkExodusIIReader::ELEM_SET || otyp == vtkExodusIIReader::EDGE_SET || otyp == vtkExodusIIReader::FACE_SET || otyp == vtkExodusIIReader::NODE_SET || otyp == vtkExodusIIReader::SIDE_SET); } int vtkExodusIIReaderPrivate::IsObjectTypeMap( int otyp ) { return (otyp == vtkExodusIIReader::ELEM_MAP || otyp == vtkExodusIIReader::EDGE_MAP || otyp == vtkExodusIIReader::FACE_MAP || otyp == vtkExodusIIReader::NODE_MAP); } int vtkExodusIIReaderPrivate::GetObjectTypeFromMapType( int mtyp ) { switch (mtyp) { case vtkExodusIIReader::ELEM_MAP: return vtkExodusIIReader::ELEM_BLOCK; case vtkExodusIIReader::FACE_MAP: return vtkExodusIIReader::FACE_BLOCK; case vtkExodusIIReader::EDGE_MAP: return vtkExodusIIReader::EDGE_BLOCK; case vtkExodusIIReader::NODE_MAP: return vtkExodusIIReader::NODAL; } return -1; } int vtkExodusIIReaderPrivate::GetMapTypeFromObjectType( int otyp ) { switch (otyp) { case vtkExodusIIReader::ELEM_BLOCK: return vtkExodusIIReader::ELEM_MAP; case vtkExodusIIReader::FACE_BLOCK: return vtkExodusIIReader::FACE_MAP; case vtkExodusIIReader::EDGE_BLOCK: return vtkExodusIIReader::EDGE_MAP; case vtkExodusIIReader::NODAL: return vtkExodusIIReader::NODE_MAP; } return -1; } int vtkExodusIIReaderPrivate::GetSetTypeFromSetConnType( int sctyp ) { switch ( sctyp ) { case vtkExodusIIReader::NODE_SET_CONN: return vtkExodusIIReader::NODE_SET; case vtkExodusIIReader::EDGE_SET_CONN: return vtkExodusIIReader::EDGE_SET; case vtkExodusIIReader::FACE_SET_CONN: return vtkExodusIIReader::FACE_SET; case vtkExodusIIReader::SIDE_SET_CONN: return vtkExodusIIReader::SIDE_SET; case vtkExodusIIReader::ELEM_SET_CONN: return vtkExodusIIReader::ELEM_SET; } return -1; } int vtkExodusIIReaderPrivate::GetBlockConnTypeFromBlockType( int btyp ) { switch ( btyp ) { case vtkExodusIIReader::EDGE_BLOCK: return vtkExodusIIReader::EDGE_BLOCK_CONN; case vtkExodusIIReader::FACE_BLOCK: return vtkExodusIIReader::FACE_BLOCK_CONN; case vtkExodusIIReader::ELEM_BLOCK: return vtkExodusIIReader::ELEM_BLOCK_ELEM_CONN; } return -1; } void vtkExodusIIReaderPrivate::RemoveBeginningAndTrailingSpaces( int len, char **names ) { int i, j; for (i=0; i<len; i++) { char *c = names[i]; int nmlen = (int)strlen(c); char *cbegin = c; char *cend = c + nmlen - 1; // remove spaces or non-printing character from start and end for (j=0; j<nmlen; j++) { if (!isgraph(*cbegin)) cbegin++; else break; } for (j=0; j<nmlen; j++) { if (!isgraph(*cend)) cend--; else break; } if (cend < cbegin) { sprintf(names[i], "null_%d", i); continue; } int newlen = cend - cbegin + 1; if (newlen < nmlen) { for (j=0; j<newlen; j++) { *c++ = *cbegin++; } *c = '\0'; } } } int vtkExodusIIReaderPrivate::GetNumberOfParts() { return this->PartInfo.size(); } const char* vtkExodusIIReaderPrivate::GetPartName(int idx) { return this->PartInfo[idx].Name.c_str(); } const char* vtkExodusIIReaderPrivate::GetPartBlockInfo(int idx) { char buffer[80]; vtkStdString blocks; vtkstd::vector<int> blkIndices = this->PartInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { sprintf(buffer,"%d, ",blkIndices[i]); blocks += buffer; } blocks.erase(blocks.size()-2,blocks.size()-1); return blocks.c_str(); } int vtkExodusIIReaderPrivate::GetPartStatus(int idx) { //a part is only active if all its blocks are active vtkstd::vector<int> blkIndices = this->PartInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { if (!this->GetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK,blkIndices[i])) { return 0; } } return 1; } int vtkExodusIIReaderPrivate::GetPartStatus(vtkStdString name) { for (unsigned int i=0;i<this->PartInfo.size();i++) { if (this->PartInfo[i].Name==name) { return this->GetPartStatus(i); } } return -1; } void vtkExodusIIReaderPrivate::SetPartStatus(int idx, int on) { //update the block status for all the blocks in this part vtkstd::vector<int> blkIndices = this->PartInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { this->SetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK, blkIndices[i], on); } } void vtkExodusIIReaderPrivate::SetPartStatus(vtkStdString name, int flag) { for(unsigned int idx=0; idx<this->PartInfo.size(); ++idx) { if ( name == this->PartInfo[idx].Name ) { this->SetPartStatus(idx,flag); return; } } } int vtkExodusIIReaderPrivate::GetNumberOfMaterials() { return this->MaterialInfo.size(); } const char* vtkExodusIIReaderPrivate::GetMaterialName(int idx) { return this->MaterialInfo[idx].Name.c_str(); } int vtkExodusIIReaderPrivate::GetMaterialStatus(int idx) { vtkstd::vector<int> blkIndices = this->MaterialInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { if (!this->GetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK,blkIndices[i])) { return 0; } } return 1; } int vtkExodusIIReaderPrivate::GetMaterialStatus(vtkStdString name) { for (unsigned int i=0;i<this->MaterialInfo.size();i++) { if (this->MaterialInfo[i].Name==name) { return this->GetMaterialStatus(i); } } return -1; } void vtkExodusIIReaderPrivate::SetMaterialStatus(int idx, int on) { //update the block status for all the blocks in this material vtkstd::vector<int> blkIndices = this->MaterialInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { this->SetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK,blkIndices[i],on); } } void vtkExodusIIReaderPrivate::SetMaterialStatus(vtkStdString name, int flag) { for(unsigned int idx=0; idx<this->MaterialInfo.size(); ++idx) { if ( name == this->MaterialInfo[idx].Name ) { this->SetMaterialStatus(idx,flag); return; } } } int vtkExodusIIReaderPrivate::GetNumberOfAssemblies() { return this->AssemblyInfo.size(); } const char* vtkExodusIIReaderPrivate::GetAssemblyName(int idx) { return this->AssemblyInfo[idx].Name.c_str(); } int vtkExodusIIReaderPrivate::GetAssemblyStatus(int idx) { vtkstd::vector<int> blkIndices = this->AssemblyInfo[idx].BlockIndices; for (unsigned int i=0;i<blkIndices.size();i++) { if (!this->GetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK,blkIndices[i])) { return 0; } } return 1; } int vtkExodusIIReaderPrivate::GetAssemblyStatus(vtkStdString name) { for (unsigned int i=0;i<this->AssemblyInfo.size();i++) { if (this->AssemblyInfo[i].Name==name) { return this->GetAssemblyStatus(i); } } return -1; } void vtkExodusIIReaderPrivate::SetAssemblyStatus(int idx, int on) { vtkstd::vector<int> blkIndices = this->AssemblyInfo[idx].BlockIndices; //update the block status for all the blocks in this material for (unsigned int i=0;i<blkIndices.size();i++) { this->SetUnsortedObjectStatus(vtkExodusIIReader::ELEM_BLOCK,blkIndices[i],on); } } void vtkExodusIIReaderPrivate::SetAssemblyStatus(vtkStdString name, int flag) { for(unsigned int idx=0; idx<this->AssemblyInfo.size(); ++idx) { if ( name == this->AssemblyInfo[idx].Name ) { this->SetAssemblyStatus(idx,flag); return; } } } // Normally, this would be below with all the other vtkExodusIIReader member definitions, // but the Tcl PrintSelf test script is really lame. void vtkExodusIIReader::PrintSelf( ostream& os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); os << indent << "FileName: " << ( this->FileName ? this->FileName : "(null)" ) << "\n"; os << indent << "XMLFileName: " << ( this->XMLFileName ? this->XMLFileName : "(null)" ) << "\n"; os << indent << "DisplayType: " << this->DisplayType << "\n"; os << indent << "TimeStep: " << this->TimeStep << "\n"; os << indent << "TimeStepRange: [" << this->TimeStepRange[0] << ", " << this->TimeStepRange[1] << "]\n"; os << indent << "ExodusModelMetadata: " << (this->ExodusModelMetadata ? "ON" : "OFF" ) << "\n"; os << indent << "PackExodusModelOntoOutput: " << (this->PackExodusModelOntoOutput ? "ON" : "OFF" ) << "\n"; os << indent << "ExodusModel: " << this->ExodusModel << "\n"; if ( this->Metadata ) { os << indent << "Metadata:\n"; this->Metadata->PrintData( os, indent.GetNextIndent() ); } else { os << indent << "Metadata: (null)\n"; } } void vtkExodusIIReaderPrivate::PrintData( ostream& os, vtkIndent indent ) { //this->Superclass::Print Self( os, indent ); os << indent << "Exoid: " << this->Exoid << "\n"; os << indent << "AppWordSize: " << this->AppWordSize << "\n"; os << indent << "DiskWordSize: " << this->DiskWordSize << "\n"; os << indent << "ExodusVersion: " << this->ExodusVersion << "\n"; os << indent << "ModelParameters:\n"; vtkIndent inden2 = indent.GetNextIndent(); os << inden2 << "Title: " << this->ModelParameters.title << "\n"; os << inden2 << "Dimension: " << this->ModelParameters.num_dim << "\n"; os << inden2 << "Nodes: " << this->ModelParameters.num_nodes << "\n"; os << inden2 << "Edges: " << this->ModelParameters.num_edge << "\n"; os << inden2 << "Faces: " << this->ModelParameters.num_face << "\n"; os << inden2 << "Elements: " << this->ModelParameters.num_elem << "\n"; os << inden2 << "Edge Blocks: " << this->ModelParameters.num_edge_blk << "\n"; os << inden2 << "Face Blocks: " << this->ModelParameters.num_face_blk << "\n"; os << inden2 << "Element Blocks: " << this->ModelParameters.num_elem_blk << "\n"; os << inden2 << "Node Sets: " << this->ModelParameters.num_node_sets << "\n"; os << inden2 << "Edge Sets: " << this->ModelParameters.num_edge_sets << "\n"; os << inden2 << "Face Sets: " << this->ModelParameters.num_face_sets << "\n"; os << inden2 << "Side Sets: " << this->ModelParameters.num_side_sets << "\n"; os << inden2 << "Element Sets: " << this->ModelParameters.num_elem_sets << "\n"; os << inden2 << "Node Maps: " << this->ModelParameters.num_node_maps << "\n"; os << inden2 << "Edge Maps: " << this->ModelParameters.num_edge_maps << "\n"; os << inden2 << "Face Maps: " << this->ModelParameters.num_face_maps << "\n"; os << inden2 << "Element Maps: " << this->ModelParameters.num_elem_maps << "\n"; os << indent << "Time steps (" << this->Times.size() << "):"; int i; for ( i = 0; i < (int)this->Times.size(); ++i ) { os << " " << this->Times[i]; } os << "\n"; os << indent << "TimeStep: " << this->TimeStep << "\n"; os << indent << "HasModeShapes: " << this->HasModeShapes << "\n"; os << indent << "ModeShapeTime: " << this->ModeShapeTime << "\n"; // Print nodal variables if ( this->ArrayInfo[ vtkExodusIIReader::NODAL ].size() > 0 ) { os << indent << "Nodal Arrays:\n"; vtkstd::vector<ArrayInfoType>::iterator ai; for ( ai = this->ArrayInfo[ vtkExodusIIReader::NODAL ].begin(); ai != this->ArrayInfo[ vtkExodusIIReader::NODAL ].end(); ++ai ) { printArray( os, indent, vtkExodusIIReader::NODAL, *ai ); } } // Print blocks os << indent << "Blocks:\n"; vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator bti; for ( bti = this->BlockInfo.begin(); bti != this->BlockInfo.end(); ++bti ) { vtkstd::vector<BlockInfoType>::iterator bi; for ( bi = bti->second.begin(); bi != bti->second.end(); ++bi ) { printBlock( os, indent.GetNextIndent(), bti->first, *bi ); } if ( this->ArrayInfo[ bti->first ].size() > 0 ) { os << indent << " Results variables:\n"; vtkstd::vector<ArrayInfoType>::iterator ai; for ( ai = this->ArrayInfo[ bti->first ].begin(); ai != this->ArrayInfo[ bti->first ].end(); ++ai ) { printArray( os, indent.GetNextIndent(), bti->first, *ai ); } } } // Print sets os << indent << "Sets:\n"; vtkstd::map<int,vtkstd::vector<SetInfoType> >::iterator sti; for ( sti = this->SetInfo.begin(); sti != this->SetInfo.end(); ++sti ) { vtkstd::vector<SetInfoType>::iterator si; for ( si = sti->second.begin(); si != sti->second.end(); ++si ) { printSet( os, indent.GetNextIndent(), sti->first, *si ); } if ( this->ArrayInfo[ sti->first ].size() > 0 ) { os << indent << " Results variables:\n"; vtkstd::vector<ArrayInfoType>::iterator ai; for ( ai = this->ArrayInfo[ sti->first ].begin(); ai != this->ArrayInfo[ sti->first ].end(); ++ai ) { printArray( os, indent.GetNextIndent(), sti->first, *ai ); } } } // Print maps os << indent << "Maps:\n"; vtkstd::map<int,vtkstd::vector<MapInfoType> >::iterator mti; for ( mti = this->MapInfo.begin(); mti != this->MapInfo.end(); ++mti ) { vtkstd::vector<MapInfoType>::iterator mi; for ( mi = mti->second.begin(); mi != mti->second.end(); ++mi ) { printMap( os, indent.GetNextIndent(), mti->first, *mi ); } } os << indent << "Array Cache:\n"; this->Cache->PrintSelf( os, inden2 ); os << indent << "Number of output cells: " << this->NumberOfCells << "\n"; os << indent << "SqueezePoints: " << this->SqueezePoints << "\n"; os << indent << "NextSqueezePoint: " << this->NextSqueezePoint << "\n"; os << indent << "ApplyDisplacements: " << this->ApplyDisplacements << "\n"; os << indent << "DisplacementMagnitude: " << this->DisplacementMagnitude << "\n"; os << indent << "GenerateObjectIdArray: " << this->GenerateObjectIdArray << "\n"; } int vtkExodusIIReaderPrivate::OpenFile( const char* filename ) { if ( ! filename || ! strlen( filename ) ) { vtkErrorMacro( "Exodus filename pointer was NULL or pointed to an empty string." ); return 0; } if ( this->Exoid >= 0 ) { this->CloseFile(); } this->Exoid = ex_open( filename, EX_READ, &this->AppWordSize, &this->DiskWordSize, &this->ExodusVersion ); if ( this->Exoid <= 0 ) { vtkErrorMacro( "Unable to open \"" << filename << "\" for reading" ); return 0; } return 1; } int vtkExodusIIReaderPrivate::CloseFile() { if ( this->Exoid >= 0 ) { VTK_EXO_FUNC( ex_close( this->Exoid ), "Could not close an open file (" << this->Exoid << ")" ); this->Exoid = -1; } return 0; } int vtkExodusIIReaderPrivate::RequestInformation() { int exoid = this->Exoid; int itmp[5]; int* ids; int nids; int obj; int i, j; int num_timesteps; char** obj_names; char** obj_typenames = 0; char** var_names = 0; int have_var_names; int num_vars = 0; /* number of variables per object */ //int num_entries; /* number of values per variable per object */ char tmpName[256]; tmpName[255] = '\0'; this->InformationTimeStamp.Modified(); // Update MTime so that it will be newer than parent's FileNameMTime VTK_EXO_FUNC( ex_get_init_ext( exoid, &this->ModelParameters ), "Unable to read database parameters." ); VTK_EXO_FUNC( ex_inquire( exoid, EX_INQ_TIME, itmp, 0, 0 ), "Inquire for EX_INQ_TIME failed" ); num_timesteps = itmp[0]; vtkstd::vector<BlockInfoType> bitBlank; vtkstd::vector<SetInfoType> sitBlank; vtkstd::vector<MapInfoType> mitBlank; vtkstd::vector<ArrayInfoType> aitBlank; this->Times.clear(); if ( num_timesteps > 0 ) { this->Times.reserve( num_timesteps ); this->Times.resize( num_timesteps ); VTK_EXO_FUNC( ex_get_all_times( this->Exoid, &this->Times[0] ), "Could not retrieve time values." ); } this->NumberOfCells = 0; for ( i = 0; i < num_obj_types; ++i ) { vtkIdType blockEntryFileOffset = 1; vtkIdType setEntryFileOffset = 1; vtkIdType blockEntryGridOffset = 0; vtkIdType setEntryGridOffset = 0; vtkstd::map<int,int> sortedObjects; int* truth_tab = 0; have_var_names = 0; VTK_EXO_FUNC( ex_inquire( exoid, obj_sizes[i], &nids, 0, 0 ), "Object ID list size could not be determined." ); if ( nids ) { ids = (int*) malloc( nids * sizeof(int) ); obj_names = (char**) malloc( nids * sizeof(char*) ); for ( obj = 0; obj < nids; ++obj ) obj_names[obj] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); if ( OBJTYPE_IS_BLOCK(i) ) { obj_typenames = (char**) malloc( nids * sizeof(char*) ); for ( obj = 0; obj < nids; ++obj ) { obj_typenames[obj] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); obj_typenames[obj][0] = '\0'; } } } else { ids = 0; obj_names = 0; obj_typenames = 0; } if ( nids == 0 && ! OBJTYPE_IS_MAP(i) ) continue; if ( nids ) { VTK_EXO_FUNC( ex_get_ids( exoid, obj_types[i], ids ), "Could not read object ids." ); VTK_EXO_FUNC( ex_get_names( exoid, obj_types[i], obj_names ), "Could not read object names." ); } BlockInfoType binfo; SetInfoType sinfo; MapInfoType minfo; if ( OBJTYPE_IS_BLOCK(i) ) { this->BlockInfo[obj_types[i]] = bitBlank; this->BlockInfo[obj_types[i]].reserve( nids ); } else if ( OBJTYPE_IS_SET(i) ) { this->SetInfo[obj_types[i]] = sitBlank; this->SetInfo[obj_types[i]].reserve( nids ); } else { this->MapInfo[obj_types[i]] = mitBlank; this->MapInfo[obj_types[i]].reserve( nids ); } if ( (OBJTYPE_IS_BLOCK(i)) || (OBJTYPE_IS_SET(i)) ) { VTK_EXO_FUNC( ex_get_var_param( exoid, obj_typestr[i], &num_vars ), "Could not read number of variables." ); if ( num_vars && num_timesteps > 0 ) { truth_tab = (int*) malloc( num_vars * nids * sizeof(int) ); VTK_EXO_FUNC( ex_get_var_tab( exoid, obj_typestr[i], nids, num_vars, truth_tab ), "Could not read truth table." ); var_names = (char**) malloc( num_vars * sizeof(char*) ); for ( j = 0; j < num_vars; ++j ) var_names[j] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); VTK_EXO_FUNC( ex_get_var_names( exoid, obj_typestr[i], num_vars, var_names ), "Could not read variable names." ); this->RemoveBeginningAndTrailingSpaces( num_vars, var_names ); have_var_names = 1; } } if ( ! have_var_names ) var_names = 0; for ( obj = 0; obj < nids; ++obj ) { if ( OBJTYPE_IS_BLOCK(i) ) { binfo.Name = obj_names[obj]; binfo.Id = ids[obj]; if ( obj_types[i] == vtkExodusIIReader::ELEM_BLOCK ) { VTK_EXO_FUNC( ex_get_block( exoid, obj_types[i], ids[obj], obj_typenames[obj], &binfo.Size, &binfo.BdsPerEntry[0], &binfo.BdsPerEntry[1], &binfo.BdsPerEntry[2], &binfo.AttributesPerEntry ), "Could not read block params." ); binfo.Status = 1; // load element blocks by default binfo.TypeName = obj_typenames[obj]; } else { VTK_EXO_FUNC( ex_get_block( exoid, obj_types[i], ids[obj], obj_typenames[obj], &binfo.Size, &binfo.BdsPerEntry[0], &binfo.BdsPerEntry[1], &binfo.BdsPerEntry[2], &binfo.AttributesPerEntry ), "Could not read block params." ); binfo.Status = 0; // don't load edge/face blocks by default binfo.TypeName = obj_typenames[obj]; binfo.BdsPerEntry[1] = binfo.BdsPerEntry[2] = 0; } //num_entries = binfo.Size; binfo.FileOffset = blockEntryFileOffset; blockEntryFileOffset += binfo.Size; if ( binfo.Status ) { binfo.GridOffset = blockEntryGridOffset; blockEntryGridOffset += binfo.Size; this->NumberOfCells += binfo.Size; } else { binfo.GridOffset = -1; } if ( binfo.Name.length() == 0 ) { SNPRINTF( tmpName, 255, "Unnamed block ID: %d Type: %s Size: %d", ids[obj], binfo.TypeName.length() ? binfo.TypeName.c_str() : "NULL", binfo.Size ); binfo.Name = tmpName; } this->DetermineVtkCellType( binfo ); if ( binfo.AttributesPerEntry ) { char** attr_names; attr_names = (char**) malloc( binfo.AttributesPerEntry * sizeof(char*) ); for ( j = 0; j < binfo.AttributesPerEntry; ++j ) attr_names[j] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); VTK_EXO_FUNC( ex_get_attr_names( exoid, obj_types[i], ids[obj], attr_names ), "Could not read attributes names." ); for ( j = 0; j < binfo.AttributesPerEntry; ++j ) { binfo.AttributeNames.push_back( attr_names[j] ); binfo.AttributeStatus.push_back( 0 ); // don't load attributes by default } for ( j = 0; j < binfo.AttributesPerEntry; ++j ) free( attr_names[j] ); free( attr_names ); } // Check to see if there is metadata that defines what part, material, // and assembly(ies) this block belongs to. if(this->Parser && this->Parser->GetPartDescription(ids[i])!="") { // First construct the names for the block, part, assembly, and // material using the parsed XML metadata. vtkstd::vector<vtkStdString> assemblyNumbers= this->Parser->GetAssemblyNumbers(binfo.Id); vtkstd::vector<vtkStdString> assemblyDescriptions= this->Parser->GetAssemblyDescriptions(binfo.Id); vtkstd::vector<vtkStdString> localAssemblyNames; for (vtkstd::vector<int>::size_type m=0;m<assemblyNumbers.size();m++) { localAssemblyNames.push_back(assemblyDescriptions[m]+vtkStdString(" (")+ assemblyNumbers[m]+vtkStdString(")")); } vtkStdString blockName, partName, materialName; char block_name_buffer[80]; sprintf(block_name_buffer,"Block: %d (%s) %s",binfo.Id, this->Parser->GetPartDescription(binfo.Id).c_str(), this->Parser->GetPartNumber(binfo.Id).c_str()); blockName = block_name_buffer; partName = this->Parser->GetPartDescription(binfo.Id)+ " (" + this->Parser->GetMaterialDescription(binfo.Id)+")" + " : " + this->Parser->GetPartNumber(binfo.Id); materialName = this->Parser->GetMaterialDescription(binfo.Id) + " : " + this->Parser->GetMaterialSpecification(binfo.Id); // Override the existing block name with the new one binfo.Name = blockName; int blockIdx = this->BlockInfo[obj_types[i]].size(); // Add this block to our parts, materials, and assemblies collections unsigned int k; int found = 0; // Look to see if this part has already been created for (k=0;k<this->PartInfo.size();k++) { if (this->PartInfo[k].Name==partName) { //binfo.PartId = k; this->PartInfo[k].BlockIndices.push_back(blockIdx); found=1; } } if (!found) { PartInfoType pinfo; pinfo.Name = partName; pinfo.Id = this->PartInfo.size(); //binfo.PartId = k; pinfo.BlockIndices.push_back(blockIdx); this->PartInfo.push_back(pinfo); } found=0; for (k=0;k<this->MaterialInfo.size();k++) { if (this->MaterialInfo[k].Name==materialName) { //binfo.MaterialId = k; this->MaterialInfo[k].BlockIndices.push_back(blockIdx); found=1; } } if (!found) { MaterialInfoType matinfo; matinfo.Name = materialName; matinfo.Id = this->MaterialInfo.size(); //binfo.MaterialId = k; matinfo.BlockIndices.push_back(blockIdx); this->MaterialInfo.push_back(matinfo); } for (k=0;k<localAssemblyNames.size();k++) { vtkStdString assemblyName=localAssemblyNames[k]; found=0; for (unsigned int n=0;n<this->AssemblyInfo.size();n++) { if (this->AssemblyInfo[n].Name==assemblyName){ //binfo.AssemblyIds.push_back(j); this->AssemblyInfo[n].BlockIndices.push_back(blockIdx); found=1; } } if (!found) { AssemblyInfoType ainfo; ainfo.Name = assemblyName; ainfo.Id = this->AssemblyInfo.size(); //binfo.AssemblyIds.push_back(k); ainfo.BlockIndices.push_back(blockIdx); this->AssemblyInfo.push_back(ainfo); } } } sortedObjects[binfo.Id] = (int) this->BlockInfo[obj_types[i]].size(); this->BlockInfo[obj_types[i]].push_back( binfo ); } else if ( OBJTYPE_IS_SET(i) ) { sinfo.Name = obj_names[obj]; sinfo.Status = 0; sinfo.Id = ids[obj]; VTK_EXO_FUNC( ex_get_set_param( exoid, obj_types[i], ids[obj], &sinfo.Size, &sinfo.DistFact ), "Could not read set parameters." ); //num_entries = sinfo.Size; sinfo.FileOffset = setEntryFileOffset; setEntryFileOffset += sinfo.Size; if ( sinfo.Status ) { sinfo.GridOffset = setEntryGridOffset; setEntryGridOffset += sinfo.Size; } else { sinfo.GridOffset = -1; } if ( sinfo.Name.length() == 0 ) { SNPRINTF( tmpName, 255, "Unnamed set ID: %d Size: %d", ids[obj], sinfo.Size ); sinfo.Name = tmpName; } sortedObjects[sinfo.Id] = (int) this->SetInfo[obj_types[i]].size(); this->SetInfo[obj_types[i]].push_back( sinfo ); } else { /* object is map */ minfo.Id = ids[obj]; minfo.Status = obj == 0 ? 1 : 0; // only load the first map by default switch (obj_types[i]) { case vtkExodusIIReader::NODE_MAP: //num_entries = this->ModelParameters.num_nodes; minfo.Size = this->ModelParameters.num_nodes; break; case vtkExodusIIReader::EDGE_MAP: //num_entries = this->ModelParameters.num_edge; minfo.Size = this->ModelParameters.num_edge; break; case vtkExodusIIReader::FACE_MAP: //num_entries = this->ModelParameters.num_face; minfo.Size = this->ModelParameters.num_face; break; case vtkExodusIIReader::ELEM_MAP: //num_entries = this->ModelParameters.num_elem; minfo.Size = this->ModelParameters.num_elem; break; default: minfo.Size = 0; } minfo.Name = obj_names[obj]; if ( minfo.Name.length() == 0 ) { // make up a name. FIXME: Possible buffer overflow w/ sprintf SNPRINTF( tmpName, 255, "Unnamed map ID: %d", ids[obj] ); minfo.Name = tmpName; } sortedObjects[minfo.Id] = (int) this->MapInfo[obj_types[i]].size(); this->MapInfo[obj_types[i]].push_back( minfo ); } } // end of loop over all object ids // Now that we have all objects of that type in the sortedObjects, we can // iterate over it to fill in the SortedObjectIndices (the map is a *sorted* // associative container) vtkstd::map<int,int>::iterator soit; for ( soit = sortedObjects.begin(); soit != sortedObjects.end(); ++soit ) { this->SortedObjectIndices[obj_types[i]].push_back( soit->second ); } if ( ((OBJTYPE_IS_BLOCK(i)) || (OBJTYPE_IS_SET(i))) && num_vars && num_timesteps > 0 ) { this->ArrayInfo[obj_types[i]] = aitBlank; // Fill in ArrayInfo entries, combining array names into vectors/tensors where appropriate: this->GlomArrayNames( obj_types[i], nids, num_vars, var_names, truth_tab ); } if ( var_names ) { for ( j = 0; j < num_vars; ++j ) free( var_names[j] ); free( var_names ); } if ( truth_tab ) free( truth_tab ); if ( nids ) { free( ids ); for ( obj = 0; obj < nids; ++obj ) free( obj_names[obj] ); free( obj_names ); if ( OBJTYPE_IS_BLOCK(i) ) { for ( obj = 0; obj < nids; ++obj ) free( obj_typenames[obj] ); free( obj_typenames ); } } } // end of loop over all object types this->ComputeGridOffsets(); // Now read information for nodal arrays VTK_EXO_FUNC( ex_get_var_param( exoid, "n", &num_vars ), "Unable to read number of nodal variables." ); if ( num_vars > 0 ) { ArrayInfoType ainfo; var_names = (char**) malloc( num_vars * sizeof(char*) ); for ( j = 0; j < num_vars; ++j ) var_names[j] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); VTK_EXO_FUNC( ex_get_var_names( exoid, "n", num_vars, var_names ), "Could not read nodal variable names." ); this->RemoveBeginningAndTrailingSpaces( num_vars, var_names ); nids = 1; vtkstd::vector<int> dummy_truth; dummy_truth.reserve( num_vars ); for ( j = 0; j < num_vars; ++j ) { dummy_truth.push_back( 1 ); } this->GlomArrayNames( vtkExodusIIReader::NODAL, nids, num_vars, var_names, &dummy_truth[0] ); for ( j = 0; j < num_vars; ++j ) { free( var_names[j] ); } free( var_names ); var_names = 0; } return 0; } int vtkExodusIIReaderPrivate::RequestData( vtkIdType timeStep, vtkUnstructuredGrid* output ) { // The work done here depends on several conditions: // - Has connectivity changed (i.e., has block/set status changed)? // - If so, AND if point "squeeze" turned on, must reload points and re-squeeze. // - If so, must re-assemble all arrays // - Must recreate block/set id array. // - Has requested time changed? // - If so, AND if "deflect mesh" turned on, must load new deflections and compute new points. // - If so, must assemble all time-varying arrays for new time. // - Has array status changed? // - If so, must delete old and/or load new arrays. // Obviously, many of these tasks overlap. For instance, it would be // foolish to re-assemble all the arrays when the connectivity has // changed and then toss them out in order to load arrays for a // different time step. // Caching strategy: use GLOBAL "object type" for assembled arrays. // If connectivity hasn't changed, then these arrays can be used; // otherwise, "raw" arrays must be used. // Pro: // - single cache == easier bookkeeping (two caches would require us to decide how to equitably split avail mem between them) // - many different operations are accelerated: // - just changing which variables are loaded // - changing which blocks are in output (doesn't require disk access if cache hit) // - possible extension to single-node/cell over time // Con: // - higher memory consumption for caching the same set of arrays (or, holding cache size fixed: fewer arrays fit) if ( ! output ) { vtkErrorMacro( "You must specify an output mesh" ); } // Connectivity first. Either from the cache or reassembled. // Connectivity isn't allowed to change with time step so this should only re-read // from disk when block/set status changes. And it might not even re-read then if // the cache contains all the requested block/set entries. this->AssembleOutputConnectivity( timeStep, output ); // Now prepare points. // These shouldn't change unless the connectivity has changed. // This function doesn't apply displacements because we don't have the displacement vectors yet. this->AssembleOutputPoints( timeStep, output ); // Finally, add the desired arrays from cache (or disk) // Point and cell arrays are handled differently because they have different problems // to solve. Point arrays must use the PointMap index to subset values while cell arrays // must be padded with zeros for cells in blocks/sets that do not contain the given arrays. this->AssembleOutputPointArrays( timeStep, output ); this->AssembleOutputCellArrays( timeStep, output ); this->AssembleOutputProceduralArrays( timeStep, output ); this->AssembleOutputPointMaps( timeStep, output ); this->AssembleOutputCellMaps( timeStep, output ); this->CloseFile(); return 0; } void vtkExodusIIReaderPrivate::Reset() { this->CloseFile(); this->BlockInfo.clear(); this->SetInfo.clear(); this->MapInfo.clear(); this->PartInfo.clear(); this->MaterialInfo.clear(); this->AssemblyInfo.clear(); this->SortedObjectIndices.clear(); this->ArrayInfo.clear(); this->ExodusVersion = -1.; this->Times.clear(); this->TimeStep = 0; this->HasModeShapes = 0; this->ModeShapeTime = -1.; this->NumberOfCells = 0; this->SqueezePoints = 1; this->PointMap.clear(); this->Cache->Clear(); this->ApplyDisplacements = 1; this->DisplacementMagnitude = 1.; memset( (void*)&this->ModelParameters, 0, sizeof(this->ModelParameters) ); this->Cache->SetCacheCapacity( 0. ); // FIXME: Perhaps Cache should have a Reset and a Clear method? this->Cache->SetCacheCapacity( 128. ); // FIXME: Perhaps Cache should have a Reset and a Clear method? this->SetCachedConnectivity( 0 ); this->NextSqueezePoint = 0; this->GenerateGlobalElementIdArray = 0; this->GenerateGlobalNodeIdArray = 0; this->GenerateObjectIdArray = 1; this->Modified(); } void vtkExodusIIReaderPrivate::SetSqueezePoints( int sp ) { if ( this->SqueezePoints == sp ) return; this->SqueezePoints = sp; this->Modified(); // Invalidate global "topology" cache this->SetCachedConnectivity( 0 ); // The point map should be invalidated this->PointMap.clear(); this->NextSqueezePoint = 0; } int vtkExodusIIReaderPrivate::GetNumberOfNodes() { if ( this->SqueezePoints ) return this->NextSqueezePoint; return this->ModelParameters.num_nodes; } int vtkExodusIIReaderPrivate::GetNumberOfObjectsOfType( int otyp ) { int i = this->GetObjectTypeIndexFromObjectType( otyp ); if ( i < 0 ) { // Could signal warning here, but might not want it if file simply doesn't have objects of some obscure type (e.g., edge sets) return 0; } return this->GetNumberOfObjectsAtTypeIndex( i ); } int vtkExodusIIReaderPrivate::GetNumberOfObjectArraysOfType( int otyp ) { vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( otyp ); if ( it != this->ArrayInfo.end() ) { return (int) it->second.size(); } // Could signal warning here, but might not want it if file simply doesn't have objects of some obscure type (e.g., edge sets) return 0; } const char* vtkExodusIIReaderPrivate::GetObjectName( int otyp, int k ) { ObjectInfoType* oinfop = this->GetSortedObjectInfo( otyp, k ); return oinfop ? oinfop->Name.c_str() : 0; } int vtkExodusIIReaderPrivate::GetObjectId( int otyp, int k ) { ObjectInfoType* oinfop = this->GetSortedObjectInfo( otyp, k ); return oinfop ? oinfop->Id : -1; } int vtkExodusIIReaderPrivate::GetObjectSize( int otyp, int k ) { ObjectInfoType* oinfop = this->GetSortedObjectInfo( otyp, k ); return oinfop ? oinfop->Size : 0; } int vtkExodusIIReaderPrivate::GetObjectStatus( int otyp, int k ) { ObjectInfoType* oinfop = this->GetSortedObjectInfo( otyp, k ); return oinfop ? oinfop->Status : 0; } int vtkExodusIIReaderPrivate::GetUnsortedObjectStatus( int otyp, int k ) { ObjectInfoType* oinfop = this->GetUnsortedObjectInfo( otyp, k ); return oinfop ? oinfop->Status : 0; } void vtkExodusIIReaderPrivate::SetObjectStatus( int otyp, int k, int stat ) { stat = (stat != 0); // Force stat to be either 0 or 1 // OK, found the object ObjectInfoType* oinfop = this->GetSortedObjectInfo( otyp, k ); if ( ! oinfop ) { // error message will have been generated by GetSortedObjectInfo() return; } if ( oinfop->Status == stat ) { // no change => do nothing return; } oinfop->Status = stat; this->ComputeGridOffsets(); // Invalidate connectivity this->SetCachedConnectivity( 0 ); // Invalidate global cell arrays vtkExodusIICacheKey pattern( 0, 1, 0, 0 ); this->Cache->Invalidate( vtkExodusIICacheKey( 0, vtkExodusIIReader::GLOBAL, 0, 0 ), pattern ); pattern = vtkExodusIICacheKey( 1, 1, 0, 0 ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_OBJECT_ID, 0, 0 ), pattern ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_ELEMENT_ID, 0, 0 ), pattern ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_NODE_ID, 0, 0 ), pattern ); this->Modified(); } void vtkExodusIIReaderPrivate::SetUnsortedObjectStatus( int otyp, int k, int stat ) { stat = (stat != 0); // Force stat to be either 0 or 1 // OK, found the object ObjectInfoType* oinfop = this->GetUnsortedObjectInfo( otyp, k ); if ( ! oinfop ) { // error message will have been generated by GetSortedObjectInfo() return; } if ( oinfop->Status == stat ) { // no change => do nothing return; } oinfop->Status = stat; this->ComputeGridOffsets(); // Invalidate connectivity this->SetCachedConnectivity( 0 ); // Invalidate global cell arrays vtkExodusIICacheKey pattern( 0, 1, 0, 0 ); this->Cache->Invalidate( vtkExodusIICacheKey( 0, vtkExodusIIReader::GLOBAL, 0, 0 ), pattern ); pattern = vtkExodusIICacheKey( 1, 1, 0, 0 ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_OBJECT_ID, 0, 0 ), pattern ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_ELEMENT_ID, 0, 0 ), pattern ); this->Cache->Invalidate( vtkExodusIICacheKey( -1, vtkExodusIIReader::GLOBAL_NODE_ID, 0, 0 ), pattern ); this->Modified(); } const char* vtkExodusIIReaderPrivate::GetObjectArrayName( int otyp, int i ) { vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( otyp ); if ( it != this->ArrayInfo.end() ) { int N = (int) it->second.size(); if ( i < 0 || i >= N ) { vtkWarningMacro( "You requested array " << i << " in a collection of only " << N << " arrays." ); return 0; } return it->second[i].Name.c_str(); } vtkWarningMacro( "Could not find collection of arrays for objects of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } int vtkExodusIIReaderPrivate::GetNumberOfObjectArrayComponents( int otyp, int i ) { vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( otyp ); if ( it != this->ArrayInfo.end() ) { int N = (int) it->second.size(); if ( i < 0 || i >= N ) { vtkWarningMacro( "You requested array " << i << " in a collection of only " << N << " arrays." ); return 0; } return it->second[i].Components; } vtkWarningMacro( "Could not find collection of arrays for objects of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } int vtkExodusIIReaderPrivate::GetObjectArrayStatus( int otyp, int i ) { vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( otyp ); if ( it != this->ArrayInfo.end() ) { int N = (int) it->second.size(); if ( i < 0 || i >= N ) { vtkWarningMacro( "You requested array " << i << " in a collection of only " << N << " arrays." ); return 0; } return it->second[i].Status; } vtkWarningMacro( "Could not find collection of arrays for objects of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } void vtkExodusIIReaderPrivate::SetObjectArrayStatus( int otyp, int i, int stat ) { stat = ( stat != 0 ); // Force stat to be either 0 or 1 vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( otyp ); if ( it != this->ArrayInfo.end() ) { int N = (int) it->second.size(); if ( i < 0 || i >= N ) { vtkWarningMacro( "You requested array " << i << " in a collection of only " << N << " arrays." ); return; } if ( it->second[i].Status == stat ) { // no change => do nothing return; } it->second[i].Status = stat; this->Modified(); // FIXME: Mark something so we know what's changed since the last RequestData?! // For the "global" (assembled) array, this is tricky because we really only want // to invalidate a range of the total array... For now, we'll just force the "global" // array to be reassembled even if it does mean a lot more copying -- it's not like // it was any faster before. //vtkExodusIICacheKey key( 0, GLOBAL, 0, i ); //vtkExodusIICacheKey pattern( 0, 1, 0, 1 ); this->Cache->Invalidate( vtkExodusIICacheKey( 0, vtkExodusIIReader::GLOBAL, otyp, i ), vtkExodusIICacheKey( 0, 1, 1, 1 ) ); } else { vtkWarningMacro( "Could not find collection of arrays for objects of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); } } int vtkExodusIIReaderPrivate::GetNumberOfObjectAttributes( int otyp, int oi ) { vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator it = this->BlockInfo.find( otyp ); if ( it != this->BlockInfo.end() ) { int N = (int) it->second.size(); if ( oi < 0 || oi >= N ) { int otypIdx = this->GetObjectTypeIndexFromObjectType(otyp); const char* btname = otypIdx >= 0 ? objtype_names[otypIdx] : "block"; vtkWarningMacro( "You requested " << btname << " " << oi << " in a collection of only " << N << " blocks." ); return 0; } oi = this->SortedObjectIndices[otyp][oi]; // index into sorted list of objects (block order, not file order) return (int) it->second[oi].AttributeNames.size(); } vtkWarningMacro( "Could not find collection of blocks of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } const char* vtkExodusIIReaderPrivate::GetObjectAttributeName( int otyp, int oi, int ai ) { vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator it = this->BlockInfo.find( otyp ); if ( it != this->BlockInfo.end() ) { int N = (int) it->second.size(); if ( oi < 0 || oi >= N ) { vtkWarningMacro( "You requested block " << oi << " in a collection of only " << N << " blocks." ); return 0; } oi = this->SortedObjectIndices[otyp][oi]; // index into sorted list of objects (block order, not file order) N = (int) it->second[oi].AttributeNames.size(); if ( ai < 0 || ai >= N ) { vtkWarningMacro( "You requested attribute " << ai << " in a collection of only " << N << " attributes." ); return 0; } else { return it->second[oi].AttributeNames[ai].c_str(); } } vtkWarningMacro( "Could not find collection of blocks of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } int vtkExodusIIReaderPrivate::GetObjectAttributeIndex( int otyp, int oi, const char* attribName ) { vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator it = this->BlockInfo.find( otyp ); if ( it != this->BlockInfo.end() ) { int N = (int) it->second.size(); if ( oi < 0 || oi >= N ) { vtkWarningMacro( "You requested block " << oi << " in a collection of only " << N << " blocks." ); return -1; } oi = this->SortedObjectIndices[otyp][oi]; // index into sorted list of objects (block order, not file order) N = (int) it->second[oi].AttributeNames.size(); int ai; for ( ai = 0; ai < N; ++ai ) { if ( it->second[oi].AttributeNames[ai] == attribName ) { return ai; } } return -1; } vtkWarningMacro( "Could not find collection of blocks of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return -1; } int vtkExodusIIReaderPrivate::GetObjectAttributeStatus( int otyp, int oi, int ai ) { vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator it = this->BlockInfo.find( otyp ); if ( it != this->BlockInfo.end() ) { int N = (int) it->second.size(); if ( oi < 0 || oi >= N ) { vtkWarningMacro( "You requested block " << oi << " in a collection of only " << N << " blocks." ); return 0; } oi = this->SortedObjectIndices[otyp][oi]; // index into sorted list of objects (block order, not file order) N = (int) it->second[oi].AttributeStatus.size(); if ( ai < 0 || ai >= N ) { vtkWarningMacro( "You requested attribute " << ai << " in a collection of only " << N << " attributes." ); return 0; } else { return it->second[oi].AttributeStatus[ai]; } } vtkWarningMacro( "Could not find collection of blocks of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); return 0; } void vtkExodusIIReaderPrivate::SetObjectAttributeStatus( int otyp, int oi, int ai, int status ) { status = status ? 1 : 0; vtkstd::map<int,vtkstd::vector<BlockInfoType> >::iterator it = this->BlockInfo.find( otyp ); if ( it != this->BlockInfo.end() ) { int N = (int) it->second.size(); if ( oi < 0 || oi >= N ) { vtkWarningMacro( "You requested block " << oi << " in a collection of only " << N << " blocks." ); return; } oi = this->SortedObjectIndices[otyp][oi]; // index into sorted list of objects (block order, not file order) N = (int) it->second[oi].AttributeStatus.size(); if ( ai < 0 || ai >= N ) { vtkWarningMacro( "You requested attribute " << ai << " in a collection of only " << N << " attribute." ); return; } else { if ( it->second[oi].AttributeStatus[ai] == status ) { return; } it->second[oi].AttributeStatus[ai] = status; this->Modified(); } } vtkWarningMacro( "Could not find collection of blocks of type " << otyp << " (" << objtype_names[this->GetObjectTypeIndexFromObjectType(otyp)] << ")." ); } void vtkExodusIIReaderPrivate::SetApplyDisplacements( int d ) { if ( this->ApplyDisplacements == d ) return; this->ApplyDisplacements = d; this->Modified(); // Require the coordinates to be recomputed: this->Cache->Invalidate( vtkExodusIICacheKey( 0, vtkExodusIIReader::NODAL_COORDS, 0, 0 ), vtkExodusIICacheKey( 0, 1, 0, 0 ) ); } void vtkExodusIIReaderPrivate::SetDisplacementMagnitude( double s ) { if ( this->DisplacementMagnitude == s ) return; this->DisplacementMagnitude = s; this->Modified(); // Require the coordinates to be recomputed: this->Cache->Invalidate( vtkExodusIICacheKey( 0, vtkExodusIIReader::NODAL_COORDS, 0, 0 ), vtkExodusIICacheKey( 0, 1, 0, 0 ) ); } vtkDataArray* vtkExodusIIReaderPrivate::FindDisplacementVectors( int timeStep ) { vtkstd::map<int,vtkstd::vector<ArrayInfoType> >::iterator it = this->ArrayInfo.find( vtkExodusIIReader::NODAL ); if ( it != this->ArrayInfo.end() ) { int N = (int) it->second.size(); for ( int i = 0; i < N; ++i ) { vtkstd::string upperName = vtksys::SystemTools::UpperCase( it->second[i].Name.substr( 0, 3 ) ); if ( upperName == "DIS" && it->second[i].Components == 3 ) { return this->GetCacheOrRead( vtkExodusIICacheKey( timeStep, vtkExodusIIReader::NODAL, 0, i ) ); } } } return 0; } // -------------------------------------------------------- PUBLIC CLASS MEMBERS vtkCxxRevisionMacro(vtkExodusIIReader,"1.19"); vtkStandardNewMacro(vtkExodusIIReader); vtkCxxSetObjectMacro(vtkExodusIIReader,Metadata,vtkExodusIIReaderPrivate); vtkCxxSetObjectMacro(vtkExodusIIReader,ExodusModel,vtkExodusModel); vtkExodusIIReader::vtkExodusIIReader() { this->FileName = 0; this->XMLFileName = 0; this->Metadata = vtkExodusIIReaderPrivate::New(); this->Metadata->Parent = this; this->TimeStep = 0; this->TimeStepRange[0] = 0; this->TimeStepRange[1] = 0; this->ExodusModelMetadata = 0; this->PackExodusModelOntoOutput = 1; this->ExodusModel = 0; this->DisplayType = 0; this->SetNumberOfInputPorts( 0 ); } vtkExodusIIReader::~vtkExodusIIReader() { this->SetXMLFileName( 0 ); this->SetFileName( 0 ); this->SetMetadata( 0 ); this->SetExodusModel( 0 ); } // Normally, vtkExodusIIReader::PrintSelf would be here. // But it's above to prevent PrintSelf-Hybrid from failing because it assumes // the first PrintSelf method is the one for the class declared in the header file. int vtkExodusIIReader::CanReadFile( const char* fname ) { int exoid; int appWordSize = 8; int diskWordSize = 8; float version; if ( (exoid = ex_open( fname, EX_READ, &appWordSize, &diskWordSize, &version )) == 0 ) { return 0; } if ( ex_close( exoid ) != 0 ) { vtkWarningMacro( "Unable to close \"" << fname << "\" opened for testing." ); return 0; } return 1; } unsigned long vtkExodusIIReader::GetMTime() { unsigned long mtime1, mtime2; unsigned long readerMTime = this->MTime.GetMTime(); unsigned long privateMTime = this->Metadata->GetMTime(); unsigned long fileNameMTime = this->FileNameMTime.GetMTime(); unsigned long xmlFileNameMTime = this->XMLFileNameMTime.GetMTime(); mtime1 = privateMTime > readerMTime ? privateMTime : readerMTime; mtime2 = fileNameMTime > xmlFileNameMTime ? fileNameMTime : xmlFileNameMTime; return mtime1 > mtime2 ? mtime1 : mtime2; } unsigned long vtkExodusIIReader::GetMetadataMTime() { return this->Metadata->InformationTimeStamp < this->Metadata->GetMTime() ? this->Metadata->InformationTimeStamp : this->Metadata->GetMTime(); } #define vtkSetStringMacroBody(propName,fname) \ int modified = 0; \ if ( fname == this->propName ) \ return; \ if ( fname && this->propName && !strcmp( fname, this->propName ) ) \ return; \ modified = 1; \ if ( this->propName ) \ delete [] this->propName; \ if ( fname ) \ { \ size_t fnl = strlen( fname ) + 1; \ char* dst = new char[fnl]; \ const char* src = fname; \ this->propName = dst; \ do { *dst++ = *src++; } while ( --fnl ); \ } \ else \ { \ this->propName = 0; \ } void vtkExodusIIReader::SetFileName( const char* fname ) { vtkSetStringMacroBody(FileName,fname); if ( modified ) { this->Metadata->Reset(); this->FileNameMTime.Modified(); } } void vtkExodusIIReader::SetXMLFileName( const char* fname ) { vtkSetStringMacroBody(XMLFileName,fname); if ( modified ) { this->XMLFileNameMTime.Modified(); } } int vtkExodusIIReader::RequestInformation( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector ) { int newMetadata = 0; vtkInformation* outInfo = outputVector->GetInformationObject(0); // If the metadata is older than the filename if ( this->GetMetadataMTime() < this->FileNameMTime ) { if ( this->Metadata->OpenFile( this->FileName ) ) { // We need to initialize the XML parser before calling RequestInformation // on the metadata if ( this->FindXMLFile() ) { vtkExodusIIXMLParser *parser = vtkExodusIIXMLParser::New(); this->Metadata->SetParser(parser); // Now overwrite any names in the exodus file with names from XML file. parser->Go( this->XMLFileName, this->Metadata ); parser->Delete(); } this->Metadata->RequestInformation(); this->Metadata->CloseFile(); newMetadata = 1; } else { vtkErrorMacro( "Unable to open file \"" << (this->FileName ? this->FileName : "(null)") << "\" to read metadata" ); return 0; } } if ( ! this->GetHasModeShapes() ) { int nTimes = (int) this->Metadata->Times.size(); double timeRange[2]; if ( nTimes ) { timeRange[0] = this->Metadata->Times[0]; timeRange[1] = this->Metadata->Times[nTimes - 1]; outInfo->Set( vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &this->Metadata->Times[0], nTimes ); outInfo->Set( vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2 ); this->TimeStepRange[0] = 0; this->TimeStepRange[1] = nTimes - 1; } } else { outInfo->Remove( vtkStreamingDemandDrivenPipeline::TIME_STEPS() ); static double timeRange[] = { 0, 1 }; outInfo->Set( vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2 ); } if ( newMetadata ) { // update ExodusModelMetadata } return 1; } int vtkExodusIIReader::RequestData( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector ) { if ( ! this->FileName || ! this->Metadata->OpenFile( this->FileName ) ) { vtkErrorMacro( "Unable to open file \"" << (this->FileName ? this->FileName : "(null)") << "\" to read data" ); return 0; } vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast( outInfo->Get( vtkDataObject::DATA_OBJECT() ) ); // Check if a particular time was requested. int timeStep = this->TimeStep; if ( outInfo->Has( vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS() ) ) { // Get the requested time step. We only support requests of a single time step in this reader right now double* requestedTimeSteps = outInfo->Get( vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS() ); // Save the time value in the output data information. int length = outInfo->Length( vtkStreamingDemandDrivenPipeline::TIME_STEPS() ); double* steps = outInfo->Get( vtkStreamingDemandDrivenPipeline::TIME_STEPS() ); if ( ! this->GetHasModeShapes() ) { // find the highest time step with a time value that is smaller than the requested time. timeStep = 0; while (timeStep < length - 1 && steps[timeStep] < requestedTimeSteps[0]) { timeStep++; } this->TimeStep = timeStep; output->GetInformation()->Set( vtkDataObject::DATA_TIME_STEPS(), steps + timeStep, 1 ); } else { // Let the metadata know the time value so that the Metadata->RequestData call below will generate // the animated mode shape properly. this->Metadata->ModeShapeTime = requestedTimeSteps[0]; output->GetInformation()->Set( vtkDataObject::DATA_TIME_STEPS(), &this->Metadata->ModeShapeTime, 1 ); //output->GetInformation()->Remove( vtkDataObject::DATA_TIME_STEPS() ); } } //cout << "Requesting step " << timeStep << " for output " << output << "\n"; this->Metadata->RequestData( timeStep, output ); return 1; } void vtkExodusIIReader::SetGenerateObjectIdCellArray( int x ) { this->Metadata->SetGenerateObjectIdArray( x ); } int vtkExodusIIReader::GetGenerateObjectIdCellArray() { return this->Metadata->GetGenerateObjectIdArray(); } void vtkExodusIIReader::SetGenerateGlobalElementIdArray( int x ) { this->Metadata->SetGenerateGlobalElementIdArray( x ); } int vtkExodusIIReader::GetGenerateGlobalElementIdArray() { return this->Metadata->GetGenerateGlobalElementIdArray(); } void vtkExodusIIReader::SetGenerateGlobalNodeIdArray( int x ) { this->Metadata->SetGenerateGlobalNodeIdArray( x ); } int vtkExodusIIReader::GetGenerateGlobalNodeIdArray() { return this->Metadata->GetGenerateGlobalNodeIdArray(); } // FIXME: Implement the four functions that return ID_NOT_FOUND below. int vtkExodusIIReader::GetGlobalElementID( vtkDataSet* data, int localID ) { return GetGlobalElementID( data, localID, SEARCH_TYPE_ELEMENT_THEN_NODE ); } int vtkExodusIIReader::GetGlobalElementID ( vtkDataSet* data, int localID, int searchType ) { (void)data; (void)localID; (void)searchType; return ID_NOT_FOUND; } int vtkExodusIIReader::GetGlobalFaceID( vtkDataSet* data, int localID ) { return GetGlobalFaceID( data, localID, SEARCH_TYPE_ELEMENT_THEN_NODE ); } int vtkExodusIIReader::GetGlobalFaceID ( vtkDataSet* data, int localID, int searchType ) { (void)data; (void)localID; (void)searchType; return ID_NOT_FOUND; } int vtkExodusIIReader::GetGlobalEdgeID( vtkDataSet* data, int localID ) { return GetGlobalEdgeID( data, localID, SEARCH_TYPE_ELEMENT_THEN_NODE ); } int vtkExodusIIReader::GetGlobalEdgeID ( vtkDataSet* data, int localID, int searchType ) { (void)data; (void)localID; (void)searchType; return ID_NOT_FOUND; } int vtkExodusIIReader::GetGlobalNodeID( vtkDataSet* data, int localID ) { return GetGlobalNodeID( data, localID, SEARCH_TYPE_NODE_THEN_ELEMENT ); } int vtkExodusIIReader::GetGlobalNodeID( vtkDataSet* data, int localID, int searchType ) { (void)data; (void)localID; (void)searchType; return ID_NOT_FOUND; } void vtkExodusIIReader::SetApplyDisplacements( int d ) { this->Metadata->SetApplyDisplacements( d ); } int vtkExodusIIReader::GetApplyDisplacements() { return this->Metadata->GetApplyDisplacements(); } void vtkExodusIIReader::SetDisplacementMagnitude( float s ) { this->Metadata->SetDisplacementMagnitude( s ); } float vtkExodusIIReader::GetDisplacementMagnitude() { return this->Metadata->GetDisplacementMagnitude(); } void vtkExodusIIReader::SetHasModeShapes( int ms ) { this->Metadata->SetHasModeShapes(ms); } int vtkExodusIIReader::GetHasModeShapes() { return this->Metadata->GetHasModeShapes(); } void vtkExodusIIReader::SetModeShapeTime( double phase ) { double x = phase < 0. ? 0. : ( phase > 1. ? 1. : phase ); if ( this->Metadata->ModeShapeTime == x ) { return; } this->Metadata->SetModeShapeTime( x ); } double vtkExodusIIReader::GetModeShapeTime() { return this->Metadata->GetModeShapeTime(); } const char* vtkExodusIIReader::GetTitle() { return this->Metadata->ModelParameters.title; } int vtkExodusIIReader::GetDimensionality() { return this->Metadata->ModelParameters.num_dim; } int vtkExodusIIReader::GetNumberOfTimeSteps() { return (int) this->Metadata->Times.size(); } int vtkExodusIIReader::GetNumberOfNodesInFile() { return this->Metadata->ModelParameters.num_nodes; } int vtkExodusIIReader::GetNumberOfEdgesInFile() { return this->Metadata->ModelParameters.num_edge; } int vtkExodusIIReader::GetNumberOfFacesInFile() { return this->Metadata->ModelParameters.num_face; } int vtkExodusIIReader::GetNumberOfElementsInFile() { return this->Metadata->ModelParameters.num_elem; } int vtkExodusIIReader::GetNumberOfObjects( int objectType ) { return this->Metadata->GetNumberOfObjectsOfType( objectType ); } int vtkExodusIIReader::GetObjectTypeFromName( const char* name ) { vtkStdString tname( name ); if ( tname == "edge" ) return EDGE_BLOCK; else if ( tname == "face" ) return FACE_BLOCK; else if ( tname == "element" ) return ELEM_BLOCK; else if ( tname == "node set" ) return NODE_SET; else if ( tname == "edge set" ) return EDGE_SET; else if ( tname == "face set" ) return FACE_SET; else if ( tname == "side set" ) return SIDE_SET; else if ( tname == "element set" ) return ELEM_SET; else if ( tname == "node map" ) return NODE_MAP; else if ( tname == "edge map" ) return EDGE_MAP; else if ( tname == "face map" ) return FACE_MAP; else if ( tname == "element map" ) return ELEM_MAP; else if ( tname == "grid" ) return GLOBAL; else if ( tname == "node" ) return NODAL; else if ( tname == "assembly" ) return ASSEMBLY; else if ( tname == "part" ) return PART; else if ( tname == "material" ) return MATERIAL; else if ( tname == "hierarchy" ) return HIERARCHY; else if ( tname == "cell" ) return GLOBAL_CONN; else if ( tname == "element block cell" ) return ELEM_BLOCK_ELEM_CONN; else if ( tname == "element block face" ) return ELEM_BLOCK_FACE_CONN; else if ( tname == "element block edge" ) return ELEM_BLOCK_EDGE_CONN; else if ( tname == "face block cell" ) return FACE_BLOCK_CONN; else if ( tname == "edge block cell" ) return EDGE_BLOCK_CONN; else if ( tname == "element set cell" ) return ELEM_SET_CONN; else if ( tname == "side set cell" ) return SIDE_SET_CONN; else if ( tname == "face set cell" ) return FACE_SET_CONN; else if ( tname == "edge set cell" ) return EDGE_SET_CONN; else if ( tname == "node set cell" ) return NODE_SET_CONN; else if ( tname == "nodal coordinates" ) return NODAL_COORDS; else if ( tname == "object id" ) return GLOBAL_OBJECT_ID; else if ( tname == "global element id" ) return GLOBAL_ELEMENT_ID; else if ( tname == "global node id" ) return GLOBAL_NODE_ID; else if ( tname == "element id" ) return ELEMENT_ID; else if ( tname == "node id" ) return NODE_ID; else if ( tname == "pointmap" ) return NODAL_SQUEEZEMAP; return -1; } const char* vtkExodusIIReader::GetObjectTypeName( int otyp ) { switch ( otyp ) { case EDGE_BLOCK: return "edge"; case FACE_BLOCK: return "face"; case ELEM_BLOCK: return "element"; case NODE_SET: return "node set"; case EDGE_SET: return "edge set"; case FACE_SET: return "face set"; case SIDE_SET: return "side set"; case ELEM_SET: return "element set"; case NODE_MAP: return "node map"; case EDGE_MAP: return "edge map"; case FACE_MAP: return "face map"; case ELEM_MAP: return "element map"; case GLOBAL: return "grid"; case NODAL: return "node"; case ASSEMBLY: return "assembly"; case PART: return "part"; case MATERIAL: return "material"; case HIERARCHY: return "hierarchy"; case GLOBAL_CONN: return "cell"; case ELEM_BLOCK_ELEM_CONN: return "element block cell"; case ELEM_BLOCK_FACE_CONN: return "element block face"; case ELEM_BLOCK_EDGE_CONN: return "element block edge"; case FACE_BLOCK_CONN: return "face block cell"; case EDGE_BLOCK_CONN: return "edge block cell"; case ELEM_SET_CONN: return "element set cell"; case SIDE_SET_CONN: return "side set cell"; case FACE_SET_CONN: return "face set cell"; case EDGE_SET_CONN: return "edge set cell"; case NODE_SET_CONN: return "node set cell"; case NODAL_COORDS: return "nodal coordinates"; case GLOBAL_OBJECT_ID: return "object id"; case GLOBAL_ELEMENT_ID: return "global element id"; case GLOBAL_NODE_ID: return "global node id"; case ELEMENT_ID: return "element id"; case NODE_ID: return "node id"; case NODAL_SQUEEZEMAP: return "pointmap"; } return 0; } int vtkExodusIIReader::GetNumberOfNodes() { return this->Metadata->GetNumberOfNodes(); } int vtkExodusIIReader::GetNumberOfEntriesInObject( int objectType, int objectIndex ) { return this->Metadata->GetObjectSize( objectType, objectIndex ); } int vtkExodusIIReader::GetObjectId( int objectType, int objectIndex ) { return this->Metadata->GetObjectId( objectType, objectIndex ); } int vtkExodusIIReader::GetObjectStatus( int objectType, int objectIndex ) { return this->Metadata->GetObjectStatus( objectType, objectIndex ); } void vtkExodusIIReader::SetObjectStatus( int objectType, int objectIndex, int status ) { this->Metadata->SetObjectStatus( objectType, objectIndex, status ); } const char* vtkExodusIIReader::GetObjectName( int objectType, int objectIndex ) { return this->Metadata->GetObjectName( objectType, objectIndex ); } int vtkExodusIIReader::GetObjectIndex( int objectType, const char* objectName ) { if ( ! objectName ) { vtkErrorMacro( "You must specify a non-NULL name" ); return -1; } int nObj = this->GetNumberOfObjects( objectType ); if ( nObj == 0 ) { vtkWarningMacro( "No objects of that type (" << objectType << ") to find index for given name " << objectName << "." ); return -1; } for ( int obj = 0; obj < nObj; ++obj ) { if ( !strcmp( objectName, this->GetObjectName( objectType, obj ) ) ) { return obj; } } vtkWarningMacro( "No objects named \"" << objectName << "\" of the specified type (" << objectType << ")." ); return -1; } int vtkExodusIIReader::GetObjectIndex( int objectType, int id ) { int nObj = this->GetNumberOfObjects( objectType ); if ( nObj == 0 ) { vtkWarningMacro( "No objects of that type (" << objectType << ") to find index for given id " << id << "." ); return -1; } for ( int obj = 0; obj < nObj; ++obj ) { if ( this->GetObjectId( objectType, obj ) == id) { return obj; } } vtkWarningMacro( "No objects with id \"" << id << "\" of the specified type (" << objectType << ")." ); return -1; } int vtkExodusIIReader::GetNumberOfObjectArrays( int objectType ) { return this->Metadata->GetNumberOfObjectArraysOfType( objectType ); } const char* vtkExodusIIReader::GetObjectArrayName( int objectType, int arrayIndex ) { return this->Metadata->GetObjectArrayName( objectType, arrayIndex ); } int vtkExodusIIReader::GetNumberOfObjectArrayComponents( int objectType, int arrayIndex ) { return this->Metadata->GetNumberOfObjectArrayComponents( objectType, arrayIndex ); } int vtkExodusIIReader::GetObjectArrayStatus( int objectType, int arrayIndex ) { return this->Metadata->GetObjectArrayStatus( objectType, arrayIndex ); } void vtkExodusIIReader::SetObjectArrayStatus( int objectType, int arrayIndex, int status ) { this->Metadata->SetObjectArrayStatus( objectType, arrayIndex, status ); } int vtkExodusIIReader::GetNumberOfObjectAttributes( int objectType, int objectIndex ) { return this->Metadata->GetNumberOfObjectAttributes( objectType, objectIndex ); } const char* vtkExodusIIReader::GetObjectAttributeName( int objectType, int objectIndex, int attribIndex ) { return this->Metadata->GetObjectAttributeName( objectType, objectIndex, attribIndex ); } int vtkExodusIIReader::GetObjectAttributeIndex( int objectType, int objectIndex, const char* attribName ) { return this->Metadata->GetObjectAttributeIndex( objectType, objectIndex, attribName ); } int vtkExodusIIReader::GetObjectAttributeStatus( int objectType, int objectIndex, int attribIndex ) { return this->Metadata->GetObjectAttributeStatus( objectType, objectIndex, attribIndex ); } void vtkExodusIIReader::SetObjectAttributeStatus( int objectType, int objectIndex, int attribIndex, int status ) { this->Metadata->SetObjectAttributeStatus( objectType, objectIndex, attribIndex, status ); } int vtkExodusIIReader::GetObjectArrayIndex( int objectType, const char* arrayName ) { if ( ! arrayName ) { vtkErrorMacro( "You must specify a non-NULL name" ); return -1; } int nObj = this->GetNumberOfObjectArrays( objectType ); if ( nObj == 0 ) { vtkWarningMacro( "No objects of that type (" << objectType << ") to find index for given array " << arrayName << "." ); return -1; } for ( int obj = 0; obj < nObj; ++obj ) { if ( !strcmp( arrayName, this->GetObjectArrayName( objectType, obj ) ) ) { return obj; } } vtkWarningMacro( "No arrays named \"" << arrayName << "\" of the specified type (" << objectType << ")." ); return -1; } int vtkExodusIIReader::GetTotalNumberOfNodes() { return this->Metadata->GetModelParams()->num_nodes; } int vtkExodusIIReader::GetTotalNumberOfEdges() { return this->Metadata->GetModelParams()->num_edge; } int vtkExodusIIReader::GetTotalNumberOfFaces() { return this->Metadata->GetModelParams()->num_face; } int vtkExodusIIReader::GetTotalNumberOfElements() { return this->Metadata->GetModelParams()->num_elem; } // %--------------------------------------------------------------------------- int vtkExodusIIReader::GetNumberOfPartArrays() { return this->Metadata->GetNumberOfParts(); } const char* vtkExodusIIReader::GetPartArrayName( int arrayIdx ) { return this->Metadata->GetPartName(arrayIdx); } int vtkExodusIIReader::GetPartArrayID( const char *name ) { int numArrays = this->GetNumberOfPartArrays(); for ( int i=0;i<numArrays;i++ ) { if ( strcmp( name, this->GetPartArrayName( i ) ) == 0 ) { return i; } } return -1; } const char* vtkExodusIIReader::GetPartBlockInfo( int arrayIdx ) { return this->Metadata->GetPartBlockInfo(arrayIdx); } void vtkExodusIIReader::SetPartArrayStatus( int index, int flag ) { // Only modify if we are 'out of sync' if (this->Metadata->GetPartStatus(index) != flag) { this->Metadata->SetPartStatus(index, flag); // Because which parts are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } void vtkExodusIIReader::SetPartArrayStatus( const char* name, int flag ) { // Only modify if we are 'out of sync' if (this->Metadata->GetPartStatus(name) != flag) { this->Metadata->SetPartStatus(name, flag); // Because which parts are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } int vtkExodusIIReader::GetPartArrayStatus( int index ) { return this->Metadata->GetPartStatus(index); } int vtkExodusIIReader::GetPartArrayStatus( const char* part ) { return this->Metadata->GetPartStatus(part); } int vtkExodusIIReader::GetNumberOfMaterialArrays() { return this->Metadata->GetNumberOfMaterials(); } const char* vtkExodusIIReader::GetMaterialArrayName( int arrayIdx ) { return this->Metadata->GetMaterialName(arrayIdx); } int vtkExodusIIReader::GetMaterialArrayID( const char* matl ) { (void)matl; return 0; } void vtkExodusIIReader::SetMaterialArrayStatus( int index, int flag ) { // Only modify if we are 'out of sync' if (this->Metadata->GetMaterialStatus(index) != flag) { this->Metadata->SetMaterialStatus(index, flag); // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } void vtkExodusIIReader::SetMaterialArrayStatus( const char* matl, int flag ) { // Only modify if we are 'out of sync' if (this->Metadata->GetMaterialStatus(matl) != flag) { this->Metadata->SetMaterialStatus(matl, flag); // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } int vtkExodusIIReader::GetMaterialArrayStatus( int index ) { return this->Metadata->GetMaterialStatus(index); } int vtkExodusIIReader::GetMaterialArrayStatus( const char* matl ) { return this->Metadata->GetMaterialStatus(matl); } int vtkExodusIIReader::GetNumberOfAssemblyArrays() { return this->Metadata->GetNumberOfAssemblies(); } const char* vtkExodusIIReader::GetAssemblyArrayName( int arrayIdx ) { return this->Metadata->GetAssemblyName(arrayIdx); } int vtkExodusIIReader::GetAssemblyArrayID( const char* name ) { int numArrays = this->GetNumberOfAssemblyArrays(); for ( int i=0;i<numArrays;i++ ) { if ( strcmp( name, this->GetAssemblyArrayName( i ) ) == 0 ) { return i; } } return -1; } void vtkExodusIIReader::SetAssemblyArrayStatus(int index, int flag) { // Only modify if we are 'out of sync' if (this->Metadata->GetAssemblyStatus(index) != flag) { this->Metadata->SetAssemblyStatus(index, flag); // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } void vtkExodusIIReader::SetAssemblyArrayStatus(const char* name, int flag) { // Only modify if we are 'out of sync' if (this->Metadata->GetAssemblyStatus(name) != flag) { this->Metadata->SetAssemblyStatus(name, flag); // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } int vtkExodusIIReader::GetAssemblyArrayStatus(int index) { return this->Metadata->GetAssemblyStatus(index); } int vtkExodusIIReader::GetAssemblyArrayStatus(const char* name) { return this->Metadata->GetAssemblyStatus(name); } int vtkExodusIIReader::GetNumberOfHierarchyArrays() { if (this->Metadata->Parser) { return this->Metadata->Parser->GetNumberOfHierarchyEntries(); } return 0; } const char* vtkExodusIIReader::GetHierarchyArrayName(int arrayIdx) { if (this->Metadata->Parser) { //MEMORY LEAK - without copying the result, the list does not appear on SGI's char* result=new char[512]; sprintf(result,"%s",this->Metadata->Parser->GetHierarchyEntry(arrayIdx).c_str()); return result; //return this->Metadata->Parser->GetHierarchyEntry(arrayIdx).c_str(); } return "Should not see this"; } void vtkExodusIIReader::SetHierarchyArrayStatus(int index, int flag) { // Only modify if we are 'out of sync' //if (this->GetHierarchyArrayStatus(index) != flag) // { if (this->Metadata->Parser) { vtkstd::vector<int> blocksIds = this->Metadata->Parser->GetBlocksForEntry(index); for (vtkstd::vector<int>::size_type i=0;i<blocksIds.size();i++) { this->Metadata->SetObjectStatus(vtkExodusIIReader::ELEM_BLOCK, this->GetObjectIndex(ELEM_BLOCK,blocksIds[i]),flag); } // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } void vtkExodusIIReader::SetHierarchyArrayStatus(const char* name, int flag) { // Only modify if we are 'out of sync' //if (this->GetHierarchyArrayStatus(name) != flag) //{ if (this->Metadata->Parser) { vtkstd::vector<int> blocksIds=this->Metadata->Parser->GetBlocksForEntry (vtkStdString(name)); for (vtkstd::vector<int>::size_type i=0;i<blocksIds.size();i++) { //cout << "turning block " << blocks[i] << " " << flag << endl; this->Metadata->SetObjectStatus(vtkExodusIIReader::ELEM_BLOCK, this->GetObjectIndex(ELEM_BLOCK,blocksIds[i]),flag); } // Because which materials are on/off affects the // geometry we need to remake the mesh cache //this->RemakeDataCacheFlag = 1; this->Modified(); } } int vtkExodusIIReader::GetHierarchyArrayStatus(int index) { if (this->Metadata->Parser) { vtkstd::vector<int> blocksIds=this->Metadata->Parser->GetBlocksForEntry(index); for (vtkstd::vector<int>::size_type i=0;i<blocksIds.size();i++) { if (this->Metadata->GetObjectStatus(vtkExodusIIReader::ELEM_BLOCK, this->GetObjectIndex(ELEM_BLOCK,blocksIds[i]))==0) return 0; } } return 1; } int vtkExodusIIReader::GetHierarchyArrayStatus(const char* name) { if (this->Metadata->Parser) { vtkstd::vector<int> blocksIds=this->Metadata->Parser->GetBlocksForEntry(name); for (vtkstd::vector<int>::size_type i=0;i<blocksIds.size();i++) { if (this->Metadata->GetObjectStatus(vtkExodusIIReader::ELEM_BLOCK, this->GetObjectIndex(ELEM_BLOCK,blocksIds[i]))==0) return 0; } } return 1; } void vtkExodusIIReader::SetDisplayType( int typ ) { if ( typ == this->DisplayType || typ < 0 || typ > 2 ) return; this->DisplayType = typ; this->Modified(); } int vtkExodusIIReader::IsValidVariable( const char *type, const char *name ) { return (this->GetVariableID( type, name ) >= 0); } int vtkExodusIIReader::GetVariableID( const char *type, const char *name ) { int otyp = this->GetObjectTypeFromName( type ); if ( otyp < 0 ) { return 0; } switch ( otyp ) { case NODAL: case EDGE_BLOCK: case FACE_BLOCK: case ELEM_BLOCK: case NODE_SET: case EDGE_SET: case FACE_SET: case SIDE_SET: case ELEM_SET: return this->GetObjectArrayIndex( otyp, name ); case ASSEMBLY: return this->GetAssemblyArrayID( name ); case HIERARCHY: return -1; // FIXME: There is no this->GetHierarchyArrayID( name ) and it's not clear there should be. case MATERIAL: return this->GetMaterialArrayID( name ); case PART: return this->GetPartArrayID( name ); default: return -1; } } int vtkExodusIIReader::GetTimeSeriesData( int ID, const char* vName, const char* vType, vtkFloatArray* result ) { (void)ID; (void)vName; (void)vType; (void)result; return -1; } void vtkExodusIIReader::SetAllArrayStatus( int otyp, int status ) { int numObj; int i; switch ( otyp ) { case EDGE_BLOCK_CONN: case FACE_BLOCK_CONN: case ELEM_BLOCK_ELEM_CONN: case NODE_SET_CONN: case EDGE_SET_CONN: case FACE_SET_CONN: case SIDE_SET_CONN: case ELEM_SET_CONN: numObj = this->GetNumberOfObjects( otyp ); for ( i = 0; i < numObj; ++i ) { this->SetObjectStatus( otyp, i, status ); } break; case NODAL: case EDGE_BLOCK: case FACE_BLOCK: case ELEM_BLOCK: case NODE_SET: case EDGE_SET: case FACE_SET: case SIDE_SET: case ELEM_SET: numObj = this->GetNumberOfObjectArrays( otyp ); for ( i = 0; i < numObj; ++i ) { this->SetObjectArrayStatus( otyp, i, status ); } break; // --------------------- case ASSEMBLY: numObj = this->GetNumberOfAssemblyArrays(); for ( i = 0; i < numObj; ++i ) { this->SetAssemblyArrayStatus( i, status ); } case PART: numObj = this->GetNumberOfPartArrays(); for ( i = 0; i < numObj; ++i ) { this->SetPartArrayStatus( i, status ); } case MATERIAL: numObj = this->GetNumberOfMaterialArrays(); for ( i = 0; i < numObj; ++i ) { this->SetMaterialArrayStatus( i, status ); } case HIERARCHY: numObj = this->GetNumberOfHierarchyArrays(); for ( i = 0; i < numObj; ++i ) { this->SetHierarchyArrayStatus( i, status ); } default: ; break; } } void vtkExodusIIReader::NewExodusModel() { // These arrays are required by the Exodus II writer: this->GenerateGlobalElementIdArrayOn(); this->GenerateGlobalNodeIdArrayOn(); this->GenerateObjectIdCellArrayOn(); if ( this->ExodusModel ) { this->ExodusModel->Reset(); return; } this->ExodusModel = vtkExodusModel::New(); } void vtkExodusIIReader::Dump() { vtkIndent indent; this->PrintSelf( cout, indent ); } bool vtkExodusIIReader::FindXMLFile() { // If the XML filename exists and is newer than any existing parser (or there is no parser), reread XML file. if ( ( this->Metadata->Parser && this->Metadata->Parser->GetMTime() < this->XMLFileNameMTime && this->XMLFileName ) || ( ! Metadata->Parser ) ) { if ( Metadata->Parser ) { Metadata->Parser->Delete(); Metadata->Parser = 0; } if ( ! this->XMLFileName || ! vtksys::SystemTools::FileExists( this->XMLFileName ) ) { if ( this->FileName ) { vtkStdString baseName( vtksys::SystemTools::GetFilenameWithoutExtension( this->FileName ) ); vtkStdString xmlExt( baseName + ".xml" ); if ( vtksys::SystemTools::FileExists( xmlExt ) ) { this->SetXMLFileName( xmlExt.c_str() ); return true; } vtkStdString dartExt( baseName + ".dart" ); if ( vtksys::SystemTools::FileExists( dartExt ) ) { this->SetXMLFileName( dartExt.c_str() ); return true; } vtkStdString baseDir( vtksys::SystemTools::GetFilenamePath( this->FileName ) ); vtkStdString artifact( baseDir + "/artifact.dta" ); if ( vtksys::SystemTools::FileExists( artifact ) ) { this->SetXMLFileName( artifact.c_str() ); return true; } // Catch the case where filename was non-NULL but didn't exist. this->SetXMLFileName( 0 ); } } else { return true; } } return false; }
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textwindowaccessibility.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2008-01-28 14:12:58 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #if !defined INCLUDED_ACCESSIBILITY_TEXTWINDOWACCESSIBILITY_HXX #define INCLUDED_ACCESSIBILITY_TEXTWINDOWACCESSIBILITY_HXX #ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ #include <toolkit/awt/vclxaccessiblecomponent.hxx> #endif #ifndef _SFXLSTNER_HXX #include <svtools/lstner.hxx> #endif #ifndef _TEXTDATA_HXX #include <svtools/textdata.hxx> #endif #ifndef _TEXTENG_HXX #include <svtools/texteng.hxx> #endif #ifndef _TEXTVIEW_HXX #include <svtools/textview.hxx> #endif #ifndef _TXTATTR_HXX #include <svtools/txtattr.hxx> #endif #ifndef _COM_SUN_STAR_AWT_FONTWEIGHT_HPP_ #include <com/sun/star/awt/FontWeight.hpp> #endif #ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_ #include <com/sun/star/lang/EventObject.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_COLOR_HPP_ #include <com/sun/star/util/Color.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_ #include <com/sun/star/accessibility/AccessibleEventId.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_ #include <com/sun/star/accessibility/AccessibleRelationType.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_ #include <com/sun/star/accessibility/AccessibleRole.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_ #include <com/sun/star/accessibility/AccessibleStateType.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLETEXTTYPE_HPP_ #include <com/sun/star/accessibility/AccessibleTextType.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_ #include <com/sun/star/accessibility/XAccessibleContext.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEDITABLETEXT_HPP_ #include <com/sun/star/accessibility/XAccessibleEditableText.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLETEXTATTRIBUTES_HPP_ #include <com/sun/star/accessibility/XAccessibleTextAttributes.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_ #include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECOMPONENT_HPP_ #include <com/sun/star/accessibility/XAccessibleComponent.hpp> #endif #ifndef _TOOLKIT_AWT_VCLXWINDOW_HXX_ #include <toolkit/awt/vclxwindow.hxx> #endif #ifndef _CPPUHELPER_COMPBASE6_HXX_ #include <cppuhelper/compbase6.hxx> #endif #ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX #include <comphelper/accessiblecontexthelper.hxx> #endif #ifndef COMPHELPER_ACCESSIBLE_TEXT_HELPER_HXX #include <comphelper/accessibletexthelper.hxx> #endif #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #include <memory> #include <queue> #include <hash_map> class TextEngine; class TextView; namespace css = ::com::sun::star; namespace accessibility { class Paragraph; class Document; class SfxListenerGuard { public: inline SfxListenerGuard(::SfxListener & rListener): m_rListener(rListener), m_pNotifier(0) {} inline ~SfxListenerGuard() { endListening(); } // Not thread safe: void startListening(::SfxBroadcaster & rNotifier); // Not thread safe: void endListening(); private: ::SfxListener & m_rListener; ::SfxBroadcaster * m_pNotifier; }; class WindowListenerGuard { public: inline WindowListenerGuard(::Link const & rListener): m_aListener(rListener), m_pNotifier(0) {} inline ~WindowListenerGuard() { endListening(); } // Not thread safe: void startListening(::Window & rNotifier); // Not thread safe: void endListening(); private: ::Link m_aListener; ::Window * m_pNotifier; }; class ParagraphInfo { public: inline ParagraphInfo(::sal_Int32 nHeight): m_nHeight(nHeight) {} inline ::css::uno::WeakReference< ::css::accessibility::XAccessible > const & getParagraph() const { return m_xParagraph; } inline ::sal_Int32 getHeight() const { return m_nHeight; } inline void setParagraph( ::css::uno::Reference< ::css::accessibility::XAccessible > const & rParagraph) { m_xParagraph = rParagraph; } inline void changeHeight(::sal_Int32 nHeight) { m_nHeight = nHeight; } private: ::css::uno::WeakReference< ::css::accessibility::XAccessible > m_xParagraph; ::sal_Int32 m_nHeight; }; typedef ::std::vector< ParagraphInfo > Paragraphs; typedef ::cppu::WeakAggComponentImplHelper6< ::css::accessibility::XAccessible, ::css::accessibility::XAccessibleContext, ::css::accessibility::XAccessibleComponent, ::css::accessibility::XAccessibleEditableText, ::css::accessibility::XAccessibleTextAttributes, ::css::accessibility::XAccessibleEventBroadcaster > ParagraphBase; // The Paragraph's number is the absolute position within the text engine (from // 0 to N - 1), whereas the Paragraph's index is the position within the text // view/accessible parent (from 0 to M - 1). Paragraphs outside the currently // visible range have an index of -1. class ParagraphImpl: public ParagraphBase, private ::comphelper::OCommonAccessibleText { public: ParagraphImpl(::rtl::Reference< Document > const & rDocument, Paragraphs::size_type nNumber, ::osl::Mutex & rMutex); // Not thread-safe. inline Paragraphs::size_type getNumber() const { return m_nNumber; } // Not thread-safe. void numberChanged(bool bIncremented); // Not thread-safe. void textChanged(); // Thread-safe. void notifyEvent(::sal_Int16 nEventId, ::css::uno::Any const & rOldValue, ::css::uno::Any const & rNewValue); protected: // OCommonAccessibleText virtual void implGetParagraphBoundary( ::css::i18n::Boundary& rBoundary, ::sal_Int32 nIndex ); virtual void implGetLineBoundary( ::css::i18n::Boundary& rBoundary, ::sal_Int32 nIndex ); private: virtual ::css::uno::Reference< ::css::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getAccessibleChildCount() throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessible > SAL_CALL getAccessibleChild(::sal_Int32 i) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessible > SAL_CALL getAccessibleParent() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getAccessibleIndexInParent() throw (::css::uno::RuntimeException); virtual ::sal_Int16 SAL_CALL getAccessibleRole() throw (::css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getAccessibleDescription() throw (::css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getAccessibleName() throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet() throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet() throw (::css::uno::RuntimeException); virtual ::css::lang::Locale SAL_CALL getLocale() throw (::css::accessibility::IllegalAccessibleComponentStateException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL containsPoint(::css::awt::Point const & rPoint) throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint(::css::awt::Point const & rPoint) throw (::css::uno::RuntimeException); virtual ::css::awt::Rectangle SAL_CALL getBounds() throw (::css::uno::RuntimeException); virtual ::css::awt::Point SAL_CALL getLocation() throw (::css::uno::RuntimeException); virtual ::css::awt::Point SAL_CALL getLocationOnScreen() throw (::css::uno::RuntimeException); virtual ::css::awt::Size SAL_CALL getSize() throw (::css::uno::RuntimeException); virtual void SAL_CALL grabFocus() throw (::css::uno::RuntimeException); virtual ::css::uno::Any SAL_CALL getAccessibleKeyBinding() throw (::css::uno::RuntimeException); virtual ::css::util::Color SAL_CALL getForeground() throw (::css::uno::RuntimeException); virtual ::css::util::Color SAL_CALL getBackground() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getCaretPosition() throw (::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL setCaretPosition(::sal_Int32 nIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Unicode SAL_CALL getCharacter(::sal_Int32 nIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::css::uno::Sequence< ::css::beans::PropertyValue > SAL_CALL getCharacterAttributes(::sal_Int32 nIndex, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aRequestedAttributes ) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::css::awt::Rectangle SAL_CALL getCharacterBounds(::sal_Int32 nIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getCharacterCount() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getIndexAtPoint(::css::awt::Point const & rPoint) throw (::css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getSelectedText() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getSelectionStart() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getSelectionEnd() throw (::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL setSelection(::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getText() throw (::css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getTextRange(::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::com::sun::star::accessibility::TextSegment SAL_CALL getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::accessibility::TextSegment SAL_CALL getTextBeforeIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::accessibility::TextSegment SAL_CALL getTextBehindIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL copyText(::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL cutText(::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL pasteText(::sal_Int32 nIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL deleteText(::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL insertText(::rtl::OUString const & rText, ::sal_Int32 nIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL replaceText( ::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex, ::rtl::OUString const & rReplacement) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL setAttributes( ::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex, ::css::uno::Sequence< ::css::beans::PropertyValue > const & rAttributeSet) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL setText(::rtl::OUString const & rText) throw (::css::uno::RuntimeException); virtual ::css::uno::Sequence< ::css::beans::PropertyValue > SAL_CALL getDefaultAttributes(const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes) throw (::css::uno::RuntimeException); virtual ::css::uno::Sequence< ::css::beans::PropertyValue > SAL_CALL getRunAttributes(::sal_Int32 Index, const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); using cppu::WeakAggComponentImplHelperBase::addEventListener; virtual void SAL_CALL addEventListener( ::css::uno::Reference< ::css::accessibility::XAccessibleEventListener > const & rListener) throw (::css::uno::RuntimeException); using cppu::WeakAggComponentImplHelperBase::removeEventListener; virtual void SAL_CALL removeEventListener( ::css::uno::Reference< ::css::accessibility::XAccessibleEventListener > const & rListener) throw (::css::uno::RuntimeException); virtual void SAL_CALL disposing(); virtual ::rtl::OUString implGetText(); virtual ::css::lang::Locale implGetLocale(); virtual void implGetSelection(::sal_Int32 & rStartIndex, ::sal_Int32 & rEndIndex); // Throws ::css::lang::DisposedException: void checkDisposed(); ::rtl::Reference< Document > m_xDocument; Paragraphs::size_type m_nNumber; // ::cppu::OInterfaceContainerHelper m_aListeners; /// client id in the AccessibleEventNotifier queue sal_uInt32 m_nClientId; ::rtl::OUString m_aParagraphText; }; typedef ::std::hash_map< ::rtl::OUString, ::css::beans::PropertyValue, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > tPropValMap; class Document: public ::VCLXAccessibleComponent, public ::SfxListener { public: Document(::VCLXWindow * pVclXWindow, ::TextEngine & rEngine, ::TextView & rView, bool bCompoundControlChild); inline ::css::uno::Reference< ::css::accessibility::XAccessible > getAccessible() { return m_xAccessible; } // Must be called only after init has been called. ::css::lang::Locale retrieveLocale(); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const *" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::sal_Int32 retrieveParagraphIndex(ParagraphImpl const * pParagraph); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const *" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::sal_Int64 retrieveParagraphState(ParagraphImpl const * pParagraph); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::css::awt::Rectangle retrieveParagraphBounds(ParagraphImpl const * pParagraph, bool bAbsolute); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::rtl::OUString retrieveParagraphText(ParagraphImpl const * pParagraph); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". void retrieveParagraphSelection(ParagraphImpl const * pParagraph, ::sal_Int32 * pBegin, ::sal_Int32 * pEnd); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const *" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::sal_Int32 retrieveParagraphCaretPosition(ParagraphImpl const * pParagraph); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. ::css::awt::Rectangle retrieveCharacterBounds(ParagraphImpl const * pParagraph, ::sal_Int32 nIndex); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::sal_Int32 retrieveCharacterIndex(ParagraphImpl const * pParagraph, ::css::awt::Point const & rPoint); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. ::css::uno::Sequence< ::css::beans::PropertyValue > retrieveCharacterAttributes( ParagraphImpl const * pParagraph, ::sal_Int32 nIndex, const ::css::uno::Sequence< ::rtl::OUString >& aRequestedAttributes); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::css::uno::Sequence< ::css::beans::PropertyValue > retrieveDefaultAttributes( ParagraphImpl const * pParagraph, const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. ::css::uno::Sequence< ::css::beans::PropertyValue > retrieveRunAttributes( ParagraphImpl const * pParagraph, ::sal_Int32 Index, const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". void changeParagraphText(ParagraphImpl * pParagraph, ::rtl::OUString const & rText); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. void changeParagraphText(ParagraphImpl * pParagraph, ::sal_Int32 nBegin, ::sal_Int32 nEnd, bool bCut, bool bPaste, ::rtl::OUString const & rText); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. void copyParagraphText(ParagraphImpl const * pParagraph, ::sal_Int32 nBegin, ::sal_Int32 nEnd); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. void changeParagraphAttributes( ParagraphImpl * pParagraph, ::sal_Int32 nBegin, ::sal_Int32 nEnd, ::css::uno::Sequence< ::css::beans::PropertyValue > const & rAttributeSet); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. void changeParagraphSelection(ParagraphImpl * pParagraph, ::sal_Int32 nBegin, ::sal_Int32 nEnd); ::css::i18n::Boundary retrieveParagraphLineBoundary( ParagraphImpl const * pParagraph, ::sal_Int32 nIndex ); ::css::uno::Reference< ::css::accessibility::XAccessibleRelationSet > retrieveParagraphRelationSet( ParagraphImpl const * pParagraph ); protected: // window event listener from base class virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ); private: virtual ::sal_Int32 SAL_CALL getAccessibleChildCount() throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessible > SAL_CALL getAccessibleChild(::sal_Int32 i) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Int16 SAL_CALL getAccessibleRole() throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint(::css::awt::Point const & rPoint) throw (::css::uno::RuntimeException); // ??? Will be called with both the external (Solar) and internal mutex // locked: virtual void SAL_CALL disposing(); // ??? Will be called with the external (Solar) mutex locked. // init will already have been called. virtual void Notify(::SfxBroadcaster & rBC, ::SfxHint const & rHint); // Assuming that this will only be called with the external (Solar) mutex // locked. // init will already have been called. DECL_LINK(WindowEventHandler, VclSimpleEvent *); // Must be called with both the external (Solar) and internal mutex // locked. void init(); // Must be called with both the external (Solar) and internal mutex // locked, and after init has been called: ::rtl::Reference< ParagraphImpl > getParagraph(Paragraphs::iterator const & rIt); // Must be called with both the external (Solar) and internal mutex // locked, and after init has been called. // Throws ::css::uno::RuntimeException. ::css::uno::Reference< ::css::accessibility::XAccessible > getAccessibleChild(Paragraphs::iterator const & rIt); // Must be called with both the external (Solar) and internal mutex // locked, and after init has been called: void determineVisibleRange(); // Must be called with both the external (Solar) and internal mutex // locked, and after init has been called: void notifyVisibleRangeChanges( Paragraphs::iterator const & rOldVisibleBegin, Paragraphs::iterator const & rOldVisibleEnd, Paragraphs::iterator const & rInserted); // Must be called with both the external (Solar) and internal mutex // locked, and after init has been called: void changeParagraphText(::ULONG nNumber, ::USHORT nBegin, ::USHORT nEnd, bool bCut, bool bPaste, ::rtl::OUString const & rText); void handleParagraphNotifications(); void handleSelectionChangeNotification(); void notifySelectionChange( sal_Int32 nFirst, sal_Int32 nLast ); void justifySelection( TextPaM& rTextStart, TextPaM& rTextEnd ); void disposeParagraphs(); static ::css::uno::Any mapFontColor(::Color const & rColor); static ::Color mapFontColor(::css::uno::Any const & rColor); static ::css::uno::Any mapFontWeight(::FontWeight nWeight); static ::FontWeight mapFontWeight(::css::uno::Any const & rWeight); void retrieveDefaultAttributesImpl( ParagraphImpl const * pParagraph, const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes, tPropValMap& rDefAttrSeq); void retrieveRunAttributesImpl( ParagraphImpl const * pParagraph, ::sal_Int32 Index, const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes, tPropValMap& rRunAttrSeq); static ::css::uno::Sequence< ::css::beans::PropertyValue > convertHashMapToSequence(tPropValMap& rAttrSeq); ::css::uno::Reference< ::css::accessibility::XAccessible > m_xAccessible; ::TextEngine & m_rEngine; ::TextView & m_rView; SfxListenerGuard m_aEngineListener; WindowListenerGuard m_aViewListener; // All the following members have valid values only after calling init: ::std::auto_ptr< Paragraphs > m_xParagraphs; // m_nViewOffset is from the start of the document (0) to the start of the // current view, and m_nViewHeight is the height of the view: ::sal_Int32 m_nViewOffset; ::sal_Int32 m_nViewHeight; // m_aVisibleBegin points to the first Paragraph that is (partially) // contained in the view, and m_aVisibleEnd points past the last Paragraph // that is (partially) contained. If no Paragraphs are (partially) in the // view, both m_aVisibleBegin and m_aVisibleEnd are set to // m_xParagraphs->end(). These values are only changed by // determineVisibleRange. Paragraphs::iterator m_aVisibleBegin; Paragraphs::iterator m_aVisibleEnd; // m_nVisibleBeginOffset is from m_nViewOffset back to the start of the // Paragraph pointed to by m_aVisibleBegin (and always has a non-negative // value). If m_aVisibleBegin == m_xParagraphs->end(), // m_nVisibleBeginOffset is set to 0. These values are only changed by // determineVisibleRange. ::sal_Int32 m_nVisibleBeginOffset; // If no selection has yet been set, all the following four variables are // set to -1. m_nSelectionLastPara/Pos is also the cursor position. ::sal_Int32 m_nSelectionFirstPara; ::sal_Int32 m_nSelectionFirstPos; ::sal_Int32 m_nSelectionLastPara; ::sal_Int32 m_nSelectionLastPos; Paragraphs::iterator m_aFocused; ::std::queue< ::TextHint > m_aParagraphNotifications; bool m_bSelectionChangedNotification; bool m_bCompoundControlChild; }; } #endif // INCLUDED_ACCESSIBILITY_TEXTWINDOWACCESSIBILITY_HXX INTEGRATION: CWS changefileheader (1.4.10); FILE MERGED 2008/04/01 14:58:48 thb 1.4.10.3: #i85898# Stripping all external header guards 2008/04/01 10:45:12 thb 1.4.10.2: #i85898# Stripping all external header guards 2008/03/28 15:57:42 rt 1.4.10.1: #i87441# Change license header to LPGL v3. /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textwindowaccessibility.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #if !defined INCLUDED_ACCESSIBILITY_TEXTWINDOWACCESSIBILITY_HXX #define INCLUDED_ACCESSIBILITY_TEXTWINDOWACCESSIBILITY_HXX #include <toolkit/awt/vclxaccessiblecomponent.hxx> #include <svtools/lstner.hxx> #include <svtools/textdata.hxx> #include <svtools/texteng.hxx> #include <svtools/textview.hxx> #include <svtools/txtattr.hxx> #include <com/sun/star/awt/FontWeight.hpp> #include <com/sun/star/lang/EventObject.hpp> #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/util/Color.hpp> #include <com/sun/star/accessibility/AccessibleEventId.hpp> #include <com/sun/star/accessibility/AccessibleRelationType.hpp> #include <com/sun/star/accessibility/AccessibleRole.hpp> #include <com/sun/star/accessibility/AccessibleStateType.hpp> #include <com/sun/star/accessibility/AccessibleTextType.hpp> #include <com/sun/star/accessibility/XAccessible.hpp> #include <com/sun/star/accessibility/XAccessibleContext.hpp> #include <com/sun/star/accessibility/XAccessibleEditableText.hpp> #include <com/sun/star/accessibility/XAccessibleTextAttributes.hpp> #include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #include <com/sun/star/accessibility/XAccessibleComponent.hpp> #include <toolkit/awt/vclxwindow.hxx> #include <cppuhelper/compbase6.hxx> #include <comphelper/accessiblecontexthelper.hxx> #include <comphelper/accessibletexthelper.hxx> #include <rtl/ref.hxx> #include <memory> #include <queue> #include <hash_map> class TextEngine; class TextView; namespace css = ::com::sun::star; namespace accessibility { class Paragraph; class Document; class SfxListenerGuard { public: inline SfxListenerGuard(::SfxListener & rListener): m_rListener(rListener), m_pNotifier(0) {} inline ~SfxListenerGuard() { endListening(); } // Not thread safe: void startListening(::SfxBroadcaster & rNotifier); // Not thread safe: void endListening(); private: ::SfxListener & m_rListener; ::SfxBroadcaster * m_pNotifier; }; class WindowListenerGuard { public: inline WindowListenerGuard(::Link const & rListener): m_aListener(rListener), m_pNotifier(0) {} inline ~WindowListenerGuard() { endListening(); } // Not thread safe: void startListening(::Window & rNotifier); // Not thread safe: void endListening(); private: ::Link m_aListener; ::Window * m_pNotifier; }; class ParagraphInfo { public: inline ParagraphInfo(::sal_Int32 nHeight): m_nHeight(nHeight) {} inline ::css::uno::WeakReference< ::css::accessibility::XAccessible > const & getParagraph() const { return m_xParagraph; } inline ::sal_Int32 getHeight() const { return m_nHeight; } inline void setParagraph( ::css::uno::Reference< ::css::accessibility::XAccessible > const & rParagraph) { m_xParagraph = rParagraph; } inline void changeHeight(::sal_Int32 nHeight) { m_nHeight = nHeight; } private: ::css::uno::WeakReference< ::css::accessibility::XAccessible > m_xParagraph; ::sal_Int32 m_nHeight; }; typedef ::std::vector< ParagraphInfo > Paragraphs; typedef ::cppu::WeakAggComponentImplHelper6< ::css::accessibility::XAccessible, ::css::accessibility::XAccessibleContext, ::css::accessibility::XAccessibleComponent, ::css::accessibility::XAccessibleEditableText, ::css::accessibility::XAccessibleTextAttributes, ::css::accessibility::XAccessibleEventBroadcaster > ParagraphBase; // The Paragraph's number is the absolute position within the text engine (from // 0 to N - 1), whereas the Paragraph's index is the position within the text // view/accessible parent (from 0 to M - 1). Paragraphs outside the currently // visible range have an index of -1. class ParagraphImpl: public ParagraphBase, private ::comphelper::OCommonAccessibleText { public: ParagraphImpl(::rtl::Reference< Document > const & rDocument, Paragraphs::size_type nNumber, ::osl::Mutex & rMutex); // Not thread-safe. inline Paragraphs::size_type getNumber() const { return m_nNumber; } // Not thread-safe. void numberChanged(bool bIncremented); // Not thread-safe. void textChanged(); // Thread-safe. void notifyEvent(::sal_Int16 nEventId, ::css::uno::Any const & rOldValue, ::css::uno::Any const & rNewValue); protected: // OCommonAccessibleText virtual void implGetParagraphBoundary( ::css::i18n::Boundary& rBoundary, ::sal_Int32 nIndex ); virtual void implGetLineBoundary( ::css::i18n::Boundary& rBoundary, ::sal_Int32 nIndex ); private: virtual ::css::uno::Reference< ::css::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getAccessibleChildCount() throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessible > SAL_CALL getAccessibleChild(::sal_Int32 i) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessible > SAL_CALL getAccessibleParent() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getAccessibleIndexInParent() throw (::css::uno::RuntimeException); virtual ::sal_Int16 SAL_CALL getAccessibleRole() throw (::css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getAccessibleDescription() throw (::css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getAccessibleName() throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet() throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet() throw (::css::uno::RuntimeException); virtual ::css::lang::Locale SAL_CALL getLocale() throw (::css::accessibility::IllegalAccessibleComponentStateException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL containsPoint(::css::awt::Point const & rPoint) throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint(::css::awt::Point const & rPoint) throw (::css::uno::RuntimeException); virtual ::css::awt::Rectangle SAL_CALL getBounds() throw (::css::uno::RuntimeException); virtual ::css::awt::Point SAL_CALL getLocation() throw (::css::uno::RuntimeException); virtual ::css::awt::Point SAL_CALL getLocationOnScreen() throw (::css::uno::RuntimeException); virtual ::css::awt::Size SAL_CALL getSize() throw (::css::uno::RuntimeException); virtual void SAL_CALL grabFocus() throw (::css::uno::RuntimeException); virtual ::css::uno::Any SAL_CALL getAccessibleKeyBinding() throw (::css::uno::RuntimeException); virtual ::css::util::Color SAL_CALL getForeground() throw (::css::uno::RuntimeException); virtual ::css::util::Color SAL_CALL getBackground() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getCaretPosition() throw (::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL setCaretPosition(::sal_Int32 nIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Unicode SAL_CALL getCharacter(::sal_Int32 nIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::css::uno::Sequence< ::css::beans::PropertyValue > SAL_CALL getCharacterAttributes(::sal_Int32 nIndex, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aRequestedAttributes ) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::css::awt::Rectangle SAL_CALL getCharacterBounds(::sal_Int32 nIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getCharacterCount() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getIndexAtPoint(::css::awt::Point const & rPoint) throw (::css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getSelectedText() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getSelectionStart() throw (::css::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getSelectionEnd() throw (::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL setSelection(::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getText() throw (::css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getTextRange(::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::com::sun::star::accessibility::TextSegment SAL_CALL getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::accessibility::TextSegment SAL_CALL getTextBeforeIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::accessibility::TextSegment SAL_CALL getTextBehindIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL copyText(::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL cutText(::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL pasteText(::sal_Int32 nIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL deleteText(::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL insertText(::rtl::OUString const & rText, ::sal_Int32 nIndex) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL replaceText( ::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex, ::rtl::OUString const & rReplacement) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL setAttributes( ::sal_Int32 nStartIndex, ::sal_Int32 nEndIndex, ::css::uno::Sequence< ::css::beans::PropertyValue > const & rAttributeSet) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Bool SAL_CALL setText(::rtl::OUString const & rText) throw (::css::uno::RuntimeException); virtual ::css::uno::Sequence< ::css::beans::PropertyValue > SAL_CALL getDefaultAttributes(const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes) throw (::css::uno::RuntimeException); virtual ::css::uno::Sequence< ::css::beans::PropertyValue > SAL_CALL getRunAttributes(::sal_Int32 Index, const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); using cppu::WeakAggComponentImplHelperBase::addEventListener; virtual void SAL_CALL addEventListener( ::css::uno::Reference< ::css::accessibility::XAccessibleEventListener > const & rListener) throw (::css::uno::RuntimeException); using cppu::WeakAggComponentImplHelperBase::removeEventListener; virtual void SAL_CALL removeEventListener( ::css::uno::Reference< ::css::accessibility::XAccessibleEventListener > const & rListener) throw (::css::uno::RuntimeException); virtual void SAL_CALL disposing(); virtual ::rtl::OUString implGetText(); virtual ::css::lang::Locale implGetLocale(); virtual void implGetSelection(::sal_Int32 & rStartIndex, ::sal_Int32 & rEndIndex); // Throws ::css::lang::DisposedException: void checkDisposed(); ::rtl::Reference< Document > m_xDocument; Paragraphs::size_type m_nNumber; // ::cppu::OInterfaceContainerHelper m_aListeners; /// client id in the AccessibleEventNotifier queue sal_uInt32 m_nClientId; ::rtl::OUString m_aParagraphText; }; typedef ::std::hash_map< ::rtl::OUString, ::css::beans::PropertyValue, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > tPropValMap; class Document: public ::VCLXAccessibleComponent, public ::SfxListener { public: Document(::VCLXWindow * pVclXWindow, ::TextEngine & rEngine, ::TextView & rView, bool bCompoundControlChild); inline ::css::uno::Reference< ::css::accessibility::XAccessible > getAccessible() { return m_xAccessible; } // Must be called only after init has been called. ::css::lang::Locale retrieveLocale(); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const *" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::sal_Int32 retrieveParagraphIndex(ParagraphImpl const * pParagraph); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const *" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::sal_Int64 retrieveParagraphState(ParagraphImpl const * pParagraph); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::css::awt::Rectangle retrieveParagraphBounds(ParagraphImpl const * pParagraph, bool bAbsolute); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::rtl::OUString retrieveParagraphText(ParagraphImpl const * pParagraph); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". void retrieveParagraphSelection(ParagraphImpl const * pParagraph, ::sal_Int32 * pBegin, ::sal_Int32 * pEnd); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const *" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::sal_Int32 retrieveParagraphCaretPosition(ParagraphImpl const * pParagraph); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. ::css::awt::Rectangle retrieveCharacterBounds(ParagraphImpl const * pParagraph, ::sal_Int32 nIndex); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::sal_Int32 retrieveCharacterIndex(ParagraphImpl const * pParagraph, ::css::awt::Point const & rPoint); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. ::css::uno::Sequence< ::css::beans::PropertyValue > retrieveCharacterAttributes( ParagraphImpl const * pParagraph, ::sal_Int32 nIndex, const ::css::uno::Sequence< ::rtl::OUString >& aRequestedAttributes); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". ::css::uno::Sequence< ::css::beans::PropertyValue > retrieveDefaultAttributes( ParagraphImpl const * pParagraph, const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. ::css::uno::Sequence< ::css::beans::PropertyValue > retrieveRunAttributes( ParagraphImpl const * pParagraph, ::sal_Int32 Index, const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". void changeParagraphText(ParagraphImpl * pParagraph, ::rtl::OUString const & rText); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. void changeParagraphText(ParagraphImpl * pParagraph, ::sal_Int32 nBegin, ::sal_Int32 nEnd, bool bCut, bool bPaste, ::rtl::OUString const & rText); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. void copyParagraphText(ParagraphImpl const * pParagraph, ::sal_Int32 nBegin, ::sal_Int32 nEnd); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. void changeParagraphAttributes( ParagraphImpl * pParagraph, ::sal_Int32 nBegin, ::sal_Int32 nEnd, ::css::uno::Sequence< ::css::beans::PropertyValue > const & rAttributeSet); // Must be called only after init has been called. // To make it possible for this method to be (indirectly) called from // within Paragraph's constructor (i.e., when the Paragraph's ref count is // still zero), pass a "ParagraphImpl const &" instead of a // "::rtl::Reference< ParagraphImpl > const &". // Throws ::css::lang::IndexOutOfBoundsException. void changeParagraphSelection(ParagraphImpl * pParagraph, ::sal_Int32 nBegin, ::sal_Int32 nEnd); ::css::i18n::Boundary retrieveParagraphLineBoundary( ParagraphImpl const * pParagraph, ::sal_Int32 nIndex ); ::css::uno::Reference< ::css::accessibility::XAccessibleRelationSet > retrieveParagraphRelationSet( ParagraphImpl const * pParagraph ); protected: // window event listener from base class virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ); private: virtual ::sal_Int32 SAL_CALL getAccessibleChildCount() throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessible > SAL_CALL getAccessibleChild(::sal_Int32 i) throw (::css::lang::IndexOutOfBoundsException, ::css::uno::RuntimeException); virtual ::sal_Int16 SAL_CALL getAccessibleRole() throw (::css::uno::RuntimeException); virtual ::css::uno::Reference< ::css::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint(::css::awt::Point const & rPoint) throw (::css::uno::RuntimeException); // ??? Will be called with both the external (Solar) and internal mutex // locked: virtual void SAL_CALL disposing(); // ??? Will be called with the external (Solar) mutex locked. // init will already have been called. virtual void Notify(::SfxBroadcaster & rBC, ::SfxHint const & rHint); // Assuming that this will only be called with the external (Solar) mutex // locked. // init will already have been called. DECL_LINK(WindowEventHandler, VclSimpleEvent *); // Must be called with both the external (Solar) and internal mutex // locked. void init(); // Must be called with both the external (Solar) and internal mutex // locked, and after init has been called: ::rtl::Reference< ParagraphImpl > getParagraph(Paragraphs::iterator const & rIt); // Must be called with both the external (Solar) and internal mutex // locked, and after init has been called. // Throws ::css::uno::RuntimeException. ::css::uno::Reference< ::css::accessibility::XAccessible > getAccessibleChild(Paragraphs::iterator const & rIt); // Must be called with both the external (Solar) and internal mutex // locked, and after init has been called: void determineVisibleRange(); // Must be called with both the external (Solar) and internal mutex // locked, and after init has been called: void notifyVisibleRangeChanges( Paragraphs::iterator const & rOldVisibleBegin, Paragraphs::iterator const & rOldVisibleEnd, Paragraphs::iterator const & rInserted); // Must be called with both the external (Solar) and internal mutex // locked, and after init has been called: void changeParagraphText(::ULONG nNumber, ::USHORT nBegin, ::USHORT nEnd, bool bCut, bool bPaste, ::rtl::OUString const & rText); void handleParagraphNotifications(); void handleSelectionChangeNotification(); void notifySelectionChange( sal_Int32 nFirst, sal_Int32 nLast ); void justifySelection( TextPaM& rTextStart, TextPaM& rTextEnd ); void disposeParagraphs(); static ::css::uno::Any mapFontColor(::Color const & rColor); static ::Color mapFontColor(::css::uno::Any const & rColor); static ::css::uno::Any mapFontWeight(::FontWeight nWeight); static ::FontWeight mapFontWeight(::css::uno::Any const & rWeight); void retrieveDefaultAttributesImpl( ParagraphImpl const * pParagraph, const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes, tPropValMap& rDefAttrSeq); void retrieveRunAttributesImpl( ParagraphImpl const * pParagraph, ::sal_Int32 Index, const ::css::uno::Sequence< ::rtl::OUString >& RequestedAttributes, tPropValMap& rRunAttrSeq); static ::css::uno::Sequence< ::css::beans::PropertyValue > convertHashMapToSequence(tPropValMap& rAttrSeq); ::css::uno::Reference< ::css::accessibility::XAccessible > m_xAccessible; ::TextEngine & m_rEngine; ::TextView & m_rView; SfxListenerGuard m_aEngineListener; WindowListenerGuard m_aViewListener; // All the following members have valid values only after calling init: ::std::auto_ptr< Paragraphs > m_xParagraphs; // m_nViewOffset is from the start of the document (0) to the start of the // current view, and m_nViewHeight is the height of the view: ::sal_Int32 m_nViewOffset; ::sal_Int32 m_nViewHeight; // m_aVisibleBegin points to the first Paragraph that is (partially) // contained in the view, and m_aVisibleEnd points past the last Paragraph // that is (partially) contained. If no Paragraphs are (partially) in the // view, both m_aVisibleBegin and m_aVisibleEnd are set to // m_xParagraphs->end(). These values are only changed by // determineVisibleRange. Paragraphs::iterator m_aVisibleBegin; Paragraphs::iterator m_aVisibleEnd; // m_nVisibleBeginOffset is from m_nViewOffset back to the start of the // Paragraph pointed to by m_aVisibleBegin (and always has a non-negative // value). If m_aVisibleBegin == m_xParagraphs->end(), // m_nVisibleBeginOffset is set to 0. These values are only changed by // determineVisibleRange. ::sal_Int32 m_nVisibleBeginOffset; // If no selection has yet been set, all the following four variables are // set to -1. m_nSelectionLastPara/Pos is also the cursor position. ::sal_Int32 m_nSelectionFirstPara; ::sal_Int32 m_nSelectionFirstPos; ::sal_Int32 m_nSelectionLastPara; ::sal_Int32 m_nSelectionLastPos; Paragraphs::iterator m_aFocused; ::std::queue< ::TextHint > m_aParagraphNotifications; bool m_bSelectionChangedNotification; bool m_bCompoundControlChild; }; } #endif // INCLUDED_ACCESSIBILITY_TEXTWINDOWACCESSIBILITY_HXX
// @(#)root/proof:$Id$ // Author: Fons Rademakers 13/02/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TProof // // // // This class controls a Parallel ROOT Facility, PROOF, cluster. // // It fires the worker servers, it keeps track of how many workers are // // running, it keeps track of the workers running status, it broadcasts // // messages to all workers, it collects results, etc. // // // ////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <fcntl.h> #include <errno.h> #ifdef WIN32 # include <io.h> # include <sys/stat.h> # include <sys/types.h> # include "snprintf.h" #else # include <unistd.h> #endif #include <vector> #include "RConfigure.h" #include "Riostream.h" #include "Getline.h" #include "TBrowser.h" #include "TChain.h" #include "TCondor.h" #include "TDSet.h" #include "TError.h" #include "TEnv.h" #include "TEntryList.h" #include "TEventList.h" #include "TFile.h" #include "TFileInfo.h" #include "TFTP.h" #include "THashList.h" #include "TInterpreter.h" #include "TKey.h" #include "TMap.h" #include "TMath.h" #include "TMessage.h" #include "TMonitor.h" #include "TMutex.h" #include "TObjArray.h" #include "TObjString.h" #include "TParameter.h" #include "TProof.h" #include "TProofNodeInfo.h" #include "TVirtualProofPlayer.h" #include "TVirtualPacketizer.h" #include "TProofServ.h" #include "TPluginManager.h" #include "TQueryResult.h" #include "TRandom.h" #include "TRegexp.h" #include "TROOT.h" #include "TSemaphore.h" #include "TSlave.h" #include "TSocket.h" #include "TSortedList.h" #include "TSystem.h" #include "TThread.h" #include "TTree.h" #include "TUrl.h" #include "TFileCollection.h" #include "TDataSetManager.h" #include "TMacro.h" TProof *gProof = 0; TVirtualMutex *gProofMutex = 0; // Rotating indicator char TProofMergePrg::fgCr[4] = {'-', '\\', '|', '/'}; TList *TProof::fgProofEnvList = 0; // List of env vars for proofserv TPluginHandler *TProof::fgLogViewer = 0; // Log viewer handler ClassImp(TProof) //----- PROOF Interrupt signal handler ----------------------------------------- //______________________________________________________________________________ Bool_t TProofInterruptHandler::Notify() { // TProof interrupt handler. if (isatty(0) == 0 || isatty(1) == 0 || fProof->GetRemoteProtocol() < 22) { // Cannot ask the user : abort any remote processing fProof->StopProcess(kTRUE); } else { // Real stop or request to switch to asynchronous? char *a = 0; if (fProof->GetRemoteProtocol() < 22) { a = Getline("\nSwith to asynchronous mode not supported remotely:" "\nEnter S/s to stop, Q/q to quit, any other key to continue: "); } else { a = Getline("\nEnter A/a to switch asynchronous, S/s to stop, Q/q to quit," " any other key to continue: "); } if (a[0] == 'Q' || a[0] == 'S' || a[0] == 'q' || a[0] == 's') { Info("Notify","Processing interrupt signal ... %c", a[0]); // Stop or abort any remote processing Bool_t abort = (a[0] == 'Q' || a[0] == 'q') ? kTRUE : kFALSE; fProof->StopProcess(abort); } else if ((a[0] == 'A' || a[0] == 'a') && fProof->GetRemoteProtocol() >= 22) { // Stop any remote processing fProof->GoAsynchronous(); } } return kTRUE; } //----- Input handler for messages from TProofServ ----------------------------- //______________________________________________________________________________ TProofInputHandler::TProofInputHandler(TProof *p, TSocket *s) : TFileHandler(s->GetDescriptor(),1), fSocket(s), fProof(p) { // Constructor } //______________________________________________________________________________ Bool_t TProofInputHandler::Notify() { // Handle input fProof->CollectInputFrom(fSocket); return kTRUE; } //------------------------------------------------------------------------------ ClassImp(TSlaveInfo) //______________________________________________________________________________ Int_t TSlaveInfo::Compare(const TObject *obj) const { // Used to sort slaveinfos by ordinal. if (!obj) return 1; const TSlaveInfo *si = dynamic_cast<const TSlaveInfo*>(obj); if (!si) return fOrdinal.CompareTo(obj->GetName()); const char *myord = GetOrdinal(); const char *otherord = si->GetOrdinal(); while (myord && otherord) { Int_t myval = atoi(myord); Int_t otherval = atoi(otherord); if (myval < otherval) return 1; if (myval > otherval) return -1; myord = strchr(myord, '.'); if (myord) myord++; otherord = strchr(otherord, '.'); if (otherord) otherord++; } if (myord) return -1; if (otherord) return 1; return 0; } //______________________________________________________________________________ void TSlaveInfo::Print(Option_t *opt) const { // Print slave info. If opt = "active" print only the active // slaves, if opt="notactive" print only the not active slaves, // if opt = "bad" print only the bad slaves, else // print all slaves. TString stat = fStatus == kActive ? "active" : fStatus == kBad ? "bad" : "not active"; Bool_t newfmt = kFALSE; TString oo(opt); if (oo.Contains("N")) { newfmt = kTRUE; oo.ReplaceAll("N",""); } if (oo == "active" && fStatus != kActive) return; if (oo == "notactive" && fStatus != kNotActive) return; if (oo == "bad" && fStatus != kBad) return; if (newfmt) { TString msd, si; if (!(fMsd.IsNull())) msd.Form("| msd: %s ", fMsd.Data()); if (fSysInfo.fCpus > 0) { si.Form("| %s, %d cores, %d MB ram", fHostName.Data(), fSysInfo.fCpus, fSysInfo.fPhysRam); } else { si.Form("| %s", fHostName.Data()); } Printf("Worker: %9s %s %s| %s", fOrdinal.Data(), si.Data(), msd.Data(), stat.Data()); } else { TString msd = fMsd.IsNull() ? "<null>" : fMsd.Data(); cout << "Slave: " << fOrdinal << " hostname: " << fHostName << " msd: " << msd << " perf index: " << fPerfIndex << " " << stat << endl; } } //______________________________________________________________________________ void TSlaveInfo::SetSysInfo(SysInfo_t si) { // Setter for fSysInfo fSysInfo.fOS = si.fOS; // OS fSysInfo.fModel = si.fModel; // computer model fSysInfo.fCpuType = si.fCpuType; // type of cpu fSysInfo.fCpus = si.fCpus; // number of cpus fSysInfo.fCpuSpeed = si.fCpuSpeed; // cpu speed in MHz fSysInfo.fBusSpeed = si.fBusSpeed; // bus speed in MHz fSysInfo.fL2Cache = si.fL2Cache; // level 2 cache size in KB fSysInfo.fPhysRam = si.fPhysRam; // Physical RAM } //------------------------------------------------------------------------------ //______________________________________________________________________________ static char *CollapseSlashesInPath(const char *path) { // Get rid of spare slashes in a path. Returned path must be deleted[] // by the user. if (path) { Int_t i = 1; // current index as we go along the string Int_t j = 0; // current end of new path in newPath char *newPath = new char [strlen(path) + 1]; newPath[0] = path[0]; while (path[i]) { if (path[i] != '/' || newPath[j] != '/') { j++; newPath[j] = path[i]; } i++; } if (newPath[j] != '/') j++; newPath[j] = 0; // We have to terminate the new path. return newPath; } return 0; } ClassImp(TProof) TSemaphore *TProof::fgSemaphore = 0; //------------------------------------------------------------------------------ //______________________________________________________________________________ TMergerInfo::~TMergerInfo() { // Destructor // Just delete the list, the objects are owned by other list if (fWorkers) { fWorkers->SetOwner(kFALSE); SafeDelete(fWorkers); } } //______________________________________________________________________________ void TMergerInfo::SetMergedWorker() { // Increase number of already merged workers by 1 if (AreAllWorkersMerged()) Error("SetMergedWorker", "all workers have been already merged before!"); else fMergedWorkers++; } //______________________________________________________________________________ void TMergerInfo::AddWorker(TSlave *sl) { // Add new worker to the list of workers to be merged by this merger if (!fWorkers) fWorkers = new TList(); if (fWorkersToMerge == fWorkers->GetSize()) { Error("AddWorker", "all workers have been already assigned to this merger"); return; } fWorkers->Add(sl); } //______________________________________________________________________________ Bool_t TMergerInfo::AreAllWorkersMerged() { // Return if merger has already merged all workers, i.e. if it has finished its merging job return (fWorkersToMerge == fMergedWorkers); } //______________________________________________________________________________ Bool_t TMergerInfo::AreAllWorkersAssigned() { // Return if the determined number of workers has been already assigned to this merger if (!fWorkers) return kFALSE; return (fWorkers->GetSize() == fWorkersToMerge); } //------------------------------------------------------------------------------ TProof::TProof(const char *masterurl, const char *conffile, const char *confdir, Int_t loglevel, const char *alias, TProofMgr *mgr) : fUrl(masterurl) { // Create a PROOF environment. Starting PROOF involves either connecting // to a master server, which in turn will start a set of slave servers, or // directly starting as master server (if master = ""). Masterurl is of // the form: [proof[s]://]host[:port]. Conffile is the name of the config // file describing the remote PROOF cluster (this argument alows you to // describe different cluster configurations). // The default is proof.conf. Confdir is the directory where the config // file and other PROOF related files are (like motd and noproof files). // Loglevel is the log level (default = 1). User specified custom config // files will be first looked for in $HOME/.conffile. // Default initializations InitMembers(); // This may be needed during init fManager = mgr; // Default server type fServType = TProofMgr::kXProofd; // Default query mode fQueryMode = kSync; // Parse the main URL, adjusting the missing fields and setting the relevant // bits ResetBit(TProof::kIsClient); ResetBit(TProof::kIsMaster); // Protocol and Host if (!masterurl || strlen(masterurl) <= 0) { fUrl.SetProtocol("proof"); fUrl.SetHost("__master__"); } else if (!(strstr(masterurl, "://"))) { fUrl.SetProtocol("proof"); } // Port if (fUrl.GetPort() == TUrl(" ").GetPort()) fUrl.SetPort(TUrl("proof:// ").GetPort()); // User if (strlen(fUrl.GetUser()) <= 0) { // Get user logon name UserGroup_t *pw = gSystem->GetUserInfo(); if (pw) { fUrl.SetUser(pw->fUser); delete pw; } } // Make sure to store the FQDN, so to get a solid reference for subsequent checks if (!strcmp(fUrl.GetHost(), "__master__")) fMaster = fUrl.GetHost(); else if (!strlen(fUrl.GetHost())) fMaster = gSystem->GetHostByName(gSystem->HostName()).GetHostName(); else fMaster = gSystem->GetHostByName(fUrl.GetHost()).GetHostName(); // Server type if (strlen(fUrl.GetOptions()) > 0) { TString opts(fUrl.GetOptions()); if (!(strncmp(fUrl.GetOptions(),"std",3))) { fServType = TProofMgr::kProofd; opts.Remove(0,3); fUrl.SetOptions(opts.Data()); } else if (!(strncmp(fUrl.GetOptions(),"lite",4))) { fServType = TProofMgr::kProofLite; opts.Remove(0,4); fUrl.SetOptions(opts.Data()); } } // Instance type fMasterServ = kFALSE; SetBit(TProof::kIsClient); ResetBit(TProof::kIsMaster); if (fMaster == "__master__") { fMasterServ = kTRUE; ResetBit(TProof::kIsClient); SetBit(TProof::kIsMaster); } else if (fMaster == "prooflite") { // Client and master are merged fMasterServ = kTRUE; SetBit(TProof::kIsMaster); } Init(masterurl, conffile, confdir, loglevel, alias); // If called by a manager, make sure it stays in last position // for cleaning if (mgr) { R__LOCKGUARD2(gROOTMutex); gROOT->GetListOfSockets()->Remove(mgr); gROOT->GetListOfSockets()->Add(mgr); } // Old-style server type: we add this to the list and set the global pointer if (IsProofd() || TestBit(TProof::kIsMaster)) if (!gROOT->GetListOfProofs()->FindObject(this)) gROOT->GetListOfProofs()->Add(this); // Still needed by the packetizers: needs to be changed gProof = this; } //______________________________________________________________________________ TProof::TProof() : fUrl(""), fServType(TProofMgr::kXProofd) { // Protected constructor to be used by classes deriving from TProof // (they have to call Init themselves and override StartSlaves // appropriately). // // This constructor simply closes any previous gProof and sets gProof // to this instance. // Default initializations InitMembers(); if (!gROOT->GetListOfProofs()->FindObject(this)) gROOT->GetListOfProofs()->Add(this); gProof = this; } //______________________________________________________________________________ void TProof::InitMembers() { // Default initializations fValid = kFALSE; fRecvMessages = 0; fSlaveInfo = 0; fMasterServ = kFALSE; fSendGroupView = kFALSE; fActiveSlaves = 0; fInactiveSlaves = 0; fUniqueSlaves = 0; fAllUniqueSlaves = 0; fNonUniqueMasters = 0; fActiveMonitor = 0; fUniqueMonitor = 0; fAllUniqueMonitor = 0; fCurrentMonitor = 0; fBytesRead = 0; fRealTime = 0; fCpuTime = 0; fIntHandler = 0; fProgressDialog = 0; fProgressDialogStarted = kFALSE; SetBit(kUseProgressDialog); fPlayer = 0; fFeedback = 0; fChains = 0; fDSet = 0; fNotIdle = 0; fSync = kTRUE; fRunStatus = kRunning; fIsWaiting = kFALSE; fRedirLog = kFALSE; fLogFileW = 0; fLogFileR = 0; fLogToWindowOnly = kFALSE; fWaitingSlaves = 0; fQueries = 0; fOtherQueries = 0; fDrawQueries = 0; fMaxDrawQueries = 1; fSeqNum = 0; fSessionID = -1; fEndMaster = kFALSE; fGlobalPackageDirList = 0; fPackageLock = 0; fEnabledPackagesOnClient = 0; fInputData = 0; fPrintProgress = 0; fLoadedMacros = 0; fProtocol = -1; fSlaves = 0; fBadSlaves = 0; fAllMonitor = 0; fDataReady = kFALSE; fBytesReady = 0; fTotalBytes = 0; fAvailablePackages = 0; fEnabledPackages = 0; fRunningDSets = 0; fCollectTimeout = -1; fManager = 0; fQueryMode = kSync; fDynamicStartup = kFALSE; fCloseMutex = 0; fMergersSet = kFALSE; fMergers = 0; fMergersCount = -1; fLastAssignedMerger = 0; fWorkersToMerge = 0; fFinalizationRunning = kFALSE; // Done return; } //______________________________________________________________________________ TProof::~TProof() { // Clean up PROOF environment. if (fChains) { while (TChain *chain = dynamic_cast<TChain*> (fChains->First()) ) { // remove "chain" from list chain->SetProof(0); RemoveChain(chain); } } // remove links to packages enabled on the client if (TestBit(TProof::kIsClient)) { // iterate over all packages TIter nextpackage(fEnabledPackagesOnClient); while (TObjString *package = dynamic_cast<TObjString*>(nextpackage())) { FileStat_t stat; gSystem->GetPathInfo(package->String(), stat); // check if symlink, if so unlink // NOTE: GetPathInfo() returns 1 in case of symlink that does not point to // existing file or to a directory, but if fIsLink is true the symlink exists if (stat.fIsLink) gSystem->Unlink(package->String()); } } Close(); SafeDelete(fIntHandler); SafeDelete(fSlaves); SafeDelete(fActiveSlaves); SafeDelete(fInactiveSlaves); SafeDelete(fUniqueSlaves); SafeDelete(fAllUniqueSlaves); SafeDelete(fNonUniqueMasters); SafeDelete(fBadSlaves); SafeDelete(fAllMonitor); SafeDelete(fActiveMonitor); SafeDelete(fUniqueMonitor); SafeDelete(fAllUniqueMonitor); SafeDelete(fSlaveInfo); SafeDelete(fChains); SafeDelete(fPlayer); SafeDelete(fFeedback); SafeDelete(fWaitingSlaves); SafeDelete(fAvailablePackages); SafeDelete(fEnabledPackages); SafeDelete(fEnabledPackagesOnClient); SafeDelete(fLoadedMacros); SafeDelete(fPackageLock); SafeDelete(fGlobalPackageDirList); SafeDelete(fRecvMessages); SafeDelete(fInputData); SafeDelete(fRunningDSets); SafeDelete(fCloseMutex); // remove file with redirected logs if (TestBit(TProof::kIsClient)) { if (fLogFileR) fclose(fLogFileR); if (fLogFileW) fclose(fLogFileW); if (fLogFileName.Length() > 0) gSystem->Unlink(fLogFileName); } // Remove for the global list gROOT->GetListOfProofs()->Remove(this); // ... and from the manager list if (fManager && fManager->IsValid()) fManager->DiscardSession(this); if (gProof && gProof == this) { // Set previous as default TIter pvp(gROOT->GetListOfProofs(), kIterBackward); while ((gProof = (TProof *)pvp())) { if (gProof->InheritsFrom(TProof::Class())) break; } } // For those interested in our destruction ... Emit("~TProof()"); } //______________________________________________________________________________ Int_t TProof::Init(const char *, const char *conffile, const char *confdir, Int_t loglevel, const char *alias) { // Start the PROOF environment. Starting PROOF involves either connecting // to a master server, which in turn will start a set of slave servers, or // directly starting as master server (if master = ""). For a description // of the arguments see the TProof ctor. Returns the number of started // master or slave servers, returns 0 in case of error, in which case // fValid remains false. R__ASSERT(gSystem); fValid = kFALSE; // If in attach mode, options is filled with additional info Bool_t attach = kFALSE; if (strlen(fUrl.GetOptions()) > 0) { attach = kTRUE; // A flag from the GUI TString opts = fUrl.GetOptions(); if (opts.Contains("GUI")) { SetBit(TProof::kUsingSessionGui); opts.Remove(opts.Index("GUI")); fUrl.SetOptions(opts); } } if (TestBit(TProof::kIsMaster)) { // Fill default conf file and conf dir if (!conffile || strlen(conffile) == 0) fConfFile = kPROOF_ConfFile; if (!confdir || strlen(confdir) == 0) fConfDir = kPROOF_ConfDir; // The group; the client receives it in the kPROOF_SESSIONTAG message if (gProofServ) fGroup = gProofServ->GetGroup(); } else { fConfDir = confdir; fConfFile = conffile; } // Analysise the conffile field ParseConfigField(fConfFile); fWorkDir = gSystem->WorkingDirectory(); fLogLevel = loglevel; fProtocol = kPROOF_Protocol; fSendGroupView = kTRUE; fImage = fMasterServ ? "" : "<local>"; fIntHandler = 0; fStatus = 0; fRecvMessages = new TList; fRecvMessages->SetOwner(kTRUE); fSlaveInfo = 0; fChains = new TList; fAvailablePackages = 0; fEnabledPackages = 0; fRunningDSets = 0; fEndMaster = TestBit(TProof::kIsMaster) ? kTRUE : kFALSE; fInputData = 0; ResetBit(TProof::kNewInputData); fPrintProgress = 0; // Timeout for some collect actions fCollectTimeout = gEnv->GetValue("Proof.CollectTimeout", -1); // Should the workers be started dynamically; default: no fDynamicStartup = gEnv->GetValue("Proof.DynamicStartup", kFALSE); // Default entry point for the data pool is the master if (TestBit(TProof::kIsClient)) fDataPoolUrl.Form("root://%s", fMaster.Data()); else fDataPoolUrl = ""; fProgressDialog = 0; fProgressDialogStarted = kFALSE; // Default alias is the master name TString al = (alias) ? alias : fMaster.Data(); SetAlias(al); // Client logging of messages from the master and slaves fRedirLog = kFALSE; if (TestBit(TProof::kIsClient)) { fLogFileName.Form("%s/ProofLog_%d", gSystem->TempDirectory(), gSystem->GetPid()); if ((fLogFileW = fopen(fLogFileName, "w")) == 0) Error("Init", "could not create temporary logfile"); if ((fLogFileR = fopen(fLogFileName, "r")) == 0) Error("Init", "could not open temp logfile for reading"); } fLogToWindowOnly = kFALSE; // Status of cluster fNotIdle = 0; // Query type fSync = (attach) ? kFALSE : kTRUE; // Not enqueued fIsWaiting = kFALSE; // Counters fBytesRead = 0; fRealTime = 0; fCpuTime = 0; // List of queries fQueries = 0; fOtherQueries = 0; fDrawQueries = 0; fMaxDrawQueries = 1; fSeqNum = 0; // Remote ID of the session fSessionID = -1; // Part of active query fWaitingSlaves = 0; // Make remote PROOF player fPlayer = 0; MakePlayer(); fFeedback = new TList; fFeedback->SetOwner(); fFeedback->SetName("FeedbackList"); AddInput(fFeedback); // sort slaves by descending performance index fSlaves = new TSortedList(kSortDescending); fActiveSlaves = new TList; fInactiveSlaves = new TList; fUniqueSlaves = new TList; fAllUniqueSlaves = new TList; fNonUniqueMasters = new TList; fBadSlaves = new TList; fAllMonitor = new TMonitor; fActiveMonitor = new TMonitor; fUniqueMonitor = new TMonitor; fAllUniqueMonitor = new TMonitor; fCurrentMonitor = 0; fPackageLock = 0; fEnabledPackagesOnClient = 0; fLoadedMacros = 0; fGlobalPackageDirList = 0; // Enable optimized sending of streamer infos to use embedded backward/forward // compatibility support between different ROOT versions and different versions of // users classes Bool_t enableSchemaEvolution = gEnv->GetValue("Proof.SchemaEvolution",1); if (enableSchemaEvolution) { TMessage::EnableSchemaEvolutionForAll(); } else { Info("TProof", "automatic schema evolution in TMessage explicitely disabled"); } if (IsMaster()) { // to make UploadPackage() method work on the master as well. fPackageDir = gProofServ->GetPackageDir(); } else { TString sandbox = gEnv->GetValue("Proof.Sandbox", ""); if (sandbox.IsNull()) { sandbox.Form("~/%s", kPROOF_WorkDir); } gSystem->ExpandPathName(sandbox); if (AssertPath(sandbox, kTRUE) != 0) { Error("Init", "failure asserting directory %s", sandbox.Data()); return 0; } // Package Dir fPackageDir = gEnv->GetValue("Proof.PackageDir", ""); if (fPackageDir.IsNull()) fPackageDir.Form("%s/%s", sandbox.Data(), kPROOF_PackDir); if (AssertPath(fPackageDir, kTRUE) != 0) { Error("Init", "failure asserting directory %s", fPackageDir.Data()); return 0; } } if (!IsMaster()) { // List of directories where to look for global packages TString globpack = gEnv->GetValue("Proof.GlobalPackageDirs",""); if (globpack.Length() > 0) { Int_t ng = 0; Int_t from = 0; TString ldir; while (globpack.Tokenize(ldir, from, ":")) { if (gSystem->AccessPathName(ldir, kReadPermission)) { Warning("Init", "directory for global packages %s does not" " exist or is not readable", ldir.Data()); } else { // Add to the list, key will be "G<ng>", i.e. "G0", "G1", ... TString key = Form("G%d", ng++); if (!fGlobalPackageDirList) { fGlobalPackageDirList = new THashList(); fGlobalPackageDirList->SetOwner(); } fGlobalPackageDirList->Add(new TNamed(key,ldir)); } } } TString lockpath(fPackageDir); lockpath.ReplaceAll("/", "%"); lockpath.Insert(0, Form("%s/%s", gSystem->TempDirectory(), kPROOF_PackageLockFile)); fPackageLock = new TProofLockPath(lockpath.Data()); fEnabledPackagesOnClient = new TList; fEnabledPackagesOnClient->SetOwner(); } // Master may want dynamic startup if (fDynamicStartup) { if (!IsMaster()) { // If on client - start the master if (!StartSlaves(attach)) return 0; } } else { // Master Only mode (for operations requiring only the master, e.g. dataset browsing, // result retrieving, ...) Bool_t masterOnly = gEnv->GetValue("Proof.MasterOnly", kFALSE); if (!IsMaster() || !masterOnly) { // Start slaves (the old, static, per-session way) if (!StartSlaves(attach)) return 0; } } if (fgSemaphore) SafeDelete(fgSemaphore); // we are now properly initialized fValid = kTRUE; // De-activate monitor (will be activated in Collect) fAllMonitor->DeActivateAll(); // By default go into parallel mode GoParallel(9999, attach); // Send relevant initial state to slaves if (!attach) SendInitialState(); else if (!IsIdle()) // redirect log fRedirLog = kTRUE; // Done at this point, the alias will be communicated to the coordinator, if any if (TestBit(TProof::kIsClient)) SetAlias(al); SetActive(kFALSE); if (IsValid()) { // Activate input handler ActivateAsyncInput(); R__LOCKGUARD2(gROOTMutex); gROOT->GetListOfSockets()->Add(this); } return fActiveSlaves->GetSize(); } //______________________________________________________________________________ void TProof::ParseConfigField(const char *config) { // The config file field may contain special instructions which need to be // parsed at the beginning, e.g. for debug runs with valgrind. TString sconf(config); // Analysise the field const char *cq = (IsLite()) ? "\"" : ""; Int_t ivg = kNPOS; if ((ivg = sconf.Index("valgrind")) != kNPOS) { Int_t jvg = sconf.Index(',', ivg); Int_t lvg = (jvg != kNPOS) ? (jvg-ivg) : sconf.Length(); TString vgconf = sconf(ivg, lvg); // Any existing valgrind setting? User can give full settings, which we fully respect, // or pass additional options for valgrind by prefixing 'valgrind_opts:'. For example, // TProof::AddEnvVar("PROOF_MASTER_WRAPPERCMD", "valgrind_opts:--time-stamp --leak-check=full" // will add option "--time-stamp --leak-check=full" to our default options TString mst, wrk, all; TList *envs = fgProofEnvList; TNamed *n = 0; if (envs) { if ((n = (TNamed *) envs->FindObject("PROOF_WRAPPERCMD"))) all = n->GetTitle(); if ((n = (TNamed *) envs->FindObject("PROOF_MASTER_WRAPPERCMD"))) mst = n->GetTitle(); if ((n = (TNamed *) envs->FindObject("PROOF_SLAVE_WRAPPERCMD"))) wrk = n->GetTitle(); } if (all != "" && mst == "") mst = all; if (all != "" && wrk == "") wrk = all; if (all != "" && all.BeginsWith("valgrind_opts:")) { // The field is used to add an option Reset the setting Info("ParseConfigField","valgrind run: resetting 'PROOF_WRAPPERCMD':" " must be set again for next run , if any"); TProof::DelEnvVar("PROOF_WRAPPERCMD"); } TString var, cmd; cmd.Form("%svalgrind -v --suppressions=<rootsys>/etc/valgrind-root.supp", cq); TString mstlab("NO"), wrklab("NO"); if (vgconf == "valgrind" || vgconf.Contains("master")) { if (!IsLite()) { // Check if we have to add a var if (mst == "" || mst.BeginsWith("valgrind_opts:")) { mst.ReplaceAll("valgrind_opts:",""); var.Form("%s --log-file=<logfilemst>.valgrind.log %s", cmd.Data(), mst.Data()); TProof::AddEnvVar("PROOF_MASTER_WRAPPERCMD", var); mstlab = "YES"; } else if (mst != "") { mstlab = "YES"; } } else { if (vgconf.Contains("master")) { Warning("ParseConfigField", "master valgrinding does not make sense for PROOF-Lite: ignoring"); vgconf.ReplaceAll("master", ""); if (!vgconf.Contains("workers")) return; } if (vgconf == "valgrind" || vgconf == "valgrind=") vgconf = "valgrind=workers"; } } if (vgconf.Contains("=workers") || vgconf.Contains("+workers")) { // Check if we have to add a var if (wrk == "" || wrk.BeginsWith("valgrind_opts:")) { wrk.ReplaceAll("valgrind_opts:",""); var.Form("%s --log-file=<logfilewrk>.valgrind.log %s%s", cmd.Data(), wrk.Data(), cq); TProof::AddEnvVar("PROOF_SLAVE_WRAPPERCMD", var); TString nwrks("2"); Int_t inw = vgconf.Index('#'); if (inw != kNPOS) { nwrks = vgconf(inw+1, vgconf.Length()); if (!nwrks.IsDigit()) nwrks = "2"; } // Set the relevant variables if (!IsLite()) { TProof::AddEnvVar("PROOF_NWORKERS", nwrks); } else { gEnv->SetValue("ProofLite.Workers", nwrks.Atoi()); } wrklab = nwrks; // Register the additional worker log in the session file // (for the master is done automatically) TProof::AddEnvVar("PROOF_ADDITIONALLOG", "valgrind.log*"); } else if (wrk != "") { wrklab = "ALL"; } } // Increase the relevant timeouts if (!IsLite()) { TProof::AddEnvVar("PROOF_INTWAIT", "5000"); gEnv->SetValue("Proof.SocketActivityTimeout", 6000); } else { gEnv->SetValue("ProofLite.StartupTimeOut", 5000); } // Warn for slowness Printf(" "); if (!IsLite()) { Printf(" ---> Starting a debug run with valgrind (master:%s, workers:%s)", mstlab.Data(), wrklab.Data()); } else { Printf(" ---> Starting a debug run with valgrind (workers:%s)", wrklab.Data()); } Printf(" ---> Please be patient: startup may be VERY slow ..."); Printf(" ---> Logs will be available as special tags in the log window (from the progress dialog or TProof::LogViewer()) "); Printf(" ---> (Reminder: this debug run makes sense only if you are running a debug version of ROOT)"); Printf(" "); } else if (sconf.BeginsWith("workers=")) { // Request for a given number of workers (within the max) or worker // startup combination: // workers=5 start max 5 workers (or less, if less are assigned) // workers=2x start max 2 workers (or less, if less are assigned) sconf.ReplaceAll("workers=",""); TProof::AddEnvVar("PROOF_NWORKERS", sconf); } } //______________________________________________________________________________ Int_t TProof::AssertPath(const char *inpath, Bool_t writable) { // Make sure that 'path' exists; if 'writable' is kTRUE, make also sure // that the path is writable if (!inpath || strlen(inpath) <= 0) { Error("AssertPath", "undefined input path"); return -1; } TString path(inpath); gSystem->ExpandPathName(path); if (gSystem->AccessPathName(path, kFileExists)) { if (gSystem->mkdir(path, kTRUE) != 0) { Error("AssertPath", "could not create path %s", path.Data()); return -1; } } // It must be writable if (gSystem->AccessPathName(path, kWritePermission) && writable) { if (gSystem->Chmod(path, 0666) != 0) { Error("AssertPath", "could not make path %s writable", path.Data()); return -1; } } // Done return 0; } //______________________________________________________________________________ void TProof::SetManager(TProofMgr *mgr) { // Set manager and schedule its destruction after this for clean // operations. fManager = mgr; if (mgr) { R__LOCKGUARD2(gROOTMutex); gROOT->GetListOfSockets()->Remove(mgr); gROOT->GetListOfSockets()->Add(mgr); } } //______________________________________________________________________________ Int_t TProof::AddWorkers(TList *workerList) { // Works on the master node only. // It starts workers on the machines in workerList and sets the paths, // packages and macros as on the master. // It is a subbstitute for StartSlaves(...) // The code is mostly the master part of StartSlaves, // with the parallel startup removed. if (!IsMaster()) { Error("AddWorkers", "AddWorkers can only be called on the master!"); return -1; } if (!workerList || !(workerList->GetSize())) { Error("AddWorkers", "The list of workers should not be empty; NULL: %d", workerList == 0); return -2; } // Code taken from master part of StartSlaves with the parllel part removed fImage = gProofServ->GetImage(); if (fImage.IsNull()) fImage = Form("%s:%s", TUrl(gSystem->HostName()).GetHostFQDN(), gProofServ->GetWorkDir()); // Get all workers UInt_t nSlaves = workerList->GetSize(); UInt_t nSlavesDone = 0; Int_t ord = 0; // Loop over all workers and start them // a list of TSlave objects for workers that are being added TList *addedWorkers = new TList(); addedWorkers->SetOwner(kFALSE); TListIter next(workerList); TObject *to; TProofNodeInfo *worker; while ((to = next())) { // Get the next worker from the list worker = (TProofNodeInfo *)to; // Read back worker node info const Char_t *image = worker->GetImage().Data(); const Char_t *workdir = worker->GetWorkDir().Data(); Int_t perfidx = worker->GetPerfIndex(); Int_t sport = worker->GetPort(); if (sport == -1) sport = fUrl.GetPort(); // create slave server TString fullord; if (worker->GetOrdinal().Length() > 0) { fullord.Form("%s.%s", gProofServ->GetOrdinal(), worker->GetOrdinal().Data()); } else { fullord.Form("%s.%d", gProofServ->GetOrdinal(), ord); } // create slave server TUrl u(Form("%s:%d",worker->GetNodeName().Data(), sport)); // Add group info in the password firdl, if any if (strlen(gProofServ->GetGroup()) > 0) { // Set also the user, otherwise the password is not exported if (strlen(u.GetUser()) <= 0) u.SetUser(gProofServ->GetUser()); u.SetPasswd(gProofServ->GetGroup()); } TSlave *slave = CreateSlave(u.GetUrl(), fullord, perfidx, image, workdir); // Add to global list (we will add to the monitor list after // finalizing the server startup) Bool_t slaveOk = kTRUE; if (slave->IsValid()) { fSlaves->Add(slave); addedWorkers->Add(slave); } else { slaveOk = kFALSE; fBadSlaves->Add(slave); } PDB(kGlobal,3) Info("StartSlaves", "worker on host %s created" " and added to list", worker->GetNodeName().Data()); // Notify opening of connection nSlavesDone++; TMessage m(kPROOF_SERVERSTARTED); m << TString("Opening connections to workers") << nSlaves << nSlavesDone << slaveOk; gProofServ->GetSocket()->Send(m); ord++; } //end of the worker loop // Cleanup SafeDelete(workerList); nSlavesDone = 0; // Here we finalize the server startup: in this way the bulk // of remote operations are almost parallelized TIter nxsl(addedWorkers); TSlave *sl = 0; while ((sl = (TSlave *) nxsl())) { // Finalize setup of the server if (sl->IsValid()) sl->SetupServ(TSlave::kSlave, 0); // Monitor good slaves Bool_t slaveOk = kTRUE; if (sl->IsValid()) { fAllMonitor->Add(sl->GetSocket()); } else { slaveOk = kFALSE; fBadSlaves->Add(sl); } // Notify end of startup operations nSlavesDone++; TMessage m(kPROOF_SERVERSTARTED); m << TString("Setting up worker servers") << nSlaves << nSlavesDone << slaveOk; gProofServ->GetSocket()->Send(m); } // Now set new state on the added workers (on all workers for simplicity) // use fEnabledPackages, fLoadedMacros, // gSystem->GetDynamicPath() and gSystem->GetIncludePath() // no need to load packages that are only loaded and not enabled (dyn mode) SetParallel(99999, 0); TList *tmpEnabledPackages = gProofServ->GetEnabledPackages(); if (tmpEnabledPackages && tmpEnabledPackages->GetSize() > 0) { TIter nxp(tmpEnabledPackages); TObjString *os = 0; while ((os = (TObjString *) nxp())) { // Upload and Enable methods are intelligent and avoid // re-uploading or re-enabling of a package to a node that has it. UploadPackage(os->GetName()); EnablePackage(os->GetName(), kTRUE); } } if (fLoadedMacros) { TIter nxp(fLoadedMacros); TObjString *os = 0; while ((os = (TObjString *) nxp())) { Printf("Loading a macro : %s", os->GetName()); Load(os->GetName(), kTRUE, kTRUE, addedWorkers); } } TString dyn = gSystem->GetDynamicPath(); dyn.ReplaceAll(":", " "); dyn.ReplaceAll("\"", " "); AddDynamicPath(dyn, addedWorkers); TString inc = gSystem->GetIncludePath(); inc.ReplaceAll("-I", " "); inc.ReplaceAll("\"", " "); AddIncludePath(inc, addedWorkers); // Cleanup delete addedWorkers; // Inform the client that the number of workers is changed if (fDynamicStartup && gProofServ) gProofServ->SendParallel(kTRUE); return 0; } //______________________________________________________________________________ Int_t TProof::RemoveWorkers(TList *workerList) { // Used for shuting down the workres after a query is finished. // Sends each of the workers from the workerList, a kPROOF_STOP message. // If the workerList == 0, shutdown all the workers. if (!IsMaster()) { Error("RemoveWorkers", "RemoveWorkers can only be called on the master!"); return -1; } fFileMap.clear(); // This could be avoided if CopyFromCache was used in SendFile if (!workerList) { // shutdown all the workers TIter nxsl(fSlaves); TSlave *sl = 0; while ((sl = (TSlave *) nxsl())) { // Shut down the worker assumig that it is not processing TerminateWorker(sl); } } else { if (!(workerList->GetSize())) { Error("RemoveWorkers", "The list of workers should not be empty!"); return -2; } // Loop over all the workers and stop them TListIter next(workerList); TObject *to; TProofNodeInfo *worker; while ((to = next())) { TSlave *sl = 0; if (!strcmp(to->ClassName(), "TProofNodeInfo")) { // Get the next worker from the list worker = (TProofNodeInfo *)to; TIter nxsl(fSlaves); while ((sl = (TSlave *) nxsl())) { // Shut down the worker assumig that it is not processing if (sl->GetName() == worker->GetNodeName()) break; } } else if (to->InheritsFrom(TSlave::Class())) { sl = (TSlave *) to; } else { Warning("RemoveWorkers","unknown object type: %s - it should be" " TProofNodeInfo or inheriting from TSlave", to->ClassName()); } // Shut down the worker assumig that it is not processing if (sl) { if (gDebug > 0) Info("RemoveWorkers","terminating worker %s", sl->GetOrdinal()); TerminateWorker(sl); } } } // Update also the master counter if (gProofServ && fSlaves->GetSize() <= 0) gProofServ->ReleaseWorker("master"); return 0; } //______________________________________________________________________________ Bool_t TProof::StartSlaves(Bool_t attach) { // Start up PROOF slaves. // If this is a master server, find the config file and start slave // servers as specified in the config file if (TestBit(TProof::kIsMaster)) { Int_t pc = 0; TList *workerList = new TList; // Get list of workers if (gProofServ->GetWorkers(workerList, pc) == TProofServ::kQueryStop) { TString emsg("no resource currently available for this session: please retry later"); if (gDebug > 0) Info("StartSlaves", emsg.Data()); gProofServ->SendAsynMessage(emsg.Data()); return kFALSE; } // Setup the workers if (AddWorkers(workerList) < 0) return kFALSE; } else { // create master server Printf("Starting master: opening connection ..."); TSlave *slave = CreateSubmaster(fUrl.GetUrl(), "0", "master", 0); if (slave->IsValid()) { // Notify fprintf(stderr,"Starting master:" " connection open: setting up server ... \r"); StartupMessage("Connection to master opened", kTRUE, 1, 1); if (!attach) { // Set worker interrupt handler slave->SetInterruptHandler(kTRUE); // Finalize setup of the server slave->SetupServ(TSlave::kMaster, fConfFile); if (slave->IsValid()) { // Notify Printf("Starting master: OK "); StartupMessage("Master started", kTRUE, 1, 1); // check protocol compatibility // protocol 1 is not supported anymore if (fProtocol == 1) { Error("StartSlaves", "client and remote protocols not compatible (%d and %d)", kPROOF_Protocol, fProtocol); slave->Close("S"); delete slave; return kFALSE; } fSlaves->Add(slave); fAllMonitor->Add(slave->GetSocket()); // Unset worker interrupt handler slave->SetInterruptHandler(kFALSE); // Set interrupt PROOF handler from now on fIntHandler = new TProofInterruptHandler(this); // Give-up after 5 minutes Int_t rc = Collect(slave, 300); Int_t slStatus = slave->GetStatus(); if (slStatus == -99 || slStatus == -98 || rc == 0) { fSlaves->Remove(slave); fAllMonitor->Remove(slave->GetSocket()); if (slStatus == -99) Error("StartSlaves", "no resources available or problems setting up workers (check logs)"); else if (slStatus == -98) Error("StartSlaves", "could not setup output redirection on master"); else Error("StartSlaves", "setting up master"); slave->Close("S"); delete slave; return 0; } if (!slave->IsValid()) { fSlaves->Remove(slave); fAllMonitor->Remove(slave->GetSocket()); slave->Close("S"); delete slave; Error("StartSlaves", "failed to setup connection with PROOF master server"); return kFALSE; } if (!gROOT->IsBatch() && TestBit(kUseProgressDialog)) { if ((fProgressDialog = gROOT->GetPluginManager()->FindHandler("TProofProgressDialog"))) if (fProgressDialog->LoadPlugin() == -1) fProgressDialog = 0; } } else { // Notify Printf("Starting master: failure"); } } else { // Notify Printf("Starting master: OK "); StartupMessage("Master attached", kTRUE, 1, 1); if (!gROOT->IsBatch() && TestBit(kUseProgressDialog)) { if ((fProgressDialog = gROOT->GetPluginManager()->FindHandler("TProofProgressDialog"))) if (fProgressDialog->LoadPlugin() == -1) fProgressDialog = 0; } fSlaves->Add(slave); fIntHandler = new TProofInterruptHandler(this); } } else { delete slave; // Notify only if verbosity is on: most likely the failure has already been notified if (gDebug > 0) Error("StartSlaves", "failed to create (or connect to) the PROOF master server"); return kFALSE; } } return kTRUE; } //______________________________________________________________________________ void TProof::Close(Option_t *opt) { // Close all open slave servers. // Client can decide to shutdown the remote session by passing option is 'S' // or 's'. Default for clients is detach, if supported. Masters always // shutdown the remote counterpart. { R__LOCKGUARD2(fCloseMutex); fValid = kFALSE; if (fSlaves) { if (fIntHandler) fIntHandler->Remove(); TIter nxs(fSlaves); TSlave *sl = 0; while ((sl = (TSlave *)nxs())) sl->Close(opt); fActiveSlaves->Clear("nodelete"); fUniqueSlaves->Clear("nodelete"); fAllUniqueSlaves->Clear("nodelete"); fNonUniqueMasters->Clear("nodelete"); fBadSlaves->Clear("nodelete"); fSlaves->Delete(); } } { R__LOCKGUARD2(gROOTMutex); gROOT->GetListOfSockets()->Remove(this); if (IsProofd()) { gROOT->GetListOfProofs()->Remove(this); if (gProof && gProof == this) { // Set previous proofd-related as default TIter pvp(gROOT->GetListOfProofs(), kIterBackward); while ((gProof = (TProof *)pvp())) { if (gProof->IsProofd()) break; } } } } } //______________________________________________________________________________ TSlave *TProof::CreateSlave(const char *url, const char *ord, Int_t perf, const char *image, const char *workdir) { // Create a new TSlave of type TSlave::kSlave. // Note: creation of TSlave is private with TProof as a friend. // Derived classes must use this function to create slaves. TSlave* sl = TSlave::Create(url, ord, perf, image, this, TSlave::kSlave, workdir, 0); if (sl->IsValid()) { sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket())); // must set fParallel to 1 for slaves since they do not // report their fParallel with a LOG_DONE message sl->fParallel = 1; } return sl; } //______________________________________________________________________________ TSlave *TProof::CreateSubmaster(const char *url, const char *ord, const char *image, const char *msd) { // Create a new TSlave of type TSlave::kMaster. // Note: creation of TSlave is private with TProof as a friend. // Derived classes must use this function to create slaves. TSlave *sl = TSlave::Create(url, ord, 100, image, this, TSlave::kMaster, 0, msd); if (sl->IsValid()) { sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket())); } return sl; } //______________________________________________________________________________ TSlave *TProof::FindSlave(TSocket *s) const { // Find slave that has TSocket s. Returns 0 in case slave is not found. TSlave *sl; TIter next(fSlaves); while ((sl = (TSlave *)next())) { if (sl->IsValid() && sl->GetSocket() == s) return sl; } return 0; } //______________________________________________________________________________ void TProof::FindUniqueSlaves() { // Add to the fUniqueSlave list the active slaves that have a unique // (user) file system image. This information is used to transfer files // only once to nodes that share a file system (an image). Submasters // which are not in fUniqueSlaves are put in the fNonUniqueMasters // list. That list is used to trigger the transferring of files to // the submaster's unique slaves without the need to transfer the file // to the submaster. fUniqueSlaves->Clear(); fUniqueMonitor->RemoveAll(); fAllUniqueSlaves->Clear(); fAllUniqueMonitor->RemoveAll(); fNonUniqueMasters->Clear(); TIter next(fActiveSlaves); while (TSlave *sl = dynamic_cast<TSlave*>(next())) { if (fImage == sl->fImage) { if (sl->GetSlaveType() == TSlave::kMaster) { fNonUniqueMasters->Add(sl); fAllUniqueSlaves->Add(sl); fAllUniqueMonitor->Add(sl->GetSocket()); } continue; } TIter next2(fUniqueSlaves); TSlave *replace_slave = 0; Bool_t add = kTRUE; while (TSlave *sl2 = dynamic_cast<TSlave*>(next2())) { if (sl->fImage == sl2->fImage) { add = kFALSE; if (sl->GetSlaveType() == TSlave::kMaster) { if (sl2->GetSlaveType() == TSlave::kSlave) { // give preference to master replace_slave = sl2; add = kTRUE; } else if (sl2->GetSlaveType() == TSlave::kMaster) { fNonUniqueMasters->Add(sl); fAllUniqueSlaves->Add(sl); fAllUniqueMonitor->Add(sl->GetSocket()); } else { Error("FindUniqueSlaves", "TSlave is neither Master nor Slave"); R__ASSERT(0); } } break; } } if (add) { fUniqueSlaves->Add(sl); fAllUniqueSlaves->Add(sl); fUniqueMonitor->Add(sl->GetSocket()); fAllUniqueMonitor->Add(sl->GetSocket()); if (replace_slave) { fUniqueSlaves->Remove(replace_slave); fAllUniqueSlaves->Remove(replace_slave); fUniqueMonitor->Remove(replace_slave->GetSocket()); fAllUniqueMonitor->Remove(replace_slave->GetSocket()); } } } // will be actiavted in Collect() fUniqueMonitor->DeActivateAll(); fAllUniqueMonitor->DeActivateAll(); } //______________________________________________________________________________ Int_t TProof::GetNumberOfSlaves() const { // Return number of slaves as described in the config file. return fSlaves->GetSize(); } //______________________________________________________________________________ Int_t TProof::GetNumberOfActiveSlaves() const { // Return number of active slaves, i.e. slaves that are valid and in // the current computing group. return fActiveSlaves->GetSize(); } //______________________________________________________________________________ Int_t TProof::GetNumberOfInactiveSlaves() const { // Return number of inactive slaves, i.e. slaves that are valid but not in // the current computing group. return fInactiveSlaves->GetSize(); } //______________________________________________________________________________ Int_t TProof::GetNumberOfUniqueSlaves() const { // Return number of unique slaves, i.e. active slaves that have each a // unique different user files system. return fUniqueSlaves->GetSize(); } //______________________________________________________________________________ Int_t TProof::GetNumberOfBadSlaves() const { // Return number of bad slaves. This are slaves that we in the config // file, but refused to startup or that died during the PROOF session. return fBadSlaves->GetSize(); } //______________________________________________________________________________ void TProof::AskStatistics() { // Ask the for the statistics of the slaves. if (!IsValid()) return; Broadcast(kPROOF_GETSTATS, kActive); Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ void TProof::GetStatistics(Bool_t verbose) { // Get statistics about CPU time, real time and bytes read. // If verbose, print the resuls (always available via GetCpuTime(), GetRealTime() // and GetBytesRead() if (fProtocol > 27) { // This returns the correct result AskStatistics(); } else { // AskStatistics is buggy: parse the output of Print() RedirectHandle_t rh; gSystem->RedirectOutput(fLogFileName, "a", &rh); Print(); gSystem->RedirectOutput(0, 0, &rh); TMacro *mp = GetLastLog(); if (mp) { // Look for global directories TIter nxl(mp->GetListOfLines()); TObjString *os = 0; while ((os = (TObjString *) nxl())) { TString s(os->GetName()); if (s.Contains("Total MB's processed:")) { s.ReplaceAll("Total MB's processed:", ""); if (s.IsFloat()) fBytesRead = (Long64_t) s.Atof() * (1024*1024); } else if (s.Contains("Total real time used (s):")) { s.ReplaceAll("Total real time used (s):", ""); if (s.IsFloat()) fRealTime = s.Atof(); } else if (s.Contains("Total CPU time used (s):")) { s.ReplaceAll("Total CPU time used (s):", ""); if (s.IsFloat()) fCpuTime = s.Atof(); } } delete mp; } } if (verbose) { Printf(" Real/CPU time (s): %.3f / %.3f; workers: %d; processed: %.2f MBs", GetRealTime(), GetCpuTime(), GetParallel(), float(GetBytesRead())/(1024*1024)); } } //______________________________________________________________________________ void TProof::AskParallel() { // Ask the for the number of parallel slaves. if (!IsValid()) return; Broadcast(kPROOF_GETPARALLEL, kActive); Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ TList *TProof::GetListOfQueries(Option_t *opt) { // Ask the master for the list of queries. if (!IsValid() || TestBit(TProof::kIsMaster)) return (TList *)0; Bool_t all = ((strchr(opt,'A') || strchr(opt,'a'))) ? kTRUE : kFALSE; TMessage m(kPROOF_QUERYLIST); m << all; Broadcast(m, kActive); Collect(kActive, fCollectTimeout); // This should have been filled by now return fQueries; } //______________________________________________________________________________ Int_t TProof::GetNumberOfQueries() { // Number of queries processed by this session if (fQueries) return fQueries->GetSize() - fOtherQueries; return 0; } //______________________________________________________________________________ void TProof::SetMaxDrawQueries(Int_t max) { // Set max number of draw queries whose results are saved if (max > 0) { if (fPlayer) fPlayer->SetMaxDrawQueries(max); fMaxDrawQueries = max; } } //______________________________________________________________________________ void TProof::GetMaxQueries() { // Get max number of queries whose full results are kept in the // remote sandbox TMessage m(kPROOF_MAXQUERIES); m << kFALSE; Broadcast(m, kActive); Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ TList *TProof::GetQueryResults() { // Return pointer to the list of query results in the player return (fPlayer ? fPlayer->GetListOfResults() : (TList *)0); } //______________________________________________________________________________ TQueryResult *TProof::GetQueryResult(const char *ref) { // Return pointer to the full TQueryResult instance owned by the player // and referenced by 'ref'. If ref = 0 or "", return the last query result. return (fPlayer ? fPlayer->GetQueryResult(ref) : (TQueryResult *)0); } //______________________________________________________________________________ void TProof::ShowQueries(Option_t *opt) { // Ask the master for the list of queries. // Options: // "A" show information about all the queries known to the // server, i.e. even those processed by other sessions // "L" show only information about queries locally available // i.e. already retrieved. If "L" is specified, "A" is // ignored. // "F" show all details available about queries // "H" print help menu // Default "" Bool_t help = ((strchr(opt,'H') || strchr(opt,'h'))) ? kTRUE : kFALSE; if (help) { // Help Printf("+++"); Printf("+++ Options: \"A\" show all queries known to server"); Printf("+++ \"L\" show retrieved queries"); Printf("+++ \"F\" full listing of query info"); Printf("+++ \"H\" print this menu"); Printf("+++"); Printf("+++ (case insensitive)"); Printf("+++"); Printf("+++ Use Retrieve(<#>) to retrieve the full" " query results from the master"); Printf("+++ e.g. Retrieve(8)"); Printf("+++"); return; } if (!IsValid()) return; Bool_t local = ((strchr(opt,'L') || strchr(opt,'l'))) ? kTRUE : kFALSE; TObject *pq = 0; if (!local) { GetListOfQueries(opt); if (!fQueries) return; TIter nxq(fQueries); // Queries processed by other sessions if (fOtherQueries > 0) { Printf("+++"); Printf("+++ Queries processed during other sessions: %d", fOtherQueries); Int_t nq = 0; while (nq++ < fOtherQueries && (pq = nxq())) pq->Print(opt); } // Queries processed by this session Printf("+++"); Printf("+++ Queries processed during this session: selector: %d, draw: %d", GetNumberOfQueries(), fDrawQueries); while ((pq = nxq())) pq->Print(opt); } else { // Queries processed by this session Printf("+++"); Printf("+++ Queries processed during this session: selector: %d, draw: %d", GetNumberOfQueries(), fDrawQueries); // Queries available locally TList *listlocal = fPlayer ? fPlayer->GetListOfResults() : (TList *)0; if (listlocal) { Printf("+++"); Printf("+++ Queries available locally: %d", listlocal->GetSize()); TIter nxlq(listlocal); while ((pq = nxlq())) pq->Print(opt); } } Printf("+++"); } //______________________________________________________________________________ Bool_t TProof::IsDataReady(Long64_t &totalbytes, Long64_t &bytesready) { // See if the data is ready to be analyzed. if (!IsValid()) return kFALSE; TList submasters; TIter nextSlave(GetListOfActiveSlaves()); while (TSlave *sl = dynamic_cast<TSlave*>(nextSlave())) { if (sl->GetSlaveType() == TSlave::kMaster) { submasters.Add(sl); } } fDataReady = kTRUE; //see if any submasters set it to false fBytesReady = 0; fTotalBytes = 0; //loop over submasters and see if data is ready if (submasters.GetSize() > 0) { Broadcast(kPROOF_DATA_READY, &submasters); Collect(&submasters); } bytesready = fBytesReady; totalbytes = fTotalBytes; EmitVA("IsDataReady(Long64_t,Long64_t)", 2, totalbytes, bytesready); //PDB(kGlobal,2) Info("IsDataReady", "%lld / %lld (%s)", bytesready, totalbytes, fDataReady?"READY":"NOT READY"); return fDataReady; } //______________________________________________________________________________ void TProof::Interrupt(EUrgent type, ESlaves list) { // Send interrupt to master or slave servers. if (!IsValid()) return; TList *slaves = 0; if (list == kAll) slaves = fSlaves; if (list == kActive) slaves = fActiveSlaves; if (list == kUnique) slaves = fUniqueSlaves; if (list == kAllUnique) slaves = fAllUniqueSlaves; if (slaves->GetSize() == 0) return; TSlave *sl; TIter next(slaves); while ((sl = (TSlave *)next())) { if (sl->IsValid()) { // Ask slave to progate the interrupt request sl->Interrupt((Int_t)type); } } } //______________________________________________________________________________ Int_t TProof::GetParallel() const { // Returns number of slaves active in parallel mode. Returns 0 in case // there are no active slaves. Returns -1 in case of error. if (!IsValid()) return -1; // iterate over active slaves and return total number of slaves TIter nextSlave(GetListOfActiveSlaves()); Int_t nparallel = 0; while (TSlave* sl = dynamic_cast<TSlave*>(nextSlave())) if (sl->GetParallel() >= 0) nparallel += sl->GetParallel(); return nparallel; } //______________________________________________________________________________ TList *TProof::GetListOfSlaveInfos() { // Returns list of TSlaveInfo's. In case of error return 0. if (!IsValid()) return 0; if (fSlaveInfo == 0) { fSlaveInfo = new TSortedList(kSortDescending); fSlaveInfo->SetOwner(); } else { fSlaveInfo->Delete(); } TList masters; TIter next(GetListOfSlaves()); TSlave *slave; while ((slave = (TSlave *) next()) != 0) { if (slave->GetSlaveType() == TSlave::kSlave) { TSlaveInfo *slaveinfo = new TSlaveInfo(slave->GetOrdinal(), slave->GetName(), slave->GetPerfIdx()); fSlaveInfo->Add(slaveinfo); TIter nextactive(GetListOfActiveSlaves()); TSlave *activeslave; while ((activeslave = (TSlave *) nextactive())) { if (TString(slaveinfo->GetOrdinal()) == activeslave->GetOrdinal()) { slaveinfo->SetStatus(TSlaveInfo::kActive); break; } } TIter nextbad(GetListOfBadSlaves()); TSlave *badslave; while ((badslave = (TSlave *) nextbad())) { if (TString(slaveinfo->GetOrdinal()) == badslave->GetOrdinal()) { slaveinfo->SetStatus(TSlaveInfo::kBad); break; } } // Get system info if supported if (slave->IsValid()) { if (slave->GetSocket()->Send(kPROOF_GETSLAVEINFO) == -1) MarkBad(slave, "could not send kPROOF_GETSLAVEINFO message"); else masters.Add(slave); } } else if (slave->GetSlaveType() == TSlave::kMaster) { if (slave->IsValid()) { if (slave->GetSocket()->Send(kPROOF_GETSLAVEINFO) == -1) MarkBad(slave, "could not send kPROOF_GETSLAVEINFO message"); else masters.Add(slave); } } else { Error("GetSlaveInfo", "TSlave is neither Master nor Slave"); R__ASSERT(0); } } if (masters.GetSize() > 0) Collect(&masters); return fSlaveInfo; } //______________________________________________________________________________ void TProof::Activate(TList *slaves) { // Activate slave server list. TMonitor *mon = fAllMonitor; mon->DeActivateAll(); slaves = !slaves ? fActiveSlaves : slaves; TIter next(slaves); TSlave *sl; while ((sl = (TSlave*) next())) { if (sl->IsValid()) mon->Activate(sl->GetSocket()); } } //______________________________________________________________________________ void TProof::SetMonitor(TMonitor *mon, Bool_t on) { // Activate (on == TRUE) or deactivate (on == FALSE) all sockets // monitored by 'mon'. TMonitor *m = (mon) ? mon : fCurrentMonitor; if (m) { if (on) m->ActivateAll(); else m->DeActivateAll(); } } //______________________________________________________________________________ Int_t TProof::BroadcastGroupPriority(const char *grp, Int_t priority, TList *workers) { // Broadcast the group priority to all workers in the specified list. Returns // the number of workers the message was successfully sent to. // Returns -1 in case of error. if (!IsValid()) return -1; if (workers->GetSize() == 0) return 0; int nsent = 0; TIter next(workers); TSlave *wrk; while ((wrk = (TSlave *)next())) { if (wrk->IsValid()) { if (wrk->SendGroupPriority(grp, priority) == -1) MarkBad(wrk, "could not send group priority"); else nsent++; } } return nsent; } //______________________________________________________________________________ Int_t TProof::BroadcastGroupPriority(const char *grp, Int_t priority, ESlaves list) { // Broadcast the group priority to all workers in the specified list. Returns // the number of workers the message was successfully sent to. // Returns -1 in case of error. TList *workers = 0; if (list == kAll) workers = fSlaves; if (list == kActive) workers = fActiveSlaves; if (list == kUnique) workers = fUniqueSlaves; if (list == kAllUnique) workers = fAllUniqueSlaves; return BroadcastGroupPriority(grp, priority, workers); } //______________________________________________________________________________ void TProof::ResetMergePrg() { // Reset the merge progress notificator fMergePrg.Reset(fActiveSlaves->GetSize()); } //______________________________________________________________________________ Int_t TProof::Broadcast(const TMessage &mess, TList *slaves) { // Broadcast a message to all slaves in the specified list. Returns // the number of slaves the message was successfully sent to. // Returns -1 in case of error. if (!IsValid()) return -1; if (!slaves || slaves->GetSize() == 0) return 0; int nsent = 0; TIter next(slaves); TSlave *sl; while ((sl = (TSlave *)next())) { if (sl->IsValid()) { if (sl->GetSocket()->Send(mess) == -1) MarkBad(sl, "could not broadcast request"); else nsent++; } } return nsent; } //______________________________________________________________________________ Int_t TProof::Broadcast(const TMessage &mess, ESlaves list) { // Broadcast a message to all slaves in the specified list (either // all slaves or only the active slaves). Returns the number of slaves // the message was successfully sent to. Returns -1 in case of error. TList *slaves = 0; if (list == kAll) slaves = fSlaves; if (list == kActive) slaves = fActiveSlaves; if (list == kUnique) slaves = fUniqueSlaves; if (list == kAllUnique) slaves = fAllUniqueSlaves; return Broadcast(mess, slaves); } //______________________________________________________________________________ Int_t TProof::Broadcast(const char *str, Int_t kind, TList *slaves) { // Broadcast a character string buffer to all slaves in the specified // list. Use kind to set the TMessage what field. Returns the number of // slaves the message was sent to. Returns -1 in case of error. TMessage mess(kind); if (str) mess.WriteString(str); return Broadcast(mess, slaves); } //______________________________________________________________________________ Int_t TProof::Broadcast(const char *str, Int_t kind, ESlaves list) { // Broadcast a character string buffer to all slaves in the specified // list (either all slaves or only the active slaves). Use kind to // set the TMessage what field. Returns the number of slaves the message // was sent to. Returns -1 in case of error. TMessage mess(kind); if (str) mess.WriteString(str); return Broadcast(mess, list); } //______________________________________________________________________________ Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, TList *slaves) { // Broadcast an object to all slaves in the specified list. Use kind to // set the TMEssage what field. Returns the number of slaves the message // was sent to. Returns -1 in case of error. TMessage mess(kind); mess.WriteObject(obj); return Broadcast(mess, slaves); } //______________________________________________________________________________ Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, ESlaves list) { // Broadcast an object to all slaves in the specified list. Use kind to // set the TMEssage what field. Returns the number of slaves the message // was sent to. Returns -1 in case of error. TMessage mess(kind); mess.WriteObject(obj); return Broadcast(mess, list); } //______________________________________________________________________________ Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, TList *slaves) { // Broadcast a raw buffer of specified length to all slaves in the // specified list. Returns the number of slaves the buffer was sent to. // Returns -1 in case of error. if (!IsValid()) return -1; if (slaves->GetSize() == 0) return 0; int nsent = 0; TIter next(slaves); TSlave *sl; while ((sl = (TSlave *)next())) { if (sl->IsValid()) { if (sl->GetSocket()->SendRaw(buffer, length) == -1) MarkBad(sl, "could not send broadcast-raw request"); else nsent++; } } return nsent; } //______________________________________________________________________________ Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, ESlaves list) { // Broadcast a raw buffer of specified length to all slaves in the // specified list. Returns the number of slaves the buffer was sent to. // Returns -1 in case of error. TList *slaves = 0; if (list == kAll) slaves = fSlaves; if (list == kActive) slaves = fActiveSlaves; if (list == kUnique) slaves = fUniqueSlaves; if (list == kAllUnique) slaves = fAllUniqueSlaves; return BroadcastRaw(buffer, length, slaves); } //______________________________________________________________________________ Int_t TProof::BroadcastFile(const char *file, Int_t opt, const char *rfile, TList *wrks) { // Broadcast file to all workers in the specified list. Returns the number of workers // the buffer was sent to. // Returns -1 in case of error. if (!IsValid()) return -1; if (wrks->GetSize() == 0) return 0; int nsent = 0; TIter next(wrks); TSlave *wrk; while ((wrk = (TSlave *)next())) { if (wrk->IsValid()) { if (SendFile(file, opt, rfile, wrk) < 0) Error("BroadcastFile", "problems sending file to worker %s (%s)", wrk->GetOrdinal(), wrk->GetName()); else nsent++; } } return nsent; } //______________________________________________________________________________ Int_t TProof::BroadcastFile(const char *file, Int_t opt, const char *rfile, ESlaves list) { // Broadcast file to all workers in the specified list. Returns the number of workers // the buffer was sent to. // Returns -1 in case of error. TList *wrks = 0; if (list == kAll) wrks = fSlaves; if (list == kActive) wrks = fActiveSlaves; if (list == kUnique) wrks = fUniqueSlaves; if (list == kAllUnique) wrks = fAllUniqueSlaves; return BroadcastFile(file, opt, rfile, wrks); } //______________________________________________________________________________ void TProof::ReleaseMonitor(TMonitor *mon) { // Release the used monitor to be used, making sure to delete newly created // monitors. if (mon && (mon != fAllMonitor) && (mon != fActiveMonitor) && (mon != fUniqueMonitor) && (mon != fAllUniqueMonitor)) { delete mon; } } //______________________________________________________________________________ Int_t TProof::Collect(const TSlave *sl, Long_t timeout, Int_t endtype) { // Collect responses from slave sl. Returns the number of slaves that // responded (=1). // If timeout >= 0, wait at most timeout seconds (timeout = -1 by default, // which means wait forever). // If defined (>= 0) endtype is the message that stops this collection. Int_t rc = 0; TMonitor *mon = 0; if (!sl->IsValid()) return 0; if (fCurrentMonitor == fAllMonitor) { mon = new TMonitor; } else { mon = fAllMonitor; mon->DeActivateAll(); } mon->Activate(sl->GetSocket()); rc = Collect(mon, timeout, endtype); ReleaseMonitor(mon); return rc; } //______________________________________________________________________________ Int_t TProof::Collect(TList *slaves, Long_t timeout, Int_t endtype) { // Collect responses from the slave servers. Returns the number of slaves // that responded. // If timeout >= 0, wait at most timeout seconds (timeout = -1 by default, // which means wait forever). // If defined (>= 0) endtype is the message that stops this collection. Int_t rc = 0; TMonitor *mon = 0; if (fCurrentMonitor == fAllMonitor) { mon = new TMonitor; } else { mon = fAllMonitor; mon->DeActivateAll(); } TIter next(slaves); TSlave *sl; while ((sl = (TSlave*) next())) { if (sl->IsValid()) mon->Activate(sl->GetSocket()); } rc = Collect(mon, timeout, endtype); ReleaseMonitor(mon); return rc; } //______________________________________________________________________________ Int_t TProof::Collect(ESlaves list, Long_t timeout, Int_t endtype) { // Collect responses from the slave servers. Returns the number of slaves // that responded. // If timeout >= 0, wait at most timeout seconds (timeout = -1 by default, // which means wait forever). // If defined (>= 0) endtype is the message that stops this collection. Int_t rc = 0; TMonitor *mon = 0; if (list == kAll) mon = fAllMonitor; if (list == kActive) mon = fActiveMonitor; if (list == kUnique) mon = fUniqueMonitor; if (list == kAllUnique) mon = fAllUniqueMonitor; if (fCurrentMonitor == mon) { // Get a copy mon = new TMonitor(*mon); } mon->ActivateAll(); rc = Collect(mon, timeout, endtype); ReleaseMonitor(mon); return rc; } //______________________________________________________________________________ Int_t TProof::Collect(TMonitor *mon, Long_t timeout, Int_t endtype) { // Collect responses from the slave servers. Returns the number of messages // received. Can be 0 if there are no active slaves. // If timeout >= 0, wait at most timeout seconds (timeout = -1 by default, // which means wait forever). // If defined (>= 0) endtype is the message that stops this collection. // Reset the status flag and clear the messages in the list, if any fStatus = 0; fRecvMessages->Clear(); Long_t actto = (Long_t)(gEnv->GetValue("Proof.SocketActivityTimeout", -1) * 1000); if (!mon->GetActive(actto)) return 0; DeActivateAsyncInput(); // Used by external code to know what we are monitoring TMonitor *savedMonitor = 0; if (fCurrentMonitor) { savedMonitor = fCurrentMonitor; fCurrentMonitor = mon; } else { fCurrentMonitor = mon; fBytesRead = 0; fRealTime = 0.0; fCpuTime = 0.0; } // We want messages on the main window during synchronous collection, // but we save the present status to restore it at the end Bool_t saveRedirLog = fRedirLog; if (!IsIdle() && !IsSync()) fRedirLog = kFALSE; int cnt = 0, rc = 0; // Timeout counter Long_t nto = timeout; PDB(kCollect, 2) Info("Collect","active: %d", mon->GetActive()); // On clients, handle Ctrl-C during collection if (fIntHandler) fIntHandler->Add(); // Sockets w/o activity during the last 'sto' millisecs are deactivated Int_t nact = 0; Long_t sto = -1; Int_t nsto = 60; mon->ResetInterrupt(); while ((nact = mon->GetActive(sto)) && (nto < 0 || nto > 0)) { // Dump last waiting sockets, if in debug mode PDB(kCollect, 2) { if (nact < 4) { TList *al = mon->GetListOfActives(); if (al && al->GetSize() > 0) { Info("Collect"," %d node(s) still active:", al->GetSize()); TIter nxs(al); TSocket *xs = 0; while ((xs = (TSocket *)nxs())) { TSlave *wrk = FindSlave(xs); if (wrk) Info("Collect"," %s", wrk->GetName()); else Info("Collect"," %p: %s:%d", xs, xs->GetInetAddress().GetHostName(), xs->GetInetAddress().GetPort()); } } } } // Wait for a ready socket TSocket *s = mon->Select(1000); if (s && s != (TSocket *)(-1)) { // Get and analyse the info it did receive rc = CollectInputFrom(s, endtype); if (rc == 1 || (rc == 2 && !savedMonitor)) { // Deactivate it if we are done with it mon->DeActivate(s); PDB(kCollect, 2) Info("Collect","deactivating %p (active: %d, %p)", s, mon->GetActive(), mon->GetListOfActives()->First()); } else if (rc == 2) { // This end message was for the saved monitor // Deactivate it if we are done with it if (savedMonitor) { savedMonitor->DeActivate(s); PDB(kCollect, 2) Info("Collect","save monitor: deactivating %p (active: %d, %p)", s, savedMonitor->GetActive(), savedMonitor->GetListOfActives()->First()); } } // Update counter (if no error occured) if (rc >= 0) cnt++; } else { // If not timed-out, exit if not stopped or not aborted // (player exits status is finished in such a case); otherwise, // we still need to collect the partial output info if (!s) if (fPlayer && (fPlayer->GetExitStatus() == TVirtualProofPlayer::kFinished)) mon->DeActivateAll(); // Decrease the timeout counter if requested if (s == (TSocket *)(-1) && nto > 0) nto--; } // Check if we need to check the socket activity (we do it every 10 cycles ~ 10 sec) sto = -1; if (--nsto <= 0) { sto = (Long_t) actto; nsto = 60; } } // If timed-out, deactivate the remaining sockets if (nto == 0) { TList *al = mon->GetListOfActives(); if (al && al->GetSize() > 0) { // Notify the name of those which did timeout Info("Collect"," %d node(s) went in timeout:", al->GetSize()); TIter nxs(al); TSocket *xs = 0; while ((xs = (TSocket *)nxs())) { TSlave *wrk = FindSlave(xs); if (wrk) Info("Collect"," %s", wrk->GetName()); else Info("Collect"," %p: %s:%d", xs, xs->GetInetAddress().GetHostName(), xs->GetInetAddress().GetPort()); } } mon->DeActivateAll(); } // Deactivate Ctrl-C special handler if (fIntHandler) fIntHandler->Remove(); // make sure group view is up to date SendGroupView(); // Restore redirection setting fRedirLog = saveRedirLog; // Restore the monitor fCurrentMonitor = savedMonitor; ActivateAsyncInput(); return cnt; } //______________________________________________________________________________ void TProof::CleanGDirectory(TList *ol) { // Remove links to objects in list 'ol' from gDirectory if (ol) { TIter nxo(ol); TObject *o = 0; while ((o = nxo())) gDirectory->RecursiveRemove(o); } } //______________________________________________________________________________ Int_t TProof::CollectInputFrom(TSocket *s, Int_t endtype) { // Collect and analyze available input from socket s. // Returns 0 on success, -1 if any failure occurs. TMessage *mess; Int_t recvrc = 0; if ((recvrc = s->Recv(mess)) < 0) { PDB(kCollect,2) Info("CollectInputFrom","%p: got %d from Recv()", s, recvrc); Bool_t bad = kTRUE; if (recvrc == -5) { // Broken connection: try reconnection if (fCurrentMonitor) fCurrentMonitor->Remove(s); if (s->Reconnect() == 0) { if (fCurrentMonitor) fCurrentMonitor->Add(s); bad = kFALSE; } } if (bad) MarkBad(s, "problems receiving a message in TProof::CollectInputFrom(...)"); // Ignore this wake up return -1; } if (!mess) { // we get here in case the remote server died MarkBad(s, "undefined message in TProof::CollectInputFrom(...)"); return -1; } Int_t rc = 0; Int_t what = mess->What(); TSlave *sl = FindSlave(s); rc = HandleInputMessage(sl, mess); if (rc == 1 && (endtype >= 0) && (what != endtype)) // This message was for the base monitor in recursive case rc = 2; // We are done successfully return rc; } //______________________________________________________________________________ Int_t TProof::HandleInputMessage(TSlave *sl, TMessage *mess) { // Analyze the received message. // Returns 0 on success (1 if this the last message from this socket), -1 if // any failure occurs. char str[512]; TObject *obj; Int_t rc = 0; if (!mess || !sl) { Warning("HandleInputMessage", "given an empty message or undefined worker"); return -1; } Bool_t delete_mess = kTRUE; TSocket *s = sl->GetSocket(); if (!s) { Warning("HandleInputMessage", "worker socket is undefined"); return -1; } // The message type Int_t what = mess->What(); PDB(kCollect,3) Info("HandleInputMessage", "got type %d from '%s'", what, sl->GetOrdinal()); switch (what) { case kMESS_OK: // Add the message to the list fRecvMessages->Add(mess); delete_mess = kFALSE; break; case kMESS_OBJECT: if (fPlayer) fPlayer->HandleRecvHisto(mess); break; case kPROOF_FATAL: MarkBad(s, "received kPROOF_FATAL"); if (fProgressDialogStarted) { // Finalize the progress dialog Emit("StopProcess(Bool_t)", kTRUE); } break; case kPROOF_STOP: // Stop collection from this worker Info("HandleInputMessage", "received kPROOF_STOP from %s: disabling any further collection this worker", (sl ? sl->GetOrdinal() : "undef")); rc = 1; break; case kPROOF_GETTREEHEADER: // Add the message to the list fRecvMessages->Add(mess); delete_mess = kFALSE; rc = 1; break; case kPROOF_TOUCH: // send a request for touching the remote admin file { sl->Touch(); } break; case kPROOF_GETOBJECT: // send slave object it asks for mess->ReadString(str, sizeof(str)); obj = gDirectory->Get(str); if (obj) s->SendObject(obj); else s->Send(kMESS_NOTOK); break; case kPROOF_GETPACKET: { TDSetElement *elem = 0; elem = fPlayer ? fPlayer->GetNextPacket(sl, mess) : 0; if (elem != (TDSetElement*) -1) { TMessage answ(kPROOF_GETPACKET); answ << elem; s->Send(answ); while (fWaitingSlaves != 0 && fWaitingSlaves->GetSize()) { TPair *p = (TPair*) fWaitingSlaves->First(); s = (TSocket*) p->Key(); TMessage *m = (TMessage*) p->Value(); elem = fPlayer ? fPlayer->GetNextPacket(sl, m) : 0; if (elem != (TDSetElement*) -1) { TMessage a(kPROOF_GETPACKET); a << elem; s->Send(a); // remove has to happen via Links because TPair does not have // a Compare() function and therefore RemoveFirst() and // Remove(TObject*) do not work fWaitingSlaves->Remove(fWaitingSlaves->FirstLink()); delete p; delete m; } else { break; } } } else { if (fWaitingSlaves == 0) fWaitingSlaves = new TList; fWaitingSlaves->Add(new TPair(s, mess)); delete_mess = kFALSE; } } break; case kPROOF_LOGFILE: { Int_t size; (*mess) >> size; PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_LOGFILE: size: %d", size); RecvLogFile(s, size); } break; case kPROOF_LOGDONE: (*mess) >> sl->fStatus >> sl->fParallel; PDB(kCollect,2) Info("HandleInputMessage","kPROOF_LOGDONE:%s: status %d parallel %d", sl->GetOrdinal(), sl->fStatus, sl->fParallel); if (sl->fStatus != 0) fStatus = sl->fStatus; //return last nonzero status rc = 1; break; case kPROOF_GETSTATS: { (*mess) >> sl->fBytesRead >> sl->fRealTime >> sl->fCpuTime >> sl->fWorkDir >> sl->fProofWorkDir; TString img; if ((mess->BufferSize() > mess->Length())) (*mess) >> img; // Set image if (img.IsNull()) { if (sl->fImage.IsNull()) sl->fImage = Form("%s:%s", TUrl(sl->fName).GetHostFQDN(), sl->fProofWorkDir.Data()); } else { sl->fImage = img; } PDB(kGlobal,2) Info("HandleInputMessage", "kPROOF_GETSTATS:%s image: %s", sl->GetOrdinal(), sl->GetImage()); fBytesRead += sl->fBytesRead; fRealTime += sl->fRealTime; fCpuTime += sl->fCpuTime; rc = 1; } break; case kPROOF_GETPARALLEL: { Bool_t async = kFALSE; (*mess) >> sl->fParallel; if ((mess->BufferSize() > mess->Length())) (*mess) >> async; rc = (async) ? 0 : 1; } break; case kPROOF_CHECKFILE: { // New servers (>= 5.22) send the status if ((mess->BufferSize() > mess->Length())) { (*mess) >> fCheckFileStatus; } else { // Form old servers this meant success (failure was signaled with the // dangerous kPROOF_FATAL) fCheckFileStatus = 1; } rc = 1; } break; case kPROOF_SENDFILE: { // New server: signals ending of sendfile operation rc = 1; } break; case kPROOF_PACKAGE_LIST: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_PACKAGE_LIST: enter"); Int_t type = 0; (*mess) >> type; switch (type) { case TProof::kListEnabledPackages: SafeDelete(fEnabledPackages); fEnabledPackages = (TList *) mess->ReadObject(TList::Class()); if (fEnabledPackages) { fEnabledPackages->SetOwner(); } else { Error("HandleInputMessage", "kPROOF_PACKAGE_LIST: kListEnabledPackages: TList not found in message!"); } break; case TProof::kListPackages: SafeDelete(fAvailablePackages); fAvailablePackages = (TList *) mess->ReadObject(TList::Class()); if (fAvailablePackages) { fAvailablePackages->SetOwner(); } else { Error("HandleInputMessage", "kPROOF_PACKAGE_LIST: kListPackages: TList not found in message!"); } break; default: Error("HandleInputMessage", "kPROOF_PACKAGE_LIST: unknown type: %d", type); } } break; case kPROOF_OUTPUTOBJECT: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_OUTPUTOBJECT: enter"); Int_t type = 0; const char *prefix = gProofServ ? gProofServ->GetPrefix() : "Lite-0"; if (!TestBit(TProof::kIsClient) && !fMergersSet && !fFinalizationRunning) { Info("HandleInputMessage", "finalization on %s started ...", prefix); fFinalizationRunning = kTRUE; } while ((mess->BufferSize() > mess->Length())) { (*mess) >> type; // If a query result header, add it to the player list if (fPlayer) { if (type == 0) { // Retrieve query result instance (output list not filled) TQueryResult *pq = (TQueryResult *) mess->ReadObject(TQueryResult::Class()); if (pq) { // Add query to the result list in TProofPlayer fPlayer->AddQueryResult(pq); fPlayer->SetCurrentQuery(pq); // And clear the output list, as we start merging a new set of results if (fPlayer->GetOutputList()) fPlayer->GetOutputList()->Clear(); // Add the unique query tag as TNamed object to the input list // so that it is available in TSelectors for monitoring fPlayer->AddInput(new TNamed("PROOF_QueryTag", Form("%s:%s",pq->GetTitle(),pq->GetName()))); } else { Warning("HandleInputMessage","kPROOF_OUTPUTOBJECT: query result missing"); } } else if (type > 0) { // Read object TObject *o = mess->ReadObject(TObject::Class()); // Increment counter on the client side fMergePrg.IncreaseIdx(); TString msg; msg.Form("%s: merging output objects ... %s", prefix, fMergePrg.Export()); if (gProofServ) gProofServ->SendAsynMessage(msg.Data(), kFALSE); else fprintf(stderr, "%s\r", msg.Data()); // Add or merge it if ((fPlayer->AddOutputObject(o) == 1)) { // Remove the object if it has been merged SafeDelete(o); } if (type > 1) { // Update the merger progress info fMergePrg.DecreaseNWrks(); if (TestBit(TProof::kIsClient) && !IsLite()) { // In PROOFLite this has to be done once only in TProofLite::Process TQueryResult *pq = fPlayer->GetCurrentQuery(); pq->SetOutputList(fPlayer->GetOutputList(), kFALSE); pq->SetInputList(fPlayer->GetInputList(), kFALSE); // If the last object, notify the GUI that the result arrived QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName())); // Processing is over UpdateDialog(); } } } } else { Warning("HandleInputMessage", "kPROOF_OUTPUTOBJECT: player undefined!"); } } } break; case kPROOF_OUTPUTLIST: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_OUTPUTLIST: enter"); TList *out = 0; if (fPlayer) { if (TestBit(TProof::kIsMaster) || fProtocol < 7) { out = (TList *) mess->ReadObject(TList::Class()); } else { TQueryResult *pq = (TQueryResult *) mess->ReadObject(TQueryResult::Class()); if (pq) { // Add query to the result list in TProofPlayer fPlayer->AddQueryResult(pq); fPlayer->SetCurrentQuery(pq); // To avoid accidental cleanups from anywhere else // remove objects from gDirectory and clone the list out = pq->GetOutputList(); CleanGDirectory(out); out = (TList *) out->Clone(); // Notify the GUI that the result arrived QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName())); } else { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_OUTPUTLIST: query result missing"); } } if (out) { out->SetOwner(); fPlayer->AddOutput(out); // Incorporate the list SafeDelete(out); } else { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_OUTPUTLIST: ouputlist is empty"); } } else { Warning("HandleInputMessage", "kPROOF_OUTPUTLIST: player undefined!"); } // On clients at this point processing is over if (TestBit(TProof::kIsClient) && !IsLite()) UpdateDialog(); } break; case kPROOF_QUERYLIST: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_QUERYLIST: enter"); (*mess) >> fOtherQueries >> fDrawQueries; if (fQueries) { fQueries->Delete(); delete fQueries; fQueries = 0; } fQueries = (TList *) mess->ReadObject(TList::Class()); } break; case kPROOF_RETRIEVE: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_RETRIEVE: enter"); TQueryResult *pq = (TQueryResult *) mess->ReadObject(TQueryResult::Class()); if (pq && fPlayer) { fPlayer->AddQueryResult(pq); // Notify the GUI that the result arrived QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName())); } else { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_RETRIEVE: query result missing or player undefined"); } } break; case kPROOF_MAXQUERIES: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_MAXQUERIES: enter"); Int_t max = 0; (*mess) >> max; Printf("Number of queries fully kept remotely: %d", max); } break; case kPROOF_SERVERSTARTED: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_SERVERSTARTED: enter"); UInt_t tot = 0, done = 0; TString action; Bool_t st = kTRUE; (*mess) >> action >> tot >> done >> st; if (TestBit(TProof::kIsClient)) { if (tot) { TString type = (action.Contains("submas")) ? "submasters" : "workers"; Int_t frac = (Int_t) (done*100.)/tot; char msg[512] = {0}; if (frac >= 100) { snprintf(msg, 512, "%s: OK (%d %s) \n", action.Data(),tot, type.Data()); } else { snprintf(msg, 512, "%s: %d out of %d (%d %%)\r", action.Data(), done, tot, frac); } if (fSync) fprintf(stderr,"%s", msg); else NotifyLogMsg(msg, 0); } // Notify GUIs StartupMessage(action.Data(), st, (Int_t)done, (Int_t)tot); } else { // Just send the message one level up TMessage m(kPROOF_SERVERSTARTED); m << action << tot << done << st; gProofServ->GetSocket()->Send(m); } } break; case kPROOF_DATASET_STATUS: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_DATASET_STATUS: enter"); UInt_t tot = 0, done = 0; TString action; Bool_t st = kTRUE; (*mess) >> action >> tot >> done >> st; if (TestBit(TProof::kIsClient)) { if (tot) { TString type = "files"; Int_t frac = (Int_t) (done*100.)/tot; char msg[512] = {0}; if (frac >= 100) { sprintf(msg,"%s: OK (%d %s) \n", action.Data(),tot, type.Data()); } else { sprintf(msg,"%s: %d out of %d (%d %%)\r", action.Data(), done, tot, frac); } if (fSync) fprintf(stderr,"%s", msg); else NotifyLogMsg(msg, 0); } // Notify GUIs DataSetStatus(action.Data(), st, (Int_t)done, (Int_t)tot); } else { // Just send the message one level up TMessage m(kPROOF_DATASET_STATUS); m << action << tot << done << st; gProofServ->GetSocket()->Send(m); } } break; case kPROOF_STARTPROCESS: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_STARTPROCESS: enter"); // For Proof-Lite this variable is the number of workers and is set // by the player if (!IsLite()) { fNotIdle = 1; fIsWaiting = kFALSE; } // Redirect the output, if needed fRedirLog = (fSync) ? fRedirLog : kTRUE; // The signal is used on masters by XrdProofdProtocol to catch // the start of processing; on clients it allows to update the // progress dialog if (!TestBit(TProof::kIsMaster)) { TString selec; Int_t dsz = -1; Long64_t first = -1, nent = -1; (*mess) >> selec >> dsz >> first >> nent; // Start or reset the progress dialog if (!gROOT->IsBatch()) { if (fProgressDialog && !TestBit(kUsingSessionGui) && TestBit(kUseProgressDialog)) { if (!fProgressDialogStarted) { fProgressDialog->ExecPlugin(5, this, selec.Data(), dsz, first, nent); fProgressDialogStarted = kTRUE; } else { ResetProgressDialog(selec, dsz, first, nent); } } ResetBit(kUsingSessionGui); } } } break; case kPROOF_ENDINIT: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_ENDINIT: enter"); if (TestBit(TProof::kIsMaster)) { if (fPlayer) fPlayer->SetInitTime(); } } break; case kPROOF_SETIDLE: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_SETIDLE: enter"); // The session is idle if (IsLite()) { if (fNotIdle > 0) { fNotIdle--; } else { Warning("HandleInputMessage", "got kPROOF_SETIDLE but no running workers ! protocol error?"); } } else { fNotIdle = 0; // Check if the query has been enqueued if ((mess->BufferSize() > mess->Length())) (*mess) >> fIsWaiting; } } break; case kPROOF_QUERYSUBMITTED: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_QUERYSUBMITTED: enter"); // We have received the sequential number (*mess) >> fSeqNum; Bool_t sync = fSync; if ((mess->BufferSize() > mess->Length())) (*mess) >> sync; if (sync != fSync && fSync) { // The server required to switch to asynchronous mode Activate(); fSync = kFALSE; } DisableGoAsyn(); // Check if the query has been enqueued fIsWaiting = kTRUE; // For Proof-Lite this variable is the number of workers and is set by the player if (!IsLite()) fNotIdle = 1; rc = 1; } break; case kPROOF_SESSIONTAG: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_SESSIONTAG: enter"); // We have received the unique tag and save it as name of this object TString stag; (*mess) >> stag; SetName(stag); // New servers send also the group if ((mess->BufferSize() > mess->Length())) (*mess) >> fGroup; } break; case kPROOF_FEEDBACK: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_FEEDBACK: enter"); TList *out = (TList *) mess->ReadObject(TList::Class()); out->SetOwner(); if (fPlayer) fPlayer->StoreFeedback(sl, out); // Adopts the list else // Not yet ready: stop collect asap rc = 1; } break; case kPROOF_AUTOBIN: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_AUTOBIN: enter"); TString name; Double_t xmin, xmax, ymin, ymax, zmin, zmax; (*mess) >> name >> xmin >> xmax >> ymin >> ymax >> zmin >> zmax; if (fPlayer) fPlayer->UpdateAutoBin(name,xmin,xmax,ymin,ymax,zmin,zmax); TMessage answ(kPROOF_AUTOBIN); answ << name << xmin << xmax << ymin << ymax << zmin << zmax; s->Send(answ); } break; case kPROOF_PROGRESS: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_PROGRESS: enter"); if (GetRemoteProtocol() > 25) { // New format TProofProgressInfo *pi = 0; (*mess) >> pi; fPlayer->Progress(sl,pi); } else if (GetRemoteProtocol() > 11) { Long64_t total, processed, bytesread; Float_t initTime, procTime, evtrti, mbrti; (*mess) >> total >> processed >> bytesread >> initTime >> procTime >> evtrti >> mbrti; if (fPlayer) fPlayer->Progress(sl, total, processed, bytesread, initTime, procTime, evtrti, mbrti); } else { // Old format Long64_t total, processed; (*mess) >> total >> processed; if (fPlayer) fPlayer->Progress(sl, total, processed); } } break; case kPROOF_STOPPROCESS: { // This message is sent from a worker that finished processing. // We determine whether it was asked to finish by the // packetizer or stopped during processing a packet // (by TProof::RemoveWorkers() or by an external signal). // In the later case call packetizer->MarkBad. PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_STOPPROCESS: enter"); Long64_t events = 0; Bool_t abort = kFALSE; TProofProgressStatus *status = 0; if ((mess->BufferSize() > mess->Length()) && (fProtocol > 18)) { (*mess) >> status >> abort; } else if ((mess->BufferSize() > mess->Length()) && (fProtocol > 8)) { (*mess) >> events >> abort; } else { (*mess) >> events; } if (!abort && fPlayer) { if (fProtocol > 18) { TList *listOfMissingFiles = 0; if (!(listOfMissingFiles = (TList *)GetOutput("MissingFiles"))) { listOfMissingFiles = new TList(); listOfMissingFiles->SetName("MissingFiles"); if (fPlayer) fPlayer->AddOutputObject(listOfMissingFiles); } if (fPlayer->GetPacketizer()) { Int_t ret = fPlayer->GetPacketizer()->AddProcessed(sl, status, 0, &listOfMissingFiles); if (ret > 0) fPlayer->GetPacketizer()->MarkBad(sl, status, &listOfMissingFiles); // This object is now owned by the packetizer status = 0; } } else { fPlayer->AddEventsProcessed(events); } } SafeDelete(status); if (!TestBit(TProof::kIsMaster)) Emit("StopProcess(Bool_t)", abort); break; } case kPROOF_SUBMERGER: { PDB(kGlobal,2) Info("HandleInputMessage", "kPROOF_SUBMERGER: enter"); HandleSubmerger(mess, sl); } break; case kPROOF_GETSLAVEINFO: { PDB(kGlobal,2) Info("HandleInputMessage", "kPROOF_GETSLAVEINFO: enter"); Bool_t active = (GetListOfActiveSlaves()->FindObject(sl) != 0); Bool_t bad = (GetListOfBadSlaves()->FindObject(sl) != 0); TList* tmpinfo = 0; (*mess) >> tmpinfo; if (tmpinfo == 0) { Error("HandleInputMessage", "kPROOF_GETSLAVEINFO: no list received!"); } else { tmpinfo->SetOwner(kFALSE); Int_t nentries = tmpinfo->GetSize(); for (Int_t i=0; i<nentries; i++) { TSlaveInfo* slinfo = dynamic_cast<TSlaveInfo*>(tmpinfo->At(i)); if (slinfo) { // Check if we have already a instance for this worker TIter nxw(fSlaveInfo); TSlaveInfo *ourwi = 0; while ((ourwi = (TSlaveInfo *)nxw())) { if (!strcmp(ourwi->GetOrdinal(), slinfo->GetOrdinal())) { ourwi->SetSysInfo(slinfo->GetSysInfo()); break; } } if (!ourwi) { fSlaveInfo->Add(slinfo); } else { slinfo = ourwi; } if (slinfo->fStatus != TSlaveInfo::kBad) { if (!active) slinfo->SetStatus(TSlaveInfo::kNotActive); if (bad) slinfo->SetStatus(TSlaveInfo::kBad); } if (sl->GetMsd() && (strlen(sl->GetMsd()) > 0)) slinfo->fMsd = sl->GetMsd(); } } delete tmpinfo; rc = 1; } } break; case kPROOF_VALIDATE_DSET: { PDB(kGlobal,2) Info("HandleInputMessage", "kPROOF_VALIDATE_DSET: enter"); TDSet* dset = 0; (*mess) >> dset; if (!fDSet) Error("HandleInputMessage", "kPROOF_VALIDATE_DSET: fDSet not set"); else fDSet->Validate(dset); delete dset; } break; case kPROOF_DATA_READY: { PDB(kGlobal,2) Info("HandleInputMessage", "kPROOF_DATA_READY: enter"); Bool_t dataready = kFALSE; Long64_t totalbytes, bytesready; (*mess) >> dataready >> totalbytes >> bytesready; fTotalBytes += totalbytes; fBytesReady += bytesready; if (dataready == kFALSE) fDataReady = dataready; } break; case kPROOF_PING: // do nothing (ping is already acknowledged) break; case kPROOF_MESSAGE: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_MESSAGE: enter"); // We have received the unique tag and save it as name of this object TString msg; (*mess) >> msg; Bool_t lfeed = kTRUE; if ((mess->BufferSize() > mess->Length())) (*mess) >> lfeed; if (TestBit(TProof::kIsClient)) { if (fSync) { // Notify locally fprintf(stderr,"%s%c", msg.Data(), (lfeed ? '\n' : '\r')); } else { // Notify locally taking care of redirection, windows logs, ... NotifyLogMsg(msg, (lfeed ? "\n" : "\r")); } } else { // The message is logged for debugging purposes. fprintf(stderr,"%s%c", msg.Data(), (lfeed ? '\n' : '\r')); if (gProofServ) { // We hide it during normal operations gProofServ->FlushLogFile(); // And send the message one level up gProofServ->SendAsynMessage(msg, lfeed); } } } break; case kPROOF_VERSARCHCOMP: { TString vac; (*mess) >> vac; PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_VERSARCHCOMP: %s", vac.Data()); Int_t from = 0; TString vers, archcomp; if (vac.Tokenize(vers, from, "|")) vac.Tokenize(archcomp, from, "|"); sl->SetArchCompiler(archcomp); vers.ReplaceAll(":","|"); sl->SetROOTVersion(vers); } break; default: { Error("HandleInputMessage", "unknown command received from '%s' (what = %d)", (sl ? sl->GetOrdinal() : "undef"), what); } break; } // Cleanup if (delete_mess) delete mess; // We are done successfully return rc; } //______________________________________________________________________________ void TProof::HandleSubmerger(TMessage *mess, TSlave *sl) { // Process a message of type kPROOF_SUBMERGER // Message sub-type Int_t type = 0; (*mess) >> type; TSocket *s = sl->GetSocket(); switch (type) { case kOutputSent: { if (IsEndMaster()) { Int_t merger_id = -1; (*mess) >> merger_id; PDB(kSubmerger, 2) Info("HandleSubmerger", "kOutputSent: Worker %s:%d:%s had sent its output to merger #%d", sl->GetName(), sl->GetPort(), sl->GetOrdinal(), merger_id); if (!fMergers || fMergers->GetSize() <= merger_id) { Error("HandleSubmerger", "kOutputSize: #%d not in list ", merger_id); break; } TMergerInfo * mi = (TMergerInfo *) fMergers->At(merger_id); mi->SetMergedWorker(); if (mi->AreAllWorkersMerged()) { mi->Deactivate(); if (GetActiveMergersCount() == 0) { fMergers->Clear(); delete fMergers; fMergersSet = kFALSE; fMergersCount = -1; fLastAssignedMerger = 0; PDB(kSubmerger, 2) Info("HandleSubmerger", "all mergers removed ... "); } } } else { PDB(kSubmerger, 2) Error("HandleSubmerger","kOutputSent: received not on endmaster!"); } } break; case kMergerDown: { Int_t merger_id = -1; (*mess) >> merger_id; PDB(kSubmerger, 2) Info("HandleSubmerger", "kMergerDown: #%d ", merger_id); if (!fMergers || fMergers->GetSize() <= merger_id) { Error("HandleSubmerger", "kMergerDown: #%d not in list ", merger_id); break; } TMergerInfo * mi = (TMergerInfo *) fMergers->At(merger_id); if (!mi->IsActive()) { break; } else { mi->Deactivate(); } // Stop the invalid merger in the case it is still listening TMessage stop(kPROOF_SUBMERGER); stop << Int_t(kStopMerging); stop << 0; s->Send(stop); // Ask for results from merger (only original results from this node as worker are returned) AskForOutput(mi->GetMerger()); // Ask for results from all workers assigned to this merger TIter nxo(mi->GetWorkers()); TObject * o = 0; while ((o = nxo())) { AskForOutput((TSlave *)o); } PDB(kSubmerger, 2) Info("HandleSubmerger", "kMergerDown: exit", merger_id); } break; case kOutputSize: { if (IsEndMaster()) { PDB(kSubmerger, 2) Info("HandleSubmerger", "worker %s reported as finished ", sl->GetOrdinal()); const char *prefix = gProofServ ? gProofServ->GetPrefix() : "Lite-0"; if (!fFinalizationRunning) { Info("HandleSubmerger", "finalization on %s started ...", prefix); fFinalizationRunning = kTRUE; } Int_t output_size = 0; Int_t merging_port = 0; (*mess) >> output_size >> merging_port; PDB(kSubmerger, 2) Info("HandleSubmerger", "kOutputSize: Worker %s:%d:%s reports %d output objects (+ available port %d)", sl->GetName(), sl->GetPort(), sl->GetOrdinal(), output_size, merging_port); TString msg; if (!fMergersSet) { // First pass - setting number of mergers according to user or dynamically fMergersCount = -1; // No mergers used if not set by user TParameter<Int_t> *mc = dynamic_cast<TParameter<Int_t> *>(GetParameter("PROOF_UseMergers")); if (mc) fMergersCount = mc->GetVal(); // Value set by user // Mergers count specified by user but not valid if (fMergersCount < 0 || (fMergersCount > (GetNumberOfSlaves()/2) )) { msg.Form("%s: Invalid request: cannot start %d mergers for %d workers", prefix, fMergersCount, GetNumberOfSlaves()); if (gProofServ) gProofServ->SendAsynMessage(msg); else Printf("%s",msg.Data()); fMergersCount = 0; } // Mergers count will be set dynamically if (fMergersCount == 0) { if (GetNumberOfSlaves() > 1) fMergersCount = TMath::Nint(TMath::Sqrt(GetNumberOfSlaves())); if (fMergersCount > 1) msg.Form("%s: Number of mergers set dynamically to %d (for %d workers)", prefix, fMergersCount, GetNumberOfSlaves()); else { msg.Form("%s: No mergers will be used for %d workers", prefix, GetNumberOfSlaves()); fMergersCount = -1; } if (gProofServ) gProofServ->SendAsynMessage(msg); else Printf("%s",msg.Data()); } else { msg.Form("%s: Number of mergers set by user to %d (for %d workers)", prefix, fMergersCount, GetNumberOfSlaves()); if (gProofServ) gProofServ->SendAsynMessage(msg); else Printf("%s",msg.Data()); } if (fMergersCount > 0) { fMergers = new TList(); fLastAssignedMerger = 0; // Total number of workers, which will not act as mergers ('pure workers') fWorkersToMerge = (GetNumberOfSlaves() - fMergersCount); // Establish the first merger if (!CreateMerger(sl, merging_port)) { // Cannot establish first merger AskForOutput(sl); fWorkersToMerge--; fMergersCount--; } if (IsLite()) fMergePrg.SetNWrks(fMergersCount); } else { AskForOutput(sl); } fMergersSet = kTRUE; } else { // Multiple pass if (fMergersCount == -1) { // No mergers. Workers send their outputs directly to master AskForOutput(sl); } else { if (fRedirectNext > 0 ) { RedirectWorker(s, sl, output_size); fRedirectNext--; } else { if (fMergersCount > fMergers->GetSize()) { // Still not enough mergers established if (!CreateMerger(sl, merging_port)) { // Cannot establish a merger AskForOutput(sl); fWorkersToMerge--; fMergersCount--; } } else RedirectWorker(s, sl, output_size); } } } } else { Error("HandleSubMerger","kOutputSize received not on endmaster!"); } } break; } } //______________________________________________________________________________ void TProof::RedirectWorker(TSocket *s, TSlave * sl, Int_t output_size) { // Redirect output of worker sl to some merger Int_t merger_id = FindNextFreeMerger(); if (merger_id == -1) { // No free merger (probably it had crashed before) AskForOutput(sl); } else { TMessage sendoutput(kPROOF_SUBMERGER); sendoutput << Int_t(kSendOutput); PDB(kSubmerger, 2) Info("RedirectWorker", "redirecting worker %s to merger %d", sl->GetOrdinal(), merger_id); PDB(kSubmerger, 2) Info("RedirectWorker", "redirecting output to merger #%d", merger_id); if (!fMergers || fMergers->GetSize() <= merger_id) { Error("RedirectWorker", "#%d not in list ", merger_id); return; } TMergerInfo * mi = (TMergerInfo *) fMergers->At(merger_id); TString hname = (IsLite()) ? "localhost" : mi->GetMerger()->GetName(); sendoutput << merger_id; sendoutput << hname; sendoutput << mi->GetPort(); s->Send(sendoutput); mi->AddMergedObjects(output_size); mi->AddWorker(sl); } } //______________________________________________________________________________ Int_t TProof::FindNextFreeMerger() { // Return a merger, which is both active and still accepts some workers to be // assigned to it. It works on the 'round-robin' basis. while (fLastAssignedMerger < fMergers->GetSize() && (!((TMergerInfo*)fMergers->At(fLastAssignedMerger))->IsActive() || ((TMergerInfo*)fMergers->At(fLastAssignedMerger))->AreAllWorkersAssigned())) { fLastAssignedMerger++; } if (fLastAssignedMerger == fMergers->GetSize()) { fLastAssignedMerger = 0; } else { return fLastAssignedMerger++; } while (fLastAssignedMerger < fMergers->GetSize() && (!((TMergerInfo*)fMergers->At(fLastAssignedMerger))->IsActive() || ((TMergerInfo*)fMergers->At(fLastAssignedMerger))->AreAllWorkersAssigned())) { fLastAssignedMerger++; } if (fLastAssignedMerger == fMergers->GetSize()) { return -1; } else { return fLastAssignedMerger++; } } //______________________________________________________________________________ void TProof::AskForOutput(TSlave *sl) { // Master asks for output from worker sl TMessage sendoutput(kPROOF_SUBMERGER); sendoutput << Int_t(kSendOutput); PDB(kSubmerger, 2) Info("AskForOutput", "worker %s was asked to send its output to master", sl->GetOrdinal()); sendoutput << -1; sendoutput << TString("master"); sendoutput << -1; sl->GetSocket()->Send(sendoutput); if (IsLite()) fMergePrg.IncreaseNWrks(); } //______________________________________________________________________________ void TProof::UpdateDialog() { // Final update of the progress dialog if (!fPlayer) return; // Handle abort ... if (fPlayer->GetExitStatus() == TVirtualProofPlayer::kAborted) { if (fSync) Info("UpdateDialog", "processing was aborted - %lld events processed", fPlayer->GetEventsProcessed()); if (GetRemoteProtocol() > 11) { // New format Progress(-1, fPlayer->GetEventsProcessed(), -1, -1., -1., -1., -1.); } else { Progress(-1, fPlayer->GetEventsProcessed()); } Emit("StopProcess(Bool_t)", kTRUE); } // Handle stop ... if (fPlayer->GetExitStatus() == TVirtualProofPlayer::kStopped) { if (fSync) Info("UpdateDialog", "processing was stopped - %lld events processed", fPlayer->GetEventsProcessed()); if (GetRemoteProtocol() > 25) { // New format Progress(-1, fPlayer->GetEventsProcessed(), -1, -1., -1., -1., -1., -1, -1, -1.); } else if (GetRemoteProtocol() > 11) { Progress(-1, fPlayer->GetEventsProcessed(), -1, -1., -1., -1., -1.); } else { Progress(-1, fPlayer->GetEventsProcessed()); } Emit("StopProcess(Bool_t)", kFALSE); } // Final update of the dialog box if (GetRemoteProtocol() > 25) { // New format EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t,Int_t,Int_t,Float_t)", 10, (Long64_t)(-1), (Long64_t)(-1), (Long64_t)(-1),(Float_t)(-1.),(Float_t)(-1.), (Float_t)(-1.),(Float_t)(-1.),(Int_t)(-1),(Int_t)(-1),(Float_t)(-1.)); } else if (GetRemoteProtocol() > 11) { // New format EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)", 7, (Long64_t)(-1), (Long64_t)(-1), (Long64_t)(-1), (Float_t)(-1.),(Float_t)(-1.),(Float_t)(-1.),(Float_t)(-1.)); } else { EmitVA("Progress(Long64_t,Long64_t)", 2, (Long64_t)(-1), (Long64_t)(-1)); } } //______________________________________________________________________________ void TProof::ActivateAsyncInput() { // Activate the a-sync input handler. TIter next(fSlaves); TSlave *sl; while ((sl = (TSlave*) next())) if (sl->GetInputHandler()) sl->GetInputHandler()->Add(); } //______________________________________________________________________________ void TProof::DeActivateAsyncInput() { // De-activate a-sync input handler. TIter next(fSlaves); TSlave *sl; while ((sl = (TSlave*) next())) if (sl->GetInputHandler()) sl->GetInputHandler()->Remove(); } //______________________________________________________________________________ Int_t TProof::GetActiveMergersCount() { // Get the active mergers count if (!fMergers) return 0; Int_t active_mergers = 0; TIter mergers(fMergers); TMergerInfo *mi = 0; while ((mi = (TMergerInfo *)mergers())) { if (mi->IsActive()) active_mergers++; } return active_mergers; } //______________________________________________________________________________ Bool_t TProof::CreateMerger(TSlave *sl, Int_t port) { // Create a new merger PDB(kSubmerger, 2) Info("CreateMerger", "worker %s will be merger ", sl->GetOrdinal()); PDB(kSubmerger, 2) Info("CreateMerger","Begin"); if (port <= 0) { PDB(kSubmerger,2) Info("CreateMerger", "cannot create merger on port %d - exit", port); return kFALSE; } Int_t mergersToCreate = fMergersCount - fMergers->GetSize(); // Number of pure workers, which are not simply divisible by mergers Int_t rest = fWorkersToMerge % mergersToCreate; // We add one more worker for each of the first 'rest' mergers being established if (rest > 0 && fMergers->GetSize() < rest) { rest = 1; } else { rest = 0; } Int_t workers = (fWorkersToMerge / mergersToCreate) + rest; TMergerInfo * merger = new TMergerInfo(sl, port, workers); TMessage bemerger(kPROOF_SUBMERGER); bemerger << Int_t(kBeMerger); bemerger << fMergers->GetSize(); bemerger << workers; sl->GetSocket()->Send(bemerger); PDB(kSubmerger,2) Info("CreateMerger", "merger #%d (port: %d) for %d workers started", fMergers->GetSize(), port, workers); fMergers->Add(merger); fWorkersToMerge = fWorkersToMerge - workers; fRedirectNext = workers / 2; PDB(kSubmerger, 2) Info("CreateMerger", "exit"); return kTRUE; } //______________________________________________________________________________ void TProof::MarkBad(TSlave *wrk, const char *reason) { // Add a bad slave server to the bad slave list and remove it from // the active list and from the two monitor objects. Assume that the work // done by this worker was lost and ask packerizer to reassign it. R__LOCKGUARD2(fCloseMutex); // We may have been invalidated in the meanwhile: nothing to do in such a case if (!IsValid()) return; if (!wrk) { Error("MarkBad", "worker instance undefined: protocol error? "); return; } // Local URL static TString thisurl; if (thisurl.IsNull()) { if (IsMaster()) { Int_t port = gEnv->GetValue("ProofServ.XpdPort",-1); thisurl = (port > 0) ? Form("%s:%d", TUrl(gSystem->HostName()).GetHostFQDN(), port) : TUrl(gSystem->HostName()).GetHostFQDN(); } else { thisurl = Form("%s@%s:%d", fUrl.GetUser(), fUrl.GetHost(), fUrl.GetPort()); } } if (!reason || strcmp(reason, kPROOF_TerminateWorker)) { // Message for notification const char *mastertype = (gProofServ && gProofServ->IsTopMaster()) ? "top master" : "master"; TString src = IsMaster() ? Form("%s at %s", mastertype, thisurl.Data()) : "local session"; TString msg(Form("\n +++ Message from %s : ", src.Data())); msg += Form("marking %s:%d (%s) as bad\n +++ Reason: %s", wrk->GetName(), wrk->GetPort(), wrk->GetOrdinal(), (reason && strlen(reason)) ? reason : "unknown"); Info("MarkBad", "%s", msg.Data()); // Notify one level up, if the case // Add some hint for diagnostics if (gProofServ) { msg += Form("\n\n +++ Most likely your code crashed on worker %s at %s:%d.\n", wrk->GetOrdinal(), wrk->GetName(), wrk->GetPort()); } else { msg = Form("\n\n +++ Most likely your code crashed\n"); } msg += Form(" +++ Please check the session logs for error messages either using\n"); msg += Form(" +++ the 'Show logs' button or executing\n"); msg += Form(" +++\n"); if (gProofServ) { msg += Form(" +++ root [] TProof::Mgr(\"%s\")->GetSessionLogs()->Display(\"%s\",0)\n\n", thisurl.Data(), wrk->GetOrdinal()); gProofServ->SendAsynMessage(msg, kTRUE); } else { msg += Form(" +++ root [] TProof::Mgr(\"%s\")->GetSessionLogs()->Display(\"*\")\n\n", thisurl.Data()); Printf("%s", msg.Data()); } } else if (reason) { if (gDebug > 0) { Info("MarkBad", "worker %s at %s:%d asked to terminate", wrk->GetOrdinal(), wrk->GetName(), wrk->GetPort()); } } if (IsMaster() && reason) { if (strcmp(reason, kPROOF_TerminateWorker)) { // if the reason was not a planned termination TList *listOfMissingFiles = 0; if (!(listOfMissingFiles = (TList *)GetOutput("MissingFiles"))) { listOfMissingFiles = new TList(); listOfMissingFiles->SetName("MissingFiles"); if (fPlayer) fPlayer->AddOutputObject(listOfMissingFiles); } // If a query is being processed, assume that the work done by // the worker was lost and needs to be reassigned. TVirtualPacketizer *packetizer = fPlayer ? fPlayer->GetPacketizer() : 0; if (packetizer) { // the worker was lost so do resubmit the packets packetizer->MarkBad(wrk, 0, &listOfMissingFiles); } } else { // Tell the coordinator that we are gone if (gProofServ) { TString ord(wrk->GetOrdinal()); Int_t id = ord.Last('.'); if (id != kNPOS) ord.Remove(0, id+1); gProofServ->ReleaseWorker(ord.Data()); } } } fActiveSlaves->Remove(wrk); FindUniqueSlaves(); fAllMonitor->Remove(wrk->GetSocket()); fActiveMonitor->Remove(wrk->GetSocket()); fSendGroupView = kTRUE; if (IsMaster()) { if (reason && !strcmp(reason, kPROOF_TerminateWorker)) { // if the reason was a planned termination then delete the worker and // remove it from all the lists fSlaves->Remove(wrk); fBadSlaves->Remove(wrk); fActiveSlaves->Remove(wrk); fInactiveSlaves->Remove(wrk); fUniqueSlaves->Remove(wrk); fAllUniqueSlaves->Remove(wrk); fNonUniqueMasters->Remove(wrk); delete wrk; } else { fBadSlaves->Add(wrk); wrk->Close(); } // Update session workers files SaveWorkerInfo(); } else { // On clients the proof session should be removed from the lists // and deleted, since it is not valid anymore fSlaves->Remove(wrk); if (fManager) fManager->DiscardSession(this); } } //______________________________________________________________________________ void TProof::MarkBad(TSocket *s, const char *reason) { // Add slave with socket s to the bad slave list and remove if from // the active list and from the two monitor objects. R__LOCKGUARD2(fCloseMutex); // We may have been invalidated in the meanwhile: nothing to do in such a case if (!IsValid()) return; TSlave *wrk = FindSlave(s); MarkBad(wrk, reason); } //______________________________________________________________________________ void TProof::TerminateWorker(TSlave *wrk) { // Ask an active worker 'wrk' to terminate, i.e. to shutdown if (!wrk) { Warning("TerminateWorker", "worker instance undefined: protocol error? "); return; } // Send stop message if (wrk->GetSocket() && wrk->GetSocket()->IsValid()) { TMessage mess(kPROOF_STOP); wrk->GetSocket()->Send(mess); } else { if (gDebug > 0) Info("TerminateWorker", "connection to worker is already down: cannot" " send termination message"); } // This is a bad worker from now on MarkBad(wrk, kPROOF_TerminateWorker); } //______________________________________________________________________________ void TProof::TerminateWorker(const char *ord) { // Ask an active worker 'ord' to terminate, i.e. to shutdown if (ord && strlen(ord) > 0) { Bool_t all = (ord[0] == '*') ? kTRUE : kFALSE; if (IsMaster()) { TIter nxw(fSlaves); TSlave *wrk = 0; while ((wrk = (TSlave *)nxw())) { if (all || !strcmp(wrk->GetOrdinal(), ord)) { TerminateWorker(wrk); if (!all) break; } } } else { TMessage mess(kPROOF_STOP); mess << TString(ord); Broadcast(mess); } } } //______________________________________________________________________________ Int_t TProof::Ping() { // Ping PROOF. Returns 1 if master server responded. return Ping(kActive); } //______________________________________________________________________________ Int_t TProof::Ping(ESlaves list) { // Ping PROOF slaves. Returns the number of slaves that responded. TList *slaves = 0; if (list == kAll) slaves = fSlaves; if (list == kActive) slaves = fActiveSlaves; if (list == kUnique) slaves = fUniqueSlaves; if (list == kAllUnique) slaves = fAllUniqueSlaves; if (slaves->GetSize() == 0) return 0; int nsent = 0; TIter next(slaves); TSlave *sl; while ((sl = (TSlave *)next())) { if (sl->IsValid()) { if (sl->Ping() == -1) { MarkBad(sl, "ping unsuccessful"); } else { nsent++; } } } return nsent; } //______________________________________________________________________________ void TProof::Touch() { // Ping PROOF slaves. Returns the number of slaves that responded. TList *slaves = fSlaves; if (slaves->GetSize() == 0) return; TIter next(slaves); TSlave *sl; while ((sl = (TSlave *)next())) { if (sl->IsValid()) { sl->Touch(); } } return; } //______________________________________________________________________________ void TProof::Print(Option_t *option) const { // Print status of PROOF cluster. TString secCont; if (TestBit(TProof::kIsClient)) { Printf("Connected to: %s (%s)", GetMaster(), IsValid() ? "valid" : "invalid"); Printf("Port number: %d", GetPort()); Printf("User: %s", GetUser()); if (gROOT->GetSvnRevision() > 0) Printf("ROOT version|rev: %s|r%d", gROOT->GetVersion(), gROOT->GetSvnRevision()); else Printf("ROOT version: %s", gROOT->GetVersion()); Printf("Architecture-Compiler: %s-%s", gSystem->GetBuildArch(), gSystem->GetBuildCompilerVersion()); TSlave *sl = (TSlave *)fActiveSlaves->First(); if (sl) { TString sc; if (sl->GetSocket()->GetSecContext()) Printf("Security context: %s", sl->GetSocket()->GetSecContext()->AsString(sc)); Printf("Proofd protocol version: %d", sl->GetSocket()->GetRemoteProtocol()); } else { Printf("Security context: Error - No connection"); Printf("Proofd protocol version: Error - No connection"); } Printf("Client protocol version: %d", GetClientProtocol()); Printf("Remote protocol version: %d", GetRemoteProtocol()); Printf("Log level: %d", GetLogLevel()); Printf("Session unique tag: %s", IsValid() ? GetSessionTag() : ""); Printf("Default data pool: %s", IsValid() ? GetDataPoolUrl() : ""); if (IsValid()) const_cast<TProof*>(this)->SendPrint(option); } else { const_cast<TProof*>(this)->AskStatistics(); if (IsParallel()) Printf("*** Master server %s (parallel mode, %d workers):", gProofServ->GetOrdinal(), GetParallel()); else Printf("*** Master server %s (sequential mode):", gProofServ->GetOrdinal()); Printf("Master host name: %s", gSystem->HostName()); Printf("Port number: %d", GetPort()); if (strlen(gProofServ->GetGroup()) > 0) { Printf("User/Group: %s/%s", GetUser(), gProofServ->GetGroup()); } else { Printf("User: %s", GetUser()); } TString ver(gROOT->GetVersion()); if (gROOT->GetSvnRevision() > 0) ver += Form("|r%d", gROOT->GetSvnRevision()); if (gSystem->Getenv("ROOTVERSIONTAG")) ver += Form("|%s", gSystem->Getenv("ROOTVERSIONTAG")); Printf("ROOT version|rev|tag: %s", ver.Data()); Printf("Architecture-Compiler: %s-%s", gSystem->GetBuildArch(), gSystem->GetBuildCompilerVersion()); Printf("Protocol version: %d", GetClientProtocol()); Printf("Image name: %s", GetImage()); Printf("Working directory: %s", gSystem->WorkingDirectory()); Printf("Config directory: %s", GetConfDir()); Printf("Config file: %s", GetConfFile()); Printf("Log level: %d", GetLogLevel()); Printf("Number of workers: %d", GetNumberOfSlaves()); Printf("Number of active workers: %d", GetNumberOfActiveSlaves()); Printf("Number of unique workers: %d", GetNumberOfUniqueSlaves()); Printf("Number of inactive workers: %d", GetNumberOfInactiveSlaves()); Printf("Number of bad workers: %d", GetNumberOfBadSlaves()); Printf("Total MB's processed: %.2f", float(GetBytesRead())/(1024*1024)); Printf("Total real time used (s): %.3f", GetRealTime()); Printf("Total CPU time used (s): %.3f", GetCpuTime()); if (TString(option).Contains("a", TString::kIgnoreCase) && GetNumberOfSlaves()) { Printf("List of workers:"); TList masters; TIter nextslave(fSlaves); while (TSlave* sl = dynamic_cast<TSlave*>(nextslave())) { if (!sl->IsValid()) continue; if (sl->GetSlaveType() == TSlave::kSlave) { sl->Print(option); } else if (sl->GetSlaveType() == TSlave::kMaster) { TMessage mess(kPROOF_PRINT); mess.WriteString(option); if (sl->GetSocket()->Send(mess) == -1) const_cast<TProof*>(this)->MarkBad(sl, "could not send kPROOF_PRINT request"); else masters.Add(sl); } else { Error("Print", "TSlave is neither Master nor Worker"); R__ASSERT(0); } } const_cast<TProof*>(this)->Collect(&masters, fCollectTimeout); } } } //______________________________________________________________________________ Long64_t TProof::Process(TDSet *dset, const char *selector, Option_t *option, Long64_t nentries, Long64_t first) { // Process a data set (TDSet) using the specified selector (.C) file. // Entry- or event-lists should be set in the data set object using // TDSet::SetEntryList. // The return value is -1 in case of error and TSelector::GetStatus() in // in case of success. if (!IsValid() || !fPlayer) return -1; // Set PROOF to running state SetRunStatus(TProof::kRunning); // Resolve query mode fSync = (GetQueryMode(option) == kSync); TString opt(option); if (fSync && (!IsIdle() || IsWaiting())) { // Already queued or processing queries: switch to asynchronous mode Info("Process", "session is in waiting or processing status: switch to asynchronous mode"); fSync = kFALSE; opt.ReplaceAll("SYNC",""); opt += "ASYN"; } // Cleanup old temporary datasets if ((IsIdle() && !IsWaiting()) && fRunningDSets && fRunningDSets->GetSize() > 0) { fRunningDSets->SetOwner(kTRUE); fRunningDSets->Delete(); } // deactivate the default application interrupt handler // ctrl-c's will be forwarded to PROOF to stop the processing TSignalHandler *sh = 0; if (fSync) { if (gApplication) sh = gSystem->RemoveSignalHandler(gApplication->GetSignalHandler()); } Long64_t rv = fPlayer->Process(dset, selector, opt.Data(), nentries, first); if (fSync) { // reactivate the default application interrupt handler if (sh) gSystem->AddSignalHandler(sh); } return rv; } //______________________________________________________________________________ Long64_t TProof::Process(TFileCollection *fc, const char *selector, Option_t *option, Long64_t nentries, Long64_t first) { // Process a data set (TFileCollection) using the specified selector (.C) file. // The default tree is analyzed (i.e. the first one found). To specify another // tree, the default tree can be changed using TFileCollection::SetDefaultMetaData . // The return value is -1 in case of error and TSelector::GetStatus() in // in case of success. if (!IsValid() || !fPlayer) return -1; if (fProtocol < 17) { Info("Process", "server version < 5.18/00:" " processing of TFileCollection not supported"); return -1; } // We include the TFileCollection to the input list and we create a // fake TDSet with infor about it TDSet *dset = new TDSet(Form("TFileCollection:%s", fc->GetName()), 0, 0, ""); fPlayer->AddInput(fc); Long64_t retval = Process(dset, selector, option, nentries, first); fPlayer->GetInputList()->Remove(fc); // To avoid problems in future // Cleanup if (IsLite() && !fSync) { if (!fRunningDSets) fRunningDSets = new TList; fRunningDSets->Add(dset); } else { delete dset; } return retval; } //______________________________________________________________________________ Long64_t TProof::Process(const char *dsetname, const char *selector, Option_t *option, Long64_t nentries, Long64_t first, TObject *elist) { // Process a dataset which is stored on the master with name 'dsetname'. // The syntax for dsetname is name[#[dir/]objname], e.g. // "mydset" analysis of the first tree in the top dir of the dataset // named "mydset" // "mydset#T" analysis tree "T" in the top dir of the dataset // named "mydset" // "mydset#adir/T" analysis tree "T" in the dir "adir" of the dataset // named "mydset" // "mydset#adir/" analysis of the first tree in the dir "adir" of the // dataset named "mydset" // The component 'name' in its more general form contains also the group and // user name following "/<group>/<user>/<dsname>". Each of these components // can contain one or more wildcards '*', in which case all the datasets matching // the expression are added together as a global dataset (wildcard support has // been added in version 5.27/02). // The last argument 'elist' specifies an entry- or event-list to be used as // event selection. // It is also possible (starting w/ version 5.27/02) to run on multiple datasets // at once in a more flexible way that the one provided by wildcarding. There // are three possibilities: // 1) specifying the dataset names separated by the OR operator '|', e.g. // dsetname = "<dset1>|<dset2>|<dset3>|..." // in this case the datasets are a seen as a global unique dataset // 2) specifying the dataset names separated by a ',' or a ' ', e.g. // dsetname = "<dset1>,<dset2> <dset3>,..." // in this case the datasets are processed one after the other and the // selector is notified when switching dataset via a bit in the current // processed element. // 3) giving the path of a textfile where the dataset names are specified // on one or multiple lines; the lines found are joined as in 1), unless // the filepath is followed by a ',' (i.e. p->Process("datasets.txt,",...) // with the dataset names listed in 'datasets.txt') in which case they are // treated as in 2); the file is open in raw mode with TFile::Open and // therefore it cane be remote, e.g. on a Web server. // Each <dsetj> has the format specified above for the single dataset processing, // included wildcarding (the name of the tree and subdirectory must be same for // all the datasets). // In the case of multiple datasets, 'elist' is treated a global entry list. // It is possible to specify per-dataset entry lists using the syntax // "mydset[#adir/[T]]?enl=entrylist" // or // "mydset[#adir/[T]]<<entrylist" // Here 'entrylist' is a tag identifying, in the order : // i. a named entry-list in the input list or in the input data list // ii. a named entry-list in memory (in gDirectory) // iii. the path of a file containing the entry-list to be used // In the case ii) and iii) the entry-list object(s) is(are) added to the input // data list. // The return value is -1 in case of error and TSelector::GetStatus() in // in case of success. if (fProtocol < 13) { Info("Process", "processing 'by name' not supported by the server"); return -1; } TString dsname, fname(dsetname); // If the 'dsetname' corresponds to an existing and readable file we will try to // interpretate its content as names of datasets to be processed. One line can contain // more datasets, separated by ',' or '|'. By default the dataset lines will be added // (i.e. joined as in option '|'); if the file name ends with ',' the dataset lines are // joined with ','. const char *separator = (fname.EndsWith(",")) ? "," : "|"; if (!strcmp(separator, ",") || fname.EndsWith("|")) fname.Remove(fname.Length()-1, 1); if (!(gSystem->AccessPathName(fname, kReadPermission))) { TUrl uf(fname, kTRUE); uf.SetOptions(TString::Format("%sfiletype=raw", uf.GetOptions())); TFile *f = TFile::Open(uf.GetUrl()); if (f && !(f->IsZombie())) { const Int_t blen = 8192; char buf[blen]; Long64_t rest = f->GetSize(); while (rest > 0) { Long64_t len = (rest > blen - 1) ? blen - 1 : rest; if (f->ReadBuffer(buf, len)) { Error("Process", "problems reading from file '%s'", fname.Data()); dsname = ""; break; } buf[len] = '\0'; dsname += buf; rest -= len; } f->Close(); SafeDelete(f); // We fail if a failure occured if (rest > 0) return -1; } else { Error("Process", "could not open file '%s'", fname.Data()); return -1; } } if (dsname.IsNull()) { dsname = dsetname; } else { // Remove trailing '\n' if (dsname.EndsWith("\n")) dsname.Remove(dsname.Length()-1, 1); // Replace all '\n' with the proper separator dsname.ReplaceAll("\n", separator); if (gDebug > 0) { Info("Process", "processing multi-dataset read from file '%s':", fname.Data()); Info("Process", " '%s'", dsname.Data()); } } TString names(dsname), name, enl, newname; // If multi-dataset check if server supports it if (fProtocol < 28 && names.Index(TRegexp("[, |]")) != kNPOS) { Info("Process", "multi-dataset processing not supported by the server"); return -1; } TEntryList *el = 0; TString dsobj, dsdir; Int_t from = 0; while (names.Tokenize(name, from, "[, |]")) { newname = name; // Extract the specific entry-list, if any enl = ""; Int_t ienl = name.Index("?enl="); if (ienl == kNPOS) { ienl = name.Index("<<"); if (ienl != kNPOS) { newname.Remove(ienl); ienl += strlen("<<"); } } else { newname.Remove(ienl); ienl += strlen("?enl="); } // Check the name syntax first TString obj, dir("/"); Int_t idxc = newname.Index("#"); if (idxc != kNPOS) { Int_t idxs = newname.Index("/", 1, idxc, TString::kExact); if (idxs != kNPOS) { obj = newname(idxs+1, newname.Length()); dir = newname(idxc+1, newname.Length()); dir.Remove(dir.Index("/") + 1); newname.Remove(idxc); } else { obj = newname(idxc+1, newname.Length()); newname.Remove(idxc); } } else if (newname.Index(":") != kNPOS && newname.Index("://") == kNPOS) { // protection against using ':' instead of '#' Error("Process", "bad name syntax (%s): please use" " a '#' after the dataset name", name.Data()); dsname.ReplaceAll(name, ""); continue; } if (dsobj.IsNull() && dsdir.IsNull()) { // The first one specifies obj and dir dsobj = obj; dsdir = dir; } else if (obj != dsobj || dir != dsdir) { // Inconsistent specification: not supported Warning("Process", "'obj' or 'dir' specification not consistent w/ the first given: ignore"); } // Process the entry-list name, if any if (ienl != kNPOS) { // Get entrylist name or path enl = name(ienl, name.Length()); // If not in the input list ... el = (GetInputList()) ? dynamic_cast<TEntryList *>(GetInputList()->FindObject(enl)) : 0; // ... check the heap if (!el && gDirectory) { if ((el = dynamic_cast<TEntryList *>(gDirectory->FindObject(enl)))) { // Add to the input list (input data not available on master where // this info will be processed) if (fProtocol >= 28) { if (!(GetInputList()->FindObject(el->GetName()))) AddInput(el); } } } // If not in the heap, check a file, if any if (!el) { if (!gSystem->AccessPathName(enl)) { TFile *f = TFile::Open(enl); if (f && !(f->IsZombie()) && f->GetListOfKeys()) { TIter nxk(f->GetListOfKeys()); TKey *k = 0; while ((k = (TKey *) nxk())) { if (!strcmp(k->GetClassName(), "TEntryList")) { if (!el) { if ((el = dynamic_cast<TEntryList *>(f->Get(k->GetName())))) { // Add to the input list (input data not available on master where // this info will be processed) if (fProtocol >= 28) { if (!(GetInputList()->FindObject(el->GetName()))) { el = (TEntryList *) el->Clone(); AddInput(el); } } else { el = (TEntryList *) el->Clone(); } } } else if (strcmp(el->GetName(), k->GetName())) { Warning("Process", "multiple entry lists found in file '%s': the first one is taken;\n" "if this is not what you want, load first the content in memory" "and select it by name ", enl.Data()); } } } } else { Warning("Process","file '%s' cannot be open or is empty - ignoring", enl.Data()); } } } // Transmit the information if (fProtocol >= 28) { newname += "?enl="; if (el) { // An entry list object is avalaible in the input list: add its name newname += el->GetName(); } else { // The entry list object was not found: send the name, the future entry list manager will // find it on the server side newname += enl; } } } // Adjust the name for this dataset dsname.ReplaceAll(name, newname); } // Create the dataset object TDSet *dset = new TDSet(dsname, dsobj, dsdir); // Set entry list if (el && fProtocol < 28) { dset->SetEntryList(el); } else { dset->SetEntryList(elist); } // Run Long64_t retval = Process(dset, selector, option, nentries, first); // Cleanup if (IsLite() && !fSync) { if (!fRunningDSets) fRunningDSets = new TList; fRunningDSets->Add(dset); } else { delete dset; } return retval; } //______________________________________________________________________________ Long64_t TProof::Process(const char *selector, Long64_t n, Option_t *option) { // Generic (non-data based) selector processing: the Process() method of the // specified selector (.C) is called 'n' times. // The return value is -1 in case of error and TSelector::GetStatus() in // in case of success. if (!IsValid()) return -1; if (fProtocol < 16) { Info("Process", "server version < 5.17/04: generic processing not supported"); return -1; } // Fake data set TDSet *dset = new TDSet; dset->SetBit(TDSet::kEmpty); Long64_t retval = Process(dset, selector, option, n); // Cleanup if (IsLite() && !fSync) { if (!fRunningDSets) fRunningDSets = new TList; fRunningDSets->Add(dset); } else { delete dset; } return retval; } //______________________________________________________________________________ Int_t TProof::GetQueryReference(Int_t qry, TString &ref) { // Get reference for the qry-th query in fQueries (as // displayed by ShowQueries). ref = ""; if (qry > 0) { if (!fQueries) GetListOfQueries(); if (fQueries) { TIter nxq(fQueries); TQueryResult *qr = 0; while ((qr = (TQueryResult *) nxq())) if (qr->GetSeqNum() == qry) { ref = Form("%s:%s", qr->GetTitle(), qr->GetName()); return 0; } } } return -1; } //______________________________________________________________________________ Long64_t TProof::Finalize(Int_t qry, Bool_t force) { // Finalize the qry-th query in fQueries. // If force, force retrieval if the query is found in the local list // but has already been finalized (default kFALSE). // If query < 0, finalize current query. // Return 0 on success, -1 on error if (fPlayer) { if (qry > 0) { TString ref; if (GetQueryReference(qry, ref) == 0) { return Finalize(ref, force); } else { Info("Finalize", "query #%d not found", qry); } } else { // The last query return Finalize("", force); } } return -1; } //______________________________________________________________________________ Long64_t TProof::Finalize(const char *ref, Bool_t force) { // Finalize query with reference ref. // If force, force retrieval if the query is found in the local list // but has already been finalized (default kFALSE). // If ref = 0, finalize current query. // Return 0 on success, -1 on error if (fPlayer) { // Get the pointer to the query TQueryResult *qr = (ref && strlen(ref) > 0) ? fPlayer->GetQueryResult(ref) : GetQueryResult(); Bool_t retrieve = kFALSE; TString xref(ref); if (!qr) { if (!xref.IsNull()) { retrieve = kTRUE; } } else { if (qr->IsFinalized()) { if (force) { retrieve = kTRUE; } else { Info("Finalize","query already finalized:" " use Finalize(<qry>,kTRUE) to force new retrieval"); qr = 0; } } else { retrieve = kTRUE; xref.Form("%s:%s", qr->GetTitle(), qr->GetName()); } } if (retrieve) { Retrieve(xref.Data()); qr = fPlayer->GetQueryResult(xref.Data()); } if (qr) return fPlayer->Finalize(qr); } return -1; } //______________________________________________________________________________ Int_t TProof::Retrieve(Int_t qry, const char *path) { // Send retrieve request for the qry-th query in fQueries. // If path is defined save it to path. if (qry > 0) { TString ref; if (GetQueryReference(qry, ref) == 0) return Retrieve(ref, path); else Info("Retrieve", "query #%d not found", qry); } else { Info("Retrieve","positive argument required - do nothing"); } return -1; } //______________________________________________________________________________ Int_t TProof::Retrieve(const char *ref, const char *path) { // Send retrieve request for the query specified by ref. // If path is defined save it to path. // Generic method working for all queries known by the server. if (ref) { TMessage m(kPROOF_RETRIEVE); m << TString(ref); Broadcast(m, kActive); Collect(kActive, fCollectTimeout); // Archive it locally, if required if (path) { // Get pointer to query TQueryResult *qr = fPlayer ? fPlayer->GetQueryResult(ref) : 0; if (qr) { TFile *farc = TFile::Open(path,"UPDATE"); if (!(farc->IsOpen())) { Info("Retrieve", "archive file cannot be open (%s)", path); return 0; } farc->cd(); // Update query status qr->SetArchived(path); // Write to file qr->Write(); farc->Close(); SafeDelete(farc); } else { Info("Retrieve", "query not found after retrieve"); return -1; } } return 0; } return -1; } //______________________________________________________________________________ Int_t TProof::Remove(Int_t qry, Bool_t all) { // Send remove request for the qry-th query in fQueries. if (qry > 0) { TString ref; if (GetQueryReference(qry, ref) == 0) return Remove(ref, all); else Info("Remove", "query #%d not found", qry); } else { Info("Remove","positive argument required - do nothing"); } return -1; } //______________________________________________________________________________ Int_t TProof::Remove(const char *ref, Bool_t all) { // Send remove request for the query specified by ref. // If all = TRUE remove also local copies of the query, if any. // Generic method working for all queries known by the server. // This method can be also used to reset the list of queries // waiting to be processed: for that purpose use ref == "cleanupqueue". if (all) { // Remove also local copies, if any if (fPlayer) fPlayer->RemoveQueryResult(ref); } if (IsLite()) return 0; if (ref) { TMessage m(kPROOF_REMOVE); m << TString(ref); Broadcast(m, kActive); Collect(kActive, fCollectTimeout); return 0; } return -1; } //______________________________________________________________________________ Int_t TProof::Archive(Int_t qry, const char *path) { // Send archive request for the qry-th query in fQueries. if (qry > 0) { TString ref; if (GetQueryReference(qry, ref) == 0) return Archive(ref, path); else Info("Archive", "query #%d not found", qry); } else { Info("Archive","positive argument required - do nothing"); } return -1; } //______________________________________________________________________________ Int_t TProof::Archive(const char *ref, const char *path) { // Send archive request for the query specified by ref. // Generic method working for all queries known by the server. // If ref == "Default", path is understood as a default path for // archiving. if (ref) { TMessage m(kPROOF_ARCHIVE); m << TString(ref) << TString(path); Broadcast(m, kActive); Collect(kActive, fCollectTimeout); return 0; } return -1; } //______________________________________________________________________________ Int_t TProof::CleanupSession(const char *sessiontag) { // Send cleanup request for the session specified by tag. if (sessiontag) { TMessage m(kPROOF_CLEANUPSESSION); m << TString(sessiontag); Broadcast(m, kActive); Collect(kActive, fCollectTimeout); return 0; } return -1; } //_____________________________________________________________________________ void TProof::SetQueryMode(EQueryMode mode) { // Change query running mode to the one specified by 'mode'. fQueryMode = mode; if (gDebug > 0) Info("SetQueryMode","query mode is set to: %s", fQueryMode == kSync ? "Sync" : "Async"); } //______________________________________________________________________________ TProof::EQueryMode TProof::GetQueryMode(Option_t *mode) const { // Find out the query mode based on the current setting and 'mode'. EQueryMode qmode = fQueryMode; if (mode && (strlen(mode) > 0)) { TString m(mode); m.ToUpper(); if (m.Contains("ASYN")) { qmode = kAsync; } else if (m.Contains("SYNC")) { qmode = kSync; } } if (gDebug > 0) Info("GetQueryMode","query mode is set to: %s", qmode == kSync ? "Sync" : "Async"); return qmode; } //______________________________________________________________________________ Long64_t TProof::DrawSelect(TDSet *dset, const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t first) { // Execute the specified drawing action on a data set (TDSet). // Event- or Entry-lists should be set in the data set object using // TDSet::SetEntryList. // Returns -1 in case of error or number of selected events otherwise. if (!IsValid() || !fPlayer) return -1; // Make sure that asynchronous processing is not active if (!IsIdle()) { Info("DrawSelect","not idle, asynchronous Draw not supported"); return -1; } TString opt(option); Int_t idx = opt.Index("ASYN", 0, TString::kIgnoreCase); if (idx != kNPOS) opt.Replace(idx,4,""); return fPlayer->DrawSelect(dset, varexp, selection, opt, nentries, first); } //______________________________________________________________________________ Long64_t TProof::DrawSelect(const char *dsetname, const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t first, TObject *enl) { // Execute the specified drawing action on a data set which is stored on the // master with name 'dsetname'. // The syntax for dsetname is name[#[dir/]objname], e.g. // "mydset" analysis of the first tree in the top dir of the dataset // named "mydset" // "mydset#T" analysis tree "T" in the top dir of the dataset // named "mydset" // "mydset#adir/T" analysis tree "T" in the dir "adir" of the dataset // named "mydset" // "mydset#adir/" analysis of the first tree in the dir "adir" of the // dataset named "mydset" // The last argument 'enl' specifies an entry- or event-list to be used as // event selection. // The return value is -1 in case of error and TSelector::GetStatus() in // in case of success. if (fProtocol < 13) { Info("Process", "processing 'by name' not supported by the server"); return -1; } TString name(dsetname); TString obj; TString dir = "/"; Int_t idxc = name.Index("#"); if (idxc != kNPOS) { Int_t idxs = name.Index("/", 1, idxc, TString::kExact); if (idxs != kNPOS) { obj = name(idxs+1, name.Length()); dir = name(idxc+1, name.Length()); dir.Remove(dir.Index("/") + 1); name.Remove(idxc); } else { obj = name(idxc+1, name.Length()); name.Remove(idxc); } } else if (name.Index(":") != kNPOS && name.Index("://") == kNPOS) { // protection against using ':' instead of '#' Error("DrawSelect", "bad name syntax (%s): please use" " a '#' after the dataset name", dsetname); return -1; } TDSet *dset = new TDSet(name, obj, dir); // Set entry-list, if required dset->SetEntryList(enl); Long64_t retval = DrawSelect(dset, varexp, selection, option, nentries, first); delete dset; return retval; } //______________________________________________________________________________ void TProof::StopProcess(Bool_t abort, Int_t timeout) { // Send STOPPROCESS message to master and workers. PDB(kGlobal,2) Info("StopProcess","enter %d", abort); if (!IsValid()) return; // Flag that we have been stopped ERunStatus rst = abort ? TProof::kAborted : TProof::kStopped; SetRunStatus(rst); if (fPlayer) fPlayer->StopProcess(abort, timeout); // Stop any blocking 'Collect' request; on masters we do this only if // aborting; when stopping, we still need to receive the results if (TestBit(TProof::kIsClient) || abort) InterruptCurrentMonitor(); if (fSlaves->GetSize() == 0) return; // Notify the remote counterpart TSlave *sl; TIter next(fSlaves); while ((sl = (TSlave *)next())) if (sl->IsValid()) // Ask slave to progate the stop/abort request sl->StopProcess(abort, timeout); } //______________________________________________________________________________ void TProof::DisableGoAsyn() { // Signal to disable related switches Emit("DisableGoAsyn()"); } //______________________________________________________________________________ void TProof::GoAsynchronous() { // Send GOASYNC message to the master. if (!IsValid()) return; if (GetRemoteProtocol() < 22) { Info("GoAsynchronous", "functionality not supported by the server - ignoring"); return; } if (fSync && !IsIdle()) { TMessage m(kPROOF_GOASYNC); Broadcast(m); } else { Info("GoAsynchronous", "either idle or already in asynchronous mode - ignoring"); } } //______________________________________________________________________________ void TProof::RecvLogFile(TSocket *s, Int_t size) { // Receive the log file of the slave with socket s. const Int_t kMAXBUF = 16384; //32768 //16384 //65536; char buf[kMAXBUF]; // Append messages to active logging unit Int_t fdout = -1; if (!fLogToWindowOnly) { fdout = (fRedirLog) ? fileno(fLogFileW) : fileno(stdout); if (fdout < 0) { Warning("RecvLogFile", "file descriptor for outputs undefined (%d):" " will not log msgs", fdout); return; } lseek(fdout, (off_t) 0, SEEK_END); } Int_t left, rec, r; Long_t filesize = 0; while (filesize < size) { left = Int_t(size - filesize); if (left > kMAXBUF) left = kMAXBUF; rec = s->RecvRaw(&buf, left); filesize = (rec > 0) ? (filesize + rec) : filesize; if (!fLogToWindowOnly) { if (rec > 0) { char *p = buf; r = rec; while (r) { Int_t w; w = write(fdout, p, r); if (w < 0) { SysError("RecvLogFile", "error writing to unit: %d", fdout); break; } r -= w; p += w; } } else if (rec < 0) { Error("RecvLogFile", "error during receiving log file"); break; } } if (rec > 0) { buf[rec] = 0; EmitVA("LogMessage(const char*,Bool_t)", 2, buf, kFALSE); } } // If idle restore logs to main session window if (fRedirLog && IsIdle() && !TestBit(TProof::kIsMaster)) fRedirLog = kFALSE; } //______________________________________________________________________________ void TProof::NotifyLogMsg(const char *msg, const char *sfx) { // Notify locally 'msg' to the appropriate units (file, stdout, window) // If defined, 'sfx' is added after 'msg' (typically a line-feed); // Must have somenthing to notify Int_t len = 0; if (!msg || (len = strlen(msg)) <= 0) return; // Get suffix length if any Int_t lsfx = (sfx) ? strlen(sfx) : 0; // Append messages to active logging unit Int_t fdout = -1; if (!fLogToWindowOnly) { fdout = (fRedirLog) ? fileno(fLogFileW) : fileno(stdout); if (fdout < 0) { Warning("NotifyLogMsg", "file descriptor for outputs undefined (%d):" " will not notify msgs", fdout); return; } lseek(fdout, (off_t) 0, SEEK_END); } if (!fLogToWindowOnly) { // Write to output unit (stdout or a log file) if (len > 0) { char *p = (char *)msg; Int_t r = len; while (r) { Int_t w = write(fdout, p, r); if (w < 0) { SysError("NotifyLogMsg", "error writing to unit: %d", fdout); break; } r -= w; p += w; } // Add a suffix, if requested if (lsfx > 0) if (write(fdout, sfx, lsfx) != lsfx) SysError("NotifyLogMsg", "error writing to unit: %d", fdout); } } if (len > 0) { // Publish the message to the separate window (if the latter is missing // the message will just get lost) EmitVA("LogMessage(const char*,Bool_t)", 2, msg, kFALSE); } // If idle restore logs to main session window if (fRedirLog && IsIdle()) fRedirLog = kFALSE; } //______________________________________________________________________________ void TProof::LogMessage(const char *msg, Bool_t all) { // Log a message into the appropriate window by emitting a signal. PDB(kGlobal,1) Info("LogMessage","Enter ... %s, 'all: %s", msg ? msg : "", all ? "true" : "false"); if (gROOT->IsBatch()) { PDB(kGlobal,1) Info("LogMessage","GUI not started - use TProof::ShowLog()"); return; } if (msg) EmitVA("LogMessage(const char*,Bool_t)", 2, msg, all); // Re-position at the beginning of the file, if requested. // This is used by the dialog when it re-opens the log window to // provide all the session messages if (all) lseek(fileno(fLogFileR), (off_t) 0, SEEK_SET); const Int_t kMAXBUF = 32768; char buf[kMAXBUF]; Int_t len; do { while ((len = read(fileno(fLogFileR), buf, kMAXBUF-1)) < 0 && TSystem::GetErrno() == EINTR) TSystem::ResetErrno(); if (len < 0) { Error("LogMessage", "error reading log file"); break; } if (len > 0) { buf[len] = 0; EmitVA("LogMessage(const char*,Bool_t)", 2, buf, kFALSE); } } while (len > 0); } //______________________________________________________________________________ Int_t TProof::SendGroupView() { // Send to all active slaves servers the current slave group size // and their unique id. Returns number of active slaves. // Returns -1 in case of error. if (!IsValid()) return -1; if (TestBit(TProof::kIsClient)) return 0; if (!fSendGroupView) return 0; fSendGroupView = kFALSE; TIter next(fActiveSlaves); TSlave *sl; int bad = 0, cnt = 0, size = GetNumberOfActiveSlaves(); char str[32]; while ((sl = (TSlave *)next())) { snprintf(str, 32, "%d %d", cnt, size); if (sl->GetSocket()->Send(str, kPROOF_GROUPVIEW) == -1) { MarkBad(sl, "could not send kPROOF_GROUPVIEW message"); bad++; } else cnt++; } // Send the group view again in case there was a change in the // group size due to a bad slave if (bad) SendGroupView(); return GetNumberOfActiveSlaves(); } //______________________________________________________________________________ Bool_t TProof::GetFileInCmd(const char *cmd, TString &fn) { // Static method to extract the filename (if any) form a CINT command. // Returns kTRUE and the filename in 'fn'; returns kFALSE if not found or not // appliable. TString s = cmd; s = s.Strip(TString::kBoth); if (s.Length() > 0 && (s.BeginsWith(".L") || s.BeginsWith(".x") || s.BeginsWith(".X"))) { TString file = s(2, s.Length()); TString acm, arg, io; fn = gSystem->SplitAclicMode(file, acm, arg, io); if (!fn.IsNull()) return kTRUE; } // Not found return kFALSE; } //______________________________________________________________________________ Int_t TProof::Exec(const char *cmd, Bool_t plusMaster) { // Send command to be executed on the PROOF master and/or slaves. // If plusMaster is kTRUE then exeucte on slaves and master too. // Command can be any legal command line command. Commands like // ".x file.C" or ".L file.C" will cause the file file.C to be send // to the PROOF cluster. Returns -1 in case of error, >=0 in case of // succes. return Exec(cmd, kActive, plusMaster); } //______________________________________________________________________________ Int_t TProof::Exec(const char *cmd, ESlaves list, Bool_t plusMaster) { // Send command to be executed on the PROOF master and/or slaves. // Command can be any legal command line command. Commands like // ".x file.C" or ".L file.C" will cause the file file.C to be send // to the PROOF cluster. Returns -1 in case of error, >=0 in case of // succes. if (!IsValid()) return -1; TString s = cmd; s = s.Strip(TString::kBoth); if (!s.Length()) return 0; // check for macro file and make sure the file is available on all slaves TString filename; if (TProof::GetFileInCmd(s.Data(), filename)) { char *fn = gSystem->Which(TROOT::GetMacroPath(), filename, kReadPermission); if (fn) { if (GetNumberOfUniqueSlaves() > 0) { if (SendFile(fn, kAscii | kForward | kCpBin) < 0) { Error("Exec", "file %s could not be transfered", fn); delete [] fn; return -1; } } else { TString scmd = s(0,3) + fn; Int_t n = SendCommand(scmd, list); delete [] fn; return n; } } else { Error("Exec", "macro %s not found", filename.Data()); return -1; } delete [] fn; } if (plusMaster) { if (IsLite()) { gROOT->ProcessLine(cmd); } else { Int_t n = GetParallel(); SetParallelSilent(0); Int_t res = SendCommand(cmd, list); SetParallelSilent(n); if (res < 0) return res; } } return SendCommand(cmd, list); } //______________________________________________________________________________ Int_t TProof::SendCommand(const char *cmd, ESlaves list) { // Send command to be executed on the PROOF master and/or slaves. // Command can be any legal command line command, however commands // like ".x file.C" or ".L file.C" will not cause the file.C to be // transfered to the PROOF cluster. In that case use TProof::Exec(). // Returns the status send by the remote server as part of the // kPROOF_LOGDONE message. Typically this is the return code of the // command on the remote side. Returns -1 in case of error. if (!IsValid()) return -1; Broadcast(cmd, kMESS_CINT, list); Collect(list); return fStatus; } //______________________________________________________________________________ Int_t TProof::SendCurrentState(ESlaves list) { // Transfer the current state of the master to the active slave servers. // The current state includes: the current working directory, etc. // Returns the number of active slaves. Returns -1 in case of error. if (!IsValid()) return -1; // Go to the new directory, reset the interpreter environment and // tell slave to delete all objects from its new current directory. Broadcast(gDirectory->GetPath(), kPROOF_RESET, list); return GetParallel(); } //______________________________________________________________________________ Int_t TProof::SendInitialState() { // Transfer the initial (i.e. current) state of the master to all // slave servers. Currently the initial state includes: log level. // Returns the number of active slaves. Returns -1 in case of error. if (!IsValid()) return -1; SetLogLevel(fLogLevel, gProofDebugMask); return GetNumberOfActiveSlaves(); } //______________________________________________________________________________ Bool_t TProof::CheckFile(const char *file, TSlave *slave, Long_t modtime, Int_t cpopt) { // Check if a file needs to be send to the slave. Use the following // algorithm: // - check if file appears in file map // - if yes, get file's modtime and check against time in map, // if modtime not same get md5 and compare against md5 in map, // if not same return kTRUE. // - if no, get file's md5 and modtime and store in file map, ask // slave if file exists with specific md5, if yes return kFALSE, // if no return kTRUE. // The options 'cpopt' define if to copy things from cache to sandbox and what. // To retrieve from the cache the binaries associated with the file TProof::kCpBin // must be set in cpopt; the default is copy everything. // Returns kTRUE in case file needs to be send, returns kFALSE in case // file is already on remote node. Bool_t sendto = kFALSE; // create worker based filename TString sn = slave->GetName(); sn += ":"; sn += slave->GetOrdinal(); sn += ":"; sn += gSystem->BaseName(file); // check if file is in map FileMap_t::const_iterator it; if ((it = fFileMap.find(sn)) != fFileMap.end()) { // file in map MD5Mod_t md = (*it).second; if (md.fModtime != modtime) { TMD5 *md5 = TMD5::FileChecksum(file); if (md5) { if ((*md5) != md.fMD5) { sendto = kTRUE; md.fMD5 = *md5; md.fModtime = modtime; fFileMap[sn] = md; // When on the master, the master and/or slaves may share // their file systems and cache. Therefore always make a // check for the file. If the file already exists with the // expected md5 the kPROOF_CHECKFILE command will cause the // file to be copied from cache to slave sandbox. if (TestBit(TProof::kIsMaster)) { sendto = kFALSE; TMessage mess(kPROOF_CHECKFILE); mess << TString(gSystem->BaseName(file)) << md.fMD5 << cpopt; slave->GetSocket()->Send(mess); fCheckFileStatus = 0; Collect(slave, fCollectTimeout, kPROOF_CHECKFILE); sendto = (fCheckFileStatus == 0) ? kTRUE : kFALSE; } } delete md5; } else { Error("CheckFile", "could not calculate local MD5 check sum - dont send"); return kFALSE; } } } else { // file not in map TMD5 *md5 = TMD5::FileChecksum(file); MD5Mod_t md; if (md5) { md.fMD5 = *md5; md.fModtime = modtime; fFileMap[sn] = md; delete md5; } else { Error("CheckFile", "could not calculate local MD5 check sum - dont send"); return kFALSE; } TMessage mess(kPROOF_CHECKFILE); mess << TString(gSystem->BaseName(file)) << md.fMD5 << cpopt; slave->GetSocket()->Send(mess); fCheckFileStatus = 0; Collect(slave, fCollectTimeout, kPROOF_CHECKFILE); sendto = (fCheckFileStatus == 0) ? kTRUE : kFALSE; } return sendto; } //______________________________________________________________________________ Int_t TProof::SendFile(const char *file, Int_t opt, const char *rfile, TSlave *wrk) { // Send a file to master or slave servers. Returns number of slaves // the file was sent to, maybe 0 in case master and slaves have the same // file system image, -1 in case of error. // If defined, send to worker 'wrk' only. // If defined, the full path of the remote path will be rfile. // If rfile = "cache" the file is copied to the remote cache instead of the sandbox // (to copy to the cache on a different name use rfile = "cache:newname"). // The mask 'opt' is an or of ESendFileOpt: // // kAscii (0x0) if set true ascii file transfer is used // kBinary (0x1) if set true binary file transfer is used // kForce (0x2) if not set an attempt is done to find out // whether the file really needs to be downloaded // (a valid copy may already exist in the cache // from a previous run); the bit is set by // UploadPackage, since the check is done elsewhere. // kForward (0x4) if set, ask server to forward the file to slave // or submaster (meaningless for slave servers). // kCpBin (0x8) Retrieve from the cache the binaries associated // with the file // kCp (0x10) Retrieve the files from the cache // if (!IsValid()) return -1; // Use the active slaves list ... TList *slaves = (rfile && !strcmp(rfile, "cache")) ? fUniqueSlaves : fActiveSlaves; // ... or the specified slave, if any if (wrk) { slaves = new TList(); slaves->Add(wrk); } if (slaves->GetSize() == 0) return 0; #ifndef R__WIN32 Int_t fd = open(file, O_RDONLY); #else Int_t fd = open(file, O_RDONLY | O_BINARY); #endif if (fd < 0) { SysError("SendFile", "cannot open file %s", file); return -1; } // Get info about the file Long64_t size; Long_t id, flags, modtime; if (gSystem->GetPathInfo(file, &id, &size, &flags, &modtime) == 1) { Error("SendFile", "cannot stat file %s", file); return -1; } if (size == 0) { Error("SendFile", "empty file %s", file); return -1; } // Decode options Bool_t bin = (opt & kBinary) ? kTRUE : kFALSE; Bool_t force = (opt & kForce) ? kTRUE : kFALSE; Bool_t fw = (opt & kForward) ? kTRUE : kFALSE; // Copy options Int_t cpopt = 0; if ((opt & kCp)) cpopt |= kCp; if ((opt & kCpBin)) cpopt |= (kCp | kCpBin); const Int_t kMAXBUF = 32768; //16384 //65536; char buf[kMAXBUF]; Int_t nsl = 0; TIter next(slaves); TSlave *sl; TString fnam(rfile); if (fnam == "cache") { fnam += Form(":%s", gSystem->BaseName(file)); } else if (fnam.IsNull()) { fnam = gSystem->BaseName(file); } // List on which we will collect the results while ((sl = (TSlave *)next())) { if (!sl->IsValid()) continue; Bool_t sendto = force ? kTRUE : CheckFile(file, sl, modtime, cpopt); // Don't send the kPROOF_SENDFILE command to real slaves when sendto // is false. Masters might still need to send the file to newly added // slaves. PDB(kPackage,2) { const char *snd = (sl->fSlaveType == TSlave::kSlave && sendto) ? "" : "not"; Info("SendFile", "%s sending file %s to: %s:%s (%d)", snd, file, sl->GetName(), sl->GetOrdinal(), sendto); } if (sl->fSlaveType == TSlave::kSlave && !sendto) continue; // The value of 'size' is used as flag remotely, so we need to // reset it to 0 if we are not going to send the file Long64_t siz = sendto ? size : 0; snprintf(buf, kMAXBUF, "%s %d %lld %d", fnam.Data(), bin, siz, fw); if (sl->GetSocket()->Send(buf, kPROOF_SENDFILE) == -1) { MarkBad(sl, "could not send kPROOF_SENDFILE request"); continue; } if (sendto) { lseek(fd, 0, SEEK_SET); Int_t len; do { while ((len = read(fd, buf, kMAXBUF)) < 0 && TSystem::GetErrno() == EINTR) TSystem::ResetErrno(); if (len < 0) { SysError("SendFile", "error reading from file %s", file); Interrupt(kSoftInterrupt, kActive); close(fd); return -1; } if (len > 0 && sl->GetSocket()->SendRaw(buf, len) == -1) { SysError("SendFile", "error writing to slave %s:%s (now offline)", sl->GetName(), sl->GetOrdinal()); MarkBad(sl, "sendraw failure"); sl = 0; break; } } while (len > 0); nsl++; } // Wait for the operation to be done if (sl) Collect(sl, fCollectTimeout, kPROOF_SENDFILE); } close(fd); // Cleanup temporary list, if any if (slaves != fActiveSlaves && slaves != fUniqueSlaves) SafeDelete(slaves); return nsl; } //______________________________________________________________________________ Int_t TProof::SendObject(const TObject *obj, ESlaves list) { // Send object to master or slave servers. Returns number of slaves object // was sent to, -1 in case of error. if (!IsValid() || !obj) return -1; TMessage mess(kMESS_OBJECT); mess.WriteObject(obj); return Broadcast(mess, list); } //______________________________________________________________________________ Int_t TProof::SendPrint(Option_t *option) { // Send print command to master server. Returns number of slaves message // was sent to. Returns -1 in case of error. if (!IsValid()) return -1; Broadcast(option, kPROOF_PRINT, kActive); return Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ void TProof::SetLogLevel(Int_t level, UInt_t mask) { // Set server logging level. char str[32]; fLogLevel = level; gProofDebugLevel = level; gProofDebugMask = (TProofDebug::EProofDebugMask) mask; snprintf(str, 32, "%d %u", level, mask); Broadcast(str, kPROOF_LOGLEVEL, kAll); } //______________________________________________________________________________ void TProof::SetRealTimeLog(Bool_t on) { // Switch ON/OFF the real-time logging facility. When this option is // ON, log messages from processing are sent back as they come, instead of // being sent back at the end in one go. This may help debugging or monitoring // in some cases, but, depending on the amount of log, it may have significant // consequencies on the load over the network, so it must be used with care. if (IsValid()) { TMessage mess(kPROOF_REALTIMELOG); mess << on; Broadcast(mess); } else { Warning("SetRealTimeLog","session is invalid - do nothing"); } } //______________________________________________________________________________ Int_t TProof::SetParallelSilent(Int_t nodes, Bool_t random) { // Tell PROOF how many slaves to use in parallel. If random is TRUE a random // selection is done (if nodes is less than the available nodes). // Returns the number of parallel slaves. Returns -1 in case of error. if (!IsValid()) return -1; if (TestBit(TProof::kIsMaster)) { GoParallel(nodes, kFALSE, random); return SendCurrentState(); } else { PDB(kGlobal,1) Info("SetParallelSilent", "request %d node%s", nodes, nodes == 1 ? "" : "s"); TMessage mess(kPROOF_PARALLEL); mess << nodes << random; Broadcast(mess); Collect(kActive, fCollectTimeout); Int_t n = GetParallel(); PDB(kGlobal,1) Info("SetParallelSilent", "got %d node%s", n, n == 1 ? "" : "s"); return n; } } //______________________________________________________________________________ Int_t TProof::SetParallel(Int_t nodes, Bool_t random) { // Tell PROOF how many slaves to use in parallel. Returns the number of // parallel slaves. Returns -1 in case of error. Int_t n = SetParallelSilent(nodes, random); if (TestBit(TProof::kIsClient)) { if (n < 1) { Printf("PROOF set to sequential mode"); } else { TString subfix = (n == 1) ? "" : "s"; if (random) subfix += ", randomly selected"; Printf("PROOF set to parallel mode (%d worker%s)", n, subfix.Data()); } } return n; } //______________________________________________________________________________ Int_t TProof::GoParallel(Int_t nodes, Bool_t attach, Bool_t random) { // Go in parallel mode with at most "nodes" slaves. Since the fSlaves // list is sorted by slave performace the active list will contain first // the most performant nodes. Returns the number of active slaves. // If random is TRUE, and nodes is less than the number of available workers, // a random selection is done. // Returns -1 in case of error. if (!IsValid()) return -1; if (nodes < 0) nodes = 0; fActiveSlaves->Clear(); fActiveMonitor->RemoveAll(); // Prepare the list of candidates first. // Algorithm depends on random option. TSlave *sl = 0; TList *wlst = new TList; TIter nxt(fSlaves); fInactiveSlaves->Clear(); while ((sl = (TSlave *)nxt())) { if (sl->IsValid() && !fBadSlaves->FindObject(sl)) { if (strcmp("IGNORE", sl->GetImage()) == 0) continue; if ((sl->GetSlaveType() != TSlave::kSlave) && (sl->GetSlaveType() != TSlave::kMaster)) { Error("GoParallel", "TSlave is neither Master nor Slave"); R__ASSERT(0); } // Good candidate wlst->Add(sl); // Set it inactive fInactiveSlaves->Add(sl); sl->SetStatus(TSlave::kInactive); } } Int_t nwrks = (nodes > wlst->GetSize()) ? wlst->GetSize() : nodes; int cnt = 0; fEndMaster = TestBit(TProof::kIsMaster) ? kTRUE : kFALSE; while (cnt < nwrks) { // Random choice, if requested if (random) { Int_t iwrk = (Int_t) (gRandom->Rndm() * wlst->GetSize()); sl = (TSlave *) wlst->At(iwrk); } else { // The first available sl = (TSlave *) wlst->First(); } if (!sl) { Error("GoParallel", "attaching to candidate!"); break; } // Remove from the list wlst->Remove(sl); Int_t slavenodes = 0; if (sl->GetSlaveType() == TSlave::kSlave) { sl->SetStatus(TSlave::kActive); fActiveSlaves->Add(sl); fInactiveSlaves->Remove(sl); fActiveMonitor->Add(sl->GetSocket()); slavenodes = 1; } else if (sl->GetSlaveType() == TSlave::kMaster) { fEndMaster = kFALSE; TMessage mess(kPROOF_PARALLEL); if (!attach) { mess << nodes-cnt; } else { // To get the number of slaves mess.SetWhat(kPROOF_LOGFILE); mess << -1 << -1; } if (sl->GetSocket()->Send(mess) == -1) { MarkBad(sl, "could not send kPROOF_PARALLEL or kPROOF_LOGFILE request"); slavenodes = 0; } else { Collect(sl, fCollectTimeout); if (sl->IsValid()) { sl->SetStatus(TSlave::kActive); fActiveSlaves->Add(sl); fInactiveSlaves->Remove(sl); fActiveMonitor->Add(sl->GetSocket()); if (sl->GetParallel() > 0) { slavenodes = sl->GetParallel(); } else { // Sequential mode: the master acts as a worker slavenodes = 1; } } else { MarkBad(sl, "collect failed after kPROOF_PARALLEL or kPROOF_LOGFILE request"); slavenodes = 0; } } } // 'slavenodes' may be different than 1 in multimaster setups cnt += slavenodes; } // Cleanup list wlst->SetOwner(0); SafeDelete(wlst); // Get slave status (will set the slaves fWorkDir correctly) AskStatistics(); // Find active slaves with unique image FindUniqueSlaves(); // Send new group-view to slaves if (!attach) SendGroupView(); Int_t n = GetParallel(); if (TestBit(TProof::kIsClient)) { if (n < 1) printf("PROOF set to sequential mode\n"); else printf("PROOF set to parallel mode (%d worker%s)\n", n, n == 1 ? "" : "s"); } PDB(kGlobal,1) Info("GoParallel", "got %d node%s", n, n == 1 ? "" : "s"); return n; } //______________________________________________________________________________ void TProof::ShowData() { // List contents of the data directory in the sandbox. // This is the place where files produced by the client queries are kept if (!IsValid() || !fManager) return; // This is run via the manager fManager->Find("~/data", "-type f", "all"); } //______________________________________________________________________________ void TProof::ClearData(UInt_t what, const char *dsname) { // Remove files for the data directory. // The option 'what' can take the values: // kPurge remove all files and directories under '~/data' // kUnregistered remove only files not in registered datasets (default) // kDataset remove files belonging to dataset 'dsname' // User is prompt for confirmation, unless kForceClear is ORed with the option if (!IsValid() || !fManager) return; // Check whether we need to prompt TString prompt, a("Y"); Bool_t force = (what & kForceClear) ? kTRUE : kFALSE; Bool_t doask = (!force && isatty(0) != 0 && isatty(1) != 0) ? kTRUE : kFALSE; // If all just send the request if ((what & TProof::kPurge)) { // Prompt, if requested if (doask && !Prompt("Do you really want to remove all data files")) return; fManager->Rm("~/data/*", "-rf", "all"); return; } else if ((what & TProof::kDataset)) { // We must have got a name if (!dsname || strlen(dsname) <= 0) { Error("ClearData", "dataset name mandatory when removing a full dataset"); return; } // Check if the dataset is registered if (!ExistsDataSet(dsname)) { Error("ClearData", "dataset '%s' does not exists", dsname); return; } // Get the file content TFileCollection *fc = GetDataSet(dsname); if (!fc) { Error("ClearData", "could not retrieve info about dataset '%s'", dsname); return; } // Prompt, if requested if (doask && !Prompt(TString::Format("Do you really want to remove all data files" " of dataset '%s'", dsname))) return; // Loop through the files Bool_t rmds = kTRUE; TIter nxf(fc->GetList()); TFileInfo *fi = 0; Int_t rfiles = 0, nfiles = fc->GetList()->GetSize(); while ((fi = (TFileInfo *) nxf())) { // Fill the host info TString host, file; // Take info from the current url TUrl uf(*(fi->GetFirstUrl())); file = uf.GetFile(); host = uf.GetHost(); // Now search for any "file:" url Int_t nurl = fi->GetNUrls(); fi->ResetUrl(); TUrl *up = 0; while (nurl-- && fi->NextUrl()) { up = fi->GetCurrentUrl(); if (!strcmp(up->GetProtocol(), "file")) { TString opt(up->GetOptions()); if (opt.BeginsWith("node=")) { host=opt; host.ReplaceAll("node=",""); file = up->GetFile(); break; } } } // Issue a remove request now if (fManager->Rm(file.Data(), "-f", host.Data()) != 0) { Error("ClearData", "problems removing '%s'", file.Data()); // Some files not removed: keep the meta info about this dataset rmds = kFALSE; } rfiles++; ClearDataProgress(rfiles, nfiles); } fprintf(stderr, "\n"); if (rmds) { // All files were removed successfully: remove also the dataset meta info RemoveDataSet(dsname); } } else if (what &TProof::kUnregistered) { // Get the existing files TString outtmp("ProofClearData_"); FILE *ftmp = gSystem->TempFileName(outtmp); if (!ftmp) { Error("ClearData", "cannot create temp file for logs"); return; } fclose(ftmp); RedirectHandle_t h; gSystem->RedirectOutput(outtmp.Data(), "w", &h); ShowData(); gSystem->RedirectOutput(0, 0, &h); // Parse the output file now ifstream in; in.open(outtmp.Data()); if (!in.is_open()) { Error("ClearData", "could not open temp file for logs: %s", outtmp.Data()); gSystem->Unlink(outtmp); return; } // Go through Int_t nfiles = 0; TMap *afmap = new TMap; TString line, host, file; Int_t from = 0; while (in.good()) { line.ReadLine(in); if (line.IsNull()) continue; while (line.EndsWith("\n")) { line.Strip(TString::kTrailing, '\n'); } from = 0; if (line.Tokenize(host, from, "| ")) line.Tokenize(file, from, "| "); if (!host.IsNull() && !file.IsNull()) { TList *fl = (TList *) afmap->GetValue(host.Data()); if (!fl) { fl = new TList(); fl->SetName(host); afmap->Add(new TObjString(host), fl); } fl->Add(new TObjString(file)); nfiles++; PDB(kDataset,2) Info("ClearData", "added info for: h:%s, f:%s", host.Data(), file.Data()); } else { Warning("ClearData", "found incomplete line: '%s'", line.Data()); } } // Close and remove the file in.close(); gSystem->Unlink(outtmp); // Get registered data files TString sel = TString::Format("/%s/%s/", GetGroup(), GetUser()); TMap *fcmap = GetDataSets(sel); if (!fcmap || fcmap->GetSize() <= 0) { PDB(kDataset,1) Info("ClearData", "no dataset beloning to '%s'", sel.Data()); SafeDelete(fcmap); return; } // Go thorugh and prepare the lists per node TString opt; TIter nxfc(fcmap); TObjString *os = 0; while ((os = (TObjString *) nxfc())) { TFileCollection *fc = 0; if ((fc = (TFileCollection *) fcmap->GetValue(os))) { TFileInfo *fi = 0; TIter nxfi(fc->GetList()); while ((fi = (TFileInfo *) nxfi())) { // Get special "file:" url fi->ResetUrl(); Int_t nurl = fi->GetNUrls(); TUrl *up = 0; while (nurl-- && fi->NextUrl()) { up = fi->GetCurrentUrl(); if (!strcmp(up->GetProtocol(), "file")) { opt = up->GetOptions(); if (opt.BeginsWith("node=")) { host=opt; host.ReplaceAll("node=",""); file = up->GetFile(); PDB(kDataset,2) Info("ClearData", "found: host: %s, file: %s", host.Data(), file.Data()); // Remove this from the full list, if there TList *fl = (TList *) afmap->GetValue(host.Data()); if (fl) { TObjString *fn = (TObjString *) fl->FindObject(file.Data()); if (fn) { fl->Remove(fn); SafeDelete(fn); nfiles--; } else { Warning("ClearData", "registered file '%s' not found in the full list!", file.Data()); } } break; } } } } } } // Clean up the the received map fcmap->SetOwner(kTRUE); SafeDelete(fcmap); // List of the files to be removed Info("ClearData", "%d unregistered files to be removed:", nfiles); afmap->Print(); // Prompt, if requested if (doask && !Prompt(TString::Format("Do you really want to remove all %d" " unregistered data files", nfiles))) return; // Remove one by one; we may implement a bloc remove in the future Int_t rfiles = 0; TIter nxls(afmap); while ((os = (TObjString *) nxls())) { TList *fl = 0; if ((fl = (TList *) afmap->GetValue(os))) { TIter nxf(fl); TObjString *fn = 0; while ((fn = (TObjString *) nxf())) { // Issue a remove request now if (fManager->Rm(fn->GetName(), "-f", os->GetName()) != 0) { Error("ClearData", "problems removing '%s' on host '%s'", fn->GetName(), os->GetName()); } rfiles++; ClearDataProgress(rfiles, nfiles); } } } fprintf(stderr, "\n"); // Final cleanup afmap->SetOwner(kTRUE); SafeDelete(afmap); } } //______________________________________________________________________________ Bool_t TProof::Prompt(const char *p) { // Prompt the question 'p' requiring an answer y,Y,n,N // Return kTRUE is the answer was y or Y, kFALSE in all other cases. TString pp(p); if (!pp.Contains("?")) pp += "?"; if (!pp.Contains("[y/N]")) pp += " [y/N]"; TString a = Getline(pp.Data()); if (a != "\n" && a[0] != 'y' && a[0] != 'Y' && a[0] != 'n' && a[0] != 'N') { Printf("Please answer y, Y, n or N"); // Unclear answer: assume negative return kFALSE; } else if (a == "\n" || a[0] == 'n' || a[0] == 'N') { // Explicitly Negative answer return kFALSE; } // Explicitly Positive answer return kTRUE; } //______________________________________________________________________________ void TProof::ClearDataProgress(Int_t r, Int_t t) { // Progress bar for clear data fprintf(stderr, "[TProof::ClearData] Total %5d files\t|", t); for (Int_t l = 0; l < 20; l++) { if (r > 0 && t > 0) { if (l < 20*r/t) fprintf(stderr, "="); else if (l == 20*r/t) fprintf(stderr, ">"); else if (l > 20*r/t) fprintf(stderr, "."); } else fprintf(stderr, "="); } fprintf(stderr, "| %.02f %% \r", 100.0*(t ? (r/t) : 1)); } //______________________________________________________________________________ void TProof::ShowCache(Bool_t all) { // List contents of file cache. If all is true show all caches also on // slaves. If everything is ok all caches are to be the same. if (!IsValid()) return; TMessage mess(kPROOF_CACHE); mess << Int_t(kShowCache) << all; Broadcast(mess, kUnique); if (all) { TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kShowSubCache) << all; Broadcast(mess2, fNonUniqueMasters); Collect(kAllUnique, fCollectTimeout); } else { Collect(kUnique, fCollectTimeout); } } //______________________________________________________________________________ void TProof::ClearCache(const char *file) { // Remove file from all file caches. If file is 0 or "" or "*", remove all // the files if (!IsValid()) return; TMessage mess(kPROOF_CACHE); mess << Int_t(kClearCache) << TString(file); Broadcast(mess, kUnique); TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kClearSubCache) << TString(file); Broadcast(mess2, fNonUniqueMasters); Collect(kAllUnique); // clear file map so files get send again to remote nodes fFileMap.clear(); } //______________________________________________________________________________ void TProof::SystemCmd(const char *cmd, Int_t fdout) { // Exec system command 'cmd'. If fdout > -1, append the output to fdout. if (fdout < 0) { // Exec directly the command gSystem->Exec(cmd); } else { // Exec via a pipe FILE *fin = gSystem->OpenPipe(cmd, "r"); if (fin) { // Now we go char line[2048]; while (fgets(line, 2048, fin)) { Int_t r = strlen(line); if (r > 0) { if (write(fdout, line, r) < 0) { ::Warning("TProof::SystemCmd", "errno %d writing to file descriptor %d", TSystem::GetErrno(), fdout); } } else { // Done break; } } gSystem->ClosePipe(fin); } } } //______________________________________________________________________________ void TProof::ShowPackages(Bool_t all, Bool_t redirlog) { // List contents of package directory. If all is true show all package // directories also on slaves. If everything is ok all package directories // should be the same. If redir is kTRUE the result is redirected to the log // file (option available for internal actions). if (!IsValid()) return; Bool_t oldredir = fRedirLog; if (redirlog) fRedirLog = kTRUE; // Active logging unit FILE *fout = (fRedirLog) ? fLogFileW : stdout; if (!fout) { Warning("ShowPackages", "file descriptor for outputs undefined (%p):" " will not log msgs", fout); return; } lseek(fileno(fout), (off_t) 0, SEEK_END); if (TestBit(TProof::kIsClient)) { if (fGlobalPackageDirList && fGlobalPackageDirList->GetSize() > 0) { // Scan the list of global packages dirs TIter nxd(fGlobalPackageDirList); TNamed *nm = 0; while ((nm = (TNamed *)nxd())) { fprintf(fout, "*** Global Package cache %s client:%s ***\n", nm->GetName(), nm->GetTitle()); fflush(fout); SystemCmd(Form("%s %s", kLS, nm->GetTitle()), fileno(fout)); fprintf(fout, "\n"); fflush(fout); } } fprintf(fout, "*** Package cache client:%s ***\n", fPackageDir.Data()); fflush(fout); SystemCmd(Form("%s %s", kLS, fPackageDir.Data()), fileno(fout)); fprintf(fout, "\n"); } // Nothing more to do if we are a Lite-session if (IsLite()) { fRedirLog = oldredir; return; } TMessage mess(kPROOF_CACHE); mess << Int_t(kShowPackages) << all; Broadcast(mess, kUnique); if (all) { TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kShowSubPackages) << all; Broadcast(mess2, fNonUniqueMasters); Collect(kAllUnique, fCollectTimeout); } else { Collect(kUnique, fCollectTimeout); } // Restore logging option fRedirLog = oldredir; } //______________________________________________________________________________ void TProof::ShowEnabledPackages(Bool_t all) { // List which packages are enabled. If all is true show enabled packages // for all active slaves. If everything is ok all active slaves should // have the same packages enabled. if (!IsValid()) return; if (TestBit(TProof::kIsClient)) { printf("*** Enabled packages on client on %s\n", gSystem->HostName()); TIter next(fEnabledPackagesOnClient); while (TObjString *str = (TObjString*) next()) printf("%s\n", str->GetName()); } // Nothing more to do if we are a Lite-session if (IsLite()) return; TMessage mess(kPROOF_CACHE); mess << Int_t(kShowEnabledPackages) << all; Broadcast(mess); Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ Int_t TProof::ClearPackages() { // Remove all packages. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (UnloadPackages() == -1) return -1; if (DisablePackages() == -1) return -1; return fStatus; } //______________________________________________________________________________ Int_t TProof::ClearPackage(const char *package) { // Remove a specific package. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("ClearPackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); if (UnloadPackage(pac) == -1) return -1; if (DisablePackage(pac) == -1) return -1; return fStatus; } //______________________________________________________________________________ Int_t TProof::DisablePackage(const char *package) { // Remove a specific package. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("DisablePackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); if (DisablePackageOnClient(pac) == -1) return -1; // Nothing more to do if we are a Lite-session if (IsLite()) return 0; Int_t st = -1; Bool_t done = kFALSE; if (fManager) { // Try to do it via XROOTD (new way) TString path; path.Form("~/packages/%s", package); if (fManager->Rm(path, "-rf", "all") != -1) { path.Append(".par"); if (fManager->Rm(path, "-f", "all") != -1) { done = kTRUE; st = 0; } } } if (!done) { // Try via TProofServ (old way) TMessage mess(kPROOF_CACHE); mess << Int_t(kDisablePackage) << pac; Broadcast(mess, kUnique); TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kDisableSubPackage) << pac; Broadcast(mess2, fNonUniqueMasters); Collect(kAllUnique); st = fStatus; } // Done return st; } //______________________________________________________________________________ Int_t TProof::DisablePackageOnClient(const char *package) { // Remove a specific package from the client. // Returns 0 in case of success and -1 in case of error. if (TestBit(TProof::kIsClient)) { // Remove the package directory and the par file locally fPackageLock->Lock(); gSystem->Exec(Form("%s %s/%s", kRM, fPackageDir.Data(), package)); gSystem->Exec(Form("%s %s/%s.par", kRM, fPackageDir.Data(), package)); gSystem->Exec(Form("%s %s/%s/%s.par", kRM, fPackageDir.Data(), kPROOF_PackDownloadDir, package)); fPackageLock->Unlock(); if (!gSystem->AccessPathName(Form("%s/%s/%s.par", fPackageDir.Data(), kPROOF_PackDownloadDir, package))) Warning("DisablePackageOnClient", "unable to remove cached package PAR file for %s", package); if (!gSystem->AccessPathName(Form("%s/%s.par", fPackageDir.Data(), package))) Warning("DisablePackageOnClient", "unable to remove package PAR file for %s", package); if (!gSystem->AccessPathName(Form("%s/%s", fPackageDir.Data(), package))) Warning("DisablePackageOnClient", "unable to remove package directory for %s", package); } return 0; } //______________________________________________________________________________ Int_t TProof::DisablePackages() { // Remove all packages. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; // remove all packages on client if (TestBit(TProof::kIsClient)) { fPackageLock->Lock(); gSystem->Exec(Form("%s %s/*", kRM, fPackageDir.Data())); fPackageLock->Unlock(); } // Nothing more to do if we are a Lite-session if (IsLite()) return 0; TMessage mess(kPROOF_CACHE); mess << Int_t(kDisablePackages); Broadcast(mess, kUnique); TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kDisableSubPackages); Broadcast(mess2, fNonUniqueMasters); Collect(kAllUnique); return fStatus; } //______________________________________________________________________________ Int_t TProof::BuildPackage(const char *package, EBuildPackageOpt opt) { // Build specified package. Executes the PROOF-INF/BUILD.sh // script if it exists on all unique nodes. If opt is kBuildOnSlavesNoWait // then submit build command to slaves, but don't wait // for results. If opt is kCollectBuildResults then collect result // from slaves. To be used on the master. // If opt = kBuildAll (default) then submit and wait for results // (to be used on the client). // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("BuildPackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); Bool_t buildOnClient = kTRUE; if (opt == kDontBuildOnClient) { buildOnClient = kFALSE; opt = kBuildAll; } // Prepare the local package TString pdir; Int_t st = 0; if (buildOnClient) { if (TestBit(TProof::kIsClient) && fPackageLock) fPackageLock->Lock(); if ((st = BuildPackageOnClient(pac, 1, &pdir) != 0)) { if (TestBit(TProof::kIsClient) && fPackageLock) fPackageLock->Unlock(); return -1; } } if (opt <= kBuildAll && !IsLite()) { TMessage mess(kPROOF_CACHE); mess << Int_t(kBuildPackage) << pac; Broadcast(mess, kUnique); TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kBuildSubPackage) << pac; Broadcast(mess2, fNonUniqueMasters); } if (opt >= kBuildAll) { // by first forwarding the build commands to the master and slaves // and only then building locally we build in parallel if (buildOnClient) { st = BuildPackageOnClient(pac, 2, &pdir); if (TestBit(TProof::kIsClient) && fPackageLock) fPackageLock->Unlock(); } fStatus = 0; if (!IsLite()) Collect(kAllUnique); if (fStatus < 0 || st < 0) return -1; } return 0; } //______________________________________________________________________________ Int_t TProof::BuildPackageOnClient(const char *pack, Int_t opt, TString *path) { // Build specified package on the client. Executes the PROOF-INF/BUILD.sh // script if it exists on the client. // If opt == 0, both the preparation and building phases are run. // If opt == 1, only the preparation phase (asserting and, eventually, downloading // of the package) is done; '*path' contains the full path to the // package to be passed in the next call // If opt == 2, only the building phase is run using *path . // Returns 0 in case of success and -1 in case of error. // The code is equivalent to the one in TProofServ.cxx (TProof::kBuildPackage // case). Keep in sync in case of changes. TString downloaddir; downloaddir.Form("%s/%s", fPackageDir.Data(), kPROOF_PackDownloadDir); if (opt != 0 && !path) { Error("BuildPackageOnClient", "for opt=%d != 0 'patyh' must be defined", opt); return -1; } if (TestBit(TProof::kIsClient)) { Int_t status = 0; TString pdir, ocwd; if (opt == 0 || opt == 1) { // Package path pdir.Form("%s/%s", fPackageDir.Data(), pack); if (gSystem->AccessPathName(pdir, kReadPermission) || gSystem->AccessPathName(pdir + "/PROOF-INF", kReadPermission)) { pdir = ""; // Is there a global package with this name? if (fGlobalPackageDirList && fGlobalPackageDirList->GetSize() > 0) { // Scan the list of global packages dirs TIter nxd(fGlobalPackageDirList); TNamed *nm = 0; while ((nm = (TNamed *)nxd())) { pdir = Form("%s/%s", nm->GetTitle(), pack); if (!gSystem->AccessPathName(pdir, kReadPermission) && !gSystem->AccessPathName(pdir + "/PROOF-INF", kReadPermission)) { // Package found, stop searching break; } pdir = ""; } } } else { // Check if the related PAR file still exists (private versions could have gone: // in such a case we should take the reference from the repository, by first cleaning // the existing directory) TString tpar(pdir); if (!tpar.EndsWith(".par")) tpar += ".par"; Bool_t badPAR = kTRUE; FileStat_t stpar; if (gSystem->GetPathInfo(tpar, stpar) == 0) { #ifndef WIN32 char ctmp[1024]; if (!R_ISLNK(stpar.fMode) || readlink(tpar.Data(), ctmp, 1024) > 0) { // The file exists badPAR = kFALSE; } #else // The file exists badPAR = kFALSE; #endif } // Cleanup, if bad if (badPAR) { // Remove package directory gSystem->Exec(Form("%s %s", kRM, pdir.Data())); // Remove link or bad file gSystem->Exec(Form("%s %s", kRM, tpar.Data())); // Reset variable pdir = ""; } } // Check if the package was downloaded from the master Bool_t wasDownloaded = kFALSE; TString dlpar; dlpar.Form("%s/%s", downloaddir.Data(), gSystem->BaseName(pack)); if (!dlpar.EndsWith(".par")) dlpar += ".par"; if (!pdir.IsNull()) { if (!gSystem->AccessPathName(dlpar, kFileExists)) wasDownloaded = kTRUE; } if (pdir.IsNull() || wasDownloaded) { // Try to download it if (DownloadPackage(pack, downloaddir) != 0) { Error("BuildPackageOnClient", "PAR file '%s.par' not found and could not be downloaded", pack); return -1; } else { TMD5 *md5 = TMD5::FileChecksum(dlpar); if (UploadPackageOnClient(dlpar, kUntar, md5) == -1) { Error("BuildPackageOnClient", "PAR file '%s.par' not found and could not be unpacked locally", pack); delete md5; return -1; } delete md5; // The package is now linked from the default package dir pdir.Form("%s/%s", fPackageDir.Data(), pack); } } else if (pdir.IsNull()) { Error("BuildPackageOnClient", "PAR file '%s.par' not found", pack); return -1; } PDB(kPackage, 1) Info("BuildPackageOnClient", "package %s exists and has PROOF-INF directory", pack); // We are done if only prepare was requested if (opt == 1) { *path = pdir; return 0; } } if (opt == 0 || opt == 2) { if (opt == 2) pdir = path->Data(); ocwd = gSystem->WorkingDirectory(); gSystem->ChangeDirectory(pdir); // check for BUILD.sh and execute if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) { // read version from file proofvers.txt, and if current version is // not the same do a "BUILD.sh clean" Bool_t savever = kFALSE; Int_t rev = -1; TString v; FILE *f = fopen("PROOF-INF/proofvers.txt", "r"); if (f) { TString r; v.Gets(f); r.Gets(f); rev = (!r.IsNull() && r.IsDigit()) ? r.Atoi() : -1; fclose(f); } if (!f || v != gROOT->GetVersion() || (gROOT->GetSvnRevision() > 0 && rev != gROOT->GetSvnRevision())) { savever = kTRUE; Info("BuildPackageOnClient", "%s: version change (current: %s:%d, build: %s:%d): cleaning ... ", pack, gROOT->GetVersion(), gROOT->GetSvnRevision(), v.Data(), rev); // Hard cleanup: go up the dir tree gSystem->ChangeDirectory(fPackageDir); // remove package directory gSystem->Exec(Form("%s %s", kRM, pdir.Data())); // find gunzip... char *gunzip = gSystem->Which(gSystem->Getenv("PATH"), kGUNZIP, kExecutePermission); if (gunzip) { TString par = Form("%s.par", pdir.Data()); // untar package TString cmd(Form(kUNTAR3, gunzip, par.Data())); status = gSystem->Exec(cmd); if ((status = gSystem->Exec(cmd))) { Error("BuildPackageOnCLient", "failure executing: %s", cmd.Data()); } else { // Go down to the package directory gSystem->ChangeDirectory(pdir); } delete [] gunzip; } else { Error("BuildPackageOnClient", "%s not found", kGUNZIP); status = -1; } } if (gSystem->Exec("PROOF-INF/BUILD.sh")) { Error("BuildPackageOnClient", "building package %s on the client failed", pack); status = -1; } if (savever && !status) { f = fopen("PROOF-INF/proofvers.txt", "w"); if (f) { fputs(gROOT->GetVersion(), f); fputs(Form("\n%d",gROOT->GetSvnRevision()), f); fclose(f); } } } else { PDB(kPackage, 1) Info("BuildPackageOnClient", "package %s exists but has no PROOF-INF/BUILD.sh script", pack); } gSystem->ChangeDirectory(ocwd); return status; } } return 0; } //______________________________________________________________________________ Int_t TProof::LoadPackage(const char *package, Bool_t notOnClient) { // Load specified package. Executes the PROOF-INF/SETUP.C script // on all active nodes. If notOnClient = true, don't load package // on the client. The default is to load the package also on the client. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("LoadPackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); if (!notOnClient) if (LoadPackageOnClient(pac) == -1) return -1; TMessage mess(kPROOF_CACHE); mess << Int_t(kLoadPackage) << pac; Broadcast(mess); Collect(); return fStatus; } //______________________________________________________________________________ Int_t TProof::LoadPackageOnClient(const char *pack) { // Load specified package in the client. Executes the PROOF-INF/SETUP.C // script on the client. Returns 0 in case of success and -1 in case of error. // The code is equivalent to the one in TProofServ.cxx (TProof::kLoadPackage // case). Keep in sync in case of changes. if (TestBit(TProof::kIsClient)) { Int_t status = 0; TString pdir, ocwd; // If already loaded don't do it again if (fEnabledPackagesOnClient->FindObject(pack)) { Info("LoadPackageOnClient", "package %s already loaded", pack); return 0; } // always follows BuildPackage so no need to check for PROOF-INF pdir.Form("%s/%s", fPackageDir.Data(), pack); if (gSystem->AccessPathName(pdir, kReadPermission)) { // Is there a global package with this name? if (fGlobalPackageDirList && fGlobalPackageDirList->GetSize() > 0) { // Scan the list of global packages dirs TIter nxd(fGlobalPackageDirList); TNamed *nm = 0; while ((nm = (TNamed *)nxd())) { pdir = Form("%s/%s", nm->GetTitle(), pack); if (!gSystem->AccessPathName(pdir, kReadPermission)) { // Package found, stop searching break; } pdir = ""; } if (pdir.Length() <= 0) { // Package not found Error("LoadPackageOnClient", "failure locating %s ...", pack); return -1; } } } ocwd = gSystem->WorkingDirectory(); gSystem->ChangeDirectory(pdir); // check for SETUP.C and execute if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) { Int_t err = 0; Int_t errm = gROOT->Macro("PROOF-INF/SETUP.C", &err); if (errm < 0) status = -1; if (err > TInterpreter::kNoError && err <= TInterpreter::kFatal) status = -1; } else { PDB(kPackage, 1) Info("LoadPackageOnCLient", "package %s exists but has no PROOF-INF/SETUP.C script", pack); } gSystem->ChangeDirectory(ocwd); if (!status) { // create link to package in working directory fPackageLock->Lock(); FileStat_t stat; Int_t st = gSystem->GetPathInfo(pack, stat); // check if symlink, if so unlink, if not give error // NOTE: GetPathnfo() returns 1 in case of symlink that does not point to // existing file or to a directory, but if fIsLink is true the symlink exists if (stat.fIsLink) gSystem->Unlink(pack); else if (st == 0) { Error("LoadPackageOnClient", "cannot create symlink %s in %s on client, " "another item with same name already exists", pack, ocwd.Data()); fPackageLock->Unlock(); return -1; } gSystem->Symlink(pdir, pack); fPackageLock->Unlock(); // add package to list of include directories to be searched by ACliC gSystem->AddIncludePath(TString("-I") + pack); // add package to list of include directories to be searched by CINT gROOT->ProcessLine(TString(".include ") + pack); fEnabledPackagesOnClient->Add(new TObjString(pack)); PDB(kPackage, 1) Info("LoadPackageOnClient", "package %s successfully loaded", pack); } else Error("LoadPackageOnClient", "loading package %s on client failed", pack); return status; } return 0; } //______________________________________________________________________________ Int_t TProof::UnloadPackage(const char *package) { // Unload specified package. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("UnloadPackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); if (UnloadPackageOnClient(pac) == -1) return -1; // Nothing more to do if we are a Lite-session if (IsLite()) return 0; TMessage mess(kPROOF_CACHE); mess << Int_t(kUnloadPackage) << pac; Broadcast(mess); Collect(); return fStatus; } //______________________________________________________________________________ Int_t TProof::UnloadPackageOnClient(const char *package) { // Unload a specific package on the client. // Returns 0 in case of success and -1 in case of error. // The code is equivalent to the one in TProofServ.cxx (TProof::UnloadPackage // case). Keep in sync in case of changes. if (TestBit(TProof::kIsClient)) { TObjString *pack = (TObjString *) fEnabledPackagesOnClient->FindObject(package); if (pack) { // Remove entry from include path TString aclicincpath = gSystem->GetIncludePath(); TString cintincpath = gInterpreter->GetIncludePath(); // remove interpreter part of gSystem->GetIncludePath() aclicincpath.Remove(aclicincpath.Length() - cintincpath.Length() - 1); // remove package's include path aclicincpath.ReplaceAll(TString(" -I") + package, ""); gSystem->SetIncludePath(aclicincpath); //TODO reset interpreter include path // remove entry from enabled packages list fEnabledPackagesOnClient->Remove(pack); } // cleanup the link if (!gSystem->AccessPathName(package)) if (gSystem->Unlink(package) != 0) Warning("UnloadPackageOnClient", "unable to remove symlink to %s", package); // delete entry delete pack; } return 0; } //______________________________________________________________________________ Int_t TProof::UnloadPackages() { // Unload all packages. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (TestBit(TProof::kIsClient)) { // Iterate over packages on the client and remove each package TIter nextpackage(fEnabledPackagesOnClient); while (TObjString *objstr = dynamic_cast<TObjString*>(nextpackage())) if (UnloadPackageOnClient(objstr->String()) == -1 ) return -1; } // Nothing more to do if we are a Lite-session if (IsLite()) return 0; TMessage mess(kPROOF_CACHE); mess << Int_t(kUnloadPackages); Broadcast(mess); Collect(); return fStatus; } //______________________________________________________________________________ Int_t TProof::EnablePackage(const char *package, Bool_t notOnClient) { // Enable specified package. Executes the PROOF-INF/BUILD.sh // script if it exists followed by the PROOF-INF/SETUP.C script. // In case notOnClient = true, don't enable the package on the client. // The default is to enable packages also on the client. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("EnablePackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); EBuildPackageOpt opt = kBuildAll; if (notOnClient) opt = kDontBuildOnClient; if (BuildPackage(pac, opt) == -1) return -1; if (LoadPackage(pac, notOnClient) == -1) return -1; return 0; } //______________________________________________________________________________ Int_t TProof::DownloadPackage(const char *pack, const char *dstdir) { // Download a PROOF archive (PAR file) from the master package repository. // The PAR file is downloaded in the current directory or in the directory // specified by 'dstdir'. If a package with the same name already exists // at destination, a check on the MD5 sum is done and the user warned or // prompted for action, depending is the file is equal or different. // Returns 0 in case of success and -1 in case of error. if (!fManager || !(fManager->IsValid())) { Error("DownloadPackage", "the manager is undefined!"); return -1; } // Create the default source and destination paths TString parname(gSystem->BaseName(pack)), src, dst; if (!parname.EndsWith(".par")) parname += ".par"; src.Form("packages/%s", parname.Data()); if (!dstdir || strlen(dstdir) <= 0) { dst.Form("./%s", parname.Data()); } else { // Check the destination directory FileStat_t st; if (gSystem->GetPathInfo(dstdir, st) != 0) { // Directory does not exit: create it if (gSystem->mkdir(dstdir, kTRUE) != 0) { Error("DownloadPackage", "could not create the destination directory '%s' (errno: %d)", dstdir, TSystem::GetErrno()); return -1; } } else if (!R_ISDIR(st.fMode) && !R_ISLNK(st.fMode)) { Error("DownloadPackage", "destination path '%s' exist but is not a directory!", dstdir); return -1; } dst.Form("%s/%s", dstdir, parname.Data()); } // Make sure the source file exists FileStat_t stsrc; RedirectHandle_t rh; if (gSystem->RedirectOutput(fLogFileName, "a", &rh) != 0) Warning("DownloadPackage", "problems redirecting output to '%s'", fLogFileName.Data()); Int_t rc = fManager->Stat(src, stsrc); if (gSystem->RedirectOutput(0, 0, &rh) != 0) Warning("DownloadPackage", "problems restoring output"); if (rc != 0) { // Check if there is another possible source ShowPackages(kFALSE, kTRUE); TMacro *mp = GetLastLog(); if (mp) { // Look for global directories Bool_t isGlobal = kFALSE; TIter nxl(mp->GetListOfLines()); TObjString *os = 0; TString globaldir; while ((os = (TObjString *) nxl())) { TString s(os->GetName()); if (s.Contains("*** Global Package cache")) { // Get the directory s.Remove(0, s.Last(':') + 1); s.Remove(s.Last(' ')); globaldir = s; isGlobal = kTRUE; } else if (s.Contains("*** Package cache")) { isGlobal = kFALSE; globaldir = ""; } // Check for the package if (isGlobal && s.Contains(parname)) { src.Form("%s/%s", globaldir.Data(), parname.Data()); break; } } // Cleanup delete mp; } } // Do it via the manager if (fManager->GetFile(src, dst, "silent") != 0) { Error("DownloadPackage", "problems downloading '%s' (src:%s, dst:%s)", pack, src.Data(), dst.Data()); return -1; } else { Info("DownloadPackage", "'%s' cross-checked against master repository (local path: %s)", pack, dst.Data()); } // Done return 0; } //______________________________________________________________________________ Int_t TProof::UploadPackage(const char *pack, EUploadPackageOpt opt) { // Upload a PROOF archive (PAR file). A PAR file is a compressed // tar file with one special additional directory, PROOF-INF // (blatantly copied from Java's jar format). It must have the extension // .par. A PAR file can be directly a binary or a source with a build // procedure. In the PROOF-INF directory there can be a build script: // BUILD.sh to be called to build the package, in case of a binary PAR // file don't specify a build script or make it a no-op. Then there is // SETUP.C which sets the right environment variables to use the package, // like LD_LIBRARY_PATH, etc. // The 'opt' allows to specify whether the .PAR should be just unpacked // in the existing dir (opt = kUntar, default) or a remove of the existing // directory should be executed (opt = kRemoveOld), so triggering a full // re-build. The option if effective only for PROOF protocol > 8 . // The lab 'dirlab' (e.g. 'G0') indicates that the package is to uploaded to // an alternative global directory for global usage. This may require special // privileges. // If download is kTRUE and the package is not found locally, then it is downloaded // from the master repository. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; TString par = pack; if (!par.EndsWith(".par")) // The client specified only the name: add the extension par += ".par"; // Default location is the local working dir; then the package dir gSystem->ExpandPathName(par); if (gSystem->AccessPathName(par, kReadPermission)) { TString tried = par; // Try the package dir par = Form("%s/%s", fPackageDir.Data(), gSystem->BaseName(par)); if (gSystem->AccessPathName(par, kReadPermission)) { // Is the package a global one if (fGlobalPackageDirList && fGlobalPackageDirList->GetSize() > 0) { // Scan the list of global packages dirs TIter nxd(fGlobalPackageDirList); TNamed *nm = 0; TString pdir; while ((nm = (TNamed *)nxd())) { pdir = Form("%s/%s", nm->GetTitle(), pack); if (!gSystem->AccessPathName(pdir, kReadPermission)) { // Package found, stop searching break; } pdir = ""; } if (pdir.Length() > 0) { // Package is in the global dirs if (gDebug > 0) Info("UploadPackage", "global package found (%s): no upload needed", pdir.Data()); return 0; } } Error("UploadPackage", "PAR file '%s' not found; paths tried: %s, %s", gSystem->BaseName(par), tried.Data(), par.Data()); return -1; } } // Strategy: // On the client: // get md5 of package and check if it is different // from the one stored in the local package directory. If it is lock // the package directory and copy the package, unlock the directory. // On the masters: // get md5 of package and check if it is different from the // one stored on the remote node. If it is different lock the remote // package directory and use TFTP or SendFile to ftp the package to the // remote node, unlock the directory. TMD5 *md5 = TMD5::FileChecksum(par); if (UploadPackageOnClient(par, opt, md5) == -1) { delete md5; return -1; } // Nothing more to do if we are a Lite-session if (IsLite()) { delete md5; return 0; } TString smsg; smsg.Form("+%s", gSystem->BaseName(par)); TMessage mess(kPROOF_CHECKFILE); mess << smsg << (*md5); TMessage mess2(kPROOF_CHECKFILE); smsg.Replace(0, 1, "-"); mess2 << smsg << (*md5); TMessage mess3(kPROOF_CHECKFILE); smsg.Replace(0, 1, "="); mess3 << smsg << (*md5); delete md5; if (fProtocol > 8) { // Send also the option mess << (UInt_t) opt; mess2 << (UInt_t) opt; mess3 << (UInt_t) opt; } // loop over all selected nodes TIter next(fUniqueSlaves); TSlave *sl = 0; while ((sl = (TSlave *) next())) { if (!sl->IsValid()) continue; sl->GetSocket()->Send(mess); fCheckFileStatus = 0; Collect(sl, fCollectTimeout, kPROOF_CHECKFILE); if (fCheckFileStatus == 0) { if (fProtocol > 5) { // remote directory is locked, upload file over the open channel smsg.Form("%s/%s/%s", sl->GetProofWorkDir(), kPROOF_PackDir, gSystem->BaseName(par)); if (SendFile(par, (kBinary | kForce | kCpBin | kForward), smsg.Data(), sl) < 0) { Error("UploadPackage", "%s: problems uploading file %s", sl->GetOrdinal(), par.Data()); return -1; } } else { // old servers receive it via TFTP TFTP ftp(TString("root://")+sl->GetName(), 1); if (!ftp.IsZombie()) { smsg.Form("%s/%s", sl->GetProofWorkDir(), kPROOF_PackDir); ftp.cd(smsg.Data()); ftp.put(par, gSystem->BaseName(par)); } } // install package and unlock dir sl->GetSocket()->Send(mess2); fCheckFileStatus = 0; Collect(sl, fCollectTimeout, kPROOF_CHECKFILE); if (fCheckFileStatus == 0) { Error("UploadPackage", "%s: unpacking of package %s failed", sl->GetOrdinal(), gSystem->BaseName(par)); return -1; } } } // loop over all other master nodes TIter nextmaster(fNonUniqueMasters); TSlave *ma; while ((ma = (TSlave *) nextmaster())) { if (!ma->IsValid()) continue; ma->GetSocket()->Send(mess3); fCheckFileStatus = 0; Collect(ma, fCollectTimeout, kPROOF_CHECKFILE); if (fCheckFileStatus == 0) { // error -> package should have been found Error("UploadPackage", "package %s did not exist on submaster %s", par.Data(), ma->GetOrdinal()); return -1; } } return 0; } //______________________________________________________________________________ Int_t TProof::UploadPackageOnClient(const char *parpack, EUploadPackageOpt opt, TMD5 *md5) { // Upload a package on the client in ~/.proof/packages. // The 'opt' allows to specify whether the .PAR should be just unpacked // in the existing dir (opt = kUntar, default) or a remove of the existing // directory should be executed (opt = kRemoveOld), thereby triggering a full // re-build. This option if effective only for PROOF protocol > 8. // Returns 0 in case of success and -1 in case of error. // Strategy: // get md5 of package and check if it is different // from the one stored in the local package directory. If it is lock // the package directory and copy the package, unlock the directory. Int_t status = 0; if (TestBit(TProof::kIsClient)) { // Make sure that 'par' is the real path and not a symlink TString par(parpack); #ifndef WIN32 char ctmp[4096]; ssize_t sz = readlink(par.Data(), ctmp, 4096); if (sz > 0) { ctmp[sz] = '\0'; par = ctmp; } else if (TSystem::GetErrno() != EINVAL) { Warning("UploadPackageOnClient", "could not resolve the symbolik link '%s'", par.Data()); } #endif // The fPackageDir directory exists (has been created in Init()); // create symlink to the par file in the fPackageDir (needed by // master in case we run on the localhost) fPackageLock->Lock(); // Check if the requested PAR has been downloaded: if not, clean any // existing downloaded file with the same name: this is because now // the client has its own version of the package and should not check // the master repository anymore for updates TString downloadpath; downloadpath.Form("%s/%s/%s", fPackageDir.Data(), kPROOF_PackDownloadDir, gSystem->BaseName(par)); if (!gSystem->AccessPathName(downloadpath, kFileExists) && downloadpath != par) { if (gSystem->Unlink(downloadpath) != 0) { Warning("UploadPackageOnClient", "problems removing downloaded version of '%s' (%s):\n" "may imply inconsistencies in subsequent updates", gSystem->BaseName(par), downloadpath.Data()); } } TString lpar; lpar.Form("%s/%s", fPackageDir.Data(), gSystem->BaseName(par)); FileStat_t stat; Int_t st = gSystem->GetPathInfo(lpar, stat); // check if symlink, if so unlink, if not give error // NOTE: GetPathInfo() returns 1 in case of symlink that does not point to // existing file, but if fIsLink is true the symlink exists if (stat.fIsLink) gSystem->Unlink(lpar); else if (st == 0) { Error("UploadPackageOnClient", "cannot create symlink %s on client, " "another item with same name already exists", lpar.Data()); fPackageLock->Unlock(); return -1; } if (!gSystem->IsAbsoluteFileName(par)) { TString fpar = par; gSystem->Symlink(gSystem->PrependPathName(gSystem->WorkingDirectory(), fpar), lpar); } else gSystem->Symlink(par, lpar); // TODO: On Windows need to copy instead of symlink // compare md5 TString packnam = par(0, par.Length() - 4); // strip off ".par" packnam = gSystem->BaseName(packnam); // strip off path TString md5f = fPackageDir + "/" + packnam + "/PROOF-INF/md5.txt"; TMD5 *md5local = TMD5::ReadChecksum(md5f); if (!md5local || (*md5) != (*md5local)) { // if not, unzip and untar package in package directory if ((opt & TProof::kRemoveOld)) { // remove any previous package directory with same name if (gSystem->Exec(Form("%s %s/%s", kRM, fPackageDir.Data(), packnam.Data()))) Error("UploadPackageOnClient", "failure executing: %s %s/%s", kRM, fPackageDir.Data(), packnam.Data()); } // find gunzip char *gunzip = gSystem->Which(gSystem->Getenv("PATH"), kGUNZIP, kExecutePermission); if (gunzip) { // untar package if (gSystem->Exec(Form(kUNTAR2, gunzip, par.Data(), fPackageDir.Data()))) Error("Uploadpackage", "failure executing: %s", Form(kUNTAR2, gunzip, par.Data(), fPackageDir.Data())); delete [] gunzip; } else Error("UploadPackageOnClient", "%s not found", kGUNZIP); // check that fPackageDir/packnam now exists if (gSystem->AccessPathName(fPackageDir + "/" + packnam, kWritePermission)) { // par file did not unpack itself in the expected directory, failure Error("UploadPackageOnClient", "package %s did not unpack into %s/%s", par.Data(), fPackageDir.Data(), packnam.Data()); status = -1; } else { // store md5 in package/PROOF-INF/md5.txt TMD5::WriteChecksum(md5f, md5); } } fPackageLock->Unlock(); delete md5local; } return status; } //______________________________________________________________________________ Int_t TProof::Load(const char *macro, Bool_t notOnClient, Bool_t uniqueWorkers, TList *wrks) { // Load the specified macro on master, workers and, if notOnClient is // kFALSE, on the client. The macro file is uploaded if new or updated. // If existing, the corresponding header basename(macro).h or .hh, is also // uploaded. The default is to load the macro also on the client. // On masters, if uniqueWorkers is kTRUE, the macro is loaded on unique workers // only, and collection is not done; if uniqueWorkers is kFALSE, collection // from the previous request is done, and broadcasting + collection from the // other workers is done. // The wrks arg can be used on the master to limit the set of workers. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!macro || !strlen(macro)) { Error("Load", "need to specify a macro name"); return -1; } if (TestBit(TProof::kIsClient)) { if (wrks) { Error("Load", "the 'wrks' arg can be used only on the master"); return -1; } // Extract the file implementation name first TString implname = macro; TString acmode, args, io; implname = gSystem->SplitAclicMode(implname, acmode, args, io); // Macro names must have a standard format Int_t dot = implname.Last('.'); if (dot == kNPOS) { Info("Load", "macro '%s' does not contain a '.': do nothing", macro); return -1; } // Is there any associated header file Bool_t hasHeader = kTRUE; TString headname = implname; headname.Remove(dot); headname += ".h"; if (gSystem->AccessPathName(headname, kReadPermission)) { TString h = headname; headname.Remove(dot); headname += ".hh"; if (gSystem->AccessPathName(headname, kReadPermission)) { hasHeader = kFALSE; if (gDebug > 0) Info("Load", "no associated header file found: tried: %s %s", h.Data(), headname.Data()); } } // Send files now; the md5 check is run here; see SendFile for more // details. if (SendFile(implname, kAscii | kForward , "cache") == -1) { Info("Load", "problems sending implementation file %s", implname.Data()); return -1; } if (hasHeader) if (SendFile(headname, kAscii | kForward , "cache") == -1) { Info("Load", "problems sending header file %s", headname.Data()); return -1; } // The files are now on the workers: now we send the loading request TString basemacro = gSystem->BaseName(macro); TMessage mess(kPROOF_CACHE); mess << Int_t(kLoadMacro) << basemacro; Broadcast(mess, kActive); // Load locally, if required if (!notOnClient) { // by first forwarding the load command to the master and workers // and only then loading locally we load/build in parallel gROOT->ProcessLine(Form(".L %s", macro)); // Update the macro path TString mp(TROOT::GetMacroPath()); TString np(gSystem->DirName(macro)); if (!np.IsNull()) { np += ":"; Int_t ip = (mp.BeginsWith(".:")) ? 2 : 0; mp.Insert(ip, np); } TROOT::SetMacroPath(mp); if (gDebug > 0) Info("Load", "macro path set to '%s'", TROOT::GetMacroPath()); } // Wait for master and workers to be done Collect(kActive); } else { // On master // The files are now on the workers: now we send the loading request first // to the unique workers, so that the eventual compilation occurs only once. TString basemacro = gSystem->BaseName(macro); TMessage mess(kPROOF_CACHE); if (uniqueWorkers) { mess << Int_t(kLoadMacro) << basemacro; if (wrks) Broadcast(mess, wrks); else Broadcast(mess, kUnique); } else { // Wait for the result of the previous sending Collect(kUnique); // We then send a tuned loading request to the other workers TList others; TSlave *wrk = 0; TIter nxw(fActiveSlaves); while ((wrk = (TSlave *)nxw())) { if (!fUniqueSlaves->FindObject(wrk)) { others.Add(wrk); } } // Do not force compilation, if it was requested Int_t ld = basemacro.Last('.'); if (ld != kNPOS) { Int_t lpp = basemacro.Index("++", ld); if (lpp != kNPOS) basemacro.Replace(lpp, 2, "+"); } mess << Int_t(kLoadMacro) << basemacro; Broadcast(mess, &others); Collect(&others); } PDB(kGlobal, 1) Info("Load", "adding loaded macro: %s", macro); if (!fLoadedMacros) { fLoadedMacros = new TList(); fLoadedMacros->SetOwner(); } // if wrks is specified the macro should already be loaded on the master. if (!wrks) fLoadedMacros->Add(new TObjString(macro)); } // Done return 0; } //______________________________________________________________________________ Int_t TProof::AddDynamicPath(const char *libpath, Bool_t onClient, TList *wrks) { // Add 'libpath' to the lib path search. // Multiple paths can be specified at once separating them with a comma or // a blank. // Return 0 on success, -1 otherwise if ((!libpath || !strlen(libpath))) { if (gDebug > 0) Info("AddDynamicPath", "list is empty - nothing to do"); return 0; } // Do it also on clients, if required if (onClient) HandleLibIncPath("lib", kTRUE, libpath); TMessage m(kPROOF_LIB_INC_PATH); m << TString("lib") << (Bool_t)kTRUE; // Add paths if (libpath && strlen(libpath)) m << TString(libpath); else m << TString("-"); // Forward the request if (wrks) Broadcast(m, wrks); else Broadcast(m); Collect(kActive, fCollectTimeout); return 0; } //______________________________________________________________________________ Int_t TProof::AddIncludePath(const char *incpath, Bool_t onClient, TList *wrks) { // Add 'incpath' to the inc path search. // Multiple paths can be specified at once separating them with a comma or // a blank. // Return 0 on success, -1 otherwise if ((!incpath || !strlen(incpath))) { if (gDebug > 0) Info("AddIncludePath", "list is empty - nothing to do"); return 0; } // Do it also on clients, if required if (onClient) HandleLibIncPath("inc", kTRUE, incpath); TMessage m(kPROOF_LIB_INC_PATH); m << TString("inc") << (Bool_t)kTRUE; // Add paths if (incpath && strlen(incpath)) m << TString(incpath); else m << TString("-"); // Forward the request if (wrks) Broadcast(m, wrks); else Broadcast(m); Collect(kActive, fCollectTimeout); return 0; } //______________________________________________________________________________ Int_t TProof::RemoveDynamicPath(const char *libpath, Bool_t onClient) { // Remove 'libpath' from the lib path search. // Multiple paths can be specified at once separating them with a comma or // a blank. // Return 0 on success, -1 otherwise if ((!libpath || !strlen(libpath))) { if (gDebug > 0) Info("RemoveDynamicPath", "list is empty - nothing to do"); return 0; } // Do it also on clients, if required if (onClient) HandleLibIncPath("lib", kFALSE, libpath); TMessage m(kPROOF_LIB_INC_PATH); m << TString("lib") <<(Bool_t)kFALSE; // Add paths if (libpath && strlen(libpath)) m << TString(libpath); else m << TString("-"); // Forward the request Broadcast(m); Collect(kActive, fCollectTimeout); return 0; } //______________________________________________________________________________ Int_t TProof::RemoveIncludePath(const char *incpath, Bool_t onClient) { // Remove 'incpath' from the inc path search. // Multiple paths can be specified at once separating them with a comma or // a blank. // Return 0 on success, -1 otherwise if ((!incpath || !strlen(incpath))) { if (gDebug > 0) Info("RemoveIncludePath", "list is empty - nothing to do"); return 0; } // Do it also on clients, if required if (onClient) HandleLibIncPath("in", kFALSE, incpath); TMessage m(kPROOF_LIB_INC_PATH); m << TString("inc") << (Bool_t)kFALSE; // Add paths if (incpath && strlen(incpath)) m << TString(incpath); else m << TString("-"); // Forward the request Broadcast(m); Collect(kActive, fCollectTimeout); return 0; } //______________________________________________________________________________ void TProof::HandleLibIncPath(const char *what, Bool_t add, const char *dirs) { // Handle lib, inc search paths modification request TString type(what); TString path(dirs); // Check type of action if ((type != "lib") && (type != "inc")) { Error("HandleLibIncPath","unknown action type: %s - protocol error?", type.Data()); return; } // Separators can be either commas or blanks path.ReplaceAll(","," "); // Decompose lists TObjArray *op = 0; if (path.Length() > 0 && path != "-") { if (!(op = path.Tokenize(" "))) { Warning("HandleLibIncPath","decomposing path %s", path.Data()); return; } } if (add) { if (type == "lib") { // Add libs TIter nxl(op, kIterBackward); TObjString *lib = 0; while ((lib = (TObjString *) nxl())) { // Expand path TString xlib = lib->GetName(); gSystem->ExpandPathName(xlib); // Add to the dynamic lib search path if it exists and can be read if (!gSystem->AccessPathName(xlib, kReadPermission)) { TString newlibpath = gSystem->GetDynamicPath(); // In the first position after the working dir Int_t pos = 0; if (newlibpath.BeginsWith(".:")) pos = 2; if (newlibpath.Index(xlib) == kNPOS) { newlibpath.Insert(pos,Form("%s:", xlib.Data())); gSystem->SetDynamicPath(newlibpath); } } else { if (gDebug > 0) Info("HandleLibIncPath", "libpath %s does not exist or cannot be read - not added", xlib.Data()); } } } else { // Add incs TIter nxi(op); TObjString *inc = 0; while ((inc = (TObjString *) nxi())) { // Expand path TString xinc = inc->GetName(); gSystem->ExpandPathName(xinc); // Add to the dynamic lib search path if it exists and can be read if (!gSystem->AccessPathName(xinc, kReadPermission)) { TString curincpath = gSystem->GetIncludePath(); if (curincpath.Index(xinc) == kNPOS) gSystem->AddIncludePath(Form("-I%s", xinc.Data())); } else if (gDebug > 0) Info("HandleLibIncPath", "incpath %s does not exist or cannot be read - not added", xinc.Data()); } } } else { if (type == "lib") { // Remove libs TIter nxl(op); TObjString *lib = 0; while ((lib = (TObjString *) nxl())) { // Expand path TString xlib = lib->GetName(); gSystem->ExpandPathName(xlib); // Remove from the dynamic lib search path TString newlibpath = gSystem->GetDynamicPath(); newlibpath.ReplaceAll(Form("%s:", xlib.Data()),""); gSystem->SetDynamicPath(newlibpath); } } else { // Remove incs TIter nxi(op); TObjString *inc = 0; while ((inc = (TObjString *) nxi())) { TString newincpath = gSystem->GetIncludePath(); newincpath.ReplaceAll(Form("-I%s", inc->GetName()),""); // Remove the interpreter path (added anyhow internally) newincpath.ReplaceAll(gInterpreter->GetIncludePath(),""); gSystem->SetIncludePath(newincpath); } } } } //______________________________________________________________________________ TList *TProof::GetListOfPackages() { // Get from the master the list of names of the packages available. if (!IsValid()) return (TList *)0; TMessage mess(kPROOF_CACHE); mess << Int_t(kListPackages); Broadcast(mess); Collect(kActive, fCollectTimeout); return fAvailablePackages; } //______________________________________________________________________________ TList *TProof::GetListOfEnabledPackages() { // Get from the master the list of names of the packages enabled. if (!IsValid()) return (TList *)0; TMessage mess(kPROOF_CACHE); mess << Int_t(kListEnabledPackages); Broadcast(mess); Collect(kActive, fCollectTimeout); return fEnabledPackages; } //______________________________________________________________________________ void TProof::PrintProgress(Long64_t total, Long64_t processed, Float_t procTime) { // Print a progress bar on stderr. Used in batch mode. if (fPrintProgress) { Bool_t redirlog = fRedirLog; fRedirLog = kFALSE; // Call the external function (*fPrintProgress)(total, processed, procTime); fRedirLog = redirlog; return; } fprintf(stderr, "[TProof::Progress] Total %lld events\t|", total); for (int l = 0; l < 20; l++) { if (total > 0) { if (l < 20*processed/total) fprintf(stderr, "="); else if (l == 20*processed/total) fprintf(stderr, ">"); else if (l > 20*processed/total) fprintf(stderr, "."); } else fprintf(stderr, "="); } Float_t evtrti = (procTime > 0. && processed > 0) ? processed / procTime : -1.; if (evtrti > 0.) fprintf(stderr, "| %.02f %% [%.1f evts/s]\r", (total ? ((100.0*processed)/total) : 100.0), evtrti); else fprintf(stderr, "| %.02f %%\r", (total ? ((100.0*processed)/total) : 100.0)); if (processed >= total) fprintf(stderr, "\n"); } //______________________________________________________________________________ void TProof::Progress(Long64_t total, Long64_t processed) { // Get query progress information. Connect a slot to this signal // to track progress. if (fPrintProgress) { // Call the external function return (*fPrintProgress)(total, processed, -1.); } PDB(kGlobal,1) Info("Progress","%2f (%lld/%lld)", 100.*processed/total, processed, total); if (gROOT->IsBatch()) { // Simple progress bar if (total > 0) PrintProgress(total, processed); } else { EmitVA("Progress(Long64_t,Long64_t)", 2, total, processed); } } //______________________________________________________________________________ void TProof::Progress(Long64_t total, Long64_t processed, Long64_t bytesread, Float_t initTime, Float_t procTime, Float_t evtrti, Float_t mbrti) { // Get query progress information. Connect a slot to this signal // to track progress. PDB(kGlobal,1) Info("Progress","%lld %lld %lld %f %f %f %f", total, processed, bytesread, initTime, procTime, evtrti, mbrti); if (gROOT->IsBatch()) { // Simple progress bar if (total > 0) PrintProgress(total, processed, procTime); } else { EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)", 7, total, processed, bytesread, initTime, procTime, evtrti, mbrti); } } //______________________________________________________________________________ void TProof::Progress(Long64_t total, Long64_t processed, Long64_t bytesread, Float_t initTime, Float_t procTime, Float_t evtrti, Float_t mbrti, Int_t actw, Int_t tses, Float_t eses) { // Get query progress information. Connect a slot to this signal // to track progress. PDB(kGlobal,1) Info("Progress","%lld %lld %lld %f %f %f %f %d %f", total, processed, bytesread, initTime, procTime, evtrti, mbrti, actw, eses); if (gROOT->IsBatch()) { // Simple progress bar if (total > 0) PrintProgress(total, processed, procTime); } else { EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t,Int_t,Int_t,Float_t)", 10, total, processed, bytesread, initTime, procTime, evtrti, mbrti, actw, tses, eses); } } //______________________________________________________________________________ void TProof::Feedback(TList *objs) { // Get list of feedback objects. Connect a slot to this signal // to monitor the feedback object. PDB(kGlobal,1) Info("Feedback","%d objects", objs->GetSize()); PDB(kFeedback,1) { Info("Feedback","%d objects", objs->GetSize()); objs->ls(); } Emit("Feedback(TList *objs)", (Long_t) objs); } //______________________________________________________________________________ void TProof::CloseProgressDialog() { // Close progress dialog. PDB(kGlobal,1) Info("CloseProgressDialog", "called: have progress dialog: %d", fProgressDialogStarted); // Nothing to do if not there if (!fProgressDialogStarted) return; Emit("CloseProgressDialog()"); } //______________________________________________________________________________ void TProof::ResetProgressDialog(const char *sel, Int_t sz, Long64_t fst, Long64_t ent) { // Reset progress dialog. PDB(kGlobal,1) Info("ResetProgressDialog","(%s,%d,%lld,%lld)", sel, sz, fst, ent); EmitVA("ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)", 4, sel, sz, fst, ent); } //______________________________________________________________________________ void TProof::StartupMessage(const char *msg, Bool_t st, Int_t done, Int_t total) { // Send startup message. PDB(kGlobal,1) Info("StartupMessage","(%s,%d,%d,%d)", msg, st, done, total); EmitVA("StartupMessage(const char*,Bool_t,Int_t,Int_t)", 4, msg, st, done, total); } //______________________________________________________________________________ void TProof::DataSetStatus(const char *msg, Bool_t st, Int_t done, Int_t total) { // Send dataset preparation status. PDB(kGlobal,1) Info("DataSetStatus","(%s,%d,%d,%d)", msg, st, done, total); EmitVA("DataSetStatus(const char*,Bool_t,Int_t,Int_t)", 4, msg, st, done, total); } //______________________________________________________________________________ void TProof::SendDataSetStatus(const char *action, UInt_t done, UInt_t tot, Bool_t st) { // Send or notify data set status if (IsLite()) { if (tot) { TString type = "files"; Int_t frac = (Int_t) (done*100.)/tot; char msg[512] = {0}; if (frac >= 100) { snprintf(msg, 512, "%s: OK (%d %s) \n", action,tot, type.Data()); } else { snprintf(msg, 512, "%s: %d out of %d (%d %%)\r", action, done, tot, frac); } if (fSync) fprintf(stderr,"%s", msg); else NotifyLogMsg(msg, 0); } return; } if (TestBit(TProof::kIsMaster)) { TMessage mess(kPROOF_DATASET_STATUS); mess << TString(action) << tot << done << st; gProofServ->GetSocket()->Send(mess); } } //______________________________________________________________________________ void TProof::QueryResultReady(const char *ref) { // Notify availability of a query result. PDB(kGlobal,1) Info("QueryResultReady","ref: %s", ref); Emit("QueryResultReady(const char*)",ref); } //______________________________________________________________________________ void TProof::ValidateDSet(TDSet *dset) { // Validate a TDSet. if (dset->ElementsValid()) return; TList nodes; nodes.SetOwner(); TList slholder; slholder.SetOwner(); TList elemholder; elemholder.SetOwner(); // build nodelist with slaves and elements TIter nextSlave(GetListOfActiveSlaves()); while (TSlave *sl = dynamic_cast<TSlave*>(nextSlave())) { TList *sllist = 0; TPair *p = dynamic_cast<TPair*>(nodes.FindObject(sl->GetName())); if (!p) { sllist = new TList; sllist->SetName(sl->GetName()); slholder.Add(sllist); TList *elemlist = new TList; elemlist->SetName(TString(sl->GetName())+"_elem"); elemholder.Add(elemlist); nodes.Add(new TPair(sllist, elemlist)); } else { sllist = dynamic_cast<TList*>(p->Key()); } if (sllist) sllist->Add(sl); } // add local elements to nodes TList nonLocal; // list of nonlocal elements // make two iterations - first add local elements - then distribute nonlocals for (Int_t i = 0; i < 2; i++) { Bool_t local = i>0?kFALSE:kTRUE; TIter nextElem(local ? dset->GetListOfElements() : &nonLocal); while (TDSetElement *elem = dynamic_cast<TDSetElement*>(nextElem())) { if (elem->GetValid()) continue; TPair *p = dynamic_cast<TPair*>(local?nodes.FindObject(TUrl(elem->GetFileName()).GetHost()):nodes.At(0)); if (p) { TList *eli = dynamic_cast<TList*>(p->Value()); TList *sli = dynamic_cast<TList*>(p->Key()); if (eli && sli) { eli->Add(elem); // order list by elements/slave TPair *p2 = p; Bool_t stop = kFALSE; while (!stop) { TPair *p3 = dynamic_cast<TPair*>(nodes.After(p2->Key())); if (p3) { TList *p3v = dynamic_cast<TList*>(p3->Value()); TList *p3k = dynamic_cast<TList*>(p3->Key()); if (p3v && p3k) { Int_t nelem = p3v->GetSize(); Int_t nsl = p3k->GetSize(); if (nelem*sli->GetSize() < eli->GetSize()*nsl) p2 = p3; else stop = kTRUE; } } else { stop = kTRUE; } } if (p2!=p) { nodes.Remove(p->Key()); nodes.AddAfter(p2->Key(), p); } } else { Warning("ValidateDSet", "invalid values from TPair! Protocol error?"); continue; } } else { if (local) { nonLocal.Add(elem); } else { Warning("ValidateDSet", "no node to allocate TDSetElement to - ignoring"); } } } } // send to slaves TList usedslaves; TIter nextNode(&nodes); SetDSet(dset); // set dset to be validated in Collect() while (TPair *node = dynamic_cast<TPair*>(nextNode())) { TList *slaves = dynamic_cast<TList*>(node->Key()); TList *setelements = dynamic_cast<TList*>(node->Value()); if (!slaves || !setelements) continue; // distribute elements over the slaves Int_t nslaves = slaves->GetSize(); Int_t nelements = setelements->GetSize(); for (Int_t i=0; i<nslaves; i++) { TDSet copyset(dset->GetType(), dset->GetObjName(), dset->GetDirectory()); for (Int_t j = (i*nelements)/nslaves; j < ((i+1)*nelements)/nslaves; j++) { TDSetElement *elem = dynamic_cast<TDSetElement*>(setelements->At(j)); if (elem) { copyset.Add(elem->GetFileName(), elem->GetObjName(), elem->GetDirectory(), elem->GetFirst(), elem->GetNum(), elem->GetMsd()); } } if (copyset.GetListOfElements()->GetSize()>0) { TMessage mesg(kPROOF_VALIDATE_DSET); mesg << &copyset; TSlave *sl = dynamic_cast<TSlave*>(slaves->At(i)); if (sl) { PDB(kGlobal,1) Info("ValidateDSet", "Sending TDSet with %d elements to slave %s" " to be validated", copyset.GetListOfElements()->GetSize(), sl->GetOrdinal()); sl->GetSocket()->Send(mesg); usedslaves.Add(sl); } } } } PDB(kGlobal,1) Info("ValidateDSet","Calling Collect"); Collect(&usedslaves); SetDSet(0); } //______________________________________________________________________________ void TProof::AddInputData(TObject *obj, Bool_t push) { // Add data objects that might be needed during the processing of // the selector (see Process()). This object can be very large, so they // are distributed in an optimized way using a dedicated file. // If push is TRUE the input data are sent over even if no apparent change // occured to the list. if (obj) { if (!fInputData) fInputData = new TList; if (!fInputData->FindObject(obj)) { fInputData->Add(obj); SetBit(TProof::kNewInputData); } } if (push) SetBit(TProof::kNewInputData); } //______________________________________________________________________________ void TProof::ClearInputData(TObject *obj) { // Remove obj form the input data list; if obj is null (default), clear the // input data info. if (!obj) { if (fInputData) { fInputData->SetOwner(kTRUE); SafeDelete(fInputData); } ResetBit(TProof::kNewInputData); // Also remove any info about input data in the input list TObject *o = 0; TList *in = GetInputList(); while ((o = GetInputList()->FindObject("PROOF_InputDataFile"))) in->Remove(o); while ((o = GetInputList()->FindObject("PROOF_InputData"))) in->Remove(o); // ... and reset the file fInputDataFile = ""; gSystem->Unlink(kPROOF_InputDataFile); } else if (fInputData) { Int_t sz = fInputData->GetSize(); while (fInputData->FindObject(obj)) fInputData->Remove(obj); // Flag for update, if anything changed if (sz != fInputData->GetSize()) SetBit(TProof::kNewInputData); } } //______________________________________________________________________________ void TProof::ClearInputData(const char *name) { // Remove obj 'name' form the input data list; TObject *obj = (fInputData && name) ? fInputData->FindObject(name) : 0; if (obj) ClearInputData(obj); } //______________________________________________________________________________ void TProof::SetInputDataFile(const char *datafile) { // Set the file to be used to optimally distribute the input data objects. // If the file exists the object in the file are added to those in the // fInputData list. If the file path is null, a default file will be created // at the moment of sending the processing request with the content of // the fInputData list. See also SendInputDataFile. if (datafile && strlen(datafile) > 0) { if (fInputDataFile != datafile && strcmp(datafile, kPROOF_InputDataFile)) SetBit(TProof::kNewInputData); fInputDataFile = datafile; } else { if (!fInputDataFile.IsNull()) SetBit(TProof::kNewInputData); fInputDataFile = ""; } // Make sure that the chosen file is readable if (fInputDataFile != kPROOF_InputDataFile && !fInputDataFile.IsNull() && gSystem->AccessPathName(fInputDataFile, kReadPermission)) { fInputDataFile = ""; } } //______________________________________________________________________________ void TProof::SendInputDataFile() { // Send the input data objects to the master; the objects are taken from the // dedicated list and / or the specified file. // If the fInputData is empty the specified file is sent over. // If there is no specified file, a file named "inputdata.root" is created locally // with the content of fInputData and sent over to the master. // If both fInputData and the specified file are not empty, a copy of the file // is made locally and augmented with the content of fInputData. // Prepare the file TString dataFile; PrepareInputDataFile(dataFile); // Send it, if not empty if (dataFile.Length() > 0) { Info("SendInputDataFile", "broadcasting %s", dataFile.Data()); BroadcastFile(dataFile.Data(), kBinary, "cache", kActive); // Set the name in the input list AddInput(new TNamed("PROOF_InputDataFile", Form("cache:%s", gSystem->BaseName(dataFile)))); } } //______________________________________________________________________________ void TProof::PrepareInputDataFile(TString &dataFile) { // Prepare the file with the input data objects to be sent the master; the // objects are taken from the dedicated list and / or the specified file. // If the fInputData is empty the specified file is sent over. // If there is no specified file, a file named "inputdata.root" is created locally // with the content of fInputData and sent over to the master. // If both fInputData and the specified file are not empty, a copy of the file // is made locally and augmented with the content of fInputData. // Save info about new data for usage in this call; Bool_t newdata = TestBit(TProof::kNewInputData) ? kTRUE : kFALSE; // Next time we need some change ResetBit(TProof::kNewInputData); // Check the list Bool_t list_ok = (fInputData && fInputData->GetSize() > 0) ? kTRUE : kFALSE; // Check the file Bool_t file_ok = kFALSE; if (fInputDataFile != kPROOF_InputDataFile && !fInputDataFile.IsNull() && !gSystem->AccessPathName(fInputDataFile, kReadPermission)) { // It must contain something TFile *f = TFile::Open(fInputDataFile); if (f && f->GetListOfKeys() && f->GetListOfKeys()->GetSize() > 0) file_ok = kTRUE; } // Remove any info about input data in the input list TObject *o = 0; TList *in = GetInputList(); while ((o = GetInputList()->FindObject("PROOF_InputDataFile"))) in->Remove(o); while ((o = GetInputList()->FindObject("PROOF_InputData"))) in->Remove(o); // We must have something to send dataFile = ""; if (!list_ok && !file_ok) return; // Three cases: if (file_ok && !list_ok) { // Just send the file dataFile = fInputDataFile; } else if (!file_ok && list_ok) { fInputDataFile = kPROOF_InputDataFile; // Nothing to do, if no new data if (!newdata && !gSystem->AccessPathName(fInputDataFile)) return; // Create the file first TFile *f = TFile::Open(fInputDataFile, "RECREATE"); if (f) { f->cd(); TIter next(fInputData); TObject *obj; while ((obj = next())) { obj->Write(0, TObject::kSingleKey, 0); } f->Close(); SafeDelete(f); } else { Error("PrepareInputDataFile", "could not (re-)create %s", fInputDataFile.Data()); return; } dataFile = fInputDataFile; } else if (file_ok && list_ok) { dataFile = kPROOF_InputDataFile; // Create the file if not existing or there are new data if (newdata || gSystem->AccessPathName(dataFile)) { // Cleanup previous file if obsolete if (!gSystem->AccessPathName(dataFile)) gSystem->Unlink(dataFile); if (dataFile != fInputDataFile) { // Make a local copy first if (gSystem->CopyFile(fInputDataFile, dataFile, kTRUE) != 0) { Error("PrepareInputDataFile", "could not make local copy of %s", fInputDataFile.Data()); return; } } // Add the input data list TFile *f = TFile::Open(dataFile, "UPDATE"); if (f) { f->cd(); TIter next(fInputData); TObject *obj = 0; while ((obj = next())) { obj->Write(0, TObject::kSingleKey, 0); } f->Close(); SafeDelete(f); } else { Error("PrepareInputDataFile", "could not open %s for updating", dataFile.Data()); return; } } } // Done return; } //______________________________________________________________________________ void TProof::AddInput(TObject *obj) { // Add objects that might be needed during the processing of // the selector (see Process()). if (fPlayer) fPlayer->AddInput(obj); } //______________________________________________________________________________ void TProof::ClearInput() { // Clear input object list. if (fPlayer) fPlayer->ClearInput(); // the system feedback list is always in the input list AddInput(fFeedback); } //______________________________________________________________________________ TList *TProof::GetInputList() { // Get input list. return (fPlayer ? fPlayer->GetInputList() : (TList *)0); } //______________________________________________________________________________ TObject *TProof::GetOutput(const char *name) { // Get specified object that has been produced during the processing // (see Process()). // Can be called by MarkBad on the master before the player is initialized return (fPlayer) ? fPlayer->GetOutput(name) : (TObject *)0; } //______________________________________________________________________________ TList *TProof::GetOutputList() { // Get list with all object created during processing (see Process()). return (fPlayer ? fPlayer->GetOutputList() : (TList *)0); } //______________________________________________________________________________ void TProof::SetParameter(const char *par, const char *value) { // Set input list parameter. If the parameter is already // set it will be set to the new value. if (!fPlayer) { Warning("SetParameter", "player undefined! Ignoring"); return; } TList *il = fPlayer->GetInputList(); TObject *item = il->FindObject(par); if (item) { il->Remove(item); delete item; } il->Add(new TNamed(par, value)); } //______________________________________________________________________________ void TProof::SetParameter(const char *par, Int_t value) { // Set an input list parameter. if (!fPlayer) { Warning("SetParameter", "player undefined! Ignoring"); return; } TList *il = fPlayer->GetInputList(); TObject *item = il->FindObject(par); if (item) { il->Remove(item); delete item; } il->Add(new TParameter<Int_t>(par, value)); } //______________________________________________________________________________ void TProof::SetParameter(const char *par, Long_t value) { // Set an input list parameter. if (!fPlayer) { Warning("SetParameter", "player undefined! Ignoring"); return; } TList *il = fPlayer->GetInputList(); TObject *item = il->FindObject(par); if (item) { il->Remove(item); delete item; } il->Add(new TParameter<Long_t>(par, value)); } //______________________________________________________________________________ void TProof::SetParameter(const char *par, Long64_t value) { // Set an input list parameter. if (!fPlayer) { Warning("SetParameter", "player undefined! Ignoring"); return; } TList *il = fPlayer->GetInputList(); TObject *item = il->FindObject(par); if (item) { il->Remove(item); delete item; } il->Add(new TParameter<Long64_t>(par, value)); } //______________________________________________________________________________ void TProof::SetParameter(const char *par, Double_t value) { // Set an input list parameter. if (!fPlayer) { Warning("SetParameter", "player undefined! Ignoring"); return; } TList *il = fPlayer->GetInputList(); TObject *item = il->FindObject(par); if (item) { il->Remove(item); delete item; } il->Add(new TParameter<Double_t>(par, value)); } //______________________________________________________________________________ TObject *TProof::GetParameter(const char *par) const { // Get specified parameter. A parameter set via SetParameter() is either // a TParameter or a TNamed or 0 in case par is not defined. if (!fPlayer) { Warning("GetParameter", "player undefined! Ignoring"); return (TObject *)0; } TList *il = fPlayer->GetInputList(); return il->FindObject(par); } //______________________________________________________________________________ void TProof::DeleteParameters(const char *wildcard) { // Delete the input list parameters specified by a wildcard (e.g. PROOF_*) // or exact name (e.g. PROOF_MaxSlavesPerNode). if (!fPlayer) return; if (!wildcard) wildcard = ""; TRegexp re(wildcard, kTRUE); Int_t nch = strlen(wildcard); TList *il = fPlayer->GetInputList(); if (il) { TObject *p = 0; TIter next(il); while ((p = next())) { TString s = p->GetName(); if (nch && s != wildcard && s.Index(re) == kNPOS) continue; il->Remove(p); delete p; } } } //______________________________________________________________________________ void TProof::ShowParameters(const char *wildcard) const { // Show the input list parameters specified by the wildcard. // Default is the special PROOF control parameters (PROOF_*). if (!fPlayer) return; if (!wildcard) wildcard = ""; TRegexp re(wildcard, kTRUE); Int_t nch = strlen(wildcard); TList *il = fPlayer->GetInputList(); TObject *p; TIter next(il); while ((p = next())) { TString s = p->GetName(); if (nch && s != wildcard && s.Index(re) == kNPOS) continue; if (p->IsA() == TNamed::Class()) { Printf("%s\t\t\t%s", s.Data(), p->GetTitle()); } else if (p->IsA() == TParameter<Long_t>::Class()) { Printf("%s\t\t\t%ld", s.Data(), dynamic_cast<TParameter<Long_t>*>(p)->GetVal()); } else if (p->IsA() == TParameter<Long64_t>::Class()) { Printf("%s\t\t\t%lld", s.Data(), dynamic_cast<TParameter<Long64_t>*>(p)->GetVal()); } else if (p->IsA() == TParameter<Double_t>::Class()) { Printf("%s\t\t\t%f", s.Data(), dynamic_cast<TParameter<Double_t>*>(p)->GetVal()); } else { Printf("%s\t\t\t%s", s.Data(), p->GetTitle()); } } } //______________________________________________________________________________ void TProof::AddFeedback(const char *name) { // Add object to feedback list. PDB(kFeedback, 3) Info("AddFeedback", "Adding object \"%s\" to feedback", name); if (fFeedback->FindObject(name) == 0) fFeedback->Add(new TObjString(name)); } //______________________________________________________________________________ void TProof::RemoveFeedback(const char *name) { // Remove object from feedback list. TObject *obj = fFeedback->FindObject(name); if (obj != 0) { fFeedback->Remove(obj); delete obj; } } //______________________________________________________________________________ void TProof::ClearFeedback() { // Clear feedback list. fFeedback->Delete(); } //______________________________________________________________________________ void TProof::ShowFeedback() const { // Show items in feedback list. if (fFeedback->GetSize() == 0) { Info("","no feedback requested"); return; } fFeedback->Print(); } //______________________________________________________________________________ TList *TProof::GetFeedbackList() const { // Return feedback list. return fFeedback; } //______________________________________________________________________________ TTree *TProof::GetTreeHeader(TDSet *dset) { // Creates a tree header (a tree with nonexisting files) object for // the DataSet. TList *l = GetListOfActiveSlaves(); TSlave *sl = (TSlave*) l->First(); if (sl == 0) { Error("GetTreeHeader", "No connection"); return 0; } TSocket *soc = sl->GetSocket(); TMessage msg(kPROOF_GETTREEHEADER); msg << dset; soc->Send(msg); TMessage *reply; Int_t d = -1; if (fProtocol >= 20) { Collect(sl, fCollectTimeout, kPROOF_GETTREEHEADER); reply = (TMessage *) fRecvMessages->First(); } else { d = soc->Recv(reply); } if (!reply) { Error("GetTreeHeader", "Error getting a replay from the master.Result %d", (int) d); return 0; } TString s1; TTree *t = 0; (*reply) >> s1; if (s1 == "Success") (*reply) >> t; PDB(kGlobal, 1) { if (t) { Info("GetTreeHeader", "%s, message size: %d, entries: %d", s1.Data(), reply->BufferSize(), (int) t->GetMaxEntryLoop()); } else { Info("GetTreeHeader", "tree header retrieval failed"); } } delete reply; return t; } //______________________________________________________________________________ TDrawFeedback *TProof::CreateDrawFeedback() { // Draw feedback creation proxy. When accessed via TProof avoids // link dependency on libProofPlayer. return (fPlayer ? fPlayer->CreateDrawFeedback(this) : (TDrawFeedback *)0); } //______________________________________________________________________________ void TProof::SetDrawFeedbackOption(TDrawFeedback *f, Option_t *opt) { // Set draw feedback option. if (fPlayer) fPlayer->SetDrawFeedbackOption(f, opt); } //______________________________________________________________________________ void TProof::DeleteDrawFeedback(TDrawFeedback *f) { // Delete draw feedback object. if (fPlayer) fPlayer->DeleteDrawFeedback(f); } //______________________________________________________________________________ TList *TProof::GetOutputNames() { // FIXME: to be written return 0; /* TMessage msg(kPROOF_GETOUTPUTLIST); TList* slaves = fActiveSlaves; Broadcast(msg, slaves); TMonitor mon; TList* outputList = new TList(); TIter si(slaves); TSlave *slave; while ((slave = (TSlave*)si.Next()) != 0) { PDB(kGlobal,4) Info("GetOutputNames","Socket added to monitor: %p (%s)", slave->GetSocket(), slave->GetName()); mon.Add(slave->GetSocket()); } mon.ActivateAll(); ((TProof*)gProof)->DeActivateAsyncInput(); ((TProof*)gProof)->fCurrentMonitor = &mon; while (mon.GetActive() != 0) { TSocket *sock = mon.Select(); if (!sock) { Error("GetOutputList","TMonitor::.Select failed!"); break; } mon.DeActivate(sock); TMessage *reply; if (sock->Recv(reply) <= 0) { MarkBad(slave, "receive failed after kPROOF_GETOUTPUTLIST request"); // Error("GetOutputList","Recv failed! for slave-%d (%s)", // slave->GetOrdinal(), slave->GetName()); continue; } if (reply->What() != kPROOF_GETOUTPUTNAMES ) { // Error("GetOutputList","unexpected message %d from slawe-%d (%s)", reply->What(), // slave->GetOrdinal(), slave->GetName()); MarkBad(slave, "wrong reply to kPROOF_GETOUTPUTLIST request"); continue; } TList* l; (*reply) >> l; TIter next(l); TNamed *n; while ( (n = dynamic_cast<TNamed*> (next())) ) { if (!outputList->FindObject(n->GetName())) outputList->Add(n); } delete reply; } ((TProof*)gProof)->fCurrentMonitor = 0; return outputList; */ } //______________________________________________________________________________ void TProof::Browse(TBrowser *b) { // Build the PROOF's structure in the browser. b->Add(fActiveSlaves, fActiveSlaves->Class(), "fActiveSlaves"); b->Add(&fMaster, fMaster.Class(), "fMaster"); b->Add(fFeedback, fFeedback->Class(), "fFeedback"); b->Add(fChains, fChains->Class(), "fChains"); if (fPlayer) { b->Add(fPlayer->GetInputList(), fPlayer->GetInputList()->Class(), "InputList"); if (fPlayer->GetOutputList()) b->Add(fPlayer->GetOutputList(), fPlayer->GetOutputList()->Class(), "OutputList"); if (fPlayer->GetListOfResults()) b->Add(fPlayer->GetListOfResults(), fPlayer->GetListOfResults()->Class(), "ListOfResults"); } } //______________________________________________________________________________ void TProof::SetPlayer(TVirtualProofPlayer *player) { // Set a new PROOF player. if (fPlayer) delete fPlayer; fPlayer = player; }; //______________________________________________________________________________ TVirtualProofPlayer *TProof::MakePlayer(const char *player, TSocket *s) { // Construct a TProofPlayer object. The player string specifies which // player should be created: remote, slave, sm (supermaster) or base. // Default is remote. Socket is needed in case a slave player is created. if (!player) player = "remote"; SetPlayer(TVirtualProofPlayer::Create(player, this, s)); return GetPlayer(); } //______________________________________________________________________________ void TProof::AddChain(TChain *chain) { // Add chain to data set fChains->Add(chain); } //______________________________________________________________________________ void TProof::RemoveChain(TChain *chain) { // Remove chain from data set fChains->Remove(chain); } //______________________________________________________________________________ void TProof::GetLog(Int_t start, Int_t end) { // Ask for remote logs in the range [start, end]. If start == -1 all the // messages not yet received are sent back. if (!IsValid() || TestBit(TProof::kIsMaster)) return; TMessage msg(kPROOF_LOGFILE); msg << start << end; Broadcast(msg, kActive); Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ TMacro *TProof::GetLastLog() { // Fill a TMacro with the log lines since the last reading (fLogFileR) // Return (TMacro *)0 if no line was logged. // The returned TMacro must be deleted by the caller. TMacro *maclog = 0; // Save present offset off_t nowlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_CUR); if (nowlog < 0) { SysError("GetLastLog", "problem lseeking log file to current position (errno: %d)", TSystem::GetErrno()); return maclog; } // Get extremes off_t startlog = nowlog; off_t endlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_END); if (endlog < 0) { SysError("GetLastLog", "problem lseeking log file to end position (errno: %d)", TSystem::GetErrno()); return maclog; } // Perhaps nothing to log UInt_t tolog = (UInt_t)(endlog - startlog); if (tolog <= 0) return maclog; // Set starting point if (lseek(fileno(fLogFileR), startlog, SEEK_SET) < 0) { SysError("GetLastLog", "problem lseeking log file to start position (errno: %d)", TSystem::GetErrno()); return maclog; } // Create the output object maclog = new TMacro; // Now we go char line[2048]; Int_t wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog; while (fgets(line, wanted, fLogFileR)) { Int_t r = strlen(line); if (r > 0) { if (line[r-1] == '\n') line[r-1] = '\0'; maclog->AddLine(line); } else { // Done break; } tolog -= r; wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog; } // Restore original pointer if (lseek(fileno(fLogFileR), nowlog, SEEK_SET) < 0) { Warning("GetLastLog", "problem lseeking log file to original position (errno: %d)", TSystem::GetErrno()); } // Done return maclog; } //______________________________________________________________________________ void TProof::PutLog(TQueryResult *pq) { // Display log of query pq into the log window frame if (!pq) return; TList *lines = pq->GetLogFile()->GetListOfLines(); if (lines) { TIter nxl(lines); TObjString *l = 0; while ((l = (TObjString *)nxl())) EmitVA("LogMessage(const char*,Bool_t)", 2, l->GetName(), kFALSE); } } //______________________________________________________________________________ void TProof::ShowLog(const char *queryref) { // Display on screen the content of the temporary log file for query // in reference // Make sure we have all info (GetListOfQueries retrieves the // head info only) Retrieve(queryref); if (fPlayer) { if (queryref) { if (fPlayer->GetListOfResults()) { TIter nxq(fPlayer->GetListOfResults()); TQueryResult *qr = 0; while ((qr = (TQueryResult *) nxq())) if (strstr(queryref, qr->GetTitle()) && strstr(queryref, qr->GetName())) break; if (qr) { PutLog(qr); return; } } } } } //______________________________________________________________________________ void TProof::ShowLog(Int_t qry) { // Display on screen the content of the temporary log file. // If qry == -2 show messages from the last (current) query. // If qry == -1 all the messages not yet displayed are shown (default). // If qry == 0, all the messages in the file are shown. // If qry > 0, only the messages related to query 'qry' are shown. // For qry != -1 the original file offset is restored at the end // Save present offset off_t nowlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_CUR); if (nowlog < 0) { SysError("ShowLog", "problem lseeking log file (errno: %d)", TSystem::GetErrno()); return; } // Get extremes off_t startlog = nowlog; off_t endlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_END); if (endlog < 0) { SysError("ShowLog", "problem lseeking log file (errno: %d)", TSystem::GetErrno()); return; } lseek(fileno(fLogFileR), nowlog, SEEK_SET); if (qry == 0) { startlog = 0; lseek(fileno(fLogFileR), (off_t) 0, SEEK_SET); } else if (qry != -1) { TQueryResult *pq = 0; if (qry == -2) { // Pickup the last one pq = (GetQueryResults()) ? ((TQueryResult *)(GetQueryResults()->Last())) : 0; if (!pq) { GetListOfQueries(); if (fQueries) pq = (TQueryResult *)(fQueries->Last()); } } else if (qry > 0) { TList *queries = GetQueryResults(); if (queries) { TIter nxq(queries); while ((pq = (TQueryResult *)nxq())) if (qry == pq->GetSeqNum()) break; } if (!pq) { queries = GetListOfQueries(); TIter nxq(queries); while ((pq = (TQueryResult *)nxq())) if (qry == pq->GetSeqNum()) break; } } if (pq) { PutLog(pq); return; } else { if (gDebug > 0) Info("ShowLog","query %d not found in list", qry); qry = -1; } } // Number of bytes to log UInt_t tolog = (UInt_t)(endlog - startlog); // Perhaps nothing if (tolog <= 0) // Set starting point lseek(fileno(fLogFileR), startlog, SEEK_SET); // Now we go Int_t np = 0; char line[2048]; Int_t wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog; while (fgets(line, wanted, fLogFileR)) { Int_t r = strlen(line); if (!SendingLogToWindow()) { if (line[r-1] != '\n') line[r-1] = '\n'; if (r > 0) { char *p = line; while (r) { Int_t w = write(fileno(stdout), p, r); if (w < 0) { SysError("ShowLog", "error writing to stdout"); break; } r -= w; p += w; } } tolog -= strlen(line); np++; // Ask if more is wanted if (!(np%10)) { char *opt = Getline("More (y/n)? [y]"); if (opt[0] == 'n') break; } // We may be over if (tolog <= 0) break; // Update wanted bytes wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog; } else { // Log to window if (line[r-1] == '\n') line[r-1] = 0; LogMessage(line, kFALSE); } } if (!SendingLogToWindow()) { // Avoid screwing up the prompt if (write(fileno(stdout), "\n", 1) != 1) SysError("ShowLog", "error writing to stdout"); } // Restore original pointer if (qry > -1) lseek(fileno(fLogFileR), nowlog, SEEK_SET); } //______________________________________________________________________________ void TProof::cd(Int_t id) { // Set session with 'id' the default one. If 'id' is not found in the list, // the current session is set as default if (GetManager()) { TProofDesc *d = GetManager()->GetProofDesc(id); if (d) { if (d->GetProof()) { gProof = d->GetProof(); return; } } // Id not found or undefined: set as default this session gProof = this; } return; } //______________________________________________________________________________ void TProof::Detach(Option_t *opt) { // Detach this instance to its proofserv. // If opt is 'S' or 's' the remote server is shutdown // Nothing to do if not in contact with proofserv if (!IsValid()) return; // Get worker and socket instances TSlave *sl = (TSlave *) fActiveSlaves->First(); TSocket *s = 0; if (!sl || !(sl->IsValid()) || !(s = sl->GetSocket())) { Error("Detach","corrupted worker instance: wrk:%p, sock:%p", sl, s); return; } Bool_t shutdown = (strchr(opt,'s') || strchr(opt,'S')) ? kTRUE : kFALSE; // If processing, try to stop processing first if (shutdown && !IsIdle()) { // Remove pending requests Remove("cleanupqueue"); // Do not wait for ever, but al least 20 seconds Long_t timeout = gEnv->GetValue("Proof.ShutdownTimeout", 60); timeout = (timeout > 20) ? timeout : 20; // Send stop signal StopProcess(kFALSE, (Long_t) (timeout / 2)); // Receive results Collect(kActive, timeout); } // Avoid spurious messages: deactivate new inputs ... DeActivateAsyncInput(); // ... and discard existing ones sl->FlushSocket(); // Close session (we always close the connection) Close(opt); // Close the progress dialog, if any if (fProgressDialogStarted) CloseProgressDialog(); // Update info in the table of our manager, if any if (GetManager() && GetManager()->QuerySessions("L")) { TIter nxd(GetManager()->QuerySessions("L")); TProofDesc *d = 0; while ((d = (TProofDesc *)nxd())) { if (d->GetProof() == this) { d->SetProof(0); GetManager()->QuerySessions("L")->Remove(d); break; } } } // Invalidate this instance fValid = kFALSE; return; } //______________________________________________________________________________ void TProof::SetAlias(const char *alias) { // Set an alias for this session. If reconnection is supported, the alias // will be communicated to the remote coordinator so that it can be recovered // when reconnecting // Set it locally TNamed::SetTitle(alias); if (TestBit(TProof::kIsMaster)) // Set the name at the same value TNamed::SetName(alias); // Nothing to do if not in contact with coordinator if (!IsValid()) return; if (!IsProofd() && TestBit(TProof::kIsClient)) { TSlave *sl = (TSlave *) fActiveSlaves->First(); if (sl) sl->SetAlias(alias); } return; } //______________________________________________________________________________ Int_t TProof::UploadDataSet(const char *dataSetName, TList *files, const char *desiredDest, Int_t opt, TList *skippedFiles) { // Upload a set of files and save the list of files by name dataSetName. // The 'files' argument is a list of TFileInfo objects describing the files // as first url. // The mask 'opt' is a combination of EUploadOpt: // kAppend (0x1) if set true files will be appended to // the dataset existing by given name // kOverwriteDataSet (0x2) if dataset with given name exited it // would be overwritten // kNoOverwriteDataSet (0x4) do not overwirte if the dataset exists // kOverwriteAllFiles (0x8) overwrite all files that may exist // kOverwriteNoFiles (0x10) overwrite none // kAskUser (0x0) ask user before overwriteng dataset/files // The default value is kAskUser. // The user will be asked to confirm overwriting dataset or files unless // specified opt provides the answer! // If kOverwriteNoFiles is set, then a pointer to TList must be passed as // skippedFiles argument. The function will add to this list TFileInfo // objects describing all files that existed on the cluster and were // not uploaded. // // Communication Summary // Client Master // |------------>DataSetName----------->| // |<-------kMESS_OK/kMESS_NOTOK<-------| (Name OK/file exist) // (*)|-------> call RegisterDataSet ------->| // (*) - optional if (fProtocol < 15) { Info("UploadDataSet", "functionality not available: the server has an" " incompatible version of TFileInfo"); return -1; } if (IsLite()) { Info("UploadDataSet", "Lite-session: functionality not needed - do nothing"); return -1; } // check if dataSetName is not excluded if (strchr(dataSetName, '/')) { if (strstr(dataSetName, "public") != dataSetName) { Error("UploadDataSet", "Name of public dataset should start with public/"); return kError; } } if ((opt & kOverwriteAllFiles && opt & kOverwriteNoFiles) || (opt & kNoOverwriteDataSet && opt & kAppend) || (opt & kOverwriteDataSet && opt & kAppend) || (opt & kNoOverwriteDataSet && opt & kOverwriteDataSet) || (opt & kAskUser && opt & (kOverwriteDataSet | kNoOverwriteDataSet | kAppend | kOverwriteAllFiles | kOverwriteNoFiles))) { Error("UploadDataSet", "you specified contradicting options."); return kError; } // Decode options Int_t overwriteAll = (opt & kOverwriteAllFiles) ? kTRUE : kFALSE; Int_t overwriteNone = (opt & kOverwriteNoFiles) ? kTRUE : kFALSE; Int_t goodName = (opt & (kOverwriteDataSet | kAppend)) ? 1 : -1; Int_t appendToDataSet = (opt & kAppend) ? kTRUE : kFALSE; Int_t overwriteNoDataSet = (opt & kNoOverwriteDataSet) ? kTRUE : kFALSE; //If skippedFiles is not provided we can not return list of skipped files. if (!skippedFiles && overwriteNone) { Error("UploadDataSet", "Provide pointer to TList object as skippedFiles argument when using kOverwriteNoFiles option."); return kError; } //If skippedFiles is provided but did not point to a TList the have to STOP if (skippedFiles) { if (skippedFiles->Class() != TList::Class()) { Error("UploadDataSet", "Provided skippedFiles argument does not point to a TList object."); return kError; } } TSocket *master; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("UploadDataSet", "No connection to the master!"); return kError; } Int_t fileCount = 0; // return value if (goodName == -1) { // -1 for undefined // First check whether this dataset already exists unless // kAppend or kOverWriteDataSet TMessage nameMess(kPROOF_DATASETS); nameMess << Int_t(kCheckDataSetName); nameMess << TString(dataSetName); Broadcast(nameMess); Collect(kActive, fCollectTimeout); //after each call to HandleDataSets if (fStatus == -1) { //We ask user to agree on overwriting the dataset name while (goodName == -1 && !overwriteNoDataSet) { Info("UploadDataSet", "dataset %s already exist. ", dataSetName); Info("UploadDataSet", "do you want to overwrite it[Yes/No/Append]?"); TString answer; answer.ReadToken(cin); if (!strncasecmp(answer.Data(), "y", 1)) { goodName = 1; } else if (!strncasecmp(answer.Data(), "n", 1)) { goodName = 0; } else if (!strncasecmp(answer.Data(), "a", 1)) { goodName = 1; appendToDataSet = kTRUE; } } } else { goodName = 1; } } // if (goodName == -1) if (goodName == 1) { //must be == 1 as -1 was used for a bad name! //Code for enforcing writing in user "home dir" only char *relativeDestDir = Form("%s/%s/", gSystem->GetUserInfo()->fUser.Data(), desiredDest?desiredDest:""); //Consider adding dataSetName to the path relativeDestDir = CollapseSlashesInPath(relativeDestDir); TString dest = Form("%s/%s", GetDataPoolUrl(), relativeDestDir); delete[] relativeDestDir; // Now we will actually copy files and create the TList object TFileCollection *fileList = new TFileCollection(); TIter next(files); while (TFileInfo *fileInfo = ((TFileInfo*)next())) { TUrl *fileUrl = fileInfo->GetFirstUrl(); if (gSystem->AccessPathName(fileUrl->GetUrl()) == kFALSE) { //matching dir entry //getting the file name from the path represented by fileUrl const char *ent = gSystem->BaseName(fileUrl->GetFile()); Int_t goodFileName = 1; if (!overwriteAll && gSystem->AccessPathName(Form("%s/%s", dest.Data(), ent), kFileExists) == kFALSE) { //Destination file exists goodFileName = -1; while (goodFileName == -1 && !overwriteAll && !overwriteNone) { Info("UploadDataSet", "file %s already exists. ", Form("%s/%s", dest.Data(), ent)); Info("UploadDataSet", "do you want to overwrite it [Yes/No/all/none]?"); TString answer; answer.ReadToken(cin); if (!strncasecmp(answer.Data(), "y", 1)) goodFileName = 1; else if (!strncasecmp(answer.Data(), "all", 3)) overwriteAll = kTRUE; else if (!strncasecmp(answer.Data(), "none", 4)) overwriteNone = kTRUE; else if (!strncasecmp(answer.Data(), "n", 1)) goodFileName = 0; } } //if file exists // Copy the file to the redirector indicated if (goodFileName == 1 || overwriteAll) { //must be == 1 as -1 was meant for bad name! Info("UploadDataSet", "Uploading %s to %s/%s", fileUrl->GetUrl(), dest.Data(), ent); if (TFile::Cp(fileUrl->GetUrl(), Form("%s/%s", dest.Data(), ent))) { fileList->GetList()->Add(new TFileInfo(Form("%s/%s", dest.Data(), ent))); } else Error("UploadDataSet", "file %s was not copied", fileUrl->GetUrl()); } else { // don't overwrite, but file exist and must be included fileList->GetList()->Add(new TFileInfo(Form("%s/%s", dest.Data(), ent))); if (skippedFiles) { // user specified the TList *skippedFiles argument so we create // the list of skipped files skippedFiles->Add(new TFileInfo(fileUrl->GetUrl())); } } } //if matching dir entry } //while if ((fileCount = fileList->GetList()->GetSize()) == 0) { Info("UploadDataSet", "no files were copied. The dataset will not be saved"); } else { TString o = (appendToDataSet) ? "" : "O"; if (!RegisterDataSet(dataSetName, fileList, o)) { Error("UploadDataSet", "Error while saving dataset: %s", dataSetName); fileCount = kError; } } delete fileList; } else if (overwriteNoDataSet) { Info("UploadDataSet", "dataset %s already exists", dataSetName); return kDataSetExists; } //if(goodName == 1) return fileCount; } //______________________________________________________________________________ Int_t TProof::UploadDataSet(const char *dataSetName, const char *files, const char *desiredDest, Int_t opt, TList *skippedFiles) { // Upload a set of files and save the list of files by name dataSetName. // The mask 'opt' is a combination of EUploadOpt: // kAppend (0x1) if set true files will be appended to // the dataset existing by given name // kOverwriteDataSet (0x2) if dataset with given name exited it // would be overwritten // kNoOverwriteDataSet (0x4) do not overwirte if the dataset exists // kOverwriteAllFiles (0x8) overwrite all files that may exist // kOverwriteNoFiles (0x10) overwrite none // kAskUser (0x0) ask user before overwriteng dataset/files // The default value is kAskUser. // The user will be asked to confirm overwriting dataset or files unless // specified opt provides the answer! // If kOverwriteNoFiles is set, then a pointer to TList must be passed as // skippedFiles argument. The function will add to this list TFileInfo // objects describing all files that existed on the cluster and were // not uploaded. // if (fProtocol < 15) { Info("UploadDataSet", "functionality not available: the server has an" " incompatible version of TFileInfo"); return -1; } TList fileList; fileList.SetOwner(); void *dataSetDir = gSystem->OpenDirectory(gSystem->DirName(files)); const char* ent; TString filesExp(gSystem->BaseName(files)); filesExp.ReplaceAll("*",".*"); TRegexp rg(filesExp); while ((ent = gSystem->GetDirEntry(dataSetDir))) { TString entryString(ent); if (entryString.Index(rg) != kNPOS) { // Matching dir entry: add to the list TString u(Form("file://%s/%s", gSystem->DirName(files), ent)); if (gSystem->AccessPathName(u, kReadPermission) == kFALSE) fileList.Add(new TFileInfo(u)); } //if matching dir entry } //while Int_t fileCount; if ((fileCount = fileList.GetSize()) == 0) Printf("No files match your selection. The dataset will not be saved"); else fileCount = UploadDataSet(dataSetName, &fileList, desiredDest, opt, skippedFiles); return fileCount; } //______________________________________________________________________________ Int_t TProof::UploadDataSetFromFile(const char *dataset, const char *file, const char *dest, Int_t opt, TList *skippedFiles) { // Upload files listed in "file" to PROOF cluster. // Where file = name of file containing list of files and // dataset = dataset name and opt is a combination of EUploadOpt bits. // Each file description (line) can include wildcards. // Check TFileInfo compatibility if (fProtocol < 15) { Info("UploadDataSetFromFile", "functionality not available: the server has an" " incompatible version of TFileInfo"); return -1; } Int_t fileCount = -1; // Create the list to feed UploadDataSet(char *dataset, TList *l, ...) TList fileList; fileList.SetOwner(); ifstream f; f.open(gSystem->ExpandPathName(file), ifstream::out); if (f.is_open()) { while (f.good()) { TString line; line.ReadToDelim(f); line.Strip(TString::kTrailing, '\n'); if (gSystem->AccessPathName(line, kReadPermission) == kFALSE) fileList.Add(new TFileInfo(line)); } f.close(); if ((fileCount = fileList.GetSize()) == 0) Info("UploadDataSetFromFile", "no files match your selection. The dataset will not be saved"); else fileCount = UploadDataSet(dataset, &fileList, dest, opt, skippedFiles); } else { Error("UploadDataSetFromFile", "unable to open the specified file"); } // Done return fileCount; } //______________________________________________________________________________ Bool_t TProof::RegisterDataSet(const char *dataSetName, TFileCollection *dataSet, const char* optStr) { // Register the 'dataSet' on the cluster under the current // user, group and the given 'dataSetName'. // If a dataset with the same name already exists the action fails unless 'opts' // contains 'O', in which case the old dataset is overwritten, or contains 'U', // in which case 'newDataSet' is added to the existing dataset (duplications are // ignored, if any). // If 'opts' contains 'V' the dataset files are also verified (if the dataset manager // is configured to allow so). By default the dataset is not verified. // If 'opts' contains 'T' the in the dataset object (status bits, meta,...) // is trusted, i.e. not reset (if the dataset manager is configured to allow so). // Returns kTRUE on success. // Check TFileInfo compatibility if (fProtocol < 17) { Info("RegisterDataSet", "functionality not available: the server does not have dataset support"); return kFALSE; } if (!dataSetName || strlen(dataSetName) <= 0) { Info("RegisterDataSet", "specifying a dataset name is mandatory"); return kFALSE; } TSocket *master; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("RegisterDataSet", "No connection to the master!"); return kFALSE; } TMessage mess(kPROOF_DATASETS); mess << Int_t(kRegisterDataSet); mess << TString(dataSetName); mess << TString(optStr); mess.WriteObject(dataSet); Broadcast(mess); Bool_t result = kTRUE; Collect(); if (fStatus != 0) { Error("RegisterDataSet", "dataset was not saved"); result = kFALSE; } return result; } //______________________________________________________________________________ Int_t TProof::SetDataSetTreeName(const char *dataset, const char *treename) { // Set/Change the name of the default tree. The tree name may contain // subdir specification in the form "subdir/name". // Returns 0 on success, -1 otherwise. // Check TFileInfo compatibility if (fProtocol < 23) { Info("SetDataSetTreeName", "functionality not supported by the server"); return -1; } if (!dataset || strlen(dataset) <= 0) { Info("SetDataSetTreeName", "specifying a dataset name is mandatory"); return -1; } if (!treename || strlen(treename) <= 0) { Info("SetDataSetTreeName", "specifying a tree name is mandatory"); return -1; } TUri uri(dataset); TString fragment(treename); if (!fragment.BeginsWith("/")) fragment.Insert(0, "/"); uri.SetFragment(fragment); TMessage mess(kPROOF_DATASETS); mess << Int_t(kSetDefaultTreeName); mess << uri.GetUri(); Broadcast(mess); Collect(); if (fStatus != 0) { Error("SetDataSetTreeName", "some error occured: default tree name not changed"); return -1; } return 0; } //______________________________________________________________________________ TMap *TProof::GetDataSets(const char *uri, const char* optStr) { // Lists all datasets that match given uri. if (fProtocol < 15) { Info("GetDataSets", "functionality not available: the server does not have dataset support"); return 0; } TSocket *master = 0; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("GetDataSets", "no connection to the master!"); return 0; } TMessage mess(kPROOF_DATASETS); mess << Int_t(kGetDataSets); mess << TString(uri?uri:""); mess << TString(optStr?optStr:""); Broadcast(mess); Collect(kActive, fCollectTimeout); TMap *dataSetMap = 0; if (fStatus != 0) { Error("GetDataSets", "error receiving datasets information"); } else { // Look in the list TMessage *retMess = (TMessage *) fRecvMessages->First(); if (retMess && retMess->What() == kMESS_OK) { if (!(dataSetMap = (TMap *)(retMess->ReadObject(TMap::Class())))) Error("GetDataSets", "error receiving datasets"); } else Error("GetDataSets", "message not found or wrong type (%p)", retMess); } return dataSetMap; } //______________________________________________________________________________ void TProof::ShowDataSets(const char *uri, const char* optStr) { // Shows datasets in locations that match the uri. // By default shows the user's datasets and global ones if (fProtocol < 15) { Info("ShowDataSets", "functionality not available: the server does not have dataset support"); return; } TSocket *master = 0; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("ShowDataSets", "no connection to the master!"); return; } TMessage mess(kPROOF_DATASETS); mess << Int_t(kShowDataSets); mess << TString(uri ? uri : ""); mess << TString(optStr ? optStr : ""); Broadcast(mess); Collect(kActive, fCollectTimeout); if (fStatus != 0) Error("ShowDataSets", "error receiving datasets information"); } //______________________________________________________________________________ Bool_t TProof::ExistsDataSet(const char *dataset) { // Returns kTRUE if 'dataset' exists, kFALSE otherwise if (fProtocol < 15) { Info("ExistsDataSet", "functionality not available: the server has an" " incompatible version of TFileInfo"); return kFALSE; } if (!dataset || strlen(dataset) <= 0) { Error("ExistsDataSet", "dataset name missing"); return kFALSE; } TMessage msg(kPROOF_DATASETS); msg << Int_t(kCheckDataSetName) << TString(dataset); Broadcast(msg); Collect(kActive, fCollectTimeout); if (fStatus == -1) { // The dataset exists return kTRUE; } // The dataset does not exists return kFALSE; } //______________________________________________________________________________ void TProof::ClearDataSetCache(const char *dataset) { // Clear the content of the dataset cache, if any (matching 'dataset', if defined). if (fProtocol < 28) { Info("ClearDataSetCache", "functionality not available on server"); return; } TMessage msg(kPROOF_DATASETS); msg << Int_t(kCache) << TString(dataset) << TString("clear"); Broadcast(msg); Collect(kActive, fCollectTimeout); // Done return; } //______________________________________________________________________________ void TProof::ShowDataSetCache(const char *dataset) { // Display the content of the dataset cache, if any (matching 'dataset', if defined). if (fProtocol < 28) { Info("ShowDataSetCache", "functionality not available on server"); return; } TMessage msg(kPROOF_DATASETS); msg << Int_t(kCache) << TString(dataset) << TString("show"); Broadcast(msg); Collect(kActive, fCollectTimeout); // Done return; } //______________________________________________________________________________ TFileCollection *TProof::GetDataSet(const char *uri, const char *optStr) { // Get a list of TFileInfo objects describing the files of the specified // dataset. // To get the short version (containing only the global meta information) // specify optStr = "S:" or optStr = "short:". // To get the sub-dataset of files located on a given server(s) specify // the list of servers (comma-separated) in the 'optStr' field. if (fProtocol < 15) { Info("GetDataSet", "functionality not available: the server has an" " incompatible version of TFileInfo"); return 0; } if (!uri || strlen(uri) <= 0) { Info("GetDataSet", "specifying a dataset name is mandatory"); return 0; } TSocket *master = 0; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("GetDataSet", "no connection to the master!"); return 0; } TMessage nameMess(kPROOF_DATASETS); nameMess << Int_t(kGetDataSet); nameMess << TString(uri); nameMess << TString(optStr ? optStr: ""); if (Broadcast(nameMess) < 0) Error("GetDataSet", "sending request failed"); Collect(kActive, fCollectTimeout); TFileCollection *fileList = 0; if (fStatus != 0) { Error("GetDataSet", "error receiving datasets information"); } else { // Look in the list TMessage *retMess = (TMessage *) fRecvMessages->First(); if (retMess && retMess->What() == kMESS_OK) { if (!(fileList = (TFileCollection*)(retMess->ReadObject(TFileCollection::Class())))) Error("GetDataSet", "error reading list of files"); } else Error("GetDataSet", "message not found or wrong type (%p)", retMess); } return fileList; } //______________________________________________________________________________ void TProof::ShowDataSet(const char *uri, const char* opt) { // display meta-info for given dataset usi TFileCollection *fileList = 0; if ((fileList = GetDataSet(uri))) { fileList->Print(opt); delete fileList; } else Warning("ShowDataSet","no such dataset: %s", uri); } //______________________________________________________________________________ Int_t TProof::RemoveDataSet(const char *uri, const char* optStr) { // Remove the specified dataset from the PROOF cluster. // Files are not deleted. TSocket *master; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("RemoveDataSet", "no connection to the master!"); return kError; } TMessage nameMess(kPROOF_DATASETS); nameMess << Int_t(kRemoveDataSet); nameMess << TString(uri?uri:""); nameMess << TString(optStr?optStr:""); if (Broadcast(nameMess) < 0) Error("RemoveDataSet", "sending request failed"); Collect(kActive, fCollectTimeout); if (fStatus != 0) return -1; else return 0; } //______________________________________________________________________________ TList* TProof::FindDataSets(const char* /*searchString*/, const char* /*optStr*/) { // Find datasets, returns in a TList all found datasets. Error ("FindDataSets", "not yet implemented"); return (TList *) 0; } //______________________________________________________________________________ Int_t TProof::VerifyDataSet(const char *uri, const char* optStr) { // Verify if all files in the specified dataset are available. // Print a list and return the number of missing files. if (fProtocol < 15) { Info("VerifyDataSet", "functionality not available: the server has an" " incompatible version of TFileInfo"); return kError; } Int_t nMissingFiles = 0; TSocket *master; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("VerifyDataSet", "no connection to the master!"); return kError; } TMessage nameMess(kPROOF_DATASETS); nameMess << Int_t(kVerifyDataSet); nameMess << TString(uri ? uri : ""); nameMess << TString(optStr ? optStr : ""); Broadcast(nameMess); Collect(kActive, fCollectTimeout); if (fStatus < 0) { Info("VerifyDataSet", "no such dataset %s", uri); return -1; } else nMissingFiles = fStatus; return nMissingFiles; } //______________________________________________________________________________ TMap *TProof::GetDataSetQuota(const char* optStr) { // returns a map of the quotas of all groups if (IsLite()) { Info("UploadDataSet", "Lite-session: functionality not implemented"); return (TMap *)0; } TSocket *master = 0; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("GetDataSetQuota", "no connection to the master!"); return 0; } TMessage mess(kPROOF_DATASETS); mess << Int_t(kGetQuota); mess << TString(optStr?optStr:""); Broadcast(mess); Collect(kActive, fCollectTimeout); TMap *groupQuotaMap = 0; if (fStatus < 0) { Info("GetDataSetQuota", "could not receive quota"); } else { // Look in the list TMessage *retMess = (TMessage *) fRecvMessages->First(); if (retMess && retMess->What() == kMESS_OK) { if (!(groupQuotaMap = (TMap*)(retMess->ReadObject(TMap::Class())))) Error("GetDataSetQuota", "error getting quotas"); } else Error("GetDataSetQuota", "message not found or wrong type (%p)", retMess); } return groupQuotaMap; } //_____________________________________________________________________________ void TProof::ShowDataSetQuota(Option_t* opt) { // shows the quota and usage of all groups // if opt contains "U" shows also distribution of usage on user-level if (fProtocol < 15) { Info("ShowDataSetQuota", "functionality not available: the server does not have dataset support"); return; } if (IsLite()) { Info("UploadDataSet", "Lite-session: functionality not implemented"); return; } TSocket *master = 0; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("ShowDataSetQuota", "no connection to the master!"); return; } TMessage mess(kPROOF_DATASETS); mess << Int_t(kShowQuota); mess << TString(opt?opt:""); Broadcast(mess); Collect(); if (fStatus != 0) Error("ShowDataSetQuota", "error receiving quota information"); } //_____________________________________________________________________________ void TProof::InterruptCurrentMonitor() { // If in active in a monitor set ready state if (fCurrentMonitor) fCurrentMonitor->Interrupt(); } //_____________________________________________________________________________ void TProof::ActivateWorker(const char *ord) { // Make sure that the worker identified by the ordinal number 'ord' is // in the active list. The request will be forwarded to the master // in direct contact with the worker. If needed, this master will move // the worker from the inactive to the active list and rebuild the list // of unique workers. // Use ord = "*" to activate all inactive workers. ModifyWorkerLists(ord, kTRUE); } //_____________________________________________________________________________ void TProof::DeactivateWorker(const char *ord) { // Remove the worker identified by the ordinal number 'ord' from the // the active list. The request will be forwarded to the master // in direct contact with the worker. If needed, this master will move // the worker from the active to the inactive list and rebuild the list // of unique workers. // Use ord = "*" to deactivate all active workers. ModifyWorkerLists(ord, kFALSE); } //_____________________________________________________________________________ void TProof::ModifyWorkerLists(const char *ord, Bool_t add) { // Modify the worker active/inactive list by making the worker identified by // the ordinal number 'ord' active (add == TRUE) or inactive (add == FALSE). // If needed, the request will be forwarded to the master in direct contact // with the worker. The end-master will move the worker from one list to the // other active and rebuild the list of unique active workers. // Use ord = "*" to deactivate all active workers. // Make sure the input make sense if (!ord || strlen(ord) <= 0) { Info("ModifyWorkerLists", "An ordinal number - e.g. \"0.4\" or \"*\" for all - is required as input"); return; } Bool_t fw = kTRUE; // Whether to forward one step down Bool_t rs = kFALSE; // Whether to rescan for unique workers // Appropriate list pointing TList *in = (add) ? fInactiveSlaves : fActiveSlaves; TList *out = (add) ? fActiveSlaves : fInactiveSlaves; if (TestBit(TProof::kIsMaster)) { fw = IsEndMaster() ? kFALSE : kTRUE; // Look for the worker in the inactive list if (in->GetSize() > 0) { TIter nxw(in); TSlave *wrk = 0; while ((wrk = (TSlave *) nxw())) { if (ord[0] == '*' || !strncmp(wrk->GetOrdinal(), ord, strlen(ord))) { // Add it to the inactive list if (!out->FindObject(wrk)) { out->Add(wrk); if (add) fActiveMonitor->Add(wrk->GetSocket()); } // Remove it from the active list in->Remove(wrk); if (!add) { fActiveMonitor->Remove(wrk->GetSocket()); wrk->SetStatus(TSlave::kInactive); } else wrk->SetStatus(TSlave::kActive); // Nothing to forward (ord is unique) fw = kFALSE; // Rescan for unique workers (active list modified) rs = kTRUE; // We are done, if not option 'all' if (ord[0] != '*') break; } } } } // Rescan for unique workers if (rs) FindUniqueSlaves(); // Forward the request one step down, if needed Int_t action = (add) ? (Int_t) kActivateWorker : (Int_t) kDeactivateWorker; if (fw) { TMessage mess(kPROOF_WORKERLISTS); mess << action << TString(ord); Broadcast(mess); Collect(kActive, fCollectTimeout); } } //_____________________________________________________________________________ TProof *TProof::Open(const char *cluster, const char *conffile, const char *confdir, Int_t loglevel) { // Start a PROOF session on a specific cluster. If cluster is 0 (the // default) then the PROOF Session Viewer GUI pops up and 0 is returned. // If cluster is "" (empty string) then we connect to a PROOF session // on the localhost ("proof://localhost"). Via conffile a specific // PROOF config file in the confir directory can be specified. // Use loglevel to set the default loging level for debugging. // The appropriate instance of TProofMgr is created, if not // yet existing. The instantiated TProof object is returned. // Use TProof::cd() to switch between PROOF sessions. // For more info on PROOF see the TProof ctor. const char *pn = "TProof::Open"; // Make sure libProof and dependents are loaded and TProof can be created, // dependents are loaded via the information in the [system].rootmap file if (!cluster) { TPluginManager *pm = gROOT->GetPluginManager(); if (!pm) { ::Error(pn, "plugin manager not found"); return 0; } if (gROOT->IsBatch()) { ::Error(pn, "we are in batch mode, cannot show PROOF Session Viewer"); return 0; } // start PROOF Session Viewer TPluginHandler *sv = pm->FindHandler("TSessionViewer", ""); if (!sv) { ::Error(pn, "no plugin found for TSessionViewer"); return 0; } if (sv->LoadPlugin() == -1) { ::Error(pn, "plugin for TSessionViewer could not be loaded"); return 0; } sv->ExecPlugin(0); return 0; } else { TString clst(cluster); if (clst.BeginsWith("workers=") || clst.BeginsWith("tunnel=")) clst.Insert(0, "/?"); // Parse input URL TUrl u(clst); // Parse any tunning info ("<cluster>/?tunnel=[<tunnel_host>:]tunnel_port) TString opts(u.GetOptions()); if (!opts.IsNull()) { Int_t it = opts.Index("tunnel="); if (it != kNPOS) { TString sport = opts(it + strlen("tunnel="), opts.Length()); TString host("127.0.0.1"); Int_t port = -1; Int_t ic = sport.Index(":"); if (ic != kNPOS) { // Isolate the host host = sport(0, ic); sport.Remove(0, ic + 1); } if (!sport.IsDigit()) { // Remove the non digit part TRegexp re("[^0-9]"); Int_t ind = sport.Index(re); if (ind != kNPOS) sport.Remove(ind); } // Set the port if (sport.IsDigit()) port = sport.Atoi(); if (port > 0) { // Set the relevant variables ::Info("TProof::Open","using tunnel at %s:%d", host.Data(), port); gEnv->SetValue("XNet.SOCKS4Host", host); gEnv->SetValue("XNet.SOCKS4Port", port); } else { // Warn parsing problems ::Warning("TProof::Open", "problems parsing tunnelling info from options: %s", opts.Data()); } } } // Find out if we are required to attach to a specific session Int_t locid = -1; Bool_t create = kFALSE; if (opts.Length() > 0) { if (opts.BeginsWith("N",TString::kIgnoreCase)) { create = kTRUE; opts.Remove(0,1); u.SetOptions(opts); } else if (opts.IsDigit()) { locid = opts.Atoi(); } } // Attach-to or create the appropriate manager TProofMgr *mgr = TProofMgr::Create(u.GetUrl()); TProof *proof = 0; if (mgr && mgr->IsValid()) { // If XProofd we always attempt an attach first (unless // explicitely not requested). Bool_t attach = (create || mgr->IsProofd() || mgr->IsLite()) ? kFALSE : kTRUE; if (attach) { TProofDesc *d = 0; if (locid < 0) // Get the list of sessions d = (TProofDesc *) mgr->QuerySessions("")->First(); else d = (TProofDesc *) mgr->GetProofDesc(locid); if (d) { proof = (TProof*) mgr->AttachSession(d); if (!proof || !proof->IsValid()) { if (locid) ::Error(pn, "new session could not be attached"); SafeDelete(proof); } } } // start the PROOF session if (!proof) { proof = (TProof*) mgr->CreateSession(conffile, confdir, loglevel); if (!proof || !proof->IsValid()) { ::Error(pn, "new session could not be created"); SafeDelete(proof); } } } return proof; } } //_____________________________________________________________________________ TProofMgr *TProof::Mgr(const char *url) { // Get instance of the effective manager for 'url' // Return 0 on failure. if (!url) return (TProofMgr *)0; // Attach or create the relevant instance return TProofMgr::Create(url); } //_____________________________________________________________________________ void TProof::Reset(const char *url, Bool_t hard) { // Wrapper around TProofMgr::Reset(...). if (url) { TProofMgr *mgr = TProof::Mgr(url); if (mgr && mgr->IsValid()) mgr->Reset(hard); else ::Error("TProof::Reset", "unable to initialize a valid manager instance"); } } //_____________________________________________________________________________ const TList *TProof::GetEnvVars() { // Get environemnt variables. return fgProofEnvList; } //_____________________________________________________________________________ void TProof::AddEnvVar(const char *name, const char *value) { // Add an variable to the list of environment variables passed to proofserv // on the master and slaves if (gDebug > 0) ::Info("TProof::AddEnvVar","%s=%s", name, value); if (fgProofEnvList == 0) { // initialize the list if needed fgProofEnvList = new TList; fgProofEnvList->SetOwner(); } else { // replace old entries with the same name TObject *o = fgProofEnvList->FindObject(name); if (o != 0) { fgProofEnvList->Remove(o); } } fgProofEnvList->Add(new TNamed(name, value)); } //_____________________________________________________________________________ void TProof::DelEnvVar(const char *name) { // Remove an variable from the list of environment variables passed to proofserv // on the master and slaves if (fgProofEnvList == 0) return; TObject *o = fgProofEnvList->FindObject(name); if (o != 0) { fgProofEnvList->Remove(o); } } //_____________________________________________________________________________ void TProof::ResetEnvVars() { // Clear the list of environment variables passed to proofserv // on the master and slaves if (fgProofEnvList == 0) return; SafeDelete(fgProofEnvList); } //______________________________________________________________________________ void TProof::SaveWorkerInfo() { // Save informations about the worker set in the file .workers in the working // dir. Called each time there is a change in the worker setup, e.g. by // TProof::MarkBad(). // We must be masters if (TestBit(TProof::kIsClient)) return; // We must have a server defined if (!gProofServ) { Error("SaveWorkerInfo","gProofServ undefined"); return; } // The relevant lists must be defined if (!fSlaves && !fBadSlaves) { Warning("SaveWorkerInfo","all relevant worker lists is undefined"); return; } // Create or truncate the file first TString fnwrk = Form("%s/.workers", gSystem->DirName(gProofServ->GetSessionDir())); FILE *fwrk = fopen(fnwrk.Data(),"w"); if (!fwrk) { Error("SaveWorkerInfo", "cannot open %s for writing (errno: %d)", fnwrk.Data(), errno); return; } // Do we need to register an additional line for another log? TString addlogext; if (gSystem->Getenv("PROOF_ADDITIONALLOG")) { addlogext = gSystem->Getenv("PROOF_ADDITIONALLOG"); if (gDebug > 0) Info("SaveWorkerInfo", "request for additional line with ext: '%s'", addlogext.Data()); } // Loop over the list of workers (active is any worker not flagged as bad) TIter nxa(fSlaves); TSlave *wrk = 0; while ((wrk = (TSlave *) nxa())) { Int_t status = (fBadSlaves && fBadSlaves->FindObject(wrk)) ? 0 : 1; // Write out record for this worker fprintf(fwrk,"%s@%s:%d %d %s %s.log\n", wrk->GetUser(), wrk->GetName(), wrk->GetPort(), status, wrk->GetOrdinal(), wrk->GetWorkDir()); // Additional line, if required if (addlogext.Length() > 0) { fprintf(fwrk,"%s@%s:%d %d %s %s.%s\n", wrk->GetUser(), wrk->GetName(), wrk->GetPort(), status, wrk->GetOrdinal(), wrk->GetWorkDir(), addlogext.Data()); } } // Close file fclose(fwrk); // We are done return; } //______________________________________________________________________________ Int_t TProof::GetParameter(TCollection *c, const char *par, TString &value) { // Get the value from the specified parameter from the specified collection. // Returns -1 in case of error (i.e. list is 0, parameter does not exist // or value type does not match), 0 otherwise. TObject *obj = c->FindObject(par); if (obj) { TNamed *p = dynamic_cast<TNamed*>(obj); if (p) { value = p->GetTitle(); return 0; } } return -1; } //______________________________________________________________________________ Int_t TProof::GetParameter(TCollection *c, const char *par, Int_t &value) { // Get the value from the specified parameter from the specified collection. // Returns -1 in case of error (i.e. list is 0, parameter does not exist // or value type does not match), 0 otherwise. TObject *obj = c->FindObject(par); if (obj) { TParameter<Int_t> *p = dynamic_cast<TParameter<Int_t>*>(obj); if (p) { value = p->GetVal(); return 0; } } return -1; } //______________________________________________________________________________ Int_t TProof::GetParameter(TCollection *c, const char *par, Long_t &value) { // Get the value from the specified parameter from the specified collection. // Returns -1 in case of error (i.e. list is 0, parameter does not exist // or value type does not match), 0 otherwise. TObject *obj = c->FindObject(par); if (obj) { TParameter<Long_t> *p = dynamic_cast<TParameter<Long_t>*>(obj); if (p) { value = p->GetVal(); return 0; } } return -1; } //______________________________________________________________________________ Int_t TProof::GetParameter(TCollection *c, const char *par, Long64_t &value) { // Get the value from the specified parameter from the specified collection. // Returns -1 in case of error (i.e. list is 0, parameter does not exist // or value type does not match), 0 otherwise. TObject *obj = c->FindObject(par); if (obj) { TParameter<Long64_t> *p = dynamic_cast<TParameter<Long64_t>*>(obj); if (p) { value = p->GetVal(); return 0; } } return -1; } //______________________________________________________________________________ Int_t TProof::GetParameter(TCollection *c, const char *par, Double_t &value) { // Get the value from the specified parameter from the specified collection. // Returns -1 in case of error (i.e. list is 0, parameter does not exist // or value type does not match), 0 otherwise. TObject *obj = c->FindObject(par); if (obj) { TParameter<Double_t> *p = dynamic_cast<TParameter<Double_t>*>(obj); if (p) { value = p->GetVal(); return 0; } } return -1; } //______________________________________________________________________________ Int_t TProof::AssertDataSet(TDSet *dset, TList *input, TDataSetManager *mgr, TString &emsg) { // Make sure that dataset is in the form to be processed. This may mean // retrieving the relevant info from the dataset manager or from the // attached input list. // Returns 0 on success, -1 on error emsg = ""; // We must have something to process if (!dset || !input || !mgr) { emsg.Form("invalid inputs (%p, %p, %p)", dset, input, mgr); return -1; } TList *datasets = new TList; TFileCollection *dataset = 0; TString lookupopt; TString dsname(dset->GetName()); // The dataset maybe in the form of a TFileCollection in the input list if (dsname.BeginsWith("TFileCollection:")) { // Isolate the real name dsname.ReplaceAll("TFileCollection:", ""); // Get the object dataset = (TFileCollection *) input->FindObject(dsname); if (!dataset) { emsg.Form("TFileCollection %s not found in input list", dset->GetName()); return -1; } // Remove from everywhere input->RecursiveRemove(dataset); // Add it to the local list datasets->Add(new TPair(dataset, new TObjString(""))); // Make sure we lookup everything (unless the client or the administartor // required something else) if (TProof::GetParameter(input, "PROOF_LookupOpt", lookupopt) != 0) { lookupopt = gEnv->GetValue("Proof.LookupOpt", "all"); input->Add(new TNamed("PROOF_LookupOpt", lookupopt.Data())); } } // This is the name we parse for additional specifications, such directory // and object name; for multiple datasets we assume that the directory and // and object name are the same for all datasets TString dsnparse; // The received message included an empty dataset, with only the name // defined: assume that a dataset, stored on the PROOF master by that // name, should be processed. if (!dataset) { TString dsns(dsname.Data()), dsn1; Int_t from1 = 0; while (dsns.Tokenize(dsn1, from1, "[, ]")) { TString dsn2, enl; Int_t from2 = 0; TFileCollection *fc = 0; while (dsn1.Tokenize(dsn2, from2, "|")) { enl = ""; Int_t ienl = dsn2.Index("?enl="); if (ienl != kNPOS) { enl = dsn2(ienl + 5, dsn2.Length()); dsn2.Remove(ienl); } if ((fc = mgr->GetDataSet(dsn2.Data()))) { dsnparse = dsn2; if (!dataset) { // This is our dataset dataset = fc; } else { // Add it to the dataset dataset->Add(fc); SafeDelete(fc); } } } // The dataset name(s) in the first element if (dataset) { if (dataset->GetList()->First()) ((TFileInfo *)(dataset->GetList()->First()))->SetTitle(dsn1.Data()); // Add it to the local list if (enl.IsNull()) { datasets->Add(new TPair(dataset, new TObjString(""))); } else { datasets->Add(new TPair(dataset, new TObjString(enl.Data()))); } } // Reset the pointer dataset = 0; } if (!datasets || datasets->GetSize() <= 0) { emsg.Form("no dataset(s) found on the master corresponding to: %s", dsname.Data()); return -1; } else { // Make 'dataset' to point to the first one in the list if (!(dataset = (TFileCollection *) ((TPair *)(datasets->First()))->Key())) { emsg.Form("dataset pointer is null: corruption? - aborting"); return -1; } } // Apply the lookup option requested by the client or the administartor // (by default we trust the information in the dataset) if (TProof::GetParameter(input, "PROOF_LookupOpt", lookupopt) != 0) { lookupopt = gEnv->GetValue("Proof.LookupOpt", "stagedOnly"); input->Add(new TNamed("PROOF_LookupOpt", lookupopt.Data())); } } else { // We were given a named, single, TFileCollection dsnparse = dsname; } // Logic for the subdir/obj names: try first to see if the dataset name contains // some info; if not check the settings in the TDSet object itself; if still empty // check the default tree name / path in the TFileCollection object; if still empty // use the default as the flow will determine TString dsTree; // Get the [subdir/]tree, if any mgr->ParseUri(dsnparse.Data(), 0, 0, 0, &dsTree); if (dsTree.IsNull()) { // Use what we have in the original dataset; we need this to locate the // meta data information dsTree += dset->GetDirectory(); dsTree += dset->GetObjName(); } if (!dsTree.IsNull() && dsTree != "/") { TString tree(dsTree); Int_t idx = tree.Index("/"); if (idx != kNPOS) { TString dir = tree(0, idx+1); tree.Remove(0, idx); dset->SetDirectory(dir); } dset->SetObjName(tree); } else { // Use the default obj name from the TFileCollection dsTree = dataset->GetDefaultTreeName(); } // Pass dataset server mapping instructions, if any TList *srvmapsref = TDataSetManager::GetDataSetSrvMaps(); TList *srvmapslist = srvmapsref; TString srvmaps; if (TProof::GetParameter(input, "PROOF_DataSetSrvMaps", srvmaps) == 0) { srvmapslist = TDataSetManager::ParseDataSetSrvMaps(srvmaps); if (gProofServ) { TString msg; if (srvmapsref && !srvmapslist) { msg.Form("+++ Info: dataset server mapping(s) DISABLED by user"); } else if (srvmapsref && srvmapslist && srvmapslist != srvmapsref) { msg.Form("+++ Info: dataset server mapping(s) modified by user"); } else if (!srvmapsref && srvmapslist) { msg.Form("+++ Info: dataset server mapping(s) added by user"); } gProofServ->SendAsynMessage(msg.Data()); } } // Flag multi-datasets if (datasets->GetSize() > 1) dset->SetBit(TDSet::kMultiDSet); // Loop over the list of datasets TList *listOfMissingFiles = new TList; TEntryList *entrylist = 0; TPair *pair = 0; TIter nxds(datasets); while ((pair = (TPair *) nxds())) { // File Collection dataset = (TFileCollection *) pair->Key(); // Entry list, if any TEntryList *enl = 0; TObjString *os = (TObjString *) pair->Value(); if (strlen(os->GetName())) { if (!(enl = dynamic_cast<TEntryList *>(input->FindObject(os->GetName())))) { if (gProofServ) gProofServ->SendAsynMessage(TString::Format("+++ Warning:" " entry list %s not found", os->GetName())); } if (enl && (!(enl->GetLists()) || enl->GetLists()->GetSize() <= 0)) { if (gProofServ) gProofServ->SendAsynMessage(TString::Format("+++ Warning:" " no sub-lists in entry-list!")); } } TList *missingFiles = new TList; TSeqCollection* files = dataset->GetList(); if (gDebug > 0) files->Print(); Bool_t availableOnly = (lookupopt != "all") ? kTRUE : kFALSE; if (dset->TestBit(TDSet::kMultiDSet)) { TDSet *ds = new TDSet(dataset->GetName(), dset->GetObjName(), dset->GetDirectory()); ds->SetSrvMaps(srvmapslist); if (!ds->Add(files, dsTree, availableOnly, missingFiles)) { emsg.Form("error integrating dataset %s", dataset->GetName()); continue; } // Add the TDSet object to the multi-dataset dset->Add(ds); // Add entry list if any if (enl) ds->SetEntryList(enl); } else { dset->SetSrvMaps(srvmapslist); if (!dset->Add(files, dsTree, availableOnly, missingFiles)) { emsg.Form("error integrating dataset %s", dataset->GetName()); continue; } if (enl) { if (!entrylist) { entrylist = enl; } else { entrylist->Add(enl); } } } if (missingFiles) { // The missing files objects have to be removed from the dataset // before delete. TIter next(missingFiles); TObject *file; while ((file = next())) { dataset->GetList()->Remove(file); listOfMissingFiles->Add(file); } missingFiles->SetOwner(kFALSE); missingFiles->Clear(); } SafeDelete(missingFiles); } // Cleanup; we need to do this because pairs do no delete their content nxds.Reset(); while ((pair = (TPair *) nxds())) { if (pair->Key()) delete pair->Key(); if (pair->Value()) delete pair->Value(); } datasets->SetOwner(kTRUE); SafeDelete(datasets); // Cleanup the server mapping list, if created by the user if (srvmapslist && srvmapslist != srvmapsref) { srvmapslist->SetOwner(kTRUE); SafeDelete(srvmapslist); } // Set the global entrylist, if required if (entrylist) dset->SetEntryList(entrylist); // Make sure it will be sent back merged with other similar lists created // during processing; this list will be transferred by the player to the // output list, once the latter has been created (see TProofPlayerRemote::Process) if (listOfMissingFiles && listOfMissingFiles->GetSize() > 0) { listOfMissingFiles->SetName("MissingFiles"); input->Add(listOfMissingFiles); } // Done return 0; } //______________________________________________________________________________ Int_t TProof::SaveInputData(TQueryResult *qr, const char *cachedir, TString &emsg) { // Save input data file from 'cachedir' into the sandbox or create a the file // with input data objects TList *input = 0; // We must have got something to process if (!qr || !(input = qr->GetInputList()) || !cachedir || strlen(cachedir) <= 0) return 0; // There must be some input data or input data file TNamed *data = (TNamed *) input->FindObject("PROOF_InputDataFile"); TList *inputdata = (TList *) input->FindObject("PROOF_InputData"); if (!data && !inputdata) return 0; // Default dstination filename if (!data) input->Add((data = new TNamed("PROOF_InputDataFile", kPROOF_InputDataFile))); TString dstname(data->GetTitle()), srcname; Bool_t fromcache = kFALSE; if (dstname.BeginsWith("cache:")) { fromcache = kTRUE; dstname.ReplaceAll("cache:", ""); srcname.Form("%s/%s", cachedir, dstname.Data()); if (gSystem->AccessPathName(srcname)) { emsg.Form("input data file not found in cache (%s)", srcname.Data()); return -1; } } // If from cache, just move the cache file if (fromcache) { if (gSystem->CopyFile(srcname, dstname, kTRUE) != 0) { emsg.Form("problems copying %s to %s", srcname.Data(), dstname.Data()); return -1; } } else { // Create the file if (inputdata && inputdata->GetSize() > 0) { TFile *f = TFile::Open(dstname.Data(), "RECREATE"); if (f) { f->cd(); inputdata->Write(); f->Close(); delete f; } else { emsg.Form("could not create %s", dstname.Data()); return -1; } } else { emsg.Form("no input data!"); return -1; } } ::Info("TProof::SaveInputData", "input data saved to %s", dstname.Data()); // Save the file name and clean up the data list data->SetTitle(dstname); if (inputdata) { input->Remove(inputdata); inputdata->SetOwner(); delete inputdata; } // Done return 0; } //______________________________________________________________________________ Int_t TProof::SendInputData(TQueryResult *qr, TProof *p, TString &emsg) { // Send the input data file to the workers TList *input = 0; // We must have got something to process if (!qr || !(input = qr->GetInputList())) return 0; // There must be some input data or input data file TNamed *inputdata = (TNamed *) input->FindObject("PROOF_InputDataFile"); if (!inputdata) return 0; TString fname(inputdata->GetTitle()); if (gSystem->AccessPathName(fname)) { emsg.Form("input data file not found in sandbox (%s)", fname.Data()); return -1; } // PROOF session must available if (!p || !p->IsValid()) { emsg.Form("TProof object undefined or invalid: protocol error!"); return -1; } // Send to unique workers and submasters p->BroadcastFile(fname, TProof::kBinary, "cache"); // Done return 0; } //______________________________________________________________________________ Int_t TProof::GetInputData(TList *input, const char *cachedir, TString &emsg) { // Get the input data from the file defined in the input list // We must have got something to process if (!input || !cachedir || strlen(cachedir) <= 0) return 0; // There must be some input data or input data file TNamed *inputdata = (TNamed *) input->FindObject("PROOF_InputDataFile"); if (!inputdata) return 0; TString fname; fname.Form("%s/%s", cachedir, inputdata->GetTitle()); if (gSystem->AccessPathName(fname)) { emsg.Form("input data file not found in cache (%s)", fname.Data()); return -1; } // Read the input data into the input list TFile *f = TFile::Open(fname.Data()); if (f) { TList *keys = (TList *) f->GetListOfKeys(); if (!keys) { emsg.Form("could not get list of object keys from file"); return -1; } TIter nxk(keys); TKey *k = 0; while ((k = (TKey *)nxk())) { TObject *o = f->Get(k->GetName()); if (o) input->Add(o); } f->Close(); delete f; } else { emsg.Form("could not open %s", fname.Data()); return -1; } // Done return 0; } //______________________________________________________________________________ void TProof::LogViewer(const char *url, Int_t idx) { // Start the log viewer window usign the plugin manager if (!gROOT->IsBatch()) { // Get the handler, if not yet done if (!fgLogViewer) { if ((fgLogViewer = gROOT->GetPluginManager()->FindHandler("TProofProgressLog"))) { if (fgLogViewer->LoadPlugin() == -1) { fgLogViewer = 0; ::Error("TProof::LogViewer", "cannot load the relevant plug-in"); return; } } } if (fgLogViewer) { // Execute the plug-in TString u = (url && strlen(url) <= 0) ? "lite" : url; fgLogViewer->ExecPlugin(2, u.Data(), idx); } } else { if (url && strlen(url) > 0) { ::Info("TProof::LogViewer", "batch mode: use TProofLog *pl = TProof::Mgr(\"%s\")->GetSessionLogs(%d)", url, idx); } else if (url && strlen(url) <= 0) { ::Info("TProof::LogViewer", "batch mode: use TProofLog *pl = TProof::Mgr(\"lite\")->GetSessionLogs(%d)", idx); } else { ::Info("TProof::LogViewer", "batch mode: use TProofLog *pl = TProof::Mgr(\"<master>\")->GetSessionLogs(%d)", idx); } } // Done return; } //______________________________________________________________________________ void TProof::SetProgressDialog(Bool_t on) { // Enable/Disable the graphic progress dialog. // By default the dialog is enabled if (on) SetBit(kUseProgressDialog); else ResetBit(kUseProgressDialog); } set macro path only when it has been changed. git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@33635 27541ba8-7e3a-0410-8455-c3a389f83636 // @(#)root/proof:$Id$ // Author: Fons Rademakers 13/02/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TProof // // // // This class controls a Parallel ROOT Facility, PROOF, cluster. // // It fires the worker servers, it keeps track of how many workers are // // running, it keeps track of the workers running status, it broadcasts // // messages to all workers, it collects results, etc. // // // ////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <fcntl.h> #include <errno.h> #ifdef WIN32 # include <io.h> # include <sys/stat.h> # include <sys/types.h> # include "snprintf.h" #else # include <unistd.h> #endif #include <vector> #include "RConfigure.h" #include "Riostream.h" #include "Getline.h" #include "TBrowser.h" #include "TChain.h" #include "TCondor.h" #include "TDSet.h" #include "TError.h" #include "TEnv.h" #include "TEntryList.h" #include "TEventList.h" #include "TFile.h" #include "TFileInfo.h" #include "TFTP.h" #include "THashList.h" #include "TInterpreter.h" #include "TKey.h" #include "TMap.h" #include "TMath.h" #include "TMessage.h" #include "TMonitor.h" #include "TMutex.h" #include "TObjArray.h" #include "TObjString.h" #include "TParameter.h" #include "TProof.h" #include "TProofNodeInfo.h" #include "TVirtualProofPlayer.h" #include "TVirtualPacketizer.h" #include "TProofServ.h" #include "TPluginManager.h" #include "TQueryResult.h" #include "TRandom.h" #include "TRegexp.h" #include "TROOT.h" #include "TSemaphore.h" #include "TSlave.h" #include "TSocket.h" #include "TSortedList.h" #include "TSystem.h" #include "TThread.h" #include "TTree.h" #include "TUrl.h" #include "TFileCollection.h" #include "TDataSetManager.h" #include "TMacro.h" TProof *gProof = 0; TVirtualMutex *gProofMutex = 0; // Rotating indicator char TProofMergePrg::fgCr[4] = {'-', '\\', '|', '/'}; TList *TProof::fgProofEnvList = 0; // List of env vars for proofserv TPluginHandler *TProof::fgLogViewer = 0; // Log viewer handler ClassImp(TProof) //----- PROOF Interrupt signal handler ----------------------------------------- //______________________________________________________________________________ Bool_t TProofInterruptHandler::Notify() { // TProof interrupt handler. if (isatty(0) == 0 || isatty(1) == 0 || fProof->GetRemoteProtocol() < 22) { // Cannot ask the user : abort any remote processing fProof->StopProcess(kTRUE); } else { // Real stop or request to switch to asynchronous? char *a = 0; if (fProof->GetRemoteProtocol() < 22) { a = Getline("\nSwith to asynchronous mode not supported remotely:" "\nEnter S/s to stop, Q/q to quit, any other key to continue: "); } else { a = Getline("\nEnter A/a to switch asynchronous, S/s to stop, Q/q to quit," " any other key to continue: "); } if (a[0] == 'Q' || a[0] == 'S' || a[0] == 'q' || a[0] == 's') { Info("Notify","Processing interrupt signal ... %c", a[0]); // Stop or abort any remote processing Bool_t abort = (a[0] == 'Q' || a[0] == 'q') ? kTRUE : kFALSE; fProof->StopProcess(abort); } else if ((a[0] == 'A' || a[0] == 'a') && fProof->GetRemoteProtocol() >= 22) { // Stop any remote processing fProof->GoAsynchronous(); } } return kTRUE; } //----- Input handler for messages from TProofServ ----------------------------- //______________________________________________________________________________ TProofInputHandler::TProofInputHandler(TProof *p, TSocket *s) : TFileHandler(s->GetDescriptor(),1), fSocket(s), fProof(p) { // Constructor } //______________________________________________________________________________ Bool_t TProofInputHandler::Notify() { // Handle input fProof->CollectInputFrom(fSocket); return kTRUE; } //------------------------------------------------------------------------------ ClassImp(TSlaveInfo) //______________________________________________________________________________ Int_t TSlaveInfo::Compare(const TObject *obj) const { // Used to sort slaveinfos by ordinal. if (!obj) return 1; const TSlaveInfo *si = dynamic_cast<const TSlaveInfo*>(obj); if (!si) return fOrdinal.CompareTo(obj->GetName()); const char *myord = GetOrdinal(); const char *otherord = si->GetOrdinal(); while (myord && otherord) { Int_t myval = atoi(myord); Int_t otherval = atoi(otherord); if (myval < otherval) return 1; if (myval > otherval) return -1; myord = strchr(myord, '.'); if (myord) myord++; otherord = strchr(otherord, '.'); if (otherord) otherord++; } if (myord) return -1; if (otherord) return 1; return 0; } //______________________________________________________________________________ void TSlaveInfo::Print(Option_t *opt) const { // Print slave info. If opt = "active" print only the active // slaves, if opt="notactive" print only the not active slaves, // if opt = "bad" print only the bad slaves, else // print all slaves. TString stat = fStatus == kActive ? "active" : fStatus == kBad ? "bad" : "not active"; Bool_t newfmt = kFALSE; TString oo(opt); if (oo.Contains("N")) { newfmt = kTRUE; oo.ReplaceAll("N",""); } if (oo == "active" && fStatus != kActive) return; if (oo == "notactive" && fStatus != kNotActive) return; if (oo == "bad" && fStatus != kBad) return; if (newfmt) { TString msd, si; if (!(fMsd.IsNull())) msd.Form("| msd: %s ", fMsd.Data()); if (fSysInfo.fCpus > 0) { si.Form("| %s, %d cores, %d MB ram", fHostName.Data(), fSysInfo.fCpus, fSysInfo.fPhysRam); } else { si.Form("| %s", fHostName.Data()); } Printf("Worker: %9s %s %s| %s", fOrdinal.Data(), si.Data(), msd.Data(), stat.Data()); } else { TString msd = fMsd.IsNull() ? "<null>" : fMsd.Data(); cout << "Slave: " << fOrdinal << " hostname: " << fHostName << " msd: " << msd << " perf index: " << fPerfIndex << " " << stat << endl; } } //______________________________________________________________________________ void TSlaveInfo::SetSysInfo(SysInfo_t si) { // Setter for fSysInfo fSysInfo.fOS = si.fOS; // OS fSysInfo.fModel = si.fModel; // computer model fSysInfo.fCpuType = si.fCpuType; // type of cpu fSysInfo.fCpus = si.fCpus; // number of cpus fSysInfo.fCpuSpeed = si.fCpuSpeed; // cpu speed in MHz fSysInfo.fBusSpeed = si.fBusSpeed; // bus speed in MHz fSysInfo.fL2Cache = si.fL2Cache; // level 2 cache size in KB fSysInfo.fPhysRam = si.fPhysRam; // Physical RAM } //------------------------------------------------------------------------------ //______________________________________________________________________________ static char *CollapseSlashesInPath(const char *path) { // Get rid of spare slashes in a path. Returned path must be deleted[] // by the user. if (path) { Int_t i = 1; // current index as we go along the string Int_t j = 0; // current end of new path in newPath char *newPath = new char [strlen(path) + 1]; newPath[0] = path[0]; while (path[i]) { if (path[i] != '/' || newPath[j] != '/') { j++; newPath[j] = path[i]; } i++; } if (newPath[j] != '/') j++; newPath[j] = 0; // We have to terminate the new path. return newPath; } return 0; } ClassImp(TProof) TSemaphore *TProof::fgSemaphore = 0; //------------------------------------------------------------------------------ //______________________________________________________________________________ TMergerInfo::~TMergerInfo() { // Destructor // Just delete the list, the objects are owned by other list if (fWorkers) { fWorkers->SetOwner(kFALSE); SafeDelete(fWorkers); } } //______________________________________________________________________________ void TMergerInfo::SetMergedWorker() { // Increase number of already merged workers by 1 if (AreAllWorkersMerged()) Error("SetMergedWorker", "all workers have been already merged before!"); else fMergedWorkers++; } //______________________________________________________________________________ void TMergerInfo::AddWorker(TSlave *sl) { // Add new worker to the list of workers to be merged by this merger if (!fWorkers) fWorkers = new TList(); if (fWorkersToMerge == fWorkers->GetSize()) { Error("AddWorker", "all workers have been already assigned to this merger"); return; } fWorkers->Add(sl); } //______________________________________________________________________________ Bool_t TMergerInfo::AreAllWorkersMerged() { // Return if merger has already merged all workers, i.e. if it has finished its merging job return (fWorkersToMerge == fMergedWorkers); } //______________________________________________________________________________ Bool_t TMergerInfo::AreAllWorkersAssigned() { // Return if the determined number of workers has been already assigned to this merger if (!fWorkers) return kFALSE; return (fWorkers->GetSize() == fWorkersToMerge); } //------------------------------------------------------------------------------ TProof::TProof(const char *masterurl, const char *conffile, const char *confdir, Int_t loglevel, const char *alias, TProofMgr *mgr) : fUrl(masterurl) { // Create a PROOF environment. Starting PROOF involves either connecting // to a master server, which in turn will start a set of slave servers, or // directly starting as master server (if master = ""). Masterurl is of // the form: [proof[s]://]host[:port]. Conffile is the name of the config // file describing the remote PROOF cluster (this argument alows you to // describe different cluster configurations). // The default is proof.conf. Confdir is the directory where the config // file and other PROOF related files are (like motd and noproof files). // Loglevel is the log level (default = 1). User specified custom config // files will be first looked for in $HOME/.conffile. // Default initializations InitMembers(); // This may be needed during init fManager = mgr; // Default server type fServType = TProofMgr::kXProofd; // Default query mode fQueryMode = kSync; // Parse the main URL, adjusting the missing fields and setting the relevant // bits ResetBit(TProof::kIsClient); ResetBit(TProof::kIsMaster); // Protocol and Host if (!masterurl || strlen(masterurl) <= 0) { fUrl.SetProtocol("proof"); fUrl.SetHost("__master__"); } else if (!(strstr(masterurl, "://"))) { fUrl.SetProtocol("proof"); } // Port if (fUrl.GetPort() == TUrl(" ").GetPort()) fUrl.SetPort(TUrl("proof:// ").GetPort()); // User if (strlen(fUrl.GetUser()) <= 0) { // Get user logon name UserGroup_t *pw = gSystem->GetUserInfo(); if (pw) { fUrl.SetUser(pw->fUser); delete pw; } } // Make sure to store the FQDN, so to get a solid reference for subsequent checks if (!strcmp(fUrl.GetHost(), "__master__")) fMaster = fUrl.GetHost(); else if (!strlen(fUrl.GetHost())) fMaster = gSystem->GetHostByName(gSystem->HostName()).GetHostName(); else fMaster = gSystem->GetHostByName(fUrl.GetHost()).GetHostName(); // Server type if (strlen(fUrl.GetOptions()) > 0) { TString opts(fUrl.GetOptions()); if (!(strncmp(fUrl.GetOptions(),"std",3))) { fServType = TProofMgr::kProofd; opts.Remove(0,3); fUrl.SetOptions(opts.Data()); } else if (!(strncmp(fUrl.GetOptions(),"lite",4))) { fServType = TProofMgr::kProofLite; opts.Remove(0,4); fUrl.SetOptions(opts.Data()); } } // Instance type fMasterServ = kFALSE; SetBit(TProof::kIsClient); ResetBit(TProof::kIsMaster); if (fMaster == "__master__") { fMasterServ = kTRUE; ResetBit(TProof::kIsClient); SetBit(TProof::kIsMaster); } else if (fMaster == "prooflite") { // Client and master are merged fMasterServ = kTRUE; SetBit(TProof::kIsMaster); } Init(masterurl, conffile, confdir, loglevel, alias); // If called by a manager, make sure it stays in last position // for cleaning if (mgr) { R__LOCKGUARD2(gROOTMutex); gROOT->GetListOfSockets()->Remove(mgr); gROOT->GetListOfSockets()->Add(mgr); } // Old-style server type: we add this to the list and set the global pointer if (IsProofd() || TestBit(TProof::kIsMaster)) if (!gROOT->GetListOfProofs()->FindObject(this)) gROOT->GetListOfProofs()->Add(this); // Still needed by the packetizers: needs to be changed gProof = this; } //______________________________________________________________________________ TProof::TProof() : fUrl(""), fServType(TProofMgr::kXProofd) { // Protected constructor to be used by classes deriving from TProof // (they have to call Init themselves and override StartSlaves // appropriately). // // This constructor simply closes any previous gProof and sets gProof // to this instance. // Default initializations InitMembers(); if (!gROOT->GetListOfProofs()->FindObject(this)) gROOT->GetListOfProofs()->Add(this); gProof = this; } //______________________________________________________________________________ void TProof::InitMembers() { // Default initializations fValid = kFALSE; fRecvMessages = 0; fSlaveInfo = 0; fMasterServ = kFALSE; fSendGroupView = kFALSE; fActiveSlaves = 0; fInactiveSlaves = 0; fUniqueSlaves = 0; fAllUniqueSlaves = 0; fNonUniqueMasters = 0; fActiveMonitor = 0; fUniqueMonitor = 0; fAllUniqueMonitor = 0; fCurrentMonitor = 0; fBytesRead = 0; fRealTime = 0; fCpuTime = 0; fIntHandler = 0; fProgressDialog = 0; fProgressDialogStarted = kFALSE; SetBit(kUseProgressDialog); fPlayer = 0; fFeedback = 0; fChains = 0; fDSet = 0; fNotIdle = 0; fSync = kTRUE; fRunStatus = kRunning; fIsWaiting = kFALSE; fRedirLog = kFALSE; fLogFileW = 0; fLogFileR = 0; fLogToWindowOnly = kFALSE; fWaitingSlaves = 0; fQueries = 0; fOtherQueries = 0; fDrawQueries = 0; fMaxDrawQueries = 1; fSeqNum = 0; fSessionID = -1; fEndMaster = kFALSE; fGlobalPackageDirList = 0; fPackageLock = 0; fEnabledPackagesOnClient = 0; fInputData = 0; fPrintProgress = 0; fLoadedMacros = 0; fProtocol = -1; fSlaves = 0; fBadSlaves = 0; fAllMonitor = 0; fDataReady = kFALSE; fBytesReady = 0; fTotalBytes = 0; fAvailablePackages = 0; fEnabledPackages = 0; fRunningDSets = 0; fCollectTimeout = -1; fManager = 0; fQueryMode = kSync; fDynamicStartup = kFALSE; fCloseMutex = 0; fMergersSet = kFALSE; fMergers = 0; fMergersCount = -1; fLastAssignedMerger = 0; fWorkersToMerge = 0; fFinalizationRunning = kFALSE; // Done return; } //______________________________________________________________________________ TProof::~TProof() { // Clean up PROOF environment. if (fChains) { while (TChain *chain = dynamic_cast<TChain*> (fChains->First()) ) { // remove "chain" from list chain->SetProof(0); RemoveChain(chain); } } // remove links to packages enabled on the client if (TestBit(TProof::kIsClient)) { // iterate over all packages TIter nextpackage(fEnabledPackagesOnClient); while (TObjString *package = dynamic_cast<TObjString*>(nextpackage())) { FileStat_t stat; gSystem->GetPathInfo(package->String(), stat); // check if symlink, if so unlink // NOTE: GetPathInfo() returns 1 in case of symlink that does not point to // existing file or to a directory, but if fIsLink is true the symlink exists if (stat.fIsLink) gSystem->Unlink(package->String()); } } Close(); SafeDelete(fIntHandler); SafeDelete(fSlaves); SafeDelete(fActiveSlaves); SafeDelete(fInactiveSlaves); SafeDelete(fUniqueSlaves); SafeDelete(fAllUniqueSlaves); SafeDelete(fNonUniqueMasters); SafeDelete(fBadSlaves); SafeDelete(fAllMonitor); SafeDelete(fActiveMonitor); SafeDelete(fUniqueMonitor); SafeDelete(fAllUniqueMonitor); SafeDelete(fSlaveInfo); SafeDelete(fChains); SafeDelete(fPlayer); SafeDelete(fFeedback); SafeDelete(fWaitingSlaves); SafeDelete(fAvailablePackages); SafeDelete(fEnabledPackages); SafeDelete(fEnabledPackagesOnClient); SafeDelete(fLoadedMacros); SafeDelete(fPackageLock); SafeDelete(fGlobalPackageDirList); SafeDelete(fRecvMessages); SafeDelete(fInputData); SafeDelete(fRunningDSets); SafeDelete(fCloseMutex); // remove file with redirected logs if (TestBit(TProof::kIsClient)) { if (fLogFileR) fclose(fLogFileR); if (fLogFileW) fclose(fLogFileW); if (fLogFileName.Length() > 0) gSystem->Unlink(fLogFileName); } // Remove for the global list gROOT->GetListOfProofs()->Remove(this); // ... and from the manager list if (fManager && fManager->IsValid()) fManager->DiscardSession(this); if (gProof && gProof == this) { // Set previous as default TIter pvp(gROOT->GetListOfProofs(), kIterBackward); while ((gProof = (TProof *)pvp())) { if (gProof->InheritsFrom(TProof::Class())) break; } } // For those interested in our destruction ... Emit("~TProof()"); } //______________________________________________________________________________ Int_t TProof::Init(const char *, const char *conffile, const char *confdir, Int_t loglevel, const char *alias) { // Start the PROOF environment. Starting PROOF involves either connecting // to a master server, which in turn will start a set of slave servers, or // directly starting as master server (if master = ""). For a description // of the arguments see the TProof ctor. Returns the number of started // master or slave servers, returns 0 in case of error, in which case // fValid remains false. R__ASSERT(gSystem); fValid = kFALSE; // If in attach mode, options is filled with additional info Bool_t attach = kFALSE; if (strlen(fUrl.GetOptions()) > 0) { attach = kTRUE; // A flag from the GUI TString opts = fUrl.GetOptions(); if (opts.Contains("GUI")) { SetBit(TProof::kUsingSessionGui); opts.Remove(opts.Index("GUI")); fUrl.SetOptions(opts); } } if (TestBit(TProof::kIsMaster)) { // Fill default conf file and conf dir if (!conffile || strlen(conffile) == 0) fConfFile = kPROOF_ConfFile; if (!confdir || strlen(confdir) == 0) fConfDir = kPROOF_ConfDir; // The group; the client receives it in the kPROOF_SESSIONTAG message if (gProofServ) fGroup = gProofServ->GetGroup(); } else { fConfDir = confdir; fConfFile = conffile; } // Analysise the conffile field ParseConfigField(fConfFile); fWorkDir = gSystem->WorkingDirectory(); fLogLevel = loglevel; fProtocol = kPROOF_Protocol; fSendGroupView = kTRUE; fImage = fMasterServ ? "" : "<local>"; fIntHandler = 0; fStatus = 0; fRecvMessages = new TList; fRecvMessages->SetOwner(kTRUE); fSlaveInfo = 0; fChains = new TList; fAvailablePackages = 0; fEnabledPackages = 0; fRunningDSets = 0; fEndMaster = TestBit(TProof::kIsMaster) ? kTRUE : kFALSE; fInputData = 0; ResetBit(TProof::kNewInputData); fPrintProgress = 0; // Timeout for some collect actions fCollectTimeout = gEnv->GetValue("Proof.CollectTimeout", -1); // Should the workers be started dynamically; default: no fDynamicStartup = gEnv->GetValue("Proof.DynamicStartup", kFALSE); // Default entry point for the data pool is the master if (TestBit(TProof::kIsClient)) fDataPoolUrl.Form("root://%s", fMaster.Data()); else fDataPoolUrl = ""; fProgressDialog = 0; fProgressDialogStarted = kFALSE; // Default alias is the master name TString al = (alias) ? alias : fMaster.Data(); SetAlias(al); // Client logging of messages from the master and slaves fRedirLog = kFALSE; if (TestBit(TProof::kIsClient)) { fLogFileName.Form("%s/ProofLog_%d", gSystem->TempDirectory(), gSystem->GetPid()); if ((fLogFileW = fopen(fLogFileName, "w")) == 0) Error("Init", "could not create temporary logfile"); if ((fLogFileR = fopen(fLogFileName, "r")) == 0) Error("Init", "could not open temp logfile for reading"); } fLogToWindowOnly = kFALSE; // Status of cluster fNotIdle = 0; // Query type fSync = (attach) ? kFALSE : kTRUE; // Not enqueued fIsWaiting = kFALSE; // Counters fBytesRead = 0; fRealTime = 0; fCpuTime = 0; // List of queries fQueries = 0; fOtherQueries = 0; fDrawQueries = 0; fMaxDrawQueries = 1; fSeqNum = 0; // Remote ID of the session fSessionID = -1; // Part of active query fWaitingSlaves = 0; // Make remote PROOF player fPlayer = 0; MakePlayer(); fFeedback = new TList; fFeedback->SetOwner(); fFeedback->SetName("FeedbackList"); AddInput(fFeedback); // sort slaves by descending performance index fSlaves = new TSortedList(kSortDescending); fActiveSlaves = new TList; fInactiveSlaves = new TList; fUniqueSlaves = new TList; fAllUniqueSlaves = new TList; fNonUniqueMasters = new TList; fBadSlaves = new TList; fAllMonitor = new TMonitor; fActiveMonitor = new TMonitor; fUniqueMonitor = new TMonitor; fAllUniqueMonitor = new TMonitor; fCurrentMonitor = 0; fPackageLock = 0; fEnabledPackagesOnClient = 0; fLoadedMacros = 0; fGlobalPackageDirList = 0; // Enable optimized sending of streamer infos to use embedded backward/forward // compatibility support between different ROOT versions and different versions of // users classes Bool_t enableSchemaEvolution = gEnv->GetValue("Proof.SchemaEvolution",1); if (enableSchemaEvolution) { TMessage::EnableSchemaEvolutionForAll(); } else { Info("TProof", "automatic schema evolution in TMessage explicitely disabled"); } if (IsMaster()) { // to make UploadPackage() method work on the master as well. fPackageDir = gProofServ->GetPackageDir(); } else { TString sandbox = gEnv->GetValue("Proof.Sandbox", ""); if (sandbox.IsNull()) { sandbox.Form("~/%s", kPROOF_WorkDir); } gSystem->ExpandPathName(sandbox); if (AssertPath(sandbox, kTRUE) != 0) { Error("Init", "failure asserting directory %s", sandbox.Data()); return 0; } // Package Dir fPackageDir = gEnv->GetValue("Proof.PackageDir", ""); if (fPackageDir.IsNull()) fPackageDir.Form("%s/%s", sandbox.Data(), kPROOF_PackDir); if (AssertPath(fPackageDir, kTRUE) != 0) { Error("Init", "failure asserting directory %s", fPackageDir.Data()); return 0; } } if (!IsMaster()) { // List of directories where to look for global packages TString globpack = gEnv->GetValue("Proof.GlobalPackageDirs",""); if (globpack.Length() > 0) { Int_t ng = 0; Int_t from = 0; TString ldir; while (globpack.Tokenize(ldir, from, ":")) { if (gSystem->AccessPathName(ldir, kReadPermission)) { Warning("Init", "directory for global packages %s does not" " exist or is not readable", ldir.Data()); } else { // Add to the list, key will be "G<ng>", i.e. "G0", "G1", ... TString key = Form("G%d", ng++); if (!fGlobalPackageDirList) { fGlobalPackageDirList = new THashList(); fGlobalPackageDirList->SetOwner(); } fGlobalPackageDirList->Add(new TNamed(key,ldir)); } } } TString lockpath(fPackageDir); lockpath.ReplaceAll("/", "%"); lockpath.Insert(0, Form("%s/%s", gSystem->TempDirectory(), kPROOF_PackageLockFile)); fPackageLock = new TProofLockPath(lockpath.Data()); fEnabledPackagesOnClient = new TList; fEnabledPackagesOnClient->SetOwner(); } // Master may want dynamic startup if (fDynamicStartup) { if (!IsMaster()) { // If on client - start the master if (!StartSlaves(attach)) return 0; } } else { // Master Only mode (for operations requiring only the master, e.g. dataset browsing, // result retrieving, ...) Bool_t masterOnly = gEnv->GetValue("Proof.MasterOnly", kFALSE); if (!IsMaster() || !masterOnly) { // Start slaves (the old, static, per-session way) if (!StartSlaves(attach)) return 0; } } if (fgSemaphore) SafeDelete(fgSemaphore); // we are now properly initialized fValid = kTRUE; // De-activate monitor (will be activated in Collect) fAllMonitor->DeActivateAll(); // By default go into parallel mode GoParallel(9999, attach); // Send relevant initial state to slaves if (!attach) SendInitialState(); else if (!IsIdle()) // redirect log fRedirLog = kTRUE; // Done at this point, the alias will be communicated to the coordinator, if any if (TestBit(TProof::kIsClient)) SetAlias(al); SetActive(kFALSE); if (IsValid()) { // Activate input handler ActivateAsyncInput(); R__LOCKGUARD2(gROOTMutex); gROOT->GetListOfSockets()->Add(this); } return fActiveSlaves->GetSize(); } //______________________________________________________________________________ void TProof::ParseConfigField(const char *config) { // The config file field may contain special instructions which need to be // parsed at the beginning, e.g. for debug runs with valgrind. TString sconf(config); // Analysise the field const char *cq = (IsLite()) ? "\"" : ""; Int_t ivg = kNPOS; if ((ivg = sconf.Index("valgrind")) != kNPOS) { Int_t jvg = sconf.Index(',', ivg); Int_t lvg = (jvg != kNPOS) ? (jvg-ivg) : sconf.Length(); TString vgconf = sconf(ivg, lvg); // Any existing valgrind setting? User can give full settings, which we fully respect, // or pass additional options for valgrind by prefixing 'valgrind_opts:'. For example, // TProof::AddEnvVar("PROOF_MASTER_WRAPPERCMD", "valgrind_opts:--time-stamp --leak-check=full" // will add option "--time-stamp --leak-check=full" to our default options TString mst, wrk, all; TList *envs = fgProofEnvList; TNamed *n = 0; if (envs) { if ((n = (TNamed *) envs->FindObject("PROOF_WRAPPERCMD"))) all = n->GetTitle(); if ((n = (TNamed *) envs->FindObject("PROOF_MASTER_WRAPPERCMD"))) mst = n->GetTitle(); if ((n = (TNamed *) envs->FindObject("PROOF_SLAVE_WRAPPERCMD"))) wrk = n->GetTitle(); } if (all != "" && mst == "") mst = all; if (all != "" && wrk == "") wrk = all; if (all != "" && all.BeginsWith("valgrind_opts:")) { // The field is used to add an option Reset the setting Info("ParseConfigField","valgrind run: resetting 'PROOF_WRAPPERCMD':" " must be set again for next run , if any"); TProof::DelEnvVar("PROOF_WRAPPERCMD"); } TString var, cmd; cmd.Form("%svalgrind -v --suppressions=<rootsys>/etc/valgrind-root.supp", cq); TString mstlab("NO"), wrklab("NO"); if (vgconf == "valgrind" || vgconf.Contains("master")) { if (!IsLite()) { // Check if we have to add a var if (mst == "" || mst.BeginsWith("valgrind_opts:")) { mst.ReplaceAll("valgrind_opts:",""); var.Form("%s --log-file=<logfilemst>.valgrind.log %s", cmd.Data(), mst.Data()); TProof::AddEnvVar("PROOF_MASTER_WRAPPERCMD", var); mstlab = "YES"; } else if (mst != "") { mstlab = "YES"; } } else { if (vgconf.Contains("master")) { Warning("ParseConfigField", "master valgrinding does not make sense for PROOF-Lite: ignoring"); vgconf.ReplaceAll("master", ""); if (!vgconf.Contains("workers")) return; } if (vgconf == "valgrind" || vgconf == "valgrind=") vgconf = "valgrind=workers"; } } if (vgconf.Contains("=workers") || vgconf.Contains("+workers")) { // Check if we have to add a var if (wrk == "" || wrk.BeginsWith("valgrind_opts:")) { wrk.ReplaceAll("valgrind_opts:",""); var.Form("%s --log-file=<logfilewrk>.valgrind.log %s%s", cmd.Data(), wrk.Data(), cq); TProof::AddEnvVar("PROOF_SLAVE_WRAPPERCMD", var); TString nwrks("2"); Int_t inw = vgconf.Index('#'); if (inw != kNPOS) { nwrks = vgconf(inw+1, vgconf.Length()); if (!nwrks.IsDigit()) nwrks = "2"; } // Set the relevant variables if (!IsLite()) { TProof::AddEnvVar("PROOF_NWORKERS", nwrks); } else { gEnv->SetValue("ProofLite.Workers", nwrks.Atoi()); } wrklab = nwrks; // Register the additional worker log in the session file // (for the master is done automatically) TProof::AddEnvVar("PROOF_ADDITIONALLOG", "valgrind.log*"); } else if (wrk != "") { wrklab = "ALL"; } } // Increase the relevant timeouts if (!IsLite()) { TProof::AddEnvVar("PROOF_INTWAIT", "5000"); gEnv->SetValue("Proof.SocketActivityTimeout", 6000); } else { gEnv->SetValue("ProofLite.StartupTimeOut", 5000); } // Warn for slowness Printf(" "); if (!IsLite()) { Printf(" ---> Starting a debug run with valgrind (master:%s, workers:%s)", mstlab.Data(), wrklab.Data()); } else { Printf(" ---> Starting a debug run with valgrind (workers:%s)", wrklab.Data()); } Printf(" ---> Please be patient: startup may be VERY slow ..."); Printf(" ---> Logs will be available as special tags in the log window (from the progress dialog or TProof::LogViewer()) "); Printf(" ---> (Reminder: this debug run makes sense only if you are running a debug version of ROOT)"); Printf(" "); } else if (sconf.BeginsWith("workers=")) { // Request for a given number of workers (within the max) or worker // startup combination: // workers=5 start max 5 workers (or less, if less are assigned) // workers=2x start max 2 workers (or less, if less are assigned) sconf.ReplaceAll("workers=",""); TProof::AddEnvVar("PROOF_NWORKERS", sconf); } } //______________________________________________________________________________ Int_t TProof::AssertPath(const char *inpath, Bool_t writable) { // Make sure that 'path' exists; if 'writable' is kTRUE, make also sure // that the path is writable if (!inpath || strlen(inpath) <= 0) { Error("AssertPath", "undefined input path"); return -1; } TString path(inpath); gSystem->ExpandPathName(path); if (gSystem->AccessPathName(path, kFileExists)) { if (gSystem->mkdir(path, kTRUE) != 0) { Error("AssertPath", "could not create path %s", path.Data()); return -1; } } // It must be writable if (gSystem->AccessPathName(path, kWritePermission) && writable) { if (gSystem->Chmod(path, 0666) != 0) { Error("AssertPath", "could not make path %s writable", path.Data()); return -1; } } // Done return 0; } //______________________________________________________________________________ void TProof::SetManager(TProofMgr *mgr) { // Set manager and schedule its destruction after this for clean // operations. fManager = mgr; if (mgr) { R__LOCKGUARD2(gROOTMutex); gROOT->GetListOfSockets()->Remove(mgr); gROOT->GetListOfSockets()->Add(mgr); } } //______________________________________________________________________________ Int_t TProof::AddWorkers(TList *workerList) { // Works on the master node only. // It starts workers on the machines in workerList and sets the paths, // packages and macros as on the master. // It is a subbstitute for StartSlaves(...) // The code is mostly the master part of StartSlaves, // with the parallel startup removed. if (!IsMaster()) { Error("AddWorkers", "AddWorkers can only be called on the master!"); return -1; } if (!workerList || !(workerList->GetSize())) { Error("AddWorkers", "The list of workers should not be empty; NULL: %d", workerList == 0); return -2; } // Code taken from master part of StartSlaves with the parllel part removed fImage = gProofServ->GetImage(); if (fImage.IsNull()) fImage = Form("%s:%s", TUrl(gSystem->HostName()).GetHostFQDN(), gProofServ->GetWorkDir()); // Get all workers UInt_t nSlaves = workerList->GetSize(); UInt_t nSlavesDone = 0; Int_t ord = 0; // Loop over all workers and start them // a list of TSlave objects for workers that are being added TList *addedWorkers = new TList(); addedWorkers->SetOwner(kFALSE); TListIter next(workerList); TObject *to; TProofNodeInfo *worker; while ((to = next())) { // Get the next worker from the list worker = (TProofNodeInfo *)to; // Read back worker node info const Char_t *image = worker->GetImage().Data(); const Char_t *workdir = worker->GetWorkDir().Data(); Int_t perfidx = worker->GetPerfIndex(); Int_t sport = worker->GetPort(); if (sport == -1) sport = fUrl.GetPort(); // create slave server TString fullord; if (worker->GetOrdinal().Length() > 0) { fullord.Form("%s.%s", gProofServ->GetOrdinal(), worker->GetOrdinal().Data()); } else { fullord.Form("%s.%d", gProofServ->GetOrdinal(), ord); } // create slave server TUrl u(Form("%s:%d",worker->GetNodeName().Data(), sport)); // Add group info in the password firdl, if any if (strlen(gProofServ->GetGroup()) > 0) { // Set also the user, otherwise the password is not exported if (strlen(u.GetUser()) <= 0) u.SetUser(gProofServ->GetUser()); u.SetPasswd(gProofServ->GetGroup()); } TSlave *slave = CreateSlave(u.GetUrl(), fullord, perfidx, image, workdir); // Add to global list (we will add to the monitor list after // finalizing the server startup) Bool_t slaveOk = kTRUE; if (slave->IsValid()) { fSlaves->Add(slave); addedWorkers->Add(slave); } else { slaveOk = kFALSE; fBadSlaves->Add(slave); } PDB(kGlobal,3) Info("StartSlaves", "worker on host %s created" " and added to list", worker->GetNodeName().Data()); // Notify opening of connection nSlavesDone++; TMessage m(kPROOF_SERVERSTARTED); m << TString("Opening connections to workers") << nSlaves << nSlavesDone << slaveOk; gProofServ->GetSocket()->Send(m); ord++; } //end of the worker loop // Cleanup SafeDelete(workerList); nSlavesDone = 0; // Here we finalize the server startup: in this way the bulk // of remote operations are almost parallelized TIter nxsl(addedWorkers); TSlave *sl = 0; while ((sl = (TSlave *) nxsl())) { // Finalize setup of the server if (sl->IsValid()) sl->SetupServ(TSlave::kSlave, 0); // Monitor good slaves Bool_t slaveOk = kTRUE; if (sl->IsValid()) { fAllMonitor->Add(sl->GetSocket()); } else { slaveOk = kFALSE; fBadSlaves->Add(sl); } // Notify end of startup operations nSlavesDone++; TMessage m(kPROOF_SERVERSTARTED); m << TString("Setting up worker servers") << nSlaves << nSlavesDone << slaveOk; gProofServ->GetSocket()->Send(m); } // Now set new state on the added workers (on all workers for simplicity) // use fEnabledPackages, fLoadedMacros, // gSystem->GetDynamicPath() and gSystem->GetIncludePath() // no need to load packages that are only loaded and not enabled (dyn mode) SetParallel(99999, 0); TList *tmpEnabledPackages = gProofServ->GetEnabledPackages(); if (tmpEnabledPackages && tmpEnabledPackages->GetSize() > 0) { TIter nxp(tmpEnabledPackages); TObjString *os = 0; while ((os = (TObjString *) nxp())) { // Upload and Enable methods are intelligent and avoid // re-uploading or re-enabling of a package to a node that has it. UploadPackage(os->GetName()); EnablePackage(os->GetName(), kTRUE); } } if (fLoadedMacros) { TIter nxp(fLoadedMacros); TObjString *os = 0; while ((os = (TObjString *) nxp())) { Printf("Loading a macro : %s", os->GetName()); Load(os->GetName(), kTRUE, kTRUE, addedWorkers); } } TString dyn = gSystem->GetDynamicPath(); dyn.ReplaceAll(":", " "); dyn.ReplaceAll("\"", " "); AddDynamicPath(dyn, addedWorkers); TString inc = gSystem->GetIncludePath(); inc.ReplaceAll("-I", " "); inc.ReplaceAll("\"", " "); AddIncludePath(inc, addedWorkers); // Cleanup delete addedWorkers; // Inform the client that the number of workers is changed if (fDynamicStartup && gProofServ) gProofServ->SendParallel(kTRUE); return 0; } //______________________________________________________________________________ Int_t TProof::RemoveWorkers(TList *workerList) { // Used for shuting down the workres after a query is finished. // Sends each of the workers from the workerList, a kPROOF_STOP message. // If the workerList == 0, shutdown all the workers. if (!IsMaster()) { Error("RemoveWorkers", "RemoveWorkers can only be called on the master!"); return -1; } fFileMap.clear(); // This could be avoided if CopyFromCache was used in SendFile if (!workerList) { // shutdown all the workers TIter nxsl(fSlaves); TSlave *sl = 0; while ((sl = (TSlave *) nxsl())) { // Shut down the worker assumig that it is not processing TerminateWorker(sl); } } else { if (!(workerList->GetSize())) { Error("RemoveWorkers", "The list of workers should not be empty!"); return -2; } // Loop over all the workers and stop them TListIter next(workerList); TObject *to; TProofNodeInfo *worker; while ((to = next())) { TSlave *sl = 0; if (!strcmp(to->ClassName(), "TProofNodeInfo")) { // Get the next worker from the list worker = (TProofNodeInfo *)to; TIter nxsl(fSlaves); while ((sl = (TSlave *) nxsl())) { // Shut down the worker assumig that it is not processing if (sl->GetName() == worker->GetNodeName()) break; } } else if (to->InheritsFrom(TSlave::Class())) { sl = (TSlave *) to; } else { Warning("RemoveWorkers","unknown object type: %s - it should be" " TProofNodeInfo or inheriting from TSlave", to->ClassName()); } // Shut down the worker assumig that it is not processing if (sl) { if (gDebug > 0) Info("RemoveWorkers","terminating worker %s", sl->GetOrdinal()); TerminateWorker(sl); } } } // Update also the master counter if (gProofServ && fSlaves->GetSize() <= 0) gProofServ->ReleaseWorker("master"); return 0; } //______________________________________________________________________________ Bool_t TProof::StartSlaves(Bool_t attach) { // Start up PROOF slaves. // If this is a master server, find the config file and start slave // servers as specified in the config file if (TestBit(TProof::kIsMaster)) { Int_t pc = 0; TList *workerList = new TList; // Get list of workers if (gProofServ->GetWorkers(workerList, pc) == TProofServ::kQueryStop) { TString emsg("no resource currently available for this session: please retry later"); if (gDebug > 0) Info("StartSlaves", emsg.Data()); gProofServ->SendAsynMessage(emsg.Data()); return kFALSE; } // Setup the workers if (AddWorkers(workerList) < 0) return kFALSE; } else { // create master server Printf("Starting master: opening connection ..."); TSlave *slave = CreateSubmaster(fUrl.GetUrl(), "0", "master", 0); if (slave->IsValid()) { // Notify fprintf(stderr,"Starting master:" " connection open: setting up server ... \r"); StartupMessage("Connection to master opened", kTRUE, 1, 1); if (!attach) { // Set worker interrupt handler slave->SetInterruptHandler(kTRUE); // Finalize setup of the server slave->SetupServ(TSlave::kMaster, fConfFile); if (slave->IsValid()) { // Notify Printf("Starting master: OK "); StartupMessage("Master started", kTRUE, 1, 1); // check protocol compatibility // protocol 1 is not supported anymore if (fProtocol == 1) { Error("StartSlaves", "client and remote protocols not compatible (%d and %d)", kPROOF_Protocol, fProtocol); slave->Close("S"); delete slave; return kFALSE; } fSlaves->Add(slave); fAllMonitor->Add(slave->GetSocket()); // Unset worker interrupt handler slave->SetInterruptHandler(kFALSE); // Set interrupt PROOF handler from now on fIntHandler = new TProofInterruptHandler(this); // Give-up after 5 minutes Int_t rc = Collect(slave, 300); Int_t slStatus = slave->GetStatus(); if (slStatus == -99 || slStatus == -98 || rc == 0) { fSlaves->Remove(slave); fAllMonitor->Remove(slave->GetSocket()); if (slStatus == -99) Error("StartSlaves", "no resources available or problems setting up workers (check logs)"); else if (slStatus == -98) Error("StartSlaves", "could not setup output redirection on master"); else Error("StartSlaves", "setting up master"); slave->Close("S"); delete slave; return 0; } if (!slave->IsValid()) { fSlaves->Remove(slave); fAllMonitor->Remove(slave->GetSocket()); slave->Close("S"); delete slave; Error("StartSlaves", "failed to setup connection with PROOF master server"); return kFALSE; } if (!gROOT->IsBatch() && TestBit(kUseProgressDialog)) { if ((fProgressDialog = gROOT->GetPluginManager()->FindHandler("TProofProgressDialog"))) if (fProgressDialog->LoadPlugin() == -1) fProgressDialog = 0; } } else { // Notify Printf("Starting master: failure"); } } else { // Notify Printf("Starting master: OK "); StartupMessage("Master attached", kTRUE, 1, 1); if (!gROOT->IsBatch() && TestBit(kUseProgressDialog)) { if ((fProgressDialog = gROOT->GetPluginManager()->FindHandler("TProofProgressDialog"))) if (fProgressDialog->LoadPlugin() == -1) fProgressDialog = 0; } fSlaves->Add(slave); fIntHandler = new TProofInterruptHandler(this); } } else { delete slave; // Notify only if verbosity is on: most likely the failure has already been notified if (gDebug > 0) Error("StartSlaves", "failed to create (or connect to) the PROOF master server"); return kFALSE; } } return kTRUE; } //______________________________________________________________________________ void TProof::Close(Option_t *opt) { // Close all open slave servers. // Client can decide to shutdown the remote session by passing option is 'S' // or 's'. Default for clients is detach, if supported. Masters always // shutdown the remote counterpart. { R__LOCKGUARD2(fCloseMutex); fValid = kFALSE; if (fSlaves) { if (fIntHandler) fIntHandler->Remove(); TIter nxs(fSlaves); TSlave *sl = 0; while ((sl = (TSlave *)nxs())) sl->Close(opt); fActiveSlaves->Clear("nodelete"); fUniqueSlaves->Clear("nodelete"); fAllUniqueSlaves->Clear("nodelete"); fNonUniqueMasters->Clear("nodelete"); fBadSlaves->Clear("nodelete"); fSlaves->Delete(); } } { R__LOCKGUARD2(gROOTMutex); gROOT->GetListOfSockets()->Remove(this); if (IsProofd()) { gROOT->GetListOfProofs()->Remove(this); if (gProof && gProof == this) { // Set previous proofd-related as default TIter pvp(gROOT->GetListOfProofs(), kIterBackward); while ((gProof = (TProof *)pvp())) { if (gProof->IsProofd()) break; } } } } } //______________________________________________________________________________ TSlave *TProof::CreateSlave(const char *url, const char *ord, Int_t perf, const char *image, const char *workdir) { // Create a new TSlave of type TSlave::kSlave. // Note: creation of TSlave is private with TProof as a friend. // Derived classes must use this function to create slaves. TSlave* sl = TSlave::Create(url, ord, perf, image, this, TSlave::kSlave, workdir, 0); if (sl->IsValid()) { sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket())); // must set fParallel to 1 for slaves since they do not // report their fParallel with a LOG_DONE message sl->fParallel = 1; } return sl; } //______________________________________________________________________________ TSlave *TProof::CreateSubmaster(const char *url, const char *ord, const char *image, const char *msd) { // Create a new TSlave of type TSlave::kMaster. // Note: creation of TSlave is private with TProof as a friend. // Derived classes must use this function to create slaves. TSlave *sl = TSlave::Create(url, ord, 100, image, this, TSlave::kMaster, 0, msd); if (sl->IsValid()) { sl->SetInputHandler(new TProofInputHandler(this, sl->GetSocket())); } return sl; } //______________________________________________________________________________ TSlave *TProof::FindSlave(TSocket *s) const { // Find slave that has TSocket s. Returns 0 in case slave is not found. TSlave *sl; TIter next(fSlaves); while ((sl = (TSlave *)next())) { if (sl->IsValid() && sl->GetSocket() == s) return sl; } return 0; } //______________________________________________________________________________ void TProof::FindUniqueSlaves() { // Add to the fUniqueSlave list the active slaves that have a unique // (user) file system image. This information is used to transfer files // only once to nodes that share a file system (an image). Submasters // which are not in fUniqueSlaves are put in the fNonUniqueMasters // list. That list is used to trigger the transferring of files to // the submaster's unique slaves without the need to transfer the file // to the submaster. fUniqueSlaves->Clear(); fUniqueMonitor->RemoveAll(); fAllUniqueSlaves->Clear(); fAllUniqueMonitor->RemoveAll(); fNonUniqueMasters->Clear(); TIter next(fActiveSlaves); while (TSlave *sl = dynamic_cast<TSlave*>(next())) { if (fImage == sl->fImage) { if (sl->GetSlaveType() == TSlave::kMaster) { fNonUniqueMasters->Add(sl); fAllUniqueSlaves->Add(sl); fAllUniqueMonitor->Add(sl->GetSocket()); } continue; } TIter next2(fUniqueSlaves); TSlave *replace_slave = 0; Bool_t add = kTRUE; while (TSlave *sl2 = dynamic_cast<TSlave*>(next2())) { if (sl->fImage == sl2->fImage) { add = kFALSE; if (sl->GetSlaveType() == TSlave::kMaster) { if (sl2->GetSlaveType() == TSlave::kSlave) { // give preference to master replace_slave = sl2; add = kTRUE; } else if (sl2->GetSlaveType() == TSlave::kMaster) { fNonUniqueMasters->Add(sl); fAllUniqueSlaves->Add(sl); fAllUniqueMonitor->Add(sl->GetSocket()); } else { Error("FindUniqueSlaves", "TSlave is neither Master nor Slave"); R__ASSERT(0); } } break; } } if (add) { fUniqueSlaves->Add(sl); fAllUniqueSlaves->Add(sl); fUniqueMonitor->Add(sl->GetSocket()); fAllUniqueMonitor->Add(sl->GetSocket()); if (replace_slave) { fUniqueSlaves->Remove(replace_slave); fAllUniqueSlaves->Remove(replace_slave); fUniqueMonitor->Remove(replace_slave->GetSocket()); fAllUniqueMonitor->Remove(replace_slave->GetSocket()); } } } // will be actiavted in Collect() fUniqueMonitor->DeActivateAll(); fAllUniqueMonitor->DeActivateAll(); } //______________________________________________________________________________ Int_t TProof::GetNumberOfSlaves() const { // Return number of slaves as described in the config file. return fSlaves->GetSize(); } //______________________________________________________________________________ Int_t TProof::GetNumberOfActiveSlaves() const { // Return number of active slaves, i.e. slaves that are valid and in // the current computing group. return fActiveSlaves->GetSize(); } //______________________________________________________________________________ Int_t TProof::GetNumberOfInactiveSlaves() const { // Return number of inactive slaves, i.e. slaves that are valid but not in // the current computing group. return fInactiveSlaves->GetSize(); } //______________________________________________________________________________ Int_t TProof::GetNumberOfUniqueSlaves() const { // Return number of unique slaves, i.e. active slaves that have each a // unique different user files system. return fUniqueSlaves->GetSize(); } //______________________________________________________________________________ Int_t TProof::GetNumberOfBadSlaves() const { // Return number of bad slaves. This are slaves that we in the config // file, but refused to startup or that died during the PROOF session. return fBadSlaves->GetSize(); } //______________________________________________________________________________ void TProof::AskStatistics() { // Ask the for the statistics of the slaves. if (!IsValid()) return; Broadcast(kPROOF_GETSTATS, kActive); Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ void TProof::GetStatistics(Bool_t verbose) { // Get statistics about CPU time, real time and bytes read. // If verbose, print the resuls (always available via GetCpuTime(), GetRealTime() // and GetBytesRead() if (fProtocol > 27) { // This returns the correct result AskStatistics(); } else { // AskStatistics is buggy: parse the output of Print() RedirectHandle_t rh; gSystem->RedirectOutput(fLogFileName, "a", &rh); Print(); gSystem->RedirectOutput(0, 0, &rh); TMacro *mp = GetLastLog(); if (mp) { // Look for global directories TIter nxl(mp->GetListOfLines()); TObjString *os = 0; while ((os = (TObjString *) nxl())) { TString s(os->GetName()); if (s.Contains("Total MB's processed:")) { s.ReplaceAll("Total MB's processed:", ""); if (s.IsFloat()) fBytesRead = (Long64_t) s.Atof() * (1024*1024); } else if (s.Contains("Total real time used (s):")) { s.ReplaceAll("Total real time used (s):", ""); if (s.IsFloat()) fRealTime = s.Atof(); } else if (s.Contains("Total CPU time used (s):")) { s.ReplaceAll("Total CPU time used (s):", ""); if (s.IsFloat()) fCpuTime = s.Atof(); } } delete mp; } } if (verbose) { Printf(" Real/CPU time (s): %.3f / %.3f; workers: %d; processed: %.2f MBs", GetRealTime(), GetCpuTime(), GetParallel(), float(GetBytesRead())/(1024*1024)); } } //______________________________________________________________________________ void TProof::AskParallel() { // Ask the for the number of parallel slaves. if (!IsValid()) return; Broadcast(kPROOF_GETPARALLEL, kActive); Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ TList *TProof::GetListOfQueries(Option_t *opt) { // Ask the master for the list of queries. if (!IsValid() || TestBit(TProof::kIsMaster)) return (TList *)0; Bool_t all = ((strchr(opt,'A') || strchr(opt,'a'))) ? kTRUE : kFALSE; TMessage m(kPROOF_QUERYLIST); m << all; Broadcast(m, kActive); Collect(kActive, fCollectTimeout); // This should have been filled by now return fQueries; } //______________________________________________________________________________ Int_t TProof::GetNumberOfQueries() { // Number of queries processed by this session if (fQueries) return fQueries->GetSize() - fOtherQueries; return 0; } //______________________________________________________________________________ void TProof::SetMaxDrawQueries(Int_t max) { // Set max number of draw queries whose results are saved if (max > 0) { if (fPlayer) fPlayer->SetMaxDrawQueries(max); fMaxDrawQueries = max; } } //______________________________________________________________________________ void TProof::GetMaxQueries() { // Get max number of queries whose full results are kept in the // remote sandbox TMessage m(kPROOF_MAXQUERIES); m << kFALSE; Broadcast(m, kActive); Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ TList *TProof::GetQueryResults() { // Return pointer to the list of query results in the player return (fPlayer ? fPlayer->GetListOfResults() : (TList *)0); } //______________________________________________________________________________ TQueryResult *TProof::GetQueryResult(const char *ref) { // Return pointer to the full TQueryResult instance owned by the player // and referenced by 'ref'. If ref = 0 or "", return the last query result. return (fPlayer ? fPlayer->GetQueryResult(ref) : (TQueryResult *)0); } //______________________________________________________________________________ void TProof::ShowQueries(Option_t *opt) { // Ask the master for the list of queries. // Options: // "A" show information about all the queries known to the // server, i.e. even those processed by other sessions // "L" show only information about queries locally available // i.e. already retrieved. If "L" is specified, "A" is // ignored. // "F" show all details available about queries // "H" print help menu // Default "" Bool_t help = ((strchr(opt,'H') || strchr(opt,'h'))) ? kTRUE : kFALSE; if (help) { // Help Printf("+++"); Printf("+++ Options: \"A\" show all queries known to server"); Printf("+++ \"L\" show retrieved queries"); Printf("+++ \"F\" full listing of query info"); Printf("+++ \"H\" print this menu"); Printf("+++"); Printf("+++ (case insensitive)"); Printf("+++"); Printf("+++ Use Retrieve(<#>) to retrieve the full" " query results from the master"); Printf("+++ e.g. Retrieve(8)"); Printf("+++"); return; } if (!IsValid()) return; Bool_t local = ((strchr(opt,'L') || strchr(opt,'l'))) ? kTRUE : kFALSE; TObject *pq = 0; if (!local) { GetListOfQueries(opt); if (!fQueries) return; TIter nxq(fQueries); // Queries processed by other sessions if (fOtherQueries > 0) { Printf("+++"); Printf("+++ Queries processed during other sessions: %d", fOtherQueries); Int_t nq = 0; while (nq++ < fOtherQueries && (pq = nxq())) pq->Print(opt); } // Queries processed by this session Printf("+++"); Printf("+++ Queries processed during this session: selector: %d, draw: %d", GetNumberOfQueries(), fDrawQueries); while ((pq = nxq())) pq->Print(opt); } else { // Queries processed by this session Printf("+++"); Printf("+++ Queries processed during this session: selector: %d, draw: %d", GetNumberOfQueries(), fDrawQueries); // Queries available locally TList *listlocal = fPlayer ? fPlayer->GetListOfResults() : (TList *)0; if (listlocal) { Printf("+++"); Printf("+++ Queries available locally: %d", listlocal->GetSize()); TIter nxlq(listlocal); while ((pq = nxlq())) pq->Print(opt); } } Printf("+++"); } //______________________________________________________________________________ Bool_t TProof::IsDataReady(Long64_t &totalbytes, Long64_t &bytesready) { // See if the data is ready to be analyzed. if (!IsValid()) return kFALSE; TList submasters; TIter nextSlave(GetListOfActiveSlaves()); while (TSlave *sl = dynamic_cast<TSlave*>(nextSlave())) { if (sl->GetSlaveType() == TSlave::kMaster) { submasters.Add(sl); } } fDataReady = kTRUE; //see if any submasters set it to false fBytesReady = 0; fTotalBytes = 0; //loop over submasters and see if data is ready if (submasters.GetSize() > 0) { Broadcast(kPROOF_DATA_READY, &submasters); Collect(&submasters); } bytesready = fBytesReady; totalbytes = fTotalBytes; EmitVA("IsDataReady(Long64_t,Long64_t)", 2, totalbytes, bytesready); //PDB(kGlobal,2) Info("IsDataReady", "%lld / %lld (%s)", bytesready, totalbytes, fDataReady?"READY":"NOT READY"); return fDataReady; } //______________________________________________________________________________ void TProof::Interrupt(EUrgent type, ESlaves list) { // Send interrupt to master or slave servers. if (!IsValid()) return; TList *slaves = 0; if (list == kAll) slaves = fSlaves; if (list == kActive) slaves = fActiveSlaves; if (list == kUnique) slaves = fUniqueSlaves; if (list == kAllUnique) slaves = fAllUniqueSlaves; if (slaves->GetSize() == 0) return; TSlave *sl; TIter next(slaves); while ((sl = (TSlave *)next())) { if (sl->IsValid()) { // Ask slave to progate the interrupt request sl->Interrupt((Int_t)type); } } } //______________________________________________________________________________ Int_t TProof::GetParallel() const { // Returns number of slaves active in parallel mode. Returns 0 in case // there are no active slaves. Returns -1 in case of error. if (!IsValid()) return -1; // iterate over active slaves and return total number of slaves TIter nextSlave(GetListOfActiveSlaves()); Int_t nparallel = 0; while (TSlave* sl = dynamic_cast<TSlave*>(nextSlave())) if (sl->GetParallel() >= 0) nparallel += sl->GetParallel(); return nparallel; } //______________________________________________________________________________ TList *TProof::GetListOfSlaveInfos() { // Returns list of TSlaveInfo's. In case of error return 0. if (!IsValid()) return 0; if (fSlaveInfo == 0) { fSlaveInfo = new TSortedList(kSortDescending); fSlaveInfo->SetOwner(); } else { fSlaveInfo->Delete(); } TList masters; TIter next(GetListOfSlaves()); TSlave *slave; while ((slave = (TSlave *) next()) != 0) { if (slave->GetSlaveType() == TSlave::kSlave) { TSlaveInfo *slaveinfo = new TSlaveInfo(slave->GetOrdinal(), slave->GetName(), slave->GetPerfIdx()); fSlaveInfo->Add(slaveinfo); TIter nextactive(GetListOfActiveSlaves()); TSlave *activeslave; while ((activeslave = (TSlave *) nextactive())) { if (TString(slaveinfo->GetOrdinal()) == activeslave->GetOrdinal()) { slaveinfo->SetStatus(TSlaveInfo::kActive); break; } } TIter nextbad(GetListOfBadSlaves()); TSlave *badslave; while ((badslave = (TSlave *) nextbad())) { if (TString(slaveinfo->GetOrdinal()) == badslave->GetOrdinal()) { slaveinfo->SetStatus(TSlaveInfo::kBad); break; } } // Get system info if supported if (slave->IsValid()) { if (slave->GetSocket()->Send(kPROOF_GETSLAVEINFO) == -1) MarkBad(slave, "could not send kPROOF_GETSLAVEINFO message"); else masters.Add(slave); } } else if (slave->GetSlaveType() == TSlave::kMaster) { if (slave->IsValid()) { if (slave->GetSocket()->Send(kPROOF_GETSLAVEINFO) == -1) MarkBad(slave, "could not send kPROOF_GETSLAVEINFO message"); else masters.Add(slave); } } else { Error("GetSlaveInfo", "TSlave is neither Master nor Slave"); R__ASSERT(0); } } if (masters.GetSize() > 0) Collect(&masters); return fSlaveInfo; } //______________________________________________________________________________ void TProof::Activate(TList *slaves) { // Activate slave server list. TMonitor *mon = fAllMonitor; mon->DeActivateAll(); slaves = !slaves ? fActiveSlaves : slaves; TIter next(slaves); TSlave *sl; while ((sl = (TSlave*) next())) { if (sl->IsValid()) mon->Activate(sl->GetSocket()); } } //______________________________________________________________________________ void TProof::SetMonitor(TMonitor *mon, Bool_t on) { // Activate (on == TRUE) or deactivate (on == FALSE) all sockets // monitored by 'mon'. TMonitor *m = (mon) ? mon : fCurrentMonitor; if (m) { if (on) m->ActivateAll(); else m->DeActivateAll(); } } //______________________________________________________________________________ Int_t TProof::BroadcastGroupPriority(const char *grp, Int_t priority, TList *workers) { // Broadcast the group priority to all workers in the specified list. Returns // the number of workers the message was successfully sent to. // Returns -1 in case of error. if (!IsValid()) return -1; if (workers->GetSize() == 0) return 0; int nsent = 0; TIter next(workers); TSlave *wrk; while ((wrk = (TSlave *)next())) { if (wrk->IsValid()) { if (wrk->SendGroupPriority(grp, priority) == -1) MarkBad(wrk, "could not send group priority"); else nsent++; } } return nsent; } //______________________________________________________________________________ Int_t TProof::BroadcastGroupPriority(const char *grp, Int_t priority, ESlaves list) { // Broadcast the group priority to all workers in the specified list. Returns // the number of workers the message was successfully sent to. // Returns -1 in case of error. TList *workers = 0; if (list == kAll) workers = fSlaves; if (list == kActive) workers = fActiveSlaves; if (list == kUnique) workers = fUniqueSlaves; if (list == kAllUnique) workers = fAllUniqueSlaves; return BroadcastGroupPriority(grp, priority, workers); } //______________________________________________________________________________ void TProof::ResetMergePrg() { // Reset the merge progress notificator fMergePrg.Reset(fActiveSlaves->GetSize()); } //______________________________________________________________________________ Int_t TProof::Broadcast(const TMessage &mess, TList *slaves) { // Broadcast a message to all slaves in the specified list. Returns // the number of slaves the message was successfully sent to. // Returns -1 in case of error. if (!IsValid()) return -1; if (!slaves || slaves->GetSize() == 0) return 0; int nsent = 0; TIter next(slaves); TSlave *sl; while ((sl = (TSlave *)next())) { if (sl->IsValid()) { if (sl->GetSocket()->Send(mess) == -1) MarkBad(sl, "could not broadcast request"); else nsent++; } } return nsent; } //______________________________________________________________________________ Int_t TProof::Broadcast(const TMessage &mess, ESlaves list) { // Broadcast a message to all slaves in the specified list (either // all slaves or only the active slaves). Returns the number of slaves // the message was successfully sent to. Returns -1 in case of error. TList *slaves = 0; if (list == kAll) slaves = fSlaves; if (list == kActive) slaves = fActiveSlaves; if (list == kUnique) slaves = fUniqueSlaves; if (list == kAllUnique) slaves = fAllUniqueSlaves; return Broadcast(mess, slaves); } //______________________________________________________________________________ Int_t TProof::Broadcast(const char *str, Int_t kind, TList *slaves) { // Broadcast a character string buffer to all slaves in the specified // list. Use kind to set the TMessage what field. Returns the number of // slaves the message was sent to. Returns -1 in case of error. TMessage mess(kind); if (str) mess.WriteString(str); return Broadcast(mess, slaves); } //______________________________________________________________________________ Int_t TProof::Broadcast(const char *str, Int_t kind, ESlaves list) { // Broadcast a character string buffer to all slaves in the specified // list (either all slaves or only the active slaves). Use kind to // set the TMessage what field. Returns the number of slaves the message // was sent to. Returns -1 in case of error. TMessage mess(kind); if (str) mess.WriteString(str); return Broadcast(mess, list); } //______________________________________________________________________________ Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, TList *slaves) { // Broadcast an object to all slaves in the specified list. Use kind to // set the TMEssage what field. Returns the number of slaves the message // was sent to. Returns -1 in case of error. TMessage mess(kind); mess.WriteObject(obj); return Broadcast(mess, slaves); } //______________________________________________________________________________ Int_t TProof::BroadcastObject(const TObject *obj, Int_t kind, ESlaves list) { // Broadcast an object to all slaves in the specified list. Use kind to // set the TMEssage what field. Returns the number of slaves the message // was sent to. Returns -1 in case of error. TMessage mess(kind); mess.WriteObject(obj); return Broadcast(mess, list); } //______________________________________________________________________________ Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, TList *slaves) { // Broadcast a raw buffer of specified length to all slaves in the // specified list. Returns the number of slaves the buffer was sent to. // Returns -1 in case of error. if (!IsValid()) return -1; if (slaves->GetSize() == 0) return 0; int nsent = 0; TIter next(slaves); TSlave *sl; while ((sl = (TSlave *)next())) { if (sl->IsValid()) { if (sl->GetSocket()->SendRaw(buffer, length) == -1) MarkBad(sl, "could not send broadcast-raw request"); else nsent++; } } return nsent; } //______________________________________________________________________________ Int_t TProof::BroadcastRaw(const void *buffer, Int_t length, ESlaves list) { // Broadcast a raw buffer of specified length to all slaves in the // specified list. Returns the number of slaves the buffer was sent to. // Returns -1 in case of error. TList *slaves = 0; if (list == kAll) slaves = fSlaves; if (list == kActive) slaves = fActiveSlaves; if (list == kUnique) slaves = fUniqueSlaves; if (list == kAllUnique) slaves = fAllUniqueSlaves; return BroadcastRaw(buffer, length, slaves); } //______________________________________________________________________________ Int_t TProof::BroadcastFile(const char *file, Int_t opt, const char *rfile, TList *wrks) { // Broadcast file to all workers in the specified list. Returns the number of workers // the buffer was sent to. // Returns -1 in case of error. if (!IsValid()) return -1; if (wrks->GetSize() == 0) return 0; int nsent = 0; TIter next(wrks); TSlave *wrk; while ((wrk = (TSlave *)next())) { if (wrk->IsValid()) { if (SendFile(file, opt, rfile, wrk) < 0) Error("BroadcastFile", "problems sending file to worker %s (%s)", wrk->GetOrdinal(), wrk->GetName()); else nsent++; } } return nsent; } //______________________________________________________________________________ Int_t TProof::BroadcastFile(const char *file, Int_t opt, const char *rfile, ESlaves list) { // Broadcast file to all workers in the specified list. Returns the number of workers // the buffer was sent to. // Returns -1 in case of error. TList *wrks = 0; if (list == kAll) wrks = fSlaves; if (list == kActive) wrks = fActiveSlaves; if (list == kUnique) wrks = fUniqueSlaves; if (list == kAllUnique) wrks = fAllUniqueSlaves; return BroadcastFile(file, opt, rfile, wrks); } //______________________________________________________________________________ void TProof::ReleaseMonitor(TMonitor *mon) { // Release the used monitor to be used, making sure to delete newly created // monitors. if (mon && (mon != fAllMonitor) && (mon != fActiveMonitor) && (mon != fUniqueMonitor) && (mon != fAllUniqueMonitor)) { delete mon; } } //______________________________________________________________________________ Int_t TProof::Collect(const TSlave *sl, Long_t timeout, Int_t endtype) { // Collect responses from slave sl. Returns the number of slaves that // responded (=1). // If timeout >= 0, wait at most timeout seconds (timeout = -1 by default, // which means wait forever). // If defined (>= 0) endtype is the message that stops this collection. Int_t rc = 0; TMonitor *mon = 0; if (!sl->IsValid()) return 0; if (fCurrentMonitor == fAllMonitor) { mon = new TMonitor; } else { mon = fAllMonitor; mon->DeActivateAll(); } mon->Activate(sl->GetSocket()); rc = Collect(mon, timeout, endtype); ReleaseMonitor(mon); return rc; } //______________________________________________________________________________ Int_t TProof::Collect(TList *slaves, Long_t timeout, Int_t endtype) { // Collect responses from the slave servers. Returns the number of slaves // that responded. // If timeout >= 0, wait at most timeout seconds (timeout = -1 by default, // which means wait forever). // If defined (>= 0) endtype is the message that stops this collection. Int_t rc = 0; TMonitor *mon = 0; if (fCurrentMonitor == fAllMonitor) { mon = new TMonitor; } else { mon = fAllMonitor; mon->DeActivateAll(); } TIter next(slaves); TSlave *sl; while ((sl = (TSlave*) next())) { if (sl->IsValid()) mon->Activate(sl->GetSocket()); } rc = Collect(mon, timeout, endtype); ReleaseMonitor(mon); return rc; } //______________________________________________________________________________ Int_t TProof::Collect(ESlaves list, Long_t timeout, Int_t endtype) { // Collect responses from the slave servers. Returns the number of slaves // that responded. // If timeout >= 0, wait at most timeout seconds (timeout = -1 by default, // which means wait forever). // If defined (>= 0) endtype is the message that stops this collection. Int_t rc = 0; TMonitor *mon = 0; if (list == kAll) mon = fAllMonitor; if (list == kActive) mon = fActiveMonitor; if (list == kUnique) mon = fUniqueMonitor; if (list == kAllUnique) mon = fAllUniqueMonitor; if (fCurrentMonitor == mon) { // Get a copy mon = new TMonitor(*mon); } mon->ActivateAll(); rc = Collect(mon, timeout, endtype); ReleaseMonitor(mon); return rc; } //______________________________________________________________________________ Int_t TProof::Collect(TMonitor *mon, Long_t timeout, Int_t endtype) { // Collect responses from the slave servers. Returns the number of messages // received. Can be 0 if there are no active slaves. // If timeout >= 0, wait at most timeout seconds (timeout = -1 by default, // which means wait forever). // If defined (>= 0) endtype is the message that stops this collection. // Reset the status flag and clear the messages in the list, if any fStatus = 0; fRecvMessages->Clear(); Long_t actto = (Long_t)(gEnv->GetValue("Proof.SocketActivityTimeout", -1) * 1000); if (!mon->GetActive(actto)) return 0; DeActivateAsyncInput(); // Used by external code to know what we are monitoring TMonitor *savedMonitor = 0; if (fCurrentMonitor) { savedMonitor = fCurrentMonitor; fCurrentMonitor = mon; } else { fCurrentMonitor = mon; fBytesRead = 0; fRealTime = 0.0; fCpuTime = 0.0; } // We want messages on the main window during synchronous collection, // but we save the present status to restore it at the end Bool_t saveRedirLog = fRedirLog; if (!IsIdle() && !IsSync()) fRedirLog = kFALSE; int cnt = 0, rc = 0; // Timeout counter Long_t nto = timeout; PDB(kCollect, 2) Info("Collect","active: %d", mon->GetActive()); // On clients, handle Ctrl-C during collection if (fIntHandler) fIntHandler->Add(); // Sockets w/o activity during the last 'sto' millisecs are deactivated Int_t nact = 0; Long_t sto = -1; Int_t nsto = 60; mon->ResetInterrupt(); while ((nact = mon->GetActive(sto)) && (nto < 0 || nto > 0)) { // Dump last waiting sockets, if in debug mode PDB(kCollect, 2) { if (nact < 4) { TList *al = mon->GetListOfActives(); if (al && al->GetSize() > 0) { Info("Collect"," %d node(s) still active:", al->GetSize()); TIter nxs(al); TSocket *xs = 0; while ((xs = (TSocket *)nxs())) { TSlave *wrk = FindSlave(xs); if (wrk) Info("Collect"," %s", wrk->GetName()); else Info("Collect"," %p: %s:%d", xs, xs->GetInetAddress().GetHostName(), xs->GetInetAddress().GetPort()); } } } } // Wait for a ready socket TSocket *s = mon->Select(1000); if (s && s != (TSocket *)(-1)) { // Get and analyse the info it did receive rc = CollectInputFrom(s, endtype); if (rc == 1 || (rc == 2 && !savedMonitor)) { // Deactivate it if we are done with it mon->DeActivate(s); PDB(kCollect, 2) Info("Collect","deactivating %p (active: %d, %p)", s, mon->GetActive(), mon->GetListOfActives()->First()); } else if (rc == 2) { // This end message was for the saved monitor // Deactivate it if we are done with it if (savedMonitor) { savedMonitor->DeActivate(s); PDB(kCollect, 2) Info("Collect","save monitor: deactivating %p (active: %d, %p)", s, savedMonitor->GetActive(), savedMonitor->GetListOfActives()->First()); } } // Update counter (if no error occured) if (rc >= 0) cnt++; } else { // If not timed-out, exit if not stopped or not aborted // (player exits status is finished in such a case); otherwise, // we still need to collect the partial output info if (!s) if (fPlayer && (fPlayer->GetExitStatus() == TVirtualProofPlayer::kFinished)) mon->DeActivateAll(); // Decrease the timeout counter if requested if (s == (TSocket *)(-1) && nto > 0) nto--; } // Check if we need to check the socket activity (we do it every 10 cycles ~ 10 sec) sto = -1; if (--nsto <= 0) { sto = (Long_t) actto; nsto = 60; } } // If timed-out, deactivate the remaining sockets if (nto == 0) { TList *al = mon->GetListOfActives(); if (al && al->GetSize() > 0) { // Notify the name of those which did timeout Info("Collect"," %d node(s) went in timeout:", al->GetSize()); TIter nxs(al); TSocket *xs = 0; while ((xs = (TSocket *)nxs())) { TSlave *wrk = FindSlave(xs); if (wrk) Info("Collect"," %s", wrk->GetName()); else Info("Collect"," %p: %s:%d", xs, xs->GetInetAddress().GetHostName(), xs->GetInetAddress().GetPort()); } } mon->DeActivateAll(); } // Deactivate Ctrl-C special handler if (fIntHandler) fIntHandler->Remove(); // make sure group view is up to date SendGroupView(); // Restore redirection setting fRedirLog = saveRedirLog; // Restore the monitor fCurrentMonitor = savedMonitor; ActivateAsyncInput(); return cnt; } //______________________________________________________________________________ void TProof::CleanGDirectory(TList *ol) { // Remove links to objects in list 'ol' from gDirectory if (ol) { TIter nxo(ol); TObject *o = 0; while ((o = nxo())) gDirectory->RecursiveRemove(o); } } //______________________________________________________________________________ Int_t TProof::CollectInputFrom(TSocket *s, Int_t endtype) { // Collect and analyze available input from socket s. // Returns 0 on success, -1 if any failure occurs. TMessage *mess; Int_t recvrc = 0; if ((recvrc = s->Recv(mess)) < 0) { PDB(kCollect,2) Info("CollectInputFrom","%p: got %d from Recv()", s, recvrc); Bool_t bad = kTRUE; if (recvrc == -5) { // Broken connection: try reconnection if (fCurrentMonitor) fCurrentMonitor->Remove(s); if (s->Reconnect() == 0) { if (fCurrentMonitor) fCurrentMonitor->Add(s); bad = kFALSE; } } if (bad) MarkBad(s, "problems receiving a message in TProof::CollectInputFrom(...)"); // Ignore this wake up return -1; } if (!mess) { // we get here in case the remote server died MarkBad(s, "undefined message in TProof::CollectInputFrom(...)"); return -1; } Int_t rc = 0; Int_t what = mess->What(); TSlave *sl = FindSlave(s); rc = HandleInputMessage(sl, mess); if (rc == 1 && (endtype >= 0) && (what != endtype)) // This message was for the base monitor in recursive case rc = 2; // We are done successfully return rc; } //______________________________________________________________________________ Int_t TProof::HandleInputMessage(TSlave *sl, TMessage *mess) { // Analyze the received message. // Returns 0 on success (1 if this the last message from this socket), -1 if // any failure occurs. char str[512]; TObject *obj; Int_t rc = 0; if (!mess || !sl) { Warning("HandleInputMessage", "given an empty message or undefined worker"); return -1; } Bool_t delete_mess = kTRUE; TSocket *s = sl->GetSocket(); if (!s) { Warning("HandleInputMessage", "worker socket is undefined"); return -1; } // The message type Int_t what = mess->What(); PDB(kCollect,3) Info("HandleInputMessage", "got type %d from '%s'", what, sl->GetOrdinal()); switch (what) { case kMESS_OK: // Add the message to the list fRecvMessages->Add(mess); delete_mess = kFALSE; break; case kMESS_OBJECT: if (fPlayer) fPlayer->HandleRecvHisto(mess); break; case kPROOF_FATAL: MarkBad(s, "received kPROOF_FATAL"); if (fProgressDialogStarted) { // Finalize the progress dialog Emit("StopProcess(Bool_t)", kTRUE); } break; case kPROOF_STOP: // Stop collection from this worker Info("HandleInputMessage", "received kPROOF_STOP from %s: disabling any further collection this worker", (sl ? sl->GetOrdinal() : "undef")); rc = 1; break; case kPROOF_GETTREEHEADER: // Add the message to the list fRecvMessages->Add(mess); delete_mess = kFALSE; rc = 1; break; case kPROOF_TOUCH: // send a request for touching the remote admin file { sl->Touch(); } break; case kPROOF_GETOBJECT: // send slave object it asks for mess->ReadString(str, sizeof(str)); obj = gDirectory->Get(str); if (obj) s->SendObject(obj); else s->Send(kMESS_NOTOK); break; case kPROOF_GETPACKET: { TDSetElement *elem = 0; elem = fPlayer ? fPlayer->GetNextPacket(sl, mess) : 0; if (elem != (TDSetElement*) -1) { TMessage answ(kPROOF_GETPACKET); answ << elem; s->Send(answ); while (fWaitingSlaves != 0 && fWaitingSlaves->GetSize()) { TPair *p = (TPair*) fWaitingSlaves->First(); s = (TSocket*) p->Key(); TMessage *m = (TMessage*) p->Value(); elem = fPlayer ? fPlayer->GetNextPacket(sl, m) : 0; if (elem != (TDSetElement*) -1) { TMessage a(kPROOF_GETPACKET); a << elem; s->Send(a); // remove has to happen via Links because TPair does not have // a Compare() function and therefore RemoveFirst() and // Remove(TObject*) do not work fWaitingSlaves->Remove(fWaitingSlaves->FirstLink()); delete p; delete m; } else { break; } } } else { if (fWaitingSlaves == 0) fWaitingSlaves = new TList; fWaitingSlaves->Add(new TPair(s, mess)); delete_mess = kFALSE; } } break; case kPROOF_LOGFILE: { Int_t size; (*mess) >> size; PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_LOGFILE: size: %d", size); RecvLogFile(s, size); } break; case kPROOF_LOGDONE: (*mess) >> sl->fStatus >> sl->fParallel; PDB(kCollect,2) Info("HandleInputMessage","kPROOF_LOGDONE:%s: status %d parallel %d", sl->GetOrdinal(), sl->fStatus, sl->fParallel); if (sl->fStatus != 0) fStatus = sl->fStatus; //return last nonzero status rc = 1; break; case kPROOF_GETSTATS: { (*mess) >> sl->fBytesRead >> sl->fRealTime >> sl->fCpuTime >> sl->fWorkDir >> sl->fProofWorkDir; TString img; if ((mess->BufferSize() > mess->Length())) (*mess) >> img; // Set image if (img.IsNull()) { if (sl->fImage.IsNull()) sl->fImage = Form("%s:%s", TUrl(sl->fName).GetHostFQDN(), sl->fProofWorkDir.Data()); } else { sl->fImage = img; } PDB(kGlobal,2) Info("HandleInputMessage", "kPROOF_GETSTATS:%s image: %s", sl->GetOrdinal(), sl->GetImage()); fBytesRead += sl->fBytesRead; fRealTime += sl->fRealTime; fCpuTime += sl->fCpuTime; rc = 1; } break; case kPROOF_GETPARALLEL: { Bool_t async = kFALSE; (*mess) >> sl->fParallel; if ((mess->BufferSize() > mess->Length())) (*mess) >> async; rc = (async) ? 0 : 1; } break; case kPROOF_CHECKFILE: { // New servers (>= 5.22) send the status if ((mess->BufferSize() > mess->Length())) { (*mess) >> fCheckFileStatus; } else { // Form old servers this meant success (failure was signaled with the // dangerous kPROOF_FATAL) fCheckFileStatus = 1; } rc = 1; } break; case kPROOF_SENDFILE: { // New server: signals ending of sendfile operation rc = 1; } break; case kPROOF_PACKAGE_LIST: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_PACKAGE_LIST: enter"); Int_t type = 0; (*mess) >> type; switch (type) { case TProof::kListEnabledPackages: SafeDelete(fEnabledPackages); fEnabledPackages = (TList *) mess->ReadObject(TList::Class()); if (fEnabledPackages) { fEnabledPackages->SetOwner(); } else { Error("HandleInputMessage", "kPROOF_PACKAGE_LIST: kListEnabledPackages: TList not found in message!"); } break; case TProof::kListPackages: SafeDelete(fAvailablePackages); fAvailablePackages = (TList *) mess->ReadObject(TList::Class()); if (fAvailablePackages) { fAvailablePackages->SetOwner(); } else { Error("HandleInputMessage", "kPROOF_PACKAGE_LIST: kListPackages: TList not found in message!"); } break; default: Error("HandleInputMessage", "kPROOF_PACKAGE_LIST: unknown type: %d", type); } } break; case kPROOF_OUTPUTOBJECT: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_OUTPUTOBJECT: enter"); Int_t type = 0; const char *prefix = gProofServ ? gProofServ->GetPrefix() : "Lite-0"; if (!TestBit(TProof::kIsClient) && !fMergersSet && !fFinalizationRunning) { Info("HandleInputMessage", "finalization on %s started ...", prefix); fFinalizationRunning = kTRUE; } while ((mess->BufferSize() > mess->Length())) { (*mess) >> type; // If a query result header, add it to the player list if (fPlayer) { if (type == 0) { // Retrieve query result instance (output list not filled) TQueryResult *pq = (TQueryResult *) mess->ReadObject(TQueryResult::Class()); if (pq) { // Add query to the result list in TProofPlayer fPlayer->AddQueryResult(pq); fPlayer->SetCurrentQuery(pq); // And clear the output list, as we start merging a new set of results if (fPlayer->GetOutputList()) fPlayer->GetOutputList()->Clear(); // Add the unique query tag as TNamed object to the input list // so that it is available in TSelectors for monitoring fPlayer->AddInput(new TNamed("PROOF_QueryTag", Form("%s:%s",pq->GetTitle(),pq->GetName()))); } else { Warning("HandleInputMessage","kPROOF_OUTPUTOBJECT: query result missing"); } } else if (type > 0) { // Read object TObject *o = mess->ReadObject(TObject::Class()); // Increment counter on the client side fMergePrg.IncreaseIdx(); TString msg; msg.Form("%s: merging output objects ... %s", prefix, fMergePrg.Export()); if (gProofServ) gProofServ->SendAsynMessage(msg.Data(), kFALSE); else fprintf(stderr, "%s\r", msg.Data()); // Add or merge it if ((fPlayer->AddOutputObject(o) == 1)) { // Remove the object if it has been merged SafeDelete(o); } if (type > 1) { // Update the merger progress info fMergePrg.DecreaseNWrks(); if (TestBit(TProof::kIsClient) && !IsLite()) { // In PROOFLite this has to be done once only in TProofLite::Process TQueryResult *pq = fPlayer->GetCurrentQuery(); pq->SetOutputList(fPlayer->GetOutputList(), kFALSE); pq->SetInputList(fPlayer->GetInputList(), kFALSE); // If the last object, notify the GUI that the result arrived QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName())); // Processing is over UpdateDialog(); } } } } else { Warning("HandleInputMessage", "kPROOF_OUTPUTOBJECT: player undefined!"); } } } break; case kPROOF_OUTPUTLIST: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_OUTPUTLIST: enter"); TList *out = 0; if (fPlayer) { if (TestBit(TProof::kIsMaster) || fProtocol < 7) { out = (TList *) mess->ReadObject(TList::Class()); } else { TQueryResult *pq = (TQueryResult *) mess->ReadObject(TQueryResult::Class()); if (pq) { // Add query to the result list in TProofPlayer fPlayer->AddQueryResult(pq); fPlayer->SetCurrentQuery(pq); // To avoid accidental cleanups from anywhere else // remove objects from gDirectory and clone the list out = pq->GetOutputList(); CleanGDirectory(out); out = (TList *) out->Clone(); // Notify the GUI that the result arrived QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName())); } else { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_OUTPUTLIST: query result missing"); } } if (out) { out->SetOwner(); fPlayer->AddOutput(out); // Incorporate the list SafeDelete(out); } else { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_OUTPUTLIST: ouputlist is empty"); } } else { Warning("HandleInputMessage", "kPROOF_OUTPUTLIST: player undefined!"); } // On clients at this point processing is over if (TestBit(TProof::kIsClient) && !IsLite()) UpdateDialog(); } break; case kPROOF_QUERYLIST: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_QUERYLIST: enter"); (*mess) >> fOtherQueries >> fDrawQueries; if (fQueries) { fQueries->Delete(); delete fQueries; fQueries = 0; } fQueries = (TList *) mess->ReadObject(TList::Class()); } break; case kPROOF_RETRIEVE: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_RETRIEVE: enter"); TQueryResult *pq = (TQueryResult *) mess->ReadObject(TQueryResult::Class()); if (pq && fPlayer) { fPlayer->AddQueryResult(pq); // Notify the GUI that the result arrived QueryResultReady(Form("%s:%s", pq->GetTitle(), pq->GetName())); } else { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_RETRIEVE: query result missing or player undefined"); } } break; case kPROOF_MAXQUERIES: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_MAXQUERIES: enter"); Int_t max = 0; (*mess) >> max; Printf("Number of queries fully kept remotely: %d", max); } break; case kPROOF_SERVERSTARTED: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_SERVERSTARTED: enter"); UInt_t tot = 0, done = 0; TString action; Bool_t st = kTRUE; (*mess) >> action >> tot >> done >> st; if (TestBit(TProof::kIsClient)) { if (tot) { TString type = (action.Contains("submas")) ? "submasters" : "workers"; Int_t frac = (Int_t) (done*100.)/tot; char msg[512] = {0}; if (frac >= 100) { snprintf(msg, 512, "%s: OK (%d %s) \n", action.Data(),tot, type.Data()); } else { snprintf(msg, 512, "%s: %d out of %d (%d %%)\r", action.Data(), done, tot, frac); } if (fSync) fprintf(stderr,"%s", msg); else NotifyLogMsg(msg, 0); } // Notify GUIs StartupMessage(action.Data(), st, (Int_t)done, (Int_t)tot); } else { // Just send the message one level up TMessage m(kPROOF_SERVERSTARTED); m << action << tot << done << st; gProofServ->GetSocket()->Send(m); } } break; case kPROOF_DATASET_STATUS: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_DATASET_STATUS: enter"); UInt_t tot = 0, done = 0; TString action; Bool_t st = kTRUE; (*mess) >> action >> tot >> done >> st; if (TestBit(TProof::kIsClient)) { if (tot) { TString type = "files"; Int_t frac = (Int_t) (done*100.)/tot; char msg[512] = {0}; if (frac >= 100) { sprintf(msg,"%s: OK (%d %s) \n", action.Data(),tot, type.Data()); } else { sprintf(msg,"%s: %d out of %d (%d %%)\r", action.Data(), done, tot, frac); } if (fSync) fprintf(stderr,"%s", msg); else NotifyLogMsg(msg, 0); } // Notify GUIs DataSetStatus(action.Data(), st, (Int_t)done, (Int_t)tot); } else { // Just send the message one level up TMessage m(kPROOF_DATASET_STATUS); m << action << tot << done << st; gProofServ->GetSocket()->Send(m); } } break; case kPROOF_STARTPROCESS: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_STARTPROCESS: enter"); // For Proof-Lite this variable is the number of workers and is set // by the player if (!IsLite()) { fNotIdle = 1; fIsWaiting = kFALSE; } // Redirect the output, if needed fRedirLog = (fSync) ? fRedirLog : kTRUE; // The signal is used on masters by XrdProofdProtocol to catch // the start of processing; on clients it allows to update the // progress dialog if (!TestBit(TProof::kIsMaster)) { TString selec; Int_t dsz = -1; Long64_t first = -1, nent = -1; (*mess) >> selec >> dsz >> first >> nent; // Start or reset the progress dialog if (!gROOT->IsBatch()) { if (fProgressDialog && !TestBit(kUsingSessionGui) && TestBit(kUseProgressDialog)) { if (!fProgressDialogStarted) { fProgressDialog->ExecPlugin(5, this, selec.Data(), dsz, first, nent); fProgressDialogStarted = kTRUE; } else { ResetProgressDialog(selec, dsz, first, nent); } } ResetBit(kUsingSessionGui); } } } break; case kPROOF_ENDINIT: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_ENDINIT: enter"); if (TestBit(TProof::kIsMaster)) { if (fPlayer) fPlayer->SetInitTime(); } } break; case kPROOF_SETIDLE: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_SETIDLE: enter"); // The session is idle if (IsLite()) { if (fNotIdle > 0) { fNotIdle--; } else { Warning("HandleInputMessage", "got kPROOF_SETIDLE but no running workers ! protocol error?"); } } else { fNotIdle = 0; // Check if the query has been enqueued if ((mess->BufferSize() > mess->Length())) (*mess) >> fIsWaiting; } } break; case kPROOF_QUERYSUBMITTED: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_QUERYSUBMITTED: enter"); // We have received the sequential number (*mess) >> fSeqNum; Bool_t sync = fSync; if ((mess->BufferSize() > mess->Length())) (*mess) >> sync; if (sync != fSync && fSync) { // The server required to switch to asynchronous mode Activate(); fSync = kFALSE; } DisableGoAsyn(); // Check if the query has been enqueued fIsWaiting = kTRUE; // For Proof-Lite this variable is the number of workers and is set by the player if (!IsLite()) fNotIdle = 1; rc = 1; } break; case kPROOF_SESSIONTAG: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_SESSIONTAG: enter"); // We have received the unique tag and save it as name of this object TString stag; (*mess) >> stag; SetName(stag); // New servers send also the group if ((mess->BufferSize() > mess->Length())) (*mess) >> fGroup; } break; case kPROOF_FEEDBACK: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_FEEDBACK: enter"); TList *out = (TList *) mess->ReadObject(TList::Class()); out->SetOwner(); if (fPlayer) fPlayer->StoreFeedback(sl, out); // Adopts the list else // Not yet ready: stop collect asap rc = 1; } break; case kPROOF_AUTOBIN: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_AUTOBIN: enter"); TString name; Double_t xmin, xmax, ymin, ymax, zmin, zmax; (*mess) >> name >> xmin >> xmax >> ymin >> ymax >> zmin >> zmax; if (fPlayer) fPlayer->UpdateAutoBin(name,xmin,xmax,ymin,ymax,zmin,zmax); TMessage answ(kPROOF_AUTOBIN); answ << name << xmin << xmax << ymin << ymax << zmin << zmax; s->Send(answ); } break; case kPROOF_PROGRESS: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_PROGRESS: enter"); if (GetRemoteProtocol() > 25) { // New format TProofProgressInfo *pi = 0; (*mess) >> pi; fPlayer->Progress(sl,pi); } else if (GetRemoteProtocol() > 11) { Long64_t total, processed, bytesread; Float_t initTime, procTime, evtrti, mbrti; (*mess) >> total >> processed >> bytesread >> initTime >> procTime >> evtrti >> mbrti; if (fPlayer) fPlayer->Progress(sl, total, processed, bytesread, initTime, procTime, evtrti, mbrti); } else { // Old format Long64_t total, processed; (*mess) >> total >> processed; if (fPlayer) fPlayer->Progress(sl, total, processed); } } break; case kPROOF_STOPPROCESS: { // This message is sent from a worker that finished processing. // We determine whether it was asked to finish by the // packetizer or stopped during processing a packet // (by TProof::RemoveWorkers() or by an external signal). // In the later case call packetizer->MarkBad. PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_STOPPROCESS: enter"); Long64_t events = 0; Bool_t abort = kFALSE; TProofProgressStatus *status = 0; if ((mess->BufferSize() > mess->Length()) && (fProtocol > 18)) { (*mess) >> status >> abort; } else if ((mess->BufferSize() > mess->Length()) && (fProtocol > 8)) { (*mess) >> events >> abort; } else { (*mess) >> events; } if (!abort && fPlayer) { if (fProtocol > 18) { TList *listOfMissingFiles = 0; if (!(listOfMissingFiles = (TList *)GetOutput("MissingFiles"))) { listOfMissingFiles = new TList(); listOfMissingFiles->SetName("MissingFiles"); if (fPlayer) fPlayer->AddOutputObject(listOfMissingFiles); } if (fPlayer->GetPacketizer()) { Int_t ret = fPlayer->GetPacketizer()->AddProcessed(sl, status, 0, &listOfMissingFiles); if (ret > 0) fPlayer->GetPacketizer()->MarkBad(sl, status, &listOfMissingFiles); // This object is now owned by the packetizer status = 0; } } else { fPlayer->AddEventsProcessed(events); } } SafeDelete(status); if (!TestBit(TProof::kIsMaster)) Emit("StopProcess(Bool_t)", abort); break; } case kPROOF_SUBMERGER: { PDB(kGlobal,2) Info("HandleInputMessage", "kPROOF_SUBMERGER: enter"); HandleSubmerger(mess, sl); } break; case kPROOF_GETSLAVEINFO: { PDB(kGlobal,2) Info("HandleInputMessage", "kPROOF_GETSLAVEINFO: enter"); Bool_t active = (GetListOfActiveSlaves()->FindObject(sl) != 0); Bool_t bad = (GetListOfBadSlaves()->FindObject(sl) != 0); TList* tmpinfo = 0; (*mess) >> tmpinfo; if (tmpinfo == 0) { Error("HandleInputMessage", "kPROOF_GETSLAVEINFO: no list received!"); } else { tmpinfo->SetOwner(kFALSE); Int_t nentries = tmpinfo->GetSize(); for (Int_t i=0; i<nentries; i++) { TSlaveInfo* slinfo = dynamic_cast<TSlaveInfo*>(tmpinfo->At(i)); if (slinfo) { // Check if we have already a instance for this worker TIter nxw(fSlaveInfo); TSlaveInfo *ourwi = 0; while ((ourwi = (TSlaveInfo *)nxw())) { if (!strcmp(ourwi->GetOrdinal(), slinfo->GetOrdinal())) { ourwi->SetSysInfo(slinfo->GetSysInfo()); break; } } if (!ourwi) { fSlaveInfo->Add(slinfo); } else { slinfo = ourwi; } if (slinfo->fStatus != TSlaveInfo::kBad) { if (!active) slinfo->SetStatus(TSlaveInfo::kNotActive); if (bad) slinfo->SetStatus(TSlaveInfo::kBad); } if (sl->GetMsd() && (strlen(sl->GetMsd()) > 0)) slinfo->fMsd = sl->GetMsd(); } } delete tmpinfo; rc = 1; } } break; case kPROOF_VALIDATE_DSET: { PDB(kGlobal,2) Info("HandleInputMessage", "kPROOF_VALIDATE_DSET: enter"); TDSet* dset = 0; (*mess) >> dset; if (!fDSet) Error("HandleInputMessage", "kPROOF_VALIDATE_DSET: fDSet not set"); else fDSet->Validate(dset); delete dset; } break; case kPROOF_DATA_READY: { PDB(kGlobal,2) Info("HandleInputMessage", "kPROOF_DATA_READY: enter"); Bool_t dataready = kFALSE; Long64_t totalbytes, bytesready; (*mess) >> dataready >> totalbytes >> bytesready; fTotalBytes += totalbytes; fBytesReady += bytesready; if (dataready == kFALSE) fDataReady = dataready; } break; case kPROOF_PING: // do nothing (ping is already acknowledged) break; case kPROOF_MESSAGE: { PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_MESSAGE: enter"); // We have received the unique tag and save it as name of this object TString msg; (*mess) >> msg; Bool_t lfeed = kTRUE; if ((mess->BufferSize() > mess->Length())) (*mess) >> lfeed; if (TestBit(TProof::kIsClient)) { if (fSync) { // Notify locally fprintf(stderr,"%s%c", msg.Data(), (lfeed ? '\n' : '\r')); } else { // Notify locally taking care of redirection, windows logs, ... NotifyLogMsg(msg, (lfeed ? "\n" : "\r")); } } else { // The message is logged for debugging purposes. fprintf(stderr,"%s%c", msg.Data(), (lfeed ? '\n' : '\r')); if (gProofServ) { // We hide it during normal operations gProofServ->FlushLogFile(); // And send the message one level up gProofServ->SendAsynMessage(msg, lfeed); } } } break; case kPROOF_VERSARCHCOMP: { TString vac; (*mess) >> vac; PDB(kGlobal,2) Info("HandleInputMessage","kPROOF_VERSARCHCOMP: %s", vac.Data()); Int_t from = 0; TString vers, archcomp; if (vac.Tokenize(vers, from, "|")) vac.Tokenize(archcomp, from, "|"); sl->SetArchCompiler(archcomp); vers.ReplaceAll(":","|"); sl->SetROOTVersion(vers); } break; default: { Error("HandleInputMessage", "unknown command received from '%s' (what = %d)", (sl ? sl->GetOrdinal() : "undef"), what); } break; } // Cleanup if (delete_mess) delete mess; // We are done successfully return rc; } //______________________________________________________________________________ void TProof::HandleSubmerger(TMessage *mess, TSlave *sl) { // Process a message of type kPROOF_SUBMERGER // Message sub-type Int_t type = 0; (*mess) >> type; TSocket *s = sl->GetSocket(); switch (type) { case kOutputSent: { if (IsEndMaster()) { Int_t merger_id = -1; (*mess) >> merger_id; PDB(kSubmerger, 2) Info("HandleSubmerger", "kOutputSent: Worker %s:%d:%s had sent its output to merger #%d", sl->GetName(), sl->GetPort(), sl->GetOrdinal(), merger_id); if (!fMergers || fMergers->GetSize() <= merger_id) { Error("HandleSubmerger", "kOutputSize: #%d not in list ", merger_id); break; } TMergerInfo * mi = (TMergerInfo *) fMergers->At(merger_id); mi->SetMergedWorker(); if (mi->AreAllWorkersMerged()) { mi->Deactivate(); if (GetActiveMergersCount() == 0) { fMergers->Clear(); delete fMergers; fMergersSet = kFALSE; fMergersCount = -1; fLastAssignedMerger = 0; PDB(kSubmerger, 2) Info("HandleSubmerger", "all mergers removed ... "); } } } else { PDB(kSubmerger, 2) Error("HandleSubmerger","kOutputSent: received not on endmaster!"); } } break; case kMergerDown: { Int_t merger_id = -1; (*mess) >> merger_id; PDB(kSubmerger, 2) Info("HandleSubmerger", "kMergerDown: #%d ", merger_id); if (!fMergers || fMergers->GetSize() <= merger_id) { Error("HandleSubmerger", "kMergerDown: #%d not in list ", merger_id); break; } TMergerInfo * mi = (TMergerInfo *) fMergers->At(merger_id); if (!mi->IsActive()) { break; } else { mi->Deactivate(); } // Stop the invalid merger in the case it is still listening TMessage stop(kPROOF_SUBMERGER); stop << Int_t(kStopMerging); stop << 0; s->Send(stop); // Ask for results from merger (only original results from this node as worker are returned) AskForOutput(mi->GetMerger()); // Ask for results from all workers assigned to this merger TIter nxo(mi->GetWorkers()); TObject * o = 0; while ((o = nxo())) { AskForOutput((TSlave *)o); } PDB(kSubmerger, 2) Info("HandleSubmerger", "kMergerDown: exit", merger_id); } break; case kOutputSize: { if (IsEndMaster()) { PDB(kSubmerger, 2) Info("HandleSubmerger", "worker %s reported as finished ", sl->GetOrdinal()); const char *prefix = gProofServ ? gProofServ->GetPrefix() : "Lite-0"; if (!fFinalizationRunning) { Info("HandleSubmerger", "finalization on %s started ...", prefix); fFinalizationRunning = kTRUE; } Int_t output_size = 0; Int_t merging_port = 0; (*mess) >> output_size >> merging_port; PDB(kSubmerger, 2) Info("HandleSubmerger", "kOutputSize: Worker %s:%d:%s reports %d output objects (+ available port %d)", sl->GetName(), sl->GetPort(), sl->GetOrdinal(), output_size, merging_port); TString msg; if (!fMergersSet) { // First pass - setting number of mergers according to user or dynamically fMergersCount = -1; // No mergers used if not set by user TParameter<Int_t> *mc = dynamic_cast<TParameter<Int_t> *>(GetParameter("PROOF_UseMergers")); if (mc) fMergersCount = mc->GetVal(); // Value set by user // Mergers count specified by user but not valid if (fMergersCount < 0 || (fMergersCount > (GetNumberOfSlaves()/2) )) { msg.Form("%s: Invalid request: cannot start %d mergers for %d workers", prefix, fMergersCount, GetNumberOfSlaves()); if (gProofServ) gProofServ->SendAsynMessage(msg); else Printf("%s",msg.Data()); fMergersCount = 0; } // Mergers count will be set dynamically if (fMergersCount == 0) { if (GetNumberOfSlaves() > 1) fMergersCount = TMath::Nint(TMath::Sqrt(GetNumberOfSlaves())); if (fMergersCount > 1) msg.Form("%s: Number of mergers set dynamically to %d (for %d workers)", prefix, fMergersCount, GetNumberOfSlaves()); else { msg.Form("%s: No mergers will be used for %d workers", prefix, GetNumberOfSlaves()); fMergersCount = -1; } if (gProofServ) gProofServ->SendAsynMessage(msg); else Printf("%s",msg.Data()); } else { msg.Form("%s: Number of mergers set by user to %d (for %d workers)", prefix, fMergersCount, GetNumberOfSlaves()); if (gProofServ) gProofServ->SendAsynMessage(msg); else Printf("%s",msg.Data()); } if (fMergersCount > 0) { fMergers = new TList(); fLastAssignedMerger = 0; // Total number of workers, which will not act as mergers ('pure workers') fWorkersToMerge = (GetNumberOfSlaves() - fMergersCount); // Establish the first merger if (!CreateMerger(sl, merging_port)) { // Cannot establish first merger AskForOutput(sl); fWorkersToMerge--; fMergersCount--; } if (IsLite()) fMergePrg.SetNWrks(fMergersCount); } else { AskForOutput(sl); } fMergersSet = kTRUE; } else { // Multiple pass if (fMergersCount == -1) { // No mergers. Workers send their outputs directly to master AskForOutput(sl); } else { if (fRedirectNext > 0 ) { RedirectWorker(s, sl, output_size); fRedirectNext--; } else { if (fMergersCount > fMergers->GetSize()) { // Still not enough mergers established if (!CreateMerger(sl, merging_port)) { // Cannot establish a merger AskForOutput(sl); fWorkersToMerge--; fMergersCount--; } } else RedirectWorker(s, sl, output_size); } } } } else { Error("HandleSubMerger","kOutputSize received not on endmaster!"); } } break; } } //______________________________________________________________________________ void TProof::RedirectWorker(TSocket *s, TSlave * sl, Int_t output_size) { // Redirect output of worker sl to some merger Int_t merger_id = FindNextFreeMerger(); if (merger_id == -1) { // No free merger (probably it had crashed before) AskForOutput(sl); } else { TMessage sendoutput(kPROOF_SUBMERGER); sendoutput << Int_t(kSendOutput); PDB(kSubmerger, 2) Info("RedirectWorker", "redirecting worker %s to merger %d", sl->GetOrdinal(), merger_id); PDB(kSubmerger, 2) Info("RedirectWorker", "redirecting output to merger #%d", merger_id); if (!fMergers || fMergers->GetSize() <= merger_id) { Error("RedirectWorker", "#%d not in list ", merger_id); return; } TMergerInfo * mi = (TMergerInfo *) fMergers->At(merger_id); TString hname = (IsLite()) ? "localhost" : mi->GetMerger()->GetName(); sendoutput << merger_id; sendoutput << hname; sendoutput << mi->GetPort(); s->Send(sendoutput); mi->AddMergedObjects(output_size); mi->AddWorker(sl); } } //______________________________________________________________________________ Int_t TProof::FindNextFreeMerger() { // Return a merger, which is both active and still accepts some workers to be // assigned to it. It works on the 'round-robin' basis. while (fLastAssignedMerger < fMergers->GetSize() && (!((TMergerInfo*)fMergers->At(fLastAssignedMerger))->IsActive() || ((TMergerInfo*)fMergers->At(fLastAssignedMerger))->AreAllWorkersAssigned())) { fLastAssignedMerger++; } if (fLastAssignedMerger == fMergers->GetSize()) { fLastAssignedMerger = 0; } else { return fLastAssignedMerger++; } while (fLastAssignedMerger < fMergers->GetSize() && (!((TMergerInfo*)fMergers->At(fLastAssignedMerger))->IsActive() || ((TMergerInfo*)fMergers->At(fLastAssignedMerger))->AreAllWorkersAssigned())) { fLastAssignedMerger++; } if (fLastAssignedMerger == fMergers->GetSize()) { return -1; } else { return fLastAssignedMerger++; } } //______________________________________________________________________________ void TProof::AskForOutput(TSlave *sl) { // Master asks for output from worker sl TMessage sendoutput(kPROOF_SUBMERGER); sendoutput << Int_t(kSendOutput); PDB(kSubmerger, 2) Info("AskForOutput", "worker %s was asked to send its output to master", sl->GetOrdinal()); sendoutput << -1; sendoutput << TString("master"); sendoutput << -1; sl->GetSocket()->Send(sendoutput); if (IsLite()) fMergePrg.IncreaseNWrks(); } //______________________________________________________________________________ void TProof::UpdateDialog() { // Final update of the progress dialog if (!fPlayer) return; // Handle abort ... if (fPlayer->GetExitStatus() == TVirtualProofPlayer::kAborted) { if (fSync) Info("UpdateDialog", "processing was aborted - %lld events processed", fPlayer->GetEventsProcessed()); if (GetRemoteProtocol() > 11) { // New format Progress(-1, fPlayer->GetEventsProcessed(), -1, -1., -1., -1., -1.); } else { Progress(-1, fPlayer->GetEventsProcessed()); } Emit("StopProcess(Bool_t)", kTRUE); } // Handle stop ... if (fPlayer->GetExitStatus() == TVirtualProofPlayer::kStopped) { if (fSync) Info("UpdateDialog", "processing was stopped - %lld events processed", fPlayer->GetEventsProcessed()); if (GetRemoteProtocol() > 25) { // New format Progress(-1, fPlayer->GetEventsProcessed(), -1, -1., -1., -1., -1., -1, -1, -1.); } else if (GetRemoteProtocol() > 11) { Progress(-1, fPlayer->GetEventsProcessed(), -1, -1., -1., -1., -1.); } else { Progress(-1, fPlayer->GetEventsProcessed()); } Emit("StopProcess(Bool_t)", kFALSE); } // Final update of the dialog box if (GetRemoteProtocol() > 25) { // New format EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t,Int_t,Int_t,Float_t)", 10, (Long64_t)(-1), (Long64_t)(-1), (Long64_t)(-1),(Float_t)(-1.),(Float_t)(-1.), (Float_t)(-1.),(Float_t)(-1.),(Int_t)(-1),(Int_t)(-1),(Float_t)(-1.)); } else if (GetRemoteProtocol() > 11) { // New format EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)", 7, (Long64_t)(-1), (Long64_t)(-1), (Long64_t)(-1), (Float_t)(-1.),(Float_t)(-1.),(Float_t)(-1.),(Float_t)(-1.)); } else { EmitVA("Progress(Long64_t,Long64_t)", 2, (Long64_t)(-1), (Long64_t)(-1)); } } //______________________________________________________________________________ void TProof::ActivateAsyncInput() { // Activate the a-sync input handler. TIter next(fSlaves); TSlave *sl; while ((sl = (TSlave*) next())) if (sl->GetInputHandler()) sl->GetInputHandler()->Add(); } //______________________________________________________________________________ void TProof::DeActivateAsyncInput() { // De-activate a-sync input handler. TIter next(fSlaves); TSlave *sl; while ((sl = (TSlave*) next())) if (sl->GetInputHandler()) sl->GetInputHandler()->Remove(); } //______________________________________________________________________________ Int_t TProof::GetActiveMergersCount() { // Get the active mergers count if (!fMergers) return 0; Int_t active_mergers = 0; TIter mergers(fMergers); TMergerInfo *mi = 0; while ((mi = (TMergerInfo *)mergers())) { if (mi->IsActive()) active_mergers++; } return active_mergers; } //______________________________________________________________________________ Bool_t TProof::CreateMerger(TSlave *sl, Int_t port) { // Create a new merger PDB(kSubmerger, 2) Info("CreateMerger", "worker %s will be merger ", sl->GetOrdinal()); PDB(kSubmerger, 2) Info("CreateMerger","Begin"); if (port <= 0) { PDB(kSubmerger,2) Info("CreateMerger", "cannot create merger on port %d - exit", port); return kFALSE; } Int_t mergersToCreate = fMergersCount - fMergers->GetSize(); // Number of pure workers, which are not simply divisible by mergers Int_t rest = fWorkersToMerge % mergersToCreate; // We add one more worker for each of the first 'rest' mergers being established if (rest > 0 && fMergers->GetSize() < rest) { rest = 1; } else { rest = 0; } Int_t workers = (fWorkersToMerge / mergersToCreate) + rest; TMergerInfo * merger = new TMergerInfo(sl, port, workers); TMessage bemerger(kPROOF_SUBMERGER); bemerger << Int_t(kBeMerger); bemerger << fMergers->GetSize(); bemerger << workers; sl->GetSocket()->Send(bemerger); PDB(kSubmerger,2) Info("CreateMerger", "merger #%d (port: %d) for %d workers started", fMergers->GetSize(), port, workers); fMergers->Add(merger); fWorkersToMerge = fWorkersToMerge - workers; fRedirectNext = workers / 2; PDB(kSubmerger, 2) Info("CreateMerger", "exit"); return kTRUE; } //______________________________________________________________________________ void TProof::MarkBad(TSlave *wrk, const char *reason) { // Add a bad slave server to the bad slave list and remove it from // the active list and from the two monitor objects. Assume that the work // done by this worker was lost and ask packerizer to reassign it. R__LOCKGUARD2(fCloseMutex); // We may have been invalidated in the meanwhile: nothing to do in such a case if (!IsValid()) return; if (!wrk) { Error("MarkBad", "worker instance undefined: protocol error? "); return; } // Local URL static TString thisurl; if (thisurl.IsNull()) { if (IsMaster()) { Int_t port = gEnv->GetValue("ProofServ.XpdPort",-1); thisurl = (port > 0) ? Form("%s:%d", TUrl(gSystem->HostName()).GetHostFQDN(), port) : TUrl(gSystem->HostName()).GetHostFQDN(); } else { thisurl = Form("%s@%s:%d", fUrl.GetUser(), fUrl.GetHost(), fUrl.GetPort()); } } if (!reason || strcmp(reason, kPROOF_TerminateWorker)) { // Message for notification const char *mastertype = (gProofServ && gProofServ->IsTopMaster()) ? "top master" : "master"; TString src = IsMaster() ? Form("%s at %s", mastertype, thisurl.Data()) : "local session"; TString msg(Form("\n +++ Message from %s : ", src.Data())); msg += Form("marking %s:%d (%s) as bad\n +++ Reason: %s", wrk->GetName(), wrk->GetPort(), wrk->GetOrdinal(), (reason && strlen(reason)) ? reason : "unknown"); Info("MarkBad", "%s", msg.Data()); // Notify one level up, if the case // Add some hint for diagnostics if (gProofServ) { msg += Form("\n\n +++ Most likely your code crashed on worker %s at %s:%d.\n", wrk->GetOrdinal(), wrk->GetName(), wrk->GetPort()); } else { msg = Form("\n\n +++ Most likely your code crashed\n"); } msg += Form(" +++ Please check the session logs for error messages either using\n"); msg += Form(" +++ the 'Show logs' button or executing\n"); msg += Form(" +++\n"); if (gProofServ) { msg += Form(" +++ root [] TProof::Mgr(\"%s\")->GetSessionLogs()->Display(\"%s\",0)\n\n", thisurl.Data(), wrk->GetOrdinal()); gProofServ->SendAsynMessage(msg, kTRUE); } else { msg += Form(" +++ root [] TProof::Mgr(\"%s\")->GetSessionLogs()->Display(\"*\")\n\n", thisurl.Data()); Printf("%s", msg.Data()); } } else if (reason) { if (gDebug > 0) { Info("MarkBad", "worker %s at %s:%d asked to terminate", wrk->GetOrdinal(), wrk->GetName(), wrk->GetPort()); } } if (IsMaster() && reason) { if (strcmp(reason, kPROOF_TerminateWorker)) { // if the reason was not a planned termination TList *listOfMissingFiles = 0; if (!(listOfMissingFiles = (TList *)GetOutput("MissingFiles"))) { listOfMissingFiles = new TList(); listOfMissingFiles->SetName("MissingFiles"); if (fPlayer) fPlayer->AddOutputObject(listOfMissingFiles); } // If a query is being processed, assume that the work done by // the worker was lost and needs to be reassigned. TVirtualPacketizer *packetizer = fPlayer ? fPlayer->GetPacketizer() : 0; if (packetizer) { // the worker was lost so do resubmit the packets packetizer->MarkBad(wrk, 0, &listOfMissingFiles); } } else { // Tell the coordinator that we are gone if (gProofServ) { TString ord(wrk->GetOrdinal()); Int_t id = ord.Last('.'); if (id != kNPOS) ord.Remove(0, id+1); gProofServ->ReleaseWorker(ord.Data()); } } } fActiveSlaves->Remove(wrk); FindUniqueSlaves(); fAllMonitor->Remove(wrk->GetSocket()); fActiveMonitor->Remove(wrk->GetSocket()); fSendGroupView = kTRUE; if (IsMaster()) { if (reason && !strcmp(reason, kPROOF_TerminateWorker)) { // if the reason was a planned termination then delete the worker and // remove it from all the lists fSlaves->Remove(wrk); fBadSlaves->Remove(wrk); fActiveSlaves->Remove(wrk); fInactiveSlaves->Remove(wrk); fUniqueSlaves->Remove(wrk); fAllUniqueSlaves->Remove(wrk); fNonUniqueMasters->Remove(wrk); delete wrk; } else { fBadSlaves->Add(wrk); wrk->Close(); } // Update session workers files SaveWorkerInfo(); } else { // On clients the proof session should be removed from the lists // and deleted, since it is not valid anymore fSlaves->Remove(wrk); if (fManager) fManager->DiscardSession(this); } } //______________________________________________________________________________ void TProof::MarkBad(TSocket *s, const char *reason) { // Add slave with socket s to the bad slave list and remove if from // the active list and from the two monitor objects. R__LOCKGUARD2(fCloseMutex); // We may have been invalidated in the meanwhile: nothing to do in such a case if (!IsValid()) return; TSlave *wrk = FindSlave(s); MarkBad(wrk, reason); } //______________________________________________________________________________ void TProof::TerminateWorker(TSlave *wrk) { // Ask an active worker 'wrk' to terminate, i.e. to shutdown if (!wrk) { Warning("TerminateWorker", "worker instance undefined: protocol error? "); return; } // Send stop message if (wrk->GetSocket() && wrk->GetSocket()->IsValid()) { TMessage mess(kPROOF_STOP); wrk->GetSocket()->Send(mess); } else { if (gDebug > 0) Info("TerminateWorker", "connection to worker is already down: cannot" " send termination message"); } // This is a bad worker from now on MarkBad(wrk, kPROOF_TerminateWorker); } //______________________________________________________________________________ void TProof::TerminateWorker(const char *ord) { // Ask an active worker 'ord' to terminate, i.e. to shutdown if (ord && strlen(ord) > 0) { Bool_t all = (ord[0] == '*') ? kTRUE : kFALSE; if (IsMaster()) { TIter nxw(fSlaves); TSlave *wrk = 0; while ((wrk = (TSlave *)nxw())) { if (all || !strcmp(wrk->GetOrdinal(), ord)) { TerminateWorker(wrk); if (!all) break; } } } else { TMessage mess(kPROOF_STOP); mess << TString(ord); Broadcast(mess); } } } //______________________________________________________________________________ Int_t TProof::Ping() { // Ping PROOF. Returns 1 if master server responded. return Ping(kActive); } //______________________________________________________________________________ Int_t TProof::Ping(ESlaves list) { // Ping PROOF slaves. Returns the number of slaves that responded. TList *slaves = 0; if (list == kAll) slaves = fSlaves; if (list == kActive) slaves = fActiveSlaves; if (list == kUnique) slaves = fUniqueSlaves; if (list == kAllUnique) slaves = fAllUniqueSlaves; if (slaves->GetSize() == 0) return 0; int nsent = 0; TIter next(slaves); TSlave *sl; while ((sl = (TSlave *)next())) { if (sl->IsValid()) { if (sl->Ping() == -1) { MarkBad(sl, "ping unsuccessful"); } else { nsent++; } } } return nsent; } //______________________________________________________________________________ void TProof::Touch() { // Ping PROOF slaves. Returns the number of slaves that responded. TList *slaves = fSlaves; if (slaves->GetSize() == 0) return; TIter next(slaves); TSlave *sl; while ((sl = (TSlave *)next())) { if (sl->IsValid()) { sl->Touch(); } } return; } //______________________________________________________________________________ void TProof::Print(Option_t *option) const { // Print status of PROOF cluster. TString secCont; if (TestBit(TProof::kIsClient)) { Printf("Connected to: %s (%s)", GetMaster(), IsValid() ? "valid" : "invalid"); Printf("Port number: %d", GetPort()); Printf("User: %s", GetUser()); if (gROOT->GetSvnRevision() > 0) Printf("ROOT version|rev: %s|r%d", gROOT->GetVersion(), gROOT->GetSvnRevision()); else Printf("ROOT version: %s", gROOT->GetVersion()); Printf("Architecture-Compiler: %s-%s", gSystem->GetBuildArch(), gSystem->GetBuildCompilerVersion()); TSlave *sl = (TSlave *)fActiveSlaves->First(); if (sl) { TString sc; if (sl->GetSocket()->GetSecContext()) Printf("Security context: %s", sl->GetSocket()->GetSecContext()->AsString(sc)); Printf("Proofd protocol version: %d", sl->GetSocket()->GetRemoteProtocol()); } else { Printf("Security context: Error - No connection"); Printf("Proofd protocol version: Error - No connection"); } Printf("Client protocol version: %d", GetClientProtocol()); Printf("Remote protocol version: %d", GetRemoteProtocol()); Printf("Log level: %d", GetLogLevel()); Printf("Session unique tag: %s", IsValid() ? GetSessionTag() : ""); Printf("Default data pool: %s", IsValid() ? GetDataPoolUrl() : ""); if (IsValid()) const_cast<TProof*>(this)->SendPrint(option); } else { const_cast<TProof*>(this)->AskStatistics(); if (IsParallel()) Printf("*** Master server %s (parallel mode, %d workers):", gProofServ->GetOrdinal(), GetParallel()); else Printf("*** Master server %s (sequential mode):", gProofServ->GetOrdinal()); Printf("Master host name: %s", gSystem->HostName()); Printf("Port number: %d", GetPort()); if (strlen(gProofServ->GetGroup()) > 0) { Printf("User/Group: %s/%s", GetUser(), gProofServ->GetGroup()); } else { Printf("User: %s", GetUser()); } TString ver(gROOT->GetVersion()); if (gROOT->GetSvnRevision() > 0) ver += Form("|r%d", gROOT->GetSvnRevision()); if (gSystem->Getenv("ROOTVERSIONTAG")) ver += Form("|%s", gSystem->Getenv("ROOTVERSIONTAG")); Printf("ROOT version|rev|tag: %s", ver.Data()); Printf("Architecture-Compiler: %s-%s", gSystem->GetBuildArch(), gSystem->GetBuildCompilerVersion()); Printf("Protocol version: %d", GetClientProtocol()); Printf("Image name: %s", GetImage()); Printf("Working directory: %s", gSystem->WorkingDirectory()); Printf("Config directory: %s", GetConfDir()); Printf("Config file: %s", GetConfFile()); Printf("Log level: %d", GetLogLevel()); Printf("Number of workers: %d", GetNumberOfSlaves()); Printf("Number of active workers: %d", GetNumberOfActiveSlaves()); Printf("Number of unique workers: %d", GetNumberOfUniqueSlaves()); Printf("Number of inactive workers: %d", GetNumberOfInactiveSlaves()); Printf("Number of bad workers: %d", GetNumberOfBadSlaves()); Printf("Total MB's processed: %.2f", float(GetBytesRead())/(1024*1024)); Printf("Total real time used (s): %.3f", GetRealTime()); Printf("Total CPU time used (s): %.3f", GetCpuTime()); if (TString(option).Contains("a", TString::kIgnoreCase) && GetNumberOfSlaves()) { Printf("List of workers:"); TList masters; TIter nextslave(fSlaves); while (TSlave* sl = dynamic_cast<TSlave*>(nextslave())) { if (!sl->IsValid()) continue; if (sl->GetSlaveType() == TSlave::kSlave) { sl->Print(option); } else if (sl->GetSlaveType() == TSlave::kMaster) { TMessage mess(kPROOF_PRINT); mess.WriteString(option); if (sl->GetSocket()->Send(mess) == -1) const_cast<TProof*>(this)->MarkBad(sl, "could not send kPROOF_PRINT request"); else masters.Add(sl); } else { Error("Print", "TSlave is neither Master nor Worker"); R__ASSERT(0); } } const_cast<TProof*>(this)->Collect(&masters, fCollectTimeout); } } } //______________________________________________________________________________ Long64_t TProof::Process(TDSet *dset, const char *selector, Option_t *option, Long64_t nentries, Long64_t first) { // Process a data set (TDSet) using the specified selector (.C) file. // Entry- or event-lists should be set in the data set object using // TDSet::SetEntryList. // The return value is -1 in case of error and TSelector::GetStatus() in // in case of success. if (!IsValid() || !fPlayer) return -1; // Set PROOF to running state SetRunStatus(TProof::kRunning); // Resolve query mode fSync = (GetQueryMode(option) == kSync); TString opt(option); if (fSync && (!IsIdle() || IsWaiting())) { // Already queued or processing queries: switch to asynchronous mode Info("Process", "session is in waiting or processing status: switch to asynchronous mode"); fSync = kFALSE; opt.ReplaceAll("SYNC",""); opt += "ASYN"; } // Cleanup old temporary datasets if ((IsIdle() && !IsWaiting()) && fRunningDSets && fRunningDSets->GetSize() > 0) { fRunningDSets->SetOwner(kTRUE); fRunningDSets->Delete(); } // deactivate the default application interrupt handler // ctrl-c's will be forwarded to PROOF to stop the processing TSignalHandler *sh = 0; if (fSync) { if (gApplication) sh = gSystem->RemoveSignalHandler(gApplication->GetSignalHandler()); } Long64_t rv = fPlayer->Process(dset, selector, opt.Data(), nentries, first); if (fSync) { // reactivate the default application interrupt handler if (sh) gSystem->AddSignalHandler(sh); } return rv; } //______________________________________________________________________________ Long64_t TProof::Process(TFileCollection *fc, const char *selector, Option_t *option, Long64_t nentries, Long64_t first) { // Process a data set (TFileCollection) using the specified selector (.C) file. // The default tree is analyzed (i.e. the first one found). To specify another // tree, the default tree can be changed using TFileCollection::SetDefaultMetaData . // The return value is -1 in case of error and TSelector::GetStatus() in // in case of success. if (!IsValid() || !fPlayer) return -1; if (fProtocol < 17) { Info("Process", "server version < 5.18/00:" " processing of TFileCollection not supported"); return -1; } // We include the TFileCollection to the input list and we create a // fake TDSet with infor about it TDSet *dset = new TDSet(Form("TFileCollection:%s", fc->GetName()), 0, 0, ""); fPlayer->AddInput(fc); Long64_t retval = Process(dset, selector, option, nentries, first); fPlayer->GetInputList()->Remove(fc); // To avoid problems in future // Cleanup if (IsLite() && !fSync) { if (!fRunningDSets) fRunningDSets = new TList; fRunningDSets->Add(dset); } else { delete dset; } return retval; } //______________________________________________________________________________ Long64_t TProof::Process(const char *dsetname, const char *selector, Option_t *option, Long64_t nentries, Long64_t first, TObject *elist) { // Process a dataset which is stored on the master with name 'dsetname'. // The syntax for dsetname is name[#[dir/]objname], e.g. // "mydset" analysis of the first tree in the top dir of the dataset // named "mydset" // "mydset#T" analysis tree "T" in the top dir of the dataset // named "mydset" // "mydset#adir/T" analysis tree "T" in the dir "adir" of the dataset // named "mydset" // "mydset#adir/" analysis of the first tree in the dir "adir" of the // dataset named "mydset" // The component 'name' in its more general form contains also the group and // user name following "/<group>/<user>/<dsname>". Each of these components // can contain one or more wildcards '*', in which case all the datasets matching // the expression are added together as a global dataset (wildcard support has // been added in version 5.27/02). // The last argument 'elist' specifies an entry- or event-list to be used as // event selection. // It is also possible (starting w/ version 5.27/02) to run on multiple datasets // at once in a more flexible way that the one provided by wildcarding. There // are three possibilities: // 1) specifying the dataset names separated by the OR operator '|', e.g. // dsetname = "<dset1>|<dset2>|<dset3>|..." // in this case the datasets are a seen as a global unique dataset // 2) specifying the dataset names separated by a ',' or a ' ', e.g. // dsetname = "<dset1>,<dset2> <dset3>,..." // in this case the datasets are processed one after the other and the // selector is notified when switching dataset via a bit in the current // processed element. // 3) giving the path of a textfile where the dataset names are specified // on one or multiple lines; the lines found are joined as in 1), unless // the filepath is followed by a ',' (i.e. p->Process("datasets.txt,",...) // with the dataset names listed in 'datasets.txt') in which case they are // treated as in 2); the file is open in raw mode with TFile::Open and // therefore it cane be remote, e.g. on a Web server. // Each <dsetj> has the format specified above for the single dataset processing, // included wildcarding (the name of the tree and subdirectory must be same for // all the datasets). // In the case of multiple datasets, 'elist' is treated a global entry list. // It is possible to specify per-dataset entry lists using the syntax // "mydset[#adir/[T]]?enl=entrylist" // or // "mydset[#adir/[T]]<<entrylist" // Here 'entrylist' is a tag identifying, in the order : // i. a named entry-list in the input list or in the input data list // ii. a named entry-list in memory (in gDirectory) // iii. the path of a file containing the entry-list to be used // In the case ii) and iii) the entry-list object(s) is(are) added to the input // data list. // The return value is -1 in case of error and TSelector::GetStatus() in // in case of success. if (fProtocol < 13) { Info("Process", "processing 'by name' not supported by the server"); return -1; } TString dsname, fname(dsetname); // If the 'dsetname' corresponds to an existing and readable file we will try to // interpretate its content as names of datasets to be processed. One line can contain // more datasets, separated by ',' or '|'. By default the dataset lines will be added // (i.e. joined as in option '|'); if the file name ends with ',' the dataset lines are // joined with ','. const char *separator = (fname.EndsWith(",")) ? "," : "|"; if (!strcmp(separator, ",") || fname.EndsWith("|")) fname.Remove(fname.Length()-1, 1); if (!(gSystem->AccessPathName(fname, kReadPermission))) { TUrl uf(fname, kTRUE); uf.SetOptions(TString::Format("%sfiletype=raw", uf.GetOptions())); TFile *f = TFile::Open(uf.GetUrl()); if (f && !(f->IsZombie())) { const Int_t blen = 8192; char buf[blen]; Long64_t rest = f->GetSize(); while (rest > 0) { Long64_t len = (rest > blen - 1) ? blen - 1 : rest; if (f->ReadBuffer(buf, len)) { Error("Process", "problems reading from file '%s'", fname.Data()); dsname = ""; break; } buf[len] = '\0'; dsname += buf; rest -= len; } f->Close(); SafeDelete(f); // We fail if a failure occured if (rest > 0) return -1; } else { Error("Process", "could not open file '%s'", fname.Data()); return -1; } } if (dsname.IsNull()) { dsname = dsetname; } else { // Remove trailing '\n' if (dsname.EndsWith("\n")) dsname.Remove(dsname.Length()-1, 1); // Replace all '\n' with the proper separator dsname.ReplaceAll("\n", separator); if (gDebug > 0) { Info("Process", "processing multi-dataset read from file '%s':", fname.Data()); Info("Process", " '%s'", dsname.Data()); } } TString names(dsname), name, enl, newname; // If multi-dataset check if server supports it if (fProtocol < 28 && names.Index(TRegexp("[, |]")) != kNPOS) { Info("Process", "multi-dataset processing not supported by the server"); return -1; } TEntryList *el = 0; TString dsobj, dsdir; Int_t from = 0; while (names.Tokenize(name, from, "[, |]")) { newname = name; // Extract the specific entry-list, if any enl = ""; Int_t ienl = name.Index("?enl="); if (ienl == kNPOS) { ienl = name.Index("<<"); if (ienl != kNPOS) { newname.Remove(ienl); ienl += strlen("<<"); } } else { newname.Remove(ienl); ienl += strlen("?enl="); } // Check the name syntax first TString obj, dir("/"); Int_t idxc = newname.Index("#"); if (idxc != kNPOS) { Int_t idxs = newname.Index("/", 1, idxc, TString::kExact); if (idxs != kNPOS) { obj = newname(idxs+1, newname.Length()); dir = newname(idxc+1, newname.Length()); dir.Remove(dir.Index("/") + 1); newname.Remove(idxc); } else { obj = newname(idxc+1, newname.Length()); newname.Remove(idxc); } } else if (newname.Index(":") != kNPOS && newname.Index("://") == kNPOS) { // protection against using ':' instead of '#' Error("Process", "bad name syntax (%s): please use" " a '#' after the dataset name", name.Data()); dsname.ReplaceAll(name, ""); continue; } if (dsobj.IsNull() && dsdir.IsNull()) { // The first one specifies obj and dir dsobj = obj; dsdir = dir; } else if (obj != dsobj || dir != dsdir) { // Inconsistent specification: not supported Warning("Process", "'obj' or 'dir' specification not consistent w/ the first given: ignore"); } // Process the entry-list name, if any if (ienl != kNPOS) { // Get entrylist name or path enl = name(ienl, name.Length()); // If not in the input list ... el = (GetInputList()) ? dynamic_cast<TEntryList *>(GetInputList()->FindObject(enl)) : 0; // ... check the heap if (!el && gDirectory) { if ((el = dynamic_cast<TEntryList *>(gDirectory->FindObject(enl)))) { // Add to the input list (input data not available on master where // this info will be processed) if (fProtocol >= 28) { if (!(GetInputList()->FindObject(el->GetName()))) AddInput(el); } } } // If not in the heap, check a file, if any if (!el) { if (!gSystem->AccessPathName(enl)) { TFile *f = TFile::Open(enl); if (f && !(f->IsZombie()) && f->GetListOfKeys()) { TIter nxk(f->GetListOfKeys()); TKey *k = 0; while ((k = (TKey *) nxk())) { if (!strcmp(k->GetClassName(), "TEntryList")) { if (!el) { if ((el = dynamic_cast<TEntryList *>(f->Get(k->GetName())))) { // Add to the input list (input data not available on master where // this info will be processed) if (fProtocol >= 28) { if (!(GetInputList()->FindObject(el->GetName()))) { el = (TEntryList *) el->Clone(); AddInput(el); } } else { el = (TEntryList *) el->Clone(); } } } else if (strcmp(el->GetName(), k->GetName())) { Warning("Process", "multiple entry lists found in file '%s': the first one is taken;\n" "if this is not what you want, load first the content in memory" "and select it by name ", enl.Data()); } } } } else { Warning("Process","file '%s' cannot be open or is empty - ignoring", enl.Data()); } } } // Transmit the information if (fProtocol >= 28) { newname += "?enl="; if (el) { // An entry list object is avalaible in the input list: add its name newname += el->GetName(); } else { // The entry list object was not found: send the name, the future entry list manager will // find it on the server side newname += enl; } } } // Adjust the name for this dataset dsname.ReplaceAll(name, newname); } // Create the dataset object TDSet *dset = new TDSet(dsname, dsobj, dsdir); // Set entry list if (el && fProtocol < 28) { dset->SetEntryList(el); } else { dset->SetEntryList(elist); } // Run Long64_t retval = Process(dset, selector, option, nentries, first); // Cleanup if (IsLite() && !fSync) { if (!fRunningDSets) fRunningDSets = new TList; fRunningDSets->Add(dset); } else { delete dset; } return retval; } //______________________________________________________________________________ Long64_t TProof::Process(const char *selector, Long64_t n, Option_t *option) { // Generic (non-data based) selector processing: the Process() method of the // specified selector (.C) is called 'n' times. // The return value is -1 in case of error and TSelector::GetStatus() in // in case of success. if (!IsValid()) return -1; if (fProtocol < 16) { Info("Process", "server version < 5.17/04: generic processing not supported"); return -1; } // Fake data set TDSet *dset = new TDSet; dset->SetBit(TDSet::kEmpty); Long64_t retval = Process(dset, selector, option, n); // Cleanup if (IsLite() && !fSync) { if (!fRunningDSets) fRunningDSets = new TList; fRunningDSets->Add(dset); } else { delete dset; } return retval; } //______________________________________________________________________________ Int_t TProof::GetQueryReference(Int_t qry, TString &ref) { // Get reference for the qry-th query in fQueries (as // displayed by ShowQueries). ref = ""; if (qry > 0) { if (!fQueries) GetListOfQueries(); if (fQueries) { TIter nxq(fQueries); TQueryResult *qr = 0; while ((qr = (TQueryResult *) nxq())) if (qr->GetSeqNum() == qry) { ref = Form("%s:%s", qr->GetTitle(), qr->GetName()); return 0; } } } return -1; } //______________________________________________________________________________ Long64_t TProof::Finalize(Int_t qry, Bool_t force) { // Finalize the qry-th query in fQueries. // If force, force retrieval if the query is found in the local list // but has already been finalized (default kFALSE). // If query < 0, finalize current query. // Return 0 on success, -1 on error if (fPlayer) { if (qry > 0) { TString ref; if (GetQueryReference(qry, ref) == 0) { return Finalize(ref, force); } else { Info("Finalize", "query #%d not found", qry); } } else { // The last query return Finalize("", force); } } return -1; } //______________________________________________________________________________ Long64_t TProof::Finalize(const char *ref, Bool_t force) { // Finalize query with reference ref. // If force, force retrieval if the query is found in the local list // but has already been finalized (default kFALSE). // If ref = 0, finalize current query. // Return 0 on success, -1 on error if (fPlayer) { // Get the pointer to the query TQueryResult *qr = (ref && strlen(ref) > 0) ? fPlayer->GetQueryResult(ref) : GetQueryResult(); Bool_t retrieve = kFALSE; TString xref(ref); if (!qr) { if (!xref.IsNull()) { retrieve = kTRUE; } } else { if (qr->IsFinalized()) { if (force) { retrieve = kTRUE; } else { Info("Finalize","query already finalized:" " use Finalize(<qry>,kTRUE) to force new retrieval"); qr = 0; } } else { retrieve = kTRUE; xref.Form("%s:%s", qr->GetTitle(), qr->GetName()); } } if (retrieve) { Retrieve(xref.Data()); qr = fPlayer->GetQueryResult(xref.Data()); } if (qr) return fPlayer->Finalize(qr); } return -1; } //______________________________________________________________________________ Int_t TProof::Retrieve(Int_t qry, const char *path) { // Send retrieve request for the qry-th query in fQueries. // If path is defined save it to path. if (qry > 0) { TString ref; if (GetQueryReference(qry, ref) == 0) return Retrieve(ref, path); else Info("Retrieve", "query #%d not found", qry); } else { Info("Retrieve","positive argument required - do nothing"); } return -1; } //______________________________________________________________________________ Int_t TProof::Retrieve(const char *ref, const char *path) { // Send retrieve request for the query specified by ref. // If path is defined save it to path. // Generic method working for all queries known by the server. if (ref) { TMessage m(kPROOF_RETRIEVE); m << TString(ref); Broadcast(m, kActive); Collect(kActive, fCollectTimeout); // Archive it locally, if required if (path) { // Get pointer to query TQueryResult *qr = fPlayer ? fPlayer->GetQueryResult(ref) : 0; if (qr) { TFile *farc = TFile::Open(path,"UPDATE"); if (!(farc->IsOpen())) { Info("Retrieve", "archive file cannot be open (%s)", path); return 0; } farc->cd(); // Update query status qr->SetArchived(path); // Write to file qr->Write(); farc->Close(); SafeDelete(farc); } else { Info("Retrieve", "query not found after retrieve"); return -1; } } return 0; } return -1; } //______________________________________________________________________________ Int_t TProof::Remove(Int_t qry, Bool_t all) { // Send remove request for the qry-th query in fQueries. if (qry > 0) { TString ref; if (GetQueryReference(qry, ref) == 0) return Remove(ref, all); else Info("Remove", "query #%d not found", qry); } else { Info("Remove","positive argument required - do nothing"); } return -1; } //______________________________________________________________________________ Int_t TProof::Remove(const char *ref, Bool_t all) { // Send remove request for the query specified by ref. // If all = TRUE remove also local copies of the query, if any. // Generic method working for all queries known by the server. // This method can be also used to reset the list of queries // waiting to be processed: for that purpose use ref == "cleanupqueue". if (all) { // Remove also local copies, if any if (fPlayer) fPlayer->RemoveQueryResult(ref); } if (IsLite()) return 0; if (ref) { TMessage m(kPROOF_REMOVE); m << TString(ref); Broadcast(m, kActive); Collect(kActive, fCollectTimeout); return 0; } return -1; } //______________________________________________________________________________ Int_t TProof::Archive(Int_t qry, const char *path) { // Send archive request for the qry-th query in fQueries. if (qry > 0) { TString ref; if (GetQueryReference(qry, ref) == 0) return Archive(ref, path); else Info("Archive", "query #%d not found", qry); } else { Info("Archive","positive argument required - do nothing"); } return -1; } //______________________________________________________________________________ Int_t TProof::Archive(const char *ref, const char *path) { // Send archive request for the query specified by ref. // Generic method working for all queries known by the server. // If ref == "Default", path is understood as a default path for // archiving. if (ref) { TMessage m(kPROOF_ARCHIVE); m << TString(ref) << TString(path); Broadcast(m, kActive); Collect(kActive, fCollectTimeout); return 0; } return -1; } //______________________________________________________________________________ Int_t TProof::CleanupSession(const char *sessiontag) { // Send cleanup request for the session specified by tag. if (sessiontag) { TMessage m(kPROOF_CLEANUPSESSION); m << TString(sessiontag); Broadcast(m, kActive); Collect(kActive, fCollectTimeout); return 0; } return -1; } //_____________________________________________________________________________ void TProof::SetQueryMode(EQueryMode mode) { // Change query running mode to the one specified by 'mode'. fQueryMode = mode; if (gDebug > 0) Info("SetQueryMode","query mode is set to: %s", fQueryMode == kSync ? "Sync" : "Async"); } //______________________________________________________________________________ TProof::EQueryMode TProof::GetQueryMode(Option_t *mode) const { // Find out the query mode based on the current setting and 'mode'. EQueryMode qmode = fQueryMode; if (mode && (strlen(mode) > 0)) { TString m(mode); m.ToUpper(); if (m.Contains("ASYN")) { qmode = kAsync; } else if (m.Contains("SYNC")) { qmode = kSync; } } if (gDebug > 0) Info("GetQueryMode","query mode is set to: %s", qmode == kSync ? "Sync" : "Async"); return qmode; } //______________________________________________________________________________ Long64_t TProof::DrawSelect(TDSet *dset, const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t first) { // Execute the specified drawing action on a data set (TDSet). // Event- or Entry-lists should be set in the data set object using // TDSet::SetEntryList. // Returns -1 in case of error or number of selected events otherwise. if (!IsValid() || !fPlayer) return -1; // Make sure that asynchronous processing is not active if (!IsIdle()) { Info("DrawSelect","not idle, asynchronous Draw not supported"); return -1; } TString opt(option); Int_t idx = opt.Index("ASYN", 0, TString::kIgnoreCase); if (idx != kNPOS) opt.Replace(idx,4,""); return fPlayer->DrawSelect(dset, varexp, selection, opt, nentries, first); } //______________________________________________________________________________ Long64_t TProof::DrawSelect(const char *dsetname, const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t first, TObject *enl) { // Execute the specified drawing action on a data set which is stored on the // master with name 'dsetname'. // The syntax for dsetname is name[#[dir/]objname], e.g. // "mydset" analysis of the first tree in the top dir of the dataset // named "mydset" // "mydset#T" analysis tree "T" in the top dir of the dataset // named "mydset" // "mydset#adir/T" analysis tree "T" in the dir "adir" of the dataset // named "mydset" // "mydset#adir/" analysis of the first tree in the dir "adir" of the // dataset named "mydset" // The last argument 'enl' specifies an entry- or event-list to be used as // event selection. // The return value is -1 in case of error and TSelector::GetStatus() in // in case of success. if (fProtocol < 13) { Info("Process", "processing 'by name' not supported by the server"); return -1; } TString name(dsetname); TString obj; TString dir = "/"; Int_t idxc = name.Index("#"); if (idxc != kNPOS) { Int_t idxs = name.Index("/", 1, idxc, TString::kExact); if (idxs != kNPOS) { obj = name(idxs+1, name.Length()); dir = name(idxc+1, name.Length()); dir.Remove(dir.Index("/") + 1); name.Remove(idxc); } else { obj = name(idxc+1, name.Length()); name.Remove(idxc); } } else if (name.Index(":") != kNPOS && name.Index("://") == kNPOS) { // protection against using ':' instead of '#' Error("DrawSelect", "bad name syntax (%s): please use" " a '#' after the dataset name", dsetname); return -1; } TDSet *dset = new TDSet(name, obj, dir); // Set entry-list, if required dset->SetEntryList(enl); Long64_t retval = DrawSelect(dset, varexp, selection, option, nentries, first); delete dset; return retval; } //______________________________________________________________________________ void TProof::StopProcess(Bool_t abort, Int_t timeout) { // Send STOPPROCESS message to master and workers. PDB(kGlobal,2) Info("StopProcess","enter %d", abort); if (!IsValid()) return; // Flag that we have been stopped ERunStatus rst = abort ? TProof::kAborted : TProof::kStopped; SetRunStatus(rst); if (fPlayer) fPlayer->StopProcess(abort, timeout); // Stop any blocking 'Collect' request; on masters we do this only if // aborting; when stopping, we still need to receive the results if (TestBit(TProof::kIsClient) || abort) InterruptCurrentMonitor(); if (fSlaves->GetSize() == 0) return; // Notify the remote counterpart TSlave *sl; TIter next(fSlaves); while ((sl = (TSlave *)next())) if (sl->IsValid()) // Ask slave to progate the stop/abort request sl->StopProcess(abort, timeout); } //______________________________________________________________________________ void TProof::DisableGoAsyn() { // Signal to disable related switches Emit("DisableGoAsyn()"); } //______________________________________________________________________________ void TProof::GoAsynchronous() { // Send GOASYNC message to the master. if (!IsValid()) return; if (GetRemoteProtocol() < 22) { Info("GoAsynchronous", "functionality not supported by the server - ignoring"); return; } if (fSync && !IsIdle()) { TMessage m(kPROOF_GOASYNC); Broadcast(m); } else { Info("GoAsynchronous", "either idle or already in asynchronous mode - ignoring"); } } //______________________________________________________________________________ void TProof::RecvLogFile(TSocket *s, Int_t size) { // Receive the log file of the slave with socket s. const Int_t kMAXBUF = 16384; //32768 //16384 //65536; char buf[kMAXBUF]; // Append messages to active logging unit Int_t fdout = -1; if (!fLogToWindowOnly) { fdout = (fRedirLog) ? fileno(fLogFileW) : fileno(stdout); if (fdout < 0) { Warning("RecvLogFile", "file descriptor for outputs undefined (%d):" " will not log msgs", fdout); return; } lseek(fdout, (off_t) 0, SEEK_END); } Int_t left, rec, r; Long_t filesize = 0; while (filesize < size) { left = Int_t(size - filesize); if (left > kMAXBUF) left = kMAXBUF; rec = s->RecvRaw(&buf, left); filesize = (rec > 0) ? (filesize + rec) : filesize; if (!fLogToWindowOnly) { if (rec > 0) { char *p = buf; r = rec; while (r) { Int_t w; w = write(fdout, p, r); if (w < 0) { SysError("RecvLogFile", "error writing to unit: %d", fdout); break; } r -= w; p += w; } } else if (rec < 0) { Error("RecvLogFile", "error during receiving log file"); break; } } if (rec > 0) { buf[rec] = 0; EmitVA("LogMessage(const char*,Bool_t)", 2, buf, kFALSE); } } // If idle restore logs to main session window if (fRedirLog && IsIdle() && !TestBit(TProof::kIsMaster)) fRedirLog = kFALSE; } //______________________________________________________________________________ void TProof::NotifyLogMsg(const char *msg, const char *sfx) { // Notify locally 'msg' to the appropriate units (file, stdout, window) // If defined, 'sfx' is added after 'msg' (typically a line-feed); // Must have somenthing to notify Int_t len = 0; if (!msg || (len = strlen(msg)) <= 0) return; // Get suffix length if any Int_t lsfx = (sfx) ? strlen(sfx) : 0; // Append messages to active logging unit Int_t fdout = -1; if (!fLogToWindowOnly) { fdout = (fRedirLog) ? fileno(fLogFileW) : fileno(stdout); if (fdout < 0) { Warning("NotifyLogMsg", "file descriptor for outputs undefined (%d):" " will not notify msgs", fdout); return; } lseek(fdout, (off_t) 0, SEEK_END); } if (!fLogToWindowOnly) { // Write to output unit (stdout or a log file) if (len > 0) { char *p = (char *)msg; Int_t r = len; while (r) { Int_t w = write(fdout, p, r); if (w < 0) { SysError("NotifyLogMsg", "error writing to unit: %d", fdout); break; } r -= w; p += w; } // Add a suffix, if requested if (lsfx > 0) if (write(fdout, sfx, lsfx) != lsfx) SysError("NotifyLogMsg", "error writing to unit: %d", fdout); } } if (len > 0) { // Publish the message to the separate window (if the latter is missing // the message will just get lost) EmitVA("LogMessage(const char*,Bool_t)", 2, msg, kFALSE); } // If idle restore logs to main session window if (fRedirLog && IsIdle()) fRedirLog = kFALSE; } //______________________________________________________________________________ void TProof::LogMessage(const char *msg, Bool_t all) { // Log a message into the appropriate window by emitting a signal. PDB(kGlobal,1) Info("LogMessage","Enter ... %s, 'all: %s", msg ? msg : "", all ? "true" : "false"); if (gROOT->IsBatch()) { PDB(kGlobal,1) Info("LogMessage","GUI not started - use TProof::ShowLog()"); return; } if (msg) EmitVA("LogMessage(const char*,Bool_t)", 2, msg, all); // Re-position at the beginning of the file, if requested. // This is used by the dialog when it re-opens the log window to // provide all the session messages if (all) lseek(fileno(fLogFileR), (off_t) 0, SEEK_SET); const Int_t kMAXBUF = 32768; char buf[kMAXBUF]; Int_t len; do { while ((len = read(fileno(fLogFileR), buf, kMAXBUF-1)) < 0 && TSystem::GetErrno() == EINTR) TSystem::ResetErrno(); if (len < 0) { Error("LogMessage", "error reading log file"); break; } if (len > 0) { buf[len] = 0; EmitVA("LogMessage(const char*,Bool_t)", 2, buf, kFALSE); } } while (len > 0); } //______________________________________________________________________________ Int_t TProof::SendGroupView() { // Send to all active slaves servers the current slave group size // and their unique id. Returns number of active slaves. // Returns -1 in case of error. if (!IsValid()) return -1; if (TestBit(TProof::kIsClient)) return 0; if (!fSendGroupView) return 0; fSendGroupView = kFALSE; TIter next(fActiveSlaves); TSlave *sl; int bad = 0, cnt = 0, size = GetNumberOfActiveSlaves(); char str[32]; while ((sl = (TSlave *)next())) { snprintf(str, 32, "%d %d", cnt, size); if (sl->GetSocket()->Send(str, kPROOF_GROUPVIEW) == -1) { MarkBad(sl, "could not send kPROOF_GROUPVIEW message"); bad++; } else cnt++; } // Send the group view again in case there was a change in the // group size due to a bad slave if (bad) SendGroupView(); return GetNumberOfActiveSlaves(); } //______________________________________________________________________________ Bool_t TProof::GetFileInCmd(const char *cmd, TString &fn) { // Static method to extract the filename (if any) form a CINT command. // Returns kTRUE and the filename in 'fn'; returns kFALSE if not found or not // appliable. TString s = cmd; s = s.Strip(TString::kBoth); if (s.Length() > 0 && (s.BeginsWith(".L") || s.BeginsWith(".x") || s.BeginsWith(".X"))) { TString file = s(2, s.Length()); TString acm, arg, io; fn = gSystem->SplitAclicMode(file, acm, arg, io); if (!fn.IsNull()) return kTRUE; } // Not found return kFALSE; } //______________________________________________________________________________ Int_t TProof::Exec(const char *cmd, Bool_t plusMaster) { // Send command to be executed on the PROOF master and/or slaves. // If plusMaster is kTRUE then exeucte on slaves and master too. // Command can be any legal command line command. Commands like // ".x file.C" or ".L file.C" will cause the file file.C to be send // to the PROOF cluster. Returns -1 in case of error, >=0 in case of // succes. return Exec(cmd, kActive, plusMaster); } //______________________________________________________________________________ Int_t TProof::Exec(const char *cmd, ESlaves list, Bool_t plusMaster) { // Send command to be executed on the PROOF master and/or slaves. // Command can be any legal command line command. Commands like // ".x file.C" or ".L file.C" will cause the file file.C to be send // to the PROOF cluster. Returns -1 in case of error, >=0 in case of // succes. if (!IsValid()) return -1; TString s = cmd; s = s.Strip(TString::kBoth); if (!s.Length()) return 0; // check for macro file and make sure the file is available on all slaves TString filename; if (TProof::GetFileInCmd(s.Data(), filename)) { char *fn = gSystem->Which(TROOT::GetMacroPath(), filename, kReadPermission); if (fn) { if (GetNumberOfUniqueSlaves() > 0) { if (SendFile(fn, kAscii | kForward | kCpBin) < 0) { Error("Exec", "file %s could not be transfered", fn); delete [] fn; return -1; } } else { TString scmd = s(0,3) + fn; Int_t n = SendCommand(scmd, list); delete [] fn; return n; } } else { Error("Exec", "macro %s not found", filename.Data()); return -1; } delete [] fn; } if (plusMaster) { if (IsLite()) { gROOT->ProcessLine(cmd); } else { Int_t n = GetParallel(); SetParallelSilent(0); Int_t res = SendCommand(cmd, list); SetParallelSilent(n); if (res < 0) return res; } } return SendCommand(cmd, list); } //______________________________________________________________________________ Int_t TProof::SendCommand(const char *cmd, ESlaves list) { // Send command to be executed on the PROOF master and/or slaves. // Command can be any legal command line command, however commands // like ".x file.C" or ".L file.C" will not cause the file.C to be // transfered to the PROOF cluster. In that case use TProof::Exec(). // Returns the status send by the remote server as part of the // kPROOF_LOGDONE message. Typically this is the return code of the // command on the remote side. Returns -1 in case of error. if (!IsValid()) return -1; Broadcast(cmd, kMESS_CINT, list); Collect(list); return fStatus; } //______________________________________________________________________________ Int_t TProof::SendCurrentState(ESlaves list) { // Transfer the current state of the master to the active slave servers. // The current state includes: the current working directory, etc. // Returns the number of active slaves. Returns -1 in case of error. if (!IsValid()) return -1; // Go to the new directory, reset the interpreter environment and // tell slave to delete all objects from its new current directory. Broadcast(gDirectory->GetPath(), kPROOF_RESET, list); return GetParallel(); } //______________________________________________________________________________ Int_t TProof::SendInitialState() { // Transfer the initial (i.e. current) state of the master to all // slave servers. Currently the initial state includes: log level. // Returns the number of active slaves. Returns -1 in case of error. if (!IsValid()) return -1; SetLogLevel(fLogLevel, gProofDebugMask); return GetNumberOfActiveSlaves(); } //______________________________________________________________________________ Bool_t TProof::CheckFile(const char *file, TSlave *slave, Long_t modtime, Int_t cpopt) { // Check if a file needs to be send to the slave. Use the following // algorithm: // - check if file appears in file map // - if yes, get file's modtime and check against time in map, // if modtime not same get md5 and compare against md5 in map, // if not same return kTRUE. // - if no, get file's md5 and modtime and store in file map, ask // slave if file exists with specific md5, if yes return kFALSE, // if no return kTRUE. // The options 'cpopt' define if to copy things from cache to sandbox and what. // To retrieve from the cache the binaries associated with the file TProof::kCpBin // must be set in cpopt; the default is copy everything. // Returns kTRUE in case file needs to be send, returns kFALSE in case // file is already on remote node. Bool_t sendto = kFALSE; // create worker based filename TString sn = slave->GetName(); sn += ":"; sn += slave->GetOrdinal(); sn += ":"; sn += gSystem->BaseName(file); // check if file is in map FileMap_t::const_iterator it; if ((it = fFileMap.find(sn)) != fFileMap.end()) { // file in map MD5Mod_t md = (*it).second; if (md.fModtime != modtime) { TMD5 *md5 = TMD5::FileChecksum(file); if (md5) { if ((*md5) != md.fMD5) { sendto = kTRUE; md.fMD5 = *md5; md.fModtime = modtime; fFileMap[sn] = md; // When on the master, the master and/or slaves may share // their file systems and cache. Therefore always make a // check for the file. If the file already exists with the // expected md5 the kPROOF_CHECKFILE command will cause the // file to be copied from cache to slave sandbox. if (TestBit(TProof::kIsMaster)) { sendto = kFALSE; TMessage mess(kPROOF_CHECKFILE); mess << TString(gSystem->BaseName(file)) << md.fMD5 << cpopt; slave->GetSocket()->Send(mess); fCheckFileStatus = 0; Collect(slave, fCollectTimeout, kPROOF_CHECKFILE); sendto = (fCheckFileStatus == 0) ? kTRUE : kFALSE; } } delete md5; } else { Error("CheckFile", "could not calculate local MD5 check sum - dont send"); return kFALSE; } } } else { // file not in map TMD5 *md5 = TMD5::FileChecksum(file); MD5Mod_t md; if (md5) { md.fMD5 = *md5; md.fModtime = modtime; fFileMap[sn] = md; delete md5; } else { Error("CheckFile", "could not calculate local MD5 check sum - dont send"); return kFALSE; } TMessage mess(kPROOF_CHECKFILE); mess << TString(gSystem->BaseName(file)) << md.fMD5 << cpopt; slave->GetSocket()->Send(mess); fCheckFileStatus = 0; Collect(slave, fCollectTimeout, kPROOF_CHECKFILE); sendto = (fCheckFileStatus == 0) ? kTRUE : kFALSE; } return sendto; } //______________________________________________________________________________ Int_t TProof::SendFile(const char *file, Int_t opt, const char *rfile, TSlave *wrk) { // Send a file to master or slave servers. Returns number of slaves // the file was sent to, maybe 0 in case master and slaves have the same // file system image, -1 in case of error. // If defined, send to worker 'wrk' only. // If defined, the full path of the remote path will be rfile. // If rfile = "cache" the file is copied to the remote cache instead of the sandbox // (to copy to the cache on a different name use rfile = "cache:newname"). // The mask 'opt' is an or of ESendFileOpt: // // kAscii (0x0) if set true ascii file transfer is used // kBinary (0x1) if set true binary file transfer is used // kForce (0x2) if not set an attempt is done to find out // whether the file really needs to be downloaded // (a valid copy may already exist in the cache // from a previous run); the bit is set by // UploadPackage, since the check is done elsewhere. // kForward (0x4) if set, ask server to forward the file to slave // or submaster (meaningless for slave servers). // kCpBin (0x8) Retrieve from the cache the binaries associated // with the file // kCp (0x10) Retrieve the files from the cache // if (!IsValid()) return -1; // Use the active slaves list ... TList *slaves = (rfile && !strcmp(rfile, "cache")) ? fUniqueSlaves : fActiveSlaves; // ... or the specified slave, if any if (wrk) { slaves = new TList(); slaves->Add(wrk); } if (slaves->GetSize() == 0) return 0; #ifndef R__WIN32 Int_t fd = open(file, O_RDONLY); #else Int_t fd = open(file, O_RDONLY | O_BINARY); #endif if (fd < 0) { SysError("SendFile", "cannot open file %s", file); return -1; } // Get info about the file Long64_t size; Long_t id, flags, modtime; if (gSystem->GetPathInfo(file, &id, &size, &flags, &modtime) == 1) { Error("SendFile", "cannot stat file %s", file); return -1; } if (size == 0) { Error("SendFile", "empty file %s", file); return -1; } // Decode options Bool_t bin = (opt & kBinary) ? kTRUE : kFALSE; Bool_t force = (opt & kForce) ? kTRUE : kFALSE; Bool_t fw = (opt & kForward) ? kTRUE : kFALSE; // Copy options Int_t cpopt = 0; if ((opt & kCp)) cpopt |= kCp; if ((opt & kCpBin)) cpopt |= (kCp | kCpBin); const Int_t kMAXBUF = 32768; //16384 //65536; char buf[kMAXBUF]; Int_t nsl = 0; TIter next(slaves); TSlave *sl; TString fnam(rfile); if (fnam == "cache") { fnam += Form(":%s", gSystem->BaseName(file)); } else if (fnam.IsNull()) { fnam = gSystem->BaseName(file); } // List on which we will collect the results while ((sl = (TSlave *)next())) { if (!sl->IsValid()) continue; Bool_t sendto = force ? kTRUE : CheckFile(file, sl, modtime, cpopt); // Don't send the kPROOF_SENDFILE command to real slaves when sendto // is false. Masters might still need to send the file to newly added // slaves. PDB(kPackage,2) { const char *snd = (sl->fSlaveType == TSlave::kSlave && sendto) ? "" : "not"; Info("SendFile", "%s sending file %s to: %s:%s (%d)", snd, file, sl->GetName(), sl->GetOrdinal(), sendto); } if (sl->fSlaveType == TSlave::kSlave && !sendto) continue; // The value of 'size' is used as flag remotely, so we need to // reset it to 0 if we are not going to send the file Long64_t siz = sendto ? size : 0; snprintf(buf, kMAXBUF, "%s %d %lld %d", fnam.Data(), bin, siz, fw); if (sl->GetSocket()->Send(buf, kPROOF_SENDFILE) == -1) { MarkBad(sl, "could not send kPROOF_SENDFILE request"); continue; } if (sendto) { lseek(fd, 0, SEEK_SET); Int_t len; do { while ((len = read(fd, buf, kMAXBUF)) < 0 && TSystem::GetErrno() == EINTR) TSystem::ResetErrno(); if (len < 0) { SysError("SendFile", "error reading from file %s", file); Interrupt(kSoftInterrupt, kActive); close(fd); return -1; } if (len > 0 && sl->GetSocket()->SendRaw(buf, len) == -1) { SysError("SendFile", "error writing to slave %s:%s (now offline)", sl->GetName(), sl->GetOrdinal()); MarkBad(sl, "sendraw failure"); sl = 0; break; } } while (len > 0); nsl++; } // Wait for the operation to be done if (sl) Collect(sl, fCollectTimeout, kPROOF_SENDFILE); } close(fd); // Cleanup temporary list, if any if (slaves != fActiveSlaves && slaves != fUniqueSlaves) SafeDelete(slaves); return nsl; } //______________________________________________________________________________ Int_t TProof::SendObject(const TObject *obj, ESlaves list) { // Send object to master or slave servers. Returns number of slaves object // was sent to, -1 in case of error. if (!IsValid() || !obj) return -1; TMessage mess(kMESS_OBJECT); mess.WriteObject(obj); return Broadcast(mess, list); } //______________________________________________________________________________ Int_t TProof::SendPrint(Option_t *option) { // Send print command to master server. Returns number of slaves message // was sent to. Returns -1 in case of error. if (!IsValid()) return -1; Broadcast(option, kPROOF_PRINT, kActive); return Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ void TProof::SetLogLevel(Int_t level, UInt_t mask) { // Set server logging level. char str[32]; fLogLevel = level; gProofDebugLevel = level; gProofDebugMask = (TProofDebug::EProofDebugMask) mask; snprintf(str, 32, "%d %u", level, mask); Broadcast(str, kPROOF_LOGLEVEL, kAll); } //______________________________________________________________________________ void TProof::SetRealTimeLog(Bool_t on) { // Switch ON/OFF the real-time logging facility. When this option is // ON, log messages from processing are sent back as they come, instead of // being sent back at the end in one go. This may help debugging or monitoring // in some cases, but, depending on the amount of log, it may have significant // consequencies on the load over the network, so it must be used with care. if (IsValid()) { TMessage mess(kPROOF_REALTIMELOG); mess << on; Broadcast(mess); } else { Warning("SetRealTimeLog","session is invalid - do nothing"); } } //______________________________________________________________________________ Int_t TProof::SetParallelSilent(Int_t nodes, Bool_t random) { // Tell PROOF how many slaves to use in parallel. If random is TRUE a random // selection is done (if nodes is less than the available nodes). // Returns the number of parallel slaves. Returns -1 in case of error. if (!IsValid()) return -1; if (TestBit(TProof::kIsMaster)) { GoParallel(nodes, kFALSE, random); return SendCurrentState(); } else { PDB(kGlobal,1) Info("SetParallelSilent", "request %d node%s", nodes, nodes == 1 ? "" : "s"); TMessage mess(kPROOF_PARALLEL); mess << nodes << random; Broadcast(mess); Collect(kActive, fCollectTimeout); Int_t n = GetParallel(); PDB(kGlobal,1) Info("SetParallelSilent", "got %d node%s", n, n == 1 ? "" : "s"); return n; } } //______________________________________________________________________________ Int_t TProof::SetParallel(Int_t nodes, Bool_t random) { // Tell PROOF how many slaves to use in parallel. Returns the number of // parallel slaves. Returns -1 in case of error. Int_t n = SetParallelSilent(nodes, random); if (TestBit(TProof::kIsClient)) { if (n < 1) { Printf("PROOF set to sequential mode"); } else { TString subfix = (n == 1) ? "" : "s"; if (random) subfix += ", randomly selected"; Printf("PROOF set to parallel mode (%d worker%s)", n, subfix.Data()); } } return n; } //______________________________________________________________________________ Int_t TProof::GoParallel(Int_t nodes, Bool_t attach, Bool_t random) { // Go in parallel mode with at most "nodes" slaves. Since the fSlaves // list is sorted by slave performace the active list will contain first // the most performant nodes. Returns the number of active slaves. // If random is TRUE, and nodes is less than the number of available workers, // a random selection is done. // Returns -1 in case of error. if (!IsValid()) return -1; if (nodes < 0) nodes = 0; fActiveSlaves->Clear(); fActiveMonitor->RemoveAll(); // Prepare the list of candidates first. // Algorithm depends on random option. TSlave *sl = 0; TList *wlst = new TList; TIter nxt(fSlaves); fInactiveSlaves->Clear(); while ((sl = (TSlave *)nxt())) { if (sl->IsValid() && !fBadSlaves->FindObject(sl)) { if (strcmp("IGNORE", sl->GetImage()) == 0) continue; if ((sl->GetSlaveType() != TSlave::kSlave) && (sl->GetSlaveType() != TSlave::kMaster)) { Error("GoParallel", "TSlave is neither Master nor Slave"); R__ASSERT(0); } // Good candidate wlst->Add(sl); // Set it inactive fInactiveSlaves->Add(sl); sl->SetStatus(TSlave::kInactive); } } Int_t nwrks = (nodes > wlst->GetSize()) ? wlst->GetSize() : nodes; int cnt = 0; fEndMaster = TestBit(TProof::kIsMaster) ? kTRUE : kFALSE; while (cnt < nwrks) { // Random choice, if requested if (random) { Int_t iwrk = (Int_t) (gRandom->Rndm() * wlst->GetSize()); sl = (TSlave *) wlst->At(iwrk); } else { // The first available sl = (TSlave *) wlst->First(); } if (!sl) { Error("GoParallel", "attaching to candidate!"); break; } // Remove from the list wlst->Remove(sl); Int_t slavenodes = 0; if (sl->GetSlaveType() == TSlave::kSlave) { sl->SetStatus(TSlave::kActive); fActiveSlaves->Add(sl); fInactiveSlaves->Remove(sl); fActiveMonitor->Add(sl->GetSocket()); slavenodes = 1; } else if (sl->GetSlaveType() == TSlave::kMaster) { fEndMaster = kFALSE; TMessage mess(kPROOF_PARALLEL); if (!attach) { mess << nodes-cnt; } else { // To get the number of slaves mess.SetWhat(kPROOF_LOGFILE); mess << -1 << -1; } if (sl->GetSocket()->Send(mess) == -1) { MarkBad(sl, "could not send kPROOF_PARALLEL or kPROOF_LOGFILE request"); slavenodes = 0; } else { Collect(sl, fCollectTimeout); if (sl->IsValid()) { sl->SetStatus(TSlave::kActive); fActiveSlaves->Add(sl); fInactiveSlaves->Remove(sl); fActiveMonitor->Add(sl->GetSocket()); if (sl->GetParallel() > 0) { slavenodes = sl->GetParallel(); } else { // Sequential mode: the master acts as a worker slavenodes = 1; } } else { MarkBad(sl, "collect failed after kPROOF_PARALLEL or kPROOF_LOGFILE request"); slavenodes = 0; } } } // 'slavenodes' may be different than 1 in multimaster setups cnt += slavenodes; } // Cleanup list wlst->SetOwner(0); SafeDelete(wlst); // Get slave status (will set the slaves fWorkDir correctly) AskStatistics(); // Find active slaves with unique image FindUniqueSlaves(); // Send new group-view to slaves if (!attach) SendGroupView(); Int_t n = GetParallel(); if (TestBit(TProof::kIsClient)) { if (n < 1) printf("PROOF set to sequential mode\n"); else printf("PROOF set to parallel mode (%d worker%s)\n", n, n == 1 ? "" : "s"); } PDB(kGlobal,1) Info("GoParallel", "got %d node%s", n, n == 1 ? "" : "s"); return n; } //______________________________________________________________________________ void TProof::ShowData() { // List contents of the data directory in the sandbox. // This is the place where files produced by the client queries are kept if (!IsValid() || !fManager) return; // This is run via the manager fManager->Find("~/data", "-type f", "all"); } //______________________________________________________________________________ void TProof::ClearData(UInt_t what, const char *dsname) { // Remove files for the data directory. // The option 'what' can take the values: // kPurge remove all files and directories under '~/data' // kUnregistered remove only files not in registered datasets (default) // kDataset remove files belonging to dataset 'dsname' // User is prompt for confirmation, unless kForceClear is ORed with the option if (!IsValid() || !fManager) return; // Check whether we need to prompt TString prompt, a("Y"); Bool_t force = (what & kForceClear) ? kTRUE : kFALSE; Bool_t doask = (!force && isatty(0) != 0 && isatty(1) != 0) ? kTRUE : kFALSE; // If all just send the request if ((what & TProof::kPurge)) { // Prompt, if requested if (doask && !Prompt("Do you really want to remove all data files")) return; fManager->Rm("~/data/*", "-rf", "all"); return; } else if ((what & TProof::kDataset)) { // We must have got a name if (!dsname || strlen(dsname) <= 0) { Error("ClearData", "dataset name mandatory when removing a full dataset"); return; } // Check if the dataset is registered if (!ExistsDataSet(dsname)) { Error("ClearData", "dataset '%s' does not exists", dsname); return; } // Get the file content TFileCollection *fc = GetDataSet(dsname); if (!fc) { Error("ClearData", "could not retrieve info about dataset '%s'", dsname); return; } // Prompt, if requested if (doask && !Prompt(TString::Format("Do you really want to remove all data files" " of dataset '%s'", dsname))) return; // Loop through the files Bool_t rmds = kTRUE; TIter nxf(fc->GetList()); TFileInfo *fi = 0; Int_t rfiles = 0, nfiles = fc->GetList()->GetSize(); while ((fi = (TFileInfo *) nxf())) { // Fill the host info TString host, file; // Take info from the current url TUrl uf(*(fi->GetFirstUrl())); file = uf.GetFile(); host = uf.GetHost(); // Now search for any "file:" url Int_t nurl = fi->GetNUrls(); fi->ResetUrl(); TUrl *up = 0; while (nurl-- && fi->NextUrl()) { up = fi->GetCurrentUrl(); if (!strcmp(up->GetProtocol(), "file")) { TString opt(up->GetOptions()); if (opt.BeginsWith("node=")) { host=opt; host.ReplaceAll("node=",""); file = up->GetFile(); break; } } } // Issue a remove request now if (fManager->Rm(file.Data(), "-f", host.Data()) != 0) { Error("ClearData", "problems removing '%s'", file.Data()); // Some files not removed: keep the meta info about this dataset rmds = kFALSE; } rfiles++; ClearDataProgress(rfiles, nfiles); } fprintf(stderr, "\n"); if (rmds) { // All files were removed successfully: remove also the dataset meta info RemoveDataSet(dsname); } } else if (what &TProof::kUnregistered) { // Get the existing files TString outtmp("ProofClearData_"); FILE *ftmp = gSystem->TempFileName(outtmp); if (!ftmp) { Error("ClearData", "cannot create temp file for logs"); return; } fclose(ftmp); RedirectHandle_t h; gSystem->RedirectOutput(outtmp.Data(), "w", &h); ShowData(); gSystem->RedirectOutput(0, 0, &h); // Parse the output file now ifstream in; in.open(outtmp.Data()); if (!in.is_open()) { Error("ClearData", "could not open temp file for logs: %s", outtmp.Data()); gSystem->Unlink(outtmp); return; } // Go through Int_t nfiles = 0; TMap *afmap = new TMap; TString line, host, file; Int_t from = 0; while (in.good()) { line.ReadLine(in); if (line.IsNull()) continue; while (line.EndsWith("\n")) { line.Strip(TString::kTrailing, '\n'); } from = 0; if (line.Tokenize(host, from, "| ")) line.Tokenize(file, from, "| "); if (!host.IsNull() && !file.IsNull()) { TList *fl = (TList *) afmap->GetValue(host.Data()); if (!fl) { fl = new TList(); fl->SetName(host); afmap->Add(new TObjString(host), fl); } fl->Add(new TObjString(file)); nfiles++; PDB(kDataset,2) Info("ClearData", "added info for: h:%s, f:%s", host.Data(), file.Data()); } else { Warning("ClearData", "found incomplete line: '%s'", line.Data()); } } // Close and remove the file in.close(); gSystem->Unlink(outtmp); // Get registered data files TString sel = TString::Format("/%s/%s/", GetGroup(), GetUser()); TMap *fcmap = GetDataSets(sel); if (!fcmap || fcmap->GetSize() <= 0) { PDB(kDataset,1) Info("ClearData", "no dataset beloning to '%s'", sel.Data()); SafeDelete(fcmap); return; } // Go thorugh and prepare the lists per node TString opt; TIter nxfc(fcmap); TObjString *os = 0; while ((os = (TObjString *) nxfc())) { TFileCollection *fc = 0; if ((fc = (TFileCollection *) fcmap->GetValue(os))) { TFileInfo *fi = 0; TIter nxfi(fc->GetList()); while ((fi = (TFileInfo *) nxfi())) { // Get special "file:" url fi->ResetUrl(); Int_t nurl = fi->GetNUrls(); TUrl *up = 0; while (nurl-- && fi->NextUrl()) { up = fi->GetCurrentUrl(); if (!strcmp(up->GetProtocol(), "file")) { opt = up->GetOptions(); if (opt.BeginsWith("node=")) { host=opt; host.ReplaceAll("node=",""); file = up->GetFile(); PDB(kDataset,2) Info("ClearData", "found: host: %s, file: %s", host.Data(), file.Data()); // Remove this from the full list, if there TList *fl = (TList *) afmap->GetValue(host.Data()); if (fl) { TObjString *fn = (TObjString *) fl->FindObject(file.Data()); if (fn) { fl->Remove(fn); SafeDelete(fn); nfiles--; } else { Warning("ClearData", "registered file '%s' not found in the full list!", file.Data()); } } break; } } } } } } // Clean up the the received map fcmap->SetOwner(kTRUE); SafeDelete(fcmap); // List of the files to be removed Info("ClearData", "%d unregistered files to be removed:", nfiles); afmap->Print(); // Prompt, if requested if (doask && !Prompt(TString::Format("Do you really want to remove all %d" " unregistered data files", nfiles))) return; // Remove one by one; we may implement a bloc remove in the future Int_t rfiles = 0; TIter nxls(afmap); while ((os = (TObjString *) nxls())) { TList *fl = 0; if ((fl = (TList *) afmap->GetValue(os))) { TIter nxf(fl); TObjString *fn = 0; while ((fn = (TObjString *) nxf())) { // Issue a remove request now if (fManager->Rm(fn->GetName(), "-f", os->GetName()) != 0) { Error("ClearData", "problems removing '%s' on host '%s'", fn->GetName(), os->GetName()); } rfiles++; ClearDataProgress(rfiles, nfiles); } } } fprintf(stderr, "\n"); // Final cleanup afmap->SetOwner(kTRUE); SafeDelete(afmap); } } //______________________________________________________________________________ Bool_t TProof::Prompt(const char *p) { // Prompt the question 'p' requiring an answer y,Y,n,N // Return kTRUE is the answer was y or Y, kFALSE in all other cases. TString pp(p); if (!pp.Contains("?")) pp += "?"; if (!pp.Contains("[y/N]")) pp += " [y/N]"; TString a = Getline(pp.Data()); if (a != "\n" && a[0] != 'y' && a[0] != 'Y' && a[0] != 'n' && a[0] != 'N') { Printf("Please answer y, Y, n or N"); // Unclear answer: assume negative return kFALSE; } else if (a == "\n" || a[0] == 'n' || a[0] == 'N') { // Explicitly Negative answer return kFALSE; } // Explicitly Positive answer return kTRUE; } //______________________________________________________________________________ void TProof::ClearDataProgress(Int_t r, Int_t t) { // Progress bar for clear data fprintf(stderr, "[TProof::ClearData] Total %5d files\t|", t); for (Int_t l = 0; l < 20; l++) { if (r > 0 && t > 0) { if (l < 20*r/t) fprintf(stderr, "="); else if (l == 20*r/t) fprintf(stderr, ">"); else if (l > 20*r/t) fprintf(stderr, "."); } else fprintf(stderr, "="); } fprintf(stderr, "| %.02f %% \r", 100.0*(t ? (r/t) : 1)); } //______________________________________________________________________________ void TProof::ShowCache(Bool_t all) { // List contents of file cache. If all is true show all caches also on // slaves. If everything is ok all caches are to be the same. if (!IsValid()) return; TMessage mess(kPROOF_CACHE); mess << Int_t(kShowCache) << all; Broadcast(mess, kUnique); if (all) { TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kShowSubCache) << all; Broadcast(mess2, fNonUniqueMasters); Collect(kAllUnique, fCollectTimeout); } else { Collect(kUnique, fCollectTimeout); } } //______________________________________________________________________________ void TProof::ClearCache(const char *file) { // Remove file from all file caches. If file is 0 or "" or "*", remove all // the files if (!IsValid()) return; TMessage mess(kPROOF_CACHE); mess << Int_t(kClearCache) << TString(file); Broadcast(mess, kUnique); TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kClearSubCache) << TString(file); Broadcast(mess2, fNonUniqueMasters); Collect(kAllUnique); // clear file map so files get send again to remote nodes fFileMap.clear(); } //______________________________________________________________________________ void TProof::SystemCmd(const char *cmd, Int_t fdout) { // Exec system command 'cmd'. If fdout > -1, append the output to fdout. if (fdout < 0) { // Exec directly the command gSystem->Exec(cmd); } else { // Exec via a pipe FILE *fin = gSystem->OpenPipe(cmd, "r"); if (fin) { // Now we go char line[2048]; while (fgets(line, 2048, fin)) { Int_t r = strlen(line); if (r > 0) { if (write(fdout, line, r) < 0) { ::Warning("TProof::SystemCmd", "errno %d writing to file descriptor %d", TSystem::GetErrno(), fdout); } } else { // Done break; } } gSystem->ClosePipe(fin); } } } //______________________________________________________________________________ void TProof::ShowPackages(Bool_t all, Bool_t redirlog) { // List contents of package directory. If all is true show all package // directories also on slaves. If everything is ok all package directories // should be the same. If redir is kTRUE the result is redirected to the log // file (option available for internal actions). if (!IsValid()) return; Bool_t oldredir = fRedirLog; if (redirlog) fRedirLog = kTRUE; // Active logging unit FILE *fout = (fRedirLog) ? fLogFileW : stdout; if (!fout) { Warning("ShowPackages", "file descriptor for outputs undefined (%p):" " will not log msgs", fout); return; } lseek(fileno(fout), (off_t) 0, SEEK_END); if (TestBit(TProof::kIsClient)) { if (fGlobalPackageDirList && fGlobalPackageDirList->GetSize() > 0) { // Scan the list of global packages dirs TIter nxd(fGlobalPackageDirList); TNamed *nm = 0; while ((nm = (TNamed *)nxd())) { fprintf(fout, "*** Global Package cache %s client:%s ***\n", nm->GetName(), nm->GetTitle()); fflush(fout); SystemCmd(Form("%s %s", kLS, nm->GetTitle()), fileno(fout)); fprintf(fout, "\n"); fflush(fout); } } fprintf(fout, "*** Package cache client:%s ***\n", fPackageDir.Data()); fflush(fout); SystemCmd(Form("%s %s", kLS, fPackageDir.Data()), fileno(fout)); fprintf(fout, "\n"); } // Nothing more to do if we are a Lite-session if (IsLite()) { fRedirLog = oldredir; return; } TMessage mess(kPROOF_CACHE); mess << Int_t(kShowPackages) << all; Broadcast(mess, kUnique); if (all) { TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kShowSubPackages) << all; Broadcast(mess2, fNonUniqueMasters); Collect(kAllUnique, fCollectTimeout); } else { Collect(kUnique, fCollectTimeout); } // Restore logging option fRedirLog = oldredir; } //______________________________________________________________________________ void TProof::ShowEnabledPackages(Bool_t all) { // List which packages are enabled. If all is true show enabled packages // for all active slaves. If everything is ok all active slaves should // have the same packages enabled. if (!IsValid()) return; if (TestBit(TProof::kIsClient)) { printf("*** Enabled packages on client on %s\n", gSystem->HostName()); TIter next(fEnabledPackagesOnClient); while (TObjString *str = (TObjString*) next()) printf("%s\n", str->GetName()); } // Nothing more to do if we are a Lite-session if (IsLite()) return; TMessage mess(kPROOF_CACHE); mess << Int_t(kShowEnabledPackages) << all; Broadcast(mess); Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ Int_t TProof::ClearPackages() { // Remove all packages. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (UnloadPackages() == -1) return -1; if (DisablePackages() == -1) return -1; return fStatus; } //______________________________________________________________________________ Int_t TProof::ClearPackage(const char *package) { // Remove a specific package. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("ClearPackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); if (UnloadPackage(pac) == -1) return -1; if (DisablePackage(pac) == -1) return -1; return fStatus; } //______________________________________________________________________________ Int_t TProof::DisablePackage(const char *package) { // Remove a specific package. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("DisablePackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); if (DisablePackageOnClient(pac) == -1) return -1; // Nothing more to do if we are a Lite-session if (IsLite()) return 0; Int_t st = -1; Bool_t done = kFALSE; if (fManager) { // Try to do it via XROOTD (new way) TString path; path.Form("~/packages/%s", package); if (fManager->Rm(path, "-rf", "all") != -1) { path.Append(".par"); if (fManager->Rm(path, "-f", "all") != -1) { done = kTRUE; st = 0; } } } if (!done) { // Try via TProofServ (old way) TMessage mess(kPROOF_CACHE); mess << Int_t(kDisablePackage) << pac; Broadcast(mess, kUnique); TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kDisableSubPackage) << pac; Broadcast(mess2, fNonUniqueMasters); Collect(kAllUnique); st = fStatus; } // Done return st; } //______________________________________________________________________________ Int_t TProof::DisablePackageOnClient(const char *package) { // Remove a specific package from the client. // Returns 0 in case of success and -1 in case of error. if (TestBit(TProof::kIsClient)) { // Remove the package directory and the par file locally fPackageLock->Lock(); gSystem->Exec(Form("%s %s/%s", kRM, fPackageDir.Data(), package)); gSystem->Exec(Form("%s %s/%s.par", kRM, fPackageDir.Data(), package)); gSystem->Exec(Form("%s %s/%s/%s.par", kRM, fPackageDir.Data(), kPROOF_PackDownloadDir, package)); fPackageLock->Unlock(); if (!gSystem->AccessPathName(Form("%s/%s/%s.par", fPackageDir.Data(), kPROOF_PackDownloadDir, package))) Warning("DisablePackageOnClient", "unable to remove cached package PAR file for %s", package); if (!gSystem->AccessPathName(Form("%s/%s.par", fPackageDir.Data(), package))) Warning("DisablePackageOnClient", "unable to remove package PAR file for %s", package); if (!gSystem->AccessPathName(Form("%s/%s", fPackageDir.Data(), package))) Warning("DisablePackageOnClient", "unable to remove package directory for %s", package); } return 0; } //______________________________________________________________________________ Int_t TProof::DisablePackages() { // Remove all packages. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; // remove all packages on client if (TestBit(TProof::kIsClient)) { fPackageLock->Lock(); gSystem->Exec(Form("%s %s/*", kRM, fPackageDir.Data())); fPackageLock->Unlock(); } // Nothing more to do if we are a Lite-session if (IsLite()) return 0; TMessage mess(kPROOF_CACHE); mess << Int_t(kDisablePackages); Broadcast(mess, kUnique); TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kDisableSubPackages); Broadcast(mess2, fNonUniqueMasters); Collect(kAllUnique); return fStatus; } //______________________________________________________________________________ Int_t TProof::BuildPackage(const char *package, EBuildPackageOpt opt) { // Build specified package. Executes the PROOF-INF/BUILD.sh // script if it exists on all unique nodes. If opt is kBuildOnSlavesNoWait // then submit build command to slaves, but don't wait // for results. If opt is kCollectBuildResults then collect result // from slaves. To be used on the master. // If opt = kBuildAll (default) then submit and wait for results // (to be used on the client). // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("BuildPackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); Bool_t buildOnClient = kTRUE; if (opt == kDontBuildOnClient) { buildOnClient = kFALSE; opt = kBuildAll; } // Prepare the local package TString pdir; Int_t st = 0; if (buildOnClient) { if (TestBit(TProof::kIsClient) && fPackageLock) fPackageLock->Lock(); if ((st = BuildPackageOnClient(pac, 1, &pdir) != 0)) { if (TestBit(TProof::kIsClient) && fPackageLock) fPackageLock->Unlock(); return -1; } } if (opt <= kBuildAll && !IsLite()) { TMessage mess(kPROOF_CACHE); mess << Int_t(kBuildPackage) << pac; Broadcast(mess, kUnique); TMessage mess2(kPROOF_CACHE); mess2 << Int_t(kBuildSubPackage) << pac; Broadcast(mess2, fNonUniqueMasters); } if (opt >= kBuildAll) { // by first forwarding the build commands to the master and slaves // and only then building locally we build in parallel if (buildOnClient) { st = BuildPackageOnClient(pac, 2, &pdir); if (TestBit(TProof::kIsClient) && fPackageLock) fPackageLock->Unlock(); } fStatus = 0; if (!IsLite()) Collect(kAllUnique); if (fStatus < 0 || st < 0) return -1; } return 0; } //______________________________________________________________________________ Int_t TProof::BuildPackageOnClient(const char *pack, Int_t opt, TString *path) { // Build specified package on the client. Executes the PROOF-INF/BUILD.sh // script if it exists on the client. // If opt == 0, both the preparation and building phases are run. // If opt == 1, only the preparation phase (asserting and, eventually, downloading // of the package) is done; '*path' contains the full path to the // package to be passed in the next call // If opt == 2, only the building phase is run using *path . // Returns 0 in case of success and -1 in case of error. // The code is equivalent to the one in TProofServ.cxx (TProof::kBuildPackage // case). Keep in sync in case of changes. TString downloaddir; downloaddir.Form("%s/%s", fPackageDir.Data(), kPROOF_PackDownloadDir); if (opt != 0 && !path) { Error("BuildPackageOnClient", "for opt=%d != 0 'patyh' must be defined", opt); return -1; } if (TestBit(TProof::kIsClient)) { Int_t status = 0; TString pdir, ocwd; if (opt == 0 || opt == 1) { // Package path pdir.Form("%s/%s", fPackageDir.Data(), pack); if (gSystem->AccessPathName(pdir, kReadPermission) || gSystem->AccessPathName(pdir + "/PROOF-INF", kReadPermission)) { pdir = ""; // Is there a global package with this name? if (fGlobalPackageDirList && fGlobalPackageDirList->GetSize() > 0) { // Scan the list of global packages dirs TIter nxd(fGlobalPackageDirList); TNamed *nm = 0; while ((nm = (TNamed *)nxd())) { pdir = Form("%s/%s", nm->GetTitle(), pack); if (!gSystem->AccessPathName(pdir, kReadPermission) && !gSystem->AccessPathName(pdir + "/PROOF-INF", kReadPermission)) { // Package found, stop searching break; } pdir = ""; } } } else { // Check if the related PAR file still exists (private versions could have gone: // in such a case we should take the reference from the repository, by first cleaning // the existing directory) TString tpar(pdir); if (!tpar.EndsWith(".par")) tpar += ".par"; Bool_t badPAR = kTRUE; FileStat_t stpar; if (gSystem->GetPathInfo(tpar, stpar) == 0) { #ifndef WIN32 char ctmp[1024]; if (!R_ISLNK(stpar.fMode) || readlink(tpar.Data(), ctmp, 1024) > 0) { // The file exists badPAR = kFALSE; } #else // The file exists badPAR = kFALSE; #endif } // Cleanup, if bad if (badPAR) { // Remove package directory gSystem->Exec(Form("%s %s", kRM, pdir.Data())); // Remove link or bad file gSystem->Exec(Form("%s %s", kRM, tpar.Data())); // Reset variable pdir = ""; } } // Check if the package was downloaded from the master Bool_t wasDownloaded = kFALSE; TString dlpar; dlpar.Form("%s/%s", downloaddir.Data(), gSystem->BaseName(pack)); if (!dlpar.EndsWith(".par")) dlpar += ".par"; if (!pdir.IsNull()) { if (!gSystem->AccessPathName(dlpar, kFileExists)) wasDownloaded = kTRUE; } if (pdir.IsNull() || wasDownloaded) { // Try to download it if (DownloadPackage(pack, downloaddir) != 0) { Error("BuildPackageOnClient", "PAR file '%s.par' not found and could not be downloaded", pack); return -1; } else { TMD5 *md5 = TMD5::FileChecksum(dlpar); if (UploadPackageOnClient(dlpar, kUntar, md5) == -1) { Error("BuildPackageOnClient", "PAR file '%s.par' not found and could not be unpacked locally", pack); delete md5; return -1; } delete md5; // The package is now linked from the default package dir pdir.Form("%s/%s", fPackageDir.Data(), pack); } } else if (pdir.IsNull()) { Error("BuildPackageOnClient", "PAR file '%s.par' not found", pack); return -1; } PDB(kPackage, 1) Info("BuildPackageOnClient", "package %s exists and has PROOF-INF directory", pack); // We are done if only prepare was requested if (opt == 1) { *path = pdir; return 0; } } if (opt == 0 || opt == 2) { if (opt == 2) pdir = path->Data(); ocwd = gSystem->WorkingDirectory(); gSystem->ChangeDirectory(pdir); // check for BUILD.sh and execute if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) { // read version from file proofvers.txt, and if current version is // not the same do a "BUILD.sh clean" Bool_t savever = kFALSE; Int_t rev = -1; TString v; FILE *f = fopen("PROOF-INF/proofvers.txt", "r"); if (f) { TString r; v.Gets(f); r.Gets(f); rev = (!r.IsNull() && r.IsDigit()) ? r.Atoi() : -1; fclose(f); } if (!f || v != gROOT->GetVersion() || (gROOT->GetSvnRevision() > 0 && rev != gROOT->GetSvnRevision())) { savever = kTRUE; Info("BuildPackageOnClient", "%s: version change (current: %s:%d, build: %s:%d): cleaning ... ", pack, gROOT->GetVersion(), gROOT->GetSvnRevision(), v.Data(), rev); // Hard cleanup: go up the dir tree gSystem->ChangeDirectory(fPackageDir); // remove package directory gSystem->Exec(Form("%s %s", kRM, pdir.Data())); // find gunzip... char *gunzip = gSystem->Which(gSystem->Getenv("PATH"), kGUNZIP, kExecutePermission); if (gunzip) { TString par = Form("%s.par", pdir.Data()); // untar package TString cmd(Form(kUNTAR3, gunzip, par.Data())); status = gSystem->Exec(cmd); if ((status = gSystem->Exec(cmd))) { Error("BuildPackageOnCLient", "failure executing: %s", cmd.Data()); } else { // Go down to the package directory gSystem->ChangeDirectory(pdir); } delete [] gunzip; } else { Error("BuildPackageOnClient", "%s not found", kGUNZIP); status = -1; } } if (gSystem->Exec("PROOF-INF/BUILD.sh")) { Error("BuildPackageOnClient", "building package %s on the client failed", pack); status = -1; } if (savever && !status) { f = fopen("PROOF-INF/proofvers.txt", "w"); if (f) { fputs(gROOT->GetVersion(), f); fputs(Form("\n%d",gROOT->GetSvnRevision()), f); fclose(f); } } } else { PDB(kPackage, 1) Info("BuildPackageOnClient", "package %s exists but has no PROOF-INF/BUILD.sh script", pack); } gSystem->ChangeDirectory(ocwd); return status; } } return 0; } //______________________________________________________________________________ Int_t TProof::LoadPackage(const char *package, Bool_t notOnClient) { // Load specified package. Executes the PROOF-INF/SETUP.C script // on all active nodes. If notOnClient = true, don't load package // on the client. The default is to load the package also on the client. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("LoadPackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); if (!notOnClient) if (LoadPackageOnClient(pac) == -1) return -1; TMessage mess(kPROOF_CACHE); mess << Int_t(kLoadPackage) << pac; Broadcast(mess); Collect(); return fStatus; } //______________________________________________________________________________ Int_t TProof::LoadPackageOnClient(const char *pack) { // Load specified package in the client. Executes the PROOF-INF/SETUP.C // script on the client. Returns 0 in case of success and -1 in case of error. // The code is equivalent to the one in TProofServ.cxx (TProof::kLoadPackage // case). Keep in sync in case of changes. if (TestBit(TProof::kIsClient)) { Int_t status = 0; TString pdir, ocwd; // If already loaded don't do it again if (fEnabledPackagesOnClient->FindObject(pack)) { Info("LoadPackageOnClient", "package %s already loaded", pack); return 0; } // always follows BuildPackage so no need to check for PROOF-INF pdir.Form("%s/%s", fPackageDir.Data(), pack); if (gSystem->AccessPathName(pdir, kReadPermission)) { // Is there a global package with this name? if (fGlobalPackageDirList && fGlobalPackageDirList->GetSize() > 0) { // Scan the list of global packages dirs TIter nxd(fGlobalPackageDirList); TNamed *nm = 0; while ((nm = (TNamed *)nxd())) { pdir = Form("%s/%s", nm->GetTitle(), pack); if (!gSystem->AccessPathName(pdir, kReadPermission)) { // Package found, stop searching break; } pdir = ""; } if (pdir.Length() <= 0) { // Package not found Error("LoadPackageOnClient", "failure locating %s ...", pack); return -1; } } } ocwd = gSystem->WorkingDirectory(); gSystem->ChangeDirectory(pdir); // check for SETUP.C and execute if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) { Int_t err = 0; Int_t errm = gROOT->Macro("PROOF-INF/SETUP.C", &err); if (errm < 0) status = -1; if (err > TInterpreter::kNoError && err <= TInterpreter::kFatal) status = -1; } else { PDB(kPackage, 1) Info("LoadPackageOnCLient", "package %s exists but has no PROOF-INF/SETUP.C script", pack); } gSystem->ChangeDirectory(ocwd); if (!status) { // create link to package in working directory fPackageLock->Lock(); FileStat_t stat; Int_t st = gSystem->GetPathInfo(pack, stat); // check if symlink, if so unlink, if not give error // NOTE: GetPathnfo() returns 1 in case of symlink that does not point to // existing file or to a directory, but if fIsLink is true the symlink exists if (stat.fIsLink) gSystem->Unlink(pack); else if (st == 0) { Error("LoadPackageOnClient", "cannot create symlink %s in %s on client, " "another item with same name already exists", pack, ocwd.Data()); fPackageLock->Unlock(); return -1; } gSystem->Symlink(pdir, pack); fPackageLock->Unlock(); // add package to list of include directories to be searched by ACliC gSystem->AddIncludePath(TString("-I") + pack); // add package to list of include directories to be searched by CINT gROOT->ProcessLine(TString(".include ") + pack); fEnabledPackagesOnClient->Add(new TObjString(pack)); PDB(kPackage, 1) Info("LoadPackageOnClient", "package %s successfully loaded", pack); } else Error("LoadPackageOnClient", "loading package %s on client failed", pack); return status; } return 0; } //______________________________________________________________________________ Int_t TProof::UnloadPackage(const char *package) { // Unload specified package. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("UnloadPackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); if (UnloadPackageOnClient(pac) == -1) return -1; // Nothing more to do if we are a Lite-session if (IsLite()) return 0; TMessage mess(kPROOF_CACHE); mess << Int_t(kUnloadPackage) << pac; Broadcast(mess); Collect(); return fStatus; } //______________________________________________________________________________ Int_t TProof::UnloadPackageOnClient(const char *package) { // Unload a specific package on the client. // Returns 0 in case of success and -1 in case of error. // The code is equivalent to the one in TProofServ.cxx (TProof::UnloadPackage // case). Keep in sync in case of changes. if (TestBit(TProof::kIsClient)) { TObjString *pack = (TObjString *) fEnabledPackagesOnClient->FindObject(package); if (pack) { // Remove entry from include path TString aclicincpath = gSystem->GetIncludePath(); TString cintincpath = gInterpreter->GetIncludePath(); // remove interpreter part of gSystem->GetIncludePath() aclicincpath.Remove(aclicincpath.Length() - cintincpath.Length() - 1); // remove package's include path aclicincpath.ReplaceAll(TString(" -I") + package, ""); gSystem->SetIncludePath(aclicincpath); //TODO reset interpreter include path // remove entry from enabled packages list fEnabledPackagesOnClient->Remove(pack); } // cleanup the link if (!gSystem->AccessPathName(package)) if (gSystem->Unlink(package) != 0) Warning("UnloadPackageOnClient", "unable to remove symlink to %s", package); // delete entry delete pack; } return 0; } //______________________________________________________________________________ Int_t TProof::UnloadPackages() { // Unload all packages. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (TestBit(TProof::kIsClient)) { // Iterate over packages on the client and remove each package TIter nextpackage(fEnabledPackagesOnClient); while (TObjString *objstr = dynamic_cast<TObjString*>(nextpackage())) if (UnloadPackageOnClient(objstr->String()) == -1 ) return -1; } // Nothing more to do if we are a Lite-session if (IsLite()) return 0; TMessage mess(kPROOF_CACHE); mess << Int_t(kUnloadPackages); Broadcast(mess); Collect(); return fStatus; } //______________________________________________________________________________ Int_t TProof::EnablePackage(const char *package, Bool_t notOnClient) { // Enable specified package. Executes the PROOF-INF/BUILD.sh // script if it exists followed by the PROOF-INF/SETUP.C script. // In case notOnClient = true, don't enable the package on the client. // The default is to enable packages also on the client. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!package || !strlen(package)) { Error("EnablePackage", "need to specify a package name"); return -1; } // if name, erroneously, is a par pathname strip off .par and path TString pac = package; if (pac.EndsWith(".par")) pac.Remove(pac.Length()-4); pac = gSystem->BaseName(pac); EBuildPackageOpt opt = kBuildAll; if (notOnClient) opt = kDontBuildOnClient; if (BuildPackage(pac, opt) == -1) return -1; if (LoadPackage(pac, notOnClient) == -1) return -1; return 0; } //______________________________________________________________________________ Int_t TProof::DownloadPackage(const char *pack, const char *dstdir) { // Download a PROOF archive (PAR file) from the master package repository. // The PAR file is downloaded in the current directory or in the directory // specified by 'dstdir'. If a package with the same name already exists // at destination, a check on the MD5 sum is done and the user warned or // prompted for action, depending is the file is equal or different. // Returns 0 in case of success and -1 in case of error. if (!fManager || !(fManager->IsValid())) { Error("DownloadPackage", "the manager is undefined!"); return -1; } // Create the default source and destination paths TString parname(gSystem->BaseName(pack)), src, dst; if (!parname.EndsWith(".par")) parname += ".par"; src.Form("packages/%s", parname.Data()); if (!dstdir || strlen(dstdir) <= 0) { dst.Form("./%s", parname.Data()); } else { // Check the destination directory FileStat_t st; if (gSystem->GetPathInfo(dstdir, st) != 0) { // Directory does not exit: create it if (gSystem->mkdir(dstdir, kTRUE) != 0) { Error("DownloadPackage", "could not create the destination directory '%s' (errno: %d)", dstdir, TSystem::GetErrno()); return -1; } } else if (!R_ISDIR(st.fMode) && !R_ISLNK(st.fMode)) { Error("DownloadPackage", "destination path '%s' exist but is not a directory!", dstdir); return -1; } dst.Form("%s/%s", dstdir, parname.Data()); } // Make sure the source file exists FileStat_t stsrc; RedirectHandle_t rh; if (gSystem->RedirectOutput(fLogFileName, "a", &rh) != 0) Warning("DownloadPackage", "problems redirecting output to '%s'", fLogFileName.Data()); Int_t rc = fManager->Stat(src, stsrc); if (gSystem->RedirectOutput(0, 0, &rh) != 0) Warning("DownloadPackage", "problems restoring output"); if (rc != 0) { // Check if there is another possible source ShowPackages(kFALSE, kTRUE); TMacro *mp = GetLastLog(); if (mp) { // Look for global directories Bool_t isGlobal = kFALSE; TIter nxl(mp->GetListOfLines()); TObjString *os = 0; TString globaldir; while ((os = (TObjString *) nxl())) { TString s(os->GetName()); if (s.Contains("*** Global Package cache")) { // Get the directory s.Remove(0, s.Last(':') + 1); s.Remove(s.Last(' ')); globaldir = s; isGlobal = kTRUE; } else if (s.Contains("*** Package cache")) { isGlobal = kFALSE; globaldir = ""; } // Check for the package if (isGlobal && s.Contains(parname)) { src.Form("%s/%s", globaldir.Data(), parname.Data()); break; } } // Cleanup delete mp; } } // Do it via the manager if (fManager->GetFile(src, dst, "silent") != 0) { Error("DownloadPackage", "problems downloading '%s' (src:%s, dst:%s)", pack, src.Data(), dst.Data()); return -1; } else { Info("DownloadPackage", "'%s' cross-checked against master repository (local path: %s)", pack, dst.Data()); } // Done return 0; } //______________________________________________________________________________ Int_t TProof::UploadPackage(const char *pack, EUploadPackageOpt opt) { // Upload a PROOF archive (PAR file). A PAR file is a compressed // tar file with one special additional directory, PROOF-INF // (blatantly copied from Java's jar format). It must have the extension // .par. A PAR file can be directly a binary or a source with a build // procedure. In the PROOF-INF directory there can be a build script: // BUILD.sh to be called to build the package, in case of a binary PAR // file don't specify a build script or make it a no-op. Then there is // SETUP.C which sets the right environment variables to use the package, // like LD_LIBRARY_PATH, etc. // The 'opt' allows to specify whether the .PAR should be just unpacked // in the existing dir (opt = kUntar, default) or a remove of the existing // directory should be executed (opt = kRemoveOld), so triggering a full // re-build. The option if effective only for PROOF protocol > 8 . // The lab 'dirlab' (e.g. 'G0') indicates that the package is to uploaded to // an alternative global directory for global usage. This may require special // privileges. // If download is kTRUE and the package is not found locally, then it is downloaded // from the master repository. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; TString par = pack; if (!par.EndsWith(".par")) // The client specified only the name: add the extension par += ".par"; // Default location is the local working dir; then the package dir gSystem->ExpandPathName(par); if (gSystem->AccessPathName(par, kReadPermission)) { TString tried = par; // Try the package dir par = Form("%s/%s", fPackageDir.Data(), gSystem->BaseName(par)); if (gSystem->AccessPathName(par, kReadPermission)) { // Is the package a global one if (fGlobalPackageDirList && fGlobalPackageDirList->GetSize() > 0) { // Scan the list of global packages dirs TIter nxd(fGlobalPackageDirList); TNamed *nm = 0; TString pdir; while ((nm = (TNamed *)nxd())) { pdir = Form("%s/%s", nm->GetTitle(), pack); if (!gSystem->AccessPathName(pdir, kReadPermission)) { // Package found, stop searching break; } pdir = ""; } if (pdir.Length() > 0) { // Package is in the global dirs if (gDebug > 0) Info("UploadPackage", "global package found (%s): no upload needed", pdir.Data()); return 0; } } Error("UploadPackage", "PAR file '%s' not found; paths tried: %s, %s", gSystem->BaseName(par), tried.Data(), par.Data()); return -1; } } // Strategy: // On the client: // get md5 of package and check if it is different // from the one stored in the local package directory. If it is lock // the package directory and copy the package, unlock the directory. // On the masters: // get md5 of package and check if it is different from the // one stored on the remote node. If it is different lock the remote // package directory and use TFTP or SendFile to ftp the package to the // remote node, unlock the directory. TMD5 *md5 = TMD5::FileChecksum(par); if (UploadPackageOnClient(par, opt, md5) == -1) { delete md5; return -1; } // Nothing more to do if we are a Lite-session if (IsLite()) { delete md5; return 0; } TString smsg; smsg.Form("+%s", gSystem->BaseName(par)); TMessage mess(kPROOF_CHECKFILE); mess << smsg << (*md5); TMessage mess2(kPROOF_CHECKFILE); smsg.Replace(0, 1, "-"); mess2 << smsg << (*md5); TMessage mess3(kPROOF_CHECKFILE); smsg.Replace(0, 1, "="); mess3 << smsg << (*md5); delete md5; if (fProtocol > 8) { // Send also the option mess << (UInt_t) opt; mess2 << (UInt_t) opt; mess3 << (UInt_t) opt; } // loop over all selected nodes TIter next(fUniqueSlaves); TSlave *sl = 0; while ((sl = (TSlave *) next())) { if (!sl->IsValid()) continue; sl->GetSocket()->Send(mess); fCheckFileStatus = 0; Collect(sl, fCollectTimeout, kPROOF_CHECKFILE); if (fCheckFileStatus == 0) { if (fProtocol > 5) { // remote directory is locked, upload file over the open channel smsg.Form("%s/%s/%s", sl->GetProofWorkDir(), kPROOF_PackDir, gSystem->BaseName(par)); if (SendFile(par, (kBinary | kForce | kCpBin | kForward), smsg.Data(), sl) < 0) { Error("UploadPackage", "%s: problems uploading file %s", sl->GetOrdinal(), par.Data()); return -1; } } else { // old servers receive it via TFTP TFTP ftp(TString("root://")+sl->GetName(), 1); if (!ftp.IsZombie()) { smsg.Form("%s/%s", sl->GetProofWorkDir(), kPROOF_PackDir); ftp.cd(smsg.Data()); ftp.put(par, gSystem->BaseName(par)); } } // install package and unlock dir sl->GetSocket()->Send(mess2); fCheckFileStatus = 0; Collect(sl, fCollectTimeout, kPROOF_CHECKFILE); if (fCheckFileStatus == 0) { Error("UploadPackage", "%s: unpacking of package %s failed", sl->GetOrdinal(), gSystem->BaseName(par)); return -1; } } } // loop over all other master nodes TIter nextmaster(fNonUniqueMasters); TSlave *ma; while ((ma = (TSlave *) nextmaster())) { if (!ma->IsValid()) continue; ma->GetSocket()->Send(mess3); fCheckFileStatus = 0; Collect(ma, fCollectTimeout, kPROOF_CHECKFILE); if (fCheckFileStatus == 0) { // error -> package should have been found Error("UploadPackage", "package %s did not exist on submaster %s", par.Data(), ma->GetOrdinal()); return -1; } } return 0; } //______________________________________________________________________________ Int_t TProof::UploadPackageOnClient(const char *parpack, EUploadPackageOpt opt, TMD5 *md5) { // Upload a package on the client in ~/.proof/packages. // The 'opt' allows to specify whether the .PAR should be just unpacked // in the existing dir (opt = kUntar, default) or a remove of the existing // directory should be executed (opt = kRemoveOld), thereby triggering a full // re-build. This option if effective only for PROOF protocol > 8. // Returns 0 in case of success and -1 in case of error. // Strategy: // get md5 of package and check if it is different // from the one stored in the local package directory. If it is lock // the package directory and copy the package, unlock the directory. Int_t status = 0; if (TestBit(TProof::kIsClient)) { // Make sure that 'par' is the real path and not a symlink TString par(parpack); #ifndef WIN32 char ctmp[4096]; ssize_t sz = readlink(par.Data(), ctmp, 4096); if (sz > 0) { ctmp[sz] = '\0'; par = ctmp; } else if (TSystem::GetErrno() != EINVAL) { Warning("UploadPackageOnClient", "could not resolve the symbolik link '%s'", par.Data()); } #endif // The fPackageDir directory exists (has been created in Init()); // create symlink to the par file in the fPackageDir (needed by // master in case we run on the localhost) fPackageLock->Lock(); // Check if the requested PAR has been downloaded: if not, clean any // existing downloaded file with the same name: this is because now // the client has its own version of the package and should not check // the master repository anymore for updates TString downloadpath; downloadpath.Form("%s/%s/%s", fPackageDir.Data(), kPROOF_PackDownloadDir, gSystem->BaseName(par)); if (!gSystem->AccessPathName(downloadpath, kFileExists) && downloadpath != par) { if (gSystem->Unlink(downloadpath) != 0) { Warning("UploadPackageOnClient", "problems removing downloaded version of '%s' (%s):\n" "may imply inconsistencies in subsequent updates", gSystem->BaseName(par), downloadpath.Data()); } } TString lpar; lpar.Form("%s/%s", fPackageDir.Data(), gSystem->BaseName(par)); FileStat_t stat; Int_t st = gSystem->GetPathInfo(lpar, stat); // check if symlink, if so unlink, if not give error // NOTE: GetPathInfo() returns 1 in case of symlink that does not point to // existing file, but if fIsLink is true the symlink exists if (stat.fIsLink) gSystem->Unlink(lpar); else if (st == 0) { Error("UploadPackageOnClient", "cannot create symlink %s on client, " "another item with same name already exists", lpar.Data()); fPackageLock->Unlock(); return -1; } if (!gSystem->IsAbsoluteFileName(par)) { TString fpar = par; gSystem->Symlink(gSystem->PrependPathName(gSystem->WorkingDirectory(), fpar), lpar); } else gSystem->Symlink(par, lpar); // TODO: On Windows need to copy instead of symlink // compare md5 TString packnam = par(0, par.Length() - 4); // strip off ".par" packnam = gSystem->BaseName(packnam); // strip off path TString md5f = fPackageDir + "/" + packnam + "/PROOF-INF/md5.txt"; TMD5 *md5local = TMD5::ReadChecksum(md5f); if (!md5local || (*md5) != (*md5local)) { // if not, unzip and untar package in package directory if ((opt & TProof::kRemoveOld)) { // remove any previous package directory with same name if (gSystem->Exec(Form("%s %s/%s", kRM, fPackageDir.Data(), packnam.Data()))) Error("UploadPackageOnClient", "failure executing: %s %s/%s", kRM, fPackageDir.Data(), packnam.Data()); } // find gunzip char *gunzip = gSystem->Which(gSystem->Getenv("PATH"), kGUNZIP, kExecutePermission); if (gunzip) { // untar package if (gSystem->Exec(Form(kUNTAR2, gunzip, par.Data(), fPackageDir.Data()))) Error("Uploadpackage", "failure executing: %s", Form(kUNTAR2, gunzip, par.Data(), fPackageDir.Data())); delete [] gunzip; } else Error("UploadPackageOnClient", "%s not found", kGUNZIP); // check that fPackageDir/packnam now exists if (gSystem->AccessPathName(fPackageDir + "/" + packnam, kWritePermission)) { // par file did not unpack itself in the expected directory, failure Error("UploadPackageOnClient", "package %s did not unpack into %s/%s", par.Data(), fPackageDir.Data(), packnam.Data()); status = -1; } else { // store md5 in package/PROOF-INF/md5.txt TMD5::WriteChecksum(md5f, md5); } } fPackageLock->Unlock(); delete md5local; } return status; } //______________________________________________________________________________ Int_t TProof::Load(const char *macro, Bool_t notOnClient, Bool_t uniqueWorkers, TList *wrks) { // Load the specified macro on master, workers and, if notOnClient is // kFALSE, on the client. The macro file is uploaded if new or updated. // If existing, the corresponding header basename(macro).h or .hh, is also // uploaded. The default is to load the macro also on the client. // On masters, if uniqueWorkers is kTRUE, the macro is loaded on unique workers // only, and collection is not done; if uniqueWorkers is kFALSE, collection // from the previous request is done, and broadcasting + collection from the // other workers is done. // The wrks arg can be used on the master to limit the set of workers. // Returns 0 in case of success and -1 in case of error. if (!IsValid()) return -1; if (!macro || !strlen(macro)) { Error("Load", "need to specify a macro name"); return -1; } if (TestBit(TProof::kIsClient)) { if (wrks) { Error("Load", "the 'wrks' arg can be used only on the master"); return -1; } // Extract the file implementation name first TString implname = macro; TString acmode, args, io; implname = gSystem->SplitAclicMode(implname, acmode, args, io); // Macro names must have a standard format Int_t dot = implname.Last('.'); if (dot == kNPOS) { Info("Load", "macro '%s' does not contain a '.': do nothing", macro); return -1; } // Is there any associated header file Bool_t hasHeader = kTRUE; TString headname = implname; headname.Remove(dot); headname += ".h"; if (gSystem->AccessPathName(headname, kReadPermission)) { TString h = headname; headname.Remove(dot); headname += ".hh"; if (gSystem->AccessPathName(headname, kReadPermission)) { hasHeader = kFALSE; if (gDebug > 0) Info("Load", "no associated header file found: tried: %s %s", h.Data(), headname.Data()); } } // Send files now; the md5 check is run here; see SendFile for more // details. if (SendFile(implname, kAscii | kForward , "cache") == -1) { Info("Load", "problems sending implementation file %s", implname.Data()); return -1; } if (hasHeader) if (SendFile(headname, kAscii | kForward , "cache") == -1) { Info("Load", "problems sending header file %s", headname.Data()); return -1; } // The files are now on the workers: now we send the loading request TString basemacro = gSystem->BaseName(macro); TMessage mess(kPROOF_CACHE); mess << Int_t(kLoadMacro) << basemacro; Broadcast(mess, kActive); // Load locally, if required if (!notOnClient) { // by first forwarding the load command to the master and workers // and only then loading locally we load/build in parallel gROOT->ProcessLine(Form(".L %s", macro)); // Update the macro path TString mp(TROOT::GetMacroPath()); TString np(gSystem->DirName(macro)); if (!np.IsNull()) { np += ":"; if (!mp.BeginsWith(np) && !mp.Contains(":"+np)) { Int_t ip = (mp.BeginsWith(".:")) ? 2 : 0; mp.Insert(ip, np); TROOT::SetMacroPath(mp); if (gDebug > 0) Info("Load", "macro path set to '%s'", TROOT::GetMacroPath()); } } } // Wait for master and workers to be done Collect(kActive); } else { // On master // The files are now on the workers: now we send the loading request first // to the unique workers, so that the eventual compilation occurs only once. TString basemacro = gSystem->BaseName(macro); TMessage mess(kPROOF_CACHE); if (uniqueWorkers) { mess << Int_t(kLoadMacro) << basemacro; if (wrks) Broadcast(mess, wrks); else Broadcast(mess, kUnique); } else { // Wait for the result of the previous sending Collect(kUnique); // We then send a tuned loading request to the other workers TList others; TSlave *wrk = 0; TIter nxw(fActiveSlaves); while ((wrk = (TSlave *)nxw())) { if (!fUniqueSlaves->FindObject(wrk)) { others.Add(wrk); } } // Do not force compilation, if it was requested Int_t ld = basemacro.Last('.'); if (ld != kNPOS) { Int_t lpp = basemacro.Index("++", ld); if (lpp != kNPOS) basemacro.Replace(lpp, 2, "+"); } mess << Int_t(kLoadMacro) << basemacro; Broadcast(mess, &others); Collect(&others); } PDB(kGlobal, 1) Info("Load", "adding loaded macro: %s", macro); if (!fLoadedMacros) { fLoadedMacros = new TList(); fLoadedMacros->SetOwner(); } // if wrks is specified the macro should already be loaded on the master. if (!wrks) fLoadedMacros->Add(new TObjString(macro)); } // Done return 0; } //______________________________________________________________________________ Int_t TProof::AddDynamicPath(const char *libpath, Bool_t onClient, TList *wrks) { // Add 'libpath' to the lib path search. // Multiple paths can be specified at once separating them with a comma or // a blank. // Return 0 on success, -1 otherwise if ((!libpath || !strlen(libpath))) { if (gDebug > 0) Info("AddDynamicPath", "list is empty - nothing to do"); return 0; } // Do it also on clients, if required if (onClient) HandleLibIncPath("lib", kTRUE, libpath); TMessage m(kPROOF_LIB_INC_PATH); m << TString("lib") << (Bool_t)kTRUE; // Add paths if (libpath && strlen(libpath)) m << TString(libpath); else m << TString("-"); // Forward the request if (wrks) Broadcast(m, wrks); else Broadcast(m); Collect(kActive, fCollectTimeout); return 0; } //______________________________________________________________________________ Int_t TProof::AddIncludePath(const char *incpath, Bool_t onClient, TList *wrks) { // Add 'incpath' to the inc path search. // Multiple paths can be specified at once separating them with a comma or // a blank. // Return 0 on success, -1 otherwise if ((!incpath || !strlen(incpath))) { if (gDebug > 0) Info("AddIncludePath", "list is empty - nothing to do"); return 0; } // Do it also on clients, if required if (onClient) HandleLibIncPath("inc", kTRUE, incpath); TMessage m(kPROOF_LIB_INC_PATH); m << TString("inc") << (Bool_t)kTRUE; // Add paths if (incpath && strlen(incpath)) m << TString(incpath); else m << TString("-"); // Forward the request if (wrks) Broadcast(m, wrks); else Broadcast(m); Collect(kActive, fCollectTimeout); return 0; } //______________________________________________________________________________ Int_t TProof::RemoveDynamicPath(const char *libpath, Bool_t onClient) { // Remove 'libpath' from the lib path search. // Multiple paths can be specified at once separating them with a comma or // a blank. // Return 0 on success, -1 otherwise if ((!libpath || !strlen(libpath))) { if (gDebug > 0) Info("RemoveDynamicPath", "list is empty - nothing to do"); return 0; } // Do it also on clients, if required if (onClient) HandleLibIncPath("lib", kFALSE, libpath); TMessage m(kPROOF_LIB_INC_PATH); m << TString("lib") <<(Bool_t)kFALSE; // Add paths if (libpath && strlen(libpath)) m << TString(libpath); else m << TString("-"); // Forward the request Broadcast(m); Collect(kActive, fCollectTimeout); return 0; } //______________________________________________________________________________ Int_t TProof::RemoveIncludePath(const char *incpath, Bool_t onClient) { // Remove 'incpath' from the inc path search. // Multiple paths can be specified at once separating them with a comma or // a blank. // Return 0 on success, -1 otherwise if ((!incpath || !strlen(incpath))) { if (gDebug > 0) Info("RemoveIncludePath", "list is empty - nothing to do"); return 0; } // Do it also on clients, if required if (onClient) HandleLibIncPath("in", kFALSE, incpath); TMessage m(kPROOF_LIB_INC_PATH); m << TString("inc") << (Bool_t)kFALSE; // Add paths if (incpath && strlen(incpath)) m << TString(incpath); else m << TString("-"); // Forward the request Broadcast(m); Collect(kActive, fCollectTimeout); return 0; } //______________________________________________________________________________ void TProof::HandleLibIncPath(const char *what, Bool_t add, const char *dirs) { // Handle lib, inc search paths modification request TString type(what); TString path(dirs); // Check type of action if ((type != "lib") && (type != "inc")) { Error("HandleLibIncPath","unknown action type: %s - protocol error?", type.Data()); return; } // Separators can be either commas or blanks path.ReplaceAll(","," "); // Decompose lists TObjArray *op = 0; if (path.Length() > 0 && path != "-") { if (!(op = path.Tokenize(" "))) { Warning("HandleLibIncPath","decomposing path %s", path.Data()); return; } } if (add) { if (type == "lib") { // Add libs TIter nxl(op, kIterBackward); TObjString *lib = 0; while ((lib = (TObjString *) nxl())) { // Expand path TString xlib = lib->GetName(); gSystem->ExpandPathName(xlib); // Add to the dynamic lib search path if it exists and can be read if (!gSystem->AccessPathName(xlib, kReadPermission)) { TString newlibpath = gSystem->GetDynamicPath(); // In the first position after the working dir Int_t pos = 0; if (newlibpath.BeginsWith(".:")) pos = 2; if (newlibpath.Index(xlib) == kNPOS) { newlibpath.Insert(pos,Form("%s:", xlib.Data())); gSystem->SetDynamicPath(newlibpath); } } else { if (gDebug > 0) Info("HandleLibIncPath", "libpath %s does not exist or cannot be read - not added", xlib.Data()); } } } else { // Add incs TIter nxi(op); TObjString *inc = 0; while ((inc = (TObjString *) nxi())) { // Expand path TString xinc = inc->GetName(); gSystem->ExpandPathName(xinc); // Add to the dynamic lib search path if it exists and can be read if (!gSystem->AccessPathName(xinc, kReadPermission)) { TString curincpath = gSystem->GetIncludePath(); if (curincpath.Index(xinc) == kNPOS) gSystem->AddIncludePath(Form("-I%s", xinc.Data())); } else if (gDebug > 0) Info("HandleLibIncPath", "incpath %s does not exist or cannot be read - not added", xinc.Data()); } } } else { if (type == "lib") { // Remove libs TIter nxl(op); TObjString *lib = 0; while ((lib = (TObjString *) nxl())) { // Expand path TString xlib = lib->GetName(); gSystem->ExpandPathName(xlib); // Remove from the dynamic lib search path TString newlibpath = gSystem->GetDynamicPath(); newlibpath.ReplaceAll(Form("%s:", xlib.Data()),""); gSystem->SetDynamicPath(newlibpath); } } else { // Remove incs TIter nxi(op); TObjString *inc = 0; while ((inc = (TObjString *) nxi())) { TString newincpath = gSystem->GetIncludePath(); newincpath.ReplaceAll(Form("-I%s", inc->GetName()),""); // Remove the interpreter path (added anyhow internally) newincpath.ReplaceAll(gInterpreter->GetIncludePath(),""); gSystem->SetIncludePath(newincpath); } } } } //______________________________________________________________________________ TList *TProof::GetListOfPackages() { // Get from the master the list of names of the packages available. if (!IsValid()) return (TList *)0; TMessage mess(kPROOF_CACHE); mess << Int_t(kListPackages); Broadcast(mess); Collect(kActive, fCollectTimeout); return fAvailablePackages; } //______________________________________________________________________________ TList *TProof::GetListOfEnabledPackages() { // Get from the master the list of names of the packages enabled. if (!IsValid()) return (TList *)0; TMessage mess(kPROOF_CACHE); mess << Int_t(kListEnabledPackages); Broadcast(mess); Collect(kActive, fCollectTimeout); return fEnabledPackages; } //______________________________________________________________________________ void TProof::PrintProgress(Long64_t total, Long64_t processed, Float_t procTime) { // Print a progress bar on stderr. Used in batch mode. if (fPrintProgress) { Bool_t redirlog = fRedirLog; fRedirLog = kFALSE; // Call the external function (*fPrintProgress)(total, processed, procTime); fRedirLog = redirlog; return; } fprintf(stderr, "[TProof::Progress] Total %lld events\t|", total); for (int l = 0; l < 20; l++) { if (total > 0) { if (l < 20*processed/total) fprintf(stderr, "="); else if (l == 20*processed/total) fprintf(stderr, ">"); else if (l > 20*processed/total) fprintf(stderr, "."); } else fprintf(stderr, "="); } Float_t evtrti = (procTime > 0. && processed > 0) ? processed / procTime : -1.; if (evtrti > 0.) fprintf(stderr, "| %.02f %% [%.1f evts/s]\r", (total ? ((100.0*processed)/total) : 100.0), evtrti); else fprintf(stderr, "| %.02f %%\r", (total ? ((100.0*processed)/total) : 100.0)); if (processed >= total) fprintf(stderr, "\n"); } //______________________________________________________________________________ void TProof::Progress(Long64_t total, Long64_t processed) { // Get query progress information. Connect a slot to this signal // to track progress. if (fPrintProgress) { // Call the external function return (*fPrintProgress)(total, processed, -1.); } PDB(kGlobal,1) Info("Progress","%2f (%lld/%lld)", 100.*processed/total, processed, total); if (gROOT->IsBatch()) { // Simple progress bar if (total > 0) PrintProgress(total, processed); } else { EmitVA("Progress(Long64_t,Long64_t)", 2, total, processed); } } //______________________________________________________________________________ void TProof::Progress(Long64_t total, Long64_t processed, Long64_t bytesread, Float_t initTime, Float_t procTime, Float_t evtrti, Float_t mbrti) { // Get query progress information. Connect a slot to this signal // to track progress. PDB(kGlobal,1) Info("Progress","%lld %lld %lld %f %f %f %f", total, processed, bytesread, initTime, procTime, evtrti, mbrti); if (gROOT->IsBatch()) { // Simple progress bar if (total > 0) PrintProgress(total, processed, procTime); } else { EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)", 7, total, processed, bytesread, initTime, procTime, evtrti, mbrti); } } //______________________________________________________________________________ void TProof::Progress(Long64_t total, Long64_t processed, Long64_t bytesread, Float_t initTime, Float_t procTime, Float_t evtrti, Float_t mbrti, Int_t actw, Int_t tses, Float_t eses) { // Get query progress information. Connect a slot to this signal // to track progress. PDB(kGlobal,1) Info("Progress","%lld %lld %lld %f %f %f %f %d %f", total, processed, bytesread, initTime, procTime, evtrti, mbrti, actw, eses); if (gROOT->IsBatch()) { // Simple progress bar if (total > 0) PrintProgress(total, processed, procTime); } else { EmitVA("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t,Int_t,Int_t,Float_t)", 10, total, processed, bytesread, initTime, procTime, evtrti, mbrti, actw, tses, eses); } } //______________________________________________________________________________ void TProof::Feedback(TList *objs) { // Get list of feedback objects. Connect a slot to this signal // to monitor the feedback object. PDB(kGlobal,1) Info("Feedback","%d objects", objs->GetSize()); PDB(kFeedback,1) { Info("Feedback","%d objects", objs->GetSize()); objs->ls(); } Emit("Feedback(TList *objs)", (Long_t) objs); } //______________________________________________________________________________ void TProof::CloseProgressDialog() { // Close progress dialog. PDB(kGlobal,1) Info("CloseProgressDialog", "called: have progress dialog: %d", fProgressDialogStarted); // Nothing to do if not there if (!fProgressDialogStarted) return; Emit("CloseProgressDialog()"); } //______________________________________________________________________________ void TProof::ResetProgressDialog(const char *sel, Int_t sz, Long64_t fst, Long64_t ent) { // Reset progress dialog. PDB(kGlobal,1) Info("ResetProgressDialog","(%s,%d,%lld,%lld)", sel, sz, fst, ent); EmitVA("ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)", 4, sel, sz, fst, ent); } //______________________________________________________________________________ void TProof::StartupMessage(const char *msg, Bool_t st, Int_t done, Int_t total) { // Send startup message. PDB(kGlobal,1) Info("StartupMessage","(%s,%d,%d,%d)", msg, st, done, total); EmitVA("StartupMessage(const char*,Bool_t,Int_t,Int_t)", 4, msg, st, done, total); } //______________________________________________________________________________ void TProof::DataSetStatus(const char *msg, Bool_t st, Int_t done, Int_t total) { // Send dataset preparation status. PDB(kGlobal,1) Info("DataSetStatus","(%s,%d,%d,%d)", msg, st, done, total); EmitVA("DataSetStatus(const char*,Bool_t,Int_t,Int_t)", 4, msg, st, done, total); } //______________________________________________________________________________ void TProof::SendDataSetStatus(const char *action, UInt_t done, UInt_t tot, Bool_t st) { // Send or notify data set status if (IsLite()) { if (tot) { TString type = "files"; Int_t frac = (Int_t) (done*100.)/tot; char msg[512] = {0}; if (frac >= 100) { snprintf(msg, 512, "%s: OK (%d %s) \n", action,tot, type.Data()); } else { snprintf(msg, 512, "%s: %d out of %d (%d %%)\r", action, done, tot, frac); } if (fSync) fprintf(stderr,"%s", msg); else NotifyLogMsg(msg, 0); } return; } if (TestBit(TProof::kIsMaster)) { TMessage mess(kPROOF_DATASET_STATUS); mess << TString(action) << tot << done << st; gProofServ->GetSocket()->Send(mess); } } //______________________________________________________________________________ void TProof::QueryResultReady(const char *ref) { // Notify availability of a query result. PDB(kGlobal,1) Info("QueryResultReady","ref: %s", ref); Emit("QueryResultReady(const char*)",ref); } //______________________________________________________________________________ void TProof::ValidateDSet(TDSet *dset) { // Validate a TDSet. if (dset->ElementsValid()) return; TList nodes; nodes.SetOwner(); TList slholder; slholder.SetOwner(); TList elemholder; elemholder.SetOwner(); // build nodelist with slaves and elements TIter nextSlave(GetListOfActiveSlaves()); while (TSlave *sl = dynamic_cast<TSlave*>(nextSlave())) { TList *sllist = 0; TPair *p = dynamic_cast<TPair*>(nodes.FindObject(sl->GetName())); if (!p) { sllist = new TList; sllist->SetName(sl->GetName()); slholder.Add(sllist); TList *elemlist = new TList; elemlist->SetName(TString(sl->GetName())+"_elem"); elemholder.Add(elemlist); nodes.Add(new TPair(sllist, elemlist)); } else { sllist = dynamic_cast<TList*>(p->Key()); } if (sllist) sllist->Add(sl); } // add local elements to nodes TList nonLocal; // list of nonlocal elements // make two iterations - first add local elements - then distribute nonlocals for (Int_t i = 0; i < 2; i++) { Bool_t local = i>0?kFALSE:kTRUE; TIter nextElem(local ? dset->GetListOfElements() : &nonLocal); while (TDSetElement *elem = dynamic_cast<TDSetElement*>(nextElem())) { if (elem->GetValid()) continue; TPair *p = dynamic_cast<TPair*>(local?nodes.FindObject(TUrl(elem->GetFileName()).GetHost()):nodes.At(0)); if (p) { TList *eli = dynamic_cast<TList*>(p->Value()); TList *sli = dynamic_cast<TList*>(p->Key()); if (eli && sli) { eli->Add(elem); // order list by elements/slave TPair *p2 = p; Bool_t stop = kFALSE; while (!stop) { TPair *p3 = dynamic_cast<TPair*>(nodes.After(p2->Key())); if (p3) { TList *p3v = dynamic_cast<TList*>(p3->Value()); TList *p3k = dynamic_cast<TList*>(p3->Key()); if (p3v && p3k) { Int_t nelem = p3v->GetSize(); Int_t nsl = p3k->GetSize(); if (nelem*sli->GetSize() < eli->GetSize()*nsl) p2 = p3; else stop = kTRUE; } } else { stop = kTRUE; } } if (p2!=p) { nodes.Remove(p->Key()); nodes.AddAfter(p2->Key(), p); } } else { Warning("ValidateDSet", "invalid values from TPair! Protocol error?"); continue; } } else { if (local) { nonLocal.Add(elem); } else { Warning("ValidateDSet", "no node to allocate TDSetElement to - ignoring"); } } } } // send to slaves TList usedslaves; TIter nextNode(&nodes); SetDSet(dset); // set dset to be validated in Collect() while (TPair *node = dynamic_cast<TPair*>(nextNode())) { TList *slaves = dynamic_cast<TList*>(node->Key()); TList *setelements = dynamic_cast<TList*>(node->Value()); if (!slaves || !setelements) continue; // distribute elements over the slaves Int_t nslaves = slaves->GetSize(); Int_t nelements = setelements->GetSize(); for (Int_t i=0; i<nslaves; i++) { TDSet copyset(dset->GetType(), dset->GetObjName(), dset->GetDirectory()); for (Int_t j = (i*nelements)/nslaves; j < ((i+1)*nelements)/nslaves; j++) { TDSetElement *elem = dynamic_cast<TDSetElement*>(setelements->At(j)); if (elem) { copyset.Add(elem->GetFileName(), elem->GetObjName(), elem->GetDirectory(), elem->GetFirst(), elem->GetNum(), elem->GetMsd()); } } if (copyset.GetListOfElements()->GetSize()>0) { TMessage mesg(kPROOF_VALIDATE_DSET); mesg << &copyset; TSlave *sl = dynamic_cast<TSlave*>(slaves->At(i)); if (sl) { PDB(kGlobal,1) Info("ValidateDSet", "Sending TDSet with %d elements to slave %s" " to be validated", copyset.GetListOfElements()->GetSize(), sl->GetOrdinal()); sl->GetSocket()->Send(mesg); usedslaves.Add(sl); } } } } PDB(kGlobal,1) Info("ValidateDSet","Calling Collect"); Collect(&usedslaves); SetDSet(0); } //______________________________________________________________________________ void TProof::AddInputData(TObject *obj, Bool_t push) { // Add data objects that might be needed during the processing of // the selector (see Process()). This object can be very large, so they // are distributed in an optimized way using a dedicated file. // If push is TRUE the input data are sent over even if no apparent change // occured to the list. if (obj) { if (!fInputData) fInputData = new TList; if (!fInputData->FindObject(obj)) { fInputData->Add(obj); SetBit(TProof::kNewInputData); } } if (push) SetBit(TProof::kNewInputData); } //______________________________________________________________________________ void TProof::ClearInputData(TObject *obj) { // Remove obj form the input data list; if obj is null (default), clear the // input data info. if (!obj) { if (fInputData) { fInputData->SetOwner(kTRUE); SafeDelete(fInputData); } ResetBit(TProof::kNewInputData); // Also remove any info about input data in the input list TObject *o = 0; TList *in = GetInputList(); while ((o = GetInputList()->FindObject("PROOF_InputDataFile"))) in->Remove(o); while ((o = GetInputList()->FindObject("PROOF_InputData"))) in->Remove(o); // ... and reset the file fInputDataFile = ""; gSystem->Unlink(kPROOF_InputDataFile); } else if (fInputData) { Int_t sz = fInputData->GetSize(); while (fInputData->FindObject(obj)) fInputData->Remove(obj); // Flag for update, if anything changed if (sz != fInputData->GetSize()) SetBit(TProof::kNewInputData); } } //______________________________________________________________________________ void TProof::ClearInputData(const char *name) { // Remove obj 'name' form the input data list; TObject *obj = (fInputData && name) ? fInputData->FindObject(name) : 0; if (obj) ClearInputData(obj); } //______________________________________________________________________________ void TProof::SetInputDataFile(const char *datafile) { // Set the file to be used to optimally distribute the input data objects. // If the file exists the object in the file are added to those in the // fInputData list. If the file path is null, a default file will be created // at the moment of sending the processing request with the content of // the fInputData list. See also SendInputDataFile. if (datafile && strlen(datafile) > 0) { if (fInputDataFile != datafile && strcmp(datafile, kPROOF_InputDataFile)) SetBit(TProof::kNewInputData); fInputDataFile = datafile; } else { if (!fInputDataFile.IsNull()) SetBit(TProof::kNewInputData); fInputDataFile = ""; } // Make sure that the chosen file is readable if (fInputDataFile != kPROOF_InputDataFile && !fInputDataFile.IsNull() && gSystem->AccessPathName(fInputDataFile, kReadPermission)) { fInputDataFile = ""; } } //______________________________________________________________________________ void TProof::SendInputDataFile() { // Send the input data objects to the master; the objects are taken from the // dedicated list and / or the specified file. // If the fInputData is empty the specified file is sent over. // If there is no specified file, a file named "inputdata.root" is created locally // with the content of fInputData and sent over to the master. // If both fInputData and the specified file are not empty, a copy of the file // is made locally and augmented with the content of fInputData. // Prepare the file TString dataFile; PrepareInputDataFile(dataFile); // Send it, if not empty if (dataFile.Length() > 0) { Info("SendInputDataFile", "broadcasting %s", dataFile.Data()); BroadcastFile(dataFile.Data(), kBinary, "cache", kActive); // Set the name in the input list AddInput(new TNamed("PROOF_InputDataFile", Form("cache:%s", gSystem->BaseName(dataFile)))); } } //______________________________________________________________________________ void TProof::PrepareInputDataFile(TString &dataFile) { // Prepare the file with the input data objects to be sent the master; the // objects are taken from the dedicated list and / or the specified file. // If the fInputData is empty the specified file is sent over. // If there is no specified file, a file named "inputdata.root" is created locally // with the content of fInputData and sent over to the master. // If both fInputData and the specified file are not empty, a copy of the file // is made locally and augmented with the content of fInputData. // Save info about new data for usage in this call; Bool_t newdata = TestBit(TProof::kNewInputData) ? kTRUE : kFALSE; // Next time we need some change ResetBit(TProof::kNewInputData); // Check the list Bool_t list_ok = (fInputData && fInputData->GetSize() > 0) ? kTRUE : kFALSE; // Check the file Bool_t file_ok = kFALSE; if (fInputDataFile != kPROOF_InputDataFile && !fInputDataFile.IsNull() && !gSystem->AccessPathName(fInputDataFile, kReadPermission)) { // It must contain something TFile *f = TFile::Open(fInputDataFile); if (f && f->GetListOfKeys() && f->GetListOfKeys()->GetSize() > 0) file_ok = kTRUE; } // Remove any info about input data in the input list TObject *o = 0; TList *in = GetInputList(); while ((o = GetInputList()->FindObject("PROOF_InputDataFile"))) in->Remove(o); while ((o = GetInputList()->FindObject("PROOF_InputData"))) in->Remove(o); // We must have something to send dataFile = ""; if (!list_ok && !file_ok) return; // Three cases: if (file_ok && !list_ok) { // Just send the file dataFile = fInputDataFile; } else if (!file_ok && list_ok) { fInputDataFile = kPROOF_InputDataFile; // Nothing to do, if no new data if (!newdata && !gSystem->AccessPathName(fInputDataFile)) return; // Create the file first TFile *f = TFile::Open(fInputDataFile, "RECREATE"); if (f) { f->cd(); TIter next(fInputData); TObject *obj; while ((obj = next())) { obj->Write(0, TObject::kSingleKey, 0); } f->Close(); SafeDelete(f); } else { Error("PrepareInputDataFile", "could not (re-)create %s", fInputDataFile.Data()); return; } dataFile = fInputDataFile; } else if (file_ok && list_ok) { dataFile = kPROOF_InputDataFile; // Create the file if not existing or there are new data if (newdata || gSystem->AccessPathName(dataFile)) { // Cleanup previous file if obsolete if (!gSystem->AccessPathName(dataFile)) gSystem->Unlink(dataFile); if (dataFile != fInputDataFile) { // Make a local copy first if (gSystem->CopyFile(fInputDataFile, dataFile, kTRUE) != 0) { Error("PrepareInputDataFile", "could not make local copy of %s", fInputDataFile.Data()); return; } } // Add the input data list TFile *f = TFile::Open(dataFile, "UPDATE"); if (f) { f->cd(); TIter next(fInputData); TObject *obj = 0; while ((obj = next())) { obj->Write(0, TObject::kSingleKey, 0); } f->Close(); SafeDelete(f); } else { Error("PrepareInputDataFile", "could not open %s for updating", dataFile.Data()); return; } } } // Done return; } //______________________________________________________________________________ void TProof::AddInput(TObject *obj) { // Add objects that might be needed during the processing of // the selector (see Process()). if (fPlayer) fPlayer->AddInput(obj); } //______________________________________________________________________________ void TProof::ClearInput() { // Clear input object list. if (fPlayer) fPlayer->ClearInput(); // the system feedback list is always in the input list AddInput(fFeedback); } //______________________________________________________________________________ TList *TProof::GetInputList() { // Get input list. return (fPlayer ? fPlayer->GetInputList() : (TList *)0); } //______________________________________________________________________________ TObject *TProof::GetOutput(const char *name) { // Get specified object that has been produced during the processing // (see Process()). // Can be called by MarkBad on the master before the player is initialized return (fPlayer) ? fPlayer->GetOutput(name) : (TObject *)0; } //______________________________________________________________________________ TList *TProof::GetOutputList() { // Get list with all object created during processing (see Process()). return (fPlayer ? fPlayer->GetOutputList() : (TList *)0); } //______________________________________________________________________________ void TProof::SetParameter(const char *par, const char *value) { // Set input list parameter. If the parameter is already // set it will be set to the new value. if (!fPlayer) { Warning("SetParameter", "player undefined! Ignoring"); return; } TList *il = fPlayer->GetInputList(); TObject *item = il->FindObject(par); if (item) { il->Remove(item); delete item; } il->Add(new TNamed(par, value)); } //______________________________________________________________________________ void TProof::SetParameter(const char *par, Int_t value) { // Set an input list parameter. if (!fPlayer) { Warning("SetParameter", "player undefined! Ignoring"); return; } TList *il = fPlayer->GetInputList(); TObject *item = il->FindObject(par); if (item) { il->Remove(item); delete item; } il->Add(new TParameter<Int_t>(par, value)); } //______________________________________________________________________________ void TProof::SetParameter(const char *par, Long_t value) { // Set an input list parameter. if (!fPlayer) { Warning("SetParameter", "player undefined! Ignoring"); return; } TList *il = fPlayer->GetInputList(); TObject *item = il->FindObject(par); if (item) { il->Remove(item); delete item; } il->Add(new TParameter<Long_t>(par, value)); } //______________________________________________________________________________ void TProof::SetParameter(const char *par, Long64_t value) { // Set an input list parameter. if (!fPlayer) { Warning("SetParameter", "player undefined! Ignoring"); return; } TList *il = fPlayer->GetInputList(); TObject *item = il->FindObject(par); if (item) { il->Remove(item); delete item; } il->Add(new TParameter<Long64_t>(par, value)); } //______________________________________________________________________________ void TProof::SetParameter(const char *par, Double_t value) { // Set an input list parameter. if (!fPlayer) { Warning("SetParameter", "player undefined! Ignoring"); return; } TList *il = fPlayer->GetInputList(); TObject *item = il->FindObject(par); if (item) { il->Remove(item); delete item; } il->Add(new TParameter<Double_t>(par, value)); } //______________________________________________________________________________ TObject *TProof::GetParameter(const char *par) const { // Get specified parameter. A parameter set via SetParameter() is either // a TParameter or a TNamed or 0 in case par is not defined. if (!fPlayer) { Warning("GetParameter", "player undefined! Ignoring"); return (TObject *)0; } TList *il = fPlayer->GetInputList(); return il->FindObject(par); } //______________________________________________________________________________ void TProof::DeleteParameters(const char *wildcard) { // Delete the input list parameters specified by a wildcard (e.g. PROOF_*) // or exact name (e.g. PROOF_MaxSlavesPerNode). if (!fPlayer) return; if (!wildcard) wildcard = ""; TRegexp re(wildcard, kTRUE); Int_t nch = strlen(wildcard); TList *il = fPlayer->GetInputList(); if (il) { TObject *p = 0; TIter next(il); while ((p = next())) { TString s = p->GetName(); if (nch && s != wildcard && s.Index(re) == kNPOS) continue; il->Remove(p); delete p; } } } //______________________________________________________________________________ void TProof::ShowParameters(const char *wildcard) const { // Show the input list parameters specified by the wildcard. // Default is the special PROOF control parameters (PROOF_*). if (!fPlayer) return; if (!wildcard) wildcard = ""; TRegexp re(wildcard, kTRUE); Int_t nch = strlen(wildcard); TList *il = fPlayer->GetInputList(); TObject *p; TIter next(il); while ((p = next())) { TString s = p->GetName(); if (nch && s != wildcard && s.Index(re) == kNPOS) continue; if (p->IsA() == TNamed::Class()) { Printf("%s\t\t\t%s", s.Data(), p->GetTitle()); } else if (p->IsA() == TParameter<Long_t>::Class()) { Printf("%s\t\t\t%ld", s.Data(), dynamic_cast<TParameter<Long_t>*>(p)->GetVal()); } else if (p->IsA() == TParameter<Long64_t>::Class()) { Printf("%s\t\t\t%lld", s.Data(), dynamic_cast<TParameter<Long64_t>*>(p)->GetVal()); } else if (p->IsA() == TParameter<Double_t>::Class()) { Printf("%s\t\t\t%f", s.Data(), dynamic_cast<TParameter<Double_t>*>(p)->GetVal()); } else { Printf("%s\t\t\t%s", s.Data(), p->GetTitle()); } } } //______________________________________________________________________________ void TProof::AddFeedback(const char *name) { // Add object to feedback list. PDB(kFeedback, 3) Info("AddFeedback", "Adding object \"%s\" to feedback", name); if (fFeedback->FindObject(name) == 0) fFeedback->Add(new TObjString(name)); } //______________________________________________________________________________ void TProof::RemoveFeedback(const char *name) { // Remove object from feedback list. TObject *obj = fFeedback->FindObject(name); if (obj != 0) { fFeedback->Remove(obj); delete obj; } } //______________________________________________________________________________ void TProof::ClearFeedback() { // Clear feedback list. fFeedback->Delete(); } //______________________________________________________________________________ void TProof::ShowFeedback() const { // Show items in feedback list. if (fFeedback->GetSize() == 0) { Info("","no feedback requested"); return; } fFeedback->Print(); } //______________________________________________________________________________ TList *TProof::GetFeedbackList() const { // Return feedback list. return fFeedback; } //______________________________________________________________________________ TTree *TProof::GetTreeHeader(TDSet *dset) { // Creates a tree header (a tree with nonexisting files) object for // the DataSet. TList *l = GetListOfActiveSlaves(); TSlave *sl = (TSlave*) l->First(); if (sl == 0) { Error("GetTreeHeader", "No connection"); return 0; } TSocket *soc = sl->GetSocket(); TMessage msg(kPROOF_GETTREEHEADER); msg << dset; soc->Send(msg); TMessage *reply; Int_t d = -1; if (fProtocol >= 20) { Collect(sl, fCollectTimeout, kPROOF_GETTREEHEADER); reply = (TMessage *) fRecvMessages->First(); } else { d = soc->Recv(reply); } if (!reply) { Error("GetTreeHeader", "Error getting a replay from the master.Result %d", (int) d); return 0; } TString s1; TTree *t = 0; (*reply) >> s1; if (s1 == "Success") (*reply) >> t; PDB(kGlobal, 1) { if (t) { Info("GetTreeHeader", "%s, message size: %d, entries: %d", s1.Data(), reply->BufferSize(), (int) t->GetMaxEntryLoop()); } else { Info("GetTreeHeader", "tree header retrieval failed"); } } delete reply; return t; } //______________________________________________________________________________ TDrawFeedback *TProof::CreateDrawFeedback() { // Draw feedback creation proxy. When accessed via TProof avoids // link dependency on libProofPlayer. return (fPlayer ? fPlayer->CreateDrawFeedback(this) : (TDrawFeedback *)0); } //______________________________________________________________________________ void TProof::SetDrawFeedbackOption(TDrawFeedback *f, Option_t *opt) { // Set draw feedback option. if (fPlayer) fPlayer->SetDrawFeedbackOption(f, opt); } //______________________________________________________________________________ void TProof::DeleteDrawFeedback(TDrawFeedback *f) { // Delete draw feedback object. if (fPlayer) fPlayer->DeleteDrawFeedback(f); } //______________________________________________________________________________ TList *TProof::GetOutputNames() { // FIXME: to be written return 0; /* TMessage msg(kPROOF_GETOUTPUTLIST); TList* slaves = fActiveSlaves; Broadcast(msg, slaves); TMonitor mon; TList* outputList = new TList(); TIter si(slaves); TSlave *slave; while ((slave = (TSlave*)si.Next()) != 0) { PDB(kGlobal,4) Info("GetOutputNames","Socket added to monitor: %p (%s)", slave->GetSocket(), slave->GetName()); mon.Add(slave->GetSocket()); } mon.ActivateAll(); ((TProof*)gProof)->DeActivateAsyncInput(); ((TProof*)gProof)->fCurrentMonitor = &mon; while (mon.GetActive() != 0) { TSocket *sock = mon.Select(); if (!sock) { Error("GetOutputList","TMonitor::.Select failed!"); break; } mon.DeActivate(sock); TMessage *reply; if (sock->Recv(reply) <= 0) { MarkBad(slave, "receive failed after kPROOF_GETOUTPUTLIST request"); // Error("GetOutputList","Recv failed! for slave-%d (%s)", // slave->GetOrdinal(), slave->GetName()); continue; } if (reply->What() != kPROOF_GETOUTPUTNAMES ) { // Error("GetOutputList","unexpected message %d from slawe-%d (%s)", reply->What(), // slave->GetOrdinal(), slave->GetName()); MarkBad(slave, "wrong reply to kPROOF_GETOUTPUTLIST request"); continue; } TList* l; (*reply) >> l; TIter next(l); TNamed *n; while ( (n = dynamic_cast<TNamed*> (next())) ) { if (!outputList->FindObject(n->GetName())) outputList->Add(n); } delete reply; } ((TProof*)gProof)->fCurrentMonitor = 0; return outputList; */ } //______________________________________________________________________________ void TProof::Browse(TBrowser *b) { // Build the PROOF's structure in the browser. b->Add(fActiveSlaves, fActiveSlaves->Class(), "fActiveSlaves"); b->Add(&fMaster, fMaster.Class(), "fMaster"); b->Add(fFeedback, fFeedback->Class(), "fFeedback"); b->Add(fChains, fChains->Class(), "fChains"); if (fPlayer) { b->Add(fPlayer->GetInputList(), fPlayer->GetInputList()->Class(), "InputList"); if (fPlayer->GetOutputList()) b->Add(fPlayer->GetOutputList(), fPlayer->GetOutputList()->Class(), "OutputList"); if (fPlayer->GetListOfResults()) b->Add(fPlayer->GetListOfResults(), fPlayer->GetListOfResults()->Class(), "ListOfResults"); } } //______________________________________________________________________________ void TProof::SetPlayer(TVirtualProofPlayer *player) { // Set a new PROOF player. if (fPlayer) delete fPlayer; fPlayer = player; }; //______________________________________________________________________________ TVirtualProofPlayer *TProof::MakePlayer(const char *player, TSocket *s) { // Construct a TProofPlayer object. The player string specifies which // player should be created: remote, slave, sm (supermaster) or base. // Default is remote. Socket is needed in case a slave player is created. if (!player) player = "remote"; SetPlayer(TVirtualProofPlayer::Create(player, this, s)); return GetPlayer(); } //______________________________________________________________________________ void TProof::AddChain(TChain *chain) { // Add chain to data set fChains->Add(chain); } //______________________________________________________________________________ void TProof::RemoveChain(TChain *chain) { // Remove chain from data set fChains->Remove(chain); } //______________________________________________________________________________ void TProof::GetLog(Int_t start, Int_t end) { // Ask for remote logs in the range [start, end]. If start == -1 all the // messages not yet received are sent back. if (!IsValid() || TestBit(TProof::kIsMaster)) return; TMessage msg(kPROOF_LOGFILE); msg << start << end; Broadcast(msg, kActive); Collect(kActive, fCollectTimeout); } //______________________________________________________________________________ TMacro *TProof::GetLastLog() { // Fill a TMacro with the log lines since the last reading (fLogFileR) // Return (TMacro *)0 if no line was logged. // The returned TMacro must be deleted by the caller. TMacro *maclog = 0; // Save present offset off_t nowlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_CUR); if (nowlog < 0) { SysError("GetLastLog", "problem lseeking log file to current position (errno: %d)", TSystem::GetErrno()); return maclog; } // Get extremes off_t startlog = nowlog; off_t endlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_END); if (endlog < 0) { SysError("GetLastLog", "problem lseeking log file to end position (errno: %d)", TSystem::GetErrno()); return maclog; } // Perhaps nothing to log UInt_t tolog = (UInt_t)(endlog - startlog); if (tolog <= 0) return maclog; // Set starting point if (lseek(fileno(fLogFileR), startlog, SEEK_SET) < 0) { SysError("GetLastLog", "problem lseeking log file to start position (errno: %d)", TSystem::GetErrno()); return maclog; } // Create the output object maclog = new TMacro; // Now we go char line[2048]; Int_t wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog; while (fgets(line, wanted, fLogFileR)) { Int_t r = strlen(line); if (r > 0) { if (line[r-1] == '\n') line[r-1] = '\0'; maclog->AddLine(line); } else { // Done break; } tolog -= r; wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog; } // Restore original pointer if (lseek(fileno(fLogFileR), nowlog, SEEK_SET) < 0) { Warning("GetLastLog", "problem lseeking log file to original position (errno: %d)", TSystem::GetErrno()); } // Done return maclog; } //______________________________________________________________________________ void TProof::PutLog(TQueryResult *pq) { // Display log of query pq into the log window frame if (!pq) return; TList *lines = pq->GetLogFile()->GetListOfLines(); if (lines) { TIter nxl(lines); TObjString *l = 0; while ((l = (TObjString *)nxl())) EmitVA("LogMessage(const char*,Bool_t)", 2, l->GetName(), kFALSE); } } //______________________________________________________________________________ void TProof::ShowLog(const char *queryref) { // Display on screen the content of the temporary log file for query // in reference // Make sure we have all info (GetListOfQueries retrieves the // head info only) Retrieve(queryref); if (fPlayer) { if (queryref) { if (fPlayer->GetListOfResults()) { TIter nxq(fPlayer->GetListOfResults()); TQueryResult *qr = 0; while ((qr = (TQueryResult *) nxq())) if (strstr(queryref, qr->GetTitle()) && strstr(queryref, qr->GetName())) break; if (qr) { PutLog(qr); return; } } } } } //______________________________________________________________________________ void TProof::ShowLog(Int_t qry) { // Display on screen the content of the temporary log file. // If qry == -2 show messages from the last (current) query. // If qry == -1 all the messages not yet displayed are shown (default). // If qry == 0, all the messages in the file are shown. // If qry > 0, only the messages related to query 'qry' are shown. // For qry != -1 the original file offset is restored at the end // Save present offset off_t nowlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_CUR); if (nowlog < 0) { SysError("ShowLog", "problem lseeking log file (errno: %d)", TSystem::GetErrno()); return; } // Get extremes off_t startlog = nowlog; off_t endlog = lseek(fileno(fLogFileR), (off_t) 0, SEEK_END); if (endlog < 0) { SysError("ShowLog", "problem lseeking log file (errno: %d)", TSystem::GetErrno()); return; } lseek(fileno(fLogFileR), nowlog, SEEK_SET); if (qry == 0) { startlog = 0; lseek(fileno(fLogFileR), (off_t) 0, SEEK_SET); } else if (qry != -1) { TQueryResult *pq = 0; if (qry == -2) { // Pickup the last one pq = (GetQueryResults()) ? ((TQueryResult *)(GetQueryResults()->Last())) : 0; if (!pq) { GetListOfQueries(); if (fQueries) pq = (TQueryResult *)(fQueries->Last()); } } else if (qry > 0) { TList *queries = GetQueryResults(); if (queries) { TIter nxq(queries); while ((pq = (TQueryResult *)nxq())) if (qry == pq->GetSeqNum()) break; } if (!pq) { queries = GetListOfQueries(); TIter nxq(queries); while ((pq = (TQueryResult *)nxq())) if (qry == pq->GetSeqNum()) break; } } if (pq) { PutLog(pq); return; } else { if (gDebug > 0) Info("ShowLog","query %d not found in list", qry); qry = -1; } } // Number of bytes to log UInt_t tolog = (UInt_t)(endlog - startlog); // Perhaps nothing if (tolog <= 0) // Set starting point lseek(fileno(fLogFileR), startlog, SEEK_SET); // Now we go Int_t np = 0; char line[2048]; Int_t wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog; while (fgets(line, wanted, fLogFileR)) { Int_t r = strlen(line); if (!SendingLogToWindow()) { if (line[r-1] != '\n') line[r-1] = '\n'; if (r > 0) { char *p = line; while (r) { Int_t w = write(fileno(stdout), p, r); if (w < 0) { SysError("ShowLog", "error writing to stdout"); break; } r -= w; p += w; } } tolog -= strlen(line); np++; // Ask if more is wanted if (!(np%10)) { char *opt = Getline("More (y/n)? [y]"); if (opt[0] == 'n') break; } // We may be over if (tolog <= 0) break; // Update wanted bytes wanted = (tolog > sizeof(line)) ? sizeof(line) : tolog; } else { // Log to window if (line[r-1] == '\n') line[r-1] = 0; LogMessage(line, kFALSE); } } if (!SendingLogToWindow()) { // Avoid screwing up the prompt if (write(fileno(stdout), "\n", 1) != 1) SysError("ShowLog", "error writing to stdout"); } // Restore original pointer if (qry > -1) lseek(fileno(fLogFileR), nowlog, SEEK_SET); } //______________________________________________________________________________ void TProof::cd(Int_t id) { // Set session with 'id' the default one. If 'id' is not found in the list, // the current session is set as default if (GetManager()) { TProofDesc *d = GetManager()->GetProofDesc(id); if (d) { if (d->GetProof()) { gProof = d->GetProof(); return; } } // Id not found or undefined: set as default this session gProof = this; } return; } //______________________________________________________________________________ void TProof::Detach(Option_t *opt) { // Detach this instance to its proofserv. // If opt is 'S' or 's' the remote server is shutdown // Nothing to do if not in contact with proofserv if (!IsValid()) return; // Get worker and socket instances TSlave *sl = (TSlave *) fActiveSlaves->First(); TSocket *s = 0; if (!sl || !(sl->IsValid()) || !(s = sl->GetSocket())) { Error("Detach","corrupted worker instance: wrk:%p, sock:%p", sl, s); return; } Bool_t shutdown = (strchr(opt,'s') || strchr(opt,'S')) ? kTRUE : kFALSE; // If processing, try to stop processing first if (shutdown && !IsIdle()) { // Remove pending requests Remove("cleanupqueue"); // Do not wait for ever, but al least 20 seconds Long_t timeout = gEnv->GetValue("Proof.ShutdownTimeout", 60); timeout = (timeout > 20) ? timeout : 20; // Send stop signal StopProcess(kFALSE, (Long_t) (timeout / 2)); // Receive results Collect(kActive, timeout); } // Avoid spurious messages: deactivate new inputs ... DeActivateAsyncInput(); // ... and discard existing ones sl->FlushSocket(); // Close session (we always close the connection) Close(opt); // Close the progress dialog, if any if (fProgressDialogStarted) CloseProgressDialog(); // Update info in the table of our manager, if any if (GetManager() && GetManager()->QuerySessions("L")) { TIter nxd(GetManager()->QuerySessions("L")); TProofDesc *d = 0; while ((d = (TProofDesc *)nxd())) { if (d->GetProof() == this) { d->SetProof(0); GetManager()->QuerySessions("L")->Remove(d); break; } } } // Invalidate this instance fValid = kFALSE; return; } //______________________________________________________________________________ void TProof::SetAlias(const char *alias) { // Set an alias for this session. If reconnection is supported, the alias // will be communicated to the remote coordinator so that it can be recovered // when reconnecting // Set it locally TNamed::SetTitle(alias); if (TestBit(TProof::kIsMaster)) // Set the name at the same value TNamed::SetName(alias); // Nothing to do if not in contact with coordinator if (!IsValid()) return; if (!IsProofd() && TestBit(TProof::kIsClient)) { TSlave *sl = (TSlave *) fActiveSlaves->First(); if (sl) sl->SetAlias(alias); } return; } //______________________________________________________________________________ Int_t TProof::UploadDataSet(const char *dataSetName, TList *files, const char *desiredDest, Int_t opt, TList *skippedFiles) { // Upload a set of files and save the list of files by name dataSetName. // The 'files' argument is a list of TFileInfo objects describing the files // as first url. // The mask 'opt' is a combination of EUploadOpt: // kAppend (0x1) if set true files will be appended to // the dataset existing by given name // kOverwriteDataSet (0x2) if dataset with given name exited it // would be overwritten // kNoOverwriteDataSet (0x4) do not overwirte if the dataset exists // kOverwriteAllFiles (0x8) overwrite all files that may exist // kOverwriteNoFiles (0x10) overwrite none // kAskUser (0x0) ask user before overwriteng dataset/files // The default value is kAskUser. // The user will be asked to confirm overwriting dataset or files unless // specified opt provides the answer! // If kOverwriteNoFiles is set, then a pointer to TList must be passed as // skippedFiles argument. The function will add to this list TFileInfo // objects describing all files that existed on the cluster and were // not uploaded. // // Communication Summary // Client Master // |------------>DataSetName----------->| // |<-------kMESS_OK/kMESS_NOTOK<-------| (Name OK/file exist) // (*)|-------> call RegisterDataSet ------->| // (*) - optional if (fProtocol < 15) { Info("UploadDataSet", "functionality not available: the server has an" " incompatible version of TFileInfo"); return -1; } if (IsLite()) { Info("UploadDataSet", "Lite-session: functionality not needed - do nothing"); return -1; } // check if dataSetName is not excluded if (strchr(dataSetName, '/')) { if (strstr(dataSetName, "public") != dataSetName) { Error("UploadDataSet", "Name of public dataset should start with public/"); return kError; } } if ((opt & kOverwriteAllFiles && opt & kOverwriteNoFiles) || (opt & kNoOverwriteDataSet && opt & kAppend) || (opt & kOverwriteDataSet && opt & kAppend) || (opt & kNoOverwriteDataSet && opt & kOverwriteDataSet) || (opt & kAskUser && opt & (kOverwriteDataSet | kNoOverwriteDataSet | kAppend | kOverwriteAllFiles | kOverwriteNoFiles))) { Error("UploadDataSet", "you specified contradicting options."); return kError; } // Decode options Int_t overwriteAll = (opt & kOverwriteAllFiles) ? kTRUE : kFALSE; Int_t overwriteNone = (opt & kOverwriteNoFiles) ? kTRUE : kFALSE; Int_t goodName = (opt & (kOverwriteDataSet | kAppend)) ? 1 : -1; Int_t appendToDataSet = (opt & kAppend) ? kTRUE : kFALSE; Int_t overwriteNoDataSet = (opt & kNoOverwriteDataSet) ? kTRUE : kFALSE; //If skippedFiles is not provided we can not return list of skipped files. if (!skippedFiles && overwriteNone) { Error("UploadDataSet", "Provide pointer to TList object as skippedFiles argument when using kOverwriteNoFiles option."); return kError; } //If skippedFiles is provided but did not point to a TList the have to STOP if (skippedFiles) { if (skippedFiles->Class() != TList::Class()) { Error("UploadDataSet", "Provided skippedFiles argument does not point to a TList object."); return kError; } } TSocket *master; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("UploadDataSet", "No connection to the master!"); return kError; } Int_t fileCount = 0; // return value if (goodName == -1) { // -1 for undefined // First check whether this dataset already exists unless // kAppend or kOverWriteDataSet TMessage nameMess(kPROOF_DATASETS); nameMess << Int_t(kCheckDataSetName); nameMess << TString(dataSetName); Broadcast(nameMess); Collect(kActive, fCollectTimeout); //after each call to HandleDataSets if (fStatus == -1) { //We ask user to agree on overwriting the dataset name while (goodName == -1 && !overwriteNoDataSet) { Info("UploadDataSet", "dataset %s already exist. ", dataSetName); Info("UploadDataSet", "do you want to overwrite it[Yes/No/Append]?"); TString answer; answer.ReadToken(cin); if (!strncasecmp(answer.Data(), "y", 1)) { goodName = 1; } else if (!strncasecmp(answer.Data(), "n", 1)) { goodName = 0; } else if (!strncasecmp(answer.Data(), "a", 1)) { goodName = 1; appendToDataSet = kTRUE; } } } else { goodName = 1; } } // if (goodName == -1) if (goodName == 1) { //must be == 1 as -1 was used for a bad name! //Code for enforcing writing in user "home dir" only char *relativeDestDir = Form("%s/%s/", gSystem->GetUserInfo()->fUser.Data(), desiredDest?desiredDest:""); //Consider adding dataSetName to the path relativeDestDir = CollapseSlashesInPath(relativeDestDir); TString dest = Form("%s/%s", GetDataPoolUrl(), relativeDestDir); delete[] relativeDestDir; // Now we will actually copy files and create the TList object TFileCollection *fileList = new TFileCollection(); TIter next(files); while (TFileInfo *fileInfo = ((TFileInfo*)next())) { TUrl *fileUrl = fileInfo->GetFirstUrl(); if (gSystem->AccessPathName(fileUrl->GetUrl()) == kFALSE) { //matching dir entry //getting the file name from the path represented by fileUrl const char *ent = gSystem->BaseName(fileUrl->GetFile()); Int_t goodFileName = 1; if (!overwriteAll && gSystem->AccessPathName(Form("%s/%s", dest.Data(), ent), kFileExists) == kFALSE) { //Destination file exists goodFileName = -1; while (goodFileName == -1 && !overwriteAll && !overwriteNone) { Info("UploadDataSet", "file %s already exists. ", Form("%s/%s", dest.Data(), ent)); Info("UploadDataSet", "do you want to overwrite it [Yes/No/all/none]?"); TString answer; answer.ReadToken(cin); if (!strncasecmp(answer.Data(), "y", 1)) goodFileName = 1; else if (!strncasecmp(answer.Data(), "all", 3)) overwriteAll = kTRUE; else if (!strncasecmp(answer.Data(), "none", 4)) overwriteNone = kTRUE; else if (!strncasecmp(answer.Data(), "n", 1)) goodFileName = 0; } } //if file exists // Copy the file to the redirector indicated if (goodFileName == 1 || overwriteAll) { //must be == 1 as -1 was meant for bad name! Info("UploadDataSet", "Uploading %s to %s/%s", fileUrl->GetUrl(), dest.Data(), ent); if (TFile::Cp(fileUrl->GetUrl(), Form("%s/%s", dest.Data(), ent))) { fileList->GetList()->Add(new TFileInfo(Form("%s/%s", dest.Data(), ent))); } else Error("UploadDataSet", "file %s was not copied", fileUrl->GetUrl()); } else { // don't overwrite, but file exist and must be included fileList->GetList()->Add(new TFileInfo(Form("%s/%s", dest.Data(), ent))); if (skippedFiles) { // user specified the TList *skippedFiles argument so we create // the list of skipped files skippedFiles->Add(new TFileInfo(fileUrl->GetUrl())); } } } //if matching dir entry } //while if ((fileCount = fileList->GetList()->GetSize()) == 0) { Info("UploadDataSet", "no files were copied. The dataset will not be saved"); } else { TString o = (appendToDataSet) ? "" : "O"; if (!RegisterDataSet(dataSetName, fileList, o)) { Error("UploadDataSet", "Error while saving dataset: %s", dataSetName); fileCount = kError; } } delete fileList; } else if (overwriteNoDataSet) { Info("UploadDataSet", "dataset %s already exists", dataSetName); return kDataSetExists; } //if(goodName == 1) return fileCount; } //______________________________________________________________________________ Int_t TProof::UploadDataSet(const char *dataSetName, const char *files, const char *desiredDest, Int_t opt, TList *skippedFiles) { // Upload a set of files and save the list of files by name dataSetName. // The mask 'opt' is a combination of EUploadOpt: // kAppend (0x1) if set true files will be appended to // the dataset existing by given name // kOverwriteDataSet (0x2) if dataset with given name exited it // would be overwritten // kNoOverwriteDataSet (0x4) do not overwirte if the dataset exists // kOverwriteAllFiles (0x8) overwrite all files that may exist // kOverwriteNoFiles (0x10) overwrite none // kAskUser (0x0) ask user before overwriteng dataset/files // The default value is kAskUser. // The user will be asked to confirm overwriting dataset or files unless // specified opt provides the answer! // If kOverwriteNoFiles is set, then a pointer to TList must be passed as // skippedFiles argument. The function will add to this list TFileInfo // objects describing all files that existed on the cluster and were // not uploaded. // if (fProtocol < 15) { Info("UploadDataSet", "functionality not available: the server has an" " incompatible version of TFileInfo"); return -1; } TList fileList; fileList.SetOwner(); void *dataSetDir = gSystem->OpenDirectory(gSystem->DirName(files)); const char* ent; TString filesExp(gSystem->BaseName(files)); filesExp.ReplaceAll("*",".*"); TRegexp rg(filesExp); while ((ent = gSystem->GetDirEntry(dataSetDir))) { TString entryString(ent); if (entryString.Index(rg) != kNPOS) { // Matching dir entry: add to the list TString u(Form("file://%s/%s", gSystem->DirName(files), ent)); if (gSystem->AccessPathName(u, kReadPermission) == kFALSE) fileList.Add(new TFileInfo(u)); } //if matching dir entry } //while Int_t fileCount; if ((fileCount = fileList.GetSize()) == 0) Printf("No files match your selection. The dataset will not be saved"); else fileCount = UploadDataSet(dataSetName, &fileList, desiredDest, opt, skippedFiles); return fileCount; } //______________________________________________________________________________ Int_t TProof::UploadDataSetFromFile(const char *dataset, const char *file, const char *dest, Int_t opt, TList *skippedFiles) { // Upload files listed in "file" to PROOF cluster. // Where file = name of file containing list of files and // dataset = dataset name and opt is a combination of EUploadOpt bits. // Each file description (line) can include wildcards. // Check TFileInfo compatibility if (fProtocol < 15) { Info("UploadDataSetFromFile", "functionality not available: the server has an" " incompatible version of TFileInfo"); return -1; } Int_t fileCount = -1; // Create the list to feed UploadDataSet(char *dataset, TList *l, ...) TList fileList; fileList.SetOwner(); ifstream f; f.open(gSystem->ExpandPathName(file), ifstream::out); if (f.is_open()) { while (f.good()) { TString line; line.ReadToDelim(f); line.Strip(TString::kTrailing, '\n'); if (gSystem->AccessPathName(line, kReadPermission) == kFALSE) fileList.Add(new TFileInfo(line)); } f.close(); if ((fileCount = fileList.GetSize()) == 0) Info("UploadDataSetFromFile", "no files match your selection. The dataset will not be saved"); else fileCount = UploadDataSet(dataset, &fileList, dest, opt, skippedFiles); } else { Error("UploadDataSetFromFile", "unable to open the specified file"); } // Done return fileCount; } //______________________________________________________________________________ Bool_t TProof::RegisterDataSet(const char *dataSetName, TFileCollection *dataSet, const char* optStr) { // Register the 'dataSet' on the cluster under the current // user, group and the given 'dataSetName'. // If a dataset with the same name already exists the action fails unless 'opts' // contains 'O', in which case the old dataset is overwritten, or contains 'U', // in which case 'newDataSet' is added to the existing dataset (duplications are // ignored, if any). // If 'opts' contains 'V' the dataset files are also verified (if the dataset manager // is configured to allow so). By default the dataset is not verified. // If 'opts' contains 'T' the in the dataset object (status bits, meta,...) // is trusted, i.e. not reset (if the dataset manager is configured to allow so). // Returns kTRUE on success. // Check TFileInfo compatibility if (fProtocol < 17) { Info("RegisterDataSet", "functionality not available: the server does not have dataset support"); return kFALSE; } if (!dataSetName || strlen(dataSetName) <= 0) { Info("RegisterDataSet", "specifying a dataset name is mandatory"); return kFALSE; } TSocket *master; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("RegisterDataSet", "No connection to the master!"); return kFALSE; } TMessage mess(kPROOF_DATASETS); mess << Int_t(kRegisterDataSet); mess << TString(dataSetName); mess << TString(optStr); mess.WriteObject(dataSet); Broadcast(mess); Bool_t result = kTRUE; Collect(); if (fStatus != 0) { Error("RegisterDataSet", "dataset was not saved"); result = kFALSE; } return result; } //______________________________________________________________________________ Int_t TProof::SetDataSetTreeName(const char *dataset, const char *treename) { // Set/Change the name of the default tree. The tree name may contain // subdir specification in the form "subdir/name". // Returns 0 on success, -1 otherwise. // Check TFileInfo compatibility if (fProtocol < 23) { Info("SetDataSetTreeName", "functionality not supported by the server"); return -1; } if (!dataset || strlen(dataset) <= 0) { Info("SetDataSetTreeName", "specifying a dataset name is mandatory"); return -1; } if (!treename || strlen(treename) <= 0) { Info("SetDataSetTreeName", "specifying a tree name is mandatory"); return -1; } TUri uri(dataset); TString fragment(treename); if (!fragment.BeginsWith("/")) fragment.Insert(0, "/"); uri.SetFragment(fragment); TMessage mess(kPROOF_DATASETS); mess << Int_t(kSetDefaultTreeName); mess << uri.GetUri(); Broadcast(mess); Collect(); if (fStatus != 0) { Error("SetDataSetTreeName", "some error occured: default tree name not changed"); return -1; } return 0; } //______________________________________________________________________________ TMap *TProof::GetDataSets(const char *uri, const char* optStr) { // Lists all datasets that match given uri. if (fProtocol < 15) { Info("GetDataSets", "functionality not available: the server does not have dataset support"); return 0; } TSocket *master = 0; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("GetDataSets", "no connection to the master!"); return 0; } TMessage mess(kPROOF_DATASETS); mess << Int_t(kGetDataSets); mess << TString(uri?uri:""); mess << TString(optStr?optStr:""); Broadcast(mess); Collect(kActive, fCollectTimeout); TMap *dataSetMap = 0; if (fStatus != 0) { Error("GetDataSets", "error receiving datasets information"); } else { // Look in the list TMessage *retMess = (TMessage *) fRecvMessages->First(); if (retMess && retMess->What() == kMESS_OK) { if (!(dataSetMap = (TMap *)(retMess->ReadObject(TMap::Class())))) Error("GetDataSets", "error receiving datasets"); } else Error("GetDataSets", "message not found or wrong type (%p)", retMess); } return dataSetMap; } //______________________________________________________________________________ void TProof::ShowDataSets(const char *uri, const char* optStr) { // Shows datasets in locations that match the uri. // By default shows the user's datasets and global ones if (fProtocol < 15) { Info("ShowDataSets", "functionality not available: the server does not have dataset support"); return; } TSocket *master = 0; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("ShowDataSets", "no connection to the master!"); return; } TMessage mess(kPROOF_DATASETS); mess << Int_t(kShowDataSets); mess << TString(uri ? uri : ""); mess << TString(optStr ? optStr : ""); Broadcast(mess); Collect(kActive, fCollectTimeout); if (fStatus != 0) Error("ShowDataSets", "error receiving datasets information"); } //______________________________________________________________________________ Bool_t TProof::ExistsDataSet(const char *dataset) { // Returns kTRUE if 'dataset' exists, kFALSE otherwise if (fProtocol < 15) { Info("ExistsDataSet", "functionality not available: the server has an" " incompatible version of TFileInfo"); return kFALSE; } if (!dataset || strlen(dataset) <= 0) { Error("ExistsDataSet", "dataset name missing"); return kFALSE; } TMessage msg(kPROOF_DATASETS); msg << Int_t(kCheckDataSetName) << TString(dataset); Broadcast(msg); Collect(kActive, fCollectTimeout); if (fStatus == -1) { // The dataset exists return kTRUE; } // The dataset does not exists return kFALSE; } //______________________________________________________________________________ void TProof::ClearDataSetCache(const char *dataset) { // Clear the content of the dataset cache, if any (matching 'dataset', if defined). if (fProtocol < 28) { Info("ClearDataSetCache", "functionality not available on server"); return; } TMessage msg(kPROOF_DATASETS); msg << Int_t(kCache) << TString(dataset) << TString("clear"); Broadcast(msg); Collect(kActive, fCollectTimeout); // Done return; } //______________________________________________________________________________ void TProof::ShowDataSetCache(const char *dataset) { // Display the content of the dataset cache, if any (matching 'dataset', if defined). if (fProtocol < 28) { Info("ShowDataSetCache", "functionality not available on server"); return; } TMessage msg(kPROOF_DATASETS); msg << Int_t(kCache) << TString(dataset) << TString("show"); Broadcast(msg); Collect(kActive, fCollectTimeout); // Done return; } //______________________________________________________________________________ TFileCollection *TProof::GetDataSet(const char *uri, const char *optStr) { // Get a list of TFileInfo objects describing the files of the specified // dataset. // To get the short version (containing only the global meta information) // specify optStr = "S:" or optStr = "short:". // To get the sub-dataset of files located on a given server(s) specify // the list of servers (comma-separated) in the 'optStr' field. if (fProtocol < 15) { Info("GetDataSet", "functionality not available: the server has an" " incompatible version of TFileInfo"); return 0; } if (!uri || strlen(uri) <= 0) { Info("GetDataSet", "specifying a dataset name is mandatory"); return 0; } TSocket *master = 0; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("GetDataSet", "no connection to the master!"); return 0; } TMessage nameMess(kPROOF_DATASETS); nameMess << Int_t(kGetDataSet); nameMess << TString(uri); nameMess << TString(optStr ? optStr: ""); if (Broadcast(nameMess) < 0) Error("GetDataSet", "sending request failed"); Collect(kActive, fCollectTimeout); TFileCollection *fileList = 0; if (fStatus != 0) { Error("GetDataSet", "error receiving datasets information"); } else { // Look in the list TMessage *retMess = (TMessage *) fRecvMessages->First(); if (retMess && retMess->What() == kMESS_OK) { if (!(fileList = (TFileCollection*)(retMess->ReadObject(TFileCollection::Class())))) Error("GetDataSet", "error reading list of files"); } else Error("GetDataSet", "message not found or wrong type (%p)", retMess); } return fileList; } //______________________________________________________________________________ void TProof::ShowDataSet(const char *uri, const char* opt) { // display meta-info for given dataset usi TFileCollection *fileList = 0; if ((fileList = GetDataSet(uri))) { fileList->Print(opt); delete fileList; } else Warning("ShowDataSet","no such dataset: %s", uri); } //______________________________________________________________________________ Int_t TProof::RemoveDataSet(const char *uri, const char* optStr) { // Remove the specified dataset from the PROOF cluster. // Files are not deleted. TSocket *master; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("RemoveDataSet", "no connection to the master!"); return kError; } TMessage nameMess(kPROOF_DATASETS); nameMess << Int_t(kRemoveDataSet); nameMess << TString(uri?uri:""); nameMess << TString(optStr?optStr:""); if (Broadcast(nameMess) < 0) Error("RemoveDataSet", "sending request failed"); Collect(kActive, fCollectTimeout); if (fStatus != 0) return -1; else return 0; } //______________________________________________________________________________ TList* TProof::FindDataSets(const char* /*searchString*/, const char* /*optStr*/) { // Find datasets, returns in a TList all found datasets. Error ("FindDataSets", "not yet implemented"); return (TList *) 0; } //______________________________________________________________________________ Int_t TProof::VerifyDataSet(const char *uri, const char* optStr) { // Verify if all files in the specified dataset are available. // Print a list and return the number of missing files. if (fProtocol < 15) { Info("VerifyDataSet", "functionality not available: the server has an" " incompatible version of TFileInfo"); return kError; } Int_t nMissingFiles = 0; TSocket *master; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("VerifyDataSet", "no connection to the master!"); return kError; } TMessage nameMess(kPROOF_DATASETS); nameMess << Int_t(kVerifyDataSet); nameMess << TString(uri ? uri : ""); nameMess << TString(optStr ? optStr : ""); Broadcast(nameMess); Collect(kActive, fCollectTimeout); if (fStatus < 0) { Info("VerifyDataSet", "no such dataset %s", uri); return -1; } else nMissingFiles = fStatus; return nMissingFiles; } //______________________________________________________________________________ TMap *TProof::GetDataSetQuota(const char* optStr) { // returns a map of the quotas of all groups if (IsLite()) { Info("UploadDataSet", "Lite-session: functionality not implemented"); return (TMap *)0; } TSocket *master = 0; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("GetDataSetQuota", "no connection to the master!"); return 0; } TMessage mess(kPROOF_DATASETS); mess << Int_t(kGetQuota); mess << TString(optStr?optStr:""); Broadcast(mess); Collect(kActive, fCollectTimeout); TMap *groupQuotaMap = 0; if (fStatus < 0) { Info("GetDataSetQuota", "could not receive quota"); } else { // Look in the list TMessage *retMess = (TMessage *) fRecvMessages->First(); if (retMess && retMess->What() == kMESS_OK) { if (!(groupQuotaMap = (TMap*)(retMess->ReadObject(TMap::Class())))) Error("GetDataSetQuota", "error getting quotas"); } else Error("GetDataSetQuota", "message not found or wrong type (%p)", retMess); } return groupQuotaMap; } //_____________________________________________________________________________ void TProof::ShowDataSetQuota(Option_t* opt) { // shows the quota and usage of all groups // if opt contains "U" shows also distribution of usage on user-level if (fProtocol < 15) { Info("ShowDataSetQuota", "functionality not available: the server does not have dataset support"); return; } if (IsLite()) { Info("UploadDataSet", "Lite-session: functionality not implemented"); return; } TSocket *master = 0; if (fActiveSlaves->GetSize()) master = ((TSlave*)(fActiveSlaves->First()))->GetSocket(); else { Error("ShowDataSetQuota", "no connection to the master!"); return; } TMessage mess(kPROOF_DATASETS); mess << Int_t(kShowQuota); mess << TString(opt?opt:""); Broadcast(mess); Collect(); if (fStatus != 0) Error("ShowDataSetQuota", "error receiving quota information"); } //_____________________________________________________________________________ void TProof::InterruptCurrentMonitor() { // If in active in a monitor set ready state if (fCurrentMonitor) fCurrentMonitor->Interrupt(); } //_____________________________________________________________________________ void TProof::ActivateWorker(const char *ord) { // Make sure that the worker identified by the ordinal number 'ord' is // in the active list. The request will be forwarded to the master // in direct contact with the worker. If needed, this master will move // the worker from the inactive to the active list and rebuild the list // of unique workers. // Use ord = "*" to activate all inactive workers. ModifyWorkerLists(ord, kTRUE); } //_____________________________________________________________________________ void TProof::DeactivateWorker(const char *ord) { // Remove the worker identified by the ordinal number 'ord' from the // the active list. The request will be forwarded to the master // in direct contact with the worker. If needed, this master will move // the worker from the active to the inactive list and rebuild the list // of unique workers. // Use ord = "*" to deactivate all active workers. ModifyWorkerLists(ord, kFALSE); } //_____________________________________________________________________________ void TProof::ModifyWorkerLists(const char *ord, Bool_t add) { // Modify the worker active/inactive list by making the worker identified by // the ordinal number 'ord' active (add == TRUE) or inactive (add == FALSE). // If needed, the request will be forwarded to the master in direct contact // with the worker. The end-master will move the worker from one list to the // other active and rebuild the list of unique active workers. // Use ord = "*" to deactivate all active workers. // Make sure the input make sense if (!ord || strlen(ord) <= 0) { Info("ModifyWorkerLists", "An ordinal number - e.g. \"0.4\" or \"*\" for all - is required as input"); return; } Bool_t fw = kTRUE; // Whether to forward one step down Bool_t rs = kFALSE; // Whether to rescan for unique workers // Appropriate list pointing TList *in = (add) ? fInactiveSlaves : fActiveSlaves; TList *out = (add) ? fActiveSlaves : fInactiveSlaves; if (TestBit(TProof::kIsMaster)) { fw = IsEndMaster() ? kFALSE : kTRUE; // Look for the worker in the inactive list if (in->GetSize() > 0) { TIter nxw(in); TSlave *wrk = 0; while ((wrk = (TSlave *) nxw())) { if (ord[0] == '*' || !strncmp(wrk->GetOrdinal(), ord, strlen(ord))) { // Add it to the inactive list if (!out->FindObject(wrk)) { out->Add(wrk); if (add) fActiveMonitor->Add(wrk->GetSocket()); } // Remove it from the active list in->Remove(wrk); if (!add) { fActiveMonitor->Remove(wrk->GetSocket()); wrk->SetStatus(TSlave::kInactive); } else wrk->SetStatus(TSlave::kActive); // Nothing to forward (ord is unique) fw = kFALSE; // Rescan for unique workers (active list modified) rs = kTRUE; // We are done, if not option 'all' if (ord[0] != '*') break; } } } } // Rescan for unique workers if (rs) FindUniqueSlaves(); // Forward the request one step down, if needed Int_t action = (add) ? (Int_t) kActivateWorker : (Int_t) kDeactivateWorker; if (fw) { TMessage mess(kPROOF_WORKERLISTS); mess << action << TString(ord); Broadcast(mess); Collect(kActive, fCollectTimeout); } } //_____________________________________________________________________________ TProof *TProof::Open(const char *cluster, const char *conffile, const char *confdir, Int_t loglevel) { // Start a PROOF session on a specific cluster. If cluster is 0 (the // default) then the PROOF Session Viewer GUI pops up and 0 is returned. // If cluster is "" (empty string) then we connect to a PROOF session // on the localhost ("proof://localhost"). Via conffile a specific // PROOF config file in the confir directory can be specified. // Use loglevel to set the default loging level for debugging. // The appropriate instance of TProofMgr is created, if not // yet existing. The instantiated TProof object is returned. // Use TProof::cd() to switch between PROOF sessions. // For more info on PROOF see the TProof ctor. const char *pn = "TProof::Open"; // Make sure libProof and dependents are loaded and TProof can be created, // dependents are loaded via the information in the [system].rootmap file if (!cluster) { TPluginManager *pm = gROOT->GetPluginManager(); if (!pm) { ::Error(pn, "plugin manager not found"); return 0; } if (gROOT->IsBatch()) { ::Error(pn, "we are in batch mode, cannot show PROOF Session Viewer"); return 0; } // start PROOF Session Viewer TPluginHandler *sv = pm->FindHandler("TSessionViewer", ""); if (!sv) { ::Error(pn, "no plugin found for TSessionViewer"); return 0; } if (sv->LoadPlugin() == -1) { ::Error(pn, "plugin for TSessionViewer could not be loaded"); return 0; } sv->ExecPlugin(0); return 0; } else { TString clst(cluster); if (clst.BeginsWith("workers=") || clst.BeginsWith("tunnel=")) clst.Insert(0, "/?"); // Parse input URL TUrl u(clst); // Parse any tunning info ("<cluster>/?tunnel=[<tunnel_host>:]tunnel_port) TString opts(u.GetOptions()); if (!opts.IsNull()) { Int_t it = opts.Index("tunnel="); if (it != kNPOS) { TString sport = opts(it + strlen("tunnel="), opts.Length()); TString host("127.0.0.1"); Int_t port = -1; Int_t ic = sport.Index(":"); if (ic != kNPOS) { // Isolate the host host = sport(0, ic); sport.Remove(0, ic + 1); } if (!sport.IsDigit()) { // Remove the non digit part TRegexp re("[^0-9]"); Int_t ind = sport.Index(re); if (ind != kNPOS) sport.Remove(ind); } // Set the port if (sport.IsDigit()) port = sport.Atoi(); if (port > 0) { // Set the relevant variables ::Info("TProof::Open","using tunnel at %s:%d", host.Data(), port); gEnv->SetValue("XNet.SOCKS4Host", host); gEnv->SetValue("XNet.SOCKS4Port", port); } else { // Warn parsing problems ::Warning("TProof::Open", "problems parsing tunnelling info from options: %s", opts.Data()); } } } // Find out if we are required to attach to a specific session Int_t locid = -1; Bool_t create = kFALSE; if (opts.Length() > 0) { if (opts.BeginsWith("N",TString::kIgnoreCase)) { create = kTRUE; opts.Remove(0,1); u.SetOptions(opts); } else if (opts.IsDigit()) { locid = opts.Atoi(); } } // Attach-to or create the appropriate manager TProofMgr *mgr = TProofMgr::Create(u.GetUrl()); TProof *proof = 0; if (mgr && mgr->IsValid()) { // If XProofd we always attempt an attach first (unless // explicitely not requested). Bool_t attach = (create || mgr->IsProofd() || mgr->IsLite()) ? kFALSE : kTRUE; if (attach) { TProofDesc *d = 0; if (locid < 0) // Get the list of sessions d = (TProofDesc *) mgr->QuerySessions("")->First(); else d = (TProofDesc *) mgr->GetProofDesc(locid); if (d) { proof = (TProof*) mgr->AttachSession(d); if (!proof || !proof->IsValid()) { if (locid) ::Error(pn, "new session could not be attached"); SafeDelete(proof); } } } // start the PROOF session if (!proof) { proof = (TProof*) mgr->CreateSession(conffile, confdir, loglevel); if (!proof || !proof->IsValid()) { ::Error(pn, "new session could not be created"); SafeDelete(proof); } } } return proof; } } //_____________________________________________________________________________ TProofMgr *TProof::Mgr(const char *url) { // Get instance of the effective manager for 'url' // Return 0 on failure. if (!url) return (TProofMgr *)0; // Attach or create the relevant instance return TProofMgr::Create(url); } //_____________________________________________________________________________ void TProof::Reset(const char *url, Bool_t hard) { // Wrapper around TProofMgr::Reset(...). if (url) { TProofMgr *mgr = TProof::Mgr(url); if (mgr && mgr->IsValid()) mgr->Reset(hard); else ::Error("TProof::Reset", "unable to initialize a valid manager instance"); } } //_____________________________________________________________________________ const TList *TProof::GetEnvVars() { // Get environemnt variables. return fgProofEnvList; } //_____________________________________________________________________________ void TProof::AddEnvVar(const char *name, const char *value) { // Add an variable to the list of environment variables passed to proofserv // on the master and slaves if (gDebug > 0) ::Info("TProof::AddEnvVar","%s=%s", name, value); if (fgProofEnvList == 0) { // initialize the list if needed fgProofEnvList = new TList; fgProofEnvList->SetOwner(); } else { // replace old entries with the same name TObject *o = fgProofEnvList->FindObject(name); if (o != 0) { fgProofEnvList->Remove(o); } } fgProofEnvList->Add(new TNamed(name, value)); } //_____________________________________________________________________________ void TProof::DelEnvVar(const char *name) { // Remove an variable from the list of environment variables passed to proofserv // on the master and slaves if (fgProofEnvList == 0) return; TObject *o = fgProofEnvList->FindObject(name); if (o != 0) { fgProofEnvList->Remove(o); } } //_____________________________________________________________________________ void TProof::ResetEnvVars() { // Clear the list of environment variables passed to proofserv // on the master and slaves if (fgProofEnvList == 0) return; SafeDelete(fgProofEnvList); } //______________________________________________________________________________ void TProof::SaveWorkerInfo() { // Save informations about the worker set in the file .workers in the working // dir. Called each time there is a change in the worker setup, e.g. by // TProof::MarkBad(). // We must be masters if (TestBit(TProof::kIsClient)) return; // We must have a server defined if (!gProofServ) { Error("SaveWorkerInfo","gProofServ undefined"); return; } // The relevant lists must be defined if (!fSlaves && !fBadSlaves) { Warning("SaveWorkerInfo","all relevant worker lists is undefined"); return; } // Create or truncate the file first TString fnwrk = Form("%s/.workers", gSystem->DirName(gProofServ->GetSessionDir())); FILE *fwrk = fopen(fnwrk.Data(),"w"); if (!fwrk) { Error("SaveWorkerInfo", "cannot open %s for writing (errno: %d)", fnwrk.Data(), errno); return; } // Do we need to register an additional line for another log? TString addlogext; if (gSystem->Getenv("PROOF_ADDITIONALLOG")) { addlogext = gSystem->Getenv("PROOF_ADDITIONALLOG"); if (gDebug > 0) Info("SaveWorkerInfo", "request for additional line with ext: '%s'", addlogext.Data()); } // Loop over the list of workers (active is any worker not flagged as bad) TIter nxa(fSlaves); TSlave *wrk = 0; while ((wrk = (TSlave *) nxa())) { Int_t status = (fBadSlaves && fBadSlaves->FindObject(wrk)) ? 0 : 1; // Write out record for this worker fprintf(fwrk,"%s@%s:%d %d %s %s.log\n", wrk->GetUser(), wrk->GetName(), wrk->GetPort(), status, wrk->GetOrdinal(), wrk->GetWorkDir()); // Additional line, if required if (addlogext.Length() > 0) { fprintf(fwrk,"%s@%s:%d %d %s %s.%s\n", wrk->GetUser(), wrk->GetName(), wrk->GetPort(), status, wrk->GetOrdinal(), wrk->GetWorkDir(), addlogext.Data()); } } // Close file fclose(fwrk); // We are done return; } //______________________________________________________________________________ Int_t TProof::GetParameter(TCollection *c, const char *par, TString &value) { // Get the value from the specified parameter from the specified collection. // Returns -1 in case of error (i.e. list is 0, parameter does not exist // or value type does not match), 0 otherwise. TObject *obj = c->FindObject(par); if (obj) { TNamed *p = dynamic_cast<TNamed*>(obj); if (p) { value = p->GetTitle(); return 0; } } return -1; } //______________________________________________________________________________ Int_t TProof::GetParameter(TCollection *c, const char *par, Int_t &value) { // Get the value from the specified parameter from the specified collection. // Returns -1 in case of error (i.e. list is 0, parameter does not exist // or value type does not match), 0 otherwise. TObject *obj = c->FindObject(par); if (obj) { TParameter<Int_t> *p = dynamic_cast<TParameter<Int_t>*>(obj); if (p) { value = p->GetVal(); return 0; } } return -1; } //______________________________________________________________________________ Int_t TProof::GetParameter(TCollection *c, const char *par, Long_t &value) { // Get the value from the specified parameter from the specified collection. // Returns -1 in case of error (i.e. list is 0, parameter does not exist // or value type does not match), 0 otherwise. TObject *obj = c->FindObject(par); if (obj) { TParameter<Long_t> *p = dynamic_cast<TParameter<Long_t>*>(obj); if (p) { value = p->GetVal(); return 0; } } return -1; } //______________________________________________________________________________ Int_t TProof::GetParameter(TCollection *c, const char *par, Long64_t &value) { // Get the value from the specified parameter from the specified collection. // Returns -1 in case of error (i.e. list is 0, parameter does not exist // or value type does not match), 0 otherwise. TObject *obj = c->FindObject(par); if (obj) { TParameter<Long64_t> *p = dynamic_cast<TParameter<Long64_t>*>(obj); if (p) { value = p->GetVal(); return 0; } } return -1; } //______________________________________________________________________________ Int_t TProof::GetParameter(TCollection *c, const char *par, Double_t &value) { // Get the value from the specified parameter from the specified collection. // Returns -1 in case of error (i.e. list is 0, parameter does not exist // or value type does not match), 0 otherwise. TObject *obj = c->FindObject(par); if (obj) { TParameter<Double_t> *p = dynamic_cast<TParameter<Double_t>*>(obj); if (p) { value = p->GetVal(); return 0; } } return -1; } //______________________________________________________________________________ Int_t TProof::AssertDataSet(TDSet *dset, TList *input, TDataSetManager *mgr, TString &emsg) { // Make sure that dataset is in the form to be processed. This may mean // retrieving the relevant info from the dataset manager or from the // attached input list. // Returns 0 on success, -1 on error emsg = ""; // We must have something to process if (!dset || !input || !mgr) { emsg.Form("invalid inputs (%p, %p, %p)", dset, input, mgr); return -1; } TList *datasets = new TList; TFileCollection *dataset = 0; TString lookupopt; TString dsname(dset->GetName()); // The dataset maybe in the form of a TFileCollection in the input list if (dsname.BeginsWith("TFileCollection:")) { // Isolate the real name dsname.ReplaceAll("TFileCollection:", ""); // Get the object dataset = (TFileCollection *) input->FindObject(dsname); if (!dataset) { emsg.Form("TFileCollection %s not found in input list", dset->GetName()); return -1; } // Remove from everywhere input->RecursiveRemove(dataset); // Add it to the local list datasets->Add(new TPair(dataset, new TObjString(""))); // Make sure we lookup everything (unless the client or the administartor // required something else) if (TProof::GetParameter(input, "PROOF_LookupOpt", lookupopt) != 0) { lookupopt = gEnv->GetValue("Proof.LookupOpt", "all"); input->Add(new TNamed("PROOF_LookupOpt", lookupopt.Data())); } } // This is the name we parse for additional specifications, such directory // and object name; for multiple datasets we assume that the directory and // and object name are the same for all datasets TString dsnparse; // The received message included an empty dataset, with only the name // defined: assume that a dataset, stored on the PROOF master by that // name, should be processed. if (!dataset) { TString dsns(dsname.Data()), dsn1; Int_t from1 = 0; while (dsns.Tokenize(dsn1, from1, "[, ]")) { TString dsn2, enl; Int_t from2 = 0; TFileCollection *fc = 0; while (dsn1.Tokenize(dsn2, from2, "|")) { enl = ""; Int_t ienl = dsn2.Index("?enl="); if (ienl != kNPOS) { enl = dsn2(ienl + 5, dsn2.Length()); dsn2.Remove(ienl); } if ((fc = mgr->GetDataSet(dsn2.Data()))) { dsnparse = dsn2; if (!dataset) { // This is our dataset dataset = fc; } else { // Add it to the dataset dataset->Add(fc); SafeDelete(fc); } } } // The dataset name(s) in the first element if (dataset) { if (dataset->GetList()->First()) ((TFileInfo *)(dataset->GetList()->First()))->SetTitle(dsn1.Data()); // Add it to the local list if (enl.IsNull()) { datasets->Add(new TPair(dataset, new TObjString(""))); } else { datasets->Add(new TPair(dataset, new TObjString(enl.Data()))); } } // Reset the pointer dataset = 0; } if (!datasets || datasets->GetSize() <= 0) { emsg.Form("no dataset(s) found on the master corresponding to: %s", dsname.Data()); return -1; } else { // Make 'dataset' to point to the first one in the list if (!(dataset = (TFileCollection *) ((TPair *)(datasets->First()))->Key())) { emsg.Form("dataset pointer is null: corruption? - aborting"); return -1; } } // Apply the lookup option requested by the client or the administartor // (by default we trust the information in the dataset) if (TProof::GetParameter(input, "PROOF_LookupOpt", lookupopt) != 0) { lookupopt = gEnv->GetValue("Proof.LookupOpt", "stagedOnly"); input->Add(new TNamed("PROOF_LookupOpt", lookupopt.Data())); } } else { // We were given a named, single, TFileCollection dsnparse = dsname; } // Logic for the subdir/obj names: try first to see if the dataset name contains // some info; if not check the settings in the TDSet object itself; if still empty // check the default tree name / path in the TFileCollection object; if still empty // use the default as the flow will determine TString dsTree; // Get the [subdir/]tree, if any mgr->ParseUri(dsnparse.Data(), 0, 0, 0, &dsTree); if (dsTree.IsNull()) { // Use what we have in the original dataset; we need this to locate the // meta data information dsTree += dset->GetDirectory(); dsTree += dset->GetObjName(); } if (!dsTree.IsNull() && dsTree != "/") { TString tree(dsTree); Int_t idx = tree.Index("/"); if (idx != kNPOS) { TString dir = tree(0, idx+1); tree.Remove(0, idx); dset->SetDirectory(dir); } dset->SetObjName(tree); } else { // Use the default obj name from the TFileCollection dsTree = dataset->GetDefaultTreeName(); } // Pass dataset server mapping instructions, if any TList *srvmapsref = TDataSetManager::GetDataSetSrvMaps(); TList *srvmapslist = srvmapsref; TString srvmaps; if (TProof::GetParameter(input, "PROOF_DataSetSrvMaps", srvmaps) == 0) { srvmapslist = TDataSetManager::ParseDataSetSrvMaps(srvmaps); if (gProofServ) { TString msg; if (srvmapsref && !srvmapslist) { msg.Form("+++ Info: dataset server mapping(s) DISABLED by user"); } else if (srvmapsref && srvmapslist && srvmapslist != srvmapsref) { msg.Form("+++ Info: dataset server mapping(s) modified by user"); } else if (!srvmapsref && srvmapslist) { msg.Form("+++ Info: dataset server mapping(s) added by user"); } gProofServ->SendAsynMessage(msg.Data()); } } // Flag multi-datasets if (datasets->GetSize() > 1) dset->SetBit(TDSet::kMultiDSet); // Loop over the list of datasets TList *listOfMissingFiles = new TList; TEntryList *entrylist = 0; TPair *pair = 0; TIter nxds(datasets); while ((pair = (TPair *) nxds())) { // File Collection dataset = (TFileCollection *) pair->Key(); // Entry list, if any TEntryList *enl = 0; TObjString *os = (TObjString *) pair->Value(); if (strlen(os->GetName())) { if (!(enl = dynamic_cast<TEntryList *>(input->FindObject(os->GetName())))) { if (gProofServ) gProofServ->SendAsynMessage(TString::Format("+++ Warning:" " entry list %s not found", os->GetName())); } if (enl && (!(enl->GetLists()) || enl->GetLists()->GetSize() <= 0)) { if (gProofServ) gProofServ->SendAsynMessage(TString::Format("+++ Warning:" " no sub-lists in entry-list!")); } } TList *missingFiles = new TList; TSeqCollection* files = dataset->GetList(); if (gDebug > 0) files->Print(); Bool_t availableOnly = (lookupopt != "all") ? kTRUE : kFALSE; if (dset->TestBit(TDSet::kMultiDSet)) { TDSet *ds = new TDSet(dataset->GetName(), dset->GetObjName(), dset->GetDirectory()); ds->SetSrvMaps(srvmapslist); if (!ds->Add(files, dsTree, availableOnly, missingFiles)) { emsg.Form("error integrating dataset %s", dataset->GetName()); continue; } // Add the TDSet object to the multi-dataset dset->Add(ds); // Add entry list if any if (enl) ds->SetEntryList(enl); } else { dset->SetSrvMaps(srvmapslist); if (!dset->Add(files, dsTree, availableOnly, missingFiles)) { emsg.Form("error integrating dataset %s", dataset->GetName()); continue; } if (enl) { if (!entrylist) { entrylist = enl; } else { entrylist->Add(enl); } } } if (missingFiles) { // The missing files objects have to be removed from the dataset // before delete. TIter next(missingFiles); TObject *file; while ((file = next())) { dataset->GetList()->Remove(file); listOfMissingFiles->Add(file); } missingFiles->SetOwner(kFALSE); missingFiles->Clear(); } SafeDelete(missingFiles); } // Cleanup; we need to do this because pairs do no delete their content nxds.Reset(); while ((pair = (TPair *) nxds())) { if (pair->Key()) delete pair->Key(); if (pair->Value()) delete pair->Value(); } datasets->SetOwner(kTRUE); SafeDelete(datasets); // Cleanup the server mapping list, if created by the user if (srvmapslist && srvmapslist != srvmapsref) { srvmapslist->SetOwner(kTRUE); SafeDelete(srvmapslist); } // Set the global entrylist, if required if (entrylist) dset->SetEntryList(entrylist); // Make sure it will be sent back merged with other similar lists created // during processing; this list will be transferred by the player to the // output list, once the latter has been created (see TProofPlayerRemote::Process) if (listOfMissingFiles && listOfMissingFiles->GetSize() > 0) { listOfMissingFiles->SetName("MissingFiles"); input->Add(listOfMissingFiles); } // Done return 0; } //______________________________________________________________________________ Int_t TProof::SaveInputData(TQueryResult *qr, const char *cachedir, TString &emsg) { // Save input data file from 'cachedir' into the sandbox or create a the file // with input data objects TList *input = 0; // We must have got something to process if (!qr || !(input = qr->GetInputList()) || !cachedir || strlen(cachedir) <= 0) return 0; // There must be some input data or input data file TNamed *data = (TNamed *) input->FindObject("PROOF_InputDataFile"); TList *inputdata = (TList *) input->FindObject("PROOF_InputData"); if (!data && !inputdata) return 0; // Default dstination filename if (!data) input->Add((data = new TNamed("PROOF_InputDataFile", kPROOF_InputDataFile))); TString dstname(data->GetTitle()), srcname; Bool_t fromcache = kFALSE; if (dstname.BeginsWith("cache:")) { fromcache = kTRUE; dstname.ReplaceAll("cache:", ""); srcname.Form("%s/%s", cachedir, dstname.Data()); if (gSystem->AccessPathName(srcname)) { emsg.Form("input data file not found in cache (%s)", srcname.Data()); return -1; } } // If from cache, just move the cache file if (fromcache) { if (gSystem->CopyFile(srcname, dstname, kTRUE) != 0) { emsg.Form("problems copying %s to %s", srcname.Data(), dstname.Data()); return -1; } } else { // Create the file if (inputdata && inputdata->GetSize() > 0) { TFile *f = TFile::Open(dstname.Data(), "RECREATE"); if (f) { f->cd(); inputdata->Write(); f->Close(); delete f; } else { emsg.Form("could not create %s", dstname.Data()); return -1; } } else { emsg.Form("no input data!"); return -1; } } ::Info("TProof::SaveInputData", "input data saved to %s", dstname.Data()); // Save the file name and clean up the data list data->SetTitle(dstname); if (inputdata) { input->Remove(inputdata); inputdata->SetOwner(); delete inputdata; } // Done return 0; } //______________________________________________________________________________ Int_t TProof::SendInputData(TQueryResult *qr, TProof *p, TString &emsg) { // Send the input data file to the workers TList *input = 0; // We must have got something to process if (!qr || !(input = qr->GetInputList())) return 0; // There must be some input data or input data file TNamed *inputdata = (TNamed *) input->FindObject("PROOF_InputDataFile"); if (!inputdata) return 0; TString fname(inputdata->GetTitle()); if (gSystem->AccessPathName(fname)) { emsg.Form("input data file not found in sandbox (%s)", fname.Data()); return -1; } // PROOF session must available if (!p || !p->IsValid()) { emsg.Form("TProof object undefined or invalid: protocol error!"); return -1; } // Send to unique workers and submasters p->BroadcastFile(fname, TProof::kBinary, "cache"); // Done return 0; } //______________________________________________________________________________ Int_t TProof::GetInputData(TList *input, const char *cachedir, TString &emsg) { // Get the input data from the file defined in the input list // We must have got something to process if (!input || !cachedir || strlen(cachedir) <= 0) return 0; // There must be some input data or input data file TNamed *inputdata = (TNamed *) input->FindObject("PROOF_InputDataFile"); if (!inputdata) return 0; TString fname; fname.Form("%s/%s", cachedir, inputdata->GetTitle()); if (gSystem->AccessPathName(fname)) { emsg.Form("input data file not found in cache (%s)", fname.Data()); return -1; } // Read the input data into the input list TFile *f = TFile::Open(fname.Data()); if (f) { TList *keys = (TList *) f->GetListOfKeys(); if (!keys) { emsg.Form("could not get list of object keys from file"); return -1; } TIter nxk(keys); TKey *k = 0; while ((k = (TKey *)nxk())) { TObject *o = f->Get(k->GetName()); if (o) input->Add(o); } f->Close(); delete f; } else { emsg.Form("could not open %s", fname.Data()); return -1; } // Done return 0; } //______________________________________________________________________________ void TProof::LogViewer(const char *url, Int_t idx) { // Start the log viewer window usign the plugin manager if (!gROOT->IsBatch()) { // Get the handler, if not yet done if (!fgLogViewer) { if ((fgLogViewer = gROOT->GetPluginManager()->FindHandler("TProofProgressLog"))) { if (fgLogViewer->LoadPlugin() == -1) { fgLogViewer = 0; ::Error("TProof::LogViewer", "cannot load the relevant plug-in"); return; } } } if (fgLogViewer) { // Execute the plug-in TString u = (url && strlen(url) <= 0) ? "lite" : url; fgLogViewer->ExecPlugin(2, u.Data(), idx); } } else { if (url && strlen(url) > 0) { ::Info("TProof::LogViewer", "batch mode: use TProofLog *pl = TProof::Mgr(\"%s\")->GetSessionLogs(%d)", url, idx); } else if (url && strlen(url) <= 0) { ::Info("TProof::LogViewer", "batch mode: use TProofLog *pl = TProof::Mgr(\"lite\")->GetSessionLogs(%d)", idx); } else { ::Info("TProof::LogViewer", "batch mode: use TProofLog *pl = TProof::Mgr(\"<master>\")->GetSessionLogs(%d)", idx); } } // Done return; } //______________________________________________________________________________ void TProof::SetProgressDialog(Bool_t on) { // Enable/Disable the graphic progress dialog. // By default the dialog is enabled if (on) SetBit(kUseProgressDialog); else ResetBit(kUseProgressDialog); }
// Copyright (c) 2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/pivx/sendcustomfeedialog.h" #include "qt/pivx/forms/ui_sendcustomfeedialog.h" #include "qt/pivx/qtutils.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include <QListView> #include <QComboBox> SendCustomFeeDialog::SendCustomFeeDialog(PIVXGUI* parent, WalletModel* model) : QDialog(parent), ui(new Ui::SendCustomFeeDialog), walletModel(model) { if (!walletModel) throw std::runtime_error(strprintf("%s: No wallet model set", __func__)); ui->setupUi(this); // Stylesheet this->setStyleSheet(parent->styleSheet()); setCssProperty(ui->frame, "container-dialog"); // Text ui->labelTitle->setText(tr("Customize Fee")); ui->labelMessage->setText(tr("Customize the transaction fee, depending on the fee value your transaction might be included faster in the blockchain.")); setCssProperty(ui->labelTitle, "text-title-dialog"); setCssProperty(ui->labelMessage, "text-main-grey"); // Recommended setCssProperty(ui->labelFee, "text-main-grey-big"); setCssProperty(ui->comboBoxRecommended, "btn-combo-dialog"); ui->comboBoxRecommended->setView(new QListView()); ui->comboBoxRecommended->addItem(tr("Normal"), 5); ui->comboBoxRecommended->addItem(tr("Slow"), 20); ui->comboBoxRecommended->addItem(tr("Fast"), 1); // Custom setCssProperty(ui->labelCustomFee, "label-subtitle-dialog"); ui->lineEditCustomFee->setPlaceholderText("0.000001"); initCssEditLine(ui->lineEditCustomFee, true); GUIUtil::setupAmountWidget(ui->lineEditCustomFee, this); // Buttons setCssProperty(ui->btnEsc, "ic-close"); setCssProperty(ui->btnCancel, "btn-dialog-cancel"); ui->btnSave->setText(tr("SAVE")); setCssBtnPrimary(ui->btnSave); connect(ui->btnEsc, &QPushButton::clicked, this, &SendCustomFeeDialog::close); connect(ui->btnCancel, &QPushButton::clicked, this, &SendCustomFeeDialog::close); connect(ui->btnSave, &QPushButton::clicked, this, &SendCustomFeeDialog::accept); connect(ui->checkBoxCustom, &QCheckBox::clicked, this, &SendCustomFeeDialog::onCustomChecked); connect(ui->checkBoxRecommended, &QCheckBox::clicked, this, &SendCustomFeeDialog::onRecommendedChecked); connect(ui->comboBoxRecommended, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged), this, &SendCustomFeeDialog::updateFee); if (parent) connect(parent, &PIVXGUI::themeChanged, this, &SendCustomFeeDialog::onChangeTheme); ui->checkBoxRecommended->setChecked(true); } void SendCustomFeeDialog::showEvent(QShowEvent* event) { updateFee(); if (walletModel->hasWalletCustomFee()) { ui->checkBoxCustom->setChecked(true); onCustomChecked(); } else { ui->checkBoxRecommended->setChecked(true); onRecommendedChecked(); } } void SendCustomFeeDialog::onCustomChecked() { bool isChecked = ui->checkBoxCustom->checkState() == Qt::Checked; ui->lineEditCustomFee->setEnabled(isChecked); ui->comboBoxRecommended->setEnabled(!isChecked); ui->checkBoxRecommended->setChecked(!isChecked); if (isChecked) { CAmount nFee; walletModel->getWalletCustomFee(nFee); ui->lineEditCustomFee->setText(BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), nFee)); } else { ui->lineEditCustomFee->clear(); } } void SendCustomFeeDialog::onRecommendedChecked() { bool isChecked = ui->checkBoxRecommended->checkState() == Qt::Checked; ui->lineEditCustomFee->setEnabled(!isChecked); ui->comboBoxRecommended->setEnabled(isChecked); ui->checkBoxCustom->setChecked(!isChecked); if (isChecked) { ui->lineEditCustomFee->clear(); } } // Fast = 1. // Medium = 5 // Slow = 20 void SendCustomFeeDialog::updateFee() { if (!walletModel->getOptionsModel()) return; QVariant num = ui->comboBoxRecommended->currentData(); bool res = false; int nBlocksToConfirm = num.toInt(&res); if (res) { feeRate = mempool.estimateFee(nBlocksToConfirm); if (feeRate < CWallet::minTxFee) feeRate = CWallet::minTxFee; // not enough data => minfee ui->labelFee->setText(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB"); } } void SendCustomFeeDialog::accept() { const bool fUseCustomFee = ui->checkBoxCustom->checkState() == Qt::Checked; const CAmount customFee = getFeeRate().GetFeePerK(); // Check insane fee const CAmount insaneFee = ::minRelayTxFee.GetFeePerK() * 10000; if (customFee >= insaneFee) { inform(tr("Fee too high. Must be below: %1").arg( BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), insaneFee))); } else if (customFee < CWallet::minTxFee.GetFeePerK()) { inform(tr("Fee too low. Must be above: %1").arg( BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK() * 1000))); } else { walletModel->setWalletCustomFee(fUseCustomFee, customFee); QDialog::accept(); } } void SendCustomFeeDialog::clear() { ui->comboBoxRecommended->setCurrentIndex(0); } CFeeRate SendCustomFeeDialog::getFeeRate() { return ui->checkBoxRecommended->isChecked() ? feeRate : CFeeRate(GUIUtil::parseValue(ui->lineEditCustomFee->text(), walletModel->getOptionsModel()->getDisplayUnit())); } bool SendCustomFeeDialog::isCustomFeeChecked() { return ui->checkBoxCustom->checkState() == Qt::Checked; } void SendCustomFeeDialog::onChangeTheme(bool isLightTheme, QString& theme) { this->setStyleSheet(theme); updateStyle(this); } void SendCustomFeeDialog::inform(const QString& text) { if (!snackBar) snackBar = new SnackBar(nullptr, this); snackBar->setText(text); snackBar->resize(this->width(), snackBar->height()); openDialog(snackBar, this); } SendCustomFeeDialog::~SendCustomFeeDialog() { delete ui; } [Trivial] Fix wording: "must be above" to "must be at least" Since the fee can be set to a value equal to minTxFee // Copyright (c) 2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/pivx/sendcustomfeedialog.h" #include "qt/pivx/forms/ui_sendcustomfeedialog.h" #include "qt/pivx/qtutils.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include <QListView> #include <QComboBox> SendCustomFeeDialog::SendCustomFeeDialog(PIVXGUI* parent, WalletModel* model) : QDialog(parent), ui(new Ui::SendCustomFeeDialog), walletModel(model) { if (!walletModel) throw std::runtime_error(strprintf("%s: No wallet model set", __func__)); ui->setupUi(this); // Stylesheet this->setStyleSheet(parent->styleSheet()); setCssProperty(ui->frame, "container-dialog"); // Text ui->labelTitle->setText(tr("Customize Fee")); ui->labelMessage->setText(tr("Customize the transaction fee, depending on the fee value your transaction might be included faster in the blockchain.")); setCssProperty(ui->labelTitle, "text-title-dialog"); setCssProperty(ui->labelMessage, "text-main-grey"); // Recommended setCssProperty(ui->labelFee, "text-main-grey-big"); setCssProperty(ui->comboBoxRecommended, "btn-combo-dialog"); ui->comboBoxRecommended->setView(new QListView()); ui->comboBoxRecommended->addItem(tr("Normal"), 5); ui->comboBoxRecommended->addItem(tr("Slow"), 20); ui->comboBoxRecommended->addItem(tr("Fast"), 1); // Custom setCssProperty(ui->labelCustomFee, "label-subtitle-dialog"); ui->lineEditCustomFee->setPlaceholderText("0.000001"); initCssEditLine(ui->lineEditCustomFee, true); GUIUtil::setupAmountWidget(ui->lineEditCustomFee, this); // Buttons setCssProperty(ui->btnEsc, "ic-close"); setCssProperty(ui->btnCancel, "btn-dialog-cancel"); ui->btnSave->setText(tr("SAVE")); setCssBtnPrimary(ui->btnSave); connect(ui->btnEsc, &QPushButton::clicked, this, &SendCustomFeeDialog::close); connect(ui->btnCancel, &QPushButton::clicked, this, &SendCustomFeeDialog::close); connect(ui->btnSave, &QPushButton::clicked, this, &SendCustomFeeDialog::accept); connect(ui->checkBoxCustom, &QCheckBox::clicked, this, &SendCustomFeeDialog::onCustomChecked); connect(ui->checkBoxRecommended, &QCheckBox::clicked, this, &SendCustomFeeDialog::onRecommendedChecked); connect(ui->comboBoxRecommended, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged), this, &SendCustomFeeDialog::updateFee); if (parent) connect(parent, &PIVXGUI::themeChanged, this, &SendCustomFeeDialog::onChangeTheme); ui->checkBoxRecommended->setChecked(true); } void SendCustomFeeDialog::showEvent(QShowEvent* event) { updateFee(); if (walletModel->hasWalletCustomFee()) { ui->checkBoxCustom->setChecked(true); onCustomChecked(); } else { ui->checkBoxRecommended->setChecked(true); onRecommendedChecked(); } } void SendCustomFeeDialog::onCustomChecked() { bool isChecked = ui->checkBoxCustom->checkState() == Qt::Checked; ui->lineEditCustomFee->setEnabled(isChecked); ui->comboBoxRecommended->setEnabled(!isChecked); ui->checkBoxRecommended->setChecked(!isChecked); if (isChecked) { CAmount nFee; walletModel->getWalletCustomFee(nFee); ui->lineEditCustomFee->setText(BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), nFee)); } else { ui->lineEditCustomFee->clear(); } } void SendCustomFeeDialog::onRecommendedChecked() { bool isChecked = ui->checkBoxRecommended->checkState() == Qt::Checked; ui->lineEditCustomFee->setEnabled(!isChecked); ui->comboBoxRecommended->setEnabled(isChecked); ui->checkBoxCustom->setChecked(!isChecked); if (isChecked) { ui->lineEditCustomFee->clear(); } } // Fast = 1. // Medium = 5 // Slow = 20 void SendCustomFeeDialog::updateFee() { if (!walletModel->getOptionsModel()) return; QVariant num = ui->comboBoxRecommended->currentData(); bool res = false; int nBlocksToConfirm = num.toInt(&res); if (res) { feeRate = mempool.estimateFee(nBlocksToConfirm); if (feeRate < CWallet::minTxFee) feeRate = CWallet::minTxFee; // not enough data => minfee ui->labelFee->setText(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB"); } } void SendCustomFeeDialog::accept() { const bool fUseCustomFee = ui->checkBoxCustom->checkState() == Qt::Checked; const CAmount customFee = getFeeRate().GetFeePerK(); // Check insane fee const CAmount insaneFee = ::minRelayTxFee.GetFeePerK() * 10000; if (customFee >= insaneFee) { inform(tr("Fee too high. Must be below: %1").arg( BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), insaneFee))); } else if (customFee < CWallet::minTxFee.GetFeePerK()) { inform(tr("Fee too low. Must be at least: %1").arg( BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()))); } else { walletModel->setWalletCustomFee(fUseCustomFee, customFee); QDialog::accept(); } } void SendCustomFeeDialog::clear() { ui->comboBoxRecommended->setCurrentIndex(0); } CFeeRate SendCustomFeeDialog::getFeeRate() { return ui->checkBoxRecommended->isChecked() ? feeRate : CFeeRate(GUIUtil::parseValue(ui->lineEditCustomFee->text(), walletModel->getOptionsModel()->getDisplayUnit())); } bool SendCustomFeeDialog::isCustomFeeChecked() { return ui->checkBoxCustom->checkState() == Qt::Checked; } void SendCustomFeeDialog::onChangeTheme(bool isLightTheme, QString& theme) { this->setStyleSheet(theme); updateStyle(this); } void SendCustomFeeDialog::inform(const QString& text) { if (!snackBar) snackBar = new SnackBar(nullptr, this); snackBar->setText(text); snackBar->resize(this->width(), snackBar->height()); openDialog(snackBar, this); } SendCustomFeeDialog::~SendCustomFeeDialog() { delete ui; }
/*========================================================================= Program: Visualization Toolkit Module: vtkEnSightReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkEnSightReader.h" #include "vtkDataArrayCollection.h" #include "vtkIdListCollection.h" #include "vtkFloatArray.h" #include "vtkObjectFactory.h" #include "vtkRectilinearGrid.h" #include "vtkStructuredGrid.h" #include "vtkStructuredPoints.h" #include "vtkUnstructuredGrid.h" vtkCxxRevisionMacro(vtkEnSightReader, "1.39"); //---------------------------------------------------------------------------- vtkEnSightReader::vtkEnSightReader() { this->MeasuredFileName = NULL; this->MatchFileName = NULL; this->IS = NULL; this->VariableMode = -1; this->UnstructuredPartIds = vtkIdList::New(); this->CellIds = NULL; this->VariableFileNames = NULL; this->ComplexVariableFileNames = NULL; this->VariableDescriptions = NULL; this->ComplexVariableDescriptions = NULL; this->VariableTimeSetIds = vtkIdList::New(); this->ComplexVariableTimeSetIds = vtkIdList::New(); this->VariableFileSetIds = vtkIdList::New(); this->ComplexVariableFileSetIds = vtkIdList::New(); this->TimeSetFileNameNumbers = vtkIdListCollection::New(); this->TimeSetsWithFilenameNumbers = vtkIdList::New(); this->TimeSets = vtkDataArrayCollection::New(); this->FileSetFileNameNumbers = vtkIdListCollection::New(); this->FileSetsWithFilenameNumbers = vtkIdList::New(); this->FileSetNumberOfSteps = vtkIdListCollection::New(); this->TimeSetIds = vtkIdList::New(); this->FileSets = vtkIdList::New(); this->GeometryTimeSet = 1; this->GeometryFileSet = 1; this->MeasuredTimeSet = 1; this->MeasuredFileSet = 1; this->UseTimeSets = 0; this->UseFileSets = 0; this->GeometryTimeValue = -1; this->MeasuredTimeValue = -1; this->NumberOfGeometryParts = 0; this->NumberOfMeasuredPoints = 0; this->MeasuredNodeIds = vtkIdList::New(); this->OutputsAreValid = 1; this->InitialRead = 1; this->NumberOfNewOutputs; } //---------------------------------------------------------------------------- vtkEnSightReader::~vtkEnSightReader() { int i, j; if (this->CellIds) { for (i = 0; i < this->UnstructuredPartIds->GetNumberOfIds(); i++) { for (j = 0; j < 16; j++) { this->CellIds[i][j]->Delete(); this->CellIds[i][j] = NULL; } delete [] this->CellIds[i]; this->CellIds[i] = NULL; } delete [] this->CellIds; this->CellIds = NULL; } if (this->MeasuredFileName) { delete [] this->MeasuredFileName; this->MeasuredFileName = NULL; } if (this->MatchFileName) { delete [] this->MatchFileName; this->MatchFileName = NULL; } if (this->NumberOfVariables > 0) { for (i = 0; i < this->NumberOfVariables; i++) { delete [] this->VariableFileNames[i]; } delete [] this->VariableFileNames; this->VariableFileNames = NULL; } if (this->NumberOfComplexVariables > 0) { for (i = 0; i < this->NumberOfComplexVariables*2; i++) { delete [] this->ComplexVariableFileNames[i]; } delete [] this->ComplexVariableFileNames; this->ComplexVariableFileNames = NULL; } this->UnstructuredPartIds->Delete(); this->UnstructuredPartIds = NULL; this->MeasuredNodeIds->Delete(); this->MeasuredNodeIds = NULL; this->VariableTimeSetIds->Delete(); this->VariableTimeSetIds = NULL; this->ComplexVariableTimeSetIds->Delete(); this->ComplexVariableTimeSetIds = NULL; this->VariableFileSetIds->Delete(); this->VariableFileSetIds = NULL; this->ComplexVariableFileSetIds->Delete(); this->ComplexVariableFileSetIds = NULL; this->TimeSetFileNameNumbers->Delete(); this->TimeSetFileNameNumbers = NULL; this->TimeSetsWithFilenameNumbers->Delete(); this->TimeSetsWithFilenameNumbers = NULL; this->TimeSets->Delete(); this->TimeSets = NULL; this->FileSetFileNameNumbers->Delete(); this->FileSetFileNameNumbers = NULL; this->FileSetsWithFilenameNumbers->Delete(); this->FileSetsWithFilenameNumbers = NULL; this->FileSetNumberOfSteps->Delete(); this->FileSetNumberOfSteps = NULL; this->TimeSetIds->Delete(); this->TimeSets = NULL; this->FileSets->Delete(); this->FileSets = NULL; } //---------------------------------------------------------------------------- void vtkEnSightReader::Execute() { vtkDebugMacro("In execute "); int i, timeSet, fileSet, timeStep, timeStepInFile, fileNum; vtkDataArray *times; vtkIdList *numStepsList, *filenameNumbers; float newTime; int numSteps; char* fileName; int filenameNum; if ( ! this->CaseFileRead) { vtkErrorMacro("error reading case file"); return; } this->OutputsAreValid = 1; this->NumberOfNewOutputs = 0; this->NumberOfGeometryParts = 0; if (this->GeometryFileName) { timeStep = timeStepInFile = 1; fileNum = 1; fileName = new char[strlen(this->GeometryFileName) + 1]; strcpy(fileName, this->GeometryFileName); if (this->UseTimeSets) { timeSet = this->TimeSetIds->IsId(this->GeometryTimeSet); if (timeSet >= 0) { times = this->TimeSets->GetItem(timeSet); this->GeometryTimeValue = times->GetComponent(0, 0); for (i = 1; i < times->GetNumberOfTuples(); i++) { newTime = times->GetComponent(i, 0); if (newTime <= this->TimeValue && newTime > this->GeometryTimeValue) { this->GeometryTimeValue = newTime; timeStep++; timeStepInFile++; } } if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) { int collectionNum = this->TimeSetsWithFilenameNumbers-> IsId(this->GeometryTimeSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers->GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); } } // There can only be file sets if there are also time sets. if (this->UseFileSets) { fileSet = this->FileSets->IsId(this->GeometryFileSet); numStepsList = (vtkIdList*)this->FileSetNumberOfSteps-> GetItemAsObject(fileSet); if (timeStep > numStepsList->GetId(0)) { numSteps = numStepsList->GetId(0); timeStepInFile -= numSteps; for (i = 1; i < numStepsList->GetNumberOfIds(); i++) { numSteps += numStepsList->GetId(i); if (timeStep > numSteps) { fileNum++; timeStepInFile -= numStepsList->GetId(i); } } } if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) { int collectionNum = this->FileSetsWithFilenameNumbers-> IsId(this->GeometryFileSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(fileNum-1); this->ReplaceWildcards(fileName, filenameNum); } } } } } if (!this->ReadGeometryFile(fileName, timeStepInFile)) { vtkErrorMacro("error reading geometry file"); delete [] fileName; return; } delete [] fileName; } if (this->MeasuredFileName) { timeStep = timeStepInFile = 1; fileNum = 1; fileName = new char[strlen(this->MeasuredFileName) + 1]; strcpy(fileName, this->MeasuredFileName); if (this->UseTimeSets) { timeSet = this->TimeSetIds->IsId(this->MeasuredTimeSet); if (timeSet >= 0) { times = this->TimeSets->GetItem(timeSet); this->MeasuredTimeValue = times->GetComponent(0, 0); for (i = 1; i < times->GetNumberOfTuples(); i++) { newTime = times->GetComponent(i, 0); if (newTime <= this->TimeValue && newTime > this->MeasuredTimeValue) { this->MeasuredTimeValue = newTime; timeStep++; timeStepInFile++; } } if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) { int collectionNum = this->TimeSetsWithFilenameNumbers-> IsId(this->MeasuredTimeSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); } } // There can only be file sets if there are also time sets. if (this->UseFileSets) { fileSet = this->FileSets->IsId(this->MeasuredFileSet); numStepsList = (vtkIdList*)this->FileSetNumberOfSteps-> GetItemAsObject(fileSet); if (timeStep > numStepsList->GetId(0)) { numSteps = numStepsList->GetId(0); timeStepInFile -= numSteps; for (i = 1; i < numStepsList->GetNumberOfIds(); i++) { numSteps += numStepsList->GetId(i); if (timeStep > numSteps) { fileNum++; timeStepInFile -= numStepsList->GetId(i); } } } if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) { int collectionNum = this->FileSetsWithFilenameNumbers-> IsId(this->MeasuredFileSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(fileSet); filenameNum = filenameNumbers->GetId(fileNum-1); this->ReplaceWildcards(fileName, filenameNum); } } } } } if (!this->ReadMeasuredGeometryFile(fileName, timeStepInFile)) { vtkErrorMacro("error reading measured geometry file"); delete [] fileName; return; } delete [] fileName; } if (!this->CheckOutputConsistency()) { for (i = 0; i < this->NumberOfOutputs; i++) { this->GetOutput(i)->Initialize(); } return; } if ((this->NumberOfVariables + this->NumberOfComplexVariables) > 0) { if (!this->ReadVariableFiles()) { vtkErrorMacro("error reading variable files"); return; } } } //---------------------------------------------------------------------------- void vtkEnSightReader::Update() { vtkDebugMacro("In update");; int i; this->UpdateInformation(); this->UpdateData(0); for (i = 0; i < this->GetNumberOfOutputs(); i++) { if ( this->GetOutput(i) ) { this->GetOutput(i)->DataHasBeenGenerated(); } } } //---------------------------------------------------------------------------- void vtkEnSightReader::ExecuteInformation() { vtkDebugMacro("In execute information"); this->CaseFileRead = this->ReadCaseFile(); } //---------------------------------------------------------------------------- int vtkEnSightReader::ReadCaseFile() { char line[256], formatLine[256]; char subLine[256], subLine2[256]; int stringRead; int timeSet, fileSet, numTimeSteps, i, filenameNum, increment, lineRead; float timeStep; // Initialize // if (!this->CaseFileName) { vtkErrorMacro("A CaseFileName must be specified."); return 0; } if (this->FilePath) { strcpy(line, this->FilePath); strcat(line, this->CaseFileName); vtkDebugMacro("full path to case file: " << line); } else { strcpy(line, this->CaseFileName); } this->IS = new ifstream(line, ios::in); if (this->IS->fail()) { vtkErrorMacro("Unable to open file: " << line); delete this->IS; this->IS = NULL; return 0; } this->TimeSets->RemoveAllItems(); for (i = 0; i < this->NumberOfVariables; i++) { delete [] this->VariableFileNames[i]; this->VariableFileNames[i] = NULL; delete [] this->VariableDescriptions[i]; this->VariableDescriptions[i] = NULL; } delete [] this->VariableFileNames; this->VariableFileNames = NULL; delete [] this->VariableDescriptions; this->VariableDescriptions = NULL; delete [] this->VariableTypes; this->VariableTypes = NULL; for (i = 0; i < this->NumberOfComplexVariables; i++) { delete [] this->ComplexVariableFileNames[2*i]; this->ComplexVariableFileNames[2*i] = NULL; delete [] this->ComplexVariableFileNames[2*i+1]; this->ComplexVariableFileNames[2*i+1] = NULL; delete [] this->ComplexVariableDescriptions[i]; this->ComplexVariableDescriptions[i] = NULL; } delete [] this->ComplexVariableFileNames; this->ComplexVariableFileNames = NULL; delete [] this->ComplexVariableDescriptions; this->ComplexVariableDescriptions = NULL; delete [] this->ComplexVariableTypes; this->ComplexVariableTypes = NULL; this->NumberOfVariables = 0; this->NumberOfComplexVariables = 0; this->ReadNextDataLine(line); if (strncmp(line, "FORMAT", 6) == 0) { // found the FORMAT section vtkDebugMacro("*** FORMAT section"); this->ReadNextDataLine(line); stringRead = sscanf(line, " %*s %*s %s", subLine); if (stringRead == 1) { if (strcmp(subLine, "gold") == 0 && strcmp(this->GetClassName(), "vtkEnSight6Reader") == 0) { // The class is vtkEnSight6Reader, but the case file says "gold". vtkErrorMacro("This is not an EnSight6 file."); delete this->IS; this->IS = NULL; return 0; } } else { if (strcmp(this->GetClassName(), "vtkEnSightGoldReader") == 0) { // The class is vtkEnSightGoldReader, but the case file does // not say "gold". vtkErrorMacro("This is not an EnSight Gold file."); delete this->IS; this->IS = NULL; return 0; } } } // We know how many lines to read in the FORMAT section, so we haven't read // the "GEOMETRY" line yet. this->ReadNextDataLine(line); if (strncmp(line, "GEOMETRY", 8) == 0) { // found the GEOMETRY section vtkDebugMacro("*** GEOMETRY section"); // There will definitely be a "model" line. There may also be "measured" // and "match" lines. while(this->ReadNextDataLine(line) != 0 && strncmp(line, "m", 1) == 0) { if (strncmp(line, "model:", 6) == 0) { if (sscanf(line, " %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->GeometryTimeSet = timeSet; this->GeometryFileSet = fileSet; this->SetGeometryFileName(subLine); vtkDebugMacro(<<this->GetGeometryFileName()); } else if (sscanf(line, " %*s %d %s", &timeSet, subLine) == 2) { this->GeometryTimeSet = timeSet; this->SetGeometryFileName(subLine); vtkDebugMacro(<<this->GetGeometryFileName()); } else if (sscanf(line, " %*s %s", subLine) == 1) { this->SetGeometryFileName(subLine); vtkDebugMacro(<<this->GetGeometryFileName()); } } else if (strncmp(line, "measured:", 9) == 0) { if (sscanf(line, " %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->MeasuredTimeSet = timeSet; this->MeasuredFileSet = fileSet; this->SetMeasuredFileName(subLine); vtkDebugMacro(<< this->GetMeasuredFileName()); } else if (sscanf(line, " %*s %d %s", &timeSet, subLine) == 2) { this->MeasuredTimeSet = timeSet; this->SetMeasuredFileName(subLine); vtkDebugMacro(<< this->GetMeasuredFileName()); } else if (sscanf(line, " %*s %s", subLine) == 1) { this->SetMeasuredFileName(subLine); vtkDebugMacro(<< this->GetMeasuredFileName()); } } else if (strncmp(line, "match:", 6) == 0) { sscanf(line, " %*s %s", subLine); this->SetMatchFileName(subLine); vtkDebugMacro(<< this->GetMatchFileName()); } } } if (strncmp(line, "VARIABLE", 8) == 0) { // found the VARIABLE section vtkDebugMacro(<< "*** VARIABLE section"); while(this->ReadNextDataLine(line) != 0 && strncmp(line, "TIME", 4) != 0 && strncmp(line, "FILE", 4) != 0) { this->NumberOfScalarsPerNode = 0; this->NumberOfVectorsPerNode = 0; this->NumberOfTensorsSymmPerNode = 0; this->NumberOfScalarsPerElement = 0; this->NumberOfVectorsPerElement = 0; this->NumberOfTensorsSymmPerElement = 0; this->NumberOfScalarsPerMeasuredNode = 0; this->NumberOfVectorsPerMeasuredNode = 0; this->NumberOfComplexScalarsPerNode = 0; this->NumberOfComplexVectorsPerNode = 0; this->NumberOfComplexScalarsPerElement = 0; this->NumberOfComplexVectorsPerElement = 0; if (strncmp(line, "constant", 8) == 0) { vtkDebugMacro(<< line); } else if (strncmp(line, "scalar", 6) == 0) { sscanf(line, " %*s %*s %s", subLine); if (strcmp(subLine, "node:") == 0) { vtkDebugMacro("scalar per node"); this->VariableMode = vtkEnSightReader::SCALAR_PER_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %s", subLine); } this->NumberOfScalarsPerNode++; } else if (strcmp(subLine, "element:") == 0) { vtkDebugMacro("scalar per element"); this->VariableMode = vtkEnSightReader::SCALAR_PER_ELEMENT; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %s", subLine); } this->NumberOfScalarsPerElement++; } else if (strcmp(subLine, "measured") == 0) { vtkDebugMacro("scalar per measured node"); this->VariableMode = vtkEnSightReader::SCALAR_PER_MEASURED_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s", subLine); } this->NumberOfScalarsPerMeasuredNode++; } this->AddVariableFileName(subLine); this->NumberOfVariables++; } else if (strncmp(line, "vector", 6) == 0) { sscanf(line, " %*s %*s %s", subLine); if (strcmp(subLine, "node:") == 0) { vtkDebugMacro("vector per node"); this->VariableMode = vtkEnSightReader::VECTOR_PER_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %s", subLine); } this->NumberOfVectorsPerNode++; } else if (strcmp(subLine, "element:") == 0) { vtkDebugMacro("vector per element"); this->VariableMode = vtkEnSightReader::VECTOR_PER_ELEMENT; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %s", subLine); } this->NumberOfVectorsPerElement++; } else if (strcmp(subLine, "measured") == 0) { vtkDebugMacro("vector per measured node"); this->VariableMode = vtkEnSightReader::VECTOR_PER_MEASURED_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s", subLine); } this->NumberOfVectorsPerMeasuredNode++; } this->AddVariableFileName(subLine); this->NumberOfVariables++; } else if (strncmp(line, "tensor", 6) == 0) { sscanf(line, " %*s %*s %*s %s", subLine); if (strcmp(subLine, "node:") == 0) { vtkDebugMacro("tensor symm per node"); this->VariableMode = vtkEnSightReader::TENSOR_SYMM_PER_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s", subLine); } this->NumberOfTensorsSymmPerNode++; } else if (strcmp(subLine, "element:") == 0) { vtkDebugMacro("tensor symm per element"); this->VariableMode = vtkEnSightReader::TENSOR_SYMM_PER_ELEMENT; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s", subLine); } this->NumberOfTensorsSymmPerElement++; } this->AddVariableFileName(subLine); this->NumberOfVariables++; } else if (strncmp(line, "complex", 6) == 0) { sscanf(line, " %*s %s", subLine); if (strcmp(subLine, "scalar") == 0) { sscanf(line, " %*s %*s %*s %s", subLine); if (strcmp(subLine, "node:") == 0) { vtkDebugMacro("complex scalar per node"); this->VariableMode = vtkEnSightReader::COMPLEX_SCALAR_PER_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->ComplexVariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->ComplexVariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s %s", subLine, subLine2); } this->NumberOfComplexScalarsPerNode++; } else if (strcmp(subLine, "element:") == 0) { vtkDebugMacro("complex scalar per element"); this->VariableMode = vtkEnSightReader::COMPLEX_SCALAR_PER_ELEMENT; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->ComplexVariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->ComplexVariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s %s", subLine, subLine2); } this->NumberOfComplexScalarsPerElement++; } } else if (strcmp(subLine, "vector") == 0) { sscanf(line, " %*s %*s %*s %s", subLine); if (strcmp(subLine, "node:") == 0) { vtkDebugMacro("complex vector per node"); this->VariableMode = vtkEnSightReader::COMPLEX_VECTOR_PER_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->ComplexVariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->ComplexVariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s %s", subLine, subLine2); } this->NumberOfComplexVectorsPerNode++; } else if (strcmp(subLine, "element:") == 0) { vtkDebugMacro("complex vector per element"); this->VariableMode = vtkEnSightReader::COMPLEX_VECTOR_PER_ELEMENT; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->ComplexVariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->ComplexVariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s %s", subLine, subLine2); } this->NumberOfComplexVectorsPerElement++; } } this->AddVariableFileName(subLine, subLine2); this->NumberOfComplexVariables++; } else { vtkErrorMacro("invalid VARIABLE line: " << line); delete this->IS; this->IS = NULL; return 0; } } } if (strncmp(line, "TIME", 4) == 0) { // found TIME section int firstTimeStep = 1; this->UseTimeSetsOn(); while(this->ReadNextDataLine(line) != 0 && strncmp(line, "FILE", 4) != 0) { sscanf(line, "%*s %*s %d", &timeSet); this->TimeSetIds->InsertNextId(timeSet); this->ReadNextDataLine(line); sscanf(line, "%*s %*s %*s %d", &numTimeSteps); this->ReadNextDataLine(line); if (strncmp(line, "filename", 8) == 0) { vtkIdList *filenameNumbers = vtkIdList::New(); this->TimeSetsWithFilenameNumbers->InsertNextId(timeSet); sscanf(line, "%*s %s", subLine); if (strncmp(subLine, "numbers", 7) == 0) { strcpy(formatLine, "%*s %*s"); strcpy(subLine, "%*s %*s"); for (i = 0; i < numTimeSteps; i++) { strcat(formatLine, " %d"); sscanf(line, formatLine, &filenameNum); filenameNumbers->InsertNextId(filenameNum); strcat(subLine, " %*d"); strcpy(formatLine, subLine); } } else { sscanf(line, "%*s %*s %*s %d", &filenameNum); this->ReadNextDataLine(line); sscanf(line, "%*s %*s %d", &increment); for (i = 0; i < numTimeSteps; i++) { filenameNumbers->InsertNextId(filenameNum + i*increment); } } this->TimeSetFileNameNumbers->AddItem(filenameNumbers); filenameNumbers->Delete(); filenameNumbers = NULL; this->ReadLine(line); } vtkFloatArray *timeValues = vtkFloatArray::New(); timeValues->SetNumberOfComponents(1); timeValues->SetNumberOfTuples(numTimeSteps); strcpy(formatLine, "%*s %*s"); strcpy(subLine, "%*s %*s"); for (i = 0; i < numTimeSteps; i++) { strcat(formatLine, " %f"); if (sscanf(line, formatLine, &timeStep) != 1) { this->ReadNextDataLine(line); strcpy(formatLine, " %f"); strcpy(subLine, ""); sscanf(line, formatLine, &timeStep); } if (firstTimeStep) { this->MinimumTimeValue = timeStep; this->MaximumTimeValue = timeStep; firstTimeStep = 0; } else { if (timeStep < this->MinimumTimeValue) { this->MinimumTimeValue = timeStep; } else if (timeStep > this->MaximumTimeValue) { this->MaximumTimeValue = timeStep; } } timeValues->SetComponent(i, 0, timeStep); strcat(subLine, " %*f"); strcpy(formatLine, subLine); } this->TimeSets->AddItem(timeValues); timeValues->Delete(); timeValues = NULL; } } if (strncmp(line, "FILE", 4) == 0) { // found FILE section this->UseFileSetsOn(); lineRead = this->ReadNextDataLine(line); while (lineRead != 0) { vtkIdList *filenameNums = vtkIdList::New(); vtkIdList *numSteps = vtkIdList::New(); sscanf(line, "%*s %*s %d", &fileSet); this->FileSets->InsertNextId(fileSet); lineRead = this->ReadNextDataLine(line); if (strncmp(line, "filename", 8) == 0) { this->FileSetsWithFilenameNumbers->InsertNextId(fileSet); while (lineRead != 0 && strncmp(line, "filename", 8) == 0) { sscanf(line, "%*s %*s %d", &filenameNum); filenameNums->InsertNextId(filenameNum); this->ReadNextDataLine(line); sscanf(line, "%*s %*s %*s %d", &numTimeSteps); numSteps->InsertNextId(numTimeSteps); lineRead = this->ReadNextDataLine(line); } this->FileSetFileNameNumbers->AddItem(filenameNums); } else { sscanf(line, "%*s %*s %*s %d", &numTimeSteps); numSteps->InsertNextId(numTimeSteps); lineRead = this->ReadNextDataLine(line); } this->FileSetNumberOfSteps->AddItem(numSteps); filenameNums->Delete(); filenameNums = NULL; numSteps->Delete(); numSteps = NULL; } } delete this->IS; this->IS = NULL; return 1; } //---------------------------------------------------------------------------- int vtkEnSightReader::ReadVariableFiles() { int i, j; char description[256]; int timeSet, fileSet, timeStep, timeStepInFile, numSteps; vtkDataArray *times; float newTime; vtkIdList *numStepsList, *filenameNumbers; int validTime, fileNum, filenameNum; char* fileName, *fileName2; for (i = 0; i < this->NumberOfVariables; i++) { timeStep = 0; timeStepInFile = 1; fileNum = 1; validTime = 1; fileName = new char[strlen(this->VariableFileNames[i]) + 1]; strcpy(fileName, this->VariableFileNames[i]); if (this->UseTimeSets) { validTime = 0; timeSet = this->VariableTimeSetIds->GetId(i); times = this->TimeSets->GetItem(this->TimeSetIds->IsId(timeSet)); for (j = 0; j < times->GetNumberOfTuples(); j++) { newTime = times->GetComponent(j, 0); if (newTime <= this->TimeValue) { timeStep++; if (this->VariableTypes[i] == SCALAR_PER_MEASURED_NODE || this->VariableTypes[i] == VECTOR_PER_MEASURED_NODE) { if (newTime >= this->MeasuredTimeValue || this->MeasuredTimeSet == -1) { validTime = 1; } } else if (newTime >= this->GeometryTimeValue || this->GeometryTimeSet == -1) { validTime = 1; } } } if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0 && validTime) { int collectionNum = this->TimeSetsWithFilenameNumbers->IsId(timeSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); } } // There can only be file sets if there are also time sets. if (this->UseFileSets) { timeStepInFile = timeStep; fileSet = this->VariableFileSetIds->GetId(i); numStepsList = (vtkIdList*)this->FileSetNumberOfSteps-> GetItemAsObject(this->FileSets->IsId(fileSet)); if (timeStep > numStepsList->GetId(0)) { numSteps = numStepsList->GetId(0); timeStepInFile -= numSteps; for (i = 1; i < numStepsList->GetNumberOfIds(); i++) { numSteps += numStepsList->GetId(i); if (timeStep > numSteps) { fileNum++; timeStepInFile -= numStepsList->GetId(i); } } } if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0 && validTime) { int collectionNum = this->FileSetsWithFilenameNumbers->IsId(fileSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); } } } } if (validTime) { switch (this->VariableTypes[i]) { case vtkEnSightReader::SCALAR_PER_NODE: this->ReadScalarsPerNode(fileName, this->VariableDescriptions[i], timeStepInFile); break; case vtkEnSightReader::SCALAR_PER_MEASURED_NODE: this->ReadScalarsPerNode(fileName, this->VariableDescriptions[i], timeStepInFile, 1); break; case vtkEnSightReader::VECTOR_PER_NODE: this->ReadVectorsPerNode(fileName, this->VariableDescriptions[i], timeStepInFile); break; case vtkEnSightReader::VECTOR_PER_MEASURED_NODE: this->ReadVectorsPerNode(fileName, this->VariableDescriptions[i], timeStepInFile, 1); break; case vtkEnSightReader::TENSOR_SYMM_PER_NODE: this->ReadTensorsPerNode(fileName, this->VariableDescriptions[i], timeStepInFile); break; case vtkEnSightReader::SCALAR_PER_ELEMENT: this->ReadScalarsPerElement(fileName, this->VariableDescriptions[i], timeStepInFile); break; case vtkEnSightReader::VECTOR_PER_ELEMENT: this->ReadVectorsPerElement(fileName, this->VariableDescriptions[i], timeStepInFile); break; case vtkEnSightReader::TENSOR_SYMM_PER_ELEMENT: this->ReadTensorsPerElement(fileName, this->VariableDescriptions[i], timeStepInFile); break; } } delete [] fileName; } for (i = 0; i < this->NumberOfComplexVariables; i++) { timeStep = 0; timeStepInFile = 1; fileNum = 1; validTime = 1; fileName = new char[strlen(this->ComplexVariableFileNames[2*i]) + 1]; strcpy(fileName, this->ComplexVariableFileNames[2*i]); fileName2 = new char[strlen(this->ComplexVariableFileNames[2*i+1]) + 1]; strcpy(fileName2, this->ComplexVariableFileNames[2*i+1]); if (this->UseTimeSets) { validTime = 0; timeSet = this->VariableTimeSetIds->GetId(i); times = this->TimeSets->GetItem(this->TimeSetIds->IsId(timeSet)); for (j = 0; j < times->GetNumberOfTuples(); j++) { newTime = times->GetComponent(j, 0); if (newTime <= this->TimeValue) { timeStep++; if (this->VariableTypes[i] == SCALAR_PER_MEASURED_NODE || this->VariableTypes[i] == VECTOR_PER_MEASURED_NODE) { if (newTime >= this->MeasuredTimeValue) { validTime = 1; } } else if (newTime >= this->GeometryTimeValue) { validTime = 1; } } } if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0 && validTime) { int collectionNum = this->TimeSetsWithFilenameNumbers->IsId(timeSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); this->ReplaceWildcards(fileName2, filenameNum); } } // There can only be file sets if there are also time sets. if (this->UseFileSets) { timeStepInFile = timeStep; fileSet = this->VariableFileSetIds->GetId(i); numStepsList = (vtkIdList*)this->FileSetNumberOfSteps-> GetItemAsObject(this->FileSets->IsId(fileSet)); if (timeStep > numStepsList->GetId(0)) { numSteps = numStepsList->GetId(0); timeStepInFile -= numSteps; for (i = 1; i < numStepsList->GetNumberOfIds(); i++) { numSteps += numStepsList->GetId(i); if (timeStep > numSteps) { fileNum++; timeStepInFile -= numStepsList->GetId(i); } } } if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0 && validTime) { int collectionNum = this->FileSetsWithFilenameNumbers->IsId(fileSet); if (collectionNum > -1) { filenameNumbers = this->FileSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); this->ReplaceWildcards(fileName2, filenameNum); } } } } if (validTime) { switch (this->ComplexVariableTypes[i]) { case vtkEnSightReader::COMPLEX_SCALAR_PER_NODE: this->ReadScalarsPerNode(fileName, this->ComplexVariableDescriptions[i], timeStepInFile, 0, 2); this->ReadScalarsPerNode(fileName2, this->ComplexVariableDescriptions[i], timeStepInFile, 0, 2, 1); break; case vtkEnSightReader::COMPLEX_VECTOR_PER_NODE: strcpy(description, this->ComplexVariableDescriptions[i]); strcat(description, "_r"); this->ReadVectorsPerNode(fileName, description, timeStepInFile); strcpy(description, this->ComplexVariableDescriptions[i]); strcat(description, "_i"); this->ReadVectorsPerNode(fileName2, description, timeStepInFile); break; case vtkEnSightReader::COMPLEX_SCALAR_PER_ELEMENT: this->ReadScalarsPerElement(fileName, this->ComplexVariableDescriptions[i], timeStepInFile, 2); this->ReadScalarsPerElement(fileName2, this->ComplexVariableDescriptions[i], timeStepInFile, 2, 1); break; case vtkEnSightReader::COMPLEX_VECTOR_PER_ELEMENT: strcpy(description, this->ComplexVariableDescriptions[i]); strcat(description, "_r"); this->ReadVectorsPerElement(fileName, description, timeStepInFile); strcpy(description, this->ComplexVariableDescriptions[i]); strcat(description, "_i"); this->ReadVectorsPerElement(fileName2, description, timeStepInFile); break; } } delete [] fileName; delete [] fileName2; } return 1; } //---------------------------------------------------------------------------- void vtkEnSightReader::AddVariableFileName(char* fileName1, char* fileName2) { int size; int i; if (this->VariableMode < 8) { size = this->NumberOfVariables; char** newFileNameList = new char *[size]; // temporary array // copy file names to temporary array for (i = 0; i < size; i++) { newFileNameList[i] = new char[strlen(this->VariableFileNames[i]) + 1]; strcpy(newFileNameList[i], this->VariableFileNames[i]); delete [] this->VariableFileNames[i]; } delete [] this->VariableFileNames; // make room for new file name this->VariableFileNames = new char *[size+1]; // copy existing file names back to first array for (i = 0; i < size; i++) { this->VariableFileNames[i] = new char[strlen(newFileNameList[i]) + 1]; strcpy(this->VariableFileNames[i], newFileNameList[i]); delete [] newFileNameList[i]; } delete [] newFileNameList; // add new file name at end of first array this->VariableFileNames[size] = new char[strlen(fileName1) + 1]; strcpy(this->VariableFileNames[size], fileName1); vtkDebugMacro( << "file name: " << this->VariableFileNames[size]); } else { size = this->NumberOfComplexVariables; char** newFileNameList = new char *[2 * size]; // temporary array // copy file names to temporary array for (i = 0; i < 2*size; i++) { newFileNameList[i] = new char[strlen(this->ComplexVariableFileNames[i]) + 1]; strcpy(newFileNameList[i], this->ComplexVariableFileNames[i]); delete [] this->ComplexVariableFileNames[i]; } delete [] this->ComplexVariableFileNames; // make room for new file name this->ComplexVariableFileNames = new char *[2*(size+1)]; // copy existing file names back to first array for (i = 0; i < 2*size; i++) { this->ComplexVariableFileNames[i] = new char[strlen(newFileNameList[i]) + 1]; strcpy(this->ComplexVariableFileNames[i], newFileNameList[i]); delete [] newFileNameList[i]; } delete [] newFileNameList; // add new file name at end of first array this->ComplexVariableFileNames[2*size] = new char[strlen(fileName1) + 1]; strcpy(this->ComplexVariableFileNames[2*size], fileName1); vtkDebugMacro("real file name: " << this->ComplexVariableFileNames[2*size]); this->ComplexVariableFileNames[2*size+1] = new char[strlen(fileName2) + 1]; strcpy(this->ComplexVariableFileNames[2*size+1], fileName2); vtkDebugMacro("imag. file name: " << this->ComplexVariableFileNames[2*size+1]); } } //---------------------------------------------------------------------------- void vtkEnSightReader::AddVariableDescription(char* description) { int size; int i; if (this->VariableMode < 8) { size = this->NumberOfVariables; char ** newDescriptionList = new char *[size]; // temporary array // copy descriptions to temporary array for (i = 0; i < size; i++) { newDescriptionList[i] = new char[strlen(this->VariableDescriptions[i]) + 1]; strcpy(newDescriptionList[i], this->VariableDescriptions[i]); delete [] this->VariableDescriptions[i]; } delete [] this->VariableDescriptions; // make room for new description this->VariableDescriptions = new char *[size+1]; // copy existing descriptions back to first array for (i = 0; i < size; i++) { this->VariableDescriptions[i] = new char[strlen(newDescriptionList[i]) + 1]; strcpy(this->VariableDescriptions[i], newDescriptionList[i]); delete [] newDescriptionList[i]; } delete [] newDescriptionList; // add new description at end of first array this->VariableDescriptions[size] = new char[strlen(description) + 1]; strcpy(this->VariableDescriptions[size], description); vtkDebugMacro("description: " << this->VariableDescriptions[size]); } else { size = this->NumberOfComplexVariables; char ** newDescriptionList = new char *[size]; // temporary array // copy descriptions to temporary array for (i = 0; i < size; i++) { newDescriptionList[i] = new char[strlen(this->ComplexVariableDescriptions[i]) + 1]; strcpy(newDescriptionList[i], this->ComplexVariableDescriptions[i]); delete [] this->ComplexVariableDescriptions[i]; } delete [] this->ComplexVariableDescriptions; // make room for new description this->ComplexVariableDescriptions = new char *[size+1]; // copy existing descriptions back to first array for (i = 0; i < size; i++) { this->ComplexVariableDescriptions[i] = new char[strlen(newDescriptionList[i]) + 1]; strcpy(this->ComplexVariableDescriptions[i], newDescriptionList[i]); delete [] newDescriptionList[i]; } delete [] newDescriptionList; // add new description at end of first array this->ComplexVariableDescriptions[size] = new char[strlen(description) + 1]; strcpy(this->ComplexVariableDescriptions[size], description); vtkDebugMacro("description: " << this->ComplexVariableDescriptions[size]); } } //---------------------------------------------------------------------------- void vtkEnSightReader::AddVariableType() { int size; int i; int *types = NULL; // Figure out what the size of the variable type array is. if (this->VariableMode < 8) { size = this->NumberOfVariables; types = new int[size]; for (i = 0; i < size; i++) { types[i] = this->VariableTypes[i]; } delete [] this->VariableTypes; this->VariableTypes = new int[size+1]; for (i = 0; i < size; i++) { this->VariableTypes[i] = types[i]; } delete [] types; this->VariableTypes[size] = this->VariableMode; vtkDebugMacro("variable type: " << this->VariableTypes[size]); } else { size = this->NumberOfComplexVariables; if (size > 0) { types = new int[size]; for (i = 0; i < size; i++) { types[i] = this->ComplexVariableTypes[i]; } delete [] this->ComplexVariableTypes; } this->ComplexVariableTypes = new int[size+1]; for (i = 0; i < size; i++) { this->ComplexVariableTypes[i] = types[i]; } if (size > 0) { delete [] types; } this->ComplexVariableTypes[size] = this->VariableMode; vtkDebugMacro("complex variable type: " << this->ComplexVariableTypes[size]); } } int vtkEnSightReader::GetElementType(char* line) { if (strncmp(line, "point", 5) == 0) { return vtkEnSightReader::POINT; } else if (strncmp(line, "bar2", 4) == 0) { return vtkEnSightReader::BAR2; } else if (strncmp(line, "bar3", 4) == 0) { return vtkEnSightReader::BAR3; } else if (strncmp(line, "nsided", 6) == 0) { return vtkEnSightReader::NSIDED; } else if (strncmp(line, "tria3", 5) == 0) { return vtkEnSightReader::TRIA3; } else if (strncmp(line, "tria6", 5) == 0) { return vtkEnSightReader::TRIA6; } else if (strncmp(line, "quad4", 5) == 0) { return vtkEnSightReader::QUAD4; } else if (strncmp(line, "quad8", 5) == 0) { return vtkEnSightReader::QUAD8; } else if (strncmp(line, "tetra4", 6) == 0) { return vtkEnSightReader::TETRA4; } else if (strncmp(line, "tetra10", 7) == 0) { return vtkEnSightReader::TETRA10; } else if (strncmp(line, "pyramid5", 8) == 0) { return vtkEnSightReader::PYRAMID5; } else if (strncmp(line, "pyramid13", 9) == 0) { return vtkEnSightReader::PYRAMID13; } else if (strncmp(line, "hexa8", 5) == 0) { return vtkEnSightReader::HEXA8; } else if (strncmp(line, "hexa20", 6) == 0) { return vtkEnSightReader::HEXA20; } else if (strncmp(line, "penta6", 6) == 0) { return vtkEnSightReader::PENTA6; } else if (strncmp(line, "penta15", 7) == 0) { return vtkEnSightReader::PENTA15; } else { return -1; } } void vtkEnSightReader::ReplaceWildcards(char* filename, int num) { int wildcardPos, numWildcards, numDigits = 1, i; int tmpNum = num, multTen = 1; char newChar; int newNum; wildcardPos = static_cast<int>(strcspn(filename, "*")); numWildcards = static_cast<int>(strspn(filename + wildcardPos, "*")); if (numWildcards == 0) { return; } tmpNum /= 10; while (tmpNum >= 1) { numDigits++; multTen *= 10; tmpNum /= 10; } for (i = 0; i < numWildcards - numDigits; i++) { filename[i + wildcardPos] = '0'; } tmpNum = num; for (i = numWildcards - numDigits; i < numWildcards; i++) { newNum = tmpNum / multTen; switch (newNum) { case 0: newChar = '0'; break; case 1: newChar = '1'; break; case 2: newChar = '2'; break; case 3: newChar = '3'; break; case 4: newChar = '4'; break; case 5: newChar = '5'; break; case 6: newChar = '6'; break; case 7: newChar = '7'; break; case 8: newChar = '8'; break; case 9: newChar = '9'; break; default: // This case should never be reached. return; } filename[i + wildcardPos] = newChar; tmpNum -= multTen * newNum; multTen /= 10; } } //---------------------------------------------------------------------------- // Called by constructor to set up output array. void vtkEnSightReader::SetNumberOfOutputsInternal(int num) { int idx; vtkDataObject **outputs; // in case nothing has changed. if (num == this->NumberOfOutputs) { return; } // Allocate new arrays. outputs = new vtkDataObject *[num]; // Initialize with NULLs. for (idx = 0; idx < num; ++idx) { outputs[idx] = NULL; } // Copy old outputs for (idx = 0; idx < num && idx < this->NumberOfOutputs; ++idx) { outputs[idx] = this->Outputs[idx]; } // delete the previous arrays if (this->Outputs) { delete [] this->Outputs; this->Outputs = NULL; this->NumberOfOutputs = 0; } // Set the new arrays this->Outputs = outputs; this->NumberOfOutputs = num; } //---------------------------------------------------------------------------- void vtkEnSightReader::ReplaceNthOutput(int idx, vtkDataObject* newOutput) { vtkDataObject *oldOutput; if (idx < 0) { vtkErrorMacro(<< "SetNthOutput: " << idx << ", cannot set output. "); return; } // Expand array if necessary. if (idx >= this->NumberOfOutputs) { this->SetNumberOfOutputsInternal(idx + 1); } // does this change anything? oldOutput = this->Outputs[idx]; if (newOutput == oldOutput) { return; } if ( !newOutput->IsA(oldOutput->GetClassName()) ) { vtkErrorMacro("Can not replace the output with a different type."); return; } if (newOutput) { vtkSource *newOutputOldSource = newOutput->GetSource(); if (newOutputOldSource) { vtkErrorMacro("The new output can not have a source."); return; } } // disconnect first existing source-output relationship. if (oldOutput) { oldOutput->SetSource(NULL); oldOutput->UnRegister(this); this->Outputs[idx] = NULL; } if (newOutput) { // Register the newOutput so it does not get deleted. // Don't set the link yet until previous links is disconnected. newOutput->Register(this); newOutput->SetSource(this); } // now actually make the link that was registered previously. this->Outputs[idx] = newOutput; } int vtkEnSightReader::CheckOutputConsistency() { if (this->NumberOfOutputs > this->NumberOfNewOutputs && ! this->InitialRead) { vtkErrorMacro("Cannot decrease number of outputs after initial read"); this->OutputsAreValid = 0; } if (this->InitialRead) { this->InitialRead = 0; } return this->OutputsAreValid; } //---------------------------------------------------------------------------- void vtkEnSightReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "CaseFileName: " << (this->CaseFileName ? this->CaseFileName : "(none)") << endl; os << indent << "FilePath: " << (this->FilePath ? this->FilePath : "(none)") << endl; os << indent << "NumberOfComplexScalarsPerNode: " << this->NumberOfComplexScalarsPerNode << endl; os << indent << "NumberOfVectorsPerElement :" << this->NumberOfVectorsPerElement << endl; os << indent << "NumberOfTensorsSymmPerElement: " << this->NumberOfTensorsSymmPerElement << endl; os << indent << "NumberOfComplexVectorsPerNode: " << this->NumberOfComplexVectorsPerNode << endl; os << indent << "NumberOfScalarsPerElement: " << this->NumberOfScalarsPerElement << endl; os << indent << "NumberOfComplexVectorsPerElement: " << this->NumberOfComplexVectorsPerElement << endl; os << indent << "NumberOfComplexScalarsPerElement: " << this->NumberOfComplexScalarsPerElement << endl; os << indent << "NumberOfTensorsSymmPerNode: " << this->NumberOfTensorsSymmPerNode << endl; os << indent << "NumberOfScalarsPerMeasuredNode: " << this->NumberOfScalarsPerMeasuredNode << endl; os << indent << "NumberOfVectorsPerMeasuredNode: " << this->NumberOfVectorsPerMeasuredNode << endl; os << indent << "NumberOfScalarsPerNode: " << this->NumberOfScalarsPerNode << endl; os << indent << "NumberOfVectorsPerNode: " << this->NumberOfVectorsPerNode << endl; os << indent << "TimeValue: " << this->TimeValue << endl; os << indent << "MinimumTimeValue: " << this->MinimumTimeValue << endl; os << indent << "MaximumTimeValue: " << this->MaximumTimeValue << endl; os << indent << "TimeSets: " << this->TimeSets << endl; } initializing NumberOfNewOutputs /*========================================================================= Program: Visualization Toolkit Module: vtkEnSightReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkEnSightReader.h" #include "vtkDataArrayCollection.h" #include "vtkIdListCollection.h" #include "vtkFloatArray.h" #include "vtkObjectFactory.h" #include "vtkRectilinearGrid.h" #include "vtkStructuredGrid.h" #include "vtkStructuredPoints.h" #include "vtkUnstructuredGrid.h" vtkCxxRevisionMacro(vtkEnSightReader, "1.40"); //---------------------------------------------------------------------------- vtkEnSightReader::vtkEnSightReader() { this->MeasuredFileName = NULL; this->MatchFileName = NULL; this->IS = NULL; this->VariableMode = -1; this->UnstructuredPartIds = vtkIdList::New(); this->CellIds = NULL; this->VariableFileNames = NULL; this->ComplexVariableFileNames = NULL; this->VariableDescriptions = NULL; this->ComplexVariableDescriptions = NULL; this->VariableTimeSetIds = vtkIdList::New(); this->ComplexVariableTimeSetIds = vtkIdList::New(); this->VariableFileSetIds = vtkIdList::New(); this->ComplexVariableFileSetIds = vtkIdList::New(); this->TimeSetFileNameNumbers = vtkIdListCollection::New(); this->TimeSetsWithFilenameNumbers = vtkIdList::New(); this->TimeSets = vtkDataArrayCollection::New(); this->FileSetFileNameNumbers = vtkIdListCollection::New(); this->FileSetsWithFilenameNumbers = vtkIdList::New(); this->FileSetNumberOfSteps = vtkIdListCollection::New(); this->TimeSetIds = vtkIdList::New(); this->FileSets = vtkIdList::New(); this->GeometryTimeSet = 1; this->GeometryFileSet = 1; this->MeasuredTimeSet = 1; this->MeasuredFileSet = 1; this->UseTimeSets = 0; this->UseFileSets = 0; this->GeometryTimeValue = -1; this->MeasuredTimeValue = -1; this->NumberOfGeometryParts = 0; this->NumberOfMeasuredPoints = 0; this->MeasuredNodeIds = vtkIdList::New(); this->OutputsAreValid = 1; this->InitialRead = 1; this->NumberOfNewOutputs = 0; } //---------------------------------------------------------------------------- vtkEnSightReader::~vtkEnSightReader() { int i, j; if (this->CellIds) { for (i = 0; i < this->UnstructuredPartIds->GetNumberOfIds(); i++) { for (j = 0; j < 16; j++) { this->CellIds[i][j]->Delete(); this->CellIds[i][j] = NULL; } delete [] this->CellIds[i]; this->CellIds[i] = NULL; } delete [] this->CellIds; this->CellIds = NULL; } if (this->MeasuredFileName) { delete [] this->MeasuredFileName; this->MeasuredFileName = NULL; } if (this->MatchFileName) { delete [] this->MatchFileName; this->MatchFileName = NULL; } if (this->NumberOfVariables > 0) { for (i = 0; i < this->NumberOfVariables; i++) { delete [] this->VariableFileNames[i]; } delete [] this->VariableFileNames; this->VariableFileNames = NULL; } if (this->NumberOfComplexVariables > 0) { for (i = 0; i < this->NumberOfComplexVariables*2; i++) { delete [] this->ComplexVariableFileNames[i]; } delete [] this->ComplexVariableFileNames; this->ComplexVariableFileNames = NULL; } this->UnstructuredPartIds->Delete(); this->UnstructuredPartIds = NULL; this->MeasuredNodeIds->Delete(); this->MeasuredNodeIds = NULL; this->VariableTimeSetIds->Delete(); this->VariableTimeSetIds = NULL; this->ComplexVariableTimeSetIds->Delete(); this->ComplexVariableTimeSetIds = NULL; this->VariableFileSetIds->Delete(); this->VariableFileSetIds = NULL; this->ComplexVariableFileSetIds->Delete(); this->ComplexVariableFileSetIds = NULL; this->TimeSetFileNameNumbers->Delete(); this->TimeSetFileNameNumbers = NULL; this->TimeSetsWithFilenameNumbers->Delete(); this->TimeSetsWithFilenameNumbers = NULL; this->TimeSets->Delete(); this->TimeSets = NULL; this->FileSetFileNameNumbers->Delete(); this->FileSetFileNameNumbers = NULL; this->FileSetsWithFilenameNumbers->Delete(); this->FileSetsWithFilenameNumbers = NULL; this->FileSetNumberOfSteps->Delete(); this->FileSetNumberOfSteps = NULL; this->TimeSetIds->Delete(); this->TimeSets = NULL; this->FileSets->Delete(); this->FileSets = NULL; } //---------------------------------------------------------------------------- void vtkEnSightReader::Execute() { vtkDebugMacro("In execute "); int i, timeSet, fileSet, timeStep, timeStepInFile, fileNum; vtkDataArray *times; vtkIdList *numStepsList, *filenameNumbers; float newTime; int numSteps; char* fileName; int filenameNum; if ( ! this->CaseFileRead) { vtkErrorMacro("error reading case file"); return; } this->OutputsAreValid = 1; this->NumberOfNewOutputs = 0; this->NumberOfGeometryParts = 0; if (this->GeometryFileName) { timeStep = timeStepInFile = 1; fileNum = 1; fileName = new char[strlen(this->GeometryFileName) + 1]; strcpy(fileName, this->GeometryFileName); if (this->UseTimeSets) { timeSet = this->TimeSetIds->IsId(this->GeometryTimeSet); if (timeSet >= 0) { times = this->TimeSets->GetItem(timeSet); this->GeometryTimeValue = times->GetComponent(0, 0); for (i = 1; i < times->GetNumberOfTuples(); i++) { newTime = times->GetComponent(i, 0); if (newTime <= this->TimeValue && newTime > this->GeometryTimeValue) { this->GeometryTimeValue = newTime; timeStep++; timeStepInFile++; } } if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) { int collectionNum = this->TimeSetsWithFilenameNumbers-> IsId(this->GeometryTimeSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers->GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); } } // There can only be file sets if there are also time sets. if (this->UseFileSets) { fileSet = this->FileSets->IsId(this->GeometryFileSet); numStepsList = (vtkIdList*)this->FileSetNumberOfSteps-> GetItemAsObject(fileSet); if (timeStep > numStepsList->GetId(0)) { numSteps = numStepsList->GetId(0); timeStepInFile -= numSteps; for (i = 1; i < numStepsList->GetNumberOfIds(); i++) { numSteps += numStepsList->GetId(i); if (timeStep > numSteps) { fileNum++; timeStepInFile -= numStepsList->GetId(i); } } } if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) { int collectionNum = this->FileSetsWithFilenameNumbers-> IsId(this->GeometryFileSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(fileNum-1); this->ReplaceWildcards(fileName, filenameNum); } } } } } if (!this->ReadGeometryFile(fileName, timeStepInFile)) { vtkErrorMacro("error reading geometry file"); delete [] fileName; return; } delete [] fileName; } if (this->MeasuredFileName) { timeStep = timeStepInFile = 1; fileNum = 1; fileName = new char[strlen(this->MeasuredFileName) + 1]; strcpy(fileName, this->MeasuredFileName); if (this->UseTimeSets) { timeSet = this->TimeSetIds->IsId(this->MeasuredTimeSet); if (timeSet >= 0) { times = this->TimeSets->GetItem(timeSet); this->MeasuredTimeValue = times->GetComponent(0, 0); for (i = 1; i < times->GetNumberOfTuples(); i++) { newTime = times->GetComponent(i, 0); if (newTime <= this->TimeValue && newTime > this->MeasuredTimeValue) { this->MeasuredTimeValue = newTime; timeStep++; timeStepInFile++; } } if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) { int collectionNum = this->TimeSetsWithFilenameNumbers-> IsId(this->MeasuredTimeSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); } } // There can only be file sets if there are also time sets. if (this->UseFileSets) { fileSet = this->FileSets->IsId(this->MeasuredFileSet); numStepsList = (vtkIdList*)this->FileSetNumberOfSteps-> GetItemAsObject(fileSet); if (timeStep > numStepsList->GetId(0)) { numSteps = numStepsList->GetId(0); timeStepInFile -= numSteps; for (i = 1; i < numStepsList->GetNumberOfIds(); i++) { numSteps += numStepsList->GetId(i); if (timeStep > numSteps) { fileNum++; timeStepInFile -= numStepsList->GetId(i); } } } if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) { int collectionNum = this->FileSetsWithFilenameNumbers-> IsId(this->MeasuredFileSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(fileSet); filenameNum = filenameNumbers->GetId(fileNum-1); this->ReplaceWildcards(fileName, filenameNum); } } } } } if (!this->ReadMeasuredGeometryFile(fileName, timeStepInFile)) { vtkErrorMacro("error reading measured geometry file"); delete [] fileName; return; } delete [] fileName; } if (!this->CheckOutputConsistency()) { for (i = 0; i < this->NumberOfOutputs; i++) { this->GetOutput(i)->Initialize(); } return; } if ((this->NumberOfVariables + this->NumberOfComplexVariables) > 0) { if (!this->ReadVariableFiles()) { vtkErrorMacro("error reading variable files"); return; } } } //---------------------------------------------------------------------------- void vtkEnSightReader::Update() { vtkDebugMacro("In update");; int i; this->UpdateInformation(); this->UpdateData(0); for (i = 0; i < this->GetNumberOfOutputs(); i++) { if ( this->GetOutput(i) ) { this->GetOutput(i)->DataHasBeenGenerated(); } } } //---------------------------------------------------------------------------- void vtkEnSightReader::ExecuteInformation() { vtkDebugMacro("In execute information"); this->CaseFileRead = this->ReadCaseFile(); } //---------------------------------------------------------------------------- int vtkEnSightReader::ReadCaseFile() { char line[256], formatLine[256]; char subLine[256], subLine2[256]; int stringRead; int timeSet, fileSet, numTimeSteps, i, filenameNum, increment, lineRead; float timeStep; // Initialize // if (!this->CaseFileName) { vtkErrorMacro("A CaseFileName must be specified."); return 0; } if (this->FilePath) { strcpy(line, this->FilePath); strcat(line, this->CaseFileName); vtkDebugMacro("full path to case file: " << line); } else { strcpy(line, this->CaseFileName); } this->IS = new ifstream(line, ios::in); if (this->IS->fail()) { vtkErrorMacro("Unable to open file: " << line); delete this->IS; this->IS = NULL; return 0; } this->TimeSets->RemoveAllItems(); for (i = 0; i < this->NumberOfVariables; i++) { delete [] this->VariableFileNames[i]; this->VariableFileNames[i] = NULL; delete [] this->VariableDescriptions[i]; this->VariableDescriptions[i] = NULL; } delete [] this->VariableFileNames; this->VariableFileNames = NULL; delete [] this->VariableDescriptions; this->VariableDescriptions = NULL; delete [] this->VariableTypes; this->VariableTypes = NULL; for (i = 0; i < this->NumberOfComplexVariables; i++) { delete [] this->ComplexVariableFileNames[2*i]; this->ComplexVariableFileNames[2*i] = NULL; delete [] this->ComplexVariableFileNames[2*i+1]; this->ComplexVariableFileNames[2*i+1] = NULL; delete [] this->ComplexVariableDescriptions[i]; this->ComplexVariableDescriptions[i] = NULL; } delete [] this->ComplexVariableFileNames; this->ComplexVariableFileNames = NULL; delete [] this->ComplexVariableDescriptions; this->ComplexVariableDescriptions = NULL; delete [] this->ComplexVariableTypes; this->ComplexVariableTypes = NULL; this->NumberOfVariables = 0; this->NumberOfComplexVariables = 0; this->ReadNextDataLine(line); if (strncmp(line, "FORMAT", 6) == 0) { // found the FORMAT section vtkDebugMacro("*** FORMAT section"); this->ReadNextDataLine(line); stringRead = sscanf(line, " %*s %*s %s", subLine); if (stringRead == 1) { if (strcmp(subLine, "gold") == 0 && strcmp(this->GetClassName(), "vtkEnSight6Reader") == 0) { // The class is vtkEnSight6Reader, but the case file says "gold". vtkErrorMacro("This is not an EnSight6 file."); delete this->IS; this->IS = NULL; return 0; } } else { if (strcmp(this->GetClassName(), "vtkEnSightGoldReader") == 0) { // The class is vtkEnSightGoldReader, but the case file does // not say "gold". vtkErrorMacro("This is not an EnSight Gold file."); delete this->IS; this->IS = NULL; return 0; } } } // We know how many lines to read in the FORMAT section, so we haven't read // the "GEOMETRY" line yet. this->ReadNextDataLine(line); if (strncmp(line, "GEOMETRY", 8) == 0) { // found the GEOMETRY section vtkDebugMacro("*** GEOMETRY section"); // There will definitely be a "model" line. There may also be "measured" // and "match" lines. while(this->ReadNextDataLine(line) != 0 && strncmp(line, "m", 1) == 0) { if (strncmp(line, "model:", 6) == 0) { if (sscanf(line, " %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->GeometryTimeSet = timeSet; this->GeometryFileSet = fileSet; this->SetGeometryFileName(subLine); vtkDebugMacro(<<this->GetGeometryFileName()); } else if (sscanf(line, " %*s %d %s", &timeSet, subLine) == 2) { this->GeometryTimeSet = timeSet; this->SetGeometryFileName(subLine); vtkDebugMacro(<<this->GetGeometryFileName()); } else if (sscanf(line, " %*s %s", subLine) == 1) { this->SetGeometryFileName(subLine); vtkDebugMacro(<<this->GetGeometryFileName()); } } else if (strncmp(line, "measured:", 9) == 0) { if (sscanf(line, " %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->MeasuredTimeSet = timeSet; this->MeasuredFileSet = fileSet; this->SetMeasuredFileName(subLine); vtkDebugMacro(<< this->GetMeasuredFileName()); } else if (sscanf(line, " %*s %d %s", &timeSet, subLine) == 2) { this->MeasuredTimeSet = timeSet; this->SetMeasuredFileName(subLine); vtkDebugMacro(<< this->GetMeasuredFileName()); } else if (sscanf(line, " %*s %s", subLine) == 1) { this->SetMeasuredFileName(subLine); vtkDebugMacro(<< this->GetMeasuredFileName()); } } else if (strncmp(line, "match:", 6) == 0) { sscanf(line, " %*s %s", subLine); this->SetMatchFileName(subLine); vtkDebugMacro(<< this->GetMatchFileName()); } } } if (strncmp(line, "VARIABLE", 8) == 0) { // found the VARIABLE section vtkDebugMacro(<< "*** VARIABLE section"); while(this->ReadNextDataLine(line) != 0 && strncmp(line, "TIME", 4) != 0 && strncmp(line, "FILE", 4) != 0) { this->NumberOfScalarsPerNode = 0; this->NumberOfVectorsPerNode = 0; this->NumberOfTensorsSymmPerNode = 0; this->NumberOfScalarsPerElement = 0; this->NumberOfVectorsPerElement = 0; this->NumberOfTensorsSymmPerElement = 0; this->NumberOfScalarsPerMeasuredNode = 0; this->NumberOfVectorsPerMeasuredNode = 0; this->NumberOfComplexScalarsPerNode = 0; this->NumberOfComplexVectorsPerNode = 0; this->NumberOfComplexScalarsPerElement = 0; this->NumberOfComplexVectorsPerElement = 0; if (strncmp(line, "constant", 8) == 0) { vtkDebugMacro(<< line); } else if (strncmp(line, "scalar", 6) == 0) { sscanf(line, " %*s %*s %s", subLine); if (strcmp(subLine, "node:") == 0) { vtkDebugMacro("scalar per node"); this->VariableMode = vtkEnSightReader::SCALAR_PER_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %s", subLine); } this->NumberOfScalarsPerNode++; } else if (strcmp(subLine, "element:") == 0) { vtkDebugMacro("scalar per element"); this->VariableMode = vtkEnSightReader::SCALAR_PER_ELEMENT; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %s", subLine); } this->NumberOfScalarsPerElement++; } else if (strcmp(subLine, "measured") == 0) { vtkDebugMacro("scalar per measured node"); this->VariableMode = vtkEnSightReader::SCALAR_PER_MEASURED_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s", subLine); } this->NumberOfScalarsPerMeasuredNode++; } this->AddVariableFileName(subLine); this->NumberOfVariables++; } else if (strncmp(line, "vector", 6) == 0) { sscanf(line, " %*s %*s %s", subLine); if (strcmp(subLine, "node:") == 0) { vtkDebugMacro("vector per node"); this->VariableMode = vtkEnSightReader::VECTOR_PER_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %s", subLine); } this->NumberOfVectorsPerNode++; } else if (strcmp(subLine, "element:") == 0) { vtkDebugMacro("vector per element"); this->VariableMode = vtkEnSightReader::VECTOR_PER_ELEMENT; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %s", subLine); } this->NumberOfVectorsPerElement++; } else if (strcmp(subLine, "measured") == 0) { vtkDebugMacro("vector per measured node"); this->VariableMode = vtkEnSightReader::VECTOR_PER_MEASURED_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s", subLine); } this->NumberOfVectorsPerMeasuredNode++; } this->AddVariableFileName(subLine); this->NumberOfVariables++; } else if (strncmp(line, "tensor", 6) == 0) { sscanf(line, " %*s %*s %*s %s", subLine); if (strcmp(subLine, "node:") == 0) { vtkDebugMacro("tensor symm per node"); this->VariableMode = vtkEnSightReader::TENSOR_SYMM_PER_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s", subLine); } this->NumberOfTensorsSymmPerNode++; } else if (strcmp(subLine, "element:") == 0) { vtkDebugMacro("tensor symm per element"); this->VariableMode = vtkEnSightReader::TENSOR_SYMM_PER_ELEMENT; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->VariableTimeSetIds->InsertNextId(timeSet); this->VariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->VariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s", subLine); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->VariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s", subLine); } this->NumberOfTensorsSymmPerElement++; } this->AddVariableFileName(subLine); this->NumberOfVariables++; } else if (strncmp(line, "complex", 6) == 0) { sscanf(line, " %*s %s", subLine); if (strcmp(subLine, "scalar") == 0) { sscanf(line, " %*s %*s %*s %s", subLine); if (strcmp(subLine, "node:") == 0) { vtkDebugMacro("complex scalar per node"); this->VariableMode = vtkEnSightReader::COMPLEX_SCALAR_PER_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->ComplexVariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->ComplexVariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s %s", subLine, subLine2); } this->NumberOfComplexScalarsPerNode++; } else if (strcmp(subLine, "element:") == 0) { vtkDebugMacro("complex scalar per element"); this->VariableMode = vtkEnSightReader::COMPLEX_SCALAR_PER_ELEMENT; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->ComplexVariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->ComplexVariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s %s", subLine, subLine2); } this->NumberOfComplexScalarsPerElement++; } } else if (strcmp(subLine, "vector") == 0) { sscanf(line, " %*s %*s %*s %s", subLine); if (strcmp(subLine, "node:") == 0) { vtkDebugMacro("complex vector per node"); this->VariableMode = vtkEnSightReader::COMPLEX_VECTOR_PER_NODE; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->ComplexVariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->ComplexVariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s %s", subLine, subLine2); } this->NumberOfComplexVectorsPerNode++; } else if (strcmp(subLine, "element:") == 0) { vtkDebugMacro("complex vector per element"); this->VariableMode = vtkEnSightReader::COMPLEX_VECTOR_PER_ELEMENT; this->AddVariableType(); if (sscanf(line, " %*s %*s %*s %*s %d %d %s", &timeSet, &fileSet, subLine) == 3) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->ComplexVariableFileSetIds->InsertNextId(fileSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %d %s", &timeSet, subLine) == 2) { this->ComplexVariableTimeSetIds->InsertNextId(timeSet); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*d %*s %s %s", subLine, subLine2); } else if (sscanf(line, " %*s %*s %*s %*s %s", subLine) == 1) { this->ComplexVariableTimeSetIds->InsertNextId(1); this->AddVariableDescription(subLine); sscanf(line, " %*s %*s %*s %*s %*s %s %s", subLine, subLine2); } this->NumberOfComplexVectorsPerElement++; } } this->AddVariableFileName(subLine, subLine2); this->NumberOfComplexVariables++; } else { vtkErrorMacro("invalid VARIABLE line: " << line); delete this->IS; this->IS = NULL; return 0; } } } if (strncmp(line, "TIME", 4) == 0) { // found TIME section int firstTimeStep = 1; this->UseTimeSetsOn(); while(this->ReadNextDataLine(line) != 0 && strncmp(line, "FILE", 4) != 0) { sscanf(line, "%*s %*s %d", &timeSet); this->TimeSetIds->InsertNextId(timeSet); this->ReadNextDataLine(line); sscanf(line, "%*s %*s %*s %d", &numTimeSteps); this->ReadNextDataLine(line); if (strncmp(line, "filename", 8) == 0) { vtkIdList *filenameNumbers = vtkIdList::New(); this->TimeSetsWithFilenameNumbers->InsertNextId(timeSet); sscanf(line, "%*s %s", subLine); if (strncmp(subLine, "numbers", 7) == 0) { strcpy(formatLine, "%*s %*s"); strcpy(subLine, "%*s %*s"); for (i = 0; i < numTimeSteps; i++) { strcat(formatLine, " %d"); sscanf(line, formatLine, &filenameNum); filenameNumbers->InsertNextId(filenameNum); strcat(subLine, " %*d"); strcpy(formatLine, subLine); } } else { sscanf(line, "%*s %*s %*s %d", &filenameNum); this->ReadNextDataLine(line); sscanf(line, "%*s %*s %d", &increment); for (i = 0; i < numTimeSteps; i++) { filenameNumbers->InsertNextId(filenameNum + i*increment); } } this->TimeSetFileNameNumbers->AddItem(filenameNumbers); filenameNumbers->Delete(); filenameNumbers = NULL; this->ReadLine(line); } vtkFloatArray *timeValues = vtkFloatArray::New(); timeValues->SetNumberOfComponents(1); timeValues->SetNumberOfTuples(numTimeSteps); strcpy(formatLine, "%*s %*s"); strcpy(subLine, "%*s %*s"); for (i = 0; i < numTimeSteps; i++) { strcat(formatLine, " %f"); if (sscanf(line, formatLine, &timeStep) != 1) { this->ReadNextDataLine(line); strcpy(formatLine, " %f"); strcpy(subLine, ""); sscanf(line, formatLine, &timeStep); } if (firstTimeStep) { this->MinimumTimeValue = timeStep; this->MaximumTimeValue = timeStep; firstTimeStep = 0; } else { if (timeStep < this->MinimumTimeValue) { this->MinimumTimeValue = timeStep; } else if (timeStep > this->MaximumTimeValue) { this->MaximumTimeValue = timeStep; } } timeValues->SetComponent(i, 0, timeStep); strcat(subLine, " %*f"); strcpy(formatLine, subLine); } this->TimeSets->AddItem(timeValues); timeValues->Delete(); timeValues = NULL; } } if (strncmp(line, "FILE", 4) == 0) { // found FILE section this->UseFileSetsOn(); lineRead = this->ReadNextDataLine(line); while (lineRead != 0) { vtkIdList *filenameNums = vtkIdList::New(); vtkIdList *numSteps = vtkIdList::New(); sscanf(line, "%*s %*s %d", &fileSet); this->FileSets->InsertNextId(fileSet); lineRead = this->ReadNextDataLine(line); if (strncmp(line, "filename", 8) == 0) { this->FileSetsWithFilenameNumbers->InsertNextId(fileSet); while (lineRead != 0 && strncmp(line, "filename", 8) == 0) { sscanf(line, "%*s %*s %d", &filenameNum); filenameNums->InsertNextId(filenameNum); this->ReadNextDataLine(line); sscanf(line, "%*s %*s %*s %d", &numTimeSteps); numSteps->InsertNextId(numTimeSteps); lineRead = this->ReadNextDataLine(line); } this->FileSetFileNameNumbers->AddItem(filenameNums); } else { sscanf(line, "%*s %*s %*s %d", &numTimeSteps); numSteps->InsertNextId(numTimeSteps); lineRead = this->ReadNextDataLine(line); } this->FileSetNumberOfSteps->AddItem(numSteps); filenameNums->Delete(); filenameNums = NULL; numSteps->Delete(); numSteps = NULL; } } delete this->IS; this->IS = NULL; return 1; } //---------------------------------------------------------------------------- int vtkEnSightReader::ReadVariableFiles() { int i, j; char description[256]; int timeSet, fileSet, timeStep, timeStepInFile, numSteps; vtkDataArray *times; float newTime; vtkIdList *numStepsList, *filenameNumbers; int validTime, fileNum, filenameNum; char* fileName, *fileName2; for (i = 0; i < this->NumberOfVariables; i++) { timeStep = 0; timeStepInFile = 1; fileNum = 1; validTime = 1; fileName = new char[strlen(this->VariableFileNames[i]) + 1]; strcpy(fileName, this->VariableFileNames[i]); if (this->UseTimeSets) { validTime = 0; timeSet = this->VariableTimeSetIds->GetId(i); times = this->TimeSets->GetItem(this->TimeSetIds->IsId(timeSet)); for (j = 0; j < times->GetNumberOfTuples(); j++) { newTime = times->GetComponent(j, 0); if (newTime <= this->TimeValue) { timeStep++; if (this->VariableTypes[i] == SCALAR_PER_MEASURED_NODE || this->VariableTypes[i] == VECTOR_PER_MEASURED_NODE) { if (newTime >= this->MeasuredTimeValue || this->MeasuredTimeSet == -1) { validTime = 1; } } else if (newTime >= this->GeometryTimeValue || this->GeometryTimeSet == -1) { validTime = 1; } } } if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0 && validTime) { int collectionNum = this->TimeSetsWithFilenameNumbers->IsId(timeSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); } } // There can only be file sets if there are also time sets. if (this->UseFileSets) { timeStepInFile = timeStep; fileSet = this->VariableFileSetIds->GetId(i); numStepsList = (vtkIdList*)this->FileSetNumberOfSteps-> GetItemAsObject(this->FileSets->IsId(fileSet)); if (timeStep > numStepsList->GetId(0)) { numSteps = numStepsList->GetId(0); timeStepInFile -= numSteps; for (i = 1; i < numStepsList->GetNumberOfIds(); i++) { numSteps += numStepsList->GetId(i); if (timeStep > numSteps) { fileNum++; timeStepInFile -= numStepsList->GetId(i); } } } if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0 && validTime) { int collectionNum = this->FileSetsWithFilenameNumbers->IsId(fileSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); } } } } if (validTime) { switch (this->VariableTypes[i]) { case vtkEnSightReader::SCALAR_PER_NODE: this->ReadScalarsPerNode(fileName, this->VariableDescriptions[i], timeStepInFile); break; case vtkEnSightReader::SCALAR_PER_MEASURED_NODE: this->ReadScalarsPerNode(fileName, this->VariableDescriptions[i], timeStepInFile, 1); break; case vtkEnSightReader::VECTOR_PER_NODE: this->ReadVectorsPerNode(fileName, this->VariableDescriptions[i], timeStepInFile); break; case vtkEnSightReader::VECTOR_PER_MEASURED_NODE: this->ReadVectorsPerNode(fileName, this->VariableDescriptions[i], timeStepInFile, 1); break; case vtkEnSightReader::TENSOR_SYMM_PER_NODE: this->ReadTensorsPerNode(fileName, this->VariableDescriptions[i], timeStepInFile); break; case vtkEnSightReader::SCALAR_PER_ELEMENT: this->ReadScalarsPerElement(fileName, this->VariableDescriptions[i], timeStepInFile); break; case vtkEnSightReader::VECTOR_PER_ELEMENT: this->ReadVectorsPerElement(fileName, this->VariableDescriptions[i], timeStepInFile); break; case vtkEnSightReader::TENSOR_SYMM_PER_ELEMENT: this->ReadTensorsPerElement(fileName, this->VariableDescriptions[i], timeStepInFile); break; } } delete [] fileName; } for (i = 0; i < this->NumberOfComplexVariables; i++) { timeStep = 0; timeStepInFile = 1; fileNum = 1; validTime = 1; fileName = new char[strlen(this->ComplexVariableFileNames[2*i]) + 1]; strcpy(fileName, this->ComplexVariableFileNames[2*i]); fileName2 = new char[strlen(this->ComplexVariableFileNames[2*i+1]) + 1]; strcpy(fileName2, this->ComplexVariableFileNames[2*i+1]); if (this->UseTimeSets) { validTime = 0; timeSet = this->VariableTimeSetIds->GetId(i); times = this->TimeSets->GetItem(this->TimeSetIds->IsId(timeSet)); for (j = 0; j < times->GetNumberOfTuples(); j++) { newTime = times->GetComponent(j, 0); if (newTime <= this->TimeValue) { timeStep++; if (this->VariableTypes[i] == SCALAR_PER_MEASURED_NODE || this->VariableTypes[i] == VECTOR_PER_MEASURED_NODE) { if (newTime >= this->MeasuredTimeValue) { validTime = 1; } } else if (newTime >= this->GeometryTimeValue) { validTime = 1; } } } if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0 && validTime) { int collectionNum = this->TimeSetsWithFilenameNumbers->IsId(timeSet); if (collectionNum > -1) { filenameNumbers = this->TimeSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); this->ReplaceWildcards(fileName2, filenameNum); } } // There can only be file sets if there are also time sets. if (this->UseFileSets) { timeStepInFile = timeStep; fileSet = this->VariableFileSetIds->GetId(i); numStepsList = (vtkIdList*)this->FileSetNumberOfSteps-> GetItemAsObject(this->FileSets->IsId(fileSet)); if (timeStep > numStepsList->GetId(0)) { numSteps = numStepsList->GetId(0); timeStepInFile -= numSteps; for (i = 1; i < numStepsList->GetNumberOfIds(); i++) { numSteps += numStepsList->GetId(i); if (timeStep > numSteps) { fileNum++; timeStepInFile -= numStepsList->GetId(i); } } } if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0 && validTime) { int collectionNum = this->FileSetsWithFilenameNumbers->IsId(fileSet); if (collectionNum > -1) { filenameNumbers = this->FileSetFileNameNumbers-> GetItem(collectionNum); filenameNum = filenameNumbers->GetId(timeStep-1); this->ReplaceWildcards(fileName, filenameNum); this->ReplaceWildcards(fileName2, filenameNum); } } } } if (validTime) { switch (this->ComplexVariableTypes[i]) { case vtkEnSightReader::COMPLEX_SCALAR_PER_NODE: this->ReadScalarsPerNode(fileName, this->ComplexVariableDescriptions[i], timeStepInFile, 0, 2); this->ReadScalarsPerNode(fileName2, this->ComplexVariableDescriptions[i], timeStepInFile, 0, 2, 1); break; case vtkEnSightReader::COMPLEX_VECTOR_PER_NODE: strcpy(description, this->ComplexVariableDescriptions[i]); strcat(description, "_r"); this->ReadVectorsPerNode(fileName, description, timeStepInFile); strcpy(description, this->ComplexVariableDescriptions[i]); strcat(description, "_i"); this->ReadVectorsPerNode(fileName2, description, timeStepInFile); break; case vtkEnSightReader::COMPLEX_SCALAR_PER_ELEMENT: this->ReadScalarsPerElement(fileName, this->ComplexVariableDescriptions[i], timeStepInFile, 2); this->ReadScalarsPerElement(fileName2, this->ComplexVariableDescriptions[i], timeStepInFile, 2, 1); break; case vtkEnSightReader::COMPLEX_VECTOR_PER_ELEMENT: strcpy(description, this->ComplexVariableDescriptions[i]); strcat(description, "_r"); this->ReadVectorsPerElement(fileName, description, timeStepInFile); strcpy(description, this->ComplexVariableDescriptions[i]); strcat(description, "_i"); this->ReadVectorsPerElement(fileName2, description, timeStepInFile); break; } } delete [] fileName; delete [] fileName2; } return 1; } //---------------------------------------------------------------------------- void vtkEnSightReader::AddVariableFileName(char* fileName1, char* fileName2) { int size; int i; if (this->VariableMode < 8) { size = this->NumberOfVariables; char** newFileNameList = new char *[size]; // temporary array // copy file names to temporary array for (i = 0; i < size; i++) { newFileNameList[i] = new char[strlen(this->VariableFileNames[i]) + 1]; strcpy(newFileNameList[i], this->VariableFileNames[i]); delete [] this->VariableFileNames[i]; } delete [] this->VariableFileNames; // make room for new file name this->VariableFileNames = new char *[size+1]; // copy existing file names back to first array for (i = 0; i < size; i++) { this->VariableFileNames[i] = new char[strlen(newFileNameList[i]) + 1]; strcpy(this->VariableFileNames[i], newFileNameList[i]); delete [] newFileNameList[i]; } delete [] newFileNameList; // add new file name at end of first array this->VariableFileNames[size] = new char[strlen(fileName1) + 1]; strcpy(this->VariableFileNames[size], fileName1); vtkDebugMacro( << "file name: " << this->VariableFileNames[size]); } else { size = this->NumberOfComplexVariables; char** newFileNameList = new char *[2 * size]; // temporary array // copy file names to temporary array for (i = 0; i < 2*size; i++) { newFileNameList[i] = new char[strlen(this->ComplexVariableFileNames[i]) + 1]; strcpy(newFileNameList[i], this->ComplexVariableFileNames[i]); delete [] this->ComplexVariableFileNames[i]; } delete [] this->ComplexVariableFileNames; // make room for new file name this->ComplexVariableFileNames = new char *[2*(size+1)]; // copy existing file names back to first array for (i = 0; i < 2*size; i++) { this->ComplexVariableFileNames[i] = new char[strlen(newFileNameList[i]) + 1]; strcpy(this->ComplexVariableFileNames[i], newFileNameList[i]); delete [] newFileNameList[i]; } delete [] newFileNameList; // add new file name at end of first array this->ComplexVariableFileNames[2*size] = new char[strlen(fileName1) + 1]; strcpy(this->ComplexVariableFileNames[2*size], fileName1); vtkDebugMacro("real file name: " << this->ComplexVariableFileNames[2*size]); this->ComplexVariableFileNames[2*size+1] = new char[strlen(fileName2) + 1]; strcpy(this->ComplexVariableFileNames[2*size+1], fileName2); vtkDebugMacro("imag. file name: " << this->ComplexVariableFileNames[2*size+1]); } } //---------------------------------------------------------------------------- void vtkEnSightReader::AddVariableDescription(char* description) { int size; int i; if (this->VariableMode < 8) { size = this->NumberOfVariables; char ** newDescriptionList = new char *[size]; // temporary array // copy descriptions to temporary array for (i = 0; i < size; i++) { newDescriptionList[i] = new char[strlen(this->VariableDescriptions[i]) + 1]; strcpy(newDescriptionList[i], this->VariableDescriptions[i]); delete [] this->VariableDescriptions[i]; } delete [] this->VariableDescriptions; // make room for new description this->VariableDescriptions = new char *[size+1]; // copy existing descriptions back to first array for (i = 0; i < size; i++) { this->VariableDescriptions[i] = new char[strlen(newDescriptionList[i]) + 1]; strcpy(this->VariableDescriptions[i], newDescriptionList[i]); delete [] newDescriptionList[i]; } delete [] newDescriptionList; // add new description at end of first array this->VariableDescriptions[size] = new char[strlen(description) + 1]; strcpy(this->VariableDescriptions[size], description); vtkDebugMacro("description: " << this->VariableDescriptions[size]); } else { size = this->NumberOfComplexVariables; char ** newDescriptionList = new char *[size]; // temporary array // copy descriptions to temporary array for (i = 0; i < size; i++) { newDescriptionList[i] = new char[strlen(this->ComplexVariableDescriptions[i]) + 1]; strcpy(newDescriptionList[i], this->ComplexVariableDescriptions[i]); delete [] this->ComplexVariableDescriptions[i]; } delete [] this->ComplexVariableDescriptions; // make room for new description this->ComplexVariableDescriptions = new char *[size+1]; // copy existing descriptions back to first array for (i = 0; i < size; i++) { this->ComplexVariableDescriptions[i] = new char[strlen(newDescriptionList[i]) + 1]; strcpy(this->ComplexVariableDescriptions[i], newDescriptionList[i]); delete [] newDescriptionList[i]; } delete [] newDescriptionList; // add new description at end of first array this->ComplexVariableDescriptions[size] = new char[strlen(description) + 1]; strcpy(this->ComplexVariableDescriptions[size], description); vtkDebugMacro("description: " << this->ComplexVariableDescriptions[size]); } } //---------------------------------------------------------------------------- void vtkEnSightReader::AddVariableType() { int size; int i; int *types = NULL; // Figure out what the size of the variable type array is. if (this->VariableMode < 8) { size = this->NumberOfVariables; types = new int[size]; for (i = 0; i < size; i++) { types[i] = this->VariableTypes[i]; } delete [] this->VariableTypes; this->VariableTypes = new int[size+1]; for (i = 0; i < size; i++) { this->VariableTypes[i] = types[i]; } delete [] types; this->VariableTypes[size] = this->VariableMode; vtkDebugMacro("variable type: " << this->VariableTypes[size]); } else { size = this->NumberOfComplexVariables; if (size > 0) { types = new int[size]; for (i = 0; i < size; i++) { types[i] = this->ComplexVariableTypes[i]; } delete [] this->ComplexVariableTypes; } this->ComplexVariableTypes = new int[size+1]; for (i = 0; i < size; i++) { this->ComplexVariableTypes[i] = types[i]; } if (size > 0) { delete [] types; } this->ComplexVariableTypes[size] = this->VariableMode; vtkDebugMacro("complex variable type: " << this->ComplexVariableTypes[size]); } } int vtkEnSightReader::GetElementType(char* line) { if (strncmp(line, "point", 5) == 0) { return vtkEnSightReader::POINT; } else if (strncmp(line, "bar2", 4) == 0) { return vtkEnSightReader::BAR2; } else if (strncmp(line, "bar3", 4) == 0) { return vtkEnSightReader::BAR3; } else if (strncmp(line, "nsided", 6) == 0) { return vtkEnSightReader::NSIDED; } else if (strncmp(line, "tria3", 5) == 0) { return vtkEnSightReader::TRIA3; } else if (strncmp(line, "tria6", 5) == 0) { return vtkEnSightReader::TRIA6; } else if (strncmp(line, "quad4", 5) == 0) { return vtkEnSightReader::QUAD4; } else if (strncmp(line, "quad8", 5) == 0) { return vtkEnSightReader::QUAD8; } else if (strncmp(line, "tetra4", 6) == 0) { return vtkEnSightReader::TETRA4; } else if (strncmp(line, "tetra10", 7) == 0) { return vtkEnSightReader::TETRA10; } else if (strncmp(line, "pyramid5", 8) == 0) { return vtkEnSightReader::PYRAMID5; } else if (strncmp(line, "pyramid13", 9) == 0) { return vtkEnSightReader::PYRAMID13; } else if (strncmp(line, "hexa8", 5) == 0) { return vtkEnSightReader::HEXA8; } else if (strncmp(line, "hexa20", 6) == 0) { return vtkEnSightReader::HEXA20; } else if (strncmp(line, "penta6", 6) == 0) { return vtkEnSightReader::PENTA6; } else if (strncmp(line, "penta15", 7) == 0) { return vtkEnSightReader::PENTA15; } else { return -1; } } void vtkEnSightReader::ReplaceWildcards(char* filename, int num) { int wildcardPos, numWildcards, numDigits = 1, i; int tmpNum = num, multTen = 1; char newChar; int newNum; wildcardPos = static_cast<int>(strcspn(filename, "*")); numWildcards = static_cast<int>(strspn(filename + wildcardPos, "*")); if (numWildcards == 0) { return; } tmpNum /= 10; while (tmpNum >= 1) { numDigits++; multTen *= 10; tmpNum /= 10; } for (i = 0; i < numWildcards - numDigits; i++) { filename[i + wildcardPos] = '0'; } tmpNum = num; for (i = numWildcards - numDigits; i < numWildcards; i++) { newNum = tmpNum / multTen; switch (newNum) { case 0: newChar = '0'; break; case 1: newChar = '1'; break; case 2: newChar = '2'; break; case 3: newChar = '3'; break; case 4: newChar = '4'; break; case 5: newChar = '5'; break; case 6: newChar = '6'; break; case 7: newChar = '7'; break; case 8: newChar = '8'; break; case 9: newChar = '9'; break; default: // This case should never be reached. return; } filename[i + wildcardPos] = newChar; tmpNum -= multTen * newNum; multTen /= 10; } } //---------------------------------------------------------------------------- // Called by constructor to set up output array. void vtkEnSightReader::SetNumberOfOutputsInternal(int num) { int idx; vtkDataObject **outputs; // in case nothing has changed. if (num == this->NumberOfOutputs) { return; } // Allocate new arrays. outputs = new vtkDataObject *[num]; // Initialize with NULLs. for (idx = 0; idx < num; ++idx) { outputs[idx] = NULL; } // Copy old outputs for (idx = 0; idx < num && idx < this->NumberOfOutputs; ++idx) { outputs[idx] = this->Outputs[idx]; } // delete the previous arrays if (this->Outputs) { delete [] this->Outputs; this->Outputs = NULL; this->NumberOfOutputs = 0; } // Set the new arrays this->Outputs = outputs; this->NumberOfOutputs = num; } //---------------------------------------------------------------------------- void vtkEnSightReader::ReplaceNthOutput(int idx, vtkDataObject* newOutput) { vtkDataObject *oldOutput; if (idx < 0) { vtkErrorMacro(<< "SetNthOutput: " << idx << ", cannot set output. "); return; } // Expand array if necessary. if (idx >= this->NumberOfOutputs) { this->SetNumberOfOutputsInternal(idx + 1); } // does this change anything? oldOutput = this->Outputs[idx]; if (newOutput == oldOutput) { return; } if ( !newOutput->IsA(oldOutput->GetClassName()) ) { vtkErrorMacro("Can not replace the output with a different type."); return; } if (newOutput) { vtkSource *newOutputOldSource = newOutput->GetSource(); if (newOutputOldSource) { vtkErrorMacro("The new output can not have a source."); return; } } // disconnect first existing source-output relationship. if (oldOutput) { oldOutput->SetSource(NULL); oldOutput->UnRegister(this); this->Outputs[idx] = NULL; } if (newOutput) { // Register the newOutput so it does not get deleted. // Don't set the link yet until previous links is disconnected. newOutput->Register(this); newOutput->SetSource(this); } // now actually make the link that was registered previously. this->Outputs[idx] = newOutput; } int vtkEnSightReader::CheckOutputConsistency() { if (this->NumberOfOutputs > this->NumberOfNewOutputs && ! this->InitialRead) { vtkErrorMacro("Cannot decrease number of outputs after initial read"); this->OutputsAreValid = 0; } if (this->InitialRead) { this->InitialRead = 0; } return this->OutputsAreValid; } //---------------------------------------------------------------------------- void vtkEnSightReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "CaseFileName: " << (this->CaseFileName ? this->CaseFileName : "(none)") << endl; os << indent << "FilePath: " << (this->FilePath ? this->FilePath : "(none)") << endl; os << indent << "NumberOfComplexScalarsPerNode: " << this->NumberOfComplexScalarsPerNode << endl; os << indent << "NumberOfVectorsPerElement :" << this->NumberOfVectorsPerElement << endl; os << indent << "NumberOfTensorsSymmPerElement: " << this->NumberOfTensorsSymmPerElement << endl; os << indent << "NumberOfComplexVectorsPerNode: " << this->NumberOfComplexVectorsPerNode << endl; os << indent << "NumberOfScalarsPerElement: " << this->NumberOfScalarsPerElement << endl; os << indent << "NumberOfComplexVectorsPerElement: " << this->NumberOfComplexVectorsPerElement << endl; os << indent << "NumberOfComplexScalarsPerElement: " << this->NumberOfComplexScalarsPerElement << endl; os << indent << "NumberOfTensorsSymmPerNode: " << this->NumberOfTensorsSymmPerNode << endl; os << indent << "NumberOfScalarsPerMeasuredNode: " << this->NumberOfScalarsPerMeasuredNode << endl; os << indent << "NumberOfVectorsPerMeasuredNode: " << this->NumberOfVectorsPerMeasuredNode << endl; os << indent << "NumberOfScalarsPerNode: " << this->NumberOfScalarsPerNode << endl; os << indent << "NumberOfVectorsPerNode: " << this->NumberOfVectorsPerNode << endl; os << indent << "TimeValue: " << this->TimeValue << endl; os << indent << "MinimumTimeValue: " << this->MinimumTimeValue << endl; os << indent << "MaximumTimeValue: " << this->MaximumTimeValue << endl; os << indent << "TimeSets: " << this->TimeSets << endl; }
#include "dx_render_device.h" #include "window.h" #include <cassert> namespace toy { // Order-dependent on VertexDescription enum const unsigned VertexDescription::element_size[VertexDescription::EF_COUNT] = { sizeof(float) * 4, sizeof(float) * 3, sizeof(float) * 2, sizeof(float) }; DXRenderDevice::DXRenderDevice() : _n_constant_buffers(0) , _n_vertex_buffers(0) , _n_index_buffers(0) , _n_input_layouts(0) , _n_vertex_shaders(0) , _n_pixel_shaders(0) , _n_dst_states(0) , _n_rasterizer_states(0) , _n_blend_states(0) , _n_texture_srvs(0) , _n_sampler_states(0) {} bool DXRenderDevice::init(const Window& window) { ComPtr<IDXGIFactory> dxgi_factory; HRESULT hr = ::CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgi_factory)); if (FAILED(hr)) { return false; } ComPtr<IDXGIAdapter> adapter; // TODO: adapter index option hr = dxgi_factory->EnumAdapters(0, &adapter); if (FAILED(hr)) { return false; } DXGI_SWAP_CHAIN_DESC swapchain_description; swapchain_description.BufferDesc.Width = 0; swapchain_description.BufferDesc.Height = 0; // TODO: sRGB option swapchain_description.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapchain_description.BufferDesc.RefreshRate.Numerator = 60; swapchain_description.BufferDesc.RefreshRate.Denominator = 1; // TODO: MSAA options swapchain_description.SampleDesc.Count = 1; swapchain_description.SampleDesc.Quality = 0; swapchain_description.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapchain_description.BufferCount = 2; swapchain_description.OutputWindow = window.handle(); swapchain_description.Windowed = true; swapchain_description.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapchain_description.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; const D3D_FEATURE_LEVEL feature_levels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; const unsigned n_feature_levels = sizeof(feature_levels) / sizeof(feature_levels[0]); D3D_FEATURE_LEVEL current_feature_level; hr = D3D11CreateDeviceAndSwapChain( adapter.get(), D3D_DRIVER_TYPE_UNKNOWN, 0, #ifdef _DEBUG D3D11_CREATE_DEVICE_DEBUG, #else 0, #endif feature_levels, n_feature_levels, D3D11_SDK_VERSION, &swapchain_description, &_swap_chain, &_device, &current_feature_level, &_immediate_device); if (FAILED(hr)) { return false; } return create_back_buffer_and_dst(); } bool DXRenderDevice::create_back_buffer_and_dst() { HRESULT hr = _swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&_back_buffer)); if (FAILED(hr)) { return false; } D3D11_TEXTURE2D_DESC back_buffer_description; _back_buffer->GetDesc(&back_buffer_description); D3D11_RENDER_TARGET_VIEW_DESC rtv_description; // TODO: MSAA support rtv_description.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtv_description.Texture2DArray.MipSlice = 0; rtv_description.Texture2DArray.ArraySize = 1; rtv_description.Format = back_buffer_description.Format; hr = _device->CreateRenderTargetView(_back_buffer.get(), &rtv_description, &_back_buffer_rtv); if (FAILED(hr)) { return false; } D3D11_TEXTURE2D_DESC dst_description; dst_description.Width = back_buffer_description.Width; dst_description.Height = back_buffer_description.Height; dst_description.MipLevels = 1; dst_description.ArraySize = 1; dst_description.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; dst_description.SampleDesc.Count = 1; dst_description.SampleDesc.Quality = 0; dst_description.Usage = D3D11_USAGE_DEFAULT; dst_description.BindFlags = D3D11_BIND_DEPTH_STENCIL; dst_description.CPUAccessFlags = 0; dst_description.MiscFlags = 0; hr = _device->CreateTexture2D(&dst_description, 0, &_depth_stencil); if (FAILED(hr)) { return false; } hr = _device->CreateDepthStencilView(_depth_stencil.get(), 0, &_depth_stencil_view); if (FAILED(hr)) { return false; } return true; } unsigned DXRenderDevice::create_constant_buffer(const size_t size) { assert(_n_constant_buffers < MAX_CONSTANT_BUFFERS); D3D11_BUFFER_DESC buffer_description; buffer_description.Usage = D3D11_USAGE_DYNAMIC; buffer_description.ByteWidth = size; buffer_description.BindFlags = D3D11_BIND_CONSTANT_BUFFER; buffer_description.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; buffer_description.MiscFlags = 0; buffer_description.StructureByteStride = 0; HRESULT hr = _device->CreateBuffer(&buffer_description, 0, &_constant_buffers[_n_constant_buffers]); if (FAILED(hr)) { return MAX_CONSTANT_BUFFERS + 1; } _n_constant_buffers++; return _n_constant_buffers - 1; } void DXRenderDevice::update_constant_buffer(const unsigned id, const void* const data, const size_t size) { assert(id < _n_constant_buffers); assert(data != nullptr); assert(size > 0); D3D11_MAPPED_SUBRESOURCE resource; HRESULT hr = _immediate_device->Map(_constant_buffers[id].get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &resource); if (FAILED(hr)) { return; } memcpy(resource.pData, data, size); _immediate_device->Unmap(_constant_buffers[id].get(), 0); } unsigned DXRenderDevice::create_static_vertex_buffer(const void* const data, const size_t size) { assert(_n_vertex_buffers < MAX_VERTEX_BUFFERS); D3D11_BUFFER_DESC buffer_description; buffer_description.Usage = D3D11_USAGE_IMMUTABLE; buffer_description.ByteWidth = size; buffer_description.BindFlags = D3D11_BIND_VERTEX_BUFFER; buffer_description.CPUAccessFlags = 0; buffer_description.MiscFlags = 0; buffer_description.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA resource; resource.SysMemPitch = 0; resource.SysMemSlicePitch = 0; resource.pSysMem = data; HRESULT hr = _device->CreateBuffer(&buffer_description, &resource, &_vertex_buffers[_n_vertex_buffers]); if (FAILED(hr)) { return MAX_VERTEX_BUFFERS + 1; } _n_vertex_buffers++; return _n_vertex_buffers - 1; } unsigned DXRenderDevice::create_static_index_buffer(const void* const data, const size_t size) { assert(_n_index_buffers < MAX_INDEX_BUFFERS); D3D11_BUFFER_DESC buffer_description; buffer_description.Usage = D3D11_USAGE_IMMUTABLE; buffer_description.ByteWidth = size; buffer_description.BindFlags = D3D11_BIND_INDEX_BUFFER; buffer_description.CPUAccessFlags = 0; buffer_description.MiscFlags = 0; buffer_description.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA resource; resource.SysMemPitch = 0; resource.SysMemSlicePitch = 0; resource.pSysMem = data; HRESULT hr = _device->CreateBuffer(&buffer_description, &resource, &_index_buffers[_n_index_buffers]); if (FAILED(hr)) { return MAX_INDEX_BUFFERS + 1; } _n_index_buffers++; return _n_index_buffers - 1; } unsigned DXRenderDevice::create_input_layout(const VertexDescription& description, ComPtr<ID3D10Blob>& vs_blob) { assert(_n_input_layouts < MAX_INPUT_LAYOUTS); assert(description.n_elements > 0); // Order-dependent on VertexDescription enum static const char* semantics[] = { "POSITION", "NORMAL", "TEXCOORD", "COLOR" }; // Order-dependent on VertexDescription enum, too static const DXGI_FORMAT formats[] = { DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32_FLOAT, }; D3D11_INPUT_ELEMENT_DESC layout[VertexDescription::MAX_ELEMENTS]; unsigned size = 0; for (unsigned i = 0; i < description.n_elements; ++i) { assert(description.elements[i].semantic < VertexDescription::ES_COUNT); assert(description.elements[i].semantic < VertexDescription::EF_COUNT); layout[i].SemanticName = semantics[description.elements[i].semantic]; layout[i].SemanticIndex = 0; layout[i].Format = formats[description.elements[i].format]; layout[i].InputSlot = 0; layout[i].AlignedByteOffset = size; layout[i].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; layout[i].InstanceDataStepRate = 0; size += VertexDescription::element_size[description.elements[i].format]; } HRESULT hr = _device->CreateInputLayout( layout, description.n_elements, vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &_input_layouts[_n_input_layouts]); if (FAILED(hr)) { return MAX_INPUT_LAYOUTS + 1; } _n_input_layouts++; return _n_input_layouts - 1; } unsigned DXRenderDevice::create_vertex_shader(const char* const code, const size_t length, const VertexDescription& vertex_description) { assert(code != nullptr); assert(length > 0); ComPtr<ID3DBlob> vs_blob; HRESULT hr = D3DX11CompileFromMemory(code, length, 0, 0, 0, "vs_main", "vs_4_0", 0, 0, 0, &vs_blob, 0, 0); if (FAILED(hr)) { return MAX_VERTEX_SHADERS + 1; } hr = _device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), 0, &_vertex_shaders[_n_vertex_shaders]); if (FAILED(hr)) { return MAX_VERTEX_SHADERS + 1; } _vertex_shader_il[_n_vertex_shaders] = create_input_layout(vertex_description, vs_blob); _n_vertex_shaders++; return _n_vertex_shaders - 1; } unsigned DXRenderDevice::create_pixel_shader(const char* const code, const size_t length) { assert(code != nullptr); assert(length > 0); if (!compile_pixel_shader(code, length, _pixel_shaders[_n_pixel_shaders])) { return MAX_PIXEL_SHADERS + 1; } _n_pixel_shaders++; return _n_pixel_shaders - 1; } void DXRenderDevice::update_pixel_shader(const unsigned shader, const char* const code, const size_t length) { assert(shader < _n_pixel_shaders); assert(code != nullptr); assert(length > 0); if (!compile_pixel_shader(code, length, _pixel_shaders[shader])) { // TODO: report errors somehow } } bool DXRenderDevice::compile_pixel_shader(const char* const code, const size_t length, ComPtr<ID3D11PixelShader>& destination) { ComPtr<ID3DBlob> ps_blob; ComPtr<ID3DBlob> error_blob; HRESULT hr = D3DX11CompileFromMemory(code, length, 0, 0, 0, "ps_main", "ps_4_0", 0, 0, 0, &ps_blob, &error_blob, 0); if (FAILED(hr)) { // TODO: remove this crap const char* const msg = static_cast<char*>(error_blob->GetBufferPointer()); ::MessageBoxA(0, msg, "PS compilation error", MB_ICONASTERISK); return false; } ID3D11PixelShader* ps = nullptr; hr = _device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), 0, &ps); if (FAILED(hr)) { return false; } destination.set(ps); return true; } unsigned DXRenderDevice::create_dst_state(const bool depth_enabled) { assert(_n_dst_states < MAX_DST_STATES); CD3D11_DEPTH_STENCIL_DESC dst_description(D3D11_DEFAULT); dst_description.DepthEnable = depth_enabled; HRESULT hr = _device->CreateDepthStencilState(&dst_description, &_dst_states[_n_dst_states]); if (FAILED(hr)) { return MAX_DST_STATES + 1; } _n_dst_states++; return _n_dst_states - 1; } unsigned DXRenderDevice::create_rasterizer_state() { assert(_n_rasterizer_states < MAX_RASTERIZER_STATES); CD3D11_RASTERIZER_DESC rs_description(D3D11_DEFAULT); // rs_description.CullMode = D3D11_CULL_NONE; rs_description.DepthClipEnable = false; HRESULT hr = _device->CreateRasterizerState(&rs_description, &_rasterizer_states[_n_rasterizer_states]); if (FAILED(hr)) { return MAX_RASTERIZER_STATES + 1; } _n_rasterizer_states++; return _n_rasterizer_states - 1; } unsigned DXRenderDevice::create_blend_state(const bool blend_enabled) { assert(_n_blend_states < MAX_BLEND_STATES); D3D11_RENDER_TARGET_BLEND_DESC rt_bs_description; rt_bs_description.BlendEnable = blend_enabled; rt_bs_description.SrcBlend = D3D11_BLEND_SRC_ALPHA; rt_bs_description.DestBlend = D3D11_BLEND_INV_SRC_ALPHA; rt_bs_description.BlendOp = D3D11_BLEND_OP_ADD; rt_bs_description.SrcBlendAlpha = D3D11_BLEND_ONE; rt_bs_description.DestBlendAlpha = D3D11_BLEND_ZERO; rt_bs_description.BlendOpAlpha = D3D11_BLEND_OP_ADD; rt_bs_description.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; D3D11_BLEND_DESC bs_description; bs_description.AlphaToCoverageEnable = false; bs_description.IndependentBlendEnable = false; bs_description.RenderTarget[0] = rt_bs_description; HRESULT hr = _device->CreateBlendState(&bs_description, &_blend_states[_n_blend_states]); if (FAILED(hr)) { return MAX_BLEND_STATES + 1; } _n_blend_states++; return _n_blend_states - 1; } unsigned DXRenderDevice::create_texture(const wchar_t* const path) { assert(_n_texture_srvs < MAX_TEXTURES); assert(path != nullptr); if (!load_texture(path, _texture_srvs[_n_texture_srvs])) { return MAX_TEXTURES + 1; } _n_texture_srvs++; return _n_texture_srvs - 1; } bool DXRenderDevice::load_texture(const wchar_t* const path, ComPtr<ID3D11ShaderResourceView>& destination) { ID3D11ShaderResourceView* texture = nullptr; HRESULT hr = D3DX11CreateShaderResourceViewFromFile(_device.get(), path, 0, 0, &texture, 0); if (FAILED(hr)) { return false; } destination.set(texture); return true; } void DXRenderDevice::update_texture(const unsigned texture, const wchar_t* const path) { assert(texture < _n_texture_srvs); assert(path != nullptr); if (!load_texture(path, _texture_srvs[texture])) { // TODO: reprot error somehow } } unsigned DXRenderDevice::create_sampler(SamplerFilter filter, SamplerAddress address) { assert(_n_sampler_states < MAX_SAMPLERS); // Order dependent on SamplerFilter enum static const D3D11_FILTER filter_modes[] = { D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_FILTER_MIN_MAG_MIP_LINEAR, D3D11_FILTER_ANISOTROPIC }; // Order dependent on SamplerAddress enum static const D3D11_TEXTURE_ADDRESS_MODE address_modes[] = { D3D11_TEXTURE_ADDRESS_WRAP, D3D11_TEXTURE_ADDRESS_CLAMP }; CD3D11_SAMPLER_DESC sampler_description(D3D11_DEFAULT); sampler_description.Filter = filter_modes[filter]; sampler_description.AddressU = address_modes[address]; sampler_description.AddressV = address_modes[address]; sampler_description.AddressW = address_modes[address]; HRESULT hr = _device->CreateSamplerState(&sampler_description, &_sampler_states[_n_sampler_states]); if (FAILED(hr)) { return MAX_SAMPLERS + 1; } _n_sampler_states++; return _n_sampler_states - 1; } void DXRenderDevice::render(const Batch& batch) { UINT stride = batch.stride; UINT offset = 0; ID3D11Buffer* vertex_buffers[] = { _vertex_buffers[batch.vertices].get() }; _immediate_device->IASetVertexBuffers(0, 1, vertex_buffers, &stride, &offset); _immediate_device->IASetIndexBuffer(_index_buffers[batch.indices].get(), DXGI_FORMAT_R32_UINT, 0); _immediate_device->IASetInputLayout(_input_layouts[_vertex_shader_il[batch.vs]].get()); _immediate_device->IASetPrimitiveTopology( batch.type == Batch::BT_TRIANGLE_LIST ? D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST : D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); ID3D11Buffer* constant_buffers[] = { _constant_buffers[batch.constants].get() }; _immediate_device->PSSetConstantBuffers(0, 1, constant_buffers); ID3D11ShaderResourceView* srvs[Batch::B_MAX_TEXTURES] = {}; for (unsigned i = 0; i < batch.n_textures; ++i) { srvs[i] = _texture_srvs[batch.textures[i]].get(); } _immediate_device->PSSetShaderResources(0, batch.n_textures, srvs); ID3D11SamplerState* samplers[Batch::B_MAX_SAMPLERS] = {}; for (unsigned i = 0; i < batch.n_samplers; ++i) { samplers[i] = _sampler_states[batch.samplers[i]].get(); } _immediate_device->PSSetSamplers(0, batch.n_samplers, samplers); _immediate_device->OMSetDepthStencilState(_dst_states[batch.dst_state].get(), 0); _immediate_device->OMSetBlendState(_blend_states[batch.blend_state].get(), 0, 0xFFFFFFFF); _immediate_device->RSSetState(_rasterizer_states[batch.rasterizer_state].get()); _immediate_device->VSSetShader(_vertex_shaders[batch.vs].get(), 0, 0); _immediate_device->GSSetShader(0, 0, 0); _immediate_device->PSSetShader(_pixel_shaders[batch.ps].get(), 0, 0); _immediate_device->DrawIndexed(batch.count, batch.start_index, 0); } void DXRenderDevice::clear(const Float4 clear_color) { _immediate_device->ClearRenderTargetView(_back_buffer_rtv.get(), &clear_color.x); _immediate_device->ClearDepthStencilView(_depth_stencil_view.get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 255); } void DXRenderDevice::set_viewport(const unsigned w, const unsigned h) { D3D11_VIEWPORT viewport; viewport.Width = float(w); viewport.Height = float(h); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; _immediate_device->RSSetViewports(1, &viewport); } void DXRenderDevice::start_frame() { ID3D11RenderTargetView* rtvs[] = { _back_buffer_rtv.get() }; _immediate_device->OMSetRenderTargets(1, rtvs, _depth_stencil_view.get()); } void DXRenderDevice::end_frame() { _swap_chain->Present(0, 0); } } // namespace toy Dumb texture error report. #include "dx_render_device.h" #include "window.h" #include <cassert> namespace toy { // Order-dependent on VertexDescription enum const unsigned VertexDescription::element_size[VertexDescription::EF_COUNT] = { sizeof(float) * 4, sizeof(float) * 3, sizeof(float) * 2, sizeof(float) }; DXRenderDevice::DXRenderDevice() : _n_constant_buffers(0) , _n_vertex_buffers(0) , _n_index_buffers(0) , _n_input_layouts(0) , _n_vertex_shaders(0) , _n_pixel_shaders(0) , _n_dst_states(0) , _n_rasterizer_states(0) , _n_blend_states(0) , _n_texture_srvs(0) , _n_sampler_states(0) {} bool DXRenderDevice::init(const Window& window) { ComPtr<IDXGIFactory> dxgi_factory; HRESULT hr = ::CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgi_factory)); if (FAILED(hr)) { return false; } ComPtr<IDXGIAdapter> adapter; // TODO: adapter index option hr = dxgi_factory->EnumAdapters(0, &adapter); if (FAILED(hr)) { return false; } DXGI_SWAP_CHAIN_DESC swapchain_description; swapchain_description.BufferDesc.Width = 0; swapchain_description.BufferDesc.Height = 0; // TODO: sRGB option swapchain_description.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapchain_description.BufferDesc.RefreshRate.Numerator = 60; swapchain_description.BufferDesc.RefreshRate.Denominator = 1; // TODO: MSAA options swapchain_description.SampleDesc.Count = 1; swapchain_description.SampleDesc.Quality = 0; swapchain_description.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapchain_description.BufferCount = 2; swapchain_description.OutputWindow = window.handle(); swapchain_description.Windowed = true; swapchain_description.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapchain_description.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; const D3D_FEATURE_LEVEL feature_levels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; const unsigned n_feature_levels = sizeof(feature_levels) / sizeof(feature_levels[0]); D3D_FEATURE_LEVEL current_feature_level; hr = D3D11CreateDeviceAndSwapChain( adapter.get(), D3D_DRIVER_TYPE_UNKNOWN, 0, #ifdef _DEBUG D3D11_CREATE_DEVICE_DEBUG, #else 0, #endif feature_levels, n_feature_levels, D3D11_SDK_VERSION, &swapchain_description, &_swap_chain, &_device, &current_feature_level, &_immediate_device); if (FAILED(hr)) { return false; } return create_back_buffer_and_dst(); } bool DXRenderDevice::create_back_buffer_and_dst() { HRESULT hr = _swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&_back_buffer)); if (FAILED(hr)) { return false; } D3D11_TEXTURE2D_DESC back_buffer_description; _back_buffer->GetDesc(&back_buffer_description); D3D11_RENDER_TARGET_VIEW_DESC rtv_description; // TODO: MSAA support rtv_description.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtv_description.Texture2DArray.MipSlice = 0; rtv_description.Texture2DArray.ArraySize = 1; rtv_description.Format = back_buffer_description.Format; hr = _device->CreateRenderTargetView(_back_buffer.get(), &rtv_description, &_back_buffer_rtv); if (FAILED(hr)) { return false; } D3D11_TEXTURE2D_DESC dst_description; dst_description.Width = back_buffer_description.Width; dst_description.Height = back_buffer_description.Height; dst_description.MipLevels = 1; dst_description.ArraySize = 1; dst_description.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; dst_description.SampleDesc.Count = 1; dst_description.SampleDesc.Quality = 0; dst_description.Usage = D3D11_USAGE_DEFAULT; dst_description.BindFlags = D3D11_BIND_DEPTH_STENCIL; dst_description.CPUAccessFlags = 0; dst_description.MiscFlags = 0; hr = _device->CreateTexture2D(&dst_description, 0, &_depth_stencil); if (FAILED(hr)) { return false; } hr = _device->CreateDepthStencilView(_depth_stencil.get(), 0, &_depth_stencil_view); if (FAILED(hr)) { return false; } return true; } unsigned DXRenderDevice::create_constant_buffer(const size_t size) { assert(_n_constant_buffers < MAX_CONSTANT_BUFFERS); D3D11_BUFFER_DESC buffer_description; buffer_description.Usage = D3D11_USAGE_DYNAMIC; buffer_description.ByteWidth = size; buffer_description.BindFlags = D3D11_BIND_CONSTANT_BUFFER; buffer_description.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; buffer_description.MiscFlags = 0; buffer_description.StructureByteStride = 0; HRESULT hr = _device->CreateBuffer(&buffer_description, 0, &_constant_buffers[_n_constant_buffers]); if (FAILED(hr)) { return MAX_CONSTANT_BUFFERS + 1; } _n_constant_buffers++; return _n_constant_buffers - 1; } void DXRenderDevice::update_constant_buffer(const unsigned id, const void* const data, const size_t size) { assert(id < _n_constant_buffers); assert(data != nullptr); assert(size > 0); D3D11_MAPPED_SUBRESOURCE resource; HRESULT hr = _immediate_device->Map(_constant_buffers[id].get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &resource); if (FAILED(hr)) { return; } memcpy(resource.pData, data, size); _immediate_device->Unmap(_constant_buffers[id].get(), 0); } unsigned DXRenderDevice::create_static_vertex_buffer(const void* const data, const size_t size) { assert(_n_vertex_buffers < MAX_VERTEX_BUFFERS); D3D11_BUFFER_DESC buffer_description; buffer_description.Usage = D3D11_USAGE_IMMUTABLE; buffer_description.ByteWidth = size; buffer_description.BindFlags = D3D11_BIND_VERTEX_BUFFER; buffer_description.CPUAccessFlags = 0; buffer_description.MiscFlags = 0; buffer_description.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA resource; resource.SysMemPitch = 0; resource.SysMemSlicePitch = 0; resource.pSysMem = data; HRESULT hr = _device->CreateBuffer(&buffer_description, &resource, &_vertex_buffers[_n_vertex_buffers]); if (FAILED(hr)) { return MAX_VERTEX_BUFFERS + 1; } _n_vertex_buffers++; return _n_vertex_buffers - 1; } unsigned DXRenderDevice::create_static_index_buffer(const void* const data, const size_t size) { assert(_n_index_buffers < MAX_INDEX_BUFFERS); D3D11_BUFFER_DESC buffer_description; buffer_description.Usage = D3D11_USAGE_IMMUTABLE; buffer_description.ByteWidth = size; buffer_description.BindFlags = D3D11_BIND_INDEX_BUFFER; buffer_description.CPUAccessFlags = 0; buffer_description.MiscFlags = 0; buffer_description.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA resource; resource.SysMemPitch = 0; resource.SysMemSlicePitch = 0; resource.pSysMem = data; HRESULT hr = _device->CreateBuffer(&buffer_description, &resource, &_index_buffers[_n_index_buffers]); if (FAILED(hr)) { return MAX_INDEX_BUFFERS + 1; } _n_index_buffers++; return _n_index_buffers - 1; } unsigned DXRenderDevice::create_input_layout(const VertexDescription& description, ComPtr<ID3D10Blob>& vs_blob) { assert(_n_input_layouts < MAX_INPUT_LAYOUTS); assert(description.n_elements > 0); // Order-dependent on VertexDescription enum static const char* semantics[] = { "POSITION", "NORMAL", "TEXCOORD", "COLOR" }; // Order-dependent on VertexDescription enum, too static const DXGI_FORMAT formats[] = { DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32_FLOAT, }; D3D11_INPUT_ELEMENT_DESC layout[VertexDescription::MAX_ELEMENTS]; unsigned size = 0; for (unsigned i = 0; i < description.n_elements; ++i) { assert(description.elements[i].semantic < VertexDescription::ES_COUNT); assert(description.elements[i].semantic < VertexDescription::EF_COUNT); layout[i].SemanticName = semantics[description.elements[i].semantic]; layout[i].SemanticIndex = 0; layout[i].Format = formats[description.elements[i].format]; layout[i].InputSlot = 0; layout[i].AlignedByteOffset = size; layout[i].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; layout[i].InstanceDataStepRate = 0; size += VertexDescription::element_size[description.elements[i].format]; } HRESULT hr = _device->CreateInputLayout( layout, description.n_elements, vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &_input_layouts[_n_input_layouts]); if (FAILED(hr)) { return MAX_INPUT_LAYOUTS + 1; } _n_input_layouts++; return _n_input_layouts - 1; } unsigned DXRenderDevice::create_vertex_shader(const char* const code, const size_t length, const VertexDescription& vertex_description) { assert(code != nullptr); assert(length > 0); ComPtr<ID3DBlob> vs_blob; HRESULT hr = D3DX11CompileFromMemory(code, length, 0, 0, 0, "vs_main", "vs_4_0", 0, 0, 0, &vs_blob, 0, 0); if (FAILED(hr)) { return MAX_VERTEX_SHADERS + 1; } hr = _device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), 0, &_vertex_shaders[_n_vertex_shaders]); if (FAILED(hr)) { return MAX_VERTEX_SHADERS + 1; } _vertex_shader_il[_n_vertex_shaders] = create_input_layout(vertex_description, vs_blob); _n_vertex_shaders++; return _n_vertex_shaders - 1; } unsigned DXRenderDevice::create_pixel_shader(const char* const code, const size_t length) { assert(code != nullptr); assert(length > 0); if (!compile_pixel_shader(code, length, _pixel_shaders[_n_pixel_shaders])) { return MAX_PIXEL_SHADERS + 1; } _n_pixel_shaders++; return _n_pixel_shaders - 1; } void DXRenderDevice::update_pixel_shader(const unsigned shader, const char* const code, const size_t length) { assert(shader < _n_pixel_shaders); assert(code != nullptr); assert(length > 0); if (!compile_pixel_shader(code, length, _pixel_shaders[shader])) { // TODO: report errors somehow } } bool DXRenderDevice::compile_pixel_shader(const char* const code, const size_t length, ComPtr<ID3D11PixelShader>& destination) { ComPtr<ID3DBlob> ps_blob; ComPtr<ID3DBlob> error_blob; HRESULT hr = D3DX11CompileFromMemory(code, length, 0, 0, 0, "ps_main", "ps_4_0", 0, 0, 0, &ps_blob, &error_blob, 0); if (FAILED(hr)) { // TODO: remove this crap const char* const msg = static_cast<char*>(error_blob->GetBufferPointer()); ::MessageBoxA(0, msg, "PS compilation error", MB_ICONASTERISK); return false; } ID3D11PixelShader* ps = nullptr; hr = _device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), 0, &ps); if (FAILED(hr)) { return false; } destination.set(ps); return true; } unsigned DXRenderDevice::create_dst_state(const bool depth_enabled) { assert(_n_dst_states < MAX_DST_STATES); CD3D11_DEPTH_STENCIL_DESC dst_description(D3D11_DEFAULT); dst_description.DepthEnable = depth_enabled; HRESULT hr = _device->CreateDepthStencilState(&dst_description, &_dst_states[_n_dst_states]); if (FAILED(hr)) { return MAX_DST_STATES + 1; } _n_dst_states++; return _n_dst_states - 1; } unsigned DXRenderDevice::create_rasterizer_state() { assert(_n_rasterizer_states < MAX_RASTERIZER_STATES); CD3D11_RASTERIZER_DESC rs_description(D3D11_DEFAULT); // rs_description.CullMode = D3D11_CULL_NONE; rs_description.DepthClipEnable = false; HRESULT hr = _device->CreateRasterizerState(&rs_description, &_rasterizer_states[_n_rasterizer_states]); if (FAILED(hr)) { return MAX_RASTERIZER_STATES + 1; } _n_rasterizer_states++; return _n_rasterizer_states - 1; } unsigned DXRenderDevice::create_blend_state(const bool blend_enabled) { assert(_n_blend_states < MAX_BLEND_STATES); D3D11_RENDER_TARGET_BLEND_DESC rt_bs_description; rt_bs_description.BlendEnable = blend_enabled; rt_bs_description.SrcBlend = D3D11_BLEND_SRC_ALPHA; rt_bs_description.DestBlend = D3D11_BLEND_INV_SRC_ALPHA; rt_bs_description.BlendOp = D3D11_BLEND_OP_ADD; rt_bs_description.SrcBlendAlpha = D3D11_BLEND_ONE; rt_bs_description.DestBlendAlpha = D3D11_BLEND_ZERO; rt_bs_description.BlendOpAlpha = D3D11_BLEND_OP_ADD; rt_bs_description.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; D3D11_BLEND_DESC bs_description; bs_description.AlphaToCoverageEnable = false; bs_description.IndependentBlendEnable = false; bs_description.RenderTarget[0] = rt_bs_description; HRESULT hr = _device->CreateBlendState(&bs_description, &_blend_states[_n_blend_states]); if (FAILED(hr)) { return MAX_BLEND_STATES + 1; } _n_blend_states++; return _n_blend_states - 1; } unsigned DXRenderDevice::create_texture(const wchar_t* const path) { assert(_n_texture_srvs < MAX_TEXTURES); assert(path != nullptr); if (!load_texture(path, _texture_srvs[_n_texture_srvs])) { return MAX_TEXTURES + 1; } _n_texture_srvs++; return _n_texture_srvs - 1; } bool DXRenderDevice::load_texture(const wchar_t* const path, ComPtr<ID3D11ShaderResourceView>& destination) { ID3D11ShaderResourceView* texture = nullptr; HRESULT hr = D3DX11CreateShaderResourceViewFromFile(_device.get(), path, 0, 0, &texture, 0); if (FAILED(hr)) { // TODO: remove this crap ::MessageBox(0, path, L"Texture is not loaded", MB_ICONASTERISK); return false; } destination.set(texture); return true; } void DXRenderDevice::update_texture(const unsigned texture, const wchar_t* const path) { assert(texture < _n_texture_srvs); assert(path != nullptr); if (!load_texture(path, _texture_srvs[texture])) { // TODO: reprot error somehow } } unsigned DXRenderDevice::create_sampler(SamplerFilter filter, SamplerAddress address) { assert(_n_sampler_states < MAX_SAMPLERS); // Order dependent on SamplerFilter enum static const D3D11_FILTER filter_modes[] = { D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_FILTER_MIN_MAG_MIP_LINEAR, D3D11_FILTER_ANISOTROPIC }; // Order dependent on SamplerAddress enum static const D3D11_TEXTURE_ADDRESS_MODE address_modes[] = { D3D11_TEXTURE_ADDRESS_WRAP, D3D11_TEXTURE_ADDRESS_CLAMP }; CD3D11_SAMPLER_DESC sampler_description(D3D11_DEFAULT); sampler_description.Filter = filter_modes[filter]; sampler_description.AddressU = address_modes[address]; sampler_description.AddressV = address_modes[address]; sampler_description.AddressW = address_modes[address]; HRESULT hr = _device->CreateSamplerState(&sampler_description, &_sampler_states[_n_sampler_states]); if (FAILED(hr)) { return MAX_SAMPLERS + 1; } _n_sampler_states++; return _n_sampler_states - 1; } void DXRenderDevice::render(const Batch& batch) { UINT stride = batch.stride; UINT offset = 0; ID3D11Buffer* vertex_buffers[] = { _vertex_buffers[batch.vertices].get() }; _immediate_device->IASetVertexBuffers(0, 1, vertex_buffers, &stride, &offset); _immediate_device->IASetIndexBuffer(_index_buffers[batch.indices].get(), DXGI_FORMAT_R32_UINT, 0); _immediate_device->IASetInputLayout(_input_layouts[_vertex_shader_il[batch.vs]].get()); _immediate_device->IASetPrimitiveTopology( batch.type == Batch::BT_TRIANGLE_LIST ? D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST : D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); ID3D11Buffer* constant_buffers[] = { _constant_buffers[batch.constants].get() }; _immediate_device->PSSetConstantBuffers(0, 1, constant_buffers); ID3D11ShaderResourceView* srvs[Batch::B_MAX_TEXTURES] = {}; for (unsigned i = 0; i < batch.n_textures; ++i) { srvs[i] = _texture_srvs[batch.textures[i]].get(); } _immediate_device->PSSetShaderResources(0, batch.n_textures, srvs); ID3D11SamplerState* samplers[Batch::B_MAX_SAMPLERS] = {}; for (unsigned i = 0; i < batch.n_samplers; ++i) { samplers[i] = _sampler_states[batch.samplers[i]].get(); } _immediate_device->PSSetSamplers(0, batch.n_samplers, samplers); _immediate_device->OMSetDepthStencilState(_dst_states[batch.dst_state].get(), 0); _immediate_device->OMSetBlendState(_blend_states[batch.blend_state].get(), 0, 0xFFFFFFFF); _immediate_device->RSSetState(_rasterizer_states[batch.rasterizer_state].get()); _immediate_device->VSSetShader(_vertex_shaders[batch.vs].get(), 0, 0); _immediate_device->GSSetShader(0, 0, 0); _immediate_device->PSSetShader(_pixel_shaders[batch.ps].get(), 0, 0); _immediate_device->DrawIndexed(batch.count, batch.start_index, 0); } void DXRenderDevice::clear(const Float4 clear_color) { _immediate_device->ClearRenderTargetView(_back_buffer_rtv.get(), &clear_color.x); _immediate_device->ClearDepthStencilView(_depth_stencil_view.get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 255); } void DXRenderDevice::set_viewport(const unsigned w, const unsigned h) { D3D11_VIEWPORT viewport; viewport.Width = float(w); viewport.Height = float(h); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; _immediate_device->RSSetViewports(1, &viewport); } void DXRenderDevice::start_frame() { ID3D11RenderTargetView* rtvs[] = { _back_buffer_rtv.get() }; _immediate_device->OMSetRenderTargets(1, rtvs, _depth_stencil_view.get()); } void DXRenderDevice::end_frame() { _swap_chain->Present(0, 0); } } // namespace toy
/*************************************************************************/ /* os_x11.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "os_x11.h" #include "core/os/dir_access.h" #include "core/print_string.h" #include "detect_prime.h" #include "drivers/gles2/rasterizer_gles2.h" #include "drivers/gles3/rasterizer_gles3.h" #include "key_mapping_x11.h" #include "main/main.h" #include "servers/visual/visual_server_raster.h" #include "servers/visual/visual_server_wrap_mt.h" #ifdef HAVE_MNTENT #include <mntent.h> #endif #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <X11/Xatom.h> #include <X11/Xutil.h> #include <X11/extensions/Xinerama.h> #include <X11/extensions/shape.h> // ICCCM #define WM_NormalState 1L // window normal state #define WM_IconicState 3L // window minimized // EWMH #define _NET_WM_STATE_REMOVE 0L // remove/unset property #define _NET_WM_STATE_ADD 1L // add/set property #define _NET_WM_STATE_TOGGLE 2L // toggle property #include <dlfcn.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> //stupid linux.h #ifdef KEY_TAB #undef KEY_TAB #endif #undef CursorShape #include <X11/XKBlib.h> // 2.2 is the first release with multitouch #define XINPUT_CLIENT_VERSION_MAJOR 2 #define XINPUT_CLIENT_VERSION_MINOR 2 #define VALUATOR_ABSX 0 #define VALUATOR_ABSY 1 #define VALUATOR_PRESSURE 2 #define VALUATOR_TILTX 3 #define VALUATOR_TILTY 4 static const double abs_resolution_mult = 10000.0; static const double abs_resolution_range_mult = 10.0; void OS_X11::initialize_core() { crash_handler.initialize(); OS_Unix::initialize_core(); } int OS_X11::get_current_video_driver() const { return video_driver_index; } Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { long im_event_mask = 0; last_button_state = 0; xmbstring = NULL; x11_window = 0; last_click_ms = 0; last_click_button_index = -1; last_click_pos = Point2(-100, -100); args = OS::get_singleton()->get_cmdline_args(); current_videomode = p_desired; main_loop = NULL; last_timestamp = 0; last_mouse_pos_valid = false; last_keyrelease_time = 0; xdnd_version = 0; XInitThreads(); /** XLIB INITIALIZATION **/ x11_display = XOpenDisplay(NULL); if (!x11_display) { ERR_PRINT("X11 Display is not available"); return ERR_UNAVAILABLE; } char *modifiers = NULL; Bool xkb_dar = False; XAutoRepeatOn(x11_display); xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, NULL); // Try to support IME if detectable auto-repeat is supported if (xkb_dar == True) { #ifdef X_HAVE_UTF8_STRING // Xutf8LookupString will be used later instead of XmbLookupString before // the multibyte sequences can be converted to unicode string. modifiers = XSetLocaleModifiers(""); #endif } if (modifiers == NULL) { if (is_stdout_verbose()) { WARN_PRINT("IME is disabled"); } XSetLocaleModifiers("@im=none"); WARN_PRINT("Error setting locale modifiers"); } const char *err; xrr_get_monitors = NULL; xrr_free_monitors = NULL; int xrandr_major = 0; int xrandr_minor = 0; int event_base, error_base; xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base); xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY); if (!xrandr_handle) { err = dlerror(); // For some arcane reason, NetBSD now ships libXrandr.so.3 while the rest of the world has libXrandr.so.2... // In case this happens for other X11 platforms in the future, let's give it a try too before failing. xrandr_handle = dlopen("libXrandr.so.3", RTLD_LAZY); if (!xrandr_handle) { fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err); } } else { XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor); if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) { xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors"); if (!xrr_get_monitors) { err = dlerror(); fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err); } else { xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors"); if (!xrr_free_monitors) { err = dlerror(); fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err); xrr_get_monitors = NULL; } } } } if (!refresh_device_info()) { OS::get_singleton()->alert("Your system does not support XInput 2.\n" "Please upgrade your distribution.", "Unable to initialize XInput"); return ERR_UNAVAILABLE; } xim = XOpenIM(x11_display, NULL, NULL, NULL); if (xim == NULL) { WARN_PRINT("XOpenIM failed"); xim_style = 0L; } else { ::XIMCallback im_destroy_callback; im_destroy_callback.client_data = (::XPointer)(this); im_destroy_callback.callback = (::XIMProc)(xim_destroy_callback); if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback, NULL) != NULL) { WARN_PRINT("Error setting XIM destroy callback"); } ::XIMStyles *xim_styles = NULL; xim_style = 0L; char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL); if (imvalret != NULL || xim_styles == NULL) { fprintf(stderr, "Input method doesn't support any styles\n"); } if (xim_styles) { xim_style = 0L; for (int i = 0; i < xim_styles->count_styles; i++) { if (xim_styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) { xim_style = xim_styles->supported_styles[i]; break; } } XFree(xim_styles); } XFree(imvalret); } /* char* windowid = getenv("GODOT_WINDOWID"); if (windowid) { //freopen("/home/punto/stdout", "w", stdout); //reopen("/home/punto/stderr", "w", stderr); x11_window = atol(windowid); XWindowAttributes xwa; XGetWindowAttributes(x11_display,x11_window,&xwa); current_videomode.width = xwa.width; current_videomode.height = xwa.height; }; */ // maybe contextgl wants to be in charge of creating the window #if defined(OPENGL_ENABLED) if (getenv("DRI_PRIME") == NULL) { int use_prime = -1; if (getenv("PRIMUS_DISPLAY") || getenv("PRIMUS_libGLd") || getenv("PRIMUS_libGLa") || getenv("PRIMUS_libGL") || getenv("PRIMUS_LOAD_GLOBAL") || getenv("BUMBLEBEE_SOCKET")) { print_verbose("Optirun/primusrun detected. Skipping GPU detection"); use_prime = 0; } if (getenv("LD_LIBRARY_PATH")) { String ld_library_path(getenv("LD_LIBRARY_PATH")); Vector<String> libraries = ld_library_path.split(":"); for (int i = 0; i < libraries.size(); ++i) { if (FileAccess::exists(libraries[i] + "/libGL.so.1") || FileAccess::exists(libraries[i] + "/libGL.so")) { print_verbose("Custom libGL override detected. Skipping GPU detection"); use_prime = 0; } } } if (use_prime == -1) { print_verbose("Detecting GPUs, set DRI_PRIME in the environment to override GPU detection logic."); use_prime = detect_prime(); } if (use_prime) { print_line("Found discrete GPU, setting DRI_PRIME=1 to use it."); print_line("Note: Set DRI_PRIME=0 in the environment to disable Godot from using the discrete GPU."); setenv("DRI_PRIME", "1", 1); } } ContextGL_X11::ContextType opengl_api_type = ContextGL_X11::GLES_3_0_COMPATIBLE; if (p_video_driver == VIDEO_DRIVER_GLES2) { opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; } bool editor = Engine::get_singleton()->is_editor_hint(); bool gl_initialization_error = false; context_gl = NULL; while (!context_gl) { context_gl = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, opengl_api_type)); if (context_gl->initialize() != OK) { memdelete(context_gl); context_gl = NULL; if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) { if (p_video_driver == VIDEO_DRIVER_GLES2) { gl_initialization_error = true; break; } p_video_driver = VIDEO_DRIVER_GLES2; opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; } else { gl_initialization_error = true; break; } } } while (true) { if (opengl_api_type == ContextGL_X11::GLES_3_0_COMPATIBLE) { if (RasterizerGLES3::is_viable() == OK) { RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); break; } else { if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) { p_video_driver = VIDEO_DRIVER_GLES2; opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; continue; } else { gl_initialization_error = true; break; } } } if (opengl_api_type == ContextGL_X11::GLES_2_0_COMPATIBLE) { if (RasterizerGLES2::is_viable() == OK) { RasterizerGLES2::register_config(); RasterizerGLES2::make_current(); break; } else { gl_initialization_error = true; break; } } } if (gl_initialization_error) { OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n" "Please update your drivers or if you have a very old or integrated GPU upgrade it.", "Unable to initialize Video driver"); return ERR_UNAVAILABLE; } video_driver_index = p_video_driver; context_gl->set_use_vsync(current_videomode.use_vsync); #endif visual_server = memnew(VisualServerRaster); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); } if (current_videomode.maximized) { current_videomode.maximized = false; set_window_maximized(true); // borderless fullscreen window mode } else if (current_videomode.fullscreen) { current_videomode.fullscreen = false; set_window_fullscreen(true); } else if (current_videomode.borderless_window) { Hints hints; Atom property; hints.flags = 2; hints.decorations = 0; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } // make PID known to X11 { const long pid = this->get_process_id(); Atom net_wm_pid = XInternAtom(x11_display, "_NET_WM_PID", False); if (net_wm_pid != None) { XChangeProperty(x11_display, x11_window, net_wm_pid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1); } } // disable resizable window if (!current_videomode.resizable && !current_videomode.fullscreen) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = PMinSize | PMaxSize; XWindowAttributes xwa; if (current_videomode.fullscreen) { XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa); } else { XGetWindowAttributes(x11_display, x11_window, &xwa); } xsh->min_width = xwa.width; xsh->max_width = xwa.width; xsh->min_height = xwa.height; xsh->max_height = xwa.height; XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); } if (current_videomode.always_on_top) { current_videomode.always_on_top = false; set_window_always_on_top(true); } ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE); ERR_FAIL_COND_V(x11_window == 0, ERR_UNAVAILABLE); XSetWindowAttributes new_attr; new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask | Button1MotionMask | Button2MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask | ButtonMotionMask | KeymapStateMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | SubstructureNotifyMask | SubstructureRedirectMask | FocusChangeMask | PropertyChangeMask | ColormapChangeMask | OwnerGrabButtonMask | im_event_mask; XChangeWindowAttributes(x11_display, x11_window, CWEventMask, &new_attr); static unsigned char all_mask_data[XIMaskLen(XI_LASTEVENT)] = {}; static unsigned char all_master_mask_data[XIMaskLen(XI_LASTEVENT)] = {}; xi.all_event_mask.deviceid = XIAllDevices; xi.all_event_mask.mask_len = sizeof(all_mask_data); xi.all_event_mask.mask = all_mask_data; xi.all_master_event_mask.deviceid = XIAllMasterDevices; xi.all_master_event_mask.mask_len = sizeof(all_master_mask_data); xi.all_master_event_mask.mask = all_master_mask_data; XISetMask(xi.all_event_mask.mask, XI_HierarchyChanged); XISetMask(xi.all_master_event_mask.mask, XI_DeviceChanged); XISetMask(xi.all_master_event_mask.mask, XI_RawMotion); #ifdef TOUCH_ENABLED if (xi.touch_devices.size()) { XISetMask(xi.all_event_mask.mask, XI_TouchBegin); XISetMask(xi.all_event_mask.mask, XI_TouchUpdate); XISetMask(xi.all_event_mask.mask, XI_TouchEnd); XISetMask(xi.all_event_mask.mask, XI_TouchOwnership); } #endif XISelectEvents(x11_display, x11_window, &xi.all_event_mask, 1); XISelectEvents(x11_display, DefaultRootWindow(x11_display), &xi.all_master_event_mask, 1); // Disabled by now since grabbing also blocks mouse events // (they are received as extended events instead of standard events) /*XIClearMask(xi.touch_event_mask.mask, XI_TouchOwnership); // Grab touch devices to avoid OS gesture interference for (int i = 0; i < xi.touch_devices.size(); ++i) { XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask); }*/ /* set the titlebar name */ XStoreName(x11_display, x11_window, "Godot"); wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true); XSetWMProtocols(x11_display, x11_window, &wm_delete, 1); im_active = false; im_position = Vector2(); if (xim && xim_style) { xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, x11_window, XNFocusWindow, x11_window, (char *)NULL); if (XGetICValues(xic, XNFilterEvents, &im_event_mask, NULL) != NULL) { WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value"); XDestroyIC(xic); xic = NULL; } if (xic) { XUnsetICFocus(xic); } else { WARN_PRINT("XCreateIC couldn't create xic"); } } else { xic = NULL; WARN_PRINT("XCreateIC couldn't create xic"); } cursor_size = XcursorGetDefaultSize(x11_display); cursor_theme = XcursorGetTheme(x11_display); if (!cursor_theme) { print_verbose("XcursorGetTheme could not get cursor theme"); cursor_theme = "default"; } for (int i = 0; i < CURSOR_MAX; i++) { cursors[i] = None; img[i] = NULL; } current_cursor = CURSOR_ARROW; for (int i = 0; i < CURSOR_MAX; i++) { static const char *cursor_file[] = { "left_ptr", "xterm", "hand2", "cross", "watch", "left_ptr_watch", "fleur", "hand1", "X_cursor", "sb_v_double_arrow", "sb_h_double_arrow", "size_bdiag", "size_fdiag", "hand1", "sb_v_double_arrow", "sb_h_double_arrow", "question_arrow" }; img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size); if (img[i]) { cursors[i] = XcursorImageLoadCursor(x11_display, img[i]); } else { print_verbose("Failed loading custom cursor: " + String(cursor_file[i])); } } { // Creating an empty/transparent cursor // Create 1x1 bitmap Pixmap cursormask = XCreatePixmap(x11_display, RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1); // Fill with zero XGCValues xgc; xgc.function = GXclear; GC gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc); XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1); // Color value doesn't matter. Mask zero means no foreground or background will be drawn XColor col = {}; Cursor cursor = XCreatePixmapCursor(x11_display, cursormask, // source (using cursor mask as placeholder, since it'll all be ignored) cursormask, // mask &col, &col, 0, 0); XFreePixmap(x11_display, cursormask); XFreeGC(x11_display, gc); if (cursor == None) { ERR_PRINT("FAILED CREATING CURSOR"); } null_cursor = cursor; } set_cursor_shape(CURSOR_BUSY); //Set Xdnd (drag & drop) support Atom XdndAware = XInternAtom(x11_display, "XdndAware", False); Atom version = 5; if (XdndAware != None) { XChangeProperty(x11_display, x11_window, XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&version, 1); } xdnd_enter = XInternAtom(x11_display, "XdndEnter", False); xdnd_position = XInternAtom(x11_display, "XdndPosition", False); xdnd_status = XInternAtom(x11_display, "XdndStatus", False); xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False); xdnd_drop = XInternAtom(x11_display, "XdndDrop", False); xdnd_finished = XInternAtom(x11_display, "XdndFinished", False); xdnd_selection = XInternAtom(x11_display, "XdndSelection", False); requested = None; visual_server->init(); AudioDriverManager::initialize(p_audio_driver); input = memnew(InputDefault); window_has_focus = true; // Set focus to true at init #ifdef JOYDEV_ENABLED joypad = memnew(JoypadLinux(input)); #endif power_manager = memnew(PowerX11); if (p_desired.layered) { set_window_per_pixel_transparency_enabled(true); } XEvent xevent; while (XPending(x11_display) > 0) { XNextEvent(x11_display, &xevent); if (xevent.type == ConfigureNotify) { _window_changed(&xevent); } } events_thread.start(_poll_events_thread, this); update_real_mouse_position(); return OK; } bool OS_X11::refresh_device_info() { int event_base, error_base; print_verbose("XInput: Refreshing devices."); if (!XQueryExtension(x11_display, "XInputExtension", &xi.opcode, &event_base, &error_base)) { print_verbose("XInput extension not available. Please upgrade your distribution."); return false; } int xi_major_query = XINPUT_CLIENT_VERSION_MAJOR; int xi_minor_query = XINPUT_CLIENT_VERSION_MINOR; if (XIQueryVersion(x11_display, &xi_major_query, &xi_minor_query) != Success) { print_verbose(vformat("XInput 2 not available (server supports %d.%d).", xi_major_query, xi_minor_query)); xi.opcode = 0; return false; } if (xi_major_query < XINPUT_CLIENT_VERSION_MAJOR || (xi_major_query == XINPUT_CLIENT_VERSION_MAJOR && xi_minor_query < XINPUT_CLIENT_VERSION_MINOR)) { print_verbose(vformat("XInput %d.%d not available (server supports %d.%d). Touch input unavailable.", XINPUT_CLIENT_VERSION_MAJOR, XINPUT_CLIENT_VERSION_MINOR, xi_major_query, xi_minor_query)); } xi.absolute_devices.clear(); xi.touch_devices.clear(); int dev_count; XIDeviceInfo *info = XIQueryDevice(x11_display, XIAllDevices, &dev_count); for (int i = 0; i < dev_count; i++) { XIDeviceInfo *dev = &info[i]; if (!dev->enabled) continue; if (!(dev->use == XIMasterPointer || dev->use == XIFloatingSlave)) continue; bool direct_touch = false; bool absolute_mode = false; int resolution_x = 0; int resolution_y = 0; double abs_x_min = 0; double abs_x_max = 0; double abs_y_min = 0; double abs_y_max = 0; double pressure_min = 0; double pressure_max = 0; double tilt_x_min = 0; double tilt_x_max = 0; double tilt_y_min = 0; double tilt_y_max = 0; for (int j = 0; j < dev->num_classes; j++) { #ifdef TOUCH_ENABLED if (dev->classes[j]->type == XITouchClass && ((XITouchClassInfo *)dev->classes[j])->mode == XIDirectTouch) { direct_touch = true; } #endif if (dev->classes[j]->type == XIValuatorClass) { XIValuatorClassInfo *class_info = (XIValuatorClassInfo *)dev->classes[j]; if (class_info->number == VALUATOR_ABSX && class_info->mode == XIModeAbsolute) { resolution_x = class_info->resolution; abs_x_min = class_info->min; abs_y_max = class_info->max; absolute_mode = true; } else if (class_info->number == VALUATOR_ABSY && class_info->mode == XIModeAbsolute) { resolution_y = class_info->resolution; abs_y_min = class_info->min; abs_y_max = class_info->max; absolute_mode = true; } else if (class_info->number == VALUATOR_PRESSURE && class_info->mode == XIModeAbsolute) { pressure_min = class_info->min; pressure_max = class_info->max; } else if (class_info->number == VALUATOR_TILTX && class_info->mode == XIModeAbsolute) { tilt_x_min = class_info->min; tilt_x_max = class_info->max; } else if (class_info->number == VALUATOR_TILTY && class_info->mode == XIModeAbsolute) { tilt_x_min = class_info->min; tilt_x_max = class_info->max; } } } if (direct_touch) { xi.touch_devices.push_back(dev->deviceid); print_verbose("XInput: Using touch device: " + String(dev->name)); } if (absolute_mode) { // If no resolution was reported, use the min/max ranges. if (resolution_x <= 0) { resolution_x = (abs_x_max - abs_x_min) * abs_resolution_range_mult; } if (resolution_y <= 0) { resolution_y = (abs_y_max - abs_y_min) * abs_resolution_range_mult; } xi.absolute_devices[dev->deviceid] = Vector2(abs_resolution_mult / resolution_x, abs_resolution_mult / resolution_y); print_verbose("XInput: Absolute pointing device: " + String(dev->name)); } xi.pressure = 0; xi.pen_pressure_range[dev->deviceid] = Vector2(pressure_min, pressure_max); xi.pen_tilt_x_range[dev->deviceid] = Vector2(tilt_x_min, tilt_x_max); xi.pen_tilt_y_range[dev->deviceid] = Vector2(tilt_y_min, tilt_y_max); } XIFreeDeviceInfo(info); #ifdef TOUCH_ENABLED if (!xi.touch_devices.size()) { print_verbose("XInput: No touch devices found."); } #endif return true; } void OS_X11::xim_destroy_callback(::XIM im, ::XPointer client_data, ::XPointer call_data) { WARN_PRINT("Input method stopped"); OS_X11 *os = reinterpret_cast<OS_X11 *>(client_data); os->xim = NULL; os->xic = NULL; } void OS_X11::set_ime_active(const bool p_active) { im_active = p_active; if (!xic) { return; } // Block events polling while changing input focus // because it triggers some event polling internally. if (p_active) { { MutexLock mutex_lock(events_mutex); XSetICFocus(xic); } set_ime_position(im_position); } else { MutexLock mutex_lock(events_mutex); XUnsetICFocus(xic); } } void OS_X11::set_ime_position(const Point2 &p_pos) { im_position = p_pos; if (!xic) return; ::XPoint spot; spot.x = short(p_pos.x); spot.y = short(p_pos.y); XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, NULL); { // Block events polling during this call // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XSetICValues(xic, XNPreeditAttributes, preedit_attr, NULL); } XFree(preedit_attr); } String OS_X11::get_unique_id() const { static String machine_id; if (machine_id.empty()) { if (FileAccess *f = FileAccess::open("/etc/machine-id", FileAccess::READ)) { while (machine_id.empty() && !f->eof_reached()) { machine_id = f->get_line().strip_edges(); } f->close(); memdelete(f); } } return machine_id; } void OS_X11::finalize() { events_thread_done = true; events_thread.wait_to_finish(); if (main_loop) memdelete(main_loop); main_loop = NULL; /* if (debugger_connection_console) { memdelete(debugger_connection_console); } */ #ifdef ALSAMIDI_ENABLED driver_alsamidi.close(); #endif #ifdef JOYDEV_ENABLED memdelete(joypad); #endif xi.touch_devices.clear(); xi.state.clear(); memdelete(input); cursors_cache.clear(); visual_server->finish(); memdelete(visual_server); //memdelete(rasterizer); memdelete(power_manager); if (xrandr_handle) dlclose(xrandr_handle); if (!OS::get_singleton()->is_no_window_mode_enabled()) { XUnmapWindow(x11_display, x11_window); } XDestroyWindow(x11_display, x11_window); #if defined(OPENGL_ENABLED) memdelete(context_gl); #endif for (int i = 0; i < CURSOR_MAX; i++) { if (cursors[i] != None) XFreeCursor(x11_display, cursors[i]); if (img[i] != NULL) XcursorImageDestroy(img[i]); }; if (xic) { XDestroyIC(xic); } if (xim) { XCloseIM(xim); } XCloseDisplay(x11_display); if (xmbstring) memfree(xmbstring); args.clear(); } void OS_X11::set_mouse_mode(MouseMode p_mode) { if (p_mode == mouse_mode) return; if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) XUngrabPointer(x11_display, CurrentTime); // The only modes that show a cursor are VISIBLE and CONFINED bool showCursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED); if (showCursor) { XDefineCursor(x11_display, x11_window, cursors[current_cursor]); // show cursor } else { XDefineCursor(x11_display, x11_window, null_cursor); // hide cursor } mouse_mode = p_mode; if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) { //flush pending motion events flush_mouse_motion(); if (XGrabPointer( x11_display, x11_window, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime) != GrabSuccess) { ERR_PRINT("NO GRAB"); } if (mouse_mode == MOUSE_MODE_CAPTURED) { center.x = current_videomode.width / 2; center.y = current_videomode.height / 2; XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)center.x, (int)center.y); input->set_mouse_position(center); } } else { do_mouse_warp = false; } XFlush(x11_display); } void OS_X11::warp_mouse_position(const Point2 &p_to) { if (mouse_mode == MOUSE_MODE_CAPTURED) { last_mouse_pos = p_to; } else { /*XWindowAttributes xwa; XGetWindowAttributes(x11_display, x11_window, &xwa); printf("%d %d\n", xwa.x, xwa.y); needed? */ XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)p_to.x, (int)p_to.y); } } void OS_X11::flush_mouse_motion() { // Block events polling while flushing motion events. MutexLock mutex_lock(events_mutex); for (uint32_t event_index = 0; event_index < polled_events.size(); ++event_index) { XEvent &event = polled_events[event_index]; if (XGetEventData(x11_display, &event.xcookie) && event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) { XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data; if (event_data->evtype == XI_RawMotion) { XFreeEventData(x11_display, &event.xcookie); polled_events.remove(event_index--); continue; } XFreeEventData(x11_display, &event.xcookie); break; } } xi.relative_motion.x = 0; xi.relative_motion.y = 0; } OS::MouseMode OS_X11::get_mouse_mode() const { return mouse_mode; } int OS_X11::get_mouse_button_state() const { return last_button_state; } Point2 OS_X11::get_mouse_position() const { return last_mouse_pos; } bool OS_X11::get_window_per_pixel_transparency_enabled() const { if (!is_layered_allowed()) return false; return layered_window; } void OS_X11::set_window_per_pixel_transparency_enabled(bool p_enabled) { if (!is_layered_allowed()) return; if (layered_window != p_enabled) { if (p_enabled) { layered_window = true; } else { layered_window = false; } } } void OS_X11::set_window_title(const String &p_title) { XStoreName(x11_display, x11_window, p_title.utf8().get_data()); Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false); Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false); if (_net_wm_name != None && utf8_string != None) { XChangeProperty(x11_display, x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length()); } } void OS_X11::set_window_mouse_passthrough(const PoolVector2Array &p_region) { int event_base, error_base; const Bool ext_okay = XShapeQueryExtension(x11_display, &event_base, &error_base); if (ext_okay) { Region region; if (p_region.size() == 0) { region = XCreateRegion(); XRectangle rect; rect.x = 0; rect.y = 0; rect.width = get_real_window_size().x; rect.height = get_real_window_size().y; XUnionRectWithRegion(&rect, region, region); } else { XPoint *points = (XPoint *)memalloc(sizeof(XPoint) * p_region.size()); for (int i = 0; i < p_region.size(); i++) { points[i].x = p_region[i].x; points[i].y = p_region[i].y; } region = XPolygonRegion(points, p_region.size(), EvenOddRule); memfree(points); } XShapeCombineRegion(x11_display, x11_window, ShapeInput, 0, 0, region, ShapeSet); XDestroyRegion(region); } } void OS_X11::set_video_mode(const VideoMode &p_video_mode, int p_screen) { } OS::VideoMode OS_X11::get_video_mode(int p_screen) const { return current_videomode; } void OS_X11::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const { } void OS_X11::set_wm_fullscreen(bool p_enabled) { if (p_enabled && !get_borderless_window()) { // remove decorations if the window is not already borderless Hints hints; Atom property; hints.flags = 2; hints.decorations = 0; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } if (p_enabled && !is_window_resizable()) { // Set the window as resizable to prevent window managers to ignore the fullscreen state flag. XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); } // Using EWMH -- Extended Window Manager Hints XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.xclient.data.l[1] = wm_fullscreen; xev.xclient.data.l[2] = 0; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); // set bypass compositor hint Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False); unsigned long compositing_disable_on = p_enabled ? 1 : 0; if (bypass_compositor != None) { XChangeProperty(x11_display, x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1); } XFlush(x11_display); if (!p_enabled) { // Reset the non-resizable flags if we un-set these before. Size2 size = get_window_size(); XSizeHints *xsh; xsh = XAllocSizeHints(); if (!is_window_resizable()) { xsh->flags = PMinSize | PMaxSize; xsh->min_width = size.x; xsh->max_width = size.x; xsh->min_height = size.y; xsh->max_height = size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); // put back or remove decorations according to the last set borderless state Hints hints; Atom property; hints.flags = 2; hints.decorations = current_videomode.borderless_window ? 0 : 1; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } } void OS_X11::set_wm_above(bool p_enabled) { Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False); XClientMessageEvent xev; memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.window = x11_window; xev.message_type = wm_state; xev.format = 32; xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.data.l[1] = wm_above; xev.data.l[3] = 1; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev); } int OS_X11::get_screen_count() const { // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) return 0; int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); XFree(xsi); return count; } int OS_X11::get_current_screen() const { int x, y; Window child; XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child); int count = get_screen_count(); for (int i = 0; i < count; i++) { Point2i pos = get_screen_position(i); Size2i size = get_screen_size(i); if ((x >= pos.x && x < pos.x + size.width) && (y >= pos.y && y < pos.y + size.height)) return i; } return 0; } void OS_X11::set_current_screen(int p_screen) { int count = get_screen_count(); if (p_screen >= count) return; if (current_videomode.fullscreen) { Point2i position = get_screen_position(p_screen); Size2i size = get_screen_size(p_screen); XMoveResizeWindow(x11_display, x11_window, position.x, position.y, size.x, size.y); } else { if (p_screen != get_current_screen()) { Point2i position = get_screen_position(p_screen); XMoveWindow(x11_display, x11_window, position.x, position.y); } } } Point2 OS_X11::get_screen_position(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) { return Point2i(0, 0); } int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); if (p_screen >= count) { return Point2i(0, 0); } Point2i position = Point2i(xsi[p_screen].x_org, xsi[p_screen].y_org); XFree(xsi); return position; } Size2 OS_X11::get_screen_size(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) return Size2i(0, 0); int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); if (p_screen >= count) return Size2i(0, 0); Size2i size = Point2i(xsi[p_screen].width, xsi[p_screen].height); XFree(xsi); return size; } int OS_X11::get_screen_dpi(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } //invalid screen? ERR_FAIL_INDEX_V(p_screen, get_screen_count(), 0); //Get physical monitor Dimensions through XRandR and calculate dpi Size2 sc = get_screen_size(p_screen); if (xrandr_ext_ok) { int count = 0; if (xrr_get_monitors) { xrr_monitor_info *monitors = xrr_get_monitors(x11_display, x11_window, true, &count); if (p_screen < count) { double xdpi = sc.width / (double)monitors[p_screen].mwidth * 25.4; double ydpi = sc.height / (double)monitors[p_screen].mheight * 25.4; xrr_free_monitors(monitors); return (xdpi + ydpi) / 2; } xrr_free_monitors(monitors); } else if (p_screen == 0) { XRRScreenSize *sizes = XRRSizes(x11_display, 0, &count); if (sizes) { double xdpi = sc.width / (double)sizes[0].mwidth * 25.4; double ydpi = sc.height / (double)sizes[0].mheight * 25.4; return (xdpi + ydpi) / 2; } } } int width_mm = DisplayWidthMM(x11_display, p_screen); int height_mm = DisplayHeightMM(x11_display, p_screen); double xdpi = (width_mm ? sc.width / (double)width_mm * 25.4 : 0); double ydpi = (height_mm ? sc.height / (double)height_mm * 25.4 : 0); if (xdpi || ydpi) return (xdpi + ydpi) / (xdpi && ydpi ? 2 : 1); //could not get dpi return 96; } Point2 OS_X11::get_window_position() const { int x, y; Window child; XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child); return Point2i(x, y); } void OS_X11::set_window_position(const Point2 &p_position) { int x = 0; int y = 0; if (!get_borderless_window()) { //exclude window decorations XSync(x11_display, False); Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (format == 32 && len == 4) { long *extents = (long *)data; x = extents[0]; y = extents[2]; } XFree(data); } } } XMoveWindow(x11_display, x11_window, p_position.x - x, p_position.y - y); update_real_mouse_position(); } Size2 OS_X11::get_window_size() const { // Use current_videomode width and height instead of XGetWindowAttributes // since right after a XResizeWindow the attributes may not be updated yet return Size2i(current_videomode.width, current_videomode.height); } Size2 OS_X11::get_real_window_size() const { XWindowAttributes xwa; XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); int w = xwa.width; int h = xwa.height; Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (format == 32 && len == 4) { long *extents = (long *)data; w += extents[0] + extents[1]; // left, right h += extents[2] + extents[3]; // top, bottom } XFree(data); } } return Size2(w, h); } Size2 OS_X11::get_max_window_size() const { return max_size; } Size2 OS_X11::get_min_window_size() const { return min_size; } void OS_X11::set_min_window_size(const Size2 p_size) { if ((p_size != Size2()) && (max_size != Size2()) && ((p_size.x > max_size.x) || (p_size.y > max_size.y))) { ERR_PRINT("Minimum window size can't be larger than maximum window size!"); return; } min_size = p_size; if (is_window_resizable()) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); XFlush(x11_display); } } void OS_X11::set_max_window_size(const Size2 p_size) { if ((p_size != Size2()) && ((p_size.x < min_size.x) || (p_size.y < min_size.y))) { ERR_PRINT("Maximum window size can't be smaller than minimum window size!"); return; } max_size = p_size; if (is_window_resizable()) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); XFlush(x11_display); } } void OS_X11::set_window_size(const Size2 p_size) { if (current_videomode.width == p_size.width && current_videomode.height == p_size.height) return; XWindowAttributes xwa; XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); int old_w = xwa.width; int old_h = xwa.height; // If window resizable is disabled we need to update the attributes first XSizeHints *xsh; xsh = XAllocSizeHints(); if (!is_window_resizable()) { xsh->flags = PMinSize | PMaxSize; xsh->min_width = p_size.x; xsh->max_width = p_size.x; xsh->min_height = p_size.y; xsh->max_height = p_size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); // Resize the window XResizeWindow(x11_display, x11_window, p_size.x, p_size.y); // Update our videomode width and height current_videomode.width = p_size.x; current_videomode.height = p_size.y; for (int timeout = 0; timeout < 50; ++timeout) { XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); if (old_w != xwa.width || old_h != xwa.height) break; usleep(10000); } } void OS_X11::set_window_fullscreen(bool p_enabled) { if (current_videomode.fullscreen == p_enabled) return; if (layered_window) set_window_per_pixel_transparency_enabled(false); if (p_enabled && current_videomode.always_on_top) { // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity) set_window_maximized(true); } set_wm_fullscreen(p_enabled); if (!p_enabled && current_videomode.always_on_top) { // Restore set_window_maximized(false); } if (!p_enabled) { set_window_position(last_position_before_fs); } else { last_position_before_fs = get_window_position(); } current_videomode.fullscreen = p_enabled; } bool OS_X11::is_window_fullscreen() const { return current_videomode.fullscreen; } void OS_X11::set_window_resizable(bool p_enabled) { XSizeHints *xsh; xsh = XAllocSizeHints(); if (!p_enabled) { Size2 size = get_window_size(); xsh->flags = PMinSize | PMaxSize; xsh->min_width = size.x; xsh->max_width = size.x; xsh->min_height = size.y; xsh->max_height = size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); current_videomode.resizable = p_enabled; XFlush(x11_display); } bool OS_X11::is_window_resizable() const { return current_videomode.resizable; } void OS_X11::set_window_minimized(bool p_enabled) { if (is_no_window_mode_enabled()) { return; } // Using ICCCM -- Inter-Client Communication Conventions Manual XEvent xev; Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_change; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? WM_IconicState : WM_NormalState; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = _NET_WM_STATE_ADD; xev.xclient.data.l[1] = wm_hidden; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); } bool OS_X11::is_window_minimized() const { // Using ICCCM -- Inter-Client Communication Conventions Manual Atom property = XInternAtom(x11_display, "WM_STATE", True); if (property == None) { return false; } Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; bool retval = false; int result = XGetWindowProperty( x11_display, x11_window, property, 0, 32, False, AnyPropertyType, &type, &format, &len, &remaining, &data); if (result == Success) { long *state = (long *)data; if (state[0] == WM_IconicState) { retval = true; } XFree(data); } return retval; } void OS_X11::set_window_maximized(bool p_enabled) { if (is_no_window_mode_enabled()) { return; } if (is_window_maximized() == p_enabled) return; // Using EWMH -- Extended Window Manager Hints XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False); Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.xclient.data.l[1] = wm_max_horz; xev.xclient.data.l[2] = wm_max_vert; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); if (p_enabled && is_window_maximize_allowed()) { // Wait for effective resizing (so the GLX context is too). // Give up after 0.5s, it's not going to happen on this WM. // https://github.com/godotengine/godot/issues/19978 for (int attempt = 0; !is_window_maximized() && attempt < 50; attempt++) { usleep(10000); } } maximized = p_enabled; } // Just a helper to reduce code duplication in `is_window_maximize_allowed` // and `is_window_maximized`. bool OS_X11::window_maximize_check(const char *p_atom_name) const { Atom property = XInternAtom(x11_display, p_atom_name, False); Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; bool retval = false; if (property == None) { return false; } int result = XGetWindowProperty( x11_display, x11_window, property, 0, 1024, False, XA_ATOM, &type, &format, &len, &remaining, &data); if (result == Success) { Atom *atoms = (Atom *)data; Atom wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False); Atom wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_VERT", False); bool found_wm_act_max_horz = false; bool found_wm_act_max_vert = false; for (uint64_t i = 0; i < len; i++) { if (atoms[i] == wm_act_max_horz) found_wm_act_max_horz = true; if (atoms[i] == wm_act_max_vert) found_wm_act_max_vert = true; if (found_wm_act_max_horz || found_wm_act_max_vert) { retval = true; break; } } XFree(data); } return retval; } bool OS_X11::is_window_maximize_allowed() const { return window_maximize_check("_NET_WM_ALLOWED_ACTIONS"); } bool OS_X11::is_window_maximized() const { // Using EWMH -- Extended Window Manager Hints return window_maximize_check("_NET_WM_STATE"); } void OS_X11::set_window_always_on_top(bool p_enabled) { if (is_window_always_on_top() == p_enabled) return; if (p_enabled && current_videomode.fullscreen) { // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity) set_window_maximized(true); } set_wm_above(p_enabled); if (!p_enabled && !current_videomode.fullscreen) { // Restore set_window_maximized(false); } current_videomode.always_on_top = p_enabled; } bool OS_X11::is_window_always_on_top() const { return current_videomode.always_on_top; } bool OS_X11::is_window_focused() const { return window_focused; } void OS_X11::set_borderless_window(bool p_borderless) { if (get_borderless_window() == p_borderless) return; current_videomode.borderless_window = p_borderless; Hints hints; Atom property; hints.flags = 2; hints.decorations = current_videomode.borderless_window ? 0 : 1; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } // Preserve window size set_window_size(Size2(current_videomode.width, current_videomode.height)); } bool OS_X11::get_borderless_window() { bool borderless = current_videomode.borderless_window; Atom prop = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; if (XGetWindowProperty(x11_display, x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (data && (format == 32) && (len >= 5)) { borderless = !((Hints *)data)->decorations; } XFree(data); } } return borderless; } void OS_X11::request_attention() { // Using EWMH -- Extended Window Manager Hints // // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE // Will be unset by the window manager after user react on the request for attention XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = _NET_WM_STATE_ADD; xev.xclient.data.l[1] = wm_attention; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(x11_display); } void *OS_X11::get_native_handle(int p_handle_type) { switch (p_handle_type) { case APPLICATION_HANDLE: return NULL; // Do we have a value to return here? case DISPLAY_HANDLE: return (void *)x11_display; case WINDOW_HANDLE: return (void *)x11_window; case WINDOW_VIEW: return NULL; // Do we have a value to return here? case OPENGL_CONTEXT: return context_gl->get_glx_context(); default: return NULL; } } void OS_X11::get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) { state->set_shift((p_x11_state & ShiftMask)); state->set_control((p_x11_state & ControlMask)); state->set_alt((p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/)); //altgr should not count as alt state->set_metakey((p_x11_state & Mod4Mask)); } unsigned int OS_X11::get_mouse_button_state(unsigned int p_x11_button, int p_x11_type) { unsigned int mask = 1 << (p_x11_button - 1); if (p_x11_type == ButtonPress) { last_button_state |= mask; } else { last_button_state &= ~mask; } return last_button_state; } void OS_X11::_handle_key_event(XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo) { // X11 functions don't know what const is XKeyEvent *xkeyevent = p_event; // This code was pretty difficult to write. // The docs stink and every toolkit seems to // do it in a different way. /* Phase 1, obtain a proper keysym */ // This was also very difficult to figure out. // You'd expect you could just use Keysym provided by // XKeycodeToKeysym to obtain internationalized // input.. WRONG!! // you must use XLookupString (???) which not only wastes // cycles generating an unnecessary string, but also // still works in half the cases. (won't handle deadkeys) // For more complex input methods (deadkeys and more advanced) // you have to use XmbLookupString (??). // So.. then you have to chosse which of both results // you want to keep. // This is a real bizarreness and cpu waster. KeySym keysym_keycode = 0; // keysym used to find a keycode KeySym keysym_unicode = 0; // keysym used to find unicode // XLookupString returns keysyms usable as nice scancodes/ char str[256 + 1]; XKeyEvent xkeyevent_no_mod = *xkeyevent; xkeyevent_no_mod.state &= ~ShiftMask; xkeyevent_no_mod.state &= ~ControlMask; XLookupString(xkeyevent, str, 256, &keysym_unicode, NULL); XLookupString(&xkeyevent_no_mod, NULL, 0, &keysym_keycode, NULL); // Meanwhile, XLookupString returns keysyms useful for unicode. if (!xmbstring) { // keep a temporary buffer for the string xmbstring = (char *)memalloc(sizeof(char) * 8); xmblen = 8; } if (xkeyevent->type == KeyPress && xic) { Status status; #ifdef X_HAVE_UTF8_STRING int utf8len = 8; char *utf8string = (char *)memalloc(sizeof(char) * utf8len); int utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string, utf8len - 1, &keysym_unicode, &status); if (status == XBufferOverflow) { utf8len = utf8bytes + 1; utf8string = (char *)memrealloc(utf8string, utf8len); utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string, utf8len - 1, &keysym_unicode, &status); } utf8string[utf8bytes] = '\0'; if (status == XLookupChars) { bool keypress = xkeyevent->type == KeyPress; unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode); if (keycode >= 'a' && keycode <= 'z') keycode -= 'a' - 'A'; String tmp; tmp.parse_utf8(utf8string, utf8bytes); for (int i = 0; i < tmp.length(); i++) { Ref<InputEventKey> k; k.instance(); if (keycode == 0 && tmp[i] == 0) { continue; } get_key_modifier_state(xkeyevent->state, k); k->set_unicode(tmp[i]); k->set_pressed(keypress); k->set_scancode(keycode); k->set_echo(false); if (k->get_scancode() == KEY_BACKTAB) { //make it consistent across platforms. k->set_scancode(KEY_TAB); k->set_shift(true); } input->accumulate_input_event(k); } memfree(utf8string); return; } memfree(utf8string); #else do { int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status); xmbstring[mnbytes] = '\0'; if (status == XBufferOverflow) { xmblen = mnbytes + 1; xmbstring = (char *)memrealloc(xmbstring, xmblen); } } while (status == XBufferOverflow); #endif } /* Phase 2, obtain a pigui keycode from the keysym */ // KeyMappingX11 just translated the X11 keysym to a PIGUI // keysym, so it works in all platforms the same. unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode); /* Phase 3, obtain a unicode character from the keysym */ // KeyMappingX11 also translates keysym to unicode. // It does a binary search on a table to translate // most properly. unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0; /* Phase 4, determine if event must be filtered */ // This seems to be a side-effect of using XIM. // XFilterEvent looks like a core X11 function, // but it's actually just used to see if we must // ignore a deadkey, or events XIM determines // must not reach the actual gui. // Guess it was a design problem of the extension bool keypress = xkeyevent->type == KeyPress; if (keycode == 0 && unicode == 0) return; /* Phase 5, determine modifier mask */ // No problems here, except I had no way to // know Mod1 was ALT and Mod4 was META (applekey/winkey) // just tried Mods until i found them. //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask)); Ref<InputEventKey> k; k.instance(); get_key_modifier_state(xkeyevent->state, k); /* Phase 6, determine echo character */ // Echo characters in X11 are a keyrelease and a keypress // one after the other with the (almot) same timestamp. // To detect them, i compare to the next event in list and // check that their difference in time is below a threshold. if (xkeyevent->type != KeyPress) { p_echo = false; // make sure there are events pending, // so this call won't block. if (p_event_index + 1 < p_events.size()) { XEvent &peek_event = p_events[p_event_index + 1]; // I'm using a threshold of 5 msecs, // since sometimes there seems to be a little // jitter. I'm still not convinced that all this approach // is correct, but the xorg developers are // not very helpful today. ::Time tresh = ABSDIFF(peek_event.xkey.time, xkeyevent->time); if (peek_event.type == KeyPress && tresh < 5) { KeySym rk; XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, NULL); if (rk == keysym_keycode) { // Consume to next event. ++p_event_index; _handle_key_event((XKeyEvent *)&peek_event, p_events, p_event_index, true); return; //ignore current, echo next } } // use the time from peek_event so it always works } // save the time to check for echo when keypress happens } /* Phase 7, send event to Window */ k->set_pressed(keypress); if (keycode >= 'a' && keycode <= 'z') keycode -= 'a' - 'A'; k->set_scancode(keycode); k->set_unicode(unicode); k->set_echo(p_echo); if (k->get_scancode() == KEY_BACKTAB) { //make it consistent across platforms. k->set_scancode(KEY_TAB); k->set_shift(true); } //don't set mod state if modifier keys are released by themselves //else event.is_action() will not work correctly here if (!k->is_pressed()) { if (k->get_scancode() == KEY_SHIFT) k->set_shift(false); else if (k->get_scancode() == KEY_CONTROL) k->set_control(false); else if (k->get_scancode() == KEY_ALT) k->set_alt(false); else if (k->get_scancode() == KEY_META) k->set_metakey(false); } bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_scancode()); if (k->is_pressed()) { if (last_is_pressed) { k->set_echo(true); } } //printf("key: %x\n",k->get_scancode()); input->accumulate_input_event(k); } Atom OS_X11::_process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property) const { if (p_target == XInternAtom(x11_display, "TARGETS", 0)) { // Request to list all supported targets. Atom data[9]; data[0] = XInternAtom(x11_display, "TARGETS", 0); data[1] = XInternAtom(x11_display, "SAVE_TARGETS", 0); data[2] = XInternAtom(x11_display, "MULTIPLE", 0); data[3] = XInternAtom(x11_display, "UTF8_STRING", 0); data[4] = XInternAtom(x11_display, "COMPOUND_TEXT", 0); data[5] = XInternAtom(x11_display, "TEXT", 0); data[6] = XA_STRING; data[7] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0); data[8] = XInternAtom(x11_display, "text/plain", 0); XChangeProperty(x11_display, p_requestor, p_property, XA_ATOM, 32, PropModeReplace, (unsigned char *)&data, sizeof(data) / sizeof(data[0])); return p_property; } else if (p_target == XInternAtom(x11_display, "SAVE_TARGETS", 0)) { // Request to check if SAVE_TARGETS is supported, nothing special to do. XChangeProperty(x11_display, p_requestor, p_property, XInternAtom(x11_display, "NULL", False), 32, PropModeReplace, NULL, 0); return p_property; } else if (p_target == XInternAtom(x11_display, "UTF8_STRING", 0) || p_target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) || p_target == XInternAtom(x11_display, "TEXT", 0) || p_target == XA_STRING || p_target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) || p_target == XInternAtom(x11_display, "text/plain", 0)) { // Directly using internal clipboard because we know our window // is the owner during a selection request. CharString clip = OS::get_clipboard().utf8(); XChangeProperty(x11_display, p_requestor, p_property, p_target, 8, PropModeReplace, (unsigned char *)clip.get_data(), clip.length()); return p_property; } else { char *target_name = XGetAtomName(x11_display, p_target); printf("Target '%s' not supported.\n", target_name); if (target_name) { XFree(target_name); } return None; } } void OS_X11::_handle_selection_request_event(XSelectionRequestEvent *p_event) const { XEvent respond; if (p_event->target == XInternAtom(x11_display, "MULTIPLE", 0)) { // Request for multiple target conversions at once. Atom atom_pair = XInternAtom(x11_display, "ATOM_PAIR", False); respond.xselection.property = None; Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; if (XGetWindowProperty(x11_display, p_event->requestor, p_event->property, 0, LONG_MAX, False, atom_pair, &type, &format, &len, &remaining, &data) == Success) { if ((len >= 2) && data) { Atom *targets = (Atom *)data; for (uint64_t i = 0; i < len; i += 2) { Atom target = targets[i]; Atom &property = targets[i + 1]; property = _process_selection_request_target(target, p_event->requestor, property); } XChangeProperty(x11_display, p_event->requestor, p_event->property, atom_pair, 32, PropModeReplace, (unsigned char *)targets, len); respond.xselection.property = p_event->property; } XFree(data); } } else { // Request for target conversion. respond.xselection.property = _process_selection_request_target(p_event->target, p_event->requestor, p_event->property); } respond.xselection.type = SelectionNotify; respond.xselection.display = p_event->display; respond.xselection.requestor = p_event->requestor; respond.xselection.selection = p_event->selection; respond.xselection.target = p_event->target; respond.xselection.time = p_event->time; XSendEvent(x11_display, p_event->requestor, True, NoEventMask, &respond); XFlush(x11_display); } struct Property { unsigned char *data; int format, nitems; Atom type; }; static Property read_property(Display *p_display, Window p_window, Atom p_property) { Atom actual_type = None; int actual_format = 0; unsigned long nitems = 0; unsigned long bytes_after = 0; unsigned char *ret = 0; int read_bytes = 1024; //Keep trying to read the property until there are no //bytes unread. if (p_property != None) { do { if (ret != 0) XFree(ret); XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType, &actual_type, &actual_format, &nitems, &bytes_after, &ret); read_bytes *= 2; } while (bytes_after != 0); } Property p = { ret, actual_format, (int)nitems, actual_type }; return p; } static Atom pick_target_from_list(Display *p_display, Atom *p_list, int p_count) { static const char *target_type = "text/uri-list"; for (int i = 0; i < p_count; i++) { Atom atom = p_list[i]; if (atom != None && String(XGetAtomName(p_display, atom)) == target_type) return atom; } return None; } static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) { static const char *target_type = "text/uri-list"; if (p_t1 != None && String(XGetAtomName(p_disp, p_t1)) == target_type) return p_t1; if (p_t2 != None && String(XGetAtomName(p_disp, p_t2)) == target_type) return p_t2; if (p_t3 != None && String(XGetAtomName(p_disp, p_t3)) == target_type) return p_t3; return None; } void OS_X11::_window_changed(XEvent *event) { if (xic) { // Not portable. set_ime_position(Point2(0, 1)); } if ((event->xconfigure.width == current_videomode.width) && (event->xconfigure.height == current_videomode.height)) return; current_videomode.width = event->xconfigure.width; current_videomode.height = event->xconfigure.height; } void OS_X11::_poll_events_thread(void *ud) { OS_X11 *os = (OS_X11 *)ud; os->_poll_events(); } Bool OS_X11::_predicate_all_events(Display *display, XEvent *event, XPointer arg) { // Just accept all events. return True; } bool OS_X11::_wait_for_events() const { int x11_fd = ConnectionNumber(x11_display); fd_set in_fds; XFlush(x11_display); FD_ZERO(&in_fds); FD_SET(x11_fd, &in_fds); struct timeval tv; tv.tv_usec = 0; tv.tv_sec = 1; // Wait for next event or timeout. int num_ready_fds = select(x11_fd + 1, &in_fds, NULL, NULL, &tv); if (num_ready_fds > 0) { // Event received. return true; } else { // Error or timeout. if (num_ready_fds < 0) { ERR_PRINT("_wait_for_events: select error: " + itos(errno)); } return false; } } void OS_X11::_poll_events() { while (!events_thread_done) { _wait_for_events(); // Process events from the queue. { MutexLock mutex_lock(events_mutex); // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_all_events, NULL)) { // Check if the input manager wants to process the event. if (XFilterEvent(&ev, None)) { // Event has been filtered by the Input Manager, // it has to be ignored and a new one will be received. continue; } // Handle selection request events directly in the event thread, because // communication through the x server takes several events sent back and forth // and we don't want to block other programs while processing only one each frame. if (ev.type == SelectionRequest) { _handle_selection_request_event(&(ev.xselectionrequest)); continue; } polled_events.push_back(ev); } } } } void OS_X11::process_xevents() { //printf("checking events %i\n", XPending(x11_display)); do_mouse_warp = false; // Is the current mouse mode one where it needs to be grabbed. bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED; xi.pressure = 0; xi.tilt = Vector2(); xi.pressure_supported = false; LocalVector<XEvent> events; { // Block events polling while flushing events. MutexLock mutex_lock(events_mutex); events = polled_events; polled_events.clear(); } for (uint32_t event_index = 0; event_index < events.size(); ++event_index) { XEvent &event = events[event_index]; if (XGetEventData(x11_display, &event.xcookie)) { if (event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) { XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data; int index = event_data->detail; Vector2 pos = Vector2(event_data->event_x, event_data->event_y); switch (event_data->evtype) { case XI_HierarchyChanged: case XI_DeviceChanged: { refresh_device_info(); } break; case XI_RawMotion: { XIRawEvent *raw_event = (XIRawEvent *)event_data; int device_id = raw_event->deviceid; // Determine the axis used (called valuators in XInput for some forsaken reason) // Mask is a bitmask indicating which axes are involved. // We are interested in the values of axes 0 and 1. if (raw_event->valuators.mask_len <= 0) { break; } const double *values = raw_event->raw_values; double rel_x = 0.0; double rel_y = 0.0; if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSX)) { rel_x = *values; values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSY)) { rel_y = *values; values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_PRESSURE)) { Map<int, Vector2>::Element *pen_pressure = xi.pen_pressure_range.find(device_id); if (pen_pressure) { Vector2 pen_pressure_range = pen_pressure->value(); if (pen_pressure_range != Vector2()) { xi.pressure_supported = true; xi.pressure = (*values - pen_pressure_range[0]) / (pen_pressure_range[1] - pen_pressure_range[0]); } } values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTX)) { Map<int, Vector2>::Element *pen_tilt_x = xi.pen_tilt_x_range.find(device_id); if (pen_tilt_x) { Vector2 pen_tilt_x_range = pen_tilt_x->value(); if (pen_tilt_x_range != Vector2()) { xi.tilt.x = ((*values - pen_tilt_x_range[0]) / (pen_tilt_x_range[1] - pen_tilt_x_range[0])) * 2 - 1; } } values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTY)) { Map<int, Vector2>::Element *pen_tilt_y = xi.pen_tilt_y_range.find(device_id); if (pen_tilt_y) { Vector2 pen_tilt_y_range = pen_tilt_y->value(); if (pen_tilt_y_range != Vector2()) { xi.tilt.y = ((*values - pen_tilt_y_range[0]) / (pen_tilt_y_range[1] - pen_tilt_y_range[0])) * 2 - 1; } } values++; } // https://bugs.freedesktop.org/show_bug.cgi?id=71609 // http://lists.libsdl.org/pipermail/commits-libsdl.org/2015-June/000282.html if (raw_event->time == xi.last_relative_time && rel_x == xi.relative_motion.x && rel_y == xi.relative_motion.y) { break; // Flush duplicate to avoid overly fast motion } xi.old_raw_pos.x = xi.raw_pos.x; xi.old_raw_pos.y = xi.raw_pos.y; xi.raw_pos.x = rel_x; xi.raw_pos.y = rel_y; Map<int, Vector2>::Element *abs_info = xi.absolute_devices.find(device_id); if (abs_info) { // Absolute mode device Vector2 mult = abs_info->value(); xi.relative_motion.x += (xi.raw_pos.x - xi.old_raw_pos.x) * mult.x; xi.relative_motion.y += (xi.raw_pos.y - xi.old_raw_pos.y) * mult.y; } else { // Relative mode device xi.relative_motion.x = xi.raw_pos.x; xi.relative_motion.y = xi.raw_pos.y; } xi.last_relative_time = raw_event->time; } break; #ifdef TOUCH_ENABLED case XI_TouchBegin: // Fall-through // Disabled hand-in-hand with the grabbing //XIAllowTouchEvents(x11_display, event_data->deviceid, event_data->detail, x11_window, XIAcceptTouch); case XI_TouchEnd: { bool is_begin = event_data->evtype == XI_TouchBegin; Ref<InputEventScreenTouch> st; st.instance(); st->set_index(index); st->set_position(pos); st->set_pressed(is_begin); if (is_begin) { if (xi.state.has(index)) // Defensive break; xi.state[index] = pos; if (xi.state.size() == 1) { // X11 may send a motion event when a touch gesture begins, that would result // in a spurious mouse motion event being sent to Godot; remember it to be able to filter it out xi.mouse_pos_to_filter = pos; } input->accumulate_input_event(st); } else { if (!xi.state.has(index)) // Defensive break; xi.state.erase(index); input->accumulate_input_event(st); } } break; case XI_TouchUpdate: { Map<int, Vector2>::Element *curr_pos_elem = xi.state.find(index); if (!curr_pos_elem) { // Defensive break; } if (curr_pos_elem->value() != pos) { Ref<InputEventScreenDrag> sd; sd.instance(); sd->set_index(index); sd->set_position(pos); sd->set_relative(pos - curr_pos_elem->value()); input->accumulate_input_event(sd); curr_pos_elem->value() = pos; } } break; #endif } } } XFreeEventData(x11_display, &event.xcookie); switch (event.type) { case Expose: Main::force_redraw(); break; case NoExpose: minimized = true; break; case VisibilityNotify: { XVisibilityEvent *visibility = (XVisibilityEvent *)&event; minimized = (visibility->state == VisibilityFullyObscured); } break; case LeaveNotify: { if (main_loop && !mouse_mode_grab) main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT); } break; case EnterNotify: { if (main_loop && !mouse_mode_grab) main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER); } break; case FocusIn: minimized = false; window_has_focus = true; main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); window_focused = true; if (mouse_mode_grab) { // Show and update the cursor if confined and the window regained focus. if (mouse_mode == MOUSE_MODE_CONFINED) XUndefineCursor(x11_display, x11_window); else if (mouse_mode == MOUSE_MODE_CAPTURED) // or re-hide it in captured mode XDefineCursor(x11_display, x11_window, null_cursor); XGrabPointer( x11_display, x11_window, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime); } #ifdef TOUCH_ENABLED // Grab touch devices to avoid OS gesture interference /*for (int i = 0; i < xi.touch_devices.size(); ++i) { XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask); }*/ #endif if (xic) { // Block events polling while changing input focus // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XSetICFocus(xic); } break; case FocusOut: window_has_focus = false; input->release_pressed_events(); main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); window_focused = false; if (mouse_mode_grab) { //dear X11, I try, I really try, but you never work, you do whathever you want. if (mouse_mode == MOUSE_MODE_CAPTURED) { // Show the cursor if we're in captured mode so it doesn't look weird. XUndefineCursor(x11_display, x11_window); } XUngrabPointer(x11_display, CurrentTime); } #ifdef TOUCH_ENABLED // Ungrab touch devices so input works as usual while we are unfocused /*for (int i = 0; i < xi.touch_devices.size(); ++i) { XIUngrabDevice(x11_display, xi.touch_devices[i], CurrentTime); }*/ // Release every pointer to avoid sticky points for (Map<int, Vector2>::Element *E = xi.state.front(); E; E = E->next()) { Ref<InputEventScreenTouch> st; st.instance(); st->set_index(E->key()); st->set_position(E->get()); input->accumulate_input_event(st); } xi.state.clear(); #endif if (xic) { // Block events polling while changing input focus // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XUnsetICFocus(xic); } break; case ConfigureNotify: _window_changed(&event); break; case ButtonPress: case ButtonRelease: { /* exit in case of a mouse button press */ last_timestamp = event.xbutton.time; if (mouse_mode == MOUSE_MODE_CAPTURED) { event.xbutton.x = last_mouse_pos.x; event.xbutton.y = last_mouse_pos.y; } Ref<InputEventMouseButton> mb; mb.instance(); get_key_modifier_state(event.xbutton.state, mb); mb->set_button_index(event.xbutton.button); if (mb->get_button_index() == 2) mb->set_button_index(3); else if (mb->get_button_index() == 3) mb->set_button_index(2); mb->set_button_mask(get_mouse_button_state(mb->get_button_index(), event.xbutton.type)); mb->set_position(Vector2(event.xbutton.x, event.xbutton.y)); mb->set_global_position(mb->get_position()); mb->set_pressed((event.type == ButtonPress)); if (event.type == ButtonPress) { uint64_t diff = get_ticks_usec() / 1000 - last_click_ms; if (mb->get_button_index() == last_click_button_index) { if (diff < 400 && Point2(last_click_pos).distance_to(Point2(event.xbutton.x, event.xbutton.y)) < 5) { last_click_ms = 0; last_click_pos = Point2(-100, -100); last_click_button_index = -1; mb->set_doubleclick(true); } } else if (mb->get_button_index() < 4 || mb->get_button_index() > 7) { last_click_button_index = mb->get_button_index(); } if (!mb->is_doubleclick()) { last_click_ms += diff; last_click_pos = Point2(event.xbutton.x, event.xbutton.y); } } input->accumulate_input_event(mb); } break; case MotionNotify: { // The X11 API requires filtering one-by-one through the motion // notify events, in order to figure out which event is the one // generated by warping the mouse pointer. while (true) { if (mouse_mode == MOUSE_MODE_CAPTURED && event.xmotion.x == current_videomode.width / 2 && event.xmotion.y == current_videomode.height / 2) { //this is likely the warp event since it was warped here center = Vector2(event.xmotion.x, event.xmotion.y); break; } if (event_index + 1 < events.size()) { const XEvent &next_event = events[event_index + 1]; if (next_event.type == MotionNotify) { ++event_index; event = next_event; } else { break; } } else { break; } } last_timestamp = event.xmotion.time; // Motion is also simple. // A little hack is in order // to be able to send relative motion events. Point2 pos(event.xmotion.x, event.xmotion.y); // Avoidance of spurious mouse motion (see handling of touch) bool filter = false; // Adding some tolerance to match better Point2i to Vector2 if (xi.state.size() && Vector2(pos).distance_squared_to(xi.mouse_pos_to_filter) < 2) { filter = true; } // Invalidate to avoid filtering a possible legitimate similar event coming later xi.mouse_pos_to_filter = Vector2(1e10, 1e10); if (filter) { break; } if (mouse_mode == MOUSE_MODE_CAPTURED) { if (xi.relative_motion.x == 0 && xi.relative_motion.y == 0) { break; } Point2i new_center = pos; pos = last_mouse_pos + xi.relative_motion; center = new_center; do_mouse_warp = window_has_focus; // warp the cursor if we're focused in } if (!last_mouse_pos_valid) { last_mouse_pos = pos; last_mouse_pos_valid = true; } // Hackish but relative mouse motion is already handled in the RawMotion event. // RawMotion does not provide the absolute mouse position (whereas MotionNotify does). // Therefore, RawMotion cannot be the authority on absolute mouse position. // RawMotion provides more precision than MotionNotify, which doesn't sense subpixel motion. // Therefore, MotionNotify cannot be the authority on relative mouse motion. // This means we need to take a combined approach... Point2 rel; // Only use raw input if in capture mode. Otherwise use the classic behavior. if (mouse_mode == MOUSE_MODE_CAPTURED) { rel = xi.relative_motion; } else { rel = pos - last_mouse_pos; } // Reset to prevent lingering motion xi.relative_motion.x = 0; xi.relative_motion.y = 0; if (mouse_mode == MOUSE_MODE_CAPTURED) { pos = Point2i(current_videomode.width / 2, current_videomode.height / 2); } Ref<InputEventMouseMotion> mm; mm.instance(); if (xi.pressure_supported) { mm->set_pressure(xi.pressure); } else { mm->set_pressure((get_mouse_button_state() & (1 << (BUTTON_LEFT - 1))) ? 1.0f : 0.0f); } mm->set_tilt(xi.tilt); // Make the absolute position integral so it doesn't look _too_ weird :) Point2i posi(pos); get_key_modifier_state(event.xmotion.state, mm); mm->set_button_mask(get_mouse_button_state()); mm->set_position(posi); mm->set_global_position(posi); input->set_mouse_position(posi); mm->set_speed(input->get_last_mouse_speed()); mm->set_relative(rel); last_mouse_pos = pos; // printf("rel: %d,%d\n", rel.x, rel.y ); // Don't propagate the motion event unless we have focus // this is so that the relative motion doesn't get messed up // after we regain focus. if (window_has_focus || !mouse_mode_grab) input->accumulate_input_event(mm); } break; case KeyPress: case KeyRelease: { last_timestamp = event.xkey.time; // key event is a little complex, so // it will be handled in its own function. _handle_key_event((XKeyEvent *)&event, events, event_index); } break; case SelectionNotify: if (event.xselection.target == requested) { Property p = read_property(x11_display, x11_window, XInternAtom(x11_display, "PRIMARY", 0)); Vector<String> files = String((char *)p.data).split("\n", false); for (int i = 0; i < files.size(); i++) { files.write[i] = files[i].replace("file://", "").http_unescape().strip_edges(); } main_loop->drop_files(files); //Reply that all is well. XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = x11_display; m.window = xdnd_source_window; m.message_type = xdnd_finished; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = 1; m.data.l[2] = xdnd_action_copy; //We only ever copy. XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m); } break; case ClientMessage: if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete) main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST); else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) { //File(s) have been dragged over the window, check for supported target (text/uri-list) xdnd_version = (event.xclient.data.l[1] >> 24); Window source = event.xclient.data.l[0]; bool more_than_3 = event.xclient.data.l[1] & 1; if (more_than_3) { Property p = read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False)); requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems); } else requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]); } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) { //xdnd position event, reply with an XDND status message //just depending on type of data for now XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = event.xclient.display; m.window = event.xclient.data.l[0]; m.message_type = xdnd_status; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = (requested != None); m.data.l[2] = 0; //empty rectangle m.data.l[3] = 0; m.data.l[4] = xdnd_action_copy; XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m); XFlush(x11_display); } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) { if (requested != None) { xdnd_source_window = event.xclient.data.l[0]; if (xdnd_version >= 1) XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, event.xclient.data.l[2]); else XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, CurrentTime); } else { //Reply that we're not interested. XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = event.xclient.display; m.window = event.xclient.data.l[0]; m.message_type = xdnd_finished; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = 0; m.data.l[2] = None; //Failed. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m); } } break; default: break; } } XFlush(x11_display); if (do_mouse_warp) { XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)current_videomode.width / 2, (int)current_videomode.height / 2); /* Window root, child; int root_x, root_y; int win_x, win_y; unsigned int mask; XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask ); printf("Root: %d,%d\n", root_x, root_y); printf("Win: %d,%d\n", win_x, win_y); */ } input->flush_accumulated_events(); } MainLoop *OS_X11::get_main_loop() const { return main_loop; } void OS_X11::delete_main_loop() { // Send owned clipboard data to clipboard manager before exit. // This has to be done here because the clipboard data is cleared before finalize(). _clipboard_transfer_ownership(XA_PRIMARY, x11_window); _clipboard_transfer_ownership(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window); if (main_loop) memdelete(main_loop); main_loop = NULL; } void OS_X11::set_main_loop(MainLoop *p_main_loop) { main_loop = p_main_loop; input->set_main_loop(p_main_loop); } bool OS_X11::can_draw() const { return !minimized; }; void OS_X11::set_clipboard(const String &p_text) { { // The clipboard content can be accessed while polling for events. MutexLock mutex_lock(events_mutex); OS::set_clipboard(p_text); } XSetSelectionOwner(x11_display, XA_PRIMARY, x11_window, CurrentTime); XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), x11_window, CurrentTime); }; Bool OS_X11::_predicate_clipboard_selection(Display *display, XEvent *event, XPointer arg) { if (event->type == SelectionNotify && event->xselection.requestor == *(Window *)arg) { return True; } else { return False; } } Bool OS_X11::_predicate_clipboard_incr(Display *display, XEvent *event, XPointer arg) { if (event->type == PropertyNotify && event->xproperty.state == PropertyNewValue) { return True; } else { return False; } } String OS_X11::_get_clipboard_impl(Atom p_source, Window x11_window, Atom target) const { String ret; Window selection_owner = XGetSelectionOwner(x11_display, p_source); if (selection_owner == x11_window) { return OS::get_clipboard(); } if (selection_owner != None) { // Block events polling while processing selection events. MutexLock mutex_lock(events_mutex); Atom selection = XA_PRIMARY; XConvertSelection(x11_display, p_source, target, selection, x11_window, CurrentTime); XFlush(x11_display); // Blocking wait for predicate to be True and remove the event from the queue. XEvent event; XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window); // Do not get any data, see how much data is there. Atom type; int format, result; unsigned long len, bytes_left, dummy; unsigned char *data; XGetWindowProperty(x11_display, x11_window, selection, // Tricky.. 0, 0, // offset - len 0, // Delete 0==FALSE AnyPropertyType, // flag &type, // return type &format, // return format &len, &bytes_left, // data length &data); if (data) { XFree(data); } if (type == XInternAtom(x11_display, "INCR", 0)) { // Data is going to be received incrementally. LocalVector<uint8_t> incr_data; uint32_t data_size = 0; bool success = false; // Delete INCR property to notify the owner. XDeleteProperty(x11_display, x11_window, type); // Process events from the queue. bool done = false; while (!done) { if (!_wait_for_events()) { // Error or timeout, abort. break; } // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, NULL)) { result = XGetWindowProperty(x11_display, x11_window, selection, // selection type 0, LONG_MAX, // offset - len True, // delete property to notify the owner AnyPropertyType, // flag &type, // return type &format, // return format &len, &bytes_left, // data length &data); if (result == Success) { if (data && (len > 0)) { uint32_t prev_size = incr_data.size(); if (prev_size == 0) { // First property contains initial data size. unsigned long initial_size = *(unsigned long *)data; incr_data.resize(initial_size); } else { // New chunk, resize to be safe and append data. incr_data.resize(MAX(data_size + len, prev_size)); memcpy(incr_data.ptr() + data_size, data, len); data_size += len; } } else { // Last chunk, process finished. done = true; success = true; } } else { printf("Failed to get selection data chunk.\n"); done = true; } if (data) { XFree(data); } if (done) { break; } } } if (success && (data_size > 0)) { ret.parse_utf8((const char *)incr_data.ptr(), data_size); } } else if (bytes_left > 0) { // Data is ready and can be processed all at once. result = XGetWindowProperty(x11_display, x11_window, selection, 0, bytes_left, 0, AnyPropertyType, &type, &format, &len, &dummy, &data); if (result == Success) { ret.parse_utf8((const char *)data); } else { printf("Failed to get selection data.\n"); } if (data) { XFree(data); } } } return ret; } String OS_X11::_get_clipboard(Atom p_source, Window x11_window) const { String ret; Atom utf8_atom = XInternAtom(x11_display, "UTF8_STRING", True); if (utf8_atom != None) { ret = _get_clipboard_impl(p_source, x11_window, utf8_atom); } if (ret.empty()) { ret = _get_clipboard_impl(p_source, x11_window, XA_STRING); } return ret; } String OS_X11::get_clipboard() const { String ret; ret = _get_clipboard(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window); if (ret.empty()) { ret = _get_clipboard(XA_PRIMARY, x11_window); }; return ret; } Bool OS_X11::_predicate_clipboard_save_targets(Display *display, XEvent *event, XPointer arg) { if (event->xany.window == *(Window *)arg) { return (event->type == SelectionRequest) || (event->type == SelectionNotify); } else { return False; } } void OS_X11::_clipboard_transfer_ownership(Atom p_source, Window x11_window) const { Window selection_owner = XGetSelectionOwner(x11_display, p_source); if (selection_owner != x11_window) { return; } // Block events polling while processing selection events. MutexLock mutex_lock(events_mutex); Atom clipboard_manager = XInternAtom(x11_display, "CLIPBOARD_MANAGER", False); Atom save_targets = XInternAtom(x11_display, "SAVE_TARGETS", False); XConvertSelection(x11_display, clipboard_manager, save_targets, None, x11_window, CurrentTime); // Process events from the queue. while (true) { if (!_wait_for_events()) { // Error or timeout, abort. break; } // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_save_targets, (XPointer)&x11_window)) { switch (ev.type) { case SelectionRequest: _handle_selection_request_event(&(ev.xselectionrequest)); break; case SelectionNotify: { if (ev.xselection.target == save_targets) { // Once SelectionNotify is received, we're done whether it succeeded or not. return; } break; } } } } } String OS_X11::get_name() const { return "X11"; } Error OS_X11::shell_open(String p_uri) { Error ok; int err_code; List<String> args; args.push_back(p_uri); // Agnostic ok = execute("xdg-open", args, true, NULL, NULL, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } // GNOME args.push_front("open"); // The command is `gio open`, so we need to add it to args ok = execute("gio", args, true, NULL, NULL, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } args.pop_front(); ok = execute("gvfs-open", args, true, NULL, NULL, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } // KDE ok = execute("kde-open5", args, true, NULL, NULL, &err_code); if (ok == OK && !err_code) { return OK; } ok = execute("kde-open", args, true, NULL, NULL, &err_code); return !err_code ? ok : FAILED; } bool OS_X11::_check_internal_feature_support(const String &p_feature) { return p_feature == "pc"; } String OS_X11::get_config_path() const { if (has_environment("XDG_CONFIG_HOME")) { return get_environment("XDG_CONFIG_HOME"); } else if (has_environment("HOME")) { return get_environment("HOME").plus_file(".config"); } else { return "."; } } String OS_X11::get_data_path() const { if (has_environment("XDG_DATA_HOME")) { return get_environment("XDG_DATA_HOME"); } else if (has_environment("HOME")) { return get_environment("HOME").plus_file(".local/share"); } else { return get_config_path(); } } String OS_X11::get_cache_path() const { if (has_environment("XDG_CACHE_HOME")) { return get_environment("XDG_CACHE_HOME"); } else if (has_environment("HOME")) { return get_environment("HOME").plus_file(".cache"); } else { return get_config_path(); } } String OS_X11::get_system_dir(SystemDir p_dir) const { String xdgparam; switch (p_dir) { case SYSTEM_DIR_DESKTOP: { xdgparam = "DESKTOP"; } break; case SYSTEM_DIR_DCIM: { xdgparam = "PICTURES"; } break; case SYSTEM_DIR_DOCUMENTS: { xdgparam = "DOCUMENTS"; } break; case SYSTEM_DIR_DOWNLOADS: { xdgparam = "DOWNLOAD"; } break; case SYSTEM_DIR_MOVIES: { xdgparam = "VIDEOS"; } break; case SYSTEM_DIR_MUSIC: { xdgparam = "MUSIC"; } break; case SYSTEM_DIR_PICTURES: { xdgparam = "PICTURES"; } break; case SYSTEM_DIR_RINGTONES: { xdgparam = "MUSIC"; } break; } String pipe; List<String> arg; arg.push_back(xdgparam); Error err = const_cast<OS_X11 *>(this)->execute("xdg-user-dir", arg, true, NULL, &pipe); if (err != OK) return "."; return pipe.strip_edges(); } void OS_X11::move_window_to_foreground() { XEvent xev; Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = net_active_window; xev.xclient.format = 32; xev.xclient.data.l[0] = 1; xev.xclient.data.l[1] = CurrentTime; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(x11_display); } void OS_X11::set_cursor_shape(CursorShape p_shape) { ERR_FAIL_INDEX(p_shape, CURSOR_MAX); if (p_shape == current_cursor) { return; } if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) { if (cursors[p_shape] != None) { XDefineCursor(x11_display, x11_window, cursors[p_shape]); } else if (cursors[CURSOR_ARROW] != None) { XDefineCursor(x11_display, x11_window, cursors[CURSOR_ARROW]); } } current_cursor = p_shape; } OS::CursorShape OS_X11::get_cursor_shape() const { return current_cursor; } void OS_X11::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) { if (p_cursor.is_valid()) { Map<CursorShape, Vector<Variant> >::Element *cursor_c = cursors_cache.find(p_shape); if (cursor_c) { if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) { set_cursor_shape(p_shape); return; } cursors_cache.erase(p_shape); } Ref<Texture> texture = p_cursor; Ref<AtlasTexture> atlas_texture = p_cursor; Ref<Image> image; Size2 texture_size; Rect2 atlas_rect; if (texture.is_valid()) { image = texture->get_data(); } if (!image.is_valid() && atlas_texture.is_valid()) { texture = atlas_texture->get_atlas(); atlas_rect.size.width = texture->get_width(); atlas_rect.size.height = texture->get_height(); atlas_rect.position.x = atlas_texture->get_region().position.x; atlas_rect.position.y = atlas_texture->get_region().position.y; texture_size.width = atlas_texture->get_region().size.x; texture_size.height = atlas_texture->get_region().size.y; } else if (image.is_valid()) { texture_size.width = texture->get_width(); texture_size.height = texture->get_height(); } ERR_FAIL_COND(!texture.is_valid()); ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0); ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256); ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height); image = texture->get_data(); ERR_FAIL_COND(!image.is_valid()); // Create the cursor structure XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height); XcursorUInt image_size = texture_size.width * texture_size.height; XcursorDim size = sizeof(XcursorPixel) * image_size; cursor_image->version = 1; cursor_image->size = size; cursor_image->xhot = p_hotspot.x; cursor_image->yhot = p_hotspot.y; // allocate memory to contain the whole file cursor_image->pixels = (XcursorPixel *)memalloc(size); image->lock(); for (XcursorPixel index = 0; index < image_size; index++) { int row_index = floor(index / texture_size.width) + atlas_rect.position.y; int column_index = (index % int(texture_size.width)) + atlas_rect.position.x; if (atlas_texture.is_valid()) { column_index = MIN(column_index, atlas_rect.size.width - 1); row_index = MIN(row_index, atlas_rect.size.height - 1); } *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32(); } image->unlock(); ERR_FAIL_COND(cursor_image->pixels == NULL); // Save it for a further usage cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image); Vector<Variant> params; params.push_back(p_cursor); params.push_back(p_hotspot); cursors_cache.insert(p_shape, params); if (p_shape == current_cursor) { if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) { XDefineCursor(x11_display, x11_window, cursors[p_shape]); } } memfree(cursor_image->pixels); XcursorImageDestroy(cursor_image); } else { // Reset to default system cursor if (img[p_shape]) { cursors[p_shape] = XcursorImageLoadCursor(x11_display, img[p_shape]); } CursorShape c = current_cursor; current_cursor = CURSOR_MAX; set_cursor_shape(c); cursors_cache.erase(p_shape); } } void OS_X11::release_rendering_thread() { #if defined(OPENGL_ENABLED) context_gl->release_current(); #endif } void OS_X11::make_rendering_thread() { #if defined(OPENGL_ENABLED) context_gl->make_current(); #endif } void OS_X11::swap_buffers() { #if defined(OPENGL_ENABLED) context_gl->swap_buffers(); #endif } void OS_X11::alert(const String &p_alert, const String &p_title) { if (is_no_window_mode_enabled()) { print_line("ALERT: " + p_title + ": " + p_alert); return; } const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" }; String path = get_environment("PATH"); Vector<String> path_elems = path.split(":", false); String program; for (int i = 0; i < path_elems.size(); i++) { for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) { String tested_path = path_elems[i].plus_file(message_programs[k]); if (FileAccess::exists(tested_path)) { program = tested_path; break; } } if (program.length()) break; } List<String> args; if (program.ends_with("zenity")) { args.push_back("--error"); args.push_back("--width"); args.push_back("500"); args.push_back("--title"); args.push_back(p_title); args.push_back("--text"); args.push_back(p_alert); } if (program.ends_with("kdialog")) { args.push_back("--error"); args.push_back(p_alert); args.push_back("--title"); args.push_back(p_title); } if (program.ends_with("Xdialog")) { args.push_back("--title"); args.push_back(p_title); args.push_back("--msgbox"); args.push_back(p_alert); args.push_back("0"); args.push_back("0"); } if (program.ends_with("xmessage")) { args.push_back("-center"); args.push_back("-title"); args.push_back(p_title); args.push_back(p_alert); } if (program.length()) { execute(program, args, true); } else { print_line(p_alert); } } bool g_set_icon_error = false; int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) { g_set_icon_error = true; return 0; } void OS_X11::set_icon(const Ref<Image> &p_icon) { int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler); Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False); if (p_icon.is_valid()) { Ref<Image> img = p_icon->duplicate(); img->convert(Image::FORMAT_RGBA8); while (true) { int w = img->get_width(); int h = img->get_height(); if (g_set_icon_error) { g_set_icon_error = false; WARN_PRINT("Icon too large, attempting to resize icon."); int new_width, new_height; if (w > h) { new_width = w / 2; new_height = h * new_width / w; } else { new_height = h / 2; new_width = w * new_height / h; } w = new_width; h = new_height; if (!w || !h) { WARN_PRINT("Unable to set icon."); break; } img->resize(w, h, Image::INTERPOLATE_CUBIC); } // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits Vector<long> pd; pd.resize(2 + w * h); pd.write[0] = w; pd.write[1] = h; PoolVector<uint8_t>::Read r = img->get_data().read(); long *wr = &pd.write[2]; uint8_t const *pr = r.ptr(); for (int i = 0; i < w * h; i++) { long v = 0; // A R G B v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2]; *wr++ = v; pr += 4; } if (net_wm_icon != None) { XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size()); } if (!g_set_icon_error) break; } } else { XDeleteProperty(x11_display, x11_window, net_wm_icon); } XFlush(x11_display); XSetErrorHandler(oldHandler); } void OS_X11::force_process_input() { process_xevents(); // get rid of pending events #ifdef JOYDEV_ENABLED joypad->process_joypads(); #endif } void OS_X11::run() { force_quit = false; if (!main_loop) return; main_loop->init(); //uint64_t last_ticks=get_ticks_usec(); //int frames=0; //uint64_t frame=0; while (!force_quit) { process_xevents(); // get rid of pending events #ifdef JOYDEV_ENABLED joypad->process_joypads(); #endif if (Main::iteration()) break; }; main_loop->finish(); } bool OS_X11::is_joy_known(int p_device) { return input->is_joy_mapped(p_device); } String OS_X11::get_joy_guid(int p_device) const { return input->get_joy_guid_remapped(p_device); } void OS_X11::_set_use_vsync(bool p_enable) { #if defined(OPENGL_ENABLED) if (context_gl) context_gl->set_use_vsync(p_enable); #endif } /* bool OS_X11::is_vsync_enabled() const { if (context_gl) return context_gl->is_using_vsync(); return true; } */ void OS_X11::set_context(int p_context) { XClassHint *classHint = XAllocClassHint(); if (classHint) { CharString name_str; switch (p_context) { case CONTEXT_EDITOR: name_str = "Godot_Editor"; break; case CONTEXT_PROJECTMAN: name_str = "Godot_ProjectList"; break; case CONTEXT_ENGINE: name_str = "Godot_Engine"; break; } CharString class_str; if (p_context == CONTEXT_ENGINE) { String config_name = GLOBAL_GET("application/config/name"); if (config_name.length() == 0) { class_str = "Godot_Engine"; } else { class_str = config_name.utf8(); } } else { class_str = "Godot"; } classHint->res_class = class_str.ptrw(); classHint->res_name = name_str.ptrw(); XSetClassHint(x11_display, x11_window, classHint); XFree(classHint); } } OS::PowerState OS_X11::get_power_state() { return power_manager->get_power_state(); } int OS_X11::get_power_seconds_left() { return power_manager->get_power_seconds_left(); } int OS_X11::get_power_percent_left() { return power_manager->get_power_percent_left(); } void OS_X11::disable_crash_handler() { crash_handler.disable(); } bool OS_X11::is_disable_crash_handler() const { return crash_handler.is_disabled(); } static String get_mountpoint(const String &p_path) { struct stat s; if (stat(p_path.utf8().get_data(), &s)) { return ""; } #ifdef HAVE_MNTENT dev_t dev = s.st_dev; FILE *fd = setmntent("/proc/mounts", "r"); if (!fd) { return ""; } struct mntent mnt; char buf[1024]; size_t buflen = 1024; while (getmntent_r(fd, &mnt, buf, buflen)) { if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) { endmntent(fd); return String(mnt.mnt_dir); } } endmntent(fd); #endif return ""; } Error OS_X11::move_to_trash(const String &p_path) { String trash_can = ""; String mnt = get_mountpoint(p_path); // If there is a directory "[Mountpoint]/.Trash-[UID]/files", use it as the trash can. if (mnt != "") { String path(mnt + "/.Trash-" + itos(getuid()) + "/files"); struct stat s; if (!stat(path.utf8().get_data(), &s)) { trash_can = path; } } // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash/files" as the trash can. if (trash_can == "") { char *dhome = getenv("XDG_DATA_HOME"); if (dhome) { trash_can = String(dhome) + "/Trash/files"; } } // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash/files" as the trash can. if (trash_can == "") { char *home = getenv("HOME"); if (home) { trash_can = String(home) + "/.local/share/Trash/files"; } } // Issue an error if none of the previous locations is appropriate for the trash can. if (trash_can == "") { ERR_PRINTS("move_to_trash: Could not determine the trash can location"); return FAILED; } // Create needed directories for decided trash can location. DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); Error err = dir_access->make_dir_recursive(trash_can); memdelete(dir_access); // Issue an error if trash can is not created proprely. if (err != OK) { ERR_PRINTS("move_to_trash: Could not create the trash can \"" + trash_can + "\""); return err; } // The trash can is successfully created, now move the given resource to it. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints. List<String> mv_args; mv_args.push_back(p_path); mv_args.push_back(trash_can); int retval; err = execute("mv", mv_args, true, NULL, NULL, &retval); // Issue an error if "mv" failed to move the given resource to the trash can. if (err != OK || retval != 0) { ERR_PRINTS("move_to_trash: Could not move the resource \"" + p_path + "\" to the trash can \"" + trash_can + "\""); return FAILED; } return OK; } OS::LatinKeyboardVariant OS_X11::get_latin_keyboard_variant() const { XkbDescRec *xkbdesc = XkbAllocKeyboard(); ERR_FAIL_COND_V(!xkbdesc, LATIN_KEYBOARD_QWERTY); XkbGetNames(x11_display, XkbSymbolsNameMask, xkbdesc); ERR_FAIL_COND_V(!xkbdesc->names, LATIN_KEYBOARD_QWERTY); ERR_FAIL_COND_V(!xkbdesc->names->symbols, LATIN_KEYBOARD_QWERTY); char *layout = XGetAtomName(x11_display, xkbdesc->names->symbols); ERR_FAIL_COND_V(!layout, LATIN_KEYBOARD_QWERTY); Vector<String> info = String(layout).split("+"); ERR_FAIL_INDEX_V(1, info.size(), LATIN_KEYBOARD_QWERTY); if (info[1].find("colemak") != -1) { return LATIN_KEYBOARD_COLEMAK; } else if (info[1].find("qwertz") != -1) { return LATIN_KEYBOARD_QWERTZ; } else if (info[1].find("azerty") != -1) { return LATIN_KEYBOARD_AZERTY; } else if (info[1].find("qzerty") != -1) { return LATIN_KEYBOARD_QZERTY; } else if (info[1].find("dvorak") != -1) { return LATIN_KEYBOARD_DVORAK; } else if (info[1].find("neo") != -1) { return LATIN_KEYBOARD_NEO; } return LATIN_KEYBOARD_QWERTY; } int OS_X11::keyboard_get_layout_count() const { int _group_count = 0; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); const Atom *groups = kbd->names->groups; if (kbd->ctrls != NULL) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } XkbFreeKeyboard(kbd, 0, true); } return _group_count; } int OS_X11::keyboard_get_current_layout() const { XkbStateRec state; XkbGetState(x11_display, XkbUseCoreKbd, &state); return state.group; } void OS_X11::keyboard_set_current_layout(int p_index) { ERR_FAIL_INDEX(p_index, keyboard_get_layout_count()); XkbLockGroup(x11_display, XkbUseCoreKbd, p_index); } String OS_X11::keyboard_get_layout_language(int p_index) const { String ret; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); XkbGetNames(x11_display, XkbGroupNamesMask, kbd); int _group_count = 0; const Atom *groups = kbd->names->groups; if (kbd->ctrls != NULL) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } Atom names = kbd->names->symbols; if (names != None) { char *name = XGetAtomName(x11_display, names); Vector<String> info = String(name).split("+"); if (p_index >= 0 && p_index < _group_count) { if (p_index + 1 < info.size()) { ret = info[p_index + 1]; // Skip "pc" at the start and "inet"/"group" at the end of symbols. } else { ret = "en"; // No symbol for layout fallback to "en". } } else { ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ")."); } XFree(name); } XkbFreeKeyboard(kbd, 0, true); } return ret.substr(0, 2); } String OS_X11::keyboard_get_layout_name(int p_index) const { String ret; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); XkbGetNames(x11_display, XkbGroupNamesMask, kbd); int _group_count = 0; const Atom *groups = kbd->names->groups; if (kbd->ctrls != NULL) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } if (p_index >= 0 && p_index < _group_count) { char *full_name = XGetAtomName(x11_display, groups[p_index]); ret.parse_utf8(full_name); XFree(full_name); } else { ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ")."); } XkbFreeKeyboard(kbd, 0, true); } return ret; } void OS_X11::update_real_mouse_position() { Window root_return, child_return; int root_x, root_y, win_x, win_y; unsigned int mask_return; Bool xquerypointer_result = XQueryPointer(x11_display, x11_window, &root_return, &child_return, &root_x, &root_y, &win_x, &win_y, &mask_return); if (xquerypointer_result) { if (win_x > 0 && win_y > 0 && win_x <= current_videomode.width && win_y <= current_videomode.height) { last_mouse_pos.x = win_x; last_mouse_pos.y = win_y; last_mouse_pos_valid = true; input->set_mouse_position(last_mouse_pos); } } } OS_X11::OS_X11() { #ifdef PULSEAUDIO_ENABLED AudioDriverManager::add_driver(&driver_pulseaudio); #endif #ifdef ALSA_ENABLED AudioDriverManager::add_driver(&driver_alsa); #endif xi.opcode = 0; xi.last_relative_time = 0; layered_window = false; minimized = false; window_focused = true; xim_style = 0L; mouse_mode = MOUSE_MODE_VISIBLE; last_position_before_fs = Vector2(); } Fix out of bounds array access on OS_X11 code The problem happened on methods `get_screen_position`, `get_screen_size` and `set_current_screen` when they were passed a negative screen value. Fixes: - #46184 - #46185 - #46186 /*************************************************************************/ /* os_x11.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "os_x11.h" #include "core/os/dir_access.h" #include "core/print_string.h" #include "detect_prime.h" #include "drivers/gles2/rasterizer_gles2.h" #include "drivers/gles3/rasterizer_gles3.h" #include "key_mapping_x11.h" #include "main/main.h" #include "servers/visual/visual_server_raster.h" #include "servers/visual/visual_server_wrap_mt.h" #ifdef HAVE_MNTENT #include <mntent.h> #endif #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <X11/Xatom.h> #include <X11/Xutil.h> #include <X11/extensions/Xinerama.h> #include <X11/extensions/shape.h> // ICCCM #define WM_NormalState 1L // window normal state #define WM_IconicState 3L // window minimized // EWMH #define _NET_WM_STATE_REMOVE 0L // remove/unset property #define _NET_WM_STATE_ADD 1L // add/set property #define _NET_WM_STATE_TOGGLE 2L // toggle property #include <dlfcn.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> //stupid linux.h #ifdef KEY_TAB #undef KEY_TAB #endif #undef CursorShape #include <X11/XKBlib.h> // 2.2 is the first release with multitouch #define XINPUT_CLIENT_VERSION_MAJOR 2 #define XINPUT_CLIENT_VERSION_MINOR 2 #define VALUATOR_ABSX 0 #define VALUATOR_ABSY 1 #define VALUATOR_PRESSURE 2 #define VALUATOR_TILTX 3 #define VALUATOR_TILTY 4 static const double abs_resolution_mult = 10000.0; static const double abs_resolution_range_mult = 10.0; void OS_X11::initialize_core() { crash_handler.initialize(); OS_Unix::initialize_core(); } int OS_X11::get_current_video_driver() const { return video_driver_index; } Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { long im_event_mask = 0; last_button_state = 0; xmbstring = NULL; x11_window = 0; last_click_ms = 0; last_click_button_index = -1; last_click_pos = Point2(-100, -100); args = OS::get_singleton()->get_cmdline_args(); current_videomode = p_desired; main_loop = NULL; last_timestamp = 0; last_mouse_pos_valid = false; last_keyrelease_time = 0; xdnd_version = 0; XInitThreads(); /** XLIB INITIALIZATION **/ x11_display = XOpenDisplay(NULL); if (!x11_display) { ERR_PRINT("X11 Display is not available"); return ERR_UNAVAILABLE; } char *modifiers = NULL; Bool xkb_dar = False; XAutoRepeatOn(x11_display); xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, NULL); // Try to support IME if detectable auto-repeat is supported if (xkb_dar == True) { #ifdef X_HAVE_UTF8_STRING // Xutf8LookupString will be used later instead of XmbLookupString before // the multibyte sequences can be converted to unicode string. modifiers = XSetLocaleModifiers(""); #endif } if (modifiers == NULL) { if (is_stdout_verbose()) { WARN_PRINT("IME is disabled"); } XSetLocaleModifiers("@im=none"); WARN_PRINT("Error setting locale modifiers"); } const char *err; xrr_get_monitors = NULL; xrr_free_monitors = NULL; int xrandr_major = 0; int xrandr_minor = 0; int event_base, error_base; xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base); xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY); if (!xrandr_handle) { err = dlerror(); // For some arcane reason, NetBSD now ships libXrandr.so.3 while the rest of the world has libXrandr.so.2... // In case this happens for other X11 platforms in the future, let's give it a try too before failing. xrandr_handle = dlopen("libXrandr.so.3", RTLD_LAZY); if (!xrandr_handle) { fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err); } } else { XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor); if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) { xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors"); if (!xrr_get_monitors) { err = dlerror(); fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err); } else { xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors"); if (!xrr_free_monitors) { err = dlerror(); fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err); xrr_get_monitors = NULL; } } } } if (!refresh_device_info()) { OS::get_singleton()->alert("Your system does not support XInput 2.\n" "Please upgrade your distribution.", "Unable to initialize XInput"); return ERR_UNAVAILABLE; } xim = XOpenIM(x11_display, NULL, NULL, NULL); if (xim == NULL) { WARN_PRINT("XOpenIM failed"); xim_style = 0L; } else { ::XIMCallback im_destroy_callback; im_destroy_callback.client_data = (::XPointer)(this); im_destroy_callback.callback = (::XIMProc)(xim_destroy_callback); if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback, NULL) != NULL) { WARN_PRINT("Error setting XIM destroy callback"); } ::XIMStyles *xim_styles = NULL; xim_style = 0L; char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL); if (imvalret != NULL || xim_styles == NULL) { fprintf(stderr, "Input method doesn't support any styles\n"); } if (xim_styles) { xim_style = 0L; for (int i = 0; i < xim_styles->count_styles; i++) { if (xim_styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) { xim_style = xim_styles->supported_styles[i]; break; } } XFree(xim_styles); } XFree(imvalret); } /* char* windowid = getenv("GODOT_WINDOWID"); if (windowid) { //freopen("/home/punto/stdout", "w", stdout); //reopen("/home/punto/stderr", "w", stderr); x11_window = atol(windowid); XWindowAttributes xwa; XGetWindowAttributes(x11_display,x11_window,&xwa); current_videomode.width = xwa.width; current_videomode.height = xwa.height; }; */ // maybe contextgl wants to be in charge of creating the window #if defined(OPENGL_ENABLED) if (getenv("DRI_PRIME") == NULL) { int use_prime = -1; if (getenv("PRIMUS_DISPLAY") || getenv("PRIMUS_libGLd") || getenv("PRIMUS_libGLa") || getenv("PRIMUS_libGL") || getenv("PRIMUS_LOAD_GLOBAL") || getenv("BUMBLEBEE_SOCKET")) { print_verbose("Optirun/primusrun detected. Skipping GPU detection"); use_prime = 0; } if (getenv("LD_LIBRARY_PATH")) { String ld_library_path(getenv("LD_LIBRARY_PATH")); Vector<String> libraries = ld_library_path.split(":"); for (int i = 0; i < libraries.size(); ++i) { if (FileAccess::exists(libraries[i] + "/libGL.so.1") || FileAccess::exists(libraries[i] + "/libGL.so")) { print_verbose("Custom libGL override detected. Skipping GPU detection"); use_prime = 0; } } } if (use_prime == -1) { print_verbose("Detecting GPUs, set DRI_PRIME in the environment to override GPU detection logic."); use_prime = detect_prime(); } if (use_prime) { print_line("Found discrete GPU, setting DRI_PRIME=1 to use it."); print_line("Note: Set DRI_PRIME=0 in the environment to disable Godot from using the discrete GPU."); setenv("DRI_PRIME", "1", 1); } } ContextGL_X11::ContextType opengl_api_type = ContextGL_X11::GLES_3_0_COMPATIBLE; if (p_video_driver == VIDEO_DRIVER_GLES2) { opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; } bool editor = Engine::get_singleton()->is_editor_hint(); bool gl_initialization_error = false; context_gl = NULL; while (!context_gl) { context_gl = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, opengl_api_type)); if (context_gl->initialize() != OK) { memdelete(context_gl); context_gl = NULL; if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) { if (p_video_driver == VIDEO_DRIVER_GLES2) { gl_initialization_error = true; break; } p_video_driver = VIDEO_DRIVER_GLES2; opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; } else { gl_initialization_error = true; break; } } } while (true) { if (opengl_api_type == ContextGL_X11::GLES_3_0_COMPATIBLE) { if (RasterizerGLES3::is_viable() == OK) { RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); break; } else { if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) { p_video_driver = VIDEO_DRIVER_GLES2; opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; continue; } else { gl_initialization_error = true; break; } } } if (opengl_api_type == ContextGL_X11::GLES_2_0_COMPATIBLE) { if (RasterizerGLES2::is_viable() == OK) { RasterizerGLES2::register_config(); RasterizerGLES2::make_current(); break; } else { gl_initialization_error = true; break; } } } if (gl_initialization_error) { OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n" "Please update your drivers or if you have a very old or integrated GPU upgrade it.", "Unable to initialize Video driver"); return ERR_UNAVAILABLE; } video_driver_index = p_video_driver; context_gl->set_use_vsync(current_videomode.use_vsync); #endif visual_server = memnew(VisualServerRaster); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); } if (current_videomode.maximized) { current_videomode.maximized = false; set_window_maximized(true); // borderless fullscreen window mode } else if (current_videomode.fullscreen) { current_videomode.fullscreen = false; set_window_fullscreen(true); } else if (current_videomode.borderless_window) { Hints hints; Atom property; hints.flags = 2; hints.decorations = 0; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } // make PID known to X11 { const long pid = this->get_process_id(); Atom net_wm_pid = XInternAtom(x11_display, "_NET_WM_PID", False); if (net_wm_pid != None) { XChangeProperty(x11_display, x11_window, net_wm_pid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1); } } // disable resizable window if (!current_videomode.resizable && !current_videomode.fullscreen) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = PMinSize | PMaxSize; XWindowAttributes xwa; if (current_videomode.fullscreen) { XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa); } else { XGetWindowAttributes(x11_display, x11_window, &xwa); } xsh->min_width = xwa.width; xsh->max_width = xwa.width; xsh->min_height = xwa.height; xsh->max_height = xwa.height; XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); } if (current_videomode.always_on_top) { current_videomode.always_on_top = false; set_window_always_on_top(true); } ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE); ERR_FAIL_COND_V(x11_window == 0, ERR_UNAVAILABLE); XSetWindowAttributes new_attr; new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask | Button1MotionMask | Button2MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask | ButtonMotionMask | KeymapStateMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | SubstructureNotifyMask | SubstructureRedirectMask | FocusChangeMask | PropertyChangeMask | ColormapChangeMask | OwnerGrabButtonMask | im_event_mask; XChangeWindowAttributes(x11_display, x11_window, CWEventMask, &new_attr); static unsigned char all_mask_data[XIMaskLen(XI_LASTEVENT)] = {}; static unsigned char all_master_mask_data[XIMaskLen(XI_LASTEVENT)] = {}; xi.all_event_mask.deviceid = XIAllDevices; xi.all_event_mask.mask_len = sizeof(all_mask_data); xi.all_event_mask.mask = all_mask_data; xi.all_master_event_mask.deviceid = XIAllMasterDevices; xi.all_master_event_mask.mask_len = sizeof(all_master_mask_data); xi.all_master_event_mask.mask = all_master_mask_data; XISetMask(xi.all_event_mask.mask, XI_HierarchyChanged); XISetMask(xi.all_master_event_mask.mask, XI_DeviceChanged); XISetMask(xi.all_master_event_mask.mask, XI_RawMotion); #ifdef TOUCH_ENABLED if (xi.touch_devices.size()) { XISetMask(xi.all_event_mask.mask, XI_TouchBegin); XISetMask(xi.all_event_mask.mask, XI_TouchUpdate); XISetMask(xi.all_event_mask.mask, XI_TouchEnd); XISetMask(xi.all_event_mask.mask, XI_TouchOwnership); } #endif XISelectEvents(x11_display, x11_window, &xi.all_event_mask, 1); XISelectEvents(x11_display, DefaultRootWindow(x11_display), &xi.all_master_event_mask, 1); // Disabled by now since grabbing also blocks mouse events // (they are received as extended events instead of standard events) /*XIClearMask(xi.touch_event_mask.mask, XI_TouchOwnership); // Grab touch devices to avoid OS gesture interference for (int i = 0; i < xi.touch_devices.size(); ++i) { XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask); }*/ /* set the titlebar name */ XStoreName(x11_display, x11_window, "Godot"); wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true); XSetWMProtocols(x11_display, x11_window, &wm_delete, 1); im_active = false; im_position = Vector2(); if (xim && xim_style) { xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, x11_window, XNFocusWindow, x11_window, (char *)NULL); if (XGetICValues(xic, XNFilterEvents, &im_event_mask, NULL) != NULL) { WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value"); XDestroyIC(xic); xic = NULL; } if (xic) { XUnsetICFocus(xic); } else { WARN_PRINT("XCreateIC couldn't create xic"); } } else { xic = NULL; WARN_PRINT("XCreateIC couldn't create xic"); } cursor_size = XcursorGetDefaultSize(x11_display); cursor_theme = XcursorGetTheme(x11_display); if (!cursor_theme) { print_verbose("XcursorGetTheme could not get cursor theme"); cursor_theme = "default"; } for (int i = 0; i < CURSOR_MAX; i++) { cursors[i] = None; img[i] = NULL; } current_cursor = CURSOR_ARROW; for (int i = 0; i < CURSOR_MAX; i++) { static const char *cursor_file[] = { "left_ptr", "xterm", "hand2", "cross", "watch", "left_ptr_watch", "fleur", "hand1", "X_cursor", "sb_v_double_arrow", "sb_h_double_arrow", "size_bdiag", "size_fdiag", "hand1", "sb_v_double_arrow", "sb_h_double_arrow", "question_arrow" }; img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size); if (img[i]) { cursors[i] = XcursorImageLoadCursor(x11_display, img[i]); } else { print_verbose("Failed loading custom cursor: " + String(cursor_file[i])); } } { // Creating an empty/transparent cursor // Create 1x1 bitmap Pixmap cursormask = XCreatePixmap(x11_display, RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1); // Fill with zero XGCValues xgc; xgc.function = GXclear; GC gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc); XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1); // Color value doesn't matter. Mask zero means no foreground or background will be drawn XColor col = {}; Cursor cursor = XCreatePixmapCursor(x11_display, cursormask, // source (using cursor mask as placeholder, since it'll all be ignored) cursormask, // mask &col, &col, 0, 0); XFreePixmap(x11_display, cursormask); XFreeGC(x11_display, gc); if (cursor == None) { ERR_PRINT("FAILED CREATING CURSOR"); } null_cursor = cursor; } set_cursor_shape(CURSOR_BUSY); //Set Xdnd (drag & drop) support Atom XdndAware = XInternAtom(x11_display, "XdndAware", False); Atom version = 5; if (XdndAware != None) { XChangeProperty(x11_display, x11_window, XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&version, 1); } xdnd_enter = XInternAtom(x11_display, "XdndEnter", False); xdnd_position = XInternAtom(x11_display, "XdndPosition", False); xdnd_status = XInternAtom(x11_display, "XdndStatus", False); xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False); xdnd_drop = XInternAtom(x11_display, "XdndDrop", False); xdnd_finished = XInternAtom(x11_display, "XdndFinished", False); xdnd_selection = XInternAtom(x11_display, "XdndSelection", False); requested = None; visual_server->init(); AudioDriverManager::initialize(p_audio_driver); input = memnew(InputDefault); window_has_focus = true; // Set focus to true at init #ifdef JOYDEV_ENABLED joypad = memnew(JoypadLinux(input)); #endif power_manager = memnew(PowerX11); if (p_desired.layered) { set_window_per_pixel_transparency_enabled(true); } XEvent xevent; while (XPending(x11_display) > 0) { XNextEvent(x11_display, &xevent); if (xevent.type == ConfigureNotify) { _window_changed(&xevent); } } events_thread.start(_poll_events_thread, this); update_real_mouse_position(); return OK; } bool OS_X11::refresh_device_info() { int event_base, error_base; print_verbose("XInput: Refreshing devices."); if (!XQueryExtension(x11_display, "XInputExtension", &xi.opcode, &event_base, &error_base)) { print_verbose("XInput extension not available. Please upgrade your distribution."); return false; } int xi_major_query = XINPUT_CLIENT_VERSION_MAJOR; int xi_minor_query = XINPUT_CLIENT_VERSION_MINOR; if (XIQueryVersion(x11_display, &xi_major_query, &xi_minor_query) != Success) { print_verbose(vformat("XInput 2 not available (server supports %d.%d).", xi_major_query, xi_minor_query)); xi.opcode = 0; return false; } if (xi_major_query < XINPUT_CLIENT_VERSION_MAJOR || (xi_major_query == XINPUT_CLIENT_VERSION_MAJOR && xi_minor_query < XINPUT_CLIENT_VERSION_MINOR)) { print_verbose(vformat("XInput %d.%d not available (server supports %d.%d). Touch input unavailable.", XINPUT_CLIENT_VERSION_MAJOR, XINPUT_CLIENT_VERSION_MINOR, xi_major_query, xi_minor_query)); } xi.absolute_devices.clear(); xi.touch_devices.clear(); int dev_count; XIDeviceInfo *info = XIQueryDevice(x11_display, XIAllDevices, &dev_count); for (int i = 0; i < dev_count; i++) { XIDeviceInfo *dev = &info[i]; if (!dev->enabled) continue; if (!(dev->use == XIMasterPointer || dev->use == XIFloatingSlave)) continue; bool direct_touch = false; bool absolute_mode = false; int resolution_x = 0; int resolution_y = 0; double abs_x_min = 0; double abs_x_max = 0; double abs_y_min = 0; double abs_y_max = 0; double pressure_min = 0; double pressure_max = 0; double tilt_x_min = 0; double tilt_x_max = 0; double tilt_y_min = 0; double tilt_y_max = 0; for (int j = 0; j < dev->num_classes; j++) { #ifdef TOUCH_ENABLED if (dev->classes[j]->type == XITouchClass && ((XITouchClassInfo *)dev->classes[j])->mode == XIDirectTouch) { direct_touch = true; } #endif if (dev->classes[j]->type == XIValuatorClass) { XIValuatorClassInfo *class_info = (XIValuatorClassInfo *)dev->classes[j]; if (class_info->number == VALUATOR_ABSX && class_info->mode == XIModeAbsolute) { resolution_x = class_info->resolution; abs_x_min = class_info->min; abs_y_max = class_info->max; absolute_mode = true; } else if (class_info->number == VALUATOR_ABSY && class_info->mode == XIModeAbsolute) { resolution_y = class_info->resolution; abs_y_min = class_info->min; abs_y_max = class_info->max; absolute_mode = true; } else if (class_info->number == VALUATOR_PRESSURE && class_info->mode == XIModeAbsolute) { pressure_min = class_info->min; pressure_max = class_info->max; } else if (class_info->number == VALUATOR_TILTX && class_info->mode == XIModeAbsolute) { tilt_x_min = class_info->min; tilt_x_max = class_info->max; } else if (class_info->number == VALUATOR_TILTY && class_info->mode == XIModeAbsolute) { tilt_x_min = class_info->min; tilt_x_max = class_info->max; } } } if (direct_touch) { xi.touch_devices.push_back(dev->deviceid); print_verbose("XInput: Using touch device: " + String(dev->name)); } if (absolute_mode) { // If no resolution was reported, use the min/max ranges. if (resolution_x <= 0) { resolution_x = (abs_x_max - abs_x_min) * abs_resolution_range_mult; } if (resolution_y <= 0) { resolution_y = (abs_y_max - abs_y_min) * abs_resolution_range_mult; } xi.absolute_devices[dev->deviceid] = Vector2(abs_resolution_mult / resolution_x, abs_resolution_mult / resolution_y); print_verbose("XInput: Absolute pointing device: " + String(dev->name)); } xi.pressure = 0; xi.pen_pressure_range[dev->deviceid] = Vector2(pressure_min, pressure_max); xi.pen_tilt_x_range[dev->deviceid] = Vector2(tilt_x_min, tilt_x_max); xi.pen_tilt_y_range[dev->deviceid] = Vector2(tilt_y_min, tilt_y_max); } XIFreeDeviceInfo(info); #ifdef TOUCH_ENABLED if (!xi.touch_devices.size()) { print_verbose("XInput: No touch devices found."); } #endif return true; } void OS_X11::xim_destroy_callback(::XIM im, ::XPointer client_data, ::XPointer call_data) { WARN_PRINT("Input method stopped"); OS_X11 *os = reinterpret_cast<OS_X11 *>(client_data); os->xim = NULL; os->xic = NULL; } void OS_X11::set_ime_active(const bool p_active) { im_active = p_active; if (!xic) { return; } // Block events polling while changing input focus // because it triggers some event polling internally. if (p_active) { { MutexLock mutex_lock(events_mutex); XSetICFocus(xic); } set_ime_position(im_position); } else { MutexLock mutex_lock(events_mutex); XUnsetICFocus(xic); } } void OS_X11::set_ime_position(const Point2 &p_pos) { im_position = p_pos; if (!xic) return; ::XPoint spot; spot.x = short(p_pos.x); spot.y = short(p_pos.y); XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, NULL); { // Block events polling during this call // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XSetICValues(xic, XNPreeditAttributes, preedit_attr, NULL); } XFree(preedit_attr); } String OS_X11::get_unique_id() const { static String machine_id; if (machine_id.empty()) { if (FileAccess *f = FileAccess::open("/etc/machine-id", FileAccess::READ)) { while (machine_id.empty() && !f->eof_reached()) { machine_id = f->get_line().strip_edges(); } f->close(); memdelete(f); } } return machine_id; } void OS_X11::finalize() { events_thread_done = true; events_thread.wait_to_finish(); if (main_loop) memdelete(main_loop); main_loop = NULL; /* if (debugger_connection_console) { memdelete(debugger_connection_console); } */ #ifdef ALSAMIDI_ENABLED driver_alsamidi.close(); #endif #ifdef JOYDEV_ENABLED memdelete(joypad); #endif xi.touch_devices.clear(); xi.state.clear(); memdelete(input); cursors_cache.clear(); visual_server->finish(); memdelete(visual_server); //memdelete(rasterizer); memdelete(power_manager); if (xrandr_handle) dlclose(xrandr_handle); if (!OS::get_singleton()->is_no_window_mode_enabled()) { XUnmapWindow(x11_display, x11_window); } XDestroyWindow(x11_display, x11_window); #if defined(OPENGL_ENABLED) memdelete(context_gl); #endif for (int i = 0; i < CURSOR_MAX; i++) { if (cursors[i] != None) XFreeCursor(x11_display, cursors[i]); if (img[i] != NULL) XcursorImageDestroy(img[i]); }; if (xic) { XDestroyIC(xic); } if (xim) { XCloseIM(xim); } XCloseDisplay(x11_display); if (xmbstring) memfree(xmbstring); args.clear(); } void OS_X11::set_mouse_mode(MouseMode p_mode) { if (p_mode == mouse_mode) return; if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) XUngrabPointer(x11_display, CurrentTime); // The only modes that show a cursor are VISIBLE and CONFINED bool showCursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED); if (showCursor) { XDefineCursor(x11_display, x11_window, cursors[current_cursor]); // show cursor } else { XDefineCursor(x11_display, x11_window, null_cursor); // hide cursor } mouse_mode = p_mode; if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) { //flush pending motion events flush_mouse_motion(); if (XGrabPointer( x11_display, x11_window, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime) != GrabSuccess) { ERR_PRINT("NO GRAB"); } if (mouse_mode == MOUSE_MODE_CAPTURED) { center.x = current_videomode.width / 2; center.y = current_videomode.height / 2; XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)center.x, (int)center.y); input->set_mouse_position(center); } } else { do_mouse_warp = false; } XFlush(x11_display); } void OS_X11::warp_mouse_position(const Point2 &p_to) { if (mouse_mode == MOUSE_MODE_CAPTURED) { last_mouse_pos = p_to; } else { /*XWindowAttributes xwa; XGetWindowAttributes(x11_display, x11_window, &xwa); printf("%d %d\n", xwa.x, xwa.y); needed? */ XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)p_to.x, (int)p_to.y); } } void OS_X11::flush_mouse_motion() { // Block events polling while flushing motion events. MutexLock mutex_lock(events_mutex); for (uint32_t event_index = 0; event_index < polled_events.size(); ++event_index) { XEvent &event = polled_events[event_index]; if (XGetEventData(x11_display, &event.xcookie) && event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) { XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data; if (event_data->evtype == XI_RawMotion) { XFreeEventData(x11_display, &event.xcookie); polled_events.remove(event_index--); continue; } XFreeEventData(x11_display, &event.xcookie); break; } } xi.relative_motion.x = 0; xi.relative_motion.y = 0; } OS::MouseMode OS_X11::get_mouse_mode() const { return mouse_mode; } int OS_X11::get_mouse_button_state() const { return last_button_state; } Point2 OS_X11::get_mouse_position() const { return last_mouse_pos; } bool OS_X11::get_window_per_pixel_transparency_enabled() const { if (!is_layered_allowed()) return false; return layered_window; } void OS_X11::set_window_per_pixel_transparency_enabled(bool p_enabled) { if (!is_layered_allowed()) return; if (layered_window != p_enabled) { if (p_enabled) { layered_window = true; } else { layered_window = false; } } } void OS_X11::set_window_title(const String &p_title) { XStoreName(x11_display, x11_window, p_title.utf8().get_data()); Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false); Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false); if (_net_wm_name != None && utf8_string != None) { XChangeProperty(x11_display, x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length()); } } void OS_X11::set_window_mouse_passthrough(const PoolVector2Array &p_region) { int event_base, error_base; const Bool ext_okay = XShapeQueryExtension(x11_display, &event_base, &error_base); if (ext_okay) { Region region; if (p_region.size() == 0) { region = XCreateRegion(); XRectangle rect; rect.x = 0; rect.y = 0; rect.width = get_real_window_size().x; rect.height = get_real_window_size().y; XUnionRectWithRegion(&rect, region, region); } else { XPoint *points = (XPoint *)memalloc(sizeof(XPoint) * p_region.size()); for (int i = 0; i < p_region.size(); i++) { points[i].x = p_region[i].x; points[i].y = p_region[i].y; } region = XPolygonRegion(points, p_region.size(), EvenOddRule); memfree(points); } XShapeCombineRegion(x11_display, x11_window, ShapeInput, 0, 0, region, ShapeSet); XDestroyRegion(region); } } void OS_X11::set_video_mode(const VideoMode &p_video_mode, int p_screen) { } OS::VideoMode OS_X11::get_video_mode(int p_screen) const { return current_videomode; } void OS_X11::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const { } void OS_X11::set_wm_fullscreen(bool p_enabled) { if (p_enabled && !get_borderless_window()) { // remove decorations if the window is not already borderless Hints hints; Atom property; hints.flags = 2; hints.decorations = 0; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } if (p_enabled && !is_window_resizable()) { // Set the window as resizable to prevent window managers to ignore the fullscreen state flag. XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); } // Using EWMH -- Extended Window Manager Hints XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.xclient.data.l[1] = wm_fullscreen; xev.xclient.data.l[2] = 0; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); // set bypass compositor hint Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False); unsigned long compositing_disable_on = p_enabled ? 1 : 0; if (bypass_compositor != None) { XChangeProperty(x11_display, x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1); } XFlush(x11_display); if (!p_enabled) { // Reset the non-resizable flags if we un-set these before. Size2 size = get_window_size(); XSizeHints *xsh; xsh = XAllocSizeHints(); if (!is_window_resizable()) { xsh->flags = PMinSize | PMaxSize; xsh->min_width = size.x; xsh->max_width = size.x; xsh->min_height = size.y; xsh->max_height = size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); // put back or remove decorations according to the last set borderless state Hints hints; Atom property; hints.flags = 2; hints.decorations = current_videomode.borderless_window ? 0 : 1; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } } void OS_X11::set_wm_above(bool p_enabled) { Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False); XClientMessageEvent xev; memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.window = x11_window; xev.message_type = wm_state; xev.format = 32; xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.data.l[1] = wm_above; xev.data.l[3] = 1; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev); } int OS_X11::get_screen_count() const { // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) return 0; int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); XFree(xsi); return count; } int OS_X11::get_current_screen() const { int x, y; Window child; XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child); int count = get_screen_count(); for (int i = 0; i < count; i++) { Point2i pos = get_screen_position(i); Size2i size = get_screen_size(i); if ((x >= pos.x && x < pos.x + size.width) && (y >= pos.y && y < pos.y + size.height)) return i; } return 0; } void OS_X11::set_current_screen(int p_screen) { if (p_screen == -1) { p_screen = get_current_screen(); } // Check if screen is valid ERR_FAIL_INDEX(p_screen, get_screen_count()); if (current_videomode.fullscreen) { Point2i position = get_screen_position(p_screen); Size2i size = get_screen_size(p_screen); XMoveResizeWindow(x11_display, x11_window, position.x, position.y, size.x, size.y); } else { if (p_screen != get_current_screen()) { Point2i position = get_screen_position(p_screen); XMoveWindow(x11_display, x11_window, position.x, position.y); } } } Point2 OS_X11::get_screen_position(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) { return Point2i(0, 0); } int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); // Check if screen is valid ERR_FAIL_INDEX_V(p_screen, count, Point2i(0, 0)); Point2i position = Point2i(xsi[p_screen].x_org, xsi[p_screen].y_org); XFree(xsi); return position; } Size2 OS_X11::get_screen_size(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) return Size2i(0, 0); int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); // Check if screen is valid ERR_FAIL_INDEX_V(p_screen, count, Size2i(0, 0)); Size2i size = Point2i(xsi[p_screen].width, xsi[p_screen].height); XFree(xsi); return size; } int OS_X11::get_screen_dpi(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } //invalid screen? ERR_FAIL_INDEX_V(p_screen, get_screen_count(), 0); //Get physical monitor Dimensions through XRandR and calculate dpi Size2 sc = get_screen_size(p_screen); if (xrandr_ext_ok) { int count = 0; if (xrr_get_monitors) { xrr_monitor_info *monitors = xrr_get_monitors(x11_display, x11_window, true, &count); if (p_screen < count) { double xdpi = sc.width / (double)monitors[p_screen].mwidth * 25.4; double ydpi = sc.height / (double)monitors[p_screen].mheight * 25.4; xrr_free_monitors(monitors); return (xdpi + ydpi) / 2; } xrr_free_monitors(monitors); } else if (p_screen == 0) { XRRScreenSize *sizes = XRRSizes(x11_display, 0, &count); if (sizes) { double xdpi = sc.width / (double)sizes[0].mwidth * 25.4; double ydpi = sc.height / (double)sizes[0].mheight * 25.4; return (xdpi + ydpi) / 2; } } } int width_mm = DisplayWidthMM(x11_display, p_screen); int height_mm = DisplayHeightMM(x11_display, p_screen); double xdpi = (width_mm ? sc.width / (double)width_mm * 25.4 : 0); double ydpi = (height_mm ? sc.height / (double)height_mm * 25.4 : 0); if (xdpi || ydpi) return (xdpi + ydpi) / (xdpi && ydpi ? 2 : 1); //could not get dpi return 96; } Point2 OS_X11::get_window_position() const { int x, y; Window child; XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child); return Point2i(x, y); } void OS_X11::set_window_position(const Point2 &p_position) { int x = 0; int y = 0; if (!get_borderless_window()) { //exclude window decorations XSync(x11_display, False); Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (format == 32 && len == 4) { long *extents = (long *)data; x = extents[0]; y = extents[2]; } XFree(data); } } } XMoveWindow(x11_display, x11_window, p_position.x - x, p_position.y - y); update_real_mouse_position(); } Size2 OS_X11::get_window_size() const { // Use current_videomode width and height instead of XGetWindowAttributes // since right after a XResizeWindow the attributes may not be updated yet return Size2i(current_videomode.width, current_videomode.height); } Size2 OS_X11::get_real_window_size() const { XWindowAttributes xwa; XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); int w = xwa.width; int h = xwa.height; Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (format == 32 && len == 4) { long *extents = (long *)data; w += extents[0] + extents[1]; // left, right h += extents[2] + extents[3]; // top, bottom } XFree(data); } } return Size2(w, h); } Size2 OS_X11::get_max_window_size() const { return max_size; } Size2 OS_X11::get_min_window_size() const { return min_size; } void OS_X11::set_min_window_size(const Size2 p_size) { if ((p_size != Size2()) && (max_size != Size2()) && ((p_size.x > max_size.x) || (p_size.y > max_size.y))) { ERR_PRINT("Minimum window size can't be larger than maximum window size!"); return; } min_size = p_size; if (is_window_resizable()) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); XFlush(x11_display); } } void OS_X11::set_max_window_size(const Size2 p_size) { if ((p_size != Size2()) && ((p_size.x < min_size.x) || (p_size.y < min_size.y))) { ERR_PRINT("Maximum window size can't be smaller than minimum window size!"); return; } max_size = p_size; if (is_window_resizable()) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); XFlush(x11_display); } } void OS_X11::set_window_size(const Size2 p_size) { if (current_videomode.width == p_size.width && current_videomode.height == p_size.height) return; XWindowAttributes xwa; XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); int old_w = xwa.width; int old_h = xwa.height; // If window resizable is disabled we need to update the attributes first XSizeHints *xsh; xsh = XAllocSizeHints(); if (!is_window_resizable()) { xsh->flags = PMinSize | PMaxSize; xsh->min_width = p_size.x; xsh->max_width = p_size.x; xsh->min_height = p_size.y; xsh->max_height = p_size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); // Resize the window XResizeWindow(x11_display, x11_window, p_size.x, p_size.y); // Update our videomode width and height current_videomode.width = p_size.x; current_videomode.height = p_size.y; for (int timeout = 0; timeout < 50; ++timeout) { XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); if (old_w != xwa.width || old_h != xwa.height) break; usleep(10000); } } void OS_X11::set_window_fullscreen(bool p_enabled) { if (current_videomode.fullscreen == p_enabled) return; if (layered_window) set_window_per_pixel_transparency_enabled(false); if (p_enabled && current_videomode.always_on_top) { // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity) set_window_maximized(true); } set_wm_fullscreen(p_enabled); if (!p_enabled && current_videomode.always_on_top) { // Restore set_window_maximized(false); } if (!p_enabled) { set_window_position(last_position_before_fs); } else { last_position_before_fs = get_window_position(); } current_videomode.fullscreen = p_enabled; } bool OS_X11::is_window_fullscreen() const { return current_videomode.fullscreen; } void OS_X11::set_window_resizable(bool p_enabled) { XSizeHints *xsh; xsh = XAllocSizeHints(); if (!p_enabled) { Size2 size = get_window_size(); xsh->flags = PMinSize | PMaxSize; xsh->min_width = size.x; xsh->max_width = size.x; xsh->min_height = size.y; xsh->max_height = size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); current_videomode.resizable = p_enabled; XFlush(x11_display); } bool OS_X11::is_window_resizable() const { return current_videomode.resizable; } void OS_X11::set_window_minimized(bool p_enabled) { if (is_no_window_mode_enabled()) { return; } // Using ICCCM -- Inter-Client Communication Conventions Manual XEvent xev; Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_change; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? WM_IconicState : WM_NormalState; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = _NET_WM_STATE_ADD; xev.xclient.data.l[1] = wm_hidden; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); } bool OS_X11::is_window_minimized() const { // Using ICCCM -- Inter-Client Communication Conventions Manual Atom property = XInternAtom(x11_display, "WM_STATE", True); if (property == None) { return false; } Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; bool retval = false; int result = XGetWindowProperty( x11_display, x11_window, property, 0, 32, False, AnyPropertyType, &type, &format, &len, &remaining, &data); if (result == Success) { long *state = (long *)data; if (state[0] == WM_IconicState) { retval = true; } XFree(data); } return retval; } void OS_X11::set_window_maximized(bool p_enabled) { if (is_no_window_mode_enabled()) { return; } if (is_window_maximized() == p_enabled) return; // Using EWMH -- Extended Window Manager Hints XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False); Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.xclient.data.l[1] = wm_max_horz; xev.xclient.data.l[2] = wm_max_vert; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); if (p_enabled && is_window_maximize_allowed()) { // Wait for effective resizing (so the GLX context is too). // Give up after 0.5s, it's not going to happen on this WM. // https://github.com/godotengine/godot/issues/19978 for (int attempt = 0; !is_window_maximized() && attempt < 50; attempt++) { usleep(10000); } } maximized = p_enabled; } // Just a helper to reduce code duplication in `is_window_maximize_allowed` // and `is_window_maximized`. bool OS_X11::window_maximize_check(const char *p_atom_name) const { Atom property = XInternAtom(x11_display, p_atom_name, False); Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; bool retval = false; if (property == None) { return false; } int result = XGetWindowProperty( x11_display, x11_window, property, 0, 1024, False, XA_ATOM, &type, &format, &len, &remaining, &data); if (result == Success) { Atom *atoms = (Atom *)data; Atom wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False); Atom wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_VERT", False); bool found_wm_act_max_horz = false; bool found_wm_act_max_vert = false; for (uint64_t i = 0; i < len; i++) { if (atoms[i] == wm_act_max_horz) found_wm_act_max_horz = true; if (atoms[i] == wm_act_max_vert) found_wm_act_max_vert = true; if (found_wm_act_max_horz || found_wm_act_max_vert) { retval = true; break; } } XFree(data); } return retval; } bool OS_X11::is_window_maximize_allowed() const { return window_maximize_check("_NET_WM_ALLOWED_ACTIONS"); } bool OS_X11::is_window_maximized() const { // Using EWMH -- Extended Window Manager Hints return window_maximize_check("_NET_WM_STATE"); } void OS_X11::set_window_always_on_top(bool p_enabled) { if (is_window_always_on_top() == p_enabled) return; if (p_enabled && current_videomode.fullscreen) { // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity) set_window_maximized(true); } set_wm_above(p_enabled); if (!p_enabled && !current_videomode.fullscreen) { // Restore set_window_maximized(false); } current_videomode.always_on_top = p_enabled; } bool OS_X11::is_window_always_on_top() const { return current_videomode.always_on_top; } bool OS_X11::is_window_focused() const { return window_focused; } void OS_X11::set_borderless_window(bool p_borderless) { if (get_borderless_window() == p_borderless) return; current_videomode.borderless_window = p_borderless; Hints hints; Atom property; hints.flags = 2; hints.decorations = current_videomode.borderless_window ? 0 : 1; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } // Preserve window size set_window_size(Size2(current_videomode.width, current_videomode.height)); } bool OS_X11::get_borderless_window() { bool borderless = current_videomode.borderless_window; Atom prop = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; if (XGetWindowProperty(x11_display, x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (data && (format == 32) && (len >= 5)) { borderless = !((Hints *)data)->decorations; } XFree(data); } } return borderless; } void OS_X11::request_attention() { // Using EWMH -- Extended Window Manager Hints // // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE // Will be unset by the window manager after user react on the request for attention XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = _NET_WM_STATE_ADD; xev.xclient.data.l[1] = wm_attention; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(x11_display); } void *OS_X11::get_native_handle(int p_handle_type) { switch (p_handle_type) { case APPLICATION_HANDLE: return NULL; // Do we have a value to return here? case DISPLAY_HANDLE: return (void *)x11_display; case WINDOW_HANDLE: return (void *)x11_window; case WINDOW_VIEW: return NULL; // Do we have a value to return here? case OPENGL_CONTEXT: return context_gl->get_glx_context(); default: return NULL; } } void OS_X11::get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) { state->set_shift((p_x11_state & ShiftMask)); state->set_control((p_x11_state & ControlMask)); state->set_alt((p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/)); //altgr should not count as alt state->set_metakey((p_x11_state & Mod4Mask)); } unsigned int OS_X11::get_mouse_button_state(unsigned int p_x11_button, int p_x11_type) { unsigned int mask = 1 << (p_x11_button - 1); if (p_x11_type == ButtonPress) { last_button_state |= mask; } else { last_button_state &= ~mask; } return last_button_state; } void OS_X11::_handle_key_event(XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo) { // X11 functions don't know what const is XKeyEvent *xkeyevent = p_event; // This code was pretty difficult to write. // The docs stink and every toolkit seems to // do it in a different way. /* Phase 1, obtain a proper keysym */ // This was also very difficult to figure out. // You'd expect you could just use Keysym provided by // XKeycodeToKeysym to obtain internationalized // input.. WRONG!! // you must use XLookupString (???) which not only wastes // cycles generating an unnecessary string, but also // still works in half the cases. (won't handle deadkeys) // For more complex input methods (deadkeys and more advanced) // you have to use XmbLookupString (??). // So.. then you have to chosse which of both results // you want to keep. // This is a real bizarreness and cpu waster. KeySym keysym_keycode = 0; // keysym used to find a keycode KeySym keysym_unicode = 0; // keysym used to find unicode // XLookupString returns keysyms usable as nice scancodes/ char str[256 + 1]; XKeyEvent xkeyevent_no_mod = *xkeyevent; xkeyevent_no_mod.state &= ~ShiftMask; xkeyevent_no_mod.state &= ~ControlMask; XLookupString(xkeyevent, str, 256, &keysym_unicode, NULL); XLookupString(&xkeyevent_no_mod, NULL, 0, &keysym_keycode, NULL); // Meanwhile, XLookupString returns keysyms useful for unicode. if (!xmbstring) { // keep a temporary buffer for the string xmbstring = (char *)memalloc(sizeof(char) * 8); xmblen = 8; } if (xkeyevent->type == KeyPress && xic) { Status status; #ifdef X_HAVE_UTF8_STRING int utf8len = 8; char *utf8string = (char *)memalloc(sizeof(char) * utf8len); int utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string, utf8len - 1, &keysym_unicode, &status); if (status == XBufferOverflow) { utf8len = utf8bytes + 1; utf8string = (char *)memrealloc(utf8string, utf8len); utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string, utf8len - 1, &keysym_unicode, &status); } utf8string[utf8bytes] = '\0'; if (status == XLookupChars) { bool keypress = xkeyevent->type == KeyPress; unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode); if (keycode >= 'a' && keycode <= 'z') keycode -= 'a' - 'A'; String tmp; tmp.parse_utf8(utf8string, utf8bytes); for (int i = 0; i < tmp.length(); i++) { Ref<InputEventKey> k; k.instance(); if (keycode == 0 && tmp[i] == 0) { continue; } get_key_modifier_state(xkeyevent->state, k); k->set_unicode(tmp[i]); k->set_pressed(keypress); k->set_scancode(keycode); k->set_echo(false); if (k->get_scancode() == KEY_BACKTAB) { //make it consistent across platforms. k->set_scancode(KEY_TAB); k->set_shift(true); } input->accumulate_input_event(k); } memfree(utf8string); return; } memfree(utf8string); #else do { int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status); xmbstring[mnbytes] = '\0'; if (status == XBufferOverflow) { xmblen = mnbytes + 1; xmbstring = (char *)memrealloc(xmbstring, xmblen); } } while (status == XBufferOverflow); #endif } /* Phase 2, obtain a pigui keycode from the keysym */ // KeyMappingX11 just translated the X11 keysym to a PIGUI // keysym, so it works in all platforms the same. unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode); /* Phase 3, obtain a unicode character from the keysym */ // KeyMappingX11 also translates keysym to unicode. // It does a binary search on a table to translate // most properly. unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0; /* Phase 4, determine if event must be filtered */ // This seems to be a side-effect of using XIM. // XFilterEvent looks like a core X11 function, // but it's actually just used to see if we must // ignore a deadkey, or events XIM determines // must not reach the actual gui. // Guess it was a design problem of the extension bool keypress = xkeyevent->type == KeyPress; if (keycode == 0 && unicode == 0) return; /* Phase 5, determine modifier mask */ // No problems here, except I had no way to // know Mod1 was ALT and Mod4 was META (applekey/winkey) // just tried Mods until i found them. //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask)); Ref<InputEventKey> k; k.instance(); get_key_modifier_state(xkeyevent->state, k); /* Phase 6, determine echo character */ // Echo characters in X11 are a keyrelease and a keypress // one after the other with the (almot) same timestamp. // To detect them, i compare to the next event in list and // check that their difference in time is below a threshold. if (xkeyevent->type != KeyPress) { p_echo = false; // make sure there are events pending, // so this call won't block. if (p_event_index + 1 < p_events.size()) { XEvent &peek_event = p_events[p_event_index + 1]; // I'm using a threshold of 5 msecs, // since sometimes there seems to be a little // jitter. I'm still not convinced that all this approach // is correct, but the xorg developers are // not very helpful today. ::Time tresh = ABSDIFF(peek_event.xkey.time, xkeyevent->time); if (peek_event.type == KeyPress && tresh < 5) { KeySym rk; XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, NULL); if (rk == keysym_keycode) { // Consume to next event. ++p_event_index; _handle_key_event((XKeyEvent *)&peek_event, p_events, p_event_index, true); return; //ignore current, echo next } } // use the time from peek_event so it always works } // save the time to check for echo when keypress happens } /* Phase 7, send event to Window */ k->set_pressed(keypress); if (keycode >= 'a' && keycode <= 'z') keycode -= 'a' - 'A'; k->set_scancode(keycode); k->set_unicode(unicode); k->set_echo(p_echo); if (k->get_scancode() == KEY_BACKTAB) { //make it consistent across platforms. k->set_scancode(KEY_TAB); k->set_shift(true); } //don't set mod state if modifier keys are released by themselves //else event.is_action() will not work correctly here if (!k->is_pressed()) { if (k->get_scancode() == KEY_SHIFT) k->set_shift(false); else if (k->get_scancode() == KEY_CONTROL) k->set_control(false); else if (k->get_scancode() == KEY_ALT) k->set_alt(false); else if (k->get_scancode() == KEY_META) k->set_metakey(false); } bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_scancode()); if (k->is_pressed()) { if (last_is_pressed) { k->set_echo(true); } } //printf("key: %x\n",k->get_scancode()); input->accumulate_input_event(k); } Atom OS_X11::_process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property) const { if (p_target == XInternAtom(x11_display, "TARGETS", 0)) { // Request to list all supported targets. Atom data[9]; data[0] = XInternAtom(x11_display, "TARGETS", 0); data[1] = XInternAtom(x11_display, "SAVE_TARGETS", 0); data[2] = XInternAtom(x11_display, "MULTIPLE", 0); data[3] = XInternAtom(x11_display, "UTF8_STRING", 0); data[4] = XInternAtom(x11_display, "COMPOUND_TEXT", 0); data[5] = XInternAtom(x11_display, "TEXT", 0); data[6] = XA_STRING; data[7] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0); data[8] = XInternAtom(x11_display, "text/plain", 0); XChangeProperty(x11_display, p_requestor, p_property, XA_ATOM, 32, PropModeReplace, (unsigned char *)&data, sizeof(data) / sizeof(data[0])); return p_property; } else if (p_target == XInternAtom(x11_display, "SAVE_TARGETS", 0)) { // Request to check if SAVE_TARGETS is supported, nothing special to do. XChangeProperty(x11_display, p_requestor, p_property, XInternAtom(x11_display, "NULL", False), 32, PropModeReplace, NULL, 0); return p_property; } else if (p_target == XInternAtom(x11_display, "UTF8_STRING", 0) || p_target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) || p_target == XInternAtom(x11_display, "TEXT", 0) || p_target == XA_STRING || p_target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) || p_target == XInternAtom(x11_display, "text/plain", 0)) { // Directly using internal clipboard because we know our window // is the owner during a selection request. CharString clip = OS::get_clipboard().utf8(); XChangeProperty(x11_display, p_requestor, p_property, p_target, 8, PropModeReplace, (unsigned char *)clip.get_data(), clip.length()); return p_property; } else { char *target_name = XGetAtomName(x11_display, p_target); printf("Target '%s' not supported.\n", target_name); if (target_name) { XFree(target_name); } return None; } } void OS_X11::_handle_selection_request_event(XSelectionRequestEvent *p_event) const { XEvent respond; if (p_event->target == XInternAtom(x11_display, "MULTIPLE", 0)) { // Request for multiple target conversions at once. Atom atom_pair = XInternAtom(x11_display, "ATOM_PAIR", False); respond.xselection.property = None; Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = NULL; if (XGetWindowProperty(x11_display, p_event->requestor, p_event->property, 0, LONG_MAX, False, atom_pair, &type, &format, &len, &remaining, &data) == Success) { if ((len >= 2) && data) { Atom *targets = (Atom *)data; for (uint64_t i = 0; i < len; i += 2) { Atom target = targets[i]; Atom &property = targets[i + 1]; property = _process_selection_request_target(target, p_event->requestor, property); } XChangeProperty(x11_display, p_event->requestor, p_event->property, atom_pair, 32, PropModeReplace, (unsigned char *)targets, len); respond.xselection.property = p_event->property; } XFree(data); } } else { // Request for target conversion. respond.xselection.property = _process_selection_request_target(p_event->target, p_event->requestor, p_event->property); } respond.xselection.type = SelectionNotify; respond.xselection.display = p_event->display; respond.xselection.requestor = p_event->requestor; respond.xselection.selection = p_event->selection; respond.xselection.target = p_event->target; respond.xselection.time = p_event->time; XSendEvent(x11_display, p_event->requestor, True, NoEventMask, &respond); XFlush(x11_display); } struct Property { unsigned char *data; int format, nitems; Atom type; }; static Property read_property(Display *p_display, Window p_window, Atom p_property) { Atom actual_type = None; int actual_format = 0; unsigned long nitems = 0; unsigned long bytes_after = 0; unsigned char *ret = 0; int read_bytes = 1024; //Keep trying to read the property until there are no //bytes unread. if (p_property != None) { do { if (ret != 0) XFree(ret); XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType, &actual_type, &actual_format, &nitems, &bytes_after, &ret); read_bytes *= 2; } while (bytes_after != 0); } Property p = { ret, actual_format, (int)nitems, actual_type }; return p; } static Atom pick_target_from_list(Display *p_display, Atom *p_list, int p_count) { static const char *target_type = "text/uri-list"; for (int i = 0; i < p_count; i++) { Atom atom = p_list[i]; if (atom != None && String(XGetAtomName(p_display, atom)) == target_type) return atom; } return None; } static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) { static const char *target_type = "text/uri-list"; if (p_t1 != None && String(XGetAtomName(p_disp, p_t1)) == target_type) return p_t1; if (p_t2 != None && String(XGetAtomName(p_disp, p_t2)) == target_type) return p_t2; if (p_t3 != None && String(XGetAtomName(p_disp, p_t3)) == target_type) return p_t3; return None; } void OS_X11::_window_changed(XEvent *event) { if (xic) { // Not portable. set_ime_position(Point2(0, 1)); } if ((event->xconfigure.width == current_videomode.width) && (event->xconfigure.height == current_videomode.height)) return; current_videomode.width = event->xconfigure.width; current_videomode.height = event->xconfigure.height; } void OS_X11::_poll_events_thread(void *ud) { OS_X11 *os = (OS_X11 *)ud; os->_poll_events(); } Bool OS_X11::_predicate_all_events(Display *display, XEvent *event, XPointer arg) { // Just accept all events. return True; } bool OS_X11::_wait_for_events() const { int x11_fd = ConnectionNumber(x11_display); fd_set in_fds; XFlush(x11_display); FD_ZERO(&in_fds); FD_SET(x11_fd, &in_fds); struct timeval tv; tv.tv_usec = 0; tv.tv_sec = 1; // Wait for next event or timeout. int num_ready_fds = select(x11_fd + 1, &in_fds, NULL, NULL, &tv); if (num_ready_fds > 0) { // Event received. return true; } else { // Error or timeout. if (num_ready_fds < 0) { ERR_PRINT("_wait_for_events: select error: " + itos(errno)); } return false; } } void OS_X11::_poll_events() { while (!events_thread_done) { _wait_for_events(); // Process events from the queue. { MutexLock mutex_lock(events_mutex); // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_all_events, NULL)) { // Check if the input manager wants to process the event. if (XFilterEvent(&ev, None)) { // Event has been filtered by the Input Manager, // it has to be ignored and a new one will be received. continue; } // Handle selection request events directly in the event thread, because // communication through the x server takes several events sent back and forth // and we don't want to block other programs while processing only one each frame. if (ev.type == SelectionRequest) { _handle_selection_request_event(&(ev.xselectionrequest)); continue; } polled_events.push_back(ev); } } } } void OS_X11::process_xevents() { //printf("checking events %i\n", XPending(x11_display)); do_mouse_warp = false; // Is the current mouse mode one where it needs to be grabbed. bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED; xi.pressure = 0; xi.tilt = Vector2(); xi.pressure_supported = false; LocalVector<XEvent> events; { // Block events polling while flushing events. MutexLock mutex_lock(events_mutex); events = polled_events; polled_events.clear(); } for (uint32_t event_index = 0; event_index < events.size(); ++event_index) { XEvent &event = events[event_index]; if (XGetEventData(x11_display, &event.xcookie)) { if (event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) { XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data; int index = event_data->detail; Vector2 pos = Vector2(event_data->event_x, event_data->event_y); switch (event_data->evtype) { case XI_HierarchyChanged: case XI_DeviceChanged: { refresh_device_info(); } break; case XI_RawMotion: { XIRawEvent *raw_event = (XIRawEvent *)event_data; int device_id = raw_event->deviceid; // Determine the axis used (called valuators in XInput for some forsaken reason) // Mask is a bitmask indicating which axes are involved. // We are interested in the values of axes 0 and 1. if (raw_event->valuators.mask_len <= 0) { break; } const double *values = raw_event->raw_values; double rel_x = 0.0; double rel_y = 0.0; if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSX)) { rel_x = *values; values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSY)) { rel_y = *values; values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_PRESSURE)) { Map<int, Vector2>::Element *pen_pressure = xi.pen_pressure_range.find(device_id); if (pen_pressure) { Vector2 pen_pressure_range = pen_pressure->value(); if (pen_pressure_range != Vector2()) { xi.pressure_supported = true; xi.pressure = (*values - pen_pressure_range[0]) / (pen_pressure_range[1] - pen_pressure_range[0]); } } values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTX)) { Map<int, Vector2>::Element *pen_tilt_x = xi.pen_tilt_x_range.find(device_id); if (pen_tilt_x) { Vector2 pen_tilt_x_range = pen_tilt_x->value(); if (pen_tilt_x_range != Vector2()) { xi.tilt.x = ((*values - pen_tilt_x_range[0]) / (pen_tilt_x_range[1] - pen_tilt_x_range[0])) * 2 - 1; } } values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTY)) { Map<int, Vector2>::Element *pen_tilt_y = xi.pen_tilt_y_range.find(device_id); if (pen_tilt_y) { Vector2 pen_tilt_y_range = pen_tilt_y->value(); if (pen_tilt_y_range != Vector2()) { xi.tilt.y = ((*values - pen_tilt_y_range[0]) / (pen_tilt_y_range[1] - pen_tilt_y_range[0])) * 2 - 1; } } values++; } // https://bugs.freedesktop.org/show_bug.cgi?id=71609 // http://lists.libsdl.org/pipermail/commits-libsdl.org/2015-June/000282.html if (raw_event->time == xi.last_relative_time && rel_x == xi.relative_motion.x && rel_y == xi.relative_motion.y) { break; // Flush duplicate to avoid overly fast motion } xi.old_raw_pos.x = xi.raw_pos.x; xi.old_raw_pos.y = xi.raw_pos.y; xi.raw_pos.x = rel_x; xi.raw_pos.y = rel_y; Map<int, Vector2>::Element *abs_info = xi.absolute_devices.find(device_id); if (abs_info) { // Absolute mode device Vector2 mult = abs_info->value(); xi.relative_motion.x += (xi.raw_pos.x - xi.old_raw_pos.x) * mult.x; xi.relative_motion.y += (xi.raw_pos.y - xi.old_raw_pos.y) * mult.y; } else { // Relative mode device xi.relative_motion.x = xi.raw_pos.x; xi.relative_motion.y = xi.raw_pos.y; } xi.last_relative_time = raw_event->time; } break; #ifdef TOUCH_ENABLED case XI_TouchBegin: // Fall-through // Disabled hand-in-hand with the grabbing //XIAllowTouchEvents(x11_display, event_data->deviceid, event_data->detail, x11_window, XIAcceptTouch); case XI_TouchEnd: { bool is_begin = event_data->evtype == XI_TouchBegin; Ref<InputEventScreenTouch> st; st.instance(); st->set_index(index); st->set_position(pos); st->set_pressed(is_begin); if (is_begin) { if (xi.state.has(index)) // Defensive break; xi.state[index] = pos; if (xi.state.size() == 1) { // X11 may send a motion event when a touch gesture begins, that would result // in a spurious mouse motion event being sent to Godot; remember it to be able to filter it out xi.mouse_pos_to_filter = pos; } input->accumulate_input_event(st); } else { if (!xi.state.has(index)) // Defensive break; xi.state.erase(index); input->accumulate_input_event(st); } } break; case XI_TouchUpdate: { Map<int, Vector2>::Element *curr_pos_elem = xi.state.find(index); if (!curr_pos_elem) { // Defensive break; } if (curr_pos_elem->value() != pos) { Ref<InputEventScreenDrag> sd; sd.instance(); sd->set_index(index); sd->set_position(pos); sd->set_relative(pos - curr_pos_elem->value()); input->accumulate_input_event(sd); curr_pos_elem->value() = pos; } } break; #endif } } } XFreeEventData(x11_display, &event.xcookie); switch (event.type) { case Expose: Main::force_redraw(); break; case NoExpose: minimized = true; break; case VisibilityNotify: { XVisibilityEvent *visibility = (XVisibilityEvent *)&event; minimized = (visibility->state == VisibilityFullyObscured); } break; case LeaveNotify: { if (main_loop && !mouse_mode_grab) main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT); } break; case EnterNotify: { if (main_loop && !mouse_mode_grab) main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER); } break; case FocusIn: minimized = false; window_has_focus = true; main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); window_focused = true; if (mouse_mode_grab) { // Show and update the cursor if confined and the window regained focus. if (mouse_mode == MOUSE_MODE_CONFINED) XUndefineCursor(x11_display, x11_window); else if (mouse_mode == MOUSE_MODE_CAPTURED) // or re-hide it in captured mode XDefineCursor(x11_display, x11_window, null_cursor); XGrabPointer( x11_display, x11_window, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime); } #ifdef TOUCH_ENABLED // Grab touch devices to avoid OS gesture interference /*for (int i = 0; i < xi.touch_devices.size(); ++i) { XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask); }*/ #endif if (xic) { // Block events polling while changing input focus // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XSetICFocus(xic); } break; case FocusOut: window_has_focus = false; input->release_pressed_events(); main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); window_focused = false; if (mouse_mode_grab) { //dear X11, I try, I really try, but you never work, you do whathever you want. if (mouse_mode == MOUSE_MODE_CAPTURED) { // Show the cursor if we're in captured mode so it doesn't look weird. XUndefineCursor(x11_display, x11_window); } XUngrabPointer(x11_display, CurrentTime); } #ifdef TOUCH_ENABLED // Ungrab touch devices so input works as usual while we are unfocused /*for (int i = 0; i < xi.touch_devices.size(); ++i) { XIUngrabDevice(x11_display, xi.touch_devices[i], CurrentTime); }*/ // Release every pointer to avoid sticky points for (Map<int, Vector2>::Element *E = xi.state.front(); E; E = E->next()) { Ref<InputEventScreenTouch> st; st.instance(); st->set_index(E->key()); st->set_position(E->get()); input->accumulate_input_event(st); } xi.state.clear(); #endif if (xic) { // Block events polling while changing input focus // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XUnsetICFocus(xic); } break; case ConfigureNotify: _window_changed(&event); break; case ButtonPress: case ButtonRelease: { /* exit in case of a mouse button press */ last_timestamp = event.xbutton.time; if (mouse_mode == MOUSE_MODE_CAPTURED) { event.xbutton.x = last_mouse_pos.x; event.xbutton.y = last_mouse_pos.y; } Ref<InputEventMouseButton> mb; mb.instance(); get_key_modifier_state(event.xbutton.state, mb); mb->set_button_index(event.xbutton.button); if (mb->get_button_index() == 2) mb->set_button_index(3); else if (mb->get_button_index() == 3) mb->set_button_index(2); mb->set_button_mask(get_mouse_button_state(mb->get_button_index(), event.xbutton.type)); mb->set_position(Vector2(event.xbutton.x, event.xbutton.y)); mb->set_global_position(mb->get_position()); mb->set_pressed((event.type == ButtonPress)); if (event.type == ButtonPress) { uint64_t diff = get_ticks_usec() / 1000 - last_click_ms; if (mb->get_button_index() == last_click_button_index) { if (diff < 400 && Point2(last_click_pos).distance_to(Point2(event.xbutton.x, event.xbutton.y)) < 5) { last_click_ms = 0; last_click_pos = Point2(-100, -100); last_click_button_index = -1; mb->set_doubleclick(true); } } else if (mb->get_button_index() < 4 || mb->get_button_index() > 7) { last_click_button_index = mb->get_button_index(); } if (!mb->is_doubleclick()) { last_click_ms += diff; last_click_pos = Point2(event.xbutton.x, event.xbutton.y); } } input->accumulate_input_event(mb); } break; case MotionNotify: { // The X11 API requires filtering one-by-one through the motion // notify events, in order to figure out which event is the one // generated by warping the mouse pointer. while (true) { if (mouse_mode == MOUSE_MODE_CAPTURED && event.xmotion.x == current_videomode.width / 2 && event.xmotion.y == current_videomode.height / 2) { //this is likely the warp event since it was warped here center = Vector2(event.xmotion.x, event.xmotion.y); break; } if (event_index + 1 < events.size()) { const XEvent &next_event = events[event_index + 1]; if (next_event.type == MotionNotify) { ++event_index; event = next_event; } else { break; } } else { break; } } last_timestamp = event.xmotion.time; // Motion is also simple. // A little hack is in order // to be able to send relative motion events. Point2 pos(event.xmotion.x, event.xmotion.y); // Avoidance of spurious mouse motion (see handling of touch) bool filter = false; // Adding some tolerance to match better Point2i to Vector2 if (xi.state.size() && Vector2(pos).distance_squared_to(xi.mouse_pos_to_filter) < 2) { filter = true; } // Invalidate to avoid filtering a possible legitimate similar event coming later xi.mouse_pos_to_filter = Vector2(1e10, 1e10); if (filter) { break; } if (mouse_mode == MOUSE_MODE_CAPTURED) { if (xi.relative_motion.x == 0 && xi.relative_motion.y == 0) { break; } Point2i new_center = pos; pos = last_mouse_pos + xi.relative_motion; center = new_center; do_mouse_warp = window_has_focus; // warp the cursor if we're focused in } if (!last_mouse_pos_valid) { last_mouse_pos = pos; last_mouse_pos_valid = true; } // Hackish but relative mouse motion is already handled in the RawMotion event. // RawMotion does not provide the absolute mouse position (whereas MotionNotify does). // Therefore, RawMotion cannot be the authority on absolute mouse position. // RawMotion provides more precision than MotionNotify, which doesn't sense subpixel motion. // Therefore, MotionNotify cannot be the authority on relative mouse motion. // This means we need to take a combined approach... Point2 rel; // Only use raw input if in capture mode. Otherwise use the classic behavior. if (mouse_mode == MOUSE_MODE_CAPTURED) { rel = xi.relative_motion; } else { rel = pos - last_mouse_pos; } // Reset to prevent lingering motion xi.relative_motion.x = 0; xi.relative_motion.y = 0; if (mouse_mode == MOUSE_MODE_CAPTURED) { pos = Point2i(current_videomode.width / 2, current_videomode.height / 2); } Ref<InputEventMouseMotion> mm; mm.instance(); if (xi.pressure_supported) { mm->set_pressure(xi.pressure); } else { mm->set_pressure((get_mouse_button_state() & (1 << (BUTTON_LEFT - 1))) ? 1.0f : 0.0f); } mm->set_tilt(xi.tilt); // Make the absolute position integral so it doesn't look _too_ weird :) Point2i posi(pos); get_key_modifier_state(event.xmotion.state, mm); mm->set_button_mask(get_mouse_button_state()); mm->set_position(posi); mm->set_global_position(posi); input->set_mouse_position(posi); mm->set_speed(input->get_last_mouse_speed()); mm->set_relative(rel); last_mouse_pos = pos; // printf("rel: %d,%d\n", rel.x, rel.y ); // Don't propagate the motion event unless we have focus // this is so that the relative motion doesn't get messed up // after we regain focus. if (window_has_focus || !mouse_mode_grab) input->accumulate_input_event(mm); } break; case KeyPress: case KeyRelease: { last_timestamp = event.xkey.time; // key event is a little complex, so // it will be handled in its own function. _handle_key_event((XKeyEvent *)&event, events, event_index); } break; case SelectionNotify: if (event.xselection.target == requested) { Property p = read_property(x11_display, x11_window, XInternAtom(x11_display, "PRIMARY", 0)); Vector<String> files = String((char *)p.data).split("\n", false); for (int i = 0; i < files.size(); i++) { files.write[i] = files[i].replace("file://", "").http_unescape().strip_edges(); } main_loop->drop_files(files); //Reply that all is well. XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = x11_display; m.window = xdnd_source_window; m.message_type = xdnd_finished; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = 1; m.data.l[2] = xdnd_action_copy; //We only ever copy. XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m); } break; case ClientMessage: if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete) main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST); else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) { //File(s) have been dragged over the window, check for supported target (text/uri-list) xdnd_version = (event.xclient.data.l[1] >> 24); Window source = event.xclient.data.l[0]; bool more_than_3 = event.xclient.data.l[1] & 1; if (more_than_3) { Property p = read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False)); requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems); } else requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]); } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) { //xdnd position event, reply with an XDND status message //just depending on type of data for now XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = event.xclient.display; m.window = event.xclient.data.l[0]; m.message_type = xdnd_status; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = (requested != None); m.data.l[2] = 0; //empty rectangle m.data.l[3] = 0; m.data.l[4] = xdnd_action_copy; XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m); XFlush(x11_display); } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) { if (requested != None) { xdnd_source_window = event.xclient.data.l[0]; if (xdnd_version >= 1) XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, event.xclient.data.l[2]); else XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, CurrentTime); } else { //Reply that we're not interested. XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = event.xclient.display; m.window = event.xclient.data.l[0]; m.message_type = xdnd_finished; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = 0; m.data.l[2] = None; //Failed. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m); } } break; default: break; } } XFlush(x11_display); if (do_mouse_warp) { XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)current_videomode.width / 2, (int)current_videomode.height / 2); /* Window root, child; int root_x, root_y; int win_x, win_y; unsigned int mask; XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask ); printf("Root: %d,%d\n", root_x, root_y); printf("Win: %d,%d\n", win_x, win_y); */ } input->flush_accumulated_events(); } MainLoop *OS_X11::get_main_loop() const { return main_loop; } void OS_X11::delete_main_loop() { // Send owned clipboard data to clipboard manager before exit. // This has to be done here because the clipboard data is cleared before finalize(). _clipboard_transfer_ownership(XA_PRIMARY, x11_window); _clipboard_transfer_ownership(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window); if (main_loop) memdelete(main_loop); main_loop = NULL; } void OS_X11::set_main_loop(MainLoop *p_main_loop) { main_loop = p_main_loop; input->set_main_loop(p_main_loop); } bool OS_X11::can_draw() const { return !minimized; }; void OS_X11::set_clipboard(const String &p_text) { { // The clipboard content can be accessed while polling for events. MutexLock mutex_lock(events_mutex); OS::set_clipboard(p_text); } XSetSelectionOwner(x11_display, XA_PRIMARY, x11_window, CurrentTime); XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), x11_window, CurrentTime); }; Bool OS_X11::_predicate_clipboard_selection(Display *display, XEvent *event, XPointer arg) { if (event->type == SelectionNotify && event->xselection.requestor == *(Window *)arg) { return True; } else { return False; } } Bool OS_X11::_predicate_clipboard_incr(Display *display, XEvent *event, XPointer arg) { if (event->type == PropertyNotify && event->xproperty.state == PropertyNewValue) { return True; } else { return False; } } String OS_X11::_get_clipboard_impl(Atom p_source, Window x11_window, Atom target) const { String ret; Window selection_owner = XGetSelectionOwner(x11_display, p_source); if (selection_owner == x11_window) { return OS::get_clipboard(); } if (selection_owner != None) { // Block events polling while processing selection events. MutexLock mutex_lock(events_mutex); Atom selection = XA_PRIMARY; XConvertSelection(x11_display, p_source, target, selection, x11_window, CurrentTime); XFlush(x11_display); // Blocking wait for predicate to be True and remove the event from the queue. XEvent event; XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window); // Do not get any data, see how much data is there. Atom type; int format, result; unsigned long len, bytes_left, dummy; unsigned char *data; XGetWindowProperty(x11_display, x11_window, selection, // Tricky.. 0, 0, // offset - len 0, // Delete 0==FALSE AnyPropertyType, // flag &type, // return type &format, // return format &len, &bytes_left, // data length &data); if (data) { XFree(data); } if (type == XInternAtom(x11_display, "INCR", 0)) { // Data is going to be received incrementally. LocalVector<uint8_t> incr_data; uint32_t data_size = 0; bool success = false; // Delete INCR property to notify the owner. XDeleteProperty(x11_display, x11_window, type); // Process events from the queue. bool done = false; while (!done) { if (!_wait_for_events()) { // Error or timeout, abort. break; } // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, NULL)) { result = XGetWindowProperty(x11_display, x11_window, selection, // selection type 0, LONG_MAX, // offset - len True, // delete property to notify the owner AnyPropertyType, // flag &type, // return type &format, // return format &len, &bytes_left, // data length &data); if (result == Success) { if (data && (len > 0)) { uint32_t prev_size = incr_data.size(); if (prev_size == 0) { // First property contains initial data size. unsigned long initial_size = *(unsigned long *)data; incr_data.resize(initial_size); } else { // New chunk, resize to be safe and append data. incr_data.resize(MAX(data_size + len, prev_size)); memcpy(incr_data.ptr() + data_size, data, len); data_size += len; } } else { // Last chunk, process finished. done = true; success = true; } } else { printf("Failed to get selection data chunk.\n"); done = true; } if (data) { XFree(data); } if (done) { break; } } } if (success && (data_size > 0)) { ret.parse_utf8((const char *)incr_data.ptr(), data_size); } } else if (bytes_left > 0) { // Data is ready and can be processed all at once. result = XGetWindowProperty(x11_display, x11_window, selection, 0, bytes_left, 0, AnyPropertyType, &type, &format, &len, &dummy, &data); if (result == Success) { ret.parse_utf8((const char *)data); } else { printf("Failed to get selection data.\n"); } if (data) { XFree(data); } } } return ret; } String OS_X11::_get_clipboard(Atom p_source, Window x11_window) const { String ret; Atom utf8_atom = XInternAtom(x11_display, "UTF8_STRING", True); if (utf8_atom != None) { ret = _get_clipboard_impl(p_source, x11_window, utf8_atom); } if (ret.empty()) { ret = _get_clipboard_impl(p_source, x11_window, XA_STRING); } return ret; } String OS_X11::get_clipboard() const { String ret; ret = _get_clipboard(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window); if (ret.empty()) { ret = _get_clipboard(XA_PRIMARY, x11_window); }; return ret; } Bool OS_X11::_predicate_clipboard_save_targets(Display *display, XEvent *event, XPointer arg) { if (event->xany.window == *(Window *)arg) { return (event->type == SelectionRequest) || (event->type == SelectionNotify); } else { return False; } } void OS_X11::_clipboard_transfer_ownership(Atom p_source, Window x11_window) const { Window selection_owner = XGetSelectionOwner(x11_display, p_source); if (selection_owner != x11_window) { return; } // Block events polling while processing selection events. MutexLock mutex_lock(events_mutex); Atom clipboard_manager = XInternAtom(x11_display, "CLIPBOARD_MANAGER", False); Atom save_targets = XInternAtom(x11_display, "SAVE_TARGETS", False); XConvertSelection(x11_display, clipboard_manager, save_targets, None, x11_window, CurrentTime); // Process events from the queue. while (true) { if (!_wait_for_events()) { // Error or timeout, abort. break; } // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_save_targets, (XPointer)&x11_window)) { switch (ev.type) { case SelectionRequest: _handle_selection_request_event(&(ev.xselectionrequest)); break; case SelectionNotify: { if (ev.xselection.target == save_targets) { // Once SelectionNotify is received, we're done whether it succeeded or not. return; } break; } } } } } String OS_X11::get_name() const { return "X11"; } Error OS_X11::shell_open(String p_uri) { Error ok; int err_code; List<String> args; args.push_back(p_uri); // Agnostic ok = execute("xdg-open", args, true, NULL, NULL, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } // GNOME args.push_front("open"); // The command is `gio open`, so we need to add it to args ok = execute("gio", args, true, NULL, NULL, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } args.pop_front(); ok = execute("gvfs-open", args, true, NULL, NULL, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } // KDE ok = execute("kde-open5", args, true, NULL, NULL, &err_code); if (ok == OK && !err_code) { return OK; } ok = execute("kde-open", args, true, NULL, NULL, &err_code); return !err_code ? ok : FAILED; } bool OS_X11::_check_internal_feature_support(const String &p_feature) { return p_feature == "pc"; } String OS_X11::get_config_path() const { if (has_environment("XDG_CONFIG_HOME")) { return get_environment("XDG_CONFIG_HOME"); } else if (has_environment("HOME")) { return get_environment("HOME").plus_file(".config"); } else { return "."; } } String OS_X11::get_data_path() const { if (has_environment("XDG_DATA_HOME")) { return get_environment("XDG_DATA_HOME"); } else if (has_environment("HOME")) { return get_environment("HOME").plus_file(".local/share"); } else { return get_config_path(); } } String OS_X11::get_cache_path() const { if (has_environment("XDG_CACHE_HOME")) { return get_environment("XDG_CACHE_HOME"); } else if (has_environment("HOME")) { return get_environment("HOME").plus_file(".cache"); } else { return get_config_path(); } } String OS_X11::get_system_dir(SystemDir p_dir) const { String xdgparam; switch (p_dir) { case SYSTEM_DIR_DESKTOP: { xdgparam = "DESKTOP"; } break; case SYSTEM_DIR_DCIM: { xdgparam = "PICTURES"; } break; case SYSTEM_DIR_DOCUMENTS: { xdgparam = "DOCUMENTS"; } break; case SYSTEM_DIR_DOWNLOADS: { xdgparam = "DOWNLOAD"; } break; case SYSTEM_DIR_MOVIES: { xdgparam = "VIDEOS"; } break; case SYSTEM_DIR_MUSIC: { xdgparam = "MUSIC"; } break; case SYSTEM_DIR_PICTURES: { xdgparam = "PICTURES"; } break; case SYSTEM_DIR_RINGTONES: { xdgparam = "MUSIC"; } break; } String pipe; List<String> arg; arg.push_back(xdgparam); Error err = const_cast<OS_X11 *>(this)->execute("xdg-user-dir", arg, true, NULL, &pipe); if (err != OK) return "."; return pipe.strip_edges(); } void OS_X11::move_window_to_foreground() { XEvent xev; Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = net_active_window; xev.xclient.format = 32; xev.xclient.data.l[0] = 1; xev.xclient.data.l[1] = CurrentTime; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(x11_display); } void OS_X11::set_cursor_shape(CursorShape p_shape) { ERR_FAIL_INDEX(p_shape, CURSOR_MAX); if (p_shape == current_cursor) { return; } if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) { if (cursors[p_shape] != None) { XDefineCursor(x11_display, x11_window, cursors[p_shape]); } else if (cursors[CURSOR_ARROW] != None) { XDefineCursor(x11_display, x11_window, cursors[CURSOR_ARROW]); } } current_cursor = p_shape; } OS::CursorShape OS_X11::get_cursor_shape() const { return current_cursor; } void OS_X11::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) { if (p_cursor.is_valid()) { Map<CursorShape, Vector<Variant> >::Element *cursor_c = cursors_cache.find(p_shape); if (cursor_c) { if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) { set_cursor_shape(p_shape); return; } cursors_cache.erase(p_shape); } Ref<Texture> texture = p_cursor; Ref<AtlasTexture> atlas_texture = p_cursor; Ref<Image> image; Size2 texture_size; Rect2 atlas_rect; if (texture.is_valid()) { image = texture->get_data(); } if (!image.is_valid() && atlas_texture.is_valid()) { texture = atlas_texture->get_atlas(); atlas_rect.size.width = texture->get_width(); atlas_rect.size.height = texture->get_height(); atlas_rect.position.x = atlas_texture->get_region().position.x; atlas_rect.position.y = atlas_texture->get_region().position.y; texture_size.width = atlas_texture->get_region().size.x; texture_size.height = atlas_texture->get_region().size.y; } else if (image.is_valid()) { texture_size.width = texture->get_width(); texture_size.height = texture->get_height(); } ERR_FAIL_COND(!texture.is_valid()); ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0); ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256); ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height); image = texture->get_data(); ERR_FAIL_COND(!image.is_valid()); // Create the cursor structure XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height); XcursorUInt image_size = texture_size.width * texture_size.height; XcursorDim size = sizeof(XcursorPixel) * image_size; cursor_image->version = 1; cursor_image->size = size; cursor_image->xhot = p_hotspot.x; cursor_image->yhot = p_hotspot.y; // allocate memory to contain the whole file cursor_image->pixels = (XcursorPixel *)memalloc(size); image->lock(); for (XcursorPixel index = 0; index < image_size; index++) { int row_index = floor(index / texture_size.width) + atlas_rect.position.y; int column_index = (index % int(texture_size.width)) + atlas_rect.position.x; if (atlas_texture.is_valid()) { column_index = MIN(column_index, atlas_rect.size.width - 1); row_index = MIN(row_index, atlas_rect.size.height - 1); } *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32(); } image->unlock(); ERR_FAIL_COND(cursor_image->pixels == NULL); // Save it for a further usage cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image); Vector<Variant> params; params.push_back(p_cursor); params.push_back(p_hotspot); cursors_cache.insert(p_shape, params); if (p_shape == current_cursor) { if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) { XDefineCursor(x11_display, x11_window, cursors[p_shape]); } } memfree(cursor_image->pixels); XcursorImageDestroy(cursor_image); } else { // Reset to default system cursor if (img[p_shape]) { cursors[p_shape] = XcursorImageLoadCursor(x11_display, img[p_shape]); } CursorShape c = current_cursor; current_cursor = CURSOR_MAX; set_cursor_shape(c); cursors_cache.erase(p_shape); } } void OS_X11::release_rendering_thread() { #if defined(OPENGL_ENABLED) context_gl->release_current(); #endif } void OS_X11::make_rendering_thread() { #if defined(OPENGL_ENABLED) context_gl->make_current(); #endif } void OS_X11::swap_buffers() { #if defined(OPENGL_ENABLED) context_gl->swap_buffers(); #endif } void OS_X11::alert(const String &p_alert, const String &p_title) { if (is_no_window_mode_enabled()) { print_line("ALERT: " + p_title + ": " + p_alert); return; } const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" }; String path = get_environment("PATH"); Vector<String> path_elems = path.split(":", false); String program; for (int i = 0; i < path_elems.size(); i++) { for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) { String tested_path = path_elems[i].plus_file(message_programs[k]); if (FileAccess::exists(tested_path)) { program = tested_path; break; } } if (program.length()) break; } List<String> args; if (program.ends_with("zenity")) { args.push_back("--error"); args.push_back("--width"); args.push_back("500"); args.push_back("--title"); args.push_back(p_title); args.push_back("--text"); args.push_back(p_alert); } if (program.ends_with("kdialog")) { args.push_back("--error"); args.push_back(p_alert); args.push_back("--title"); args.push_back(p_title); } if (program.ends_with("Xdialog")) { args.push_back("--title"); args.push_back(p_title); args.push_back("--msgbox"); args.push_back(p_alert); args.push_back("0"); args.push_back("0"); } if (program.ends_with("xmessage")) { args.push_back("-center"); args.push_back("-title"); args.push_back(p_title); args.push_back(p_alert); } if (program.length()) { execute(program, args, true); } else { print_line(p_alert); } } bool g_set_icon_error = false; int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) { g_set_icon_error = true; return 0; } void OS_X11::set_icon(const Ref<Image> &p_icon) { int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler); Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False); if (p_icon.is_valid()) { Ref<Image> img = p_icon->duplicate(); img->convert(Image::FORMAT_RGBA8); while (true) { int w = img->get_width(); int h = img->get_height(); if (g_set_icon_error) { g_set_icon_error = false; WARN_PRINT("Icon too large, attempting to resize icon."); int new_width, new_height; if (w > h) { new_width = w / 2; new_height = h * new_width / w; } else { new_height = h / 2; new_width = w * new_height / h; } w = new_width; h = new_height; if (!w || !h) { WARN_PRINT("Unable to set icon."); break; } img->resize(w, h, Image::INTERPOLATE_CUBIC); } // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits Vector<long> pd; pd.resize(2 + w * h); pd.write[0] = w; pd.write[1] = h; PoolVector<uint8_t>::Read r = img->get_data().read(); long *wr = &pd.write[2]; uint8_t const *pr = r.ptr(); for (int i = 0; i < w * h; i++) { long v = 0; // A R G B v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2]; *wr++ = v; pr += 4; } if (net_wm_icon != None) { XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size()); } if (!g_set_icon_error) break; } } else { XDeleteProperty(x11_display, x11_window, net_wm_icon); } XFlush(x11_display); XSetErrorHandler(oldHandler); } void OS_X11::force_process_input() { process_xevents(); // get rid of pending events #ifdef JOYDEV_ENABLED joypad->process_joypads(); #endif } void OS_X11::run() { force_quit = false; if (!main_loop) return; main_loop->init(); //uint64_t last_ticks=get_ticks_usec(); //int frames=0; //uint64_t frame=0; while (!force_quit) { process_xevents(); // get rid of pending events #ifdef JOYDEV_ENABLED joypad->process_joypads(); #endif if (Main::iteration()) break; }; main_loop->finish(); } bool OS_X11::is_joy_known(int p_device) { return input->is_joy_mapped(p_device); } String OS_X11::get_joy_guid(int p_device) const { return input->get_joy_guid_remapped(p_device); } void OS_X11::_set_use_vsync(bool p_enable) { #if defined(OPENGL_ENABLED) if (context_gl) context_gl->set_use_vsync(p_enable); #endif } /* bool OS_X11::is_vsync_enabled() const { if (context_gl) return context_gl->is_using_vsync(); return true; } */ void OS_X11::set_context(int p_context) { XClassHint *classHint = XAllocClassHint(); if (classHint) { CharString name_str; switch (p_context) { case CONTEXT_EDITOR: name_str = "Godot_Editor"; break; case CONTEXT_PROJECTMAN: name_str = "Godot_ProjectList"; break; case CONTEXT_ENGINE: name_str = "Godot_Engine"; break; } CharString class_str; if (p_context == CONTEXT_ENGINE) { String config_name = GLOBAL_GET("application/config/name"); if (config_name.length() == 0) { class_str = "Godot_Engine"; } else { class_str = config_name.utf8(); } } else { class_str = "Godot"; } classHint->res_class = class_str.ptrw(); classHint->res_name = name_str.ptrw(); XSetClassHint(x11_display, x11_window, classHint); XFree(classHint); } } OS::PowerState OS_X11::get_power_state() { return power_manager->get_power_state(); } int OS_X11::get_power_seconds_left() { return power_manager->get_power_seconds_left(); } int OS_X11::get_power_percent_left() { return power_manager->get_power_percent_left(); } void OS_X11::disable_crash_handler() { crash_handler.disable(); } bool OS_X11::is_disable_crash_handler() const { return crash_handler.is_disabled(); } static String get_mountpoint(const String &p_path) { struct stat s; if (stat(p_path.utf8().get_data(), &s)) { return ""; } #ifdef HAVE_MNTENT dev_t dev = s.st_dev; FILE *fd = setmntent("/proc/mounts", "r"); if (!fd) { return ""; } struct mntent mnt; char buf[1024]; size_t buflen = 1024; while (getmntent_r(fd, &mnt, buf, buflen)) { if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) { endmntent(fd); return String(mnt.mnt_dir); } } endmntent(fd); #endif return ""; } Error OS_X11::move_to_trash(const String &p_path) { String trash_can = ""; String mnt = get_mountpoint(p_path); // If there is a directory "[Mountpoint]/.Trash-[UID]/files", use it as the trash can. if (mnt != "") { String path(mnt + "/.Trash-" + itos(getuid()) + "/files"); struct stat s; if (!stat(path.utf8().get_data(), &s)) { trash_can = path; } } // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash/files" as the trash can. if (trash_can == "") { char *dhome = getenv("XDG_DATA_HOME"); if (dhome) { trash_can = String(dhome) + "/Trash/files"; } } // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash/files" as the trash can. if (trash_can == "") { char *home = getenv("HOME"); if (home) { trash_can = String(home) + "/.local/share/Trash/files"; } } // Issue an error if none of the previous locations is appropriate for the trash can. if (trash_can == "") { ERR_PRINTS("move_to_trash: Could not determine the trash can location"); return FAILED; } // Create needed directories for decided trash can location. DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); Error err = dir_access->make_dir_recursive(trash_can); memdelete(dir_access); // Issue an error if trash can is not created proprely. if (err != OK) { ERR_PRINTS("move_to_trash: Could not create the trash can \"" + trash_can + "\""); return err; } // The trash can is successfully created, now move the given resource to it. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints. List<String> mv_args; mv_args.push_back(p_path); mv_args.push_back(trash_can); int retval; err = execute("mv", mv_args, true, NULL, NULL, &retval); // Issue an error if "mv" failed to move the given resource to the trash can. if (err != OK || retval != 0) { ERR_PRINTS("move_to_trash: Could not move the resource \"" + p_path + "\" to the trash can \"" + trash_can + "\""); return FAILED; } return OK; } OS::LatinKeyboardVariant OS_X11::get_latin_keyboard_variant() const { XkbDescRec *xkbdesc = XkbAllocKeyboard(); ERR_FAIL_COND_V(!xkbdesc, LATIN_KEYBOARD_QWERTY); XkbGetNames(x11_display, XkbSymbolsNameMask, xkbdesc); ERR_FAIL_COND_V(!xkbdesc->names, LATIN_KEYBOARD_QWERTY); ERR_FAIL_COND_V(!xkbdesc->names->symbols, LATIN_KEYBOARD_QWERTY); char *layout = XGetAtomName(x11_display, xkbdesc->names->symbols); ERR_FAIL_COND_V(!layout, LATIN_KEYBOARD_QWERTY); Vector<String> info = String(layout).split("+"); ERR_FAIL_INDEX_V(1, info.size(), LATIN_KEYBOARD_QWERTY); if (info[1].find("colemak") != -1) { return LATIN_KEYBOARD_COLEMAK; } else if (info[1].find("qwertz") != -1) { return LATIN_KEYBOARD_QWERTZ; } else if (info[1].find("azerty") != -1) { return LATIN_KEYBOARD_AZERTY; } else if (info[1].find("qzerty") != -1) { return LATIN_KEYBOARD_QZERTY; } else if (info[1].find("dvorak") != -1) { return LATIN_KEYBOARD_DVORAK; } else if (info[1].find("neo") != -1) { return LATIN_KEYBOARD_NEO; } return LATIN_KEYBOARD_QWERTY; } int OS_X11::keyboard_get_layout_count() const { int _group_count = 0; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); const Atom *groups = kbd->names->groups; if (kbd->ctrls != NULL) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } XkbFreeKeyboard(kbd, 0, true); } return _group_count; } int OS_X11::keyboard_get_current_layout() const { XkbStateRec state; XkbGetState(x11_display, XkbUseCoreKbd, &state); return state.group; } void OS_X11::keyboard_set_current_layout(int p_index) { ERR_FAIL_INDEX(p_index, keyboard_get_layout_count()); XkbLockGroup(x11_display, XkbUseCoreKbd, p_index); } String OS_X11::keyboard_get_layout_language(int p_index) const { String ret; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); XkbGetNames(x11_display, XkbGroupNamesMask, kbd); int _group_count = 0; const Atom *groups = kbd->names->groups; if (kbd->ctrls != NULL) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } Atom names = kbd->names->symbols; if (names != None) { char *name = XGetAtomName(x11_display, names); Vector<String> info = String(name).split("+"); if (p_index >= 0 && p_index < _group_count) { if (p_index + 1 < info.size()) { ret = info[p_index + 1]; // Skip "pc" at the start and "inet"/"group" at the end of symbols. } else { ret = "en"; // No symbol for layout fallback to "en". } } else { ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ")."); } XFree(name); } XkbFreeKeyboard(kbd, 0, true); } return ret.substr(0, 2); } String OS_X11::keyboard_get_layout_name(int p_index) const { String ret; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); XkbGetNames(x11_display, XkbGroupNamesMask, kbd); int _group_count = 0; const Atom *groups = kbd->names->groups; if (kbd->ctrls != NULL) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } if (p_index >= 0 && p_index < _group_count) { char *full_name = XGetAtomName(x11_display, groups[p_index]); ret.parse_utf8(full_name); XFree(full_name); } else { ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ")."); } XkbFreeKeyboard(kbd, 0, true); } return ret; } void OS_X11::update_real_mouse_position() { Window root_return, child_return; int root_x, root_y, win_x, win_y; unsigned int mask_return; Bool xquerypointer_result = XQueryPointer(x11_display, x11_window, &root_return, &child_return, &root_x, &root_y, &win_x, &win_y, &mask_return); if (xquerypointer_result) { if (win_x > 0 && win_y > 0 && win_x <= current_videomode.width && win_y <= current_videomode.height) { last_mouse_pos.x = win_x; last_mouse_pos.y = win_y; last_mouse_pos_valid = true; input->set_mouse_position(last_mouse_pos); } } } OS_X11::OS_X11() { #ifdef PULSEAUDIO_ENABLED AudioDriverManager::add_driver(&driver_pulseaudio); #endif #ifdef ALSA_ENABLED AudioDriverManager::add_driver(&driver_alsa); #endif xi.opcode = 0; xi.last_relative_time = 0; layered_window = false; minimized = false; window_focused = true; xim_style = 0L; mouse_mode = MOUSE_MODE_VISIBLE; last_position_before_fs = Vector2(); }
/* Copyright (c) 2012, Antonie Jovanoski * * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com> */ #include "qtweetstatusupdatewithmedia.h" #include <QHttpMultiPart> #include <QHttpPart> #include <QFile> #include <QNetworkReply> #include <QNetworkRequest> #include "json/qjsondocument.h" #include "json/qjsonobject.h" #include "qtweetconvert.h" #include "qtweetstatus.h" QTweetStatusUpdateWithMedia::QTweetStatusUpdateWithMedia(QObject *parent) : QTweetNetBase(parent), m_inReplyToStatusID(0), m_latitude(91.0f), m_longitude(181.0f), m_displayCoordinates(false) { } QTweetStatusUpdateWithMedia::QTweetStatusUpdateWithMedia(OAuthTwitter *oauthTwitter, QObject *parent) : QTweetNetBase(oauthTwitter, parent), m_inReplyToStatusID(0), m_latitude(91.0f), m_longitude(181.0f), m_displayCoordinates(false) { } void QTweetStatusUpdateWithMedia::post() { if (!isAuthenticationEnabled()) { qCritical("Needs authentication to be enabled"); return; } QUrl url("https://upload.twitter.com/1/statuses/update_with_media.json"); QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::POST); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart statusPart; statusPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"status\"")); statusPart.setBody(m_status.toUtf8()); multiPart->append(statusPart); QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"media[]\"")); QFile *file = new QFile(m_imageFilename); file->open(QFile::ReadOnly); imagePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(imagePart); if (m_sensitive) { QHttpPart possiblySensitivePart; possiblySensitivePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"possibly_sensitive\"")); possiblySensitivePart.setBody("true"); multiPart->append(possiblySensitivePart); } if (m_inReplyToStatusID) { QHttpPart inReplyToStatusIDPart; inReplyToStatusIDPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"in_reply_to_status_id\"")); inReplyToStatusIDPart.setBody(QString::number(m_inReplyToStatusID).toUtf8()); multiPart->append(inReplyToStatusIDPart); } if (m_latitude < 90.0f && m_latitude > -90.0f) { QHttpPart latitudePart; latitudePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"lat\"")); latitudePart.setBody(QString::number(m_latitude).toUtf8()); multiPart->append(latitudePart); } if (m_longitude < 181.0f && m_longitude > -180.0f) { QHttpPart longitudePart; longitudePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"long\"")); longitudePart.setBody(QString::number(m_longitude).toUtf8()); multiPart->append(longitudePart); } if (!m_placeID.isEmpty()) { QHttpPart placeIDPart; placeIDPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"place_id\"")); placeIDPart.setBody(m_placeID.toUtf8()); multiPart->append(placeIDPart); } if (m_displayCoordinates) { QHttpPart displayCoordinatesPart; displayCoordinatesPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"display_coordinates\"")); displayCoordinatesPart.setBody("true"); multiPart->append(displayCoordinatesPart); } QNetworkRequest req(url); req.setRawHeader(AUTH_HEADER, oauthHeader); QNetworkReply *reply = oauthTwitter()->networkAccessManager()->post(req, multiPart); multiPart->setParent(reply); connect(reply, SIGNAL(finished()), this, SLOT(reply())); } void QTweetStatusUpdateWithMedia::parseJsonFinished(const QJsonDocument &jsonDoc) { if (jsonDoc.isObject()) { QTweetStatus status = QTweetConvert::jsonObjectToStatus(jsonDoc.object()); emit postedUpdate(status); } } Updated url for QTweetStatusUpdateWithMedia. /* Copyright (c) 2012, Antonie Jovanoski * * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com> */ #include "qtweetstatusupdatewithmedia.h" #include <QHttpMultiPart> #include <QHttpPart> #include <QFile> #include <QNetworkReply> #include <QNetworkRequest> #include "json/qjsondocument.h" #include "json/qjsonobject.h" #include "qtweetconvert.h" #include "qtweetstatus.h" QTweetStatusUpdateWithMedia::QTweetStatusUpdateWithMedia(QObject *parent) : QTweetNetBase(parent), m_inReplyToStatusID(0), m_latitude(91.0f), m_longitude(181.0f), m_displayCoordinates(false) { } QTweetStatusUpdateWithMedia::QTweetStatusUpdateWithMedia(OAuthTwitter *oauthTwitter, QObject *parent) : QTweetNetBase(oauthTwitter, parent), m_inReplyToStatusID(0), m_latitude(91.0f), m_longitude(181.0f), m_displayCoordinates(false) { } void QTweetStatusUpdateWithMedia::post() { if (!isAuthenticationEnabled()) { qCritical("Needs authentication to be enabled"); return; } QUrl url("https://api.twitter.com/1.1/statuses/update_with_media.json"); QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::POST); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart statusPart; statusPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"status\"")); statusPart.setBody(m_status.toUtf8()); multiPart->append(statusPart); QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"media[]\"")); QFile *file = new QFile(m_imageFilename); file->open(QFile::ReadOnly); imagePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(imagePart); if (m_sensitive) { QHttpPart possiblySensitivePart; possiblySensitivePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"possibly_sensitive\"")); possiblySensitivePart.setBody("true"); multiPart->append(possiblySensitivePart); } if (m_inReplyToStatusID) { QHttpPart inReplyToStatusIDPart; inReplyToStatusIDPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"in_reply_to_status_id\"")); inReplyToStatusIDPart.setBody(QString::number(m_inReplyToStatusID).toUtf8()); multiPart->append(inReplyToStatusIDPart); } if (m_latitude < 90.0f && m_latitude > -90.0f) { QHttpPart latitudePart; latitudePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"lat\"")); latitudePart.setBody(QString::number(m_latitude).toUtf8()); multiPart->append(latitudePart); } if (m_longitude < 181.0f && m_longitude > -180.0f) { QHttpPart longitudePart; longitudePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"long\"")); longitudePart.setBody(QString::number(m_longitude).toUtf8()); multiPart->append(longitudePart); } if (!m_placeID.isEmpty()) { QHttpPart placeIDPart; placeIDPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"place_id\"")); placeIDPart.setBody(m_placeID.toUtf8()); multiPart->append(placeIDPart); } if (m_displayCoordinates) { QHttpPart displayCoordinatesPart; displayCoordinatesPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"display_coordinates\"")); displayCoordinatesPart.setBody("true"); multiPart->append(displayCoordinatesPart); } QNetworkRequest req(url); req.setRawHeader(AUTH_HEADER, oauthHeader); QNetworkReply *reply = oauthTwitter()->networkAccessManager()->post(req, multiPart); multiPart->setParent(reply); connect(reply, SIGNAL(finished()), this, SLOT(reply())); } void QTweetStatusUpdateWithMedia::parseJsonFinished(const QJsonDocument &jsonDoc) { if (jsonDoc.isObject()) { QTweetStatus status = QTweetConvert::jsonObjectToStatus(jsonDoc.object()); emit postedUpdate(status); } }
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: forbiddencharacterstable.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:44:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _FORBIDDENCHARACTERSTABLE_HXX #define _FORBIDDENCHARACTERSTABLE_HXX #ifndef _TABLE_HXX //autogen #include <tools/table.hxx> #endif #include <vos/refernce.hxx> #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_I18N_FORBIDDENCHARACTERS_HPP_ #include <com/sun/star/i18n/ForbiddenCharacters.hpp> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; }}}} struct ForbiddenCharactersInfo { com::sun::star::i18n::ForbiddenCharacters aForbiddenChars; BOOL bTemporary; }; DECLARE_TABLE( SvxForbiddenCharactersTableImpl, ForbiddenCharactersInfo* ) class SVX_DLLPUBLIC SvxForbiddenCharactersTable : public SvxForbiddenCharactersTableImpl, public vos::OReference { private: ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF; public: SvxForbiddenCharactersTable( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xMSF, USHORT nISize = 4, USHORT nGrow = 4 ); ~SvxForbiddenCharactersTable(); const com::sun::star::i18n::ForbiddenCharacters* GetForbiddenCharacters( USHORT nLanuage, BOOL bGetDefault ) const; void SetForbiddenCharacters( USHORT nLanuage , const com::sun::star::i18n::ForbiddenCharacters& ); void ClearForbiddenCharacters( USHORT nLanuage ); }; #endif // _FORBIDDENCHARACTERSTABLE_HXX INTEGRATION: CWS changefileheader (1.4.1256); FILE MERGED 2008/04/01 15:49:15 thb 1.4.1256.3: #i85898# Stripping all external header guards 2008/04/01 12:46:20 thb 1.4.1256.2: #i85898# Stripping all external header guards 2008/03/31 14:17:55 rt 1.4.1256.1: #i87441# Change license header to LPGL v3. /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: forbiddencharacterstable.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _FORBIDDENCHARACTERSTABLE_HXX #define _FORBIDDENCHARACTERSTABLE_HXX #ifndef _TABLE_HXX //autogen #include <tools/table.hxx> #endif #include <vos/refernce.hxx> #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/i18n/ForbiddenCharacters.hpp> #include "svx/svxdllapi.h" namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; }}}} struct ForbiddenCharactersInfo { com::sun::star::i18n::ForbiddenCharacters aForbiddenChars; BOOL bTemporary; }; DECLARE_TABLE( SvxForbiddenCharactersTableImpl, ForbiddenCharactersInfo* ) class SVX_DLLPUBLIC SvxForbiddenCharactersTable : public SvxForbiddenCharactersTableImpl, public vos::OReference { private: ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF; public: SvxForbiddenCharactersTable( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xMSF, USHORT nISize = 4, USHORT nGrow = 4 ); ~SvxForbiddenCharactersTable(); const com::sun::star::i18n::ForbiddenCharacters* GetForbiddenCharacters( USHORT nLanuage, BOOL bGetDefault ) const; void SetForbiddenCharacters( USHORT nLanuage , const com::sun::star::i18n::ForbiddenCharacters& ); void ClearForbiddenCharacters( USHORT nLanuage ); }; #endif // _FORBIDDENCHARACTERSTABLE_HXX
/*========================================================================= Program: Visualization Toolkit Module: vtkPostgreSQLDatabase.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkPostgreSQLDatabase.h" #include "vtkPostgreSQLDatabasePrivate.h" #include "vtkPostgreSQLQuery.h" #include "vtkSQLDatabaseSchema.h" #include "vtkObjectFactory.h" #include "vtkStringArray.h" #include <vtksys/SystemTools.hxx> #include <vtksys/ios/sstream> #define PQXX_ALLOW_LONG_LONG #include <pqxx/pqxx> vtkStandardNewMacro(vtkPostgreSQLDatabase); vtkCxxRevisionMacro(vtkPostgreSQLDatabase, "1.19"); // ---------------------------------------------------------------------- vtkPostgreSQLDatabase::vtkPostgreSQLDatabase() { this->Connection = 0; this->ConnectionMTime = this->MTime; this->DatabaseType = 0; this->SetDatabaseType("psql"); this->HostName = 0; this->User = 0; this->Password = 0; this->DatabaseName = 0; this->ServerPort = -1; this->ConnectOptions = 0; } // ---------------------------------------------------------------------- vtkPostgreSQLDatabase::~vtkPostgreSQLDatabase() { if ( this->IsOpen() ) { this->Close(); } this->SetHostName( 0 ); this->SetUser( 0 ); this->SetPassword( 0 ); this->SetDatabaseName( 0 ); this->SetConnectOptions( 0 ); this->SetDatabaseType( 0 ); } // ---------------------------------------------------------------------- void vtkPostgreSQLDatabase::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Connection: "; if ( this->Connection ) { os << this->Connection << endl; } else { os << "(null)" << endl; } os << indent << "DatabaseType: " << (this->DatabaseType ? this->DatabaseType : "NULL") << endl; os << indent << "HostName: " << (this->HostName ? this->HostName : "NULL") << endl; os << indent << "User: " << (this->User ? this->User : "NULL") << endl; os << indent << "Password: " << (this->Password ? this->Password : "NULL") << endl; os << indent << "DatabaseName: " << (this->DatabaseName ? this->DatabaseName : "NULL") << endl; os << indent << "ServerPort: " << this->ServerPort << endl; os << indent << "ConnectOptions: " << (this->ConnectOptions ? this->ConnectOptions : "NULL") << endl; } // ---------------------------------------------------------------------- vtkStdString vtkPostgreSQLDatabase::GetColumnSpecification( vtkSQLDatabaseSchema* schema, int tblHandle, int colHandle ) { vtksys_ios::ostringstream queryStr; queryStr << schema->GetColumnNameFromHandle( tblHandle, colHandle ); // Figure out column type int colType = schema->GetColumnTypeFromHandle( tblHandle, colHandle ); vtkStdString colTypeStr; switch ( static_cast<vtkSQLDatabaseSchema::DatabaseColumnType>( colType ) ) { case vtkSQLDatabaseSchema::SERIAL: colTypeStr = "SERIAL"; break; case vtkSQLDatabaseSchema::SMALLINT: colTypeStr = "SMALLINT"; break; case vtkSQLDatabaseSchema::INTEGER: colTypeStr = "INTEGER"; break; case vtkSQLDatabaseSchema::BIGINT: colTypeStr = "BIGINT"; break; case vtkSQLDatabaseSchema::VARCHAR: colTypeStr = "VARCHAR"; break; case vtkSQLDatabaseSchema::TEXT: colTypeStr = "TEXT"; break; case vtkSQLDatabaseSchema::REAL: colTypeStr = "REAL"; break; case vtkSQLDatabaseSchema::DOUBLE: colTypeStr = "DOUBLE PRECISION"; break; case vtkSQLDatabaseSchema::BLOB: colTypeStr = "BYTEA"; break; case vtkSQLDatabaseSchema::TIME: colTypeStr = "TIME"; break; case vtkSQLDatabaseSchema::DATE: colTypeStr = "DATE"; break; case vtkSQLDatabaseSchema::TIMESTAMP: colTypeStr = "TIMESTAMP WITH TIME ZONE"; break; } if ( colTypeStr.size() ) { queryStr << " " << colTypeStr; } else // if ( colTypeStr.size() ) { vtkGenericWarningMacro( "Unable to get column specification: unsupported data type " << colType ); return vtkStdString(); } // Decide whether size is allowed, required, or unused int colSizeType = 0; switch ( static_cast<vtkSQLDatabaseSchema::DatabaseColumnType>( colType ) ) { case vtkSQLDatabaseSchema::SERIAL: colSizeType = 0; break; case vtkSQLDatabaseSchema::SMALLINT: colSizeType = 0; break; case vtkSQLDatabaseSchema::INTEGER: colSizeType = 0; break; case vtkSQLDatabaseSchema::BIGINT: colSizeType = 0; break; case vtkSQLDatabaseSchema::VARCHAR: colSizeType = -1; break; case vtkSQLDatabaseSchema::TEXT: colSizeType = 0; break; case vtkSQLDatabaseSchema::REAL: colSizeType = 0; break; case vtkSQLDatabaseSchema::DOUBLE: colSizeType = 0; break; case vtkSQLDatabaseSchema::BLOB: colSizeType = 0; break; case vtkSQLDatabaseSchema::TIME: colSizeType = 1; break; case vtkSQLDatabaseSchema::DATE: colSizeType = 0; break; case vtkSQLDatabaseSchema::TIMESTAMP: colSizeType = 0; break; } // Specify size if allowed or required if ( colSizeType ) { int colSize = schema->GetColumnSizeFromHandle( tblHandle, colHandle ); // IF size is provided but absurd, // OR, if size is required but not provided OR absurd, // THEN assign the default size. if ( ( colSize < 0 ) || ( colSizeType == -1 && colSize < 1 ) ) { colSize = VTK_SQL_DEFAULT_COLUMN_SIZE; } // At this point, we have either a valid size if required, or a possibly null valid size // if not required. Thus, skip sizing in the latter case. if ( colSize > 0 ) { queryStr << "(" << colSize << ")"; } } vtkStdString attStr = schema->GetColumnAttributesFromHandle( tblHandle, colHandle ); if ( attStr.size() ) { queryStr << " " << attStr; } return queryStr.str(); } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::Open() { if ( ! this->HostName || ! this->DatabaseName ) { //this->LastErrorText = "Cannot open database because HostName and/or DatabaseName are null."; vtkErrorMacro(<< this->GetLastErrorText()); return false; } if ( this->Connection ) { if ( this->ConnectionMTime > this->URLMTime ) { return true; // we already had that database open. } this->Close(); // close the old connection before opening a new one } vtkstd::string options( "host=" ); options += this->HostName; options += " dbname="; options += this->DatabaseName; if ( this->ServerPort ) { options += " port="; options += this->ServerPort; } if ( this->User && strlen( this->User ) > 0 ) { options += " user="; options += this->User; } if ( this->Password && strlen( this->Password ) > 0 ) { options += " password="; options += this->Password; } if ( this->ConnectOptions && strlen( this->ConnectOptions ) > 0 ) { options += this->ConnectOptions; } try { this->Connection = new vtkPostgreSQLDatabasePrivate( options.c_str() ); this->ConnectionMTime.Modified(); } catch ( pqxx::sql_error& e ) { this->Connection->LastErrorText = e.what(); return false; } catch ( pqxx::broken_connection& e ) { if ( this->Connection ) { delete this->Connection; this->Connection = 0; } return false; } this->Connection->LastErrorText.clear(); return true; } // ---------------------------------------------------------------------- void vtkPostgreSQLDatabase::Close() { if ( this->Connection ) { delete this->Connection; this->Connection = 0; this->URLMTime.Modified(); // Force a re-open to occur when Open() is called. } } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::IsOpen() { return this->Connection != 0; } // ---------------------------------------------------------------------- vtkSQLQuery* vtkPostgreSQLDatabase::GetQueryInstance() { vtkPostgreSQLQuery* query = vtkPostgreSQLQuery::New(); query->SetDatabase( this ); return query; } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::HasError() { // Assume that an unopened connection is not a symptom of failure. return this->Connection ? this->Connection->LastErrorText != NULL : false; } // ---------------------------------------------------------------------- const char* vtkPostgreSQLDatabase::GetLastErrorText() { if ( ! this->Connection ) { return "Database is not open."; } else { return this->Connection->LastErrorText; } } // ---------------------------------------------------------------------- vtkStdString vtkPostgreSQLDatabase::GetURL() { vtkStdString url = this->GetDatabaseType(); url += "://"; if ( this->HostName && this->DatabaseName ) { if ( this->User ) { url += this->User; if ( this->Password ) { url += ":"; url += this->Password; } url += "@"; } url += this->HostName; url += "/"; url += this->DatabaseName; } return url; } // ---------------------------------------------------------------------- vtkStringArray* vtkPostgreSQLDatabase::GetTables() { if ( ! this->Connection ) { // This will always be "Database not open." vtkErrorMacro(<< this->GetLastErrorText()); return 0; } // NB: Other columns of interest include table_catalog, table_schema, table_type, // self_referencing_column_name, reference_generation, user_defined_type_catalog, // user_defined_type_schema, user_defined_type_name, is_insertable_into, is_typed, // commit_action vtkSQLQuery* query = this->GetQueryInstance(); query->SetQuery( "SELECT table_name FROM information_schema.tables" " WHERE table_schema='public' and table_type='BASE TABLE'" ); bool status = query->Execute(); if ( ! status ) { vtkErrorMacro(<< "Database returned error: " << query->GetLastErrorText()); this->Connection->LastErrorText = query->GetLastErrorText(); query->Delete(); return 0; } vtkDebugMacro(<< "GetTables(): SQL query succeeded." ); vtkStringArray* results = vtkStringArray::New(); while ( query->NextRow() ) { results->InsertNextValue( query->DataValue( 0 ).ToString() ); } query->Delete(); this->Connection->LastErrorText.clear(); return results; } // ---------------------------------------------------------------------- vtkStringArray* vtkPostgreSQLDatabase::GetRecord( const char* table ) { // NB: There are *too many* other column names to list. Even the ones // currently in the query below are probably over the top. But there's // just so much peanut-buttery goodness in the table, I couldn't resist. vtkSQLQuery* query = this->GetQueryInstance(); vtkStdString text( "SELECT column_name,column_default,data_type,is_nullable,character_maximum_length,numeric_precision,datetime_precision" " FROM information_schema.columns" " WHERE table_name='" ); text += table; text += "' ORDER BY ordinal_position"; query->SetQuery( text.c_str() ); bool status = query->Execute(); if ( ! status ) { vtkErrorMacro(<< "GetRecord(" << table << "): Database returned error: " << query->GetLastErrorText()); this->Connection->LastErrorText = query->GetLastErrorText(); query->Delete(); return 0; } // Each row in the results that come back from this query // describes a single column in the table. vtkStringArray* results = vtkStringArray::New(); while ( query->NextRow() ) { results->InsertNextValue( query->DataValue( 0 ).ToString() ); } query->Delete(); this->Connection->LastErrorText.clear(); return results; } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::IsSupported( int feature ) { switch (feature) { case VTK_SQL_FEATURE_BLOB: case VTK_SQL_FEATURE_LAST_INSERT_ID: case VTK_SQL_FEATURE_NAMED_PLACEHOLDERS: case VTK_SQL_FEATURE_POSITIONAL_PLACEHOLDERS: case VTK_SQL_FEATURE_PREPARED_QUERIES: case VTK_SQL_FEATURE_TRANSACTIONS: case VTK_SQL_FEATURE_UNICODE: case VTK_SQL_FEATURE_BATCH_OPERATIONS: case VTK_SQL_FEATURE_QUERY_SIZE: return true; default: { vtkErrorMacro( << "Unknown SQL feature code " << feature << "! See " << "vtkSQLDatabase.h for a list of possible features."); return false; }; } } // ---------------------------------------------------------------------- vtkStringArray* vtkPostgreSQLDatabase::GetDatabases() { if ( ! this->Connection ) { vtkErrorMacro( "Must be connected to a server to get a list of databases." ); return 0; } vtkSQLQuery* query = this->GetQueryInstance(); if ( ! query ) { vtkErrorMacro( "Could not create a query." ); return 0; } query->SetQuery( "SELECT datname FROM pg_database" ); if ( ! query->Execute() ) { query->Delete(); return 0; } vtkStringArray* dbNames = vtkStringArray::New(); while ( query->NextRow() ) { dbNames->InsertNextValue( query->DataValue( 0 ).ToString() ); } query->Delete(); return dbNames; } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::CreateDatabase( const char* dbName, bool dropExisting ) { if ( ! dbName ) { vtkErrorMacro( "Databases must have a non-NULL name" ); return false; } bool dropCurrentlyConnected = false; if ( this->DatabaseName && ! strcmp( this->DatabaseName, dbName ) ) { dropCurrentlyConnected = true; if ( dropExisting ) { // we can't drop a database we're connected to... this->SetDatabaseName( "template1" ); this->Open(); } else { // this will fail... let it. then report the error via LastErrorText } } if ( ! this->Connection ) { bool err = true; if ( this->DatabaseName && this->HostName ) { err = this->Open() ? false : true; } if ( err ) { vtkErrorMacro( "Must be connected to a server to create a database." ); return false; } } if ( dropExisting ) { this->DropDatabase( dbName ); } pqxx::nontransaction work( this->Connection->Connection ); vtkstd::string qstr( "CREATE DATABASE " ); qstr += dbName; try { pqxx::result res = work.exec( qstr.c_str() ); } catch ( const vtkstd::exception& e ) { vtkErrorMacro( "Could not create database \"" << dbName << "\". " << this->GetLastErrorText() << "\n" ); return false; } if ( dropCurrentlyConnected ) { this->SetDatabaseName( dbName ); this->Open(); } this->Connection->LastErrorText.clear(); return true; } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::DropDatabase( const char* dbName ) { if ( ! dbName || strlen( dbName ) <= 0 ) { vtkErrorMacro( "DropDatabase called with an empty database name" ); return false; } if ( ! strcmp( dbName, this->DatabaseName ) ) { // Can't drop database we're connected to... connect to the default db. this->SetDatabaseName( "template1" ); } if ( ! this->Connection ) { bool err = true; if ( this->DatabaseName && this->HostName ) { err = this->Open() ? false : true; } if ( err ) { vtkErrorMacro( "Must be connected to a server to create a database." ); return false; } } pqxx::nontransaction work( this->Connection->Connection ); vtkstd::string qstr( "DROP DATABASE " ); qstr += dbName; //qstr += " IF EXISTS"; try { pqxx::result res = work.exec( qstr.c_str() ); } catch ( const vtkstd::exception& e ) { this->Connection->LastErrorText = e.what(); return false; } this->Connection->LastErrorText.clear(); return true; } BUG: Quote database names when creating and deleting or they will be downcased. This presents problems because the PostgreSQL connection option for database name is case sensitive. /*========================================================================= Program: Visualization Toolkit Module: vtkPostgreSQLDatabase.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkPostgreSQLDatabase.h" #include "vtkPostgreSQLDatabasePrivate.h" #include "vtkPostgreSQLQuery.h" #include "vtkSQLDatabaseSchema.h" #include "vtkObjectFactory.h" #include "vtkStringArray.h" #include <vtksys/SystemTools.hxx> #include <vtksys/ios/sstream> #define PQXX_ALLOW_LONG_LONG #include <pqxx/pqxx> vtkStandardNewMacro(vtkPostgreSQLDatabase); vtkCxxRevisionMacro(vtkPostgreSQLDatabase, "1.20"); // ---------------------------------------------------------------------- vtkPostgreSQLDatabase::vtkPostgreSQLDatabase() { this->Connection = 0; this->ConnectionMTime = this->MTime; this->DatabaseType = 0; this->SetDatabaseType("psql"); this->HostName = 0; this->User = 0; this->Password = 0; this->DatabaseName = 0; this->ServerPort = -1; this->ConnectOptions = 0; } // ---------------------------------------------------------------------- vtkPostgreSQLDatabase::~vtkPostgreSQLDatabase() { if ( this->IsOpen() ) { this->Close(); } this->SetHostName( 0 ); this->SetUser( 0 ); this->SetPassword( 0 ); this->SetDatabaseName( 0 ); this->SetConnectOptions( 0 ); this->SetDatabaseType( 0 ); } // ---------------------------------------------------------------------- void vtkPostgreSQLDatabase::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Connection: "; if ( this->Connection ) { os << this->Connection << endl; } else { os << "(null)" << endl; } os << indent << "DatabaseType: " << (this->DatabaseType ? this->DatabaseType : "NULL") << endl; os << indent << "HostName: " << (this->HostName ? this->HostName : "NULL") << endl; os << indent << "User: " << (this->User ? this->User : "NULL") << endl; os << indent << "Password: " << (this->Password ? this->Password : "NULL") << endl; os << indent << "DatabaseName: " << (this->DatabaseName ? this->DatabaseName : "NULL") << endl; os << indent << "ServerPort: " << this->ServerPort << endl; os << indent << "ConnectOptions: " << (this->ConnectOptions ? this->ConnectOptions : "NULL") << endl; } // ---------------------------------------------------------------------- vtkStdString vtkPostgreSQLDatabase::GetColumnSpecification( vtkSQLDatabaseSchema* schema, int tblHandle, int colHandle ) { vtksys_ios::ostringstream queryStr; queryStr << schema->GetColumnNameFromHandle( tblHandle, colHandle ); // Figure out column type int colType = schema->GetColumnTypeFromHandle( tblHandle, colHandle ); vtkStdString colTypeStr; switch ( static_cast<vtkSQLDatabaseSchema::DatabaseColumnType>( colType ) ) { case vtkSQLDatabaseSchema::SERIAL: colTypeStr = "SERIAL"; break; case vtkSQLDatabaseSchema::SMALLINT: colTypeStr = "SMALLINT"; break; case vtkSQLDatabaseSchema::INTEGER: colTypeStr = "INTEGER"; break; case vtkSQLDatabaseSchema::BIGINT: colTypeStr = "BIGINT"; break; case vtkSQLDatabaseSchema::VARCHAR: colTypeStr = "VARCHAR"; break; case vtkSQLDatabaseSchema::TEXT: colTypeStr = "TEXT"; break; case vtkSQLDatabaseSchema::REAL: colTypeStr = "REAL"; break; case vtkSQLDatabaseSchema::DOUBLE: colTypeStr = "DOUBLE PRECISION"; break; case vtkSQLDatabaseSchema::BLOB: colTypeStr = "BYTEA"; break; case vtkSQLDatabaseSchema::TIME: colTypeStr = "TIME"; break; case vtkSQLDatabaseSchema::DATE: colTypeStr = "DATE"; break; case vtkSQLDatabaseSchema::TIMESTAMP: colTypeStr = "TIMESTAMP WITH TIME ZONE"; break; } if ( colTypeStr.size() ) { queryStr << " " << colTypeStr; } else // if ( colTypeStr.size() ) { vtkGenericWarningMacro( "Unable to get column specification: unsupported data type " << colType ); return vtkStdString(); } // Decide whether size is allowed, required, or unused int colSizeType = 0; switch ( static_cast<vtkSQLDatabaseSchema::DatabaseColumnType>( colType ) ) { case vtkSQLDatabaseSchema::SERIAL: colSizeType = 0; break; case vtkSQLDatabaseSchema::SMALLINT: colSizeType = 0; break; case vtkSQLDatabaseSchema::INTEGER: colSizeType = 0; break; case vtkSQLDatabaseSchema::BIGINT: colSizeType = 0; break; case vtkSQLDatabaseSchema::VARCHAR: colSizeType = -1; break; case vtkSQLDatabaseSchema::TEXT: colSizeType = 0; break; case vtkSQLDatabaseSchema::REAL: colSizeType = 0; break; case vtkSQLDatabaseSchema::DOUBLE: colSizeType = 0; break; case vtkSQLDatabaseSchema::BLOB: colSizeType = 0; break; case vtkSQLDatabaseSchema::TIME: colSizeType = 1; break; case vtkSQLDatabaseSchema::DATE: colSizeType = 0; break; case vtkSQLDatabaseSchema::TIMESTAMP: colSizeType = 0; break; } // Specify size if allowed or required if ( colSizeType ) { int colSize = schema->GetColumnSizeFromHandle( tblHandle, colHandle ); // IF size is provided but absurd, // OR, if size is required but not provided OR absurd, // THEN assign the default size. if ( ( colSize < 0 ) || ( colSizeType == -1 && colSize < 1 ) ) { colSize = VTK_SQL_DEFAULT_COLUMN_SIZE; } // At this point, we have either a valid size if required, or a possibly null valid size // if not required. Thus, skip sizing in the latter case. if ( colSize > 0 ) { queryStr << "(" << colSize << ")"; } } vtkStdString attStr = schema->GetColumnAttributesFromHandle( tblHandle, colHandle ); if ( attStr.size() ) { queryStr << " " << attStr; } return queryStr.str(); } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::Open() { if ( ! this->HostName || ! this->DatabaseName ) { //this->LastErrorText = "Cannot open database because HostName and/or DatabaseName are null."; vtkErrorMacro(<< this->GetLastErrorText()); return false; } if ( this->Connection ) { if ( this->ConnectionMTime > this->URLMTime ) { return true; // we already had that database open. } this->Close(); // close the old connection before opening a new one } vtkstd::string options( "host=" ); options += this->HostName; options += " dbname="; options += this->DatabaseName; if ( this->ServerPort ) { options += " port="; options += this->ServerPort; } if ( this->User && strlen( this->User ) > 0 ) { options += " user="; options += this->User; } if ( this->Password && strlen( this->Password ) > 0 ) { options += " password="; options += this->Password; } if ( this->ConnectOptions && strlen( this->ConnectOptions ) > 0 ) { options += this->ConnectOptions; } try { this->Connection = new vtkPostgreSQLDatabasePrivate( options.c_str() ); this->ConnectionMTime.Modified(); } catch ( pqxx::sql_error& e ) { this->Connection->LastErrorText = e.what(); return false; } catch ( pqxx::broken_connection& e ) { if ( this->Connection ) { delete this->Connection; this->Connection = 0; } return false; } this->Connection->LastErrorText.clear(); return true; } // ---------------------------------------------------------------------- void vtkPostgreSQLDatabase::Close() { if ( this->Connection ) { delete this->Connection; this->Connection = 0; this->URLMTime.Modified(); // Force a re-open to occur when Open() is called. } } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::IsOpen() { return this->Connection != 0; } // ---------------------------------------------------------------------- vtkSQLQuery* vtkPostgreSQLDatabase::GetQueryInstance() { vtkPostgreSQLQuery* query = vtkPostgreSQLQuery::New(); query->SetDatabase( this ); return query; } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::HasError() { // Assume that an unopened connection is not a symptom of failure. return this->Connection ? this->Connection->LastErrorText != NULL : false; } // ---------------------------------------------------------------------- const char* vtkPostgreSQLDatabase::GetLastErrorText() { if ( ! this->Connection ) { return "Database is not open."; } else { return this->Connection->LastErrorText; } } // ---------------------------------------------------------------------- vtkStdString vtkPostgreSQLDatabase::GetURL() { vtkStdString url = this->GetDatabaseType(); url += "://"; if ( this->HostName && this->DatabaseName ) { if ( this->User ) { url += this->User; if ( this->Password ) { url += ":"; url += this->Password; } url += "@"; } url += this->HostName; url += "/"; url += this->DatabaseName; } return url; } // ---------------------------------------------------------------------- vtkStringArray* vtkPostgreSQLDatabase::GetTables() { if ( ! this->Connection ) { // This will always be "Database not open." vtkErrorMacro(<< this->GetLastErrorText()); return 0; } // NB: Other columns of interest include table_catalog, table_schema, table_type, // self_referencing_column_name, reference_generation, user_defined_type_catalog, // user_defined_type_schema, user_defined_type_name, is_insertable_into, is_typed, // commit_action vtkSQLQuery* query = this->GetQueryInstance(); query->SetQuery( "SELECT table_name FROM information_schema.tables" " WHERE table_schema='public' and table_type='BASE TABLE'" ); bool status = query->Execute(); if ( ! status ) { vtkErrorMacro(<< "Database returned error: " << query->GetLastErrorText()); this->Connection->LastErrorText = query->GetLastErrorText(); query->Delete(); return 0; } vtkDebugMacro(<< "GetTables(): SQL query succeeded." ); vtkStringArray* results = vtkStringArray::New(); while ( query->NextRow() ) { results->InsertNextValue( query->DataValue( 0 ).ToString() ); } query->Delete(); this->Connection->LastErrorText.clear(); return results; } // ---------------------------------------------------------------------- vtkStringArray* vtkPostgreSQLDatabase::GetRecord( const char* table ) { // NB: There are *too many* other column names to list. Even the ones // currently in the query below are probably over the top. But there's // just so much peanut-buttery goodness in the table, I couldn't resist. vtkSQLQuery* query = this->GetQueryInstance(); vtkStdString text( "SELECT column_name,column_default,data_type,is_nullable,character_maximum_length,numeric_precision,datetime_precision" " FROM information_schema.columns" " WHERE table_name='" ); text += table; text += "' ORDER BY ordinal_position"; query->SetQuery( text.c_str() ); bool status = query->Execute(); if ( ! status ) { vtkErrorMacro(<< "GetRecord(" << table << "): Database returned error: " << query->GetLastErrorText()); this->Connection->LastErrorText = query->GetLastErrorText(); query->Delete(); return 0; } // Each row in the results that come back from this query // describes a single column in the table. vtkStringArray* results = vtkStringArray::New(); while ( query->NextRow() ) { results->InsertNextValue( query->DataValue( 0 ).ToString() ); } query->Delete(); this->Connection->LastErrorText.clear(); return results; } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::IsSupported( int feature ) { switch (feature) { case VTK_SQL_FEATURE_BLOB: case VTK_SQL_FEATURE_LAST_INSERT_ID: case VTK_SQL_FEATURE_NAMED_PLACEHOLDERS: case VTK_SQL_FEATURE_POSITIONAL_PLACEHOLDERS: case VTK_SQL_FEATURE_PREPARED_QUERIES: case VTK_SQL_FEATURE_TRANSACTIONS: case VTK_SQL_FEATURE_UNICODE: case VTK_SQL_FEATURE_BATCH_OPERATIONS: case VTK_SQL_FEATURE_QUERY_SIZE: return true; default: { vtkErrorMacro( << "Unknown SQL feature code " << feature << "! See " << "vtkSQLDatabase.h for a list of possible features."); return false; }; } } // ---------------------------------------------------------------------- vtkStringArray* vtkPostgreSQLDatabase::GetDatabases() { if ( ! this->Connection ) { vtkErrorMacro( "Must be connected to a server to get a list of databases." ); return 0; } vtkSQLQuery* query = this->GetQueryInstance(); if ( ! query ) { vtkErrorMacro( "Could not create a query." ); return 0; } query->SetQuery( "SELECT datname FROM pg_database" ); if ( ! query->Execute() ) { query->Delete(); return 0; } vtkStringArray* dbNames = vtkStringArray::New(); while ( query->NextRow() ) { dbNames->InsertNextValue( query->DataValue( 0 ).ToString() ); } query->Delete(); return dbNames; } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::CreateDatabase( const char* dbName, bool dropExisting ) { if ( ! dbName ) { vtkErrorMacro( "Databases must have a non-NULL name" ); return false; } bool dropCurrentlyConnected = false; if ( this->DatabaseName && ! strcmp( this->DatabaseName, dbName ) ) { dropCurrentlyConnected = true; if ( dropExisting ) { // we can't drop a database we're connected to... this->SetDatabaseName( "template1" ); this->Open(); } else { // this will fail... let it. then report the error via LastErrorText } } if ( ! this->Connection ) { bool err = true; if ( this->DatabaseName && this->HostName ) { err = this->Open() ? false : true; } if ( err ) { vtkErrorMacro( "Must be connected to a server to create a database." ); return false; } } if ( dropExisting ) { this->DropDatabase( dbName ); } vtkstd::string qstr( "CREATE DATABASE \"" ); qstr += dbName; qstr += "\""; try { pqxx::nontransaction work( this->Connection->Connection ); pqxx::result res = work.exec( qstr.c_str() ); work.commit(); } catch ( const vtkstd::exception& e ) { vtkErrorMacro( "Could not create database \"" << dbName << "\". " << this->GetLastErrorText() << "\n" ); return false; } if ( dropCurrentlyConnected ) { this->SetDatabaseName( dbName ); this->Open(); } if ( this->Connection ) { this->Connection->LastErrorText.clear(); } return true; } // ---------------------------------------------------------------------- bool vtkPostgreSQLDatabase::DropDatabase( const char* dbName ) { if ( ! dbName || strlen( dbName ) <= 0 ) { vtkErrorMacro( "DropDatabase called with an empty database name" ); return false; } if ( ! strcmp( dbName, this->DatabaseName ) ) { // Can't drop database we're connected to... connect to the default db. this->SetDatabaseName( "template1" ); } if ( ! this->Connection ) { bool err = true; if ( this->DatabaseName && this->HostName ) { err = this->Open() ? false : true; } if ( err ) { vtkErrorMacro( "Must be connected to a server to create a database." ); return false; } } vtkstd::string qstr( "DROP DATABASE \"" ); qstr += dbName; qstr += "\""; //qstr += " IF EXISTS"; try { pqxx::nontransaction work( this->Connection->Connection ); pqxx::result res = work.exec( qstr.c_str() ); work.commit(); } catch ( const vtkstd::exception& e ) { this->Connection->LastErrorText = e.what(); return false; } if ( this->Connection ) { this->Connection->LastErrorText.clear(); } return true; }
// Copyright (c) 2017-2018 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "cbtx.h" #include "core_io.h" #include "deterministicmns.h" #include "simplifiedmns.h" #include "specialtx.h" #include "base58.h" #include "chainparams.h" #include "consensus/merkle.h" #include "univalue.h" #include "validation.h" CSimplifiedMNListEntry::CSimplifiedMNListEntry(const CDeterministicMN& dmn) : proRegTxHash(dmn.proTxHash), confirmedHash(dmn.pdmnState->confirmedHash), service(dmn.pdmnState->addr), pubKeyOperator(dmn.pdmnState->pubKeyOperator), keyIDVoting(dmn.pdmnState->keyIDVoting), isValid(dmn.pdmnState->nPoSeBanHeight == -1) { } uint256 CSimplifiedMNListEntry::CalcHash() const { CHashWriter hw(SER_GETHASH, CLIENT_VERSION); hw << *this; return hw.GetHash(); } std::string CSimplifiedMNListEntry::ToString() const { return strprintf("CSimplifiedMNListEntry(proRegTxHash=%s, confirmedHash=%s, service=%s, pubKeyOperator=%s, votingAddress=%s, isValie=%d)", proRegTxHash.ToString(), confirmedHash.ToString(), service.ToString(false), pubKeyOperator.ToString(), CBitcoinAddress(keyIDVoting).ToString(), isValid); } void CSimplifiedMNListEntry::ToJson(UniValue& obj) const { obj.clear(); obj.setObject(); obj.push_back(Pair("proRegTxHash", proRegTxHash.ToString())); obj.push_back(Pair("confirmedHash", confirmedHash.ToString())); obj.push_back(Pair("service", service.ToString(false))); obj.push_back(Pair("pubKeyOperator", pubKeyOperator.ToString())); obj.push_back(Pair("votingAddress", CBitcoinAddress(keyIDVoting).ToString())); obj.push_back(Pair("isValid", isValid)); } CSimplifiedMNList::CSimplifiedMNList(const std::vector<CSimplifiedMNListEntry>& smlEntries) { mnList = smlEntries; std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) { return a.proRegTxHash.Compare(b.proRegTxHash) < 0; }); } CSimplifiedMNList::CSimplifiedMNList(const CDeterministicMNList& dmnList) { mnList.reserve(dmnList.GetAllMNsCount()); dmnList.ForEachMN(false, [this](const CDeterministicMNCPtr& dmn) { mnList.emplace_back(*dmn); }); std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) { return a.proRegTxHash.Compare(b.proRegTxHash) < 0; }); } uint256 CSimplifiedMNList::CalcMerkleRoot(bool* pmutated) const { std::vector<uint256> leaves; leaves.reserve(mnList.size()); for (const auto& e : mnList) { leaves.emplace_back(e.CalcHash()); } return ComputeMerkleRoot(leaves, pmutated); } void CSimplifiedMNListDiff::ToJson(UniValue& obj) const { obj.setObject(); obj.push_back(Pair("baseBlockHash", baseBlockHash.ToString())); obj.push_back(Pair("blockHash", blockHash.ToString())); CDataStream ssCbTxMerkleTree(SER_NETWORK, PROTOCOL_VERSION); ssCbTxMerkleTree << cbTxMerkleTree; obj.push_back(Pair("cbTxMerkleTree", HexStr(ssCbTxMerkleTree.begin(), ssCbTxMerkleTree.end()))); obj.push_back(Pair("cbTx", EncodeHexTx(*cbTx))); UniValue deletedMNsArr(UniValue::VARR); for (const auto& h : deletedMNs) { deletedMNsArr.push_back(h.ToString()); } obj.push_back(Pair("deletedMNs", deletedMNsArr)); UniValue mnListArr(UniValue::VARR); for (const auto& e : mnList) { UniValue eObj; e.ToJson(eObj); mnListArr.push_back(eObj); } obj.push_back(Pair("mnList", mnListArr)); CCbTx cbTxPayload; if (GetTxPayload(*cbTx, cbTxPayload)) { obj.push_back(Pair("merkleRootMNList", cbTxPayload.merkleRootMNList.ToString())); } } bool BuildSimplifiedMNListDiff(const uint256& baseBlockHash, const uint256& blockHash, CSimplifiedMNListDiff& mnListDiffRet, std::string& errorRet) { AssertLockHeld(cs_main); mnListDiffRet = CSimplifiedMNListDiff(); BlockMap::iterator baseBlockIt = mapBlockIndex.begin(); if (!baseBlockHash.IsNull()) { baseBlockIt = mapBlockIndex.find(baseBlockHash); } auto blockIt = mapBlockIndex.find(blockHash); if (baseBlockIt == mapBlockIndex.end()) { errorRet = strprintf("block %s not found", baseBlockHash.ToString()); return false; } if (blockIt == mapBlockIndex.end()) { errorRet = strprintf("block %s not found", blockHash.ToString()); return false; } if (!chainActive.Contains(baseBlockIt->second) || !chainActive.Contains(blockIt->second)) { errorRet = strprintf("block %s and %s are not in the same chain", baseBlockHash.ToString(), blockHash.ToString()); return false; } if (baseBlockIt->second->nHeight > blockIt->second->nHeight) { errorRet = strprintf("base block %s is higher then block %s", baseBlockHash.ToString(), blockHash.ToString()); return false; } LOCK(deterministicMNManager->cs); auto baseDmnList = deterministicMNManager->GetListForBlock(baseBlockHash); auto dmnList = deterministicMNManager->GetListForBlock(blockHash); mnListDiffRet = baseDmnList.BuildSimplifiedDiff(dmnList); // TODO store coinbase TX in CBlockIndex CBlock block; if (!ReadBlockFromDisk(block, blockIt->second, Params().GetConsensus())) { errorRet = strprintf("failed to read block %s from disk", blockHash.ToString()); return false; } mnListDiffRet.cbTx = block.vtx[0]; std::vector<uint256> vHashes; std::vector<bool> vMatch(block.vtx.size(), false); for (const auto& tx : block.vtx) { vHashes.emplace_back(tx->GetHash()); } vMatch[0] = true; // only coinbase matches mnListDiffRet.cbTxMerkleTree = CPartialMerkleTree(vHashes, vMatch); return true; } Fix incorrect usage of begin() when genesis block is requested in "protx diff" (#2699) * Fix incorrect usage of begin() when genesis block is requested in "protx diff" .begin() on mapBlockIndex does NOT return the genesis block, but just the block with lowest hash. The fix is to use chainActive[0] to get the genesis block. * Update src/evo/simplifiedmns.cpp Co-Authored-By: codablock <66f42ae8113cc8789ea5acab0b0aaf5dd9cd30fc@gmail.com> // Copyright (c) 2017-2018 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "cbtx.h" #include "core_io.h" #include "deterministicmns.h" #include "simplifiedmns.h" #include "specialtx.h" #include "base58.h" #include "chainparams.h" #include "consensus/merkle.h" #include "univalue.h" #include "validation.h" CSimplifiedMNListEntry::CSimplifiedMNListEntry(const CDeterministicMN& dmn) : proRegTxHash(dmn.proTxHash), confirmedHash(dmn.pdmnState->confirmedHash), service(dmn.pdmnState->addr), pubKeyOperator(dmn.pdmnState->pubKeyOperator), keyIDVoting(dmn.pdmnState->keyIDVoting), isValid(dmn.pdmnState->nPoSeBanHeight == -1) { } uint256 CSimplifiedMNListEntry::CalcHash() const { CHashWriter hw(SER_GETHASH, CLIENT_VERSION); hw << *this; return hw.GetHash(); } std::string CSimplifiedMNListEntry::ToString() const { return strprintf("CSimplifiedMNListEntry(proRegTxHash=%s, confirmedHash=%s, service=%s, pubKeyOperator=%s, votingAddress=%s, isValie=%d)", proRegTxHash.ToString(), confirmedHash.ToString(), service.ToString(false), pubKeyOperator.ToString(), CBitcoinAddress(keyIDVoting).ToString(), isValid); } void CSimplifiedMNListEntry::ToJson(UniValue& obj) const { obj.clear(); obj.setObject(); obj.push_back(Pair("proRegTxHash", proRegTxHash.ToString())); obj.push_back(Pair("confirmedHash", confirmedHash.ToString())); obj.push_back(Pair("service", service.ToString(false))); obj.push_back(Pair("pubKeyOperator", pubKeyOperator.ToString())); obj.push_back(Pair("votingAddress", CBitcoinAddress(keyIDVoting).ToString())); obj.push_back(Pair("isValid", isValid)); } CSimplifiedMNList::CSimplifiedMNList(const std::vector<CSimplifiedMNListEntry>& smlEntries) { mnList = smlEntries; std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) { return a.proRegTxHash.Compare(b.proRegTxHash) < 0; }); } CSimplifiedMNList::CSimplifiedMNList(const CDeterministicMNList& dmnList) { mnList.reserve(dmnList.GetAllMNsCount()); dmnList.ForEachMN(false, [this](const CDeterministicMNCPtr& dmn) { mnList.emplace_back(*dmn); }); std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) { return a.proRegTxHash.Compare(b.proRegTxHash) < 0; }); } uint256 CSimplifiedMNList::CalcMerkleRoot(bool* pmutated) const { std::vector<uint256> leaves; leaves.reserve(mnList.size()); for (const auto& e : mnList) { leaves.emplace_back(e.CalcHash()); } return ComputeMerkleRoot(leaves, pmutated); } void CSimplifiedMNListDiff::ToJson(UniValue& obj) const { obj.setObject(); obj.push_back(Pair("baseBlockHash", baseBlockHash.ToString())); obj.push_back(Pair("blockHash", blockHash.ToString())); CDataStream ssCbTxMerkleTree(SER_NETWORK, PROTOCOL_VERSION); ssCbTxMerkleTree << cbTxMerkleTree; obj.push_back(Pair("cbTxMerkleTree", HexStr(ssCbTxMerkleTree.begin(), ssCbTxMerkleTree.end()))); obj.push_back(Pair("cbTx", EncodeHexTx(*cbTx))); UniValue deletedMNsArr(UniValue::VARR); for (const auto& h : deletedMNs) { deletedMNsArr.push_back(h.ToString()); } obj.push_back(Pair("deletedMNs", deletedMNsArr)); UniValue mnListArr(UniValue::VARR); for (const auto& e : mnList) { UniValue eObj; e.ToJson(eObj); mnListArr.push_back(eObj); } obj.push_back(Pair("mnList", mnListArr)); CCbTx cbTxPayload; if (GetTxPayload(*cbTx, cbTxPayload)) { obj.push_back(Pair("merkleRootMNList", cbTxPayload.merkleRootMNList.ToString())); } } bool BuildSimplifiedMNListDiff(const uint256& baseBlockHash, const uint256& blockHash, CSimplifiedMNListDiff& mnListDiffRet, std::string& errorRet) { AssertLockHeld(cs_main); mnListDiffRet = CSimplifiedMNListDiff(); const CBlockIndex* baseBlockIndex = chainActive.Genesis(); if (!baseBlockHash.IsNull()) { auto it = mapBlockIndex.find(baseBlockHash); if (it == mapBlockIndex.end()) { errorRet = strprintf("block %s not found", baseBlockHash.ToString()); return false; } baseBlockIndex = it->second; } auto blockIt = mapBlockIndex.find(blockHash); if (blockIt == mapBlockIndex.end()) { errorRet = strprintf("block %s not found", blockHash.ToString()); return false; } const CBlockIndex* blockIndex = blockIt->second; if (!chainActive.Contains(baseBlockIndex) || !chainActive.Contains(blockIndex)) { errorRet = strprintf("block %s and %s are not in the same chain", baseBlockHash.ToString(), blockHash.ToString()); return false; } if (baseBlockIndex->nHeight > blockIndex->nHeight) { errorRet = strprintf("base block %s is higher then block %s", baseBlockHash.ToString(), blockHash.ToString()); return false; } LOCK(deterministicMNManager->cs); auto baseDmnList = deterministicMNManager->GetListForBlock(baseBlockHash); auto dmnList = deterministicMNManager->GetListForBlock(blockHash); mnListDiffRet = baseDmnList.BuildSimplifiedDiff(dmnList); // TODO store coinbase TX in CBlockIndex CBlock block; if (!ReadBlockFromDisk(block, blockIndex, Params().GetConsensus())) { errorRet = strprintf("failed to read block %s from disk", blockHash.ToString()); return false; } mnListDiffRet.cbTx = block.vtx[0]; std::vector<uint256> vHashes; std::vector<bool> vMatch(block.vtx.size(), false); for (const auto& tx : block.vtx) { vHashes.emplace_back(tx->GetHash()); } vMatch[0] = true; // only coinbase matches mnListDiffRet.cbTxMerkleTree = CPartialMerkleTree(vHashes, vMatch); return true; }
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtQuick/private/qsgcontext_p.h> #include <QtQuick/private/qsgbatchrenderer_p.h> #include <QtQuick/private/qsgdistancefieldutil_p.h> #include <QtQuick/private/qsgdefaultdistancefieldglyphcache_p.h> #include <QtQuick/private/qsgdefaultrectanglenode_p.h> #include <QtQuick/private/qsgdefaultimagenode_p.h> #include <QtQuick/private/qsgdefaultglyphnode_p.h> #include <QtQuick/private/qsgdistancefieldglyphnode_p.h> #include <QtQuick/private/qsgdistancefieldglyphnode_p_p.h> #include <QtQuick/private/qsgshareddistancefieldglyphcache_p.h> #include <QtQuick/private/qsgatlastexture_p.h> #include <QtQuick/private/qsgtexture_p.h> #include <QtQuick/private/qquickpixmapcache_p.h> #include <QGuiApplication> #include <QOpenGLContext> #include <QQuickWindow> #include <QtGui/qopenglframebufferobject.h> #include <private/qqmlglobal_p.h> #include <QtQuick/private/qsgtexture_p.h> #include <QtGui/private/qguiapplication_p.h> #include <qpa/qplatformintegration.h> #include <qpa/qplatformsharedgraphicscache.h> #include <private/qobject_p.h> #include <qmutex.h> #include <private/qqmlprofilerservice_p.h> DEFINE_BOOL_CONFIG_OPTION(qmlFlashMode, QML_FLASH_MODE) DEFINE_BOOL_CONFIG_OPTION(qmlTranslucentMode, QML_TRANSLUCENT_MODE) DEFINE_BOOL_CONFIG_OPTION(qmlDisableDistanceField, QML_DISABLE_DISTANCEFIELD) /* Comments about this class from Gunnar: The QSGContext class is right now two things.. The first is the adaptation layer and central storage ground for all the things in the scene graph, like textures and materials. This part really belongs inside the scene graph coreapi. The other part is the QML adaptation classes, like how to implement rectangle nodes. This is not part of the scene graph core API, but more part of the QML adaptation of scene graph. If we ever move the scene graph core API into its own thing, this class needs to be split in two. Right now its one because we're lazy when it comes to defining plugin interfaces.. */ QT_BEGIN_NAMESPACE class QSGContextPrivate : public QObjectPrivate { public: QSGContextPrivate() : gl(0) , depthStencilBufferManager(0) , distanceFieldCacheManager(0) #if !defined(QT_OPENGL_ES) || defined(QT_OPENGL_ES_2_ANGLE) , distanceFieldAntialiasing(QSGGlyphNode::HighQualitySubPixelAntialiasing) #else , distanceFieldAntialiasing(QSGGlyphNode::GrayAntialiasing) #endif , atlasManager(0) , flashMode(qmlFlashMode()) , distanceFieldDisabled(qmlDisableDistanceField()) , msaa(false) { renderAlpha = qmlTranslucentMode() ? 0.5 : 1; } ~QSGContextPrivate() { } QOpenGLContext *gl; QMutex textureMutex; QHash<QQuickTextureFactory *, QSGTexture *> textures; QSGDepthStencilBufferManager *depthStencilBufferManager; QSGDistanceFieldGlyphCacheManager *distanceFieldCacheManager; QSGDistanceFieldGlyphNode::AntialiasingMode distanceFieldAntialiasing; QSGAtlasTexture::Manager *atlasManager; bool flashMode; float renderAlpha; bool distanceFieldDisabled; bool msaa; }; class QSGTextureCleanupEvent : public QEvent { public: QSGTextureCleanupEvent(QSGTexture *t) : QEvent(QEvent::User), texture(t) { } ~QSGTextureCleanupEvent() { delete texture; } QSGTexture *texture; }; namespace QSGMultisampleAntialiasing { class ImageNode : public QSGDefaultImageNode { public: void setAntialiasing(bool) { } }; class RectangleNode : public QSGDefaultRectangleNode { public: void setAntialiasing(bool) { } }; } /*! \class QSGContext \brief The QSGContext holds the scene graph entry points for one QML engine. The context is not ready for use until it has a QOpenGLContext. Once that happens, the scene graph population can start. \internal */ QSGContext::QSGContext(QObject *parent) : QObject(*(new QSGContextPrivate), parent) { Q_D(QSGContext); QByteArray mode = qgetenv("QSG_DISTANCEFIELD_ANTIALIASING"); if (mode == "subpixel") d->distanceFieldAntialiasing = QSGGlyphNode::HighQualitySubPixelAntialiasing; else if (mode == "subpixel-lowq") d->distanceFieldAntialiasing = QSGGlyphNode::LowQualitySubPixelAntialiasing; else if (mode == "gray") d->distanceFieldAntialiasing = QSGGlyphNode::GrayAntialiasing; } QSGContext::~QSGContext() { invalidate(); } void QSGContext::invalidate() { Q_D(QSGContext); d->textureMutex.lock(); qDeleteAll(d->textures.values()); d->textures.clear(); d->textureMutex.unlock(); delete d->depthStencilBufferManager; d->depthStencilBufferManager = 0; delete d->distanceFieldCacheManager; d->distanceFieldCacheManager = 0; d->gl = 0; emit invalidated(); /* The cleanup of the atlas textures is a bit intruiging. As part of the cleanup in the threaded render loop, we do: 1. call this function 2. call QCoreApp::sendPostedEvents() to immediately process any pending deferred deletes. 3. delete the GL context. As textures need the atlas manager while cleaning up, the manager needs to be cleaned up after the textures, so we post a deleteLater here at the very bottom so it gets deferred deleted last. Another alternative would be to use a QPointer in QSGAtlasTexture::Texture, but this seemed simpler. */ if (d->atlasManager) { d->atlasManager->deleteLater(); d->atlasManager = 0; } } QSGTexture *QSGContext::textureForFactory(QQuickTextureFactory *factory, QQuickWindow *window) { Q_D(QSGContext); if (!factory) return 0; d->textureMutex.lock(); QSGTexture *texture = d->textures.value(factory); if (!texture) { if (QQuickDefaultTextureFactory *dtf = qobject_cast<QQuickDefaultTextureFactory *>(factory)) texture = createTexture(dtf->image()); else texture = factory->createTexture(window); d->textures.insert(factory, texture); connect(factory, SIGNAL(destroyed(QObject *)), this, SLOT(textureFactoryDestroyed(QObject *)), Qt::DirectConnection); } d->textureMutex.unlock(); return texture; } void QSGContext::textureFactoryDestroyed(QObject *o) { Q_D(QSGContext); QQuickTextureFactory *f = static_cast<QQuickTextureFactory *>(o); d->textureMutex.lock(); QSGTexture *t = d->textures.take(f); d->textureMutex.unlock(); if (t) { if (t->thread() == thread()) t->deleteLater(); else QCoreApplication::postEvent(this, new QSGTextureCleanupEvent(t)); } } QOpenGLContext *QSGContext::glContext() const { Q_D(const QSGContext); return d->gl; } /*! Initializes the scene graph context with the GL context \a context. This also emits the ready() signal so that the QML graph can start building scene graph nodes. */ void QSGContext::initialize(QOpenGLContext *context) { Q_D(QSGContext); QByteArray aaType = qgetenv("QSG_ANTIALIASING_METHOD"); if (aaType == "msaa") { d->msaa = true; } else if (aaType == "vertex") { d->msaa = false; } else { if (context->format().samples() > 0) d->msaa = true; else d->msaa = false; } // Sanity check the surface format, in case it was overridden by the application QSurfaceFormat requested = defaultSurfaceFormat(); QSurfaceFormat actual = context->format(); if (requested.depthBufferSize() > 0 && actual.depthBufferSize() <= 0) qWarning("QSGContext::initialize: depth buffer support missing, expect rendering errors"); if (requested.stencilBufferSize() > 0 && actual.stencilBufferSize() <= 0) qWarning("QSGContext::initialize: stencil buffer support missing, expect rendering errors"); d->atlasManager = new QSGAtlasTexture::Manager(); Q_ASSERT(!d->gl); d->gl = context; emit initialized(); } /*! Returns if the scene graph context is ready or not, meaning that it has a valid GL context. */ bool QSGContext::isReady() const { Q_D(const QSGContext); return d->gl; } void QSGContext::renderNextFrame(QSGRenderer *renderer, GLuint fboId) { if (fboId) { QSGBindableFboId bindable(fboId); renderer->renderScene(bindable); } else { renderer->renderScene(); } } /*! Factory function for scene graph backends of the Rectangle element. */ QSGRectangleNode *QSGContext::createRectangleNode() { Q_D(QSGContext); return d->msaa ? new QSGMultisampleAntialiasing::RectangleNode : new QSGDefaultRectangleNode; } /*! Factory function for scene graph backends of the Image element. */ QSGImageNode *QSGContext::createImageNode() { Q_D(QSGContext); return d->msaa ? new QSGMultisampleAntialiasing::ImageNode : new QSGDefaultImageNode; } /*! Factory function for scene graph backends of the distance-field glyph cache. */ QSGDistanceFieldGlyphCache *QSGContext::distanceFieldGlyphCache(const QRawFont &font) { Q_D(QSGContext); if (!d->distanceFieldCacheManager) d->distanceFieldCacheManager = new QSGDistanceFieldGlyphCacheManager; QSGDistanceFieldGlyphCache *cache = d->distanceFieldCacheManager->cache(font); if (!cache) { QPlatformIntegration *platformIntegration = QGuiApplicationPrivate::platformIntegration(); if (platformIntegration != 0 && platformIntegration->hasCapability(QPlatformIntegration::SharedGraphicsCache)) { QFontEngine *fe = QRawFontPrivate::get(font)->fontEngine; if (!fe->faceId().filename.isEmpty()) { QByteArray keyName = fe->faceId().filename; if (font.style() != QFont::StyleNormal) keyName += QByteArray(" I"); if (font.weight() != QFont::Normal) keyName += ' ' + QByteArray::number(font.weight()); keyName += QByteArray(" DF"); QPlatformSharedGraphicsCache *sharedGraphicsCache = platformIntegration->createPlatformSharedGraphicsCache(keyName); if (sharedGraphicsCache != 0) { sharedGraphicsCache->ensureCacheInitialized(keyName, QPlatformSharedGraphicsCache::OpenGLTexture, QPlatformSharedGraphicsCache::Alpha8); cache = new QSGSharedDistanceFieldGlyphCache(keyName, sharedGraphicsCache, d->distanceFieldCacheManager, glContext(), font); } } } if (!cache) cache = new QSGDefaultDistanceFieldGlyphCache(d->distanceFieldCacheManager, glContext(), font); d->distanceFieldCacheManager->insertCache(font, cache); } return cache; } /*! Factory function for scene graph backends of the Text elements which supports native text rendering. Used in special cases where native look and feel is a main objective. */ QSGGlyphNode *QSGContext::createNativeGlyphNode() { #if defined(QT_OPENGL_ES) && !defined(QT_OPENGL_ES_2_ANGLE) return createGlyphNode(); #else return new QSGDefaultGlyphNode; #endif } /*! Factory function for scene graph backends of the Text elements; */ QSGGlyphNode *QSGContext::createGlyphNode() { Q_D(QSGContext); if (d->distanceFieldDisabled) { return createNativeGlyphNode(); } else { QSGDistanceFieldGlyphNode *node = new QSGDistanceFieldGlyphNode(this); node->setPreferredAntialiasingMode(d->distanceFieldAntialiasing); return node; } } /*! Factory function for the scene graph renderers. The renderers are used for the toplevel renderer and once for every QQuickShaderEffectSource used in the QML scene. */ QSGRenderer *QSGContext::createRenderer() { return new QSGBatchRenderer::Renderer(this); } QSurfaceFormat QSGContext::defaultSurfaceFormat() const { QSurfaceFormat format; format.setDepthBufferSize(24); format.setStencilBufferSize(8); if (QQuickWindow::hasDefaultAlphaBuffer()) format.setAlphaBufferSize(8); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); return format; } /*! Factory function for texture objects. If \a image is a valid image, the QSGTexture::setImage function will be called with \a image as argument. */ QSGTexture *QSGContext::createTexture(const QImage &image) const { Q_D(const QSGContext); QSGTexture *at = d->atlasManager->create(image); if (at) return at; return createTextureNoAtlas(image); } QSGTexture *QSGContext::createTextureNoAtlas(const QImage &image) const { QSGPlainTexture *t = new QSGPlainTexture(); if (!image.isNull()) t->setImage(image); return t; } /*! Returns the minimum supported framebuffer object size. */ QSize QSGContext::minimumFBOSize() const { #ifdef Q_OS_MAC return QSize(33, 33); #else return QSize(1, 1); #endif } /*! Returns a shared pointer to a depth stencil buffer that can be used with \a fbo. */ QSharedPointer<QSGDepthStencilBuffer> QSGContext::depthStencilBufferForFbo(QOpenGLFramebufferObject *fbo) { Q_D(QSGContext); if (!d->gl) return QSharedPointer<QSGDepthStencilBuffer>(); QSGDepthStencilBufferManager *manager = depthStencilBufferManager(); QSGDepthStencilBuffer::Format format; format.size = fbo->size(); format.samples = fbo->format().samples(); format.attachments = QSGDepthStencilBuffer::DepthAttachment | QSGDepthStencilBuffer::StencilAttachment; QSharedPointer<QSGDepthStencilBuffer> buffer = manager->bufferForFormat(format); if (buffer.isNull()) { buffer = QSharedPointer<QSGDepthStencilBuffer>(new QSGDefaultDepthStencilBuffer(d->gl, format)); manager->insertBuffer(buffer); } return buffer; } /*! Returns a pointer to the context's depth/stencil buffer manager. This is useful for custom implementations of \l depthStencilBufferForFbo(). */ QSGDepthStencilBufferManager *QSGContext::depthStencilBufferManager() { Q_D(QSGContext); if (!d->gl) return 0; if (!d->depthStencilBufferManager) d->depthStencilBufferManager = new QSGDepthStencilBufferManager(d->gl); return d->depthStencilBufferManager; } /*! Sets whether the scene graph should render with flashing update rectangles or not */ void QSGContext::setFlashModeEnabled(bool enabled) { d_func()->flashMode = enabled; } /*! Returns true if the scene graph should be rendered with flashing update rectangles */ bool QSGContext::isFlashModeEnabled() const { return d_func()->flashMode; } /*! Sets the toplevel opacity for rendering. This value will be multiplied into all drawing calls where possible. The default value is 1. Any other value will cause artifacts and is primarily useful for debugging. */ void QSGContext::setRenderAlpha(qreal renderAlpha) { d_func()->renderAlpha = renderAlpha; } /*! Returns the toplevel opacity used for rendering. The default value is 1. \sa setRenderAlpha() */ qreal QSGContext::renderAlpha() const { return d_func()->renderAlpha; } /*! Sets whether or not the scene graph should use the distance field technique to render text */ void QSGContext::setDistanceFieldEnabled(bool enabled) { d_func()->distanceFieldDisabled = !enabled; } /*! Returns true if the scene graph uses the distance field technique to render text */ bool QSGContext::isDistanceFieldEnabled() const { return !d_func()->distanceFieldDisabled; } /*! Creates a new animation driver. */ QAnimationDriver *QSGContext::createAnimationDriver(QObject *parent) { return new QAnimationDriver(parent); } QT_END_NAMESPACE Avoid infinite loop with distance fields disabled createGlyphNode() and createNativeGlyphNode() kept calling each other on GLES whenever QML_DISABLE_DISTANCEFIELD was set. Change-Id: Ic1c2cfe0c4c7301f82cbbcce1cb512bd515b52ef Reviewed-by: Gunnar Sletta <d0b71651f3efaa9fda200bbcc395b7b82a871fdd@digia.com> /**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtQuick/private/qsgcontext_p.h> #include <QtQuick/private/qsgbatchrenderer_p.h> #include <QtQuick/private/qsgdistancefieldutil_p.h> #include <QtQuick/private/qsgdefaultdistancefieldglyphcache_p.h> #include <QtQuick/private/qsgdefaultrectanglenode_p.h> #include <QtQuick/private/qsgdefaultimagenode_p.h> #include <QtQuick/private/qsgdefaultglyphnode_p.h> #include <QtQuick/private/qsgdistancefieldglyphnode_p.h> #include <QtQuick/private/qsgdistancefieldglyphnode_p_p.h> #include <QtQuick/private/qsgshareddistancefieldglyphcache_p.h> #include <QtQuick/private/qsgatlastexture_p.h> #include <QtQuick/private/qsgtexture_p.h> #include <QtQuick/private/qquickpixmapcache_p.h> #include <QGuiApplication> #include <QOpenGLContext> #include <QQuickWindow> #include <QtGui/qopenglframebufferobject.h> #include <private/qqmlglobal_p.h> #include <QtQuick/private/qsgtexture_p.h> #include <QtGui/private/qguiapplication_p.h> #include <qpa/qplatformintegration.h> #include <qpa/qplatformsharedgraphicscache.h> #include <private/qobject_p.h> #include <qmutex.h> #include <private/qqmlprofilerservice_p.h> DEFINE_BOOL_CONFIG_OPTION(qmlFlashMode, QML_FLASH_MODE) DEFINE_BOOL_CONFIG_OPTION(qmlTranslucentMode, QML_TRANSLUCENT_MODE) DEFINE_BOOL_CONFIG_OPTION(qmlDisableDistanceField, QML_DISABLE_DISTANCEFIELD) /* Comments about this class from Gunnar: The QSGContext class is right now two things.. The first is the adaptation layer and central storage ground for all the things in the scene graph, like textures and materials. This part really belongs inside the scene graph coreapi. The other part is the QML adaptation classes, like how to implement rectangle nodes. This is not part of the scene graph core API, but more part of the QML adaptation of scene graph. If we ever move the scene graph core API into its own thing, this class needs to be split in two. Right now its one because we're lazy when it comes to defining plugin interfaces.. */ QT_BEGIN_NAMESPACE class QSGContextPrivate : public QObjectPrivate { public: QSGContextPrivate() : gl(0) , depthStencilBufferManager(0) , distanceFieldCacheManager(0) #if !defined(QT_OPENGL_ES) || defined(QT_OPENGL_ES_2_ANGLE) , distanceFieldAntialiasing(QSGGlyphNode::HighQualitySubPixelAntialiasing) #else , distanceFieldAntialiasing(QSGGlyphNode::GrayAntialiasing) #endif , atlasManager(0) , flashMode(qmlFlashMode()) , distanceFieldDisabled(qmlDisableDistanceField()) , msaa(false) { renderAlpha = qmlTranslucentMode() ? 0.5 : 1; } ~QSGContextPrivate() { } QOpenGLContext *gl; QMutex textureMutex; QHash<QQuickTextureFactory *, QSGTexture *> textures; QSGDepthStencilBufferManager *depthStencilBufferManager; QSGDistanceFieldGlyphCacheManager *distanceFieldCacheManager; QSGDistanceFieldGlyphNode::AntialiasingMode distanceFieldAntialiasing; QSGAtlasTexture::Manager *atlasManager; bool flashMode; float renderAlpha; bool distanceFieldDisabled; bool msaa; }; class QSGTextureCleanupEvent : public QEvent { public: QSGTextureCleanupEvent(QSGTexture *t) : QEvent(QEvent::User), texture(t) { } ~QSGTextureCleanupEvent() { delete texture; } QSGTexture *texture; }; namespace QSGMultisampleAntialiasing { class ImageNode : public QSGDefaultImageNode { public: void setAntialiasing(bool) { } }; class RectangleNode : public QSGDefaultRectangleNode { public: void setAntialiasing(bool) { } }; } /*! \class QSGContext \brief The QSGContext holds the scene graph entry points for one QML engine. The context is not ready for use until it has a QOpenGLContext. Once that happens, the scene graph population can start. \internal */ QSGContext::QSGContext(QObject *parent) : QObject(*(new QSGContextPrivate), parent) { Q_D(QSGContext); QByteArray mode = qgetenv("QSG_DISTANCEFIELD_ANTIALIASING"); if (mode == "subpixel") d->distanceFieldAntialiasing = QSGGlyphNode::HighQualitySubPixelAntialiasing; else if (mode == "subpixel-lowq") d->distanceFieldAntialiasing = QSGGlyphNode::LowQualitySubPixelAntialiasing; else if (mode == "gray") d->distanceFieldAntialiasing = QSGGlyphNode::GrayAntialiasing; } QSGContext::~QSGContext() { invalidate(); } void QSGContext::invalidate() { Q_D(QSGContext); d->textureMutex.lock(); qDeleteAll(d->textures.values()); d->textures.clear(); d->textureMutex.unlock(); delete d->depthStencilBufferManager; d->depthStencilBufferManager = 0; delete d->distanceFieldCacheManager; d->distanceFieldCacheManager = 0; d->gl = 0; emit invalidated(); /* The cleanup of the atlas textures is a bit intruiging. As part of the cleanup in the threaded render loop, we do: 1. call this function 2. call QCoreApp::sendPostedEvents() to immediately process any pending deferred deletes. 3. delete the GL context. As textures need the atlas manager while cleaning up, the manager needs to be cleaned up after the textures, so we post a deleteLater here at the very bottom so it gets deferred deleted last. Another alternative would be to use a QPointer in QSGAtlasTexture::Texture, but this seemed simpler. */ if (d->atlasManager) { d->atlasManager->deleteLater(); d->atlasManager = 0; } } QSGTexture *QSGContext::textureForFactory(QQuickTextureFactory *factory, QQuickWindow *window) { Q_D(QSGContext); if (!factory) return 0; d->textureMutex.lock(); QSGTexture *texture = d->textures.value(factory); if (!texture) { if (QQuickDefaultTextureFactory *dtf = qobject_cast<QQuickDefaultTextureFactory *>(factory)) texture = createTexture(dtf->image()); else texture = factory->createTexture(window); d->textures.insert(factory, texture); connect(factory, SIGNAL(destroyed(QObject *)), this, SLOT(textureFactoryDestroyed(QObject *)), Qt::DirectConnection); } d->textureMutex.unlock(); return texture; } void QSGContext::textureFactoryDestroyed(QObject *o) { Q_D(QSGContext); QQuickTextureFactory *f = static_cast<QQuickTextureFactory *>(o); d->textureMutex.lock(); QSGTexture *t = d->textures.take(f); d->textureMutex.unlock(); if (t) { if (t->thread() == thread()) t->deleteLater(); else QCoreApplication::postEvent(this, new QSGTextureCleanupEvent(t)); } } QOpenGLContext *QSGContext::glContext() const { Q_D(const QSGContext); return d->gl; } /*! Initializes the scene graph context with the GL context \a context. This also emits the ready() signal so that the QML graph can start building scene graph nodes. */ void QSGContext::initialize(QOpenGLContext *context) { Q_D(QSGContext); QByteArray aaType = qgetenv("QSG_ANTIALIASING_METHOD"); if (aaType == "msaa") { d->msaa = true; } else if (aaType == "vertex") { d->msaa = false; } else { if (context->format().samples() > 0) d->msaa = true; else d->msaa = false; } // Sanity check the surface format, in case it was overridden by the application QSurfaceFormat requested = defaultSurfaceFormat(); QSurfaceFormat actual = context->format(); if (requested.depthBufferSize() > 0 && actual.depthBufferSize() <= 0) qWarning("QSGContext::initialize: depth buffer support missing, expect rendering errors"); if (requested.stencilBufferSize() > 0 && actual.stencilBufferSize() <= 0) qWarning("QSGContext::initialize: stencil buffer support missing, expect rendering errors"); d->atlasManager = new QSGAtlasTexture::Manager(); Q_ASSERT(!d->gl); d->gl = context; emit initialized(); } /*! Returns if the scene graph context is ready or not, meaning that it has a valid GL context. */ bool QSGContext::isReady() const { Q_D(const QSGContext); return d->gl; } void QSGContext::renderNextFrame(QSGRenderer *renderer, GLuint fboId) { if (fboId) { QSGBindableFboId bindable(fboId); renderer->renderScene(bindable); } else { renderer->renderScene(); } } /*! Factory function for scene graph backends of the Rectangle element. */ QSGRectangleNode *QSGContext::createRectangleNode() { Q_D(QSGContext); return d->msaa ? new QSGMultisampleAntialiasing::RectangleNode : new QSGDefaultRectangleNode; } /*! Factory function for scene graph backends of the Image element. */ QSGImageNode *QSGContext::createImageNode() { Q_D(QSGContext); return d->msaa ? new QSGMultisampleAntialiasing::ImageNode : new QSGDefaultImageNode; } /*! Factory function for scene graph backends of the distance-field glyph cache. */ QSGDistanceFieldGlyphCache *QSGContext::distanceFieldGlyphCache(const QRawFont &font) { Q_D(QSGContext); if (!d->distanceFieldCacheManager) d->distanceFieldCacheManager = new QSGDistanceFieldGlyphCacheManager; QSGDistanceFieldGlyphCache *cache = d->distanceFieldCacheManager->cache(font); if (!cache) { QPlatformIntegration *platformIntegration = QGuiApplicationPrivate::platformIntegration(); if (platformIntegration != 0 && platformIntegration->hasCapability(QPlatformIntegration::SharedGraphicsCache)) { QFontEngine *fe = QRawFontPrivate::get(font)->fontEngine; if (!fe->faceId().filename.isEmpty()) { QByteArray keyName = fe->faceId().filename; if (font.style() != QFont::StyleNormal) keyName += QByteArray(" I"); if (font.weight() != QFont::Normal) keyName += ' ' + QByteArray::number(font.weight()); keyName += QByteArray(" DF"); QPlatformSharedGraphicsCache *sharedGraphicsCache = platformIntegration->createPlatformSharedGraphicsCache(keyName); if (sharedGraphicsCache != 0) { sharedGraphicsCache->ensureCacheInitialized(keyName, QPlatformSharedGraphicsCache::OpenGLTexture, QPlatformSharedGraphicsCache::Alpha8); cache = new QSGSharedDistanceFieldGlyphCache(keyName, sharedGraphicsCache, d->distanceFieldCacheManager, glContext(), font); } } } if (!cache) cache = new QSGDefaultDistanceFieldGlyphCache(d->distanceFieldCacheManager, glContext(), font); d->distanceFieldCacheManager->insertCache(font, cache); } return cache; } /*! Factory function for scene graph backends of the Text elements which supports native text rendering. Used in special cases where native look and feel is a main objective. */ QSGGlyphNode *QSGContext::createNativeGlyphNode() { #if defined(QT_OPENGL_ES) && !defined(QT_OPENGL_ES_2_ANGLE) Q_D(QSGContext); if (d->distanceFieldDisabled) return new QSGDefaultGlyphNode; else return createGlyphNode(); #else return new QSGDefaultGlyphNode; #endif } /*! Factory function for scene graph backends of the Text elements; */ QSGGlyphNode *QSGContext::createGlyphNode() { Q_D(QSGContext); if (d->distanceFieldDisabled) { return createNativeGlyphNode(); } else { QSGDistanceFieldGlyphNode *node = new QSGDistanceFieldGlyphNode(this); node->setPreferredAntialiasingMode(d->distanceFieldAntialiasing); return node; } } /*! Factory function for the scene graph renderers. The renderers are used for the toplevel renderer and once for every QQuickShaderEffectSource used in the QML scene. */ QSGRenderer *QSGContext::createRenderer() { return new QSGBatchRenderer::Renderer(this); } QSurfaceFormat QSGContext::defaultSurfaceFormat() const { QSurfaceFormat format; format.setDepthBufferSize(24); format.setStencilBufferSize(8); if (QQuickWindow::hasDefaultAlphaBuffer()) format.setAlphaBufferSize(8); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); return format; } /*! Factory function for texture objects. If \a image is a valid image, the QSGTexture::setImage function will be called with \a image as argument. */ QSGTexture *QSGContext::createTexture(const QImage &image) const { Q_D(const QSGContext); QSGTexture *at = d->atlasManager->create(image); if (at) return at; return createTextureNoAtlas(image); } QSGTexture *QSGContext::createTextureNoAtlas(const QImage &image) const { QSGPlainTexture *t = new QSGPlainTexture(); if (!image.isNull()) t->setImage(image); return t; } /*! Returns the minimum supported framebuffer object size. */ QSize QSGContext::minimumFBOSize() const { #ifdef Q_OS_MAC return QSize(33, 33); #else return QSize(1, 1); #endif } /*! Returns a shared pointer to a depth stencil buffer that can be used with \a fbo. */ QSharedPointer<QSGDepthStencilBuffer> QSGContext::depthStencilBufferForFbo(QOpenGLFramebufferObject *fbo) { Q_D(QSGContext); if (!d->gl) return QSharedPointer<QSGDepthStencilBuffer>(); QSGDepthStencilBufferManager *manager = depthStencilBufferManager(); QSGDepthStencilBuffer::Format format; format.size = fbo->size(); format.samples = fbo->format().samples(); format.attachments = QSGDepthStencilBuffer::DepthAttachment | QSGDepthStencilBuffer::StencilAttachment; QSharedPointer<QSGDepthStencilBuffer> buffer = manager->bufferForFormat(format); if (buffer.isNull()) { buffer = QSharedPointer<QSGDepthStencilBuffer>(new QSGDefaultDepthStencilBuffer(d->gl, format)); manager->insertBuffer(buffer); } return buffer; } /*! Returns a pointer to the context's depth/stencil buffer manager. This is useful for custom implementations of \l depthStencilBufferForFbo(). */ QSGDepthStencilBufferManager *QSGContext::depthStencilBufferManager() { Q_D(QSGContext); if (!d->gl) return 0; if (!d->depthStencilBufferManager) d->depthStencilBufferManager = new QSGDepthStencilBufferManager(d->gl); return d->depthStencilBufferManager; } /*! Sets whether the scene graph should render with flashing update rectangles or not */ void QSGContext::setFlashModeEnabled(bool enabled) { d_func()->flashMode = enabled; } /*! Returns true if the scene graph should be rendered with flashing update rectangles */ bool QSGContext::isFlashModeEnabled() const { return d_func()->flashMode; } /*! Sets the toplevel opacity for rendering. This value will be multiplied into all drawing calls where possible. The default value is 1. Any other value will cause artifacts and is primarily useful for debugging. */ void QSGContext::setRenderAlpha(qreal renderAlpha) { d_func()->renderAlpha = renderAlpha; } /*! Returns the toplevel opacity used for rendering. The default value is 1. \sa setRenderAlpha() */ qreal QSGContext::renderAlpha() const { return d_func()->renderAlpha; } /*! Sets whether or not the scene graph should use the distance field technique to render text */ void QSGContext::setDistanceFieldEnabled(bool enabled) { d_func()->distanceFieldDisabled = !enabled; } /*! Returns true if the scene graph uses the distance field technique to render text */ bool QSGContext::isDistanceFieldEnabled() const { return !d_func()->distanceFieldDisabled; } /*! Creates a new animation driver. */ QAnimationDriver *QSGContext::createAnimationDriver(QObject *parent) { return new QAnimationDriver(parent); } QT_END_NAMESPACE
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------- // Implementation of the ITS tracker class // It reads AliITSclusterV2 clusters and creates AliITStrackMI tracks // and fills with them the ESD // Origin: Marian Ivanov, CERN, Marian.Ivanov@cern.ch // dEdx analysis by: Boris Batyunya, JINR, Boris.Batiounia@cern.ch // //------------------------------------------------------------------------- #include <TMatrixD.h> #include <TTree.h> #include <TTreeStream.h> #include <TTree.h> #include "AliESD.h" #include "AliESDV0MI.h" #include "AliHelix.h" #include "AliITSclusterV2.h" #include "AliITSgeom.h" #include "AliITStrackerMI.h" ClassImp(AliITStrackerMI) AliITStrackerMI::AliITSlayer AliITStrackerMI::fgLayers[kMaxLayer]; // ITS layers AliITStrackerMI::AliITStrackerMI(const AliITSgeom *geom) : AliTracker() { //-------------------------------------------------------------------- //This is the AliITStrackerMI constructor //-------------------------------------------------------------------- fCoeficients = 0; fAfterV0 = kFALSE; AliITSgeom *g=(AliITSgeom*)geom; Float_t x,y,z; Int_t i; for (i=1; i<kMaxLayer+1; i++) { Int_t nlad=g->GetNladders(i); Int_t ndet=g->GetNdetectors(i); g->GetTrans(i,1,1,x,y,z); Double_t r=TMath::Sqrt(x*x + y*y); Double_t poff=TMath::ATan2(y,x); Double_t zoff=z; g->GetTrans(i,1,2,x,y,z); r += TMath::Sqrt(x*x + y*y); g->GetTrans(i,2,1,x,y,z); r += TMath::Sqrt(x*x + y*y); g->GetTrans(i,2,2,x,y,z); r += TMath::Sqrt(x*x + y*y); r*=0.25; new (fgLayers+i-1) AliITSlayer(r,poff,zoff,nlad,ndet); for (Int_t j=1; j<nlad+1; j++) { for (Int_t k=1; k<ndet+1; k++) { //Fill this layer with detectors Float_t x,y,zshift; g->GetTrans(i,j,k,x,y,zshift); Double_t rot[9]; g->GetRotMatrix(i,j,k,rot); Double_t phi=TMath::ATan2(rot[1],rot[0])+TMath::Pi(); phi+=TMath::Pi()/2; if (i==1) phi+=TMath::Pi(); Double_t cp=TMath::Cos(phi), sp=TMath::Sin(phi); Double_t r=x*cp+y*sp; AliITSdetector &det=fgLayers[i-1].GetDetector((j-1)*ndet + k-1); new(&det) AliITSdetector(r,phi); } } } fI=kMaxLayer; fPass=0; fConstraint[0]=1; fConstraint[1]=0; Double_t xyz[]={kXV,kYV,kZV}, ers[]={kSigmaXV,kSigmaYV,kSigmaZV}; SetVertex(xyz,ers); for (Int_t i=0; i<kMaxLayer; i++) fLayersNotToSkip[i]=kLayersNotToSkip[i]; fLastLayerToTrackTo=kLastLayerToTrackTo; for (Int_t i=0;i<100000;i++){ fBestTrackIndex[i]=0; } // fDebugStreamer = new TTreeSRedirector("ITSdebug.root"); } AliITStrackerMI::~AliITStrackerMI() { // //destructor // if (fCoeficients) delete []fCoeficients; if (fDebugStreamer) { //fDebugStreamer->Close(); delete fDebugStreamer; } } void AliITStrackerMI::SetLayersNotToSkip(Int_t *l) { //-------------------------------------------------------------------- //This function set masks of the layers which must be not skipped //-------------------------------------------------------------------- for (Int_t i=0; i<kMaxLayer; i++) fLayersNotToSkip[i]=l[i]; } Int_t AliITStrackerMI::LoadClusters(TTree *cTree) { //-------------------------------------------------------------------- //This function loads ITS clusters //-------------------------------------------------------------------- TBranch *branch=cTree->GetBranch("Clusters"); if (!branch) { Error("LoadClusters"," can't get the branch !\n"); return 1; } TClonesArray dummy("AliITSclusterV2",10000), *clusters=&dummy; branch->SetAddress(&clusters); Int_t j=0; Int_t detector=0; for (Int_t i=0; i<kMaxLayer; i++) { Int_t ndet=fgLayers[i].GetNdetectors(); Int_t jmax = j + fgLayers[i].GetNladders()*ndet; for (; j<jmax; j++) { if (!cTree->GetEvent(j)) continue; Int_t ncl=clusters->GetEntriesFast(); SignDeltas(clusters,GetZ()); while (ncl--) { AliITSclusterV2 *c=(AliITSclusterV2*)clusters->UncheckedAt(ncl); detector = c->GetDetectorIndex(); fgLayers[i].InsertCluster(new AliITSclusterV2(*c)); } clusters->Delete(); //add dead zone virtual "cluster" if (i<2){ for (Float_t ydead = 0; ydead < 1.31 ; ydead+=(i+1.)*0.018){ Int_t lab[4] = {0,0,0,detector}; Int_t info[3] = {0,0,0}; Float_t hit[5]={0,0,0.004/12.,0.001/12.,0}; if (i==0) hit[0] =ydead-0.4; if (i==1) hit[0]=ydead-3.75; hit[1] =-0.04; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); hit[1]=-7.05; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); hit[1]=-7.15; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); hit[1] =0.06; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); hit[1]=7.05; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); hit[1]=7.25; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); } } } // fgLayers[i].ResetRoad(); //road defined by the cluster density fgLayers[i].SortClusters(); } return 0; } void AliITStrackerMI::UnloadClusters() { //-------------------------------------------------------------------- //This function unloads ITS clusters //-------------------------------------------------------------------- for (Int_t i=0; i<kMaxLayer; i++) fgLayers[i].ResetClusters(); } static Int_t CorrectForDeadZoneMaterial(AliITStrackMI *t) { //-------------------------------------------------------------------- // Correction for the material between the TPC and the ITS // (should it belong to the TPC code ?) //-------------------------------------------------------------------- Double_t riw=80., diw=0.0053, x0iw=30; // TPC inner wall ? Double_t rcd=61., dcd=0.0053, x0cd=30; // TPC "central drum" ? Double_t yr=12.8, dr=0.03; // rods ? Double_t zm=0.2, dm=0.40; // membrane //Double_t rr=52., dr=0.19, x0r=24., yyr=7.77; //rails Double_t rs=50., ds=0.001; // something belonging to the ITS (screen ?) if (t->GetX() > riw) { if (!t->PropagateTo(riw,diw,x0iw)) return 1; if (TMath::Abs(t->GetY())>yr) t->CorrectForMaterial(dr); if (TMath::Abs(t->GetZ())<zm) t->CorrectForMaterial(dm); if (!t->PropagateTo(rcd,dcd,x0cd)) return 1; //Double_t x,y,z; t->GetGlobalXYZat(rr,x,y,z); //if (TMath::Abs(y)<yyr) t->PropagateTo(rr,dr,x0r); if (!t->PropagateTo(rs,ds)) return 1; } else if (t->GetX() < rs) { if (!t->PropagateTo(rs,-ds)) return 1; //Double_t x,y,z; t->GetGlobalXYZat(rr,x,y,z); //if (TMath::Abs(y)<yyr) t->PropagateTo(rr,-dr,x0r); if (!t->PropagateTo(rcd,-dcd,x0cd)) return 1; if (!t->PropagateTo(riw+0.001,-diw,x0iw)) return 1; } else { ::Error("CorrectForDeadZoneMaterial","track is already in the dead zone !"); return 1; } return 0; } Int_t AliITStrackerMI::Clusters2Tracks(AliESD *event) { //-------------------------------------------------------------------- // This functions reconstructs ITS tracks // The clusters must be already loaded ! //-------------------------------------------------------------------- TObjArray itsTracks(15000); fOriginal.Clear(); fEsd = event; // store pointer to the esd {/* Read ESD tracks */ Int_t nentr=event->GetNumberOfTracks(); Info("Clusters2Tracks", "Number of ESD tracks: %d\n", nentr); while (nentr--) { AliESDtrack *esd=event->GetTrack(nentr); if ((esd->GetStatus()&AliESDtrack::kTPCin)==0) continue; if (esd->GetStatus()&AliESDtrack::kTPCout) continue; if (esd->GetStatus()&AliESDtrack::kITSin) continue; if (esd->GetKinkIndex(0)>0) continue; //kink daughter AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("Clusters2Tracks",msg); delete t; continue; } t->fD[0] = t->GetD(GetX(),GetY()); t->fD[1] = t->GetZat(GetX())-GetZ(); Double_t vdist = TMath::Sqrt(t->fD[0]*t->fD[0]+t->fD[1]*t->fD[1]); if (t->GetMass()<0.13) t->SetMass(0.13957); // MI look to the esd - mass hypothesys !!!!!!!!!!! // write expected q t->fExpQ = TMath::Max(0.8*t->fESDtrack->GetTPCsignal(),30.); if (esd->GetV0Index(0)>0 && t->fD[0]<30){ //track - can be V0 according to TPC } else{ if (TMath::Abs(t->fD[0])>10) { delete t; continue; } if (TMath::Abs(vdist)>20) { delete t; continue; } if (TMath::Abs(1/t->Get1Pt())<0.120) { delete t; continue; } if (CorrectForDeadZoneMaterial(t)!=0) { //Warning("Clusters2Tracks", // "failed to correct for the material in the dead zone !\n"); delete t; continue; } } t->fReconstructed = kFALSE; itsTracks.AddLast(t); fOriginal.AddLast(t); } } /* End Read ESD tracks */ itsTracks.Sort(); fOriginal.Sort(); Int_t nentr=itsTracks.GetEntriesFast(); fTrackHypothesys.Expand(nentr); fBestHypothesys.Expand(nentr); MakeCoeficients(nentr); Int_t ntrk=0; for (fPass=0; fPass<2; fPass++) { Int_t &constraint=fConstraint[fPass]; if (constraint<0) continue; for (Int_t i=0; i<nentr; i++) { // cerr<<fPass<<" "<<i<<'\r'; fCurrentEsdTrack = i; AliITStrackMI *t=(AliITStrackMI*)itsTracks.UncheckedAt(i); if (t==0) continue; //this track has been already tracked if (t->fReconstructed&&(t->fNUsed<1.5)) continue; //this track was already "succesfully" reconstructed if ( (TMath::Abs(t->GetD(GetX(),GetY())) >3.) && fConstraint[fPass]) continue; if ( (TMath::Abs(t->GetZat(GetX())-GetZ())>3.) && fConstraint[fPass]) continue; Int_t tpcLabel=t->GetLabel(); //save the TPC track label fI = 6; ResetTrackToFollow(*t); ResetBestTrack(); FollowProlongationTree(t,i,fConstraint[fPass]); SortTrackHypothesys(fCurrentEsdTrack,20,0); //MI change // AliITStrackMI * besttrack = GetBestHypothesys(fCurrentEsdTrack,t,15); if (!besttrack) continue; besttrack->SetLabel(tpcLabel); // besttrack->CookdEdx(); CookdEdx(besttrack); besttrack->fFakeRatio=1.; CookLabel(besttrack,0.); //For comparison only UpdateESDtrack(besttrack,AliESDtrack::kITSin); /* if ( besttrack->GetNumberOfClusters()<6 && fConstraint[fPass]) { continue; } if (besttrack->fChi2MIP[0]+besttrack->fNUsed>3.5) continue; if ( (TMath::Abs(besttrack->fD[0]*besttrack->fD[0]+besttrack->fD[1]*besttrack->fD[1])>0.1) && fConstraint[fPass]) continue; //delete itsTracks.RemoveAt(i); */ if (fConstraint[fPass]&&(!besttrack->IsGoldPrimary())) continue; //to be tracked also without vertex constrain t->fReconstructed = kTRUE; ntrk++; } GetBestHypothesysMIP(itsTracks); } //GetBestHypothesysMIP(itsTracks); UpdateTPCV0(event); FindV02(event); fAfterV0 = kTRUE; //GetBestHypothesysMIP(itsTracks); // itsTracks.Delete(); // Int_t entries = fTrackHypothesys.GetEntriesFast(); for (Int_t ientry=0;ientry<entries;ientry++){ TObjArray * array =(TObjArray*)fTrackHypothesys.UncheckedAt(ientry); if (array) array->Delete(); delete fTrackHypothesys.RemoveAt(ientry); } fTrackHypothesys.Delete(); fBestHypothesys.Delete(); fOriginal.Clear(); delete []fCoeficients; fCoeficients=0; Info("Clusters2Tracks","Number of prolonged tracks: %d\n",ntrk); return 0; } Int_t AliITStrackerMI::PropagateBack(AliESD *event) { //-------------------------------------------------------------------- // This functions propagates reconstructed ITS tracks back // The clusters must be loaded ! //-------------------------------------------------------------------- Int_t nentr=event->GetNumberOfTracks(); Info("PropagateBack", "Number of ESD tracks: %d\n", nentr); Int_t ntrk=0; for (Int_t i=0; i<nentr; i++) { AliESDtrack *esd=event->GetTrack(i); if ((esd->GetStatus()&AliESDtrack::kITSin)==0) continue; if (esd->GetStatus()&AliESDtrack::kITSout) continue; AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("PropagateBack",msg); delete t; continue; } t->fExpQ = TMath::Max(0.8*t->fESDtrack->GetTPCsignal(),30.); ResetTrackToFollow(*t); // propagete to vertex [SR, GSI 17.02.2003] // Start Time measurement [SR, GSI 17.02.2003], corrected by I.Belikov if (fTrackToFollow.PropagateTo(3.,0.0028,65.19)) { if (fTrackToFollow.PropagateToVertex()) { fTrackToFollow.StartTimeIntegral(); } fTrackToFollow.PropagateTo(3.,-0.0028,65.19); } fTrackToFollow.ResetCovariance(); fTrackToFollow.ResetClusters(); if (RefitAt(49.,&fTrackToFollow,t)) { if (CorrectForDeadZoneMaterial(&fTrackToFollow)!=0) { //Warning("PropagateBack", // "failed to correct for the material in the dead zone !\n"); delete t; continue; } fTrackToFollow.SetLabel(t->GetLabel()); //fTrackToFollow.CookdEdx(); CookLabel(&fTrackToFollow,0.); //For comparison only fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSout); //UseClusters(&fTrackToFollow); ntrk++; } delete t; } Info("PropagateBack","Number of back propagated ITS tracks: %d\n",ntrk); return 0; } Int_t AliITStrackerMI::RefitInward(AliESD *event) { //-------------------------------------------------------------------- // This functions refits ITS tracks using the // "inward propagated" TPC tracks // The clusters must be loaded ! //-------------------------------------------------------------------- RefitV02(event); Int_t nentr=event->GetNumberOfTracks(); Info("RefitInward", "Number of ESD tracks: %d\n", nentr); Int_t ntrk=0; for (Int_t i=0; i<nentr; i++) { AliESDtrack *esd=event->GetTrack(i); if ((esd->GetStatus()&AliESDtrack::kITSout) == 0) continue; if (esd->GetStatus()&AliESDtrack::kITSrefit) continue; if (esd->GetStatus()&AliESDtrack::kTPCout) if ((esd->GetStatus()&AliESDtrack::kTPCrefit)==0) continue; AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("RefitInward",msg); delete t; continue; } t->fExpQ = TMath::Max(0.8*t->fESDtrack->GetTPCsignal(),30.); if (CorrectForDeadZoneMaterial(t)!=0) { //Warning("RefitInward", // "failed to correct for the material in the dead zone !\n"); delete t; continue; } ResetTrackToFollow(*t); fTrackToFollow.ResetClusters(); if ((esd->GetStatus()&AliESDtrack::kTPCin)==0) fTrackToFollow.ResetCovariance(); //Refitting... if (RefitAt(3.7, &fTrackToFollow, t)) { fTrackToFollow.SetLabel(t->GetLabel()); // fTrackToFollow.CookdEdx(); CookdEdx(&fTrackToFollow); CookLabel(&fTrackToFollow,0.0); //For comparison only if (fTrackToFollow.PropagateTo(3.,0.0028,65.19)) {//The beam pipe Double_t a=fTrackToFollow.GetAlpha(); Double_t cs=TMath::Cos(a),sn=TMath::Sin(a); Double_t xv= GetX()*cs + GetY()*sn; Double_t yv=-GetX()*sn + GetY()*cs; Double_t c=fTrackToFollow.GetC(), snp=fTrackToFollow.GetSnp(); Double_t x=fTrackToFollow.GetX(), y=fTrackToFollow.GetY(); Double_t tgfv=-(c*(x-xv)-snp)/(c*(y-yv) + TMath::Sqrt(1.-snp*snp)); Double_t fv=TMath::ATan(tgfv); cs=TMath::Cos(fv); sn=TMath::Sin(fv); x = xv*cs + yv*sn; yv=-xv*sn + yv*cs; xv=x; if (fTrackToFollow.Propagate(fv+a,xv)) { fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSrefit); //UseClusters(&fTrackToFollow); { AliITSclusterV2 c; c.SetY(yv); c.SetZ(GetZ()); c.SetSigmaY2(GetSigmaY()*GetSigmaY()); c.SetSigmaZ2(GetSigmaZ()*GetSigmaZ()); Double_t chi2=fTrackToFollow.GetPredictedChi2(&c); //Double_t chi2=GetPredictedChi2MI(&fTrackToFollow,&c,fI); if (chi2<kMaxChi2) if (fTrackToFollow.Update(&c,-chi2,0)) //if (UpdateMI(&fTrackToFollow,&c,-chi2,0)) fTrackToFollow.SetConstrainedESDtrack(chi2); } ntrk++; } } } delete t; } Info("RefitInward","Number of refitted tracks: %d\n",ntrk); return 0; } AliCluster *AliITStrackerMI::GetCluster(Int_t index) const { //-------------------------------------------------------------------- // Return pointer to a given cluster //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; return fgLayers[l].GetCluster(c); } void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdindex, Bool_t constrain) { //-------------------------------------------------------------------- // Follow prolongation tree //-------------------------------------------------------------------- // AliESDtrack * esd = otrack->fESDtrack; if (esd->GetV0Index(0)>0){ // // TEMPORARY SOLLUTION: map V0 indexes to point to proper track // mapping of esd track is different as its track in Containers // Need something more stable // Indexes are set back againg to the ESD track indexes in UpdateTPCV0 for (Int_t i=0;i<3;i++){ Int_t index = esd->GetV0Index(i); if (index==0) break; AliESDV0MI * vertex = fEsd->GetV0MI(index); if (vertex->GetStatus()<0) continue; // rejected V0 // if (esd->GetSign()>0) { vertex->SetIndex(0,esdindex); } else{ vertex->SetIndex(1,esdindex); } } } TObjArray *bestarray = (TObjArray*)fBestHypothesys.At(esdindex); if (!bestarray){ bestarray = new TObjArray(5); fBestHypothesys.AddAt(bestarray,esdindex); } // //setup tree of the prolongations // static AliITStrackMI tracks[7][100]; AliITStrackMI *currenttrack; static AliITStrackMI currenttrack1; static AliITStrackMI currenttrack2; static AliITStrackMI backuptrack; Int_t ntracks[7]; Int_t nindexes[7][100]; Float_t normalizedchi2[100]; for (Int_t ilayer=0;ilayer<6;ilayer++) ntracks[ilayer]=0; otrack->fNSkipped=0; new (&(tracks[6][0])) AliITStrackMI(*otrack); ntracks[6]=1; for (Int_t i=0;i<7;i++) nindexes[i][0]=0; // // // follow prolongations for (Int_t ilayer=5;ilayer>=0;ilayer--){ // AliITSlayer &layer=fgLayers[ilayer]; Double_t r=layer.GetR(); ntracks[ilayer]=0; // // Int_t nskipped=0; Float_t nused =0; for (Int_t itrack =0;itrack<ntracks[ilayer+1];itrack++){ //set current track if (ntracks[ilayer]>=100) break; if (tracks[ilayer+1][nindexes[ilayer+1][itrack]].fNSkipped>0) nskipped++; if (tracks[ilayer+1][nindexes[ilayer+1][itrack]].fNUsed>2.) nused++; if (ntracks[ilayer]>15+ilayer){ if (itrack>1&&tracks[ilayer+1][nindexes[ilayer+1][itrack]].fNSkipped>0 && nskipped>4+ilayer) continue; if (itrack>1&&tracks[ilayer+1][nindexes[ilayer+1][itrack]].fNUsed>2. && nused>3) continue; } new(&currenttrack1) AliITStrackMI(tracks[ilayer+1][nindexes[ilayer+1][itrack]]); if (ilayer==3 || ilayer==1) { Double_t rs=0.5*(fgLayers[ilayer+1].GetR() + r); Double_t d=0.0034, x0=38.6; if (ilayer==1) {rs=9.; d=0.0097; x0=42;} if (!currenttrack1.PropagateTo(rs,d,x0)) { continue; } } // //find intersection with layer Double_t x,y,z; if (!currenttrack1.GetGlobalXYZat(r,x,y,z)) { continue; } Double_t phi=TMath::ATan2(y,x); Int_t idet=layer.FindDetectorIndex(phi,z); if (idet<0) { continue; } //propagate to the intersection const AliITSdetector &det=layer.GetDetector(idet); phi=det.GetPhi(); new(&currenttrack2) AliITStrackMI(currenttrack1); if (!currenttrack1.Propagate(phi,det.GetR())) { continue; } currenttrack2.Propagate(phi,det.GetR()); // currenttrack1.SetDetectorIndex(idet); currenttrack2.SetDetectorIndex(idet); // // Double_t dz=7.5*TMath::Sqrt(currenttrack1.GetSigmaZ2() + 16.*kSigmaZ2[ilayer]); Double_t dy=7.5*TMath::Sqrt(currenttrack1.GetSigmaY2() + 16.*kSigmaY2[ilayer]); // Bool_t isBoundary=kFALSE; if (currenttrack1.GetY()-dy< det.GetYmin()+0.2) isBoundary = kTRUE; if (currenttrack1.GetY()+dy> det.GetYmax()-0.2) isBoundary = kTRUE; if (currenttrack1.GetZ()-dz< det.GetZmin()+0.2) isBoundary = kTRUE; if (currenttrack1.GetZ()+dz> det.GetZmax()-0.2) isBoundary = kTRUE; if (isBoundary){ // track at boundary between detectors Float_t maxtgl = TMath::Abs(currenttrack1.GetTgl()); if (maxtgl>1) maxtgl=1; dz = TMath::Sqrt(dz*dz+0.25*maxtgl*maxtgl); // Float_t maxsnp = TMath::Abs(currenttrack1.GetSnp()); if (maxsnp>0.95) continue; //if (maxsnp>0.5) maxsnp=0.5; dy=TMath::Sqrt(dy*dy+0.25*maxsnp*maxsnp); } Double_t zmin=currenttrack1.GetZ() - dz; Double_t zmax=currenttrack1.GetZ() + dz; Double_t ymin=currenttrack1.GetY() + r*phi - dy; Double_t ymax=currenttrack1.GetY() + r*phi + dy; layer.SelectClusters(zmin,zmax,ymin,ymax); // // loop over all possible prolongations // Double_t msz=1./((currenttrack1.GetSigmaZ2() + 16.*kSigmaZ2[ilayer])); Double_t msy=1./((currenttrack1.GetSigmaY2() + 16.*kSigmaY2[ilayer])); if (constrain){ msy/=60; msz/=60.; } else{ msy/=50; msz/=50.; } // const AliITSclusterV2 *c=0; Int_t ci=-1; Double_t chi2=12345.; Int_t deadzone=0; currenttrack = &currenttrack1; while ((c=layer.GetNextCluster(ci))!=0) { if (ntracks[ilayer]>95) break; //space for skipped clusters Bool_t change =kFALSE; if (c->GetQ()==0 && (deadzone==1)) continue; Int_t idet=c->GetDetectorIndex(); if (currenttrack->GetDetectorIndex()!=idet) { const AliITSdetector &det=layer.GetDetector(idet); Double_t y,z; if (!currenttrack2.GetProlongationFast(det.GetPhi(),det.GetR(),y,z)) continue; Float_t pz = (z - c->GetZ()) , py=(y - c->GetY()); if (pz*pz*msz+py*py*msy>1.) continue; // new (&backuptrack) AliITStrackMI(currenttrack2); change = kTRUE; currenttrack =&currenttrack2; if (!currenttrack->Propagate(det.GetPhi(),det.GetR())) { new (currenttrack) AliITStrackMI(backuptrack); change = kFALSE; continue; } currenttrack->SetDetectorIndex(idet); } else{ Float_t pz = (currenttrack->GetZ() - c->GetZ()) , py=(currenttrack->GetY() - c->GetY()); if (pz*pz*msz+py*py*msy>1.) continue; } chi2=GetPredictedChi2MI(currenttrack,c,ilayer); if (chi2<kMaxChi2s[ilayer]){ if (c->GetQ()==0) deadzone=1; // take dead zone only once if (ntracks[ilayer]>=100) continue; AliITStrackMI * updatetrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(*currenttrack); updatetrack->fClIndex[ilayer]=0; if (change){ new (&currenttrack2) AliITStrackMI(backuptrack); } if (c->GetQ()!=0){ if (!UpdateMI(updatetrack,c,chi2,(ilayer<<28)+ci)) continue; updatetrack->SetSampledEdx(c->GetQ(),updatetrack->GetNumberOfClusters()-1); //b.b. } else { updatetrack->fNDeadZone++; updatetrack->fDeadZoneProbability=GetDeadZoneProbability(updatetrack->GetZ(),TMath::Sqrt(updatetrack->GetSigmaZ2())); } if (c->IsUsed()){ updatetrack->fNUsed++; } Double_t x0; Double_t d=layer.GetThickness(updatetrack->GetY(),updatetrack->GetZ(),x0); updatetrack->CorrectForMaterial(d,x0); if (constrain) { updatetrack->fConstrain = constrain; fI = ilayer; Double_t d=GetEffectiveThickness(0,0); //Think of this !!!! Double_t xyz[]={GetX(),GetY(),GetZ()}; Double_t ptfactor = 1; Double_t ers[]={GetSigmaX()*ptfactor,GetSigmaY()*ptfactor,GetSigmaZ()}; Bool_t isPrim = kTRUE; if (ilayer<4){ updatetrack->fD[0] = updatetrack->GetD(GetX(),GetY()); updatetrack->fD[1] = updatetrack->GetZat(GetX())-GetZ(); if ( TMath::Abs(updatetrack->fD[0]/(1.+ilayer))>0.4 || TMath::Abs(updatetrack->fD[1]/(1.+ilayer))>0.4) isPrim=kFALSE; } if (isPrim) updatetrack->Improve(d,xyz,ers); } //apply vertex constrain ntracks[ilayer]++; } // create new hypothesy } // loop over possible cluster prolongation // if (constrain&&itrack<2&&currenttrack1.fNSkipped==0 && deadzone==0){ if (constrain&&itrack<2&&currenttrack1.fNSkipped==0 && deadzone==0&&ntracks[ilayer]<100){ AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1); vtrack->fClIndex[ilayer]=0; fI = ilayer; Double_t d=GetEffectiveThickness(0,0); //Think of this !!!! Double_t xyz[]={GetX(),GetY(),GetZ()}; Double_t ers[]={GetSigmaX(),GetSigmaY(),GetSigmaZ()}; vtrack->Improve(d,xyz,ers); vtrack->fNSkipped++; ntracks[ilayer]++; } if (constrain&&itrack<1&&TMath::Abs(currenttrack1.fP3)>1.1){ //big theta -- for low mult. runs AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1); vtrack->fClIndex[ilayer]=0; fI = ilayer; Double_t d=GetEffectiveThickness(0,0); //Think of this !!!! Double_t xyz[]={GetX(),GetY(),GetZ()}; Double_t ers[]={GetSigmaX(),GetSigmaY(),GetSigmaZ()}; vtrack->Improve(d,xyz,ers); vtrack->fNDeadZone++; ntracks[ilayer]++; } } //loop over track candidates // // Int_t accepted=0; Int_t golds=0; for (Int_t itrack=0;itrack<ntracks[ilayer];itrack++){ normalizedchi2[itrack] = NormalizedChi2(&tracks[ilayer][itrack],ilayer); if ( normalizedchi2[itrack]<3+0.5*ilayer) golds++; if (ilayer>4) accepted++; else{ if ( constrain && normalizedchi2[itrack]<kMaxNormChi2C[ilayer]+1) accepted++; if (!constrain && normalizedchi2[itrack]<kMaxNormChi2NonC[ilayer]+1) accepted++; } } TMath::Sort(ntracks[ilayer],normalizedchi2,nindexes[ilayer],kFALSE); ntracks[ilayer] = TMath::Min(accepted,7+2*ilayer); if (ntracks[ilayer]<golds+2+ilayer) ntracks[ilayer]=TMath::Min(golds+2+ilayer,accepted); if (ntracks[ilayer]>90) ntracks[ilayer]=90; } //loop over layers //printf("%d\t%d\t%d\t%d\t%d\t%d\n",ntracks[0],ntracks[1],ntracks[2],ntracks[3],ntracks[4],ntracks[5]); Int_t max = constrain? 20: 5; for (Int_t i=0;i<TMath::Min(max,ntracks[0]);i++) { AliITStrackMI & track= tracks[0][nindexes[0][i]]; if (track.GetNumberOfClusters()<2) continue; if (!constrain&&track.fNormChi2[0]>7.)continue; AddTrackHypothesys(new AliITStrackMI(track), esdindex); } for (Int_t i=0;i<TMath::Min(2,ntracks[1]);i++) { AliITStrackMI & track= tracks[1][nindexes[1][i]]; if (track.GetNumberOfClusters()<4) continue; if (!constrain&&track.fNormChi2[1]>7.)continue; if (constrain) track.fNSkipped+=1; if (!constrain) { track.fD[0] = track.GetD(GetX(),GetY()); track.fNSkipped+=4./(4.+8.*TMath::Abs(track.fD[0])); if (track.fN+track.fNDeadZone+track.fNSkipped>6) { track.fNSkipped = 6-track.fN+track.fNDeadZone; } } AddTrackHypothesys(new AliITStrackMI(track), esdindex); } //} if (!constrain){ for (Int_t i=0;i<TMath::Min(2,ntracks[2]);i++) { AliITStrackMI & track= tracks[2][nindexes[2][i]]; if (track.GetNumberOfClusters()<3) continue; if (!constrain&&track.fNormChi2[2]>7.)continue; if (constrain) track.fNSkipped+=2; if (!constrain){ track.fD[0] = track.GetD(GetX(),GetY()); track.fNSkipped+= 7./(7.+8.*TMath::Abs(track.fD[0])); if (track.fN+track.fNDeadZone+track.fNSkipped>6) { track.fNSkipped = 6-track.fN+track.fNDeadZone; } } AddTrackHypothesys(new AliITStrackMI(track), esdindex); } } if (!constrain){ // // register best tracks - important for V0 finder // for (Int_t ilayer=0;ilayer<5;ilayer++){ if (ntracks[ilayer]==0) continue; AliITStrackMI & track= tracks[ilayer][nindexes[ilayer][0]]; if (track.GetNumberOfClusters()<1) continue; CookLabel(&track,0); bestarray->AddAt(new AliITStrackMI(track),ilayer); } } // // update TPC V0 information // if (otrack->fESDtrack->GetV0Index(0)>0){ Float_t fprimvertex[3]={GetX(),GetY(),GetZ()}; for (Int_t i=0;i<3;i++){ Int_t index = otrack->fESDtrack->GetV0Index(i); if (index==0) break; AliESDV0MI * vertex = fEsd->GetV0MI(index); if (vertex->GetStatus()<0) continue; // rejected V0 // if (otrack->fP4>0) { vertex->SetIndex(0,esdindex); } else{ vertex->SetIndex(1,esdindex); } //find nearest layer with track info Int_t nearestold = GetNearestLayer(vertex->GetXrp()); Int_t nearest = nearestold; for (Int_t ilayer =nearest;ilayer<8;ilayer++){ if (ntracks[nearest]==0){ nearest = ilayer; } } // AliITStrackMI & track= tracks[nearest][nindexes[nearest][0]]; if (nearestold<5&&nearest<5){ Bool_t accept = track.fNormChi2[nearest]<10; if (accept){ if (track.fP4>0) { vertex->SetP(track); vertex->Update(fprimvertex); // vertex->SetIndex(0,track.fESDtrack->GetID()); if (track.GetNumberOfClusters()>2) AddTrackHypothesys(new AliITStrackMI(track), esdindex); }else{ vertex->SetM(track); vertex->Update(fprimvertex); //vertex->SetIndex(1,track.fESDtrack->GetID()); if (track.GetNumberOfClusters()>2) AddTrackHypothesys(new AliITStrackMI(track), esdindex); } vertex->SetStatus(vertex->GetStatus()+1); }else{ // vertex->SetStatus(-2); // reject V0 - not enough clusters } } // if (nearestold>3){ // Int_t indexlayer = (ntracks[0]>0)? 0:1; // if (ntracks[indexlayer]>0){ // AliITStrackMI & track= tracks[indexlayer][nindexes[indexlayer][0]]; // if (track.GetNumberOfClusters()>4&&track.fNormChi2[indexlayer]<4){ // vertex->SetStatus(-1); // reject V0 - clusters before // } // } // } } } } AliITStrackerMI::AliITSlayer & AliITStrackerMI::GetLayer(Int_t layer) const { //-------------------------------------------------------------------- // // return fgLayers[layer]; } AliITStrackerMI::AliITSlayer::AliITSlayer() { //-------------------------------------------------------------------- //default AliITSlayer constructor //-------------------------------------------------------------------- fN=0; fDetectors=0; fSkip = 0; fCurrentSlice=-1; for (Int_t i=0; i<kMaxClusterPerLayer;i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } } AliITStrackerMI::AliITSlayer:: AliITSlayer(Double_t r,Double_t p,Double_t z,Int_t nl,Int_t nd) { //-------------------------------------------------------------------- //main AliITSlayer constructor //-------------------------------------------------------------------- fR=r; fPhiOffset=p; fZOffset=z; fNladders=nl; fNdetectors=nd; fDetectors=new AliITSdetector[fNladders*fNdetectors]; fN=0; fI=0; fSkip = 0; fRoad=2*fR*TMath::Sqrt(3.14/1.);//assuming that there's only one cluster } AliITStrackerMI::AliITSlayer::~AliITSlayer() { //-------------------------------------------------------------------- // AliITSlayer destructor //-------------------------------------------------------------------- delete[] fDetectors; for (Int_t i=0; i<fN; i++) delete fClusters[i]; for (Int_t i=0; i<kMaxClusterPerLayer;i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } } void AliITStrackerMI::AliITSlayer::ResetClusters() { //-------------------------------------------------------------------- // This function removes loaded clusters //-------------------------------------------------------------------- for (Int_t i=0; i<fN; i++) delete fClusters[i]; for (Int_t i=0; i<kMaxClusterPerLayer;i++){ fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } fN=0; fI=0; } void AliITStrackerMI::AliITSlayer::ResetWeights() { //-------------------------------------------------------------------- // This function reset weights of the clusters //-------------------------------------------------------------------- for (Int_t i=0; i<kMaxClusterPerLayer;i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } for (Int_t i=0; i<fN;i++) { AliITSclusterV2 * cl = (AliITSclusterV2*)GetCluster(i); if (cl&&cl->IsUsed()) cl->Use(); } } void AliITStrackerMI::AliITSlayer::ResetRoad() { //-------------------------------------------------------------------- // This function calculates the road defined by the cluster density //-------------------------------------------------------------------- Int_t n=0; for (Int_t i=0; i<fN; i++) { if (TMath::Abs(fClusters[i]->GetZ())<fR) n++; } //if (n>1) fRoad=2*fR*TMath::Sqrt(3.14/n); if (n>1) fRoad=2*fR*TMath::Sqrt(3.14/n); } Int_t AliITStrackerMI::AliITSlayer::InsertCluster(AliITSclusterV2 *c) { //-------------------------------------------------------------------- //This function adds a cluster to this layer //-------------------------------------------------------------------- if (fN==kMaxClusterPerLayer) { ::Error("InsertCluster","Too many clusters !\n"); return 1; } fCurrentSlice=-1; fClusters[fN]=c; fN++; AliITSdetector &det=GetDetector(c->GetDetectorIndex()); if (c->GetY()<det.GetYmin()) det.SetYmin(c->GetY()); if (c->GetY()>det.GetYmax()) det.SetYmax(c->GetY()); if (c->GetZ()<det.GetZmin()) det.SetZmin(c->GetZ()); if (c->GetZ()>det.GetZmax()) det.SetZmax(c->GetZ()); return 0; } void AliITStrackerMI::AliITSlayer::SortClusters() { // //sort clusters // AliITSclusterV2 **clusters = new AliITSclusterV2*[fN]; Float_t *z = new Float_t[fN]; Int_t * index = new Int_t[fN]; // for (Int_t i=0;i<fN;i++){ z[i] = fClusters[i]->GetZ(); } TMath::Sort(fN,z,index,kFALSE); for (Int_t i=0;i<fN;i++){ clusters[i] = fClusters[index[i]]; } // for (Int_t i=0;i<fN;i++){ fClusters[i] = clusters[i]; fZ[i] = fClusters[i]->GetZ(); AliITSdetector &det=GetDetector(fClusters[i]->GetDetectorIndex()); Double_t y=fR*det.GetPhi() + fClusters[i]->GetY(); if (y>2.*fR*TMath::Pi()) y -= 2.*fR*TMath::Pi(); fY[i] = y; } delete[] index; delete[] z; delete[] clusters; // fYB[0]=10000000; fYB[1]=-10000000; for (Int_t i=0;i<fN;i++){ if (fY[i]<fYB[0]) fYB[0]=fY[i]; if (fY[i]>fYB[1]) fYB[1]=fY[i]; fClusterIndex[i] = i; } // // fill slices fDy5 = (fYB[1]-fYB[0])/5.; fDy10 = (fYB[1]-fYB[0])/10.; fDy20 = (fYB[1]-fYB[0])/20.; for (Int_t i=0;i<6;i++) fN5[i] =0; for (Int_t i=0;i<11;i++) fN10[i]=0; for (Int_t i=0;i<21;i++) fN20[i]=0; // for (Int_t i=0;i<6;i++) {fBy5[i][0] = fYB[0]+(i-0.75)*fDy5; fBy5[i][1] = fYB[0]+(i+0.75)*fDy5;} for (Int_t i=0;i<11;i++) {fBy10[i][0] = fYB[0]+(i-0.75)*fDy10; fBy10[i][1] = fYB[0]+(i+0.75)*fDy10;} for (Int_t i=0;i<21;i++) {fBy20[i][0] = fYB[0]+(i-0.75)*fDy20; fBy20[i][1] = fYB[0]+(i+0.75)*fDy20;} // // for (Int_t i=0;i<fN;i++) for (Int_t irot=-1;irot<=1;irot++){ Float_t curY = fY[i]+irot*TMath::TwoPi()*fR; // slice 5 for (Int_t slice=0; slice<6;slice++){ if (fBy5[slice][0]<curY && curY<fBy5[slice][1]&&fN5[slice]<kMaxClusterPerLayer5){ fClusters5[slice][fN5[slice]] = fClusters[i]; fY5[slice][fN5[slice]] = curY; fZ5[slice][fN5[slice]] = fZ[i]; fClusterIndex5[slice][fN5[slice]]=i; fN5[slice]++; } } // slice 10 for (Int_t slice=0; slice<11;slice++){ if (fBy10[slice][0]<curY && curY<fBy10[slice][1]&&fN10[slice]<kMaxClusterPerLayer10){ fClusters10[slice][fN10[slice]] = fClusters[i]; fY10[slice][fN10[slice]] = curY; fZ10[slice][fN10[slice]] = fZ[i]; fClusterIndex10[slice][fN10[slice]]=i; fN10[slice]++; } } // slice 20 for (Int_t slice=0; slice<21;slice++){ if (fBy20[slice][0]<curY && curY<fBy20[slice][1]&&fN20[slice]<kMaxClusterPerLayer20){ fClusters20[slice][fN20[slice]] = fClusters[i]; fY20[slice][fN20[slice]] = curY; fZ20[slice][fN20[slice]] = fZ[i]; fClusterIndex20[slice][fN20[slice]]=i; fN20[slice]++; } } } // // consistency check // for (Int_t i=0;i<fN-1;i++){ if (fZ[i]>fZ[i+1]){ printf("Bugg\n"); } } // for (Int_t slice=0;slice<21;slice++) for (Int_t i=0;i<fN20[slice]-1;i++){ if (fZ20[slice][i]>fZ20[slice][i+1]){ printf("Bugg\n"); } } } Int_t AliITStrackerMI::AliITSlayer::FindClusterIndex(Float_t z) const { //-------------------------------------------------------------------- // This function returns the index of the nearest cluster //-------------------------------------------------------------------- Int_t ncl=0; const Float_t *zcl; if (fCurrentSlice<0) { ncl = fN; zcl = fZ; } else{ ncl = fNcs; zcl = fZcs;; } if (ncl==0) return 0; Int_t b=0, e=ncl-1, m=(b+e)/2; for (; b<e; m=(b+e)/2) { // if (z > fClusters[m]->GetZ()) b=m+1; if (z > zcl[m]) b=m+1; else e=m; } return m; } void AliITStrackerMI::AliITSlayer:: SelectClusters(Double_t zmin,Double_t zmax,Double_t ymin, Double_t ymax) { //-------------------------------------------------------------------- // This function sets the "window" //-------------------------------------------------------------------- Double_t circle=2*TMath::Pi()*fR; fYmin = ymin; fYmax =ymax; Float_t ymiddle = (fYmin+fYmax)*0.5; if (ymiddle<fYB[0]) {fYmin+=circle; fYmax+=circle;ymiddle+=circle;} else{ if (ymiddle>fYB[1]) {fYmin-=circle; fYmax-=circle;ymiddle-=circle;} } // fCurrentSlice =-1; // defualt take all fClustersCs = fClusters; fClusterIndexCs = fClusterIndex; fYcs = fY; fZcs = fZ; fNcs = fN; // //is in 20 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy20){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy20); if (slice<0) slice=0; if (slice>20) slice=20; Bool_t isOK = (fYmin>fBy20[slice][0]&&fYmax<fBy20[slice][1]); if (isOK) { fCurrentSlice=slice; fClustersCs = fClusters20[fCurrentSlice]; fClusterIndexCs = fClusterIndex20[fCurrentSlice]; fYcs = fY20[fCurrentSlice]; fZcs = fZ20[fCurrentSlice]; fNcs = fN20[fCurrentSlice]; } } // //is in 10 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy10){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy10); if (slice<0) slice=0; if (slice>10) slice=10; Bool_t isOK = (fYmin>fBy10[slice][0]&&fYmax<fBy10[slice][1]); if (isOK) { fCurrentSlice=slice; fClustersCs = fClusters10[fCurrentSlice]; fClusterIndexCs = fClusterIndex10[fCurrentSlice]; fYcs = fY10[fCurrentSlice]; fZcs = fZ10[fCurrentSlice]; fNcs = fN10[fCurrentSlice]; } } // //is in 5 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy5){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy5); if (slice<0) slice=0; if (slice>5) slice=5; Bool_t isOK = (fYmin>fBy5[slice][0]&&fYmax<fBy5[slice][1]); if ( isOK){ fCurrentSlice=slice; fClustersCs = fClusters5[fCurrentSlice]; fClusterIndexCs = fClusterIndex5[fCurrentSlice]; fYcs = fY5[fCurrentSlice]; fZcs = fZ5[fCurrentSlice]; fNcs = fN5[fCurrentSlice]; } } // fI=FindClusterIndex(zmin); fZmax=zmax; fImax = TMath::Min(FindClusterIndex(zmax)+1,fNcs); fSkip = 0; fAccepted =0; } Int_t AliITStrackerMI::AliITSlayer:: FindDetectorIndex(Double_t phi, Double_t z) const { //-------------------------------------------------------------------- //This function finds the detector crossed by the track //-------------------------------------------------------------------- Double_t dphi=-(phi-fPhiOffset); if (dphi < 0) dphi += 2*TMath::Pi(); else if (dphi >= 2*TMath::Pi()) dphi -= 2*TMath::Pi(); Int_t np=Int_t(dphi*fNladders*0.5/TMath::Pi()+0.5); if (np>=fNladders) np-=fNladders; if (np<0) np+=fNladders; Double_t dz=fZOffset-z; Int_t nz=Int_t(dz*(fNdetectors-1)*0.5/fZOffset+0.5); if (nz>=fNdetectors) return -1; if (nz<0) return -1; return np*fNdetectors + nz; } const AliITSclusterV2 *AliITStrackerMI::AliITSlayer::GetNextCluster(Int_t &ci){ //-------------------------------------------------------------------- // This function returns clusters within the "window" //-------------------------------------------------------------------- if (fCurrentSlice<0){ Double_t rpi2 = 2.*fR*TMath::Pi(); for (Int_t i=fI; i<fImax; i++) { Double_t y = fY[i]; if (fYmax<y) y -= rpi2; if (fYmin>y) y += rpi2; if (y<fYmin) continue; if (y>fYmax) continue; if (fClusters[i]->GetQ()==0&&fSkip==2) continue; ci=i; fI=i+1; return fClusters[i]; } } else{ for (Int_t i=fI; i<fImax; i++) { if (fYcs[i]<fYmin) continue; if (fYcs[i]>fYmax) continue; if (fClustersCs[i]->GetQ()==0&&fSkip==2) continue; ci=fClusterIndexCs[i]; fI=i+1; return fClustersCs[i]; } } return 0; } Double_t AliITStrackerMI::AliITSlayer::GetThickness(Double_t y,Double_t z,Double_t &x0) const { //-------------------------------------------------------------------- //This function returns the layer thickness at this point (units X0) //-------------------------------------------------------------------- Double_t d=0.0085; x0=21.82; if (43<fR&&fR<45) { //SSD2 Double_t dd=0.0034; d=dd; if (TMath::Abs(y-0.00)>3.40) d+=dd; if (TMath::Abs(y-1.90)<0.45) {d+=(0.013-0.0034);} if (TMath::Abs(y+1.90)<0.45) {d+=(0.013-0.0034);} for (Int_t i=0; i<12; i++) { if (TMath::Abs(z-3.9*(i+0.5))<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=0.0034; break; } if (TMath::Abs(z+3.9*(i+0.5))<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=0.0034; break; } if (TMath::Abs(z-3.4-3.9*i)<0.50) {d+=(0.016-0.0034); break;} if (TMath::Abs(z+0.5+3.9*i)<0.50) {d+=(0.016-0.0034); break;} } } else if (37<fR&&fR<41) { //SSD1 Double_t dd=0.0034; d=dd; if (TMath::Abs(y-0.00)>3.40) d+=dd; if (TMath::Abs(y-1.90)<0.45) {d+=(0.013-0.0034);} if (TMath::Abs(y+1.90)<0.45) {d+=(0.013-0.0034);} for (Int_t i=0; i<11; i++) { if (TMath::Abs(z-3.9*i)<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=dd; break; } if (TMath::Abs(z+3.9*i)<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=dd; break; } if (TMath::Abs(z-1.85-3.9*i)<0.50) {d+=(0.016-0.0034); break;} if (TMath::Abs(z+2.05+3.9*i)<0.50) {d+=(0.016-0.0034); break;} } } else if (13<fR&&fR<26) { //SDD Double_t dd=0.0033; d=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; if (TMath::Abs(y-1.80)<0.55) { d+=0.016; for (Int_t j=0; j<20; j++) { if (TMath::Abs(z+0.7+1.47*j)<0.12) {d+=0.08; x0=9.; break;} if (TMath::Abs(z-0.7-1.47*j)<0.12) {d+=0.08; x0=9.; break;} } } if (TMath::Abs(y+1.80)<0.55) { d+=0.016; for (Int_t j=0; j<20; j++) { if (TMath::Abs(z-0.7-1.47*j)<0.12) {d+=0.08; x0=9.; break;} if (TMath::Abs(z+0.7+1.47*j)<0.12) {d+=0.08; x0=9.; break;} } } for (Int_t i=0; i<4; i++) { if (TMath::Abs(z-7.3*i)<0.60) { d+=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; break; } if (TMath::Abs(z+7.3*i)<0.60) { d+=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; break; } } } else if (6<fR&&fR<8) { //SPD2 Double_t dd=0.0063; x0=21.5; d=dd; if (TMath::Abs(y-3.08)>0.5) d+=dd; //if (TMath::Abs(y-3.08)>0.45) d+=dd; if (TMath::Abs(y-3.03)<0.10) {d+=0.014;} } else if (3<fR&&fR<5) { //SPD1 Double_t dd=0.0063; x0=21.5; d=dd; if (TMath::Abs(y+0.21)>0.6) d+=dd; //if (TMath::Abs(y+0.21)>0.45) d+=dd; if (TMath::Abs(y+0.10)<0.10) {d+=0.014;} } return d; } Double_t AliITStrackerMI::GetEffectiveThickness(Double_t y,Double_t z) const { //-------------------------------------------------------------------- //Returns the thickness between the current layer and the vertex (units X0) //-------------------------------------------------------------------- Double_t d=0.0028*3*3; //beam pipe Double_t x0=0; Double_t xn=fgLayers[fI].GetR(); for (Int_t i=0; i<fI; i++) { Double_t xi=fgLayers[i].GetR(); d+=fgLayers[i].GetThickness(y,z,x0)*xi*xi; } if (fI>1) { Double_t xi=9.; d+=0.0097*xi*xi; } if (fI>3) { Double_t xi=0.5*(fgLayers[3].GetR()+fgLayers[4].GetR()); d+=0.0034*xi*xi; } return d/(xn*xn); } Int_t AliITStrackerMI::AliITSlayer::InRoad() const { //-------------------------------------------------------------------- // This function returns number of clusters within the "window" //-------------------------------------------------------------------- Int_t ncl=0; for (Int_t i=fI; i<fN; i++) { const AliITSclusterV2 *c=fClusters[i]; if (c->GetZ() > fZmax) break; if (c->IsUsed()) continue; const AliITSdetector &det=GetDetector(c->GetDetectorIndex()); Double_t y=fR*det.GetPhi() + c->GetY(); if (y>2.*fR*TMath::Pi()) y -= 2*fR*TMath::Pi(); if (y>1.*fR*TMath::Pi() && fYmax<y) y -= 2*fR*TMath::Pi(); if (y<fYmin) continue; if (y>fYmax) continue; ncl++; } return ncl; } Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *t,const AliITStrackMI *c) { //-------------------------------------------------------------------- // This function refits the track "t" at the position "x" using // the clusters from "c" //-------------------------------------------------------------------- Int_t index[kMaxLayer]; Int_t k; for (k=0; k<kMaxLayer; k++) index[k]=-1; Int_t nc=c->GetNumberOfClusters(); for (k=0; k<nc; k++) { Int_t idx=c->GetClusterIndex(k),nl=(idx&0xf0000000)>>28; index[nl]=idx; } Int_t from, to, step; if (xx > t->GetX()) { from=0; to=kMaxLayer; step=+1; } else { from=kMaxLayer-1; to=-1; step=-1; } for (Int_t i=from; i != to; i += step) { AliITSlayer &layer=fgLayers[i]; Double_t r=layer.GetR(); { Double_t hI=i-0.5*step; if (TMath::Abs(hI-1.5)<0.01 || TMath::Abs(hI-3.5)<0.01) { Double_t rs=0.5*(fgLayers[i-step].GetR() + r); Double_t d=0.0034, x0=38.6; if (TMath::Abs(hI-1.5)<0.01) {rs=9.; d=0.0097; x0=42;} if (!t->PropagateTo(rs,-step*d,x0)) { return kFALSE; } } } // remember old position [SR, GSI 18.02.2003] Double_t oldX=0., oldY=0., oldZ=0.; if (t->IsStartedTimeIntegral() && step==1) { t->GetGlobalXYZat(t->GetX(),oldX,oldY,oldZ); } // Double_t x,y,z; if (!t->GetGlobalXYZat(r,x,y,z)) { return kFALSE; } Double_t phi=TMath::ATan2(y,x); Int_t idet=layer.FindDetectorIndex(phi,z); if (idet<0) { return kFALSE; } const AliITSdetector &det=layer.GetDetector(idet); phi=det.GetPhi(); if (!t->Propagate(phi,det.GetR())) { return kFALSE; } t->SetDetectorIndex(idet); const AliITSclusterV2 *cl=0; Double_t maxchi2=1000.*kMaxChi2; Int_t idx=index[i]; if (idx>0) { const AliITSclusterV2 *c=(AliITSclusterV2 *)GetCluster(idx); if (c){ if (idet != c->GetDetectorIndex()) { idet=c->GetDetectorIndex(); const AliITSdetector &det=layer.GetDetector(idet); if (!t->Propagate(det.GetPhi(),det.GetR())) { return kFALSE; } t->SetDetectorIndex(idet); } //Double_t chi2=t->GetPredictedChi2(c); Int_t layer = (idx & 0xf0000000) >> 28;; Double_t chi2=GetPredictedChi2MI(t,c,layer); if (chi2<maxchi2) { cl=c; maxchi2=chi2; } else { return kFALSE; } } } /* if (cl==0) if (t->GetNumberOfClusters()>2) { Double_t dz=4*TMath::Sqrt(t->GetSigmaZ2()+kSigmaZ2[i]); Double_t dy=4*TMath::Sqrt(t->GetSigmaY2()+kSigmaY2[i]); Double_t zmin=t->GetZ() - dz; Double_t zmax=t->GetZ() + dz; Double_t ymin=t->GetY() + phi*r - dy; Double_t ymax=t->GetY() + phi*r + dy; layer.SelectClusters(zmin,zmax,ymin,ymax); const AliITSclusterV2 *c=0; Int_t ci=-1; while ((c=layer.GetNextCluster(ci))!=0) { if (idet != c->GetDetectorIndex()) continue; Double_t chi2=t->GetPredictedChi2(c); if (chi2<maxchi2) { cl=c; maxchi2=chi2; idx=ci; } } } */ if (cl) { //if (!t->Update(cl,maxchi2,idx)) { if (!UpdateMI(t,cl,maxchi2,idx)) { return kFALSE; } t->SetSampledEdx(cl->GetQ(),t->GetNumberOfClusters()-1); } { Double_t x0; Double_t d=layer.GetThickness(t->GetY(),t->GetZ(),x0); t->CorrectForMaterial(-step*d,x0); } // track time update [SR, GSI 17.02.2003] if (t->IsStartedTimeIntegral() && step==1) { Double_t newX, newY, newZ; t->GetGlobalXYZat(t->GetX(),newX,newY,newZ); Double_t dL2 = (oldX-newX)*(oldX-newX) + (oldY-newY)*(oldY-newY) + (oldZ-newZ)*(oldZ-newZ); t->AddTimeStep(TMath::Sqrt(dL2)); } // } if (!t->PropagateTo(xx,0.,0.)) return kFALSE; return kTRUE; } Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *t,const Int_t *clindex) { //-------------------------------------------------------------------- // This function refits the track "t" at the position "x" using // the clusters from array //-------------------------------------------------------------------- Int_t index[kMaxLayer]; Int_t k; for (k=0; k<kMaxLayer; k++) index[k]=-1; // for (k=0; k<kMaxLayer; k++) { index[k]=clindex[k]; } Int_t from, to, step; if (xx > t->GetX()) { from=0; to=kMaxLayer; step=+1; } else { from=kMaxLayer-1; to=-1; step=-1; } for (Int_t i=from; i != to; i += step) { AliITSlayer &layer=fgLayers[i]; Double_t r=layer.GetR(); if (step<0 && xx>r) break; // { Double_t hI=i-0.5*step; if (TMath::Abs(hI-1.5)<0.01 || TMath::Abs(hI-3.5)<0.01) { Double_t rs=0.5*(fgLayers[i-step].GetR() + r); Double_t d=0.0034, x0=38.6; if (TMath::Abs(hI-1.5)<0.01) {rs=9.; d=0.0097; x0=42;} if (!t->PropagateTo(rs,-step*d,x0)) { return kFALSE; } } } // remember old position [SR, GSI 18.02.2003] Double_t oldX=0., oldY=0., oldZ=0.; if (t->IsStartedTimeIntegral() && step==1) { t->GetGlobalXYZat(t->GetX(),oldX,oldY,oldZ); } // Double_t x,y,z; if (!t->GetGlobalXYZat(r,x,y,z)) { return kFALSE; } Double_t phi=TMath::ATan2(y,x); Int_t idet=layer.FindDetectorIndex(phi,z); if (idet<0) { return kFALSE; } const AliITSdetector &det=layer.GetDetector(idet); phi=det.GetPhi(); if (!t->Propagate(phi,det.GetR())) { return kFALSE; } t->SetDetectorIndex(idet); const AliITSclusterV2 *cl=0; Double_t maxchi2=1000.*kMaxChi2; Int_t idx=index[i]; if (idx>0) { const AliITSclusterV2 *c=(AliITSclusterV2 *)GetCluster(idx); if (c){ if (idet != c->GetDetectorIndex()) { idet=c->GetDetectorIndex(); const AliITSdetector &det=layer.GetDetector(idet); if (!t->Propagate(det.GetPhi(),det.GetR())) { return kFALSE; } t->SetDetectorIndex(idet); } //Double_t chi2=t->GetPredictedChi2(c); Int_t layer = (idx & 0xf0000000) >> 28;; Double_t chi2=GetPredictedChi2MI(t,c,layer); if (chi2<maxchi2) { cl=c; maxchi2=chi2; } else { return kFALSE; } } } /* if (cl==0) if (t->GetNumberOfClusters()>2) { Double_t dz=4*TMath::Sqrt(t->GetSigmaZ2()+kSigmaZ2[i]); Double_t dy=4*TMath::Sqrt(t->GetSigmaY2()+kSigmaY2[i]); Double_t zmin=t->GetZ() - dz; Double_t zmax=t->GetZ() + dz; Double_t ymin=t->GetY() + phi*r - dy; Double_t ymax=t->GetY() + phi*r + dy; layer.SelectClusters(zmin,zmax,ymin,ymax); const AliITSclusterV2 *c=0; Int_t ci=-1; while ((c=layer.GetNextCluster(ci))!=0) { if (idet != c->GetDetectorIndex()) continue; Double_t chi2=t->GetPredictedChi2(c); if (chi2<maxchi2) { cl=c; maxchi2=chi2; idx=ci; } } } */ if (cl) { //if (!t->Update(cl,maxchi2,idx)) { if (!UpdateMI(t,cl,maxchi2,idx)) { return kFALSE; } t->SetSampledEdx(cl->GetQ(),t->GetNumberOfClusters()-1); } { Double_t x0; Double_t d=layer.GetThickness(t->GetY(),t->GetZ(),x0); t->CorrectForMaterial(-step*d,x0); } // track time update [SR, GSI 17.02.2003] if (t->IsStartedTimeIntegral() && step==1) { Double_t newX, newY, newZ; t->GetGlobalXYZat(t->GetX(),newX,newY,newZ); Double_t dL2 = (oldX-newX)*(oldX-newX) + (oldY-newY)*(oldY-newY) + (oldZ-newZ)*(oldZ-newZ); t->AddTimeStep(TMath::Sqrt(dL2)); } // } if (!t->PropagateTo(xx,0.,0.)) return kFALSE; return kTRUE; } Double_t AliITStrackerMI::GetNormalizedChi2(AliITStrackMI * track, Int_t mode) { // // calculate normalized chi2 // return NormalizedChi2(track,0); Float_t chi2 = 0; Float_t sum=0; Float_t *erry = GetErrY(fCurrentEsdTrack), *errz = GetErrZ(fCurrentEsdTrack); // track->fdEdxMismatch=0; Float_t dedxmismatch =0; Float_t *ny = GetNy(fCurrentEsdTrack), *nz = GetNz(fCurrentEsdTrack); if (mode<100){ for (Int_t i = 0;i<6;i++){ if (track->fClIndex[i]>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->fSigmaY[i]; cerrz = track->fSigmaZ[i];} cerry*=cerry; cerrz*=cerrz; Float_t cchi2 = (track->fDy[i]*track->fDy[i]/cerry)+(track->fDz[i]*track->fDz[i]/cerrz); if (i>1){ Float_t ratio = track->fNormQ[i]/track->fExpQ; if (ratio<0.5) { cchi2+=(0.5-ratio)*10.; //track->fdEdxMismatch+=(0.5-ratio)*10.; dedxmismatch+=(0.5-ratio)*10.; } } if (i<2 ||i>3){ AliITSclusterV2 * cl = (AliITSclusterV2*)GetCluster( track->fClIndex[i]); Double_t delta = cl->GetNy()+cl->GetNz()-ny[i]-nz[i]; if (delta>1) chi2 +=0.5*TMath::Min(delta/2,2.); if (i<2) chi2+=2*cl->GetDeltaProbability(); } chi2+=cchi2; sum++; } } if (TMath::Abs(track->fdEdxMismatch-dedxmismatch)>0.0001){ track->fdEdxMismatch = dedxmismatch; } } else{ for (Int_t i = 0;i<4;i++){ if (track->fClIndex[i]>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->fSigmaY[i]; cerrz = track->fSigmaZ[i];} cerry*=cerry; cerrz*=cerrz; chi2+= (track->fDy[i]*track->fDy[i]/cerry); chi2+= (track->fDz[i]*track->fDz[i]/cerrz); sum++; } } for (Int_t i = 4;i<6;i++){ if (track->fClIndex[i]>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->fSigmaY[i]; cerrz = track->fSigmaZ[i];} cerry*=cerry; cerrz*=cerrz; Float_t cerryb, cerrzb; if (ny[i+6]>0) {cerryb = erry[i+6]; cerrzb=errz[i+6];} else { cerryb= track->fSigmaY[i+6]; cerrzb = track->fSigmaZ[i+6];} cerryb*=cerryb; cerrzb*=cerrzb; chi2+= TMath::Min((track->fDy[i+6]*track->fDy[i+6]/cerryb),track->fDy[i]*track->fDy[i]/cerry); chi2+= TMath::Min((track->fDz[i+6]*track->fDz[i+6]/cerrzb),track->fDz[i]*track->fDz[i]/cerrz); sum++; } } } if (track->fESDtrack->GetTPCsignal()>85){ Float_t ratio = track->fdEdx/track->fESDtrack->GetTPCsignal(); if (ratio<0.5) { chi2+=(0.5-ratio)*5.; } if (ratio>2){ chi2+=(ratio-2.0)*3; } } // Double_t match = TMath::Sqrt(track->fChi22); if (track->fConstrain) match/=track->GetNumberOfClusters(); if (!track->fConstrain) match/=track->GetNumberOfClusters()-2.; if (match<0) match=0; Float_t deadzonefactor = (track->fNDeadZone>0) ? 3*(1.1-track->fDeadZoneProbability):0.; Double_t normchi2 = 2*track->fNSkipped+match+deadzonefactor+(1+(2*track->fNSkipped+deadzonefactor)/track->GetNumberOfClusters())* (chi2)/TMath::Max(double(sum-track->fNSkipped), 1./(1.+track->fNSkipped)); return normchi2; } Double_t AliITStrackerMI::GetMatchingChi2(AliITStrackMI * track1, AliITStrackMI * track2) { // // return matching chi2 between two tracks AliITStrackMI track3(*track2); track3.Propagate(track1->GetAlpha(),track1->GetX()); TMatrixD vec(5,1); vec(0,0)=track1->fP0-track3.fP0; vec(1,0)=track1->fP1-track3.fP1; vec(2,0)=track1->fP2-track3.fP2; vec(3,0)=track1->fP3-track3.fP3; vec(4,0)=track1->fP4-track3.fP4; // TMatrixD cov(5,5); cov(0,0) = track1->fC00+track3.fC00; cov(1,1) = track1->fC11+track3.fC11; cov(2,2) = track1->fC22+track3.fC22; cov(3,3) = track1->fC33+track3.fC33; cov(4,4) = track1->fC44+track3.fC44; cov(0,1)=cov(1,0) = track1->fC10+track3.fC10; cov(0,2)=cov(2,0) = track1->fC20+track3.fC20; cov(0,3)=cov(3,0) = track1->fC30+track3.fC30; cov(0,4)=cov(4,0) = track1->fC40+track3.fC40; // cov(1,2)=cov(2,1) = track1->fC21+track3.fC21; cov(1,3)=cov(3,1) = track1->fC31+track3.fC31; cov(1,4)=cov(4,1) = track1->fC41+track3.fC41; // cov(2,3)=cov(3,2) = track1->fC32+track3.fC32; cov(2,4)=cov(4,2) = track1->fC42+track3.fC42; // cov(3,4)=cov(4,3) = track1->fC43+track3.fC43; cov.Invert(); TMatrixD vec2(cov,TMatrixD::kMult,vec); TMatrixD chi2(vec2,TMatrixD::kTransposeMult,vec); return chi2(0,0); } Double_t AliITStrackerMI::GetDeadZoneProbability(Double_t zpos, Double_t zerr) { // // return probability that given point - characterized by z position and error is in dead zone // Double_t probability =0; Double_t absz = TMath::Abs(zpos); Double_t nearestz = (absz<2)? 0.:7.1; if (TMath::Abs(absz-nearestz)>0.25+3*zerr) return 0; Double_t zmin=0, zmax=0; if (zpos<-6.){ zmin = -7.25; zmax = -6.95; } if (zpos>6){ zmin = 7.0; zmax =7.3; } if (absz<2){ zmin = -0.75; zmax = 1.5; } probability = (TMath::Erf((zpos-zmin)/zerr) - TMath::Erf((zpos-zmax)/zerr))*0.5; return probability; } Double_t AliITStrackerMI::GetTruncatedChi2(AliITStrackMI * track, Float_t fac) { // // calculate normalized chi2 Float_t chi2[6]; Float_t *erry = GetErrY(fCurrentEsdTrack), *errz = GetErrZ(fCurrentEsdTrack); Float_t ncl = 0; for (Int_t i = 0;i<6;i++){ if (TMath::Abs(track->fDy[i])>0){ chi2[i]= (track->fDy[i]/erry[i])*(track->fDy[i]/erry[i]); chi2[i]+= (track->fDz[i]/errz[i])*(track->fDz[i]/errz[i]); ncl++; } else{chi2[i]=10000;} } Int_t index[6]; TMath::Sort(6,chi2,index,kFALSE); Float_t max = float(ncl)*fac-1.; Float_t sumchi=0, sumweight=0; for (Int_t i=0;i<max+1;i++){ Float_t weight = (i<max)?1.:(max+1.-i); sumchi+=weight*chi2[index[i]]; sumweight+=weight; } Double_t normchi2 = sumchi/sumweight; return normchi2; } Double_t AliITStrackerMI::GetInterpolatedChi2(AliITStrackMI * forwardtrack, AliITStrackMI * backtrack) { // // calculate normalized chi2 // if (forwardtrack->fNUsed>0.3*float(forwardtrack->GetNumberOfClusters())) return 10000; Int_t npoints = 0; Double_t res =0; for (Int_t i=0;i<6;i++){ if ( (backtrack->fSigmaY[i]<0.000000001) || (forwardtrack->fSigmaY[i]<0.000000001)) continue; Double_t sy1 = forwardtrack->fSigmaY[i]; Double_t sz1 = forwardtrack->fSigmaZ[i]; Double_t sy2 = backtrack->fSigmaY[i]; Double_t sz2 = backtrack->fSigmaZ[i]; if (i<2){ sy2=1000.;sz2=1000;} // Double_t dy0 = (forwardtrack->fDy[i]/(sy1*sy1) +backtrack->fDy[i]/(sy2*sy2))/(1./(sy1*sy1)+1./(sy2*sy2)); Double_t dz0 = (forwardtrack->fDz[i]/(sz1*sz1) +backtrack->fDz[i]/(sz2*sz2))/(1./(sz1*sz1)+1./(sz2*sz2)); // Double_t nz0 = dz0*TMath::Sqrt((1./(sz1*sz1)+1./(sz2*sz2))); Double_t ny0 = dy0*TMath::Sqrt((1./(sy1*sy1)+1./(sy2*sy2))); // res+= nz0*nz0+ny0*ny0; npoints++; } if (npoints>1) return TMath::Max(TMath::Abs(0.3*forwardtrack->Get1Pt())-0.5,0.)+ //2*forwardtrack->fNUsed+ res/TMath::Max(double(npoints-forwardtrack->fNSkipped), 1./(1.+forwardtrack->fNSkipped)); return 1000; } Float_t *AliITStrackerMI::GetWeight(Int_t index) { //-------------------------------------------------------------------- // Return pointer to a given cluster //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; return fgLayers[l].GetWeight(c); } void AliITStrackerMI::RegisterClusterTracks(AliITStrackMI* track,Int_t id) { //--------------------------------------------- // register track to the list // if (track->fESDtrack->GetKinkIndex(0)!=0) return; //don't register kink tracks // // for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].fN) continue; for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].fClusterTracks[itrack][c]<0){ fgLayers[l].fClusterTracks[itrack][c]=id; break; } } } } void AliITStrackerMI::UnRegisterClusterTracks(AliITStrackMI* track, Int_t id) { //--------------------------------------------- // unregister track from the list for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].fN) continue; for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].fClusterTracks[itrack][c]==id){ fgLayers[l].fClusterTracks[itrack][c]=-1; } } } } Float_t AliITStrackerMI::GetNumberOfSharedClusters(AliITStrackMI* track,Int_t id, Int_t list[6], AliITSclusterV2 *clist[6]) { //------------------------------------------------------------- //get number of shared clusters //------------------------------------------------------------- Float_t shared=0; for (Int_t i=0;i<6;i++) { list[i]=-1, clist[i]=0;} // mean number of clusters Float_t *ny = GetNy(id), *nz = GetNz(id); for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].fN) continue; if (ny[l]==0){ printf("problem\n"); } AliITSclusterV2 *cl = (AliITSclusterV2*)GetCluster(index); Float_t weight=1; // Float_t deltan = 0; if (l>3&&cl->GetNy()+cl->GetNz()>6) continue; if (l>2&&track->fNormQ[l]/track->fExpQ>3.5) continue; if (l<2 || l>3){ deltan = (cl->GetNy()+cl->GetNz()-ny[l]-nz[l]); } else{ deltan = (cl->GetNz()-nz[l]); } if (deltan>2.0) continue; // extended - highly probable shared cluster weight = 2./TMath::Max(3.+deltan,2.); // for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].fClusterTracks[itrack][c]>=0 && fgLayers[l].fClusterTracks[itrack][c]!=id){ list[l]=index; clist[l] = (AliITSclusterV2*)GetCluster(index); shared+=weight; break; } } } track->fNUsed=shared; return shared; } Int_t AliITStrackerMI::GetOverlapTrack(AliITStrackMI *track, Int_t trackID, Int_t &shared, Int_t clusterlist[6],Int_t overlist[6]) { // // find first shared track // // mean number of clusters Float_t *ny = GetNy(trackID), *nz = GetNz(trackID); // for (Int_t i=0;i<6;i++) overlist[i]=-1; Int_t sharedtrack=100000; Int_t tracks[24],trackindex=0; for (Int_t i=0;i<24;i++) {tracks[i]=-1;} // for (Int_t icluster=0;icluster<6;icluster++){ if (clusterlist[icluster]<0) continue; Int_t index = clusterlist[icluster]; Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (ny[l]==0){ printf("problem\n"); } if (c>fgLayers[l].fN) continue; //if (l>3) continue; AliITSclusterV2 *cl = (AliITSclusterV2*)GetCluster(index); // Float_t deltan = 0; if (l>3&&cl->GetNy()+cl->GetNz()>6) continue; if (l>2&&track->fNormQ[l]/track->fExpQ>3.5) continue; if (l<2 || l>3){ deltan = (cl->GetNy()+cl->GetNz()-ny[l]-nz[l]); } else{ deltan = (cl->GetNz()-nz[l]); } if (deltan>2.0) continue; // extended - highly probable shared cluster // for (Int_t itrack=3;itrack>=0;itrack--){ if (fgLayers[l].fClusterTracks[itrack][c]<0) continue; if (fgLayers[l].fClusterTracks[itrack][c]!=trackID){ tracks[trackindex] = fgLayers[l].fClusterTracks[itrack][c]; trackindex++; } } } if (trackindex==0) return -1; if (trackindex==1){ sharedtrack = tracks[0]; }else{ if (trackindex==2) sharedtrack =TMath::Min(tracks[0],tracks[1]); else{ // Int_t track[24], cluster[24]; for (Int_t i=0;i<trackindex;i++){ track[i]=-1; cluster[i]=0;} Int_t index =0; // for (Int_t i=0;i<trackindex;i++){ if (tracks[i]<0) continue; track[index] = tracks[i]; cluster[index]++; for (Int_t j=i+1;j<trackindex;j++){ if (tracks[j]<0) continue; if (tracks[j]==tracks[i]){ cluster[index]++; tracks[j]=-1; } } index++; } Int_t max=0; for (Int_t i=0;i<index;i++){ if (cluster[index]>max) { sharedtrack=track[index]; max=cluster[index]; } } } } if (sharedtrack>=100000) return -1; // // make list of overlaps shared =0; for (Int_t icluster=0;icluster<6;icluster++){ if (clusterlist[icluster]<0) continue; Int_t index = clusterlist[icluster]; Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].fN) continue; AliITSclusterV2 *cl = (AliITSclusterV2*)GetCluster(index); if (l==0 || l==1){ if (cl->GetNy()>2) continue; if (cl->GetNz()>2) continue; } if (l==4 || l==5){ if (cl->GetNy()>3) continue; if (cl->GetNz()>3) continue; } // for (Int_t itrack=3;itrack>=0;itrack--){ if (fgLayers[l].fClusterTracks[itrack][c]<0) continue; if (fgLayers[l].fClusterTracks[itrack][c]==sharedtrack){ overlist[l]=index; shared++; } } } return sharedtrack; } AliITStrackMI * AliITStrackerMI::GetBest2Tracks(Int_t trackID1, Int_t trackID2, Float_t th0, Float_t th1){ // // try to find track hypothesys without conflicts // with minimal chi2; TClonesArray *arr1 = (TClonesArray*)fTrackHypothesys.At(trackID1); Int_t entries1 = arr1->GetEntriesFast(); TClonesArray *arr2 = (TClonesArray*)fTrackHypothesys.At(trackID2); if (!arr2) return (AliITStrackMI*) arr1->UncheckedAt(0); Int_t entries2 = arr2->GetEntriesFast(); if (entries2<=0) return (AliITStrackMI*) arr1->UncheckedAt(0); // AliITStrackMI * track10=(AliITStrackMI*) arr1->UncheckedAt(0); AliITStrackMI * track20=(AliITStrackMI*) arr2->UncheckedAt(0); if (TMath::Abs(1./track10->Get1Pt())>0.5+TMath::Abs(1/track20->Get1Pt())) return track10; for (Int_t itrack=0;itrack<entries1;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr1->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID1); } // for (Int_t itrack=0;itrack<entries2;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr2->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID2); } Int_t index1=0; Int_t index2=0; Float_t maxconflicts=6; Double_t maxchi2 =1000.; // // get weight of hypothesys - using best hypothesy Double_t w1,w2; Int_t list1[6],list2[6]; AliITSclusterV2 *clist1[6], *clist2[6] ; RegisterClusterTracks(track10,trackID1); RegisterClusterTracks(track20,trackID2); Float_t conflict1 = GetNumberOfSharedClusters(track10,trackID1,list1,clist1); Float_t conflict2 = GetNumberOfSharedClusters(track20,trackID2,list2,clist2); UnRegisterClusterTracks(track10,trackID1); UnRegisterClusterTracks(track20,trackID2); // // normalized chi2 Float_t chi21 =0,chi22=0,ncl1=0,ncl2=0; Float_t nerry[6],nerrz[6]; Float_t *erry1=GetErrY(trackID1),*errz1 = GetErrZ(trackID1); Float_t *erry2=GetErrY(trackID2),*errz2 = GetErrZ(trackID2); for (Int_t i=0;i<6;i++){ if ( (erry1[i]>0) && (erry2[i]>0)) { nerry[i] = TMath::Min(erry1[i],erry2[i]); nerrz[i] = TMath::Min(errz1[i],errz2[i]); }else{ nerry[i] = TMath::Max(erry1[i],erry2[i]); nerrz[i] = TMath::Max(errz1[i],errz2[i]); } if (TMath::Abs(track10->fDy[i])>0.000000000000001){ chi21 += track10->fDy[i]*track10->fDy[i]/(nerry[i]*nerry[i]); chi21 += track10->fDz[i]*track10->fDz[i]/(nerrz[i]*nerrz[i]); ncl1++; } if (TMath::Abs(track20->fDy[i])>0.000000000000001){ chi22 += track20->fDy[i]*track20->fDy[i]/(nerry[i]*nerry[i]); chi22 += track20->fDz[i]*track20->fDz[i]/(nerrz[i]*nerrz[i]); ncl2++; } } chi21/=ncl1; chi22/=ncl2; // // Float_t d1 = TMath::Sqrt(track10->fD[0]*track10->fD[0]+track10->fD[1]*track10->fD[1])+0.1; Float_t d2 = TMath::Sqrt(track20->fD[0]*track20->fD[0]+track20->fD[1]*track20->fD[1])+0.1; Float_t s1 = TMath::Sqrt(track10->GetSigmaY2()*track10->GetSigmaZ2()); Float_t s2 = TMath::Sqrt(track20->GetSigmaY2()*track20->GetSigmaZ2()); // w1 = (d2/(d1+d2)+ 2*s2/(s1+s2)+ +s2/(s1+s2)*0.5*(chi22+2.)/(chi21+chi22+4.) +1.*TMath::Abs(1./track10->Get1Pt())/(TMath::Abs(1./track10->Get1Pt())+TMath::Abs(1./track20->Get1Pt())) ); w2 = (d1/(d1+d2)+ 2*s1/(s1+s2)+ s1/(s1+s2)*0.5*(chi21+2.)/(chi21+chi22+4.) +1.*TMath::Abs(1./track20->Get1Pt())/(TMath::Abs(1./track10->Get1Pt())+TMath::Abs(1./track20->Get1Pt())) ); Double_t sumw = w1+w2; w1/=sumw; w2/=sumw; if (w1<w2*0.5) { w1 = (d2+0.5)/(d1+d2+1.); w2 = (d1+0.5)/(d1+d2+1.); } // Float_t maxmax = w1*track10->fChi2MIP[0]+w2*track20->fChi2MIP[0]+w1*conflict1+w2*conflict2+1.; //Float_t maxconflicts0 = w1*conflict1+w2*conflict2; // // get pair of "best" hypothesys // Float_t * ny1 = GetNy(trackID1), * nz1 = GetNz(trackID1); Float_t * ny2 = GetNy(trackID2), * nz2 = GetNz(trackID2); for (Int_t itrack1=0;itrack1<entries1;itrack1++){ AliITStrackMI * track1=(AliITStrackMI*) arr1->UncheckedAt(itrack1); //if (track1->fFakeRatio>0) continue; RegisterClusterTracks(track1,trackID1); for (Int_t itrack2=0;itrack2<entries2;itrack2++){ AliITStrackMI * track2=(AliITStrackMI*) arr2->UncheckedAt(itrack2); // Float_t current = w1*track1->fChi2MIP[0]+w2*track2->fChi2MIP[0]; //if (track2->fFakeRatio>0) continue; Float_t nskipped=0; RegisterClusterTracks(track2,trackID2); Int_t list1[6],list2[6]; AliITSclusterV2 *clist1[6], *clist2[6] ; Float_t cconflict1 = GetNumberOfSharedClusters(track1,trackID1,list1,clist1); Float_t cconflict2 = GetNumberOfSharedClusters(track2,trackID2,list2,clist2); UnRegisterClusterTracks(track2,trackID2); // if (track1->fConstrain) nskipped+=w1*track1->fNSkipped; if (track2->fConstrain) nskipped+=w2*track2->fNSkipped; if (nskipped>0.5) continue; // //if ( w1*conflict1+w2*conflict2>maxconflicts0) continue; if (conflict1+1<cconflict1) continue; if (conflict2+1<cconflict2) continue; Float_t conflict=0; Float_t sumchi2=0; Float_t sum=0; for (Int_t i=0;i<6;i++){ // Float_t c1 =0.; // conflict coeficients Float_t c2 =0.; if (clist1[i]&&clist2[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist1[i]->GetNy()+clist1[i]->GetNz()-TMath::Max(ny1[i],ny2[i])-TMath::Max(nz1[i],nz2[i])); } else{ deltan = (clist1[i]->GetNz()-TMath::Max(nz1[i],nz2[i])); } c1 = 2./TMath::Max(3.+deltan,2.); c2 = 2./TMath::Max(3.+deltan,2.); } else{ if (clist1[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist1[i]->GetNy()+clist1[i]->GetNz()-ny1[i]-nz1[i]); } else{ deltan = (clist1[i]->GetNz()-nz1[i]); } c1 = 2./TMath::Max(3.+deltan,2.); c2 = 0; } if (clist2[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist2[i]->GetNy()+clist2[i]->GetNz()-ny2[i]-nz2[i]); } else{ deltan = (clist2[i]->GetNz()-nz2[i]); } c2 = 2./TMath::Max(3.+deltan,2.); c1 = 0; } } // Double_t chi21=0,chi22=0; if (TMath::Abs(track1->fDy[i])>0.) { chi21 = (track1->fDy[i]/track1->fSigmaY[i])*(track1->fDy[i]/track1->fSigmaY[i])+ (track1->fDz[i]/track1->fSigmaZ[i])*(track1->fDz[i]/track1->fSigmaZ[i]); //chi21 = (track1->fDy[i]*track1->fDy[i])/(nerry[i]*nerry[i])+ // (track1->fDz[i]*track1->fDz[i])/(nerrz[i]*nerrz[i]); }else{ if (TMath::Abs(track1->fSigmaY[i]>0.)) c1=1; } // if (TMath::Abs(track2->fDy[i])>0.) { chi22 = (track2->fDy[i]/track2->fSigmaY[i])*(track2->fDy[i]/track2->fSigmaY[i])+ (track2->fDz[i]/track2->fSigmaZ[i])*(track2->fDz[i]/track2->fSigmaZ[i]); //chi22 = (track2->fDy[i]*track2->fDy[i])/(nerry[i]*nerry[i])+ // (track2->fDz[i]*track2->fDz[i])/(nerrz[i]*nerrz[i]); } else{ if (TMath::Abs(track2->fSigmaY[i]>0.)) c2=1; } sumchi2+=w1*(1.+c1)*(1+c1)*(chi21+c1)+w2*(1.+c2)*(1+c2)*(chi22+c2); if (chi21>0) sum+=w1; if (chi22>0) sum+=w2; conflict+=(c1+c2); } Double_t norm = sum-w1*track1->fNSkipped-w2*track2->fNSkipped; if (norm<0) norm =1/(w1*track1->fNSkipped+w2*track2->fNSkipped); Double_t normchi2 = 2*conflict+sumchi2/sum; if ( normchi2 <maxchi2 ){ index1 = itrack1; index2 = itrack2; maxconflicts = conflict; maxchi2 = normchi2; } } UnRegisterClusterTracks(track1,trackID1); } // // if (maxconflicts<4 && maxchi2<th0){ if (maxchi2<th0*2.){ Float_t orig = track10->fFakeRatio*track10->GetNumberOfClusters(); AliITStrackMI* track1=(AliITStrackMI*) arr1->UncheckedAt(index1); track1->fChi2MIP[5] = maxconflicts; track1->fChi2MIP[6] = maxchi2; track1->fChi2MIP[7] = 0.01+orig-(track1->fFakeRatio*track1->GetNumberOfClusters()); // track1->UpdateESDtrack(AliESDtrack::kITSin); track1->fChi2MIP[8] = index1; fBestTrackIndex[trackID1] =index1; UpdateESDtrack(track1, AliESDtrack::kITSin); } else if (track10->fChi2MIP[0]<th1){ track10->fChi2MIP[5] = maxconflicts; track10->fChi2MIP[6] = maxchi2; // track10->UpdateESDtrack(AliESDtrack::kITSin); UpdateESDtrack(track10,AliESDtrack::kITSin); } for (Int_t itrack=0;itrack<entries1;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr1->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID1); } // for (Int_t itrack=0;itrack<entries2;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr2->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID2); } if (track10->fConstrain&&track10->fChi2MIP[0]<kMaxChi2PerCluster[0]&&track10->fChi2MIP[1]<kMaxChi2PerCluster[1] &&track10->fChi2MIP[2]<kMaxChi2PerCluster[2]&&track10->fChi2MIP[3]<kMaxChi2PerCluster[3]){ // if (track10->fChi2MIP[0]<kMaxChi2PerCluster[0]&&track10->fChi2MIP[1]<kMaxChi2PerCluster[1] // &&track10->fChi2MIP[2]<kMaxChi2PerCluster[2]&&track10->fChi2MIP[3]<kMaxChi2PerCluster[3]){ RegisterClusterTracks(track10,trackID1); } if (track20->fConstrain&&track20->fChi2MIP[0]<kMaxChi2PerCluster[0]&&track20->fChi2MIP[1]<kMaxChi2PerCluster[1] &&track20->fChi2MIP[2]<kMaxChi2PerCluster[2]&&track20->fChi2MIP[3]<kMaxChi2PerCluster[3]){ //if (track20->fChi2MIP[0]<kMaxChi2PerCluster[0]&&track20->fChi2MIP[1]<kMaxChi2PerCluster[1] // &&track20->fChi2MIP[2]<kMaxChi2PerCluster[2]&&track20->fChi2MIP[3]<kMaxChi2PerCluster[3]){ RegisterClusterTracks(track20,trackID2); } return track10; } void AliITStrackerMI::UseClusters(const AliKalmanTrack *t, Int_t from) const { //-------------------------------------------------------------------- // This function marks clusters assigned to the track //-------------------------------------------------------------------- AliTracker::UseClusters(t,from); AliITSclusterV2 *c=(AliITSclusterV2 *)GetCluster(t->GetClusterIndex(0)); //if (c->GetQ()>2) c->Use(); if (c->GetSigmaZ2()>0.1) c->Use(); c=(AliITSclusterV2 *)GetCluster(t->GetClusterIndex(1)); //if (c->GetQ()>2) c->Use(); if (c->GetSigmaZ2()>0.1) c->Use(); } void AliITStrackerMI::AddTrackHypothesys(AliITStrackMI * track, Int_t esdindex) { //------------------------------------------------------------------ // add track to the list of hypothesys //------------------------------------------------------------------ if (esdindex>=fTrackHypothesys.GetEntriesFast()) fTrackHypothesys.Expand(esdindex*2+10); // TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); if (!array) { array = new TObjArray(10); fTrackHypothesys.AddAt(array,esdindex); } array->AddLast(track); } void AliITStrackerMI::SortTrackHypothesys(Int_t esdindex, Int_t maxcut, Int_t mode) { //------------------------------------------------------------------- // compress array of track hypothesys // keep only maxsize best hypothesys //------------------------------------------------------------------- if (esdindex>fTrackHypothesys.GetEntriesFast()) return; if (! (fTrackHypothesys.At(esdindex)) ) return; TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); Int_t entries = array->GetEntriesFast(); // //- find preliminary besttrack as a reference Float_t minchi2=10000; Int_t maxn=0; AliITStrackMI * besttrack=0; for (Int_t itrack=0;itrack<array->GetEntriesFast();itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (!track) continue; Float_t chi2 = NormalizedChi2(track,0); // Int_t tpcLabel=track->fESDtrack->GetTPCLabel(); track->SetLabel(tpcLabel); CookdEdx(track); track->fFakeRatio=1.; CookLabel(track,0.); //For comparison only // //if (chi2<kMaxChi2PerCluster[0]&&track->fFakeRatio==0){ if (chi2<kMaxChi2PerCluster[0]){ if (track->GetNumberOfClusters()<maxn) continue; maxn = track->GetNumberOfClusters(); if (chi2<minchi2){ minchi2=chi2; besttrack=track; } } else{ if (track->fConstrain || track->fN>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } if (!besttrack) return; // // //take errors of best track as a reference Float_t *erry = GetErrY(esdindex), *errz = GetErrZ(esdindex); Float_t *ny = GetNy(esdindex), *nz = GetNz(esdindex); for (Int_t i=0;i<6;i++) { if (besttrack->fClIndex[i]>0){ erry[i] = besttrack->fSigmaY[i]; erry[i+6] = besttrack->fSigmaY[i+6]; errz[i] = besttrack->fSigmaZ[i]; errz[i+6] = besttrack->fSigmaZ[i+6]; ny[i] = besttrack->fNy[i]; nz[i] = besttrack->fNz[i]; } } // // calculate normalized chi2 // Float_t * chi2 = new Float_t[entries]; Int_t * index = new Int_t[entries]; for (Int_t i=0;i<entries;i++) chi2[i] =10000; for (Int_t itrack=0;itrack<entries;itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (track){ track->fChi2MIP[0] = GetNormalizedChi2(track, mode); if (track->fChi2MIP[0]<kMaxChi2PerCluster[0]) chi2[itrack] = track->fChi2MIP[0]; else{ if (track->fConstrain || track->fN>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } } // TMath::Sort(entries,chi2,index,kFALSE); besttrack = (AliITStrackMI*)array->At(index[0]); if (besttrack&&besttrack->fChi2MIP[0]<kMaxChi2PerCluster[0]){ for (Int_t i=0;i<6;i++){ if (besttrack->fClIndex[i]>0){ erry[i] = besttrack->fSigmaY[i]; erry[i+6] = besttrack->fSigmaY[i+6]; errz[i] = besttrack->fSigmaZ[i]; erry[i+6] = besttrack->fSigmaY[i+6]; ny[i] = besttrack->fNy[i]; nz[i] = besttrack->fNz[i]; } } } // // calculate one more time with updated normalized errors for (Int_t i=0;i<entries;i++) chi2[i] =10000; for (Int_t itrack=0;itrack<entries;itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (track){ track->fChi2MIP[0] = GetNormalizedChi2(track,mode); if (track->fChi2MIP[0]<kMaxChi2PerCluster[0]) chi2[itrack] = track->fChi2MIP[0]-0*(track->GetNumberOfClusters()+track->fNDeadZone); else { if (track->fConstrain || track->fN>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } } entries = array->GetEntriesFast(); // // if (entries>0){ TObjArray * newarray = new TObjArray(); TMath::Sort(entries,chi2,index,kFALSE); besttrack = (AliITStrackMI*)array->At(index[0]); if (besttrack){ // for (Int_t i=0;i<6;i++){ if (besttrack->fNz[i]>0&&besttrack->fNy[i]>0){ erry[i] = besttrack->fSigmaY[i]; erry[i+6] = besttrack->fSigmaY[i+6]; errz[i] = besttrack->fSigmaZ[i]; errz[i+6] = besttrack->fSigmaZ[i+6]; ny[i] = besttrack->fNy[i]; nz[i] = besttrack->fNz[i]; } } besttrack->fChi2MIP[0] = GetNormalizedChi2(besttrack,mode); Float_t minchi2 = TMath::Min(besttrack->fChi2MIP[0]+5.+besttrack->fNUsed, double(kMaxChi2PerCluster[0])); Float_t minn = besttrack->GetNumberOfClusters()-3; Int_t accepted=0; for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(index[i]); if (!track) continue; if (accepted>maxcut) break; track->fChi2MIP[0] = GetNormalizedChi2(track,mode); if (track->fConstrain || track->fN>5){ //keep best short tracks - without vertex constrain if (track->GetNumberOfClusters()<6 && (track->fChi2MIP[0]+track->fNUsed>minchi2)){ delete array->RemoveAt(index[i]); continue; } } Bool_t shortbest = !track->fConstrain && track->fN<6; if ((track->fChi2MIP[0]+track->fNUsed<minchi2 && track->GetNumberOfClusters()>=minn) ||shortbest){ if (!shortbest) accepted++; // newarray->AddLast(array->RemoveAt(index[i])); for (Int_t i=0;i<6;i++){ if (nz[i]==0){ erry[i] = track->fSigmaY[i]; erry[i+6] = track->fSigmaY[i+6]; errz[i] = track->fSigmaZ[i]; errz[i] = track->fSigmaZ[i+6]; ny[i] = track->fNy[i]; nz[i] = track->fNz[i]; } } } else{ delete array->RemoveAt(index[i]); } } array->Delete(); delete fTrackHypothesys.RemoveAt(esdindex); fTrackHypothesys.AddAt(newarray,esdindex); } else{ array->Delete(); delete fTrackHypothesys.RemoveAt(esdindex); } } delete [] chi2; delete [] index; } AliITStrackMI * AliITStrackerMI::GetBestHypothesys(Int_t esdindex, AliITStrackMI * original, Int_t checkmax) { //------------------------------------------------------------- // try to find best hypothesy // currently - minimal chi2 of track+backpropagated track+matching to the tpc track //------------------------------------------------------------- if (fTrackHypothesys.GetEntriesFast()<=esdindex) return 0; TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); if (!array) return 0; Int_t entries = array->GetEntriesFast(); if (!entries) return 0; Float_t minchi2 = 100000; AliITStrackMI * besttrack=0; // AliITStrackMI * backtrack = new AliITStrackMI(*original); AliITStrackMI * forwardtrack = new AliITStrackMI(*original); Double_t xyzv[]={GetX(),GetY(),GetZ()}; Double_t ersv[]={GetSigmaX()/3.,GetSigmaY()/3.,GetSigmaZ()/3.}; // for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; Float_t sigmarfi,sigmaz; GetDCASigma(track,sigmarfi,sigmaz); track->fDnorm[0] = sigmarfi; track->fDnorm[1] = sigmaz; // track->fChi2MIP[1] = 1000000; track->fChi2MIP[2] = 1000000; track->fChi2MIP[3] = 1000000; // // backtrack backtrack = new(backtrack) AliITStrackMI(*track); if (track->fConstrain){ if (!backtrack->PropagateTo(3.,0.0028,65.19)) continue; if (!backtrack->Improve(0,xyzv,ersv)) continue; if (!backtrack->PropagateTo(2.,0.0028,0)) continue; if (!backtrack->Improve(0,xyzv,ersv)) continue; if (!backtrack->PropagateTo(1.,0.0028,0)) continue; if (!backtrack->Improve(0,xyzv,ersv)) continue; if (!backtrack->PropagateToVertex()) continue; backtrack->ResetCovariance(); if (!backtrack->Improve(0,xyzv,ersv)) continue; }else{ backtrack->ResetCovariance(); } backtrack->ResetClusters(); Double_t x = original->GetX(); if (!RefitAt(x,backtrack,track)) continue; // track->fChi2MIP[1] = NormalizedChi2(backtrack,0); //for (Int_t i=2;i<6;i++){track->fDy[i]+=backtrack->fDy[i]; track->fDz[i]+=backtrack->fDz[i];} if (track->fChi2MIP[1]>kMaxChi2PerCluster[1]*6.) continue; track->fChi22 = GetMatchingChi2(backtrack,original); if ((track->fConstrain) && track->fChi22>90.) continue; if ((!track->fConstrain) && track->fChi22>30.) continue; if ( track->fChi22/track->GetNumberOfClusters()>11.) continue; if (!(track->fConstrain)&&track->fChi2MIP[1]>kMaxChi2PerCluster[1]) continue; Bool_t isOK=kTRUE; if(!isOK) continue; // //forward track - without constraint forwardtrack = new(forwardtrack) AliITStrackMI(*original); forwardtrack->ResetClusters(); x = track->GetX(); RefitAt(x,forwardtrack,track); track->fChi2MIP[2] = NormalizedChi2(forwardtrack,0); if (track->fChi2MIP[2]>kMaxChi2PerCluster[2]*6.0) continue; if (!(track->fConstrain)&&track->fChi2MIP[2]>kMaxChi2PerCluster[2]) continue; track->fD[0] = forwardtrack->GetD(GetX(),GetY()); track->fD[1] = forwardtrack->GetZat(GetX())-GetZ(); forwardtrack->fD[0] = track->fD[0]; forwardtrack->fD[1] = track->fD[1]; { Int_t list[6]; AliITSclusterV2* clist[6]; track->fChi2MIP[4] = GetNumberOfSharedClusters(track,esdindex,list,clist); if ( (!track->fConstrain) && track->fChi2MIP[4]>1.0) continue; } track->fChi2MIP[3] = GetInterpolatedChi2(forwardtrack,backtrack); if ( (track->fChi2MIP[3]>6.*kMaxChi2PerCluster[3])) continue; if ( (!track->fConstrain) && (track->fChi2MIP[3]>2*kMaxChi2PerCluster[3])) { track->fChi2MIP[3]=1000; continue; } Double_t chi2 = track->fChi2MIP[0]+track->fNUsed; // for (Int_t ichi=0;ichi<5;ichi++){ forwardtrack->fChi2MIP[ichi] = track->fChi2MIP[ichi]; } if (chi2 < minchi2){ //besttrack = new AliITStrackMI(*forwardtrack); besttrack = track; besttrack->SetLabel(track->GetLabel()); besttrack->fFakeRatio = track->fFakeRatio; minchi2 = chi2; original->fD[0] = forwardtrack->GetD(GetX(),GetY()); original->fD[1] = forwardtrack->GetZat(GetX())-GetZ(); } } delete backtrack; delete forwardtrack; Int_t accepted=0; for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; if (accepted>checkmax || track->fChi2MIP[3]>kMaxChi2PerCluster[3]*6. || (track->GetNumberOfClusters()<besttrack->GetNumberOfClusters()-1.)|| track->fChi2MIP[0]>besttrack->fChi2MIP[0]+2.*besttrack->fNUsed+3.){ if (track->fConstrain || track->fN>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(i); continue; } } else{ accepted++; } } // array->Compress(); SortTrackHypothesys(esdindex,checkmax,1); array = (TObjArray*) fTrackHypothesys.At(esdindex); besttrack = (AliITStrackMI*)array->At(0); if (!besttrack) return 0; besttrack->fChi2MIP[8]=0; fBestTrackIndex[esdindex]=0; entries = array->GetEntriesFast(); AliITStrackMI *longtrack =0; minchi2 =1000; Float_t minn=besttrack->GetNumberOfClusters()+besttrack->fNDeadZone; for (Int_t itrack=entries-1;itrack>0;itrack--){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (!track->fConstrain) continue; if (track->GetNumberOfClusters()+track->fNDeadZone<minn) continue; if (track->fChi2MIP[0]-besttrack->fChi2MIP[0]>0.0) continue; if (track->fChi2MIP[0]>4.) continue; minn = track->GetNumberOfClusters()+track->fNDeadZone; longtrack =track; } //if (longtrack) besttrack=longtrack; Int_t list[6]; AliITSclusterV2 * clist[6]; Float_t shared = GetNumberOfSharedClusters(besttrack,esdindex,list,clist); if (besttrack->fConstrain&&besttrack->fChi2MIP[0]<kMaxChi2PerCluster[0]&&besttrack->fChi2MIP[1]<kMaxChi2PerCluster[1] &&besttrack->fChi2MIP[2]<kMaxChi2PerCluster[2]&&besttrack->fChi2MIP[3]<kMaxChi2PerCluster[3]){ RegisterClusterTracks(besttrack,esdindex); } // // if (shared>0.0){ Int_t nshared; Int_t overlist[6]; Int_t sharedtrack = GetOverlapTrack(besttrack, esdindex, nshared, list, overlist); if (sharedtrack>=0){ // besttrack = GetBest2Tracks(esdindex,sharedtrack,10,5.5); if (besttrack){ shared = GetNumberOfSharedClusters(besttrack,esdindex,list,clist); } else return 0; } } if (shared>2.5) return 0; if (shared>1.0) return besttrack; // // Don't sign clusters if not gold track // if (!besttrack->IsGoldPrimary()) return besttrack; if (besttrack->fESDtrack->GetKinkIndex(0)!=0) return besttrack; //track belong to kink // if (fConstraint[fPass]){ // // sign clusters // Float_t *ny = GetNy(esdindex), *nz = GetNz(esdindex); for (Int_t i=0;i<6;i++){ Int_t index = besttrack->fClIndex[i]; if (index<=0) continue; Int_t ilayer = (index & 0xf0000000) >> 28; if (besttrack->fSigmaY[ilayer]<0.00000000001) continue; AliITSclusterV2 *c = (AliITSclusterV2*)GetCluster(index); if (!c) continue; if (ilayer>3&&c->GetNy()+c->GetNz()>6) continue; if ( (c->GetNy()+c->GetNz() )> ny[i]+nz[i]+0.7) continue; //shared track if ( c->GetNz()> nz[i]+0.7) continue; //shared track if ( ilayer>2&& besttrack->fNormQ[ilayer]/besttrack->fExpQ>1.5) continue; //if ( c->GetNy()> ny[i]+0.7) continue; //shared track Bool_t cansign = kTRUE; for (Int_t itrack=0;itrack<entries; itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; if (track->fChi2MIP[0]>besttrack->fChi2MIP[0]+2.*shared+1.) break; if ( (track->fClIndex[ilayer]>0) && (track->fClIndex[ilayer]!=besttrack->fClIndex[ilayer])){ cansign = kFALSE; break; } } if (cansign){ if (TMath::Abs(besttrack->fDy[ilayer]/besttrack->fSigmaY[ilayer])>3.) continue; if (TMath::Abs(besttrack->fDz[ilayer]/besttrack->fSigmaZ[ilayer])>3.) continue; if (!c->IsUsed()) c->Use(); } } } return besttrack; } void AliITStrackerMI::GetBestHypothesysMIP(TObjArray &itsTracks) { // // get "best" hypothesys // Int_t nentries = itsTracks.GetEntriesFast(); for (Int_t i=0;i<nentries;i++){ AliITStrackMI* track = (AliITStrackMI*)itsTracks.At(i); if (!track) continue; TObjArray * array = (TObjArray*) fTrackHypothesys.At(i); if (!array) continue; if (array->GetEntriesFast()<=0) continue; // AliITStrackMI* longtrack=0; Float_t minn=0; Float_t maxchi2=1000; for (Int_t j=0;j<array->GetEntriesFast();j++){ AliITStrackMI* track = (AliITStrackMI*)array->At(j); if (!track) continue; if (track->fGoldV0) { longtrack = track; //gold V0 track taken break; } if (track->GetNumberOfClusters()+track->fNDeadZone<minn) continue; Float_t chi2 = track->fChi2MIP[0]; if (fAfterV0){ if (!track->fGoldV0&&track->fConstrain==kFALSE) chi2+=5; } if (track->GetNumberOfClusters()+track->fNDeadZone>minn) maxchi2 = track->fChi2MIP[0]; // if (chi2 > maxchi2) continue; minn= track->GetNumberOfClusters()+track->fNDeadZone; maxchi2 = chi2; longtrack=track; } // // // AliITStrackMI * besttrack = (AliITStrackMI*)array->At(0); if (!longtrack) {longtrack = besttrack;} else besttrack= longtrack; // if (besttrack){ Int_t list[6]; AliITSclusterV2 * clist[6]; Float_t shared = GetNumberOfSharedClusters(longtrack,i,list,clist); // track->fNUsed = shared; track->fNSkipped = besttrack->fNSkipped; track->fChi2MIP[0] = besttrack->fChi2MIP[0]; if (shared>0){ Int_t nshared; Int_t overlist[6]; // Int_t sharedtrack = GetOverlapTrack(longtrack, i, nshared, list, overlist); //if (sharedtrack==-1) sharedtrack=0; if (sharedtrack>=0){ besttrack = GetBest2Tracks(i,sharedtrack,10,5.5); } } if (besttrack&&fAfterV0){ UpdateESDtrack(besttrack,AliESDtrack::kITSin); } if (besttrack&&fConstraint[fPass]) UpdateESDtrack(besttrack,AliESDtrack::kITSin); //if (besttrack&&besttrack->fConstrain) // UpdateESDtrack(besttrack,AliESDtrack::kITSin); if (besttrack->fChi2MIP[0]+besttrack->fNUsed>1.5){ if ( (TMath::Abs(besttrack->fD[0])>0.1) && fConstraint[fPass]) { track->fReconstructed= kFALSE; } if ( (TMath::Abs(besttrack->fD[1])>0.1) && fConstraint[fPass]){ track->fReconstructed= kFALSE; } } } } } void AliITStrackerMI::CookLabel(AliITStrackMI *track,Float_t wrong) const { //-------------------------------------------------------------------- //This function "cooks" a track label. If label<0, this track is fake. //-------------------------------------------------------------------- Int_t tpcLabel=-1; if ( track->fESDtrack) tpcLabel = TMath::Abs(track->fESDtrack->GetTPCLabel()); track->fChi2MIP[9]=0; Int_t nwrong=0; for (Int_t i=0;i<track->GetNumberOfClusters();i++){ Int_t cindex = track->GetClusterIndex(i); Int_t l=(cindex & 0xf0000000) >> 28; AliITSclusterV2 *cl = (AliITSclusterV2*)GetCluster(cindex); Int_t isWrong=1; for (Int_t ind=0;ind<3;ind++){ if (tpcLabel>0) if (cl->GetLabel(ind)==tpcLabel) isWrong=0; } track->fChi2MIP[9]+=isWrong*(2<<l); nwrong+=isWrong; } track->fFakeRatio = double(nwrong)/double(track->GetNumberOfClusters()); if (tpcLabel>0){ if (track->fFakeRatio>wrong) track->fLab = -tpcLabel; else track->fLab = tpcLabel; } } void AliITStrackerMI::CookdEdx(AliITStrackMI* track) { // // // Int_t list[6]; //AliITSclusterV2 * clist[6]; // Int_t shared = GetNumberOfSharedClusters(track,index,list,clist); Float_t dedx[4]; Int_t accepted=0; track->fChi2MIP[9]=0; for (Int_t i=0;i<track->GetNumberOfClusters();i++){ Int_t cindex = track->GetClusterIndex(i); Int_t l=(cindex & 0xf0000000) >> 28; AliITSclusterV2 *cl = (AliITSclusterV2*)GetCluster(cindex); Int_t lab = TMath::Abs(track->fESDtrack->GetTPCLabel()); Int_t isWrong=1; for (Int_t ind=0;ind<3;ind++){ if (cl->GetLabel(ind)==lab) isWrong=0; } track->fChi2MIP[9]+=isWrong*(2<<l); if (l<2) continue; //if (l>3 && (cl->GetNy()>4) || (cl->GetNz()>4)) continue; //shared track //if (l>3&& !(cl->GetType()==1||cl->GetType()==10)) continue; //if (l<4&& !(cl->GetType()==1)) continue; dedx[accepted]= track->fdEdxSample[i]; //dedx[accepted]= track->fNormQ[l]; accepted++; } if (accepted<1) { track->SetdEdx(0); return; } Int_t indexes[4]; TMath::Sort(accepted,dedx,indexes,kFALSE); Double_t low=0.; Double_t up=0.51; Double_t nl=low*accepted, nu =up*accepted; Float_t sumamp = 0; Float_t sumweight =0; for (Int_t i=0; i<accepted; i++) { Float_t weight =1; if (i<nl+0.1) weight = TMath::Max(1.-(nl-i),0.); if (i>nu-1) weight = TMath::Max(nu-i,0.); sumamp+= dedx[indexes[i]]*weight; sumweight+=weight; } track->SetdEdx(sumamp/sumweight); } void AliITStrackerMI::MakeCoeficients(Int_t ntracks){ // // if (fCoeficients) delete []fCoeficients; fCoeficients = new Float_t[ntracks*48]; for (Int_t i=0;i<ntracks*48;i++) fCoeficients[i]=-1.; } Double_t AliITStrackerMI::GetPredictedChi2MI(AliITStrackMI* track, const AliITSclusterV2 *cluster,Int_t layer) { // // // Float_t erry,errz; Float_t theta = track->GetTgl(); Float_t phi = track->GetSnp(); phi = TMath::Sqrt(phi*phi/(1.-phi*phi)); GetError(layer,cluster,theta,phi,track->fExpQ,erry,errz); Double_t chi2 = track->GetPredictedChi2MI(cluster->GetY(),cluster->GetZ(),erry,errz); Float_t ny,nz; GetNTeor(layer,cluster, theta,phi,ny,nz); Double_t delta = cluster->GetNy()+cluster->GetNz()-nz-ny; if (delta>1){ chi2+=0.5*TMath::Min(delta/2,2.); chi2+=2.*cluster->GetDeltaProbability(); } // track->fNy[layer] =ny; track->fNz[layer] =nz; track->fSigmaY[layer] = erry; track->fSigmaZ[layer] = errz; //track->fNormQ[layer] = cluster->GetQ()/TMath::Sqrt(1+theta*theta+phi*phi); track->fNormQ[layer] = cluster->GetQ()/TMath::Sqrt((1.+ track->fP3*track->fP3)/(1.- track->fP2*track->fP2)); return chi2; } Int_t AliITStrackerMI::UpdateMI(AliITStrackMI* track, const AliITSclusterV2* cl,Double_t chi2,Int_t index) const { // // // Int_t layer = (index & 0xf0000000) >> 28; track->fClIndex[layer] = index; if ( (layer>1) &&track->fNormQ[layer]/track->fExpQ<0.5 ) { chi2+= (0.5-track->fNormQ[layer]/track->fExpQ)*10.; track->fdEdxMismatch+=(0.5-track->fNormQ[layer]/track->fExpQ)*10.; } return track->UpdateMI(cl->GetY(),cl->GetZ(),track->fSigmaY[layer],track->fSigmaZ[layer],chi2,index); } void AliITStrackerMI::GetNTeor(Int_t layer, const AliITSclusterV2* /*cl*/, Float_t theta, Float_t phi, Float_t &ny, Float_t &nz) { // //get "mean shape" // if (layer==0){ ny = 1.+TMath::Abs(phi)*3.2; nz = 1.+TMath::Abs(theta)*0.34; return; } if (layer==1){ ny = 1.+TMath::Abs(phi)*3.2; nz = 1.+TMath::Abs(theta)*0.28; return; } if (layer>3){ ny = 2.02+TMath::Abs(phi)*1.95; nz = 2.02+TMath::Abs(phi)*2.35; return; } ny = 6.6-2.7*TMath::Abs(phi); nz = 2.8-3.11*TMath::Abs(phi)+0.45*TMath::Abs(theta); } Int_t AliITStrackerMI::GetError(Int_t layer, const AliITSclusterV2*cl, Float_t theta, Float_t phi,Float_t expQ, Float_t &erry, Float_t &errz) { //calculate cluster position error // Float_t nz,ny; GetNTeor(layer, cl,theta,phi,ny,nz); erry = TMath::Sqrt(cl->GetSigmaY2()); errz = TMath::Sqrt(cl->GetSigmaZ2()); // // PIXELS if (layer<2){ if (TMath::Abs(ny-cl->GetNy())>0.6) { if (ny<cl->GetNy()){ erry*=0.4+TMath::Abs(ny-cl->GetNy()); errz*=0.4+TMath::Abs(ny-cl->GetNy()); }else{ erry*=0.7+0.5*TMath::Abs(ny-cl->GetNy()); errz*=0.7+0.5*TMath::Abs(ny-cl->GetNy()); } } if (TMath::Abs(nz-cl->GetNz())>1.) { erry*=TMath::Abs(nz-cl->GetNz()); errz*=TMath::Abs(nz-cl->GetNz()); } erry*=0.85; errz*=0.85; erry= TMath::Min(erry,float(0.005)); errz= TMath::Min(errz,float(0.03)); return 10; } //STRIPS if (layer>3){ //factor 1.8 appears in new simulation // Float_t scale=1.8; if (cl->GetNy()==100||cl->GetNz()==100){ erry = 0.004*scale; errz = 0.2*scale; return 100; } if (cl->GetNy()+cl->GetNz()>12){ erry = 0.06*scale; errz = 0.57*scale; return 100; } Float_t normq = cl->GetQ()/(TMath::Sqrt(1+theta*theta+phi*phi)); Float_t chargematch = TMath::Max(double(normq/expQ),2.); // if (cl->GetType()==1 || cl->GetType()==10 ){ if (chargematch<1.0 || (cl->GetNy()+cl->GetNz()<nz+ny+0.5)){ errz = 0.043*scale; erry = 0.00094*scale; return 101; } if (cl->GetNy()+cl->GetNz()<nz+ny+1.2){ errz = 0.06*scale; erry =0.0013*scale; return 102; } erry = 0.0027*scale; errz = TMath::Min(0.028*(chargematch+cl->GetNy()+cl->GetNz()-nz+ny),0.15)*scale; return 103; } if (cl->GetType()==2 || cl->GetType()==11 ){ erry = TMath::Min(0.0010*(1+chargematch+cl->GetNy()+cl->GetNz()-nz+ny),0.05)*scale; errz = TMath::Min(0.025*(1+chargematch+cl->GetNy()+cl->GetNz()-nz+ny),0.5)*scale; return 104; } if (cl->GetType()>100 ){ if ((chargematch+cl->GetNy()+cl->GetNz()-nz-ny<1.5)){ errz = 0.05*scale; erry = 0.00096*scale; return 105; } if (cl->GetNy()+cl->GetNz()-nz-ny<1){ errz = 0.10*scale; erry = 0.0025*scale; return 106; } errz = TMath::Min(0.05*(chargematch+cl->GetNy()+cl->GetNz()-nz-ny),0.4)*scale; erry = TMath::Min(0.003*(chargematch+cl->GetNy()+cl->GetNz()-nz-ny),0.05)*scale; return 107; } Float_t diff = cl->GetNy()+cl->GetNz()-ny-nz; if (diff<1) diff=1; if (diff>4) diff=4; if (cl->GetType()==5||cl->GetType()==6||cl->GetType()==7||cl->GetType()==8){ errz = 0.14*diff; erry = 0.003*diff; return 108; } erry = 0.04*diff; errz = 0.06*diff; return 109; } //DRIFTS Float_t normq = cl->GetQ()/(TMath::Sqrt(1+theta*theta+phi*phi)); Float_t chargematch = normq/expQ; Float_t factorz=1; Int_t cnz = cl->GetNz()%10; //charge match if (cl->GetType()==1){ if (chargematch<1.25){ erry = 0.0028*(1.+6./cl->GetQ()); // gold clusters } else{ erry = 0.003*chargematch; if (cl->GetNz()==3) erry*=1.5; } if (chargematch<1.0){ errz = 0.0011*(1.+6./cl->GetQ()); } else{ errz = 0.002*(1+2*(chargematch-1.)); } if (cnz>nz+0.6) { erry*=(cnz-nz+0.5); errz*=1.4*(cnz-nz+0.5); } } if (cl->GetType()>1){ if (chargematch<1){ erry = 0.00385*(1.+6./cl->GetQ()); // gold clusters errz = 0.0016*(1.+6./cl->GetQ()); } else{ errz = 0.0014*(1+3*(chargematch-1.)); erry = 0.003*(1+3*(chargematch-1.)); } if (cnz>nz+0.6) { erry*=(cnz-nz+0.5); errz*=1.4*(cnz-nz+0.5); } } if (TMath::Abs(cl->GetY())>2.5){ factorz*=1+2*(TMath::Abs(cl->GetY())-2.5); } if (TMath::Abs(cl->GetY())<1){ factorz*=1.+0.5*TMath::Abs(TMath::Abs(cl->GetY())-1.); } factorz= TMath::Min(factorz,float(4.)); errz*=factorz; erry= TMath::Min(erry,float(0.05)); errz= TMath::Min(errz,float(0.05)); return 200; } void AliITStrackerMI::GetDCASigma(AliITStrackMI* track, Float_t & sigmarfi, Float_t &sigmaz) { // //DCA sigmas parameterization //to be paramterized using external parameters in future // // sigmarfi = 0.004+1.4 *TMath::Abs(track->fP4)+332.*track->fP4*track->fP4; sigmaz = 0.011+4.37*TMath::Abs(track->fP4); } void AliITStrackerMI::SignDeltas( TObjArray *ClusterArray, Float_t vz) { // // Int_t entries = ClusterArray->GetEntriesFast(); if (entries<4) return; AliITSclusterV2* cluster = (AliITSclusterV2*)ClusterArray->At(0); Int_t layer = cluster->GetLayer(); if (layer>1) return; Int_t index[10000]; Int_t ncandidates=0; Float_t r = (layer>0)? 7:4; // for (Int_t i=0;i<entries;i++){ AliITSclusterV2* cl0 = (AliITSclusterV2*)ClusterArray->At(i); Float_t nz = 1+TMath::Abs((cl0->GetZ()-vz)/r); if (cl0->GetNy()+cl0->GetNz()<=5+2*layer+nz) continue; index[ncandidates] = i; //candidate to belong to delta electron track ncandidates++; if (cl0->GetNy()+cl0->GetNz()>9+2*layer+nz) { cl0->SetDeltaProbability(1); } } // // // for (Int_t i=0;i<ncandidates;i++){ AliITSclusterV2* cl0 = (AliITSclusterV2*)ClusterArray->At(index[i]); if (cl0->GetDeltaProbability()>0.8) continue; // Int_t ncl = 0; Float_t y[100],z[100],sumy,sumz,sumy2, sumyz, sumw; sumy=sumz=sumy2=sumyz=sumw=0.0; for (Int_t j=0;j<ncandidates;j++){ if (i==j) continue; AliITSclusterV2* cl1 = (AliITSclusterV2*)ClusterArray->At(index[j]); // Float_t dz = cl0->GetZ()-cl1->GetZ(); Float_t dy = cl0->GetY()-cl1->GetY(); if (TMath::Sqrt(dz*dz+dy*dy)<0.2){ Float_t weight = cl1->GetNy()+cl1->GetNz()-2; y[ncl] = cl1->GetY(); z[ncl] = cl1->GetZ(); sumy+= y[ncl]*weight; sumz+= z[ncl]*weight; sumy2+=y[ncl]*y[ncl]*weight; sumyz+=y[ncl]*z[ncl]*weight; sumw+=weight; ncl++; } } if (ncl<4) continue; Float_t det = sumw*sumy2 - sumy*sumy; Float_t delta=1000; if (TMath::Abs(det)>0.01){ Float_t z0 = (sumy2*sumz - sumy*sumyz)/det; Float_t k = (sumyz*sumw - sumy*sumz)/det; delta = TMath::Abs(cl0->GetZ()-(z0+k*cl0->GetY())); } else{ Float_t z0 = sumyz/sumy; delta = TMath::Abs(cl0->GetZ()-z0); } if ( delta<0.05) { cl0->SetDeltaProbability(1-20.*delta); } } } void AliITStrackerMI::UpdateESDtrack(AliITStrackMI* track, ULong_t flags) const { // // track->UpdateESDtrack(flags); AliITStrackMI * oldtrack = (AliITStrackMI*)(track->fESDtrack->GetITStrack()); if (oldtrack) delete oldtrack; track->fESDtrack->SetITStrack(new AliITStrackMI(*track)); if (TMath::Abs(track->fDnorm[1])<0.000000001){ printf("Problem\n"); } } Int_t AliITStrackerMI::GetNearestLayer(const Double_t *xr) const{ // //Get nearest upper layer close to the point xr. // rough approximation // const Float_t kRadiuses[6]={4,6.5,15.03,24.,38.5,43.7}; Float_t radius = TMath::Sqrt(xr[0]*xr[0]+xr[1]*xr[1]); Int_t res =6; for (Int_t i=0;i<6;i++){ if (radius<kRadiuses[i]){ res =i; break; } } return res; } void AliITStrackerMI::UpdateTPCV0(AliESD *event){ // //try to update, or reject TPC V0s // Int_t nv0s = event->GetNumberOfV0MIs(); Int_t nitstracks = fTrackHypothesys.GetEntriesFast(); for (Int_t i=0;i<nv0s;i++){ AliESDV0MI * vertex = event->GetV0MI(i); Int_t ip = vertex->GetIndex(0); Int_t im = vertex->GetIndex(1); // TObjArray * arrayp = (ip<nitstracks) ? (TObjArray*)fTrackHypothesys.At(ip):0; TObjArray * arraym = (im<nitstracks) ? (TObjArray*)fTrackHypothesys.At(im):0; AliITStrackMI * trackp = (arrayp!=0) ? (AliITStrackMI*)arrayp->At(0):0; AliITStrackMI * trackm = (arraym!=0) ? (AliITStrackMI*)arraym->At(0):0; // // if (trackp){ if (trackp->fN+trackp->fNDeadZone>5.5){ if (trackp->fConstrain&&trackp->fChi2MIP[0]<3) vertex->SetStatus(-100); if (!trackp->fConstrain&&trackp->fChi2MIP[0]<2) vertex->SetStatus(-100); } } if (trackm){ if (trackm->fN+trackm->fNDeadZone>5.5){ if (trackm->fConstrain&&trackm->fChi2MIP[0]<3) vertex->SetStatus(-100); if (!trackm->fConstrain&&trackm->fChi2MIP[0]<2) vertex->SetStatus(-100); } } if (vertex->GetStatus()==-100) continue; // Int_t clayer = GetNearestLayer(vertex->GetXrp()); vertex->SetNBefore(clayer); // vertex->SetChi2Before(9*clayer); // vertex->SetNAfter(6-clayer); // vertex->SetChi2After(0); // // if (clayer >1 ){ // calculate chi2 before vertex Float_t chi2p = 0, chi2m=0; // if (trackp){ for (Int_t ilayer=0;ilayer<clayer;ilayer++){ if (trackp->fClIndex[ilayer]>0){ chi2p+=trackp->fDy[ilayer]*trackp->fDy[ilayer]/(trackp->fSigmaY[ilayer]*trackp->fSigmaY[ilayer])+ trackp->fDz[ilayer]*trackp->fDz[ilayer]/(trackp->fSigmaZ[ilayer]*trackp->fSigmaZ[ilayer]); } else{ chi2p+=9; } } }else{ chi2p = 9*clayer; } // if (trackm){ for (Int_t ilayer=0;ilayer<clayer;ilayer++){ if (trackm->fClIndex[ilayer]>0){ chi2m+=trackm->fDy[ilayer]*trackm->fDy[ilayer]/(trackm->fSigmaY[ilayer]*trackm->fSigmaY[ilayer])+ trackm->fDz[ilayer]*trackm->fDz[ilayer]/(trackm->fSigmaZ[ilayer]*trackm->fSigmaZ[ilayer]); } else{ chi2m+=9; } } }else{ chi2m = 9*clayer; } vertex->SetChi2Before(TMath::Min(chi2p,chi2m)); if (TMath::Min(chi2p,chi2m)/Float_t(clayer)<4) vertex->SetStatus(-10); // track exist before vertex } if (clayer < 5 ){ // calculate chi2 after vertex Float_t chi2p = 0, chi2m=0; // if (trackp&&TMath::Abs(trackp->fP3)<1.){ for (Int_t ilayer=clayer;ilayer<6;ilayer++){ if (trackp->fClIndex[ilayer]>0){ chi2p+=trackp->fDy[ilayer]*trackp->fDy[ilayer]/(trackp->fSigmaY[ilayer]*trackp->fSigmaY[ilayer])+ trackp->fDz[ilayer]*trackp->fDz[ilayer]/(trackp->fSigmaZ[ilayer]*trackp->fSigmaZ[ilayer]); } else{ chi2p+=9; } } }else{ chi2p = 0; } // if (trackm&&TMath::Abs(trackm->fP3)<1.){ for (Int_t ilayer=clayer;ilayer<6;ilayer++){ if (trackm->fClIndex[ilayer]>0){ chi2m+=trackm->fDy[ilayer]*trackm->fDy[ilayer]/(trackm->fSigmaY[ilayer]*trackm->fSigmaY[ilayer])+ trackm->fDz[ilayer]*trackm->fDz[ilayer]/(trackm->fSigmaZ[ilayer]*trackm->fSigmaZ[ilayer]); } else{ chi2m+=9; } } }else{ chi2m = 0; } vertex->SetChi2After(TMath::Max(chi2p,chi2m)); if (TMath::Max(chi2m,chi2p)/Float_t(6-clayer)>9) vertex->SetStatus(-20); // track not found in ITS } } // } void AliITStrackerMI::FindV02(AliESD *event) { // // V0 finder // // Cuts on DCA - R dependent // max distance DCA between 2 tracks cut // maxDist = TMath::Min(kMaxDist,kMaxDist0+pvertex->GetRr()*kMaxDist); // const Float_t kMaxDist0 = 0.1; const Float_t kMaxDist1 = 0.1; const Float_t kMaxDist = 1; const Float_t kMinPointAngle = 0.85; const Float_t kMinPointAngle2 = 0.99; const Float_t kMinR = 0.5; const Float_t kMaxR = 220; //const Float_t kCausality0Cut = 0.19; //const Float_t kLikelihood01Cut = 0.25; //const Float_t kPointAngleCut = 0.9996; const Float_t kCausality0Cut = 0.19; const Float_t kLikelihood01Cut = 0.45; const Float_t kLikelihood1Cut = 0.5; const Float_t kCombinedCut = 0.55; // // TTreeSRedirector &cstream = *fDebugStreamer; Int_t ntracks = event->GetNumberOfTracks(); Int_t nitstracks = fTrackHypothesys.GetEntriesFast(); fOriginal.Expand(ntracks); fTrackHypothesys.Expand(ntracks); fBestHypothesys.Expand(ntracks); // AliHelix * helixes = new AliHelix[ntracks+2]; TObjArray trackarray(ntracks+2); //array with tracks - with vertex constrain TObjArray trackarrayc(ntracks+2); //array of "best tracks" - without vertex constrain TObjArray trackarrayl(ntracks+2); //array of "longest tracks" - without vertex constrain Bool_t * forbidden = new Bool_t [ntracks+2]; Int_t *itsmap = new Int_t [ntracks+2]; Float_t *dist = new Float_t[ntracks+2]; Float_t *normdist0 = new Float_t[ntracks+2]; Float_t *normdist1 = new Float_t[ntracks+2]; Float_t *normdist = new Float_t[ntracks+2]; Float_t *norm = new Float_t[ntracks+2]; Float_t *maxr = new Float_t[ntracks+2]; Float_t *minr = new Float_t[ntracks+2]; Float_t *minPointAngle= new Float_t[ntracks+2]; // AliESDV0MI *pvertex = new AliESDV0MI; AliITStrackMI * dummy= new AliITStrackMI; dummy->SetLabel(0); AliITStrackMI trackat0; //temporary track for DCA calculation // Float_t primvertex[3]={GetX(),GetY(),GetZ()}; // // make its - esd map // for (Int_t itrack=0;itrack<ntracks+2;itrack++) { itsmap[itrack] = -1; forbidden[itrack] = kFALSE; maxr[itrack] = kMaxR; minr[itrack] = kMinR; minPointAngle[itrack] = kMinPointAngle; } for (Int_t itrack=0;itrack<nitstracks;itrack++){ AliITStrackMI * original = (AliITStrackMI*)(fOriginal.At(itrack)); Int_t esdindex = original->fESDtrack->GetID(); itsmap[esdindex] = itrack; } // // create its tracks from esd tracks if not done before // for (Int_t itrack=0;itrack<ntracks;itrack++){ if (itsmap[itrack]>=0) continue; AliITStrackMI * tpctrack = new AliITStrackMI(*(event->GetTrack(itrack))); tpctrack->fD[0] = tpctrack->GetD(GetX(),GetY()); tpctrack->fD[1] = tpctrack->GetZat(GetX())-GetZ(); if (tpctrack->fD[0]<20 && tpctrack->fD[1]<20){ // tracks which can reach inner part of ITS // propagate track to outer its volume - with correction for material CorrectForDeadZoneMaterial(tpctrack); } itsmap[itrack] = nitstracks; fOriginal.AddAt(tpctrack,nitstracks); nitstracks++; } // // fill temporary arrays // for (Int_t itrack=0;itrack<ntracks;itrack++){ AliESDtrack * esdtrack = event->GetTrack(itrack); Int_t itsindex = itsmap[itrack]; AliITStrackMI *original = (AliITStrackMI*)fOriginal.At(itsmap[itrack]); if (!original) continue; AliITStrackMI *bestConst = 0; AliITStrackMI *bestLong = 0; AliITStrackMI *best = 0; // // TObjArray * array = (TObjArray*) fTrackHypothesys.At(itsindex); Int_t hentries = (array==0) ? 0 : array->GetEntriesFast(); // Get best track with vertex constrain for (Int_t ih=0;ih<hentries;ih++){ AliITStrackMI * trackh = (AliITStrackMI*)array->At(ih); if (!trackh->fConstrain) continue; if (!bestConst) bestConst = trackh; if (trackh->fN>5.0){ bestConst = trackh; // full track - with minimal chi2 break; } if (trackh->fN+trackh->fNDeadZone<=bestConst->fN+bestConst->fNDeadZone) continue; bestConst = trackh; break; } // Get best long track without vertex constrain and best track without vertex constrain for (Int_t ih=0;ih<hentries;ih++){ AliITStrackMI * trackh = (AliITStrackMI*)array->At(ih); if (trackh->fConstrain) continue; if (!best) best = trackh; if (!bestLong) bestLong = trackh; if (trackh->fN>5.0){ bestLong = trackh; // full track - with minimal chi2 break; } if (trackh->fN+trackh->fNDeadZone<=bestLong->fN+bestLong->fNDeadZone) continue; bestLong = trackh; } if (!best) { best = original; bestLong = original; } trackat0 = *bestLong; Double_t xx,yy,zz,alpha; bestLong->GetGlobalXYZat(bestLong->GetX(),xx,yy,zz); alpha = TMath::ATan2(yy,xx); trackat0.Propagate(alpha,0); // calculate normalized distances to the vertex // Float_t ptfac = (1.+100.*TMath::Abs(trackat0.fP4)); if ( bestLong->fN>3 ){ dist[itsindex] = trackat0.fP0; norm[itsindex] = ptfac*TMath::Sqrt(trackat0.fC00); normdist0[itsindex] = TMath::Abs(trackat0.fP0/norm[itsindex]); normdist1[itsindex] = TMath::Abs((trackat0.fP1-primvertex[2])/(ptfac*TMath::Sqrt(trackat0.fC11))); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); if (!bestConst){ if (bestLong->fN+bestLong->fNDeadZone<6) normdist[itsindex]*=2.; if (bestLong->fN+bestLong->fNDeadZone<5) normdist[itsindex]*=2.; if (bestLong->fN+bestLong->fNDeadZone<4) normdist[itsindex]*=2.; }else{ if (bestConst->fN+bestConst->fNDeadZone<6) normdist[itsindex]*=1.5; if (bestConst->fN+bestConst->fNDeadZone<5) normdist[itsindex]*=1.5; } } else{ if (bestConst&&bestConst->fN+bestConst->fNDeadZone>4.5){ dist[itsindex] = bestConst->fD[0]; norm[itsindex] = bestConst->fDnorm[0]; normdist0[itsindex] = TMath::Abs(bestConst->fD[0]/norm[itsindex]); normdist1[itsindex] = TMath::Abs(bestConst->fD[0]/norm[itsindex]); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); }else{ dist[itsindex] = trackat0.fP0; norm[itsindex] = ptfac*TMath::Sqrt(trackat0.fC00); normdist0[itsindex] = TMath::Abs(trackat0.fP0/norm[itsindex]); normdist1[itsindex] = TMath::Abs((trackat0.fP1-primvertex[2])/(ptfac*TMath::Sqrt(trackat0.fC11))); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); if (TMath::Abs(trackat0.fP3)>1.05){ if (normdist[itsindex]<3) forbidden[itsindex]=kTRUE; if (normdist[itsindex]>3) { minr[itsindex] = TMath::Max(Float_t(40.),minr[itsindex]); } } } } // //----------------------------------------------------------- //Forbid primary track candidates - // //treetr->SetAlias("forbidden0","Tr0.fN<4&&Tr1.fN+Tr1.fNDeadZone>4.5"); //treetr->SetAlias("forbidden1","ND<3&&Tr1.fN+Tr1.fNDeadZone>5.5"); //treetr->SetAlias("forbidden2","ND<2&&Tr1.fClIndex[0]>0&&Tr1.fClIndex[0]>0"); //treetr->SetAlias("forbidden3","ND<1&&Tr1.fClIndex[0]>0"); //treetr->SetAlias("forbidden4","ND<4&&Tr1.fNormChi2[0]<2"); //treetr->SetAlias("forbidden5","ND<5&&Tr1.fNormChi2[0]<1"); //----------------------------------------------------------- if (bestConst){ if (bestLong->fN<4 && bestConst->fN+bestConst->fNDeadZone>4.5) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<3 && bestConst->fN+bestConst->fNDeadZone>5.5) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<2 && bestConst->fClIndex[0]>0 && bestConst->fClIndex[1]>0 ) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<1 && bestConst->fClIndex[0]>0) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<4 && bestConst->fNormChi2[0]<2) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<5 && bestConst->fNormChi2[0]<1) forbidden[itsindex]=kTRUE; if (bestConst->fNormChi2[0]<2.5) { minPointAngle[itsindex]= 0.9999; maxr[itsindex] = 10; } } // //forbid daughter kink candidates // if (esdtrack->GetKinkIndex(0)>0) forbidden[itsindex] = kTRUE; Bool_t isElectron = kTRUE; Bool_t isProton = kTRUE; Double_t pid[5]; esdtrack->GetESDpid(pid); for (Int_t i=1;i<5;i++){ if (pid[0]<pid[i]) isElectron= kFALSE; if (pid[4]<pid[i]) isProton= kFALSE; } if (isElectron){ forbidden[itsindex]=kFALSE; normdist[itsindex]*=-1; } if (isProton){ if (normdist[itsindex]>2) forbidden[itsindex]=kFALSE; normdist[itsindex]*=-1; } // // Causality cuts in TPC volume // if (esdtrack->GetTPCdensity(0,10) >0.6) maxr[itsindex] = TMath::Min(Float_t(110),maxr[itsindex]); if (esdtrack->GetTPCdensity(10,30)>0.6) maxr[itsindex] = TMath::Min(Float_t(120),maxr[itsindex]); if (esdtrack->GetTPCdensity(20,40)>0.6) maxr[itsindex] = TMath::Min(Float_t(130),maxr[itsindex]); if (esdtrack->GetTPCdensity(30,50)>0.6) maxr[itsindex] = TMath::Min(Float_t(140),maxr[itsindex]); // if (esdtrack->GetTPCdensity(0,60)<0.4&&bestLong->fN<3) minr[itsindex]=100; // // if (kFALSE){ cstream<<"Track"<< "Tr0.="<<best<< "Tr1.="<<((bestConst)? bestConst:dummy)<< "Tr2.="<<bestLong<< "Tr3.="<<&trackat0<< "Esd.="<<esdtrack<< "Dist="<<dist[itsindex]<< "ND0="<<normdist0[itsindex]<< "ND1="<<normdist1[itsindex]<< "ND="<<normdist[itsindex]<< "Pz="<<primvertex[2]<< "Forbid="<<forbidden[itsindex]<< "\n"; // } trackarray.AddAt(best,itsindex); trackarrayc.AddAt(bestConst,itsindex); trackarrayl.AddAt(bestLong,itsindex); new (&helixes[itsindex]) AliHelix(*best); } // // // // first iterration of V0 finder // for (Int_t iesd0=0;iesd0<ntracks;iesd0++){ Int_t itrack0 = itsmap[iesd0]; if (forbidden[itrack0]) continue; AliITStrackMI * btrack0 = (AliITStrackMI*)trackarray.At(itrack0); if (!btrack0) continue; if (btrack0->fP4>0) continue; AliITStrackMI *trackc0 = (AliITStrackMI*)trackarrayc.At(itrack0); // for (Int_t iesd1=0;iesd1<ntracks;iesd1++){ Int_t itrack1 = itsmap[iesd1]; if (forbidden[itrack1]) continue; AliITStrackMI * btrack1 = (AliITStrackMI*)trackarray.At(itrack1); if (!btrack1) continue; if (btrack1->fP4<0) continue; Bool_t isGold = kFALSE; if (TMath::Abs(TMath::Abs(btrack0->GetLabel())-TMath::Abs(btrack1->GetLabel()))==1){ isGold = kTRUE; } AliITStrackMI *trackc1 = (AliITStrackMI*)trackarrayc.At(itrack1); AliHelix &h1 = helixes[itrack0]; AliHelix &h2 = helixes[itrack1]; // // find linear distance Double_t rmin =0; // // // Double_t phase[2][2],radius[2]; Int_t points = h1.GetRPHIintersections(h2, phase, radius); if (points==0) continue; Double_t delta[2]={1000,1000}; rmin = radius[0]; h1.ParabolicDCA(h2,phase[0][0],phase[0][1],radius[0],delta[0]); if (points==2){ if (radius[1]<rmin) rmin = radius[1]; h1.ParabolicDCA(h2,phase[1][0],phase[1][1],radius[1],delta[1]); } rmin = TMath::Sqrt(rmin); Double_t distance = 0; Double_t radiusC = 0; Int_t iphase = 0; if (delta[0]<delta[1]){ distance = TMath::Sqrt(delta[0]); radiusC = TMath::Sqrt(radius[0]); }else{ distance = TMath::Sqrt(delta[1]); radiusC = TMath::Sqrt(radius[1]); iphase=1; } if (radiusC<TMath::Max(minr[itrack0],minr[itrack1])) continue; if (radiusC>TMath::Min(maxr[itrack0],maxr[itrack1])) continue; Float_t maxDist = TMath::Min(kMaxDist,Float_t(kMaxDist0+radiusC*kMaxDist1)); if (distance>maxDist) continue; Float_t pointAngle = h1.GetPointAngle(h2,phase[iphase],primvertex); if (pointAngle<TMath::Max(minPointAngle[itrack0],minPointAngle[itrack1])) continue; // // // Double_t distance = TestV0(h1,h2,pvertex,rmin); // // if (distance>maxDist) continue; // if (pvertex->GetRr()<kMinR) continue; // if (pvertex->GetRr()>kMaxR) continue; AliITStrackMI * track0=btrack0; AliITStrackMI * track1=btrack1; // if (pvertex->GetRr()<3.5){ if (radiusC<3.5){ //use longest tracks inside the pipe track0 = (AliITStrackMI*)trackarrayl.At(itrack0); track1 = (AliITStrackMI*)trackarrayl.At(itrack1); } // // pvertex->SetM(*track0); pvertex->SetP(*track1); pvertex->Update(primvertex); pvertex->SetClusters(track0->fClIndex,track1->fClIndex); // register clusters if (pvertex->GetRr()<kMinR) continue; if (pvertex->GetRr()>kMaxR) continue; if (pvertex->GetPointAngle()<kMinPointAngle) continue; if (pvertex->GetDist2()>maxDist) continue; pvertex->SetLab(0,track0->GetLabel()); pvertex->SetLab(1,track1->GetLabel()); pvertex->SetIndex(0,track0->fESDtrack->GetID()); pvertex->SetIndex(1,track1->fESDtrack->GetID()); // AliITStrackMI * htrackc0 = trackc0 ? trackc0:dummy; AliITStrackMI * htrackc1 = trackc1 ? trackc1:dummy; // // TObjArray * array0b = (TObjArray*)fBestHypothesys.At(itrack0); if (!array0b&&pvertex->GetRr()<40 && TMath::Abs(track0->fP3)<1.1) FollowProlongationTree((AliITStrackMI*)fOriginal.At(itrack0),itrack0, kFALSE); TObjArray * array1b = (TObjArray*)fBestHypothesys.At(itrack1); if (!array1b&&pvertex->GetRr()<40 && TMath::Abs(track1->fP3)<1.1) FollowProlongationTree((AliITStrackMI*)fOriginal.At(itrack1),itrack1, kFALSE); // AliITStrackMI * track0b = (AliITStrackMI*)fOriginal.At(itrack0); AliITStrackMI * track1b = (AliITStrackMI*)fOriginal.At(itrack1); AliITStrackMI * track0l = (AliITStrackMI*)fOriginal.At(itrack0); AliITStrackMI * track1l = (AliITStrackMI*)fOriginal.At(itrack1); Float_t minchi2before0=16; Float_t minchi2before1=16; Float_t minchi2after0 =16; Float_t minchi2after1 =16; Int_t maxLayer = GetNearestLayer(pvertex->GetXrp()); if (array0b) for (Int_t i=0;i<5;i++){ // best track after vertex AliITStrackMI * btrack = (AliITStrackMI*)array0b->At(i); if (!btrack) continue; if (btrack->fN>track0l->fN) track0l = btrack; // if (btrack->fX<pvertex->GetRr()-2.-0.5/(0.1+pvertex->GetAnglep()[2])) { if (btrack->fX<pvertex->GetRr()-2.) { if ( (maxLayer>i+2|| (i==0)) && btrack->fN==(6-i)&&i<2){ Float_t sumchi2= 0; Float_t sumn = 0; if (maxLayer<3){ // take prim vertex as additional measurement if (normdist[itrack0]>0 && htrackc0){ sumchi2 += (3-maxLayer)*normdist[itrack0]*normdist[itrack0]; }else{ sumchi2 += (3-maxLayer)*(3*normdist[itrack0]*normdist[itrack0]+3.); } sumn += 3-maxLayer; } for (Int_t ilayer=i;ilayer<maxLayer;ilayer++){ sumn+=1.; if (!btrack->fClIndex[ilayer]){ sumchi2+=25; continue; }else{ sumchi2+=btrack->fDy[ilayer]*btrack->fDy[ilayer]/(btrack->fSigmaY[ilayer]*btrack->fSigmaY[ilayer]); sumchi2+=btrack->fDz[ilayer]*btrack->fDz[ilayer]/(btrack->fSigmaZ[ilayer]*btrack->fSigmaZ[ilayer]); } } sumchi2/=sumn; if (sumchi2<minchi2before0) minchi2before0=sumchi2; } continue; //safety space - Geo manager will give exact layer } track0b = btrack; minchi2after0 = btrack->fNormChi2[i]; break; } if (array1b) for (Int_t i=0;i<5;i++){ // best track after vertex AliITStrackMI * btrack = (AliITStrackMI*)array1b->At(i); if (!btrack) continue; if (btrack->fN>track1l->fN) track1l = btrack; // if (btrack->fX<pvertex->GetRr()-2-0.5/(0.1+pvertex->GetAnglep()[2])){ if (btrack->fX<pvertex->GetRr()-2){ if ((maxLayer>i+2 || (i==0))&&btrack->fN==(6-i)&&(i<2)){ Float_t sumchi2= 0; Float_t sumn = 0; if (maxLayer<3){ // take prim vertex as additional measurement if (normdist[itrack1]>0 && htrackc1){ sumchi2 += (3-maxLayer)*normdist[itrack1]*normdist[itrack1]; }else{ sumchi2 += (3-maxLayer)*(3*normdist[itrack1]*normdist[itrack1]+3.); } sumn += 3-maxLayer; } for (Int_t ilayer=i;ilayer<maxLayer;ilayer++){ sumn+=1.; if (!btrack->fClIndex[ilayer]){ sumchi2+=30; continue; }else{ sumchi2+=btrack->fDy[ilayer]*btrack->fDy[ilayer]/(btrack->fSigmaY[ilayer]*btrack->fSigmaY[ilayer]); sumchi2+=btrack->fDz[ilayer]*btrack->fDz[ilayer]/(btrack->fSigmaZ[ilayer]*btrack->fSigmaZ[ilayer]); } } sumchi2/=sumn; if (sumchi2<minchi2before1) minchi2before1=sumchi2; } continue; //safety space - Geo manager will give exact layer } track1b = btrack; minchi2after1 = btrack->fNormChi2[i]; break; } // // position resolution - used for DCA cut Float_t sigmad = track0b->fC00+track0b->fC11+track1b->fC00+track1b->fC11+ (track0b->fX-pvertex->GetRr())*(track0b->fX-pvertex->GetRr())*(track0b->fC22+track0b->fC33)+ (track1b->fX-pvertex->GetRr())*(track1b->fX-pvertex->GetRr())*(track1b->fC22+track1b->fC33); sigmad =TMath::Sqrt(sigmad)+0.04; if (pvertex->GetRr()>50){ Double_t cov0[15],cov1[15]; track0b->fESDtrack->GetInnerExternalCovariance(cov0); track1b->fESDtrack->GetInnerExternalCovariance(cov1); sigmad = cov0[0]+cov0[2]+cov1[0]+cov1[2]+ (80.-pvertex->GetRr())*(80.-pvertex->GetRr())*(cov0[5]+cov0[9])+ (80.-pvertex->GetRr())*(80.-pvertex->GetRr())*(cov1[5]+cov1[9]); sigmad =TMath::Sqrt(sigmad)+0.05; } // AliESDV0MI vertex2; vertex2.SetM(*track0b); vertex2.SetP(*track1b); vertex2.Update(primvertex); if (vertex2.GetDist2()<=pvertex->GetDist2()&&(vertex2.GetPointAngle()>=pvertex->GetPointAngle())){ pvertex->SetM(*track0b); pvertex->SetP(*track1b); pvertex->Update(primvertex); pvertex->SetClusters(track0b->fClIndex,track1b->fClIndex); // register clusters pvertex->SetIndex(0,track0->fESDtrack->GetID()); pvertex->SetIndex(1,track1->fESDtrack->GetID()); } pvertex->SetDistSigma(sigmad); pvertex->SetDistNorm(pvertex->GetDist2()/sigmad); pvertex->SetNormDCAPrim(normdist[itrack0],normdist[itrack1]); // // define likelihhod and causalities // Float_t pa0=1, pa1=1, pb0=0.26, pb1=0.26; if (maxLayer<1){ Float_t fnorm0 = normdist[itrack0]; if (fnorm0<0) fnorm0*=-3; Float_t fnorm1 = normdist[itrack1]; if (fnorm1<0) fnorm1*=-3; if (pvertex->GetAnglep()[2]>0.1 || (pvertex->GetRr()<10.5)&& pvertex->GetAnglep()[2]>0.05 || pvertex->GetRr()<3){ pb0 = TMath::Exp(-TMath::Min(fnorm0,Float_t(16.))/12.); pb1 = TMath::Exp(-TMath::Min(fnorm1,Float_t(16.))/12.); } pvertex->SetChi2Before(normdist[itrack0]); pvertex->SetChi2After(normdist[itrack1]); pvertex->SetNAfter(0); pvertex->SetNBefore(0); }else{ pvertex->SetChi2Before(minchi2before0); pvertex->SetChi2After(minchi2before1); if (pvertex->GetAnglep()[2]>0.1 || ( pvertex->GetRr()<10.5 && pvertex->GetAnglep()[2]>0.05) || pvertex->GetRr()<3){ pb0 = TMath::Exp(-TMath::Min(minchi2before0,Float_t(16))/12.); pb1 = TMath::Exp(-TMath::Min(minchi2before1,Float_t(16))/12.); } pvertex->SetNAfter(maxLayer); pvertex->SetNBefore(maxLayer); } if (pvertex->GetRr()<90){ pa0 *= TMath::Min(track0->fESDtrack->GetTPCdensity(0,60),Float_t(1.)); pa1 *= TMath::Min(track1->fESDtrack->GetTPCdensity(0,60),Float_t(1.)); } if (pvertex->GetRr()<20){ pa0 *= (0.2+TMath::Exp(-TMath::Min(minchi2after0,Float_t(16))/8.))/1.2; pa1 *= (0.2+TMath::Exp(-TMath::Min(minchi2after1,Float_t(16))/8.))/1.2; } // pvertex->SetCausality(pb0,pb1,pa0,pa1); // // Likelihood calculations - apply cuts // Bool_t v0OK = kTRUE; Float_t p12 = pvertex->GetParamP()->GetParameter()[4]*pvertex->GetParamP()->GetParameter()[4]; p12 += pvertex->GetParamM()->GetParameter()[4]*pvertex->GetParamM()->GetParameter()[4]; p12 = TMath::Sqrt(p12); // "mean" momenta Float_t sigmap0 = 0.0001+0.001/(0.1+pvertex->GetRr()); Float_t sigmap = 0.5*sigmap0*(0.6+0.4*p12); // "resolution: of point angle - as a function of radius and momenta Float_t causalityA = (1.0-pvertex->GetCausalityP()[0])*(1.0-pvertex->GetCausalityP()[1]); Float_t causalityB = TMath::Sqrt(TMath::Min(pvertex->GetCausalityP()[2],Float_t(0.7))* TMath::Min(pvertex->GetCausalityP()[3],Float_t(0.7))); // Float_t likelihood0 = (TMath::Exp(-pvertex->GetDistNorm())+0.1) *(pvertex->GetDist2()<0.5)*(pvertex->GetDistNorm()<5); Float_t likelihood1 = TMath::Exp(-(1.0001-pvertex->GetPointAngle())/sigmap)+ 0.4*TMath::Exp(-(1.0001-pvertex->GetPointAngle())/(4.*sigmap))+ 0.4*TMath::Exp(-(1.0001-pvertex->GetPointAngle())/(8.*sigmap))+ 0.1*TMath::Exp(-(1.0001-pvertex->GetPointAngle())/0.01); // if (causalityA<kCausality0Cut) v0OK = kFALSE; if (TMath::Sqrt(likelihood0*likelihood1)<kLikelihood01Cut) v0OK = kFALSE; if (likelihood1<kLikelihood1Cut) v0OK = kFALSE; if (TMath::Power(likelihood0*likelihood1*causalityB,0.33)<kCombinedCut) v0OK = kFALSE; // // if (kFALSE){ Bool_t gold = TMath::Abs(TMath::Abs(track0->GetLabel())-TMath::Abs(track1->GetLabel()))==1; cstream<<"It0"<< "Tr0.="<<track0<< //best without constrain "Tr1.="<<track1<< //best without constrain "Tr0B.="<<track0b<< //best without constrain after vertex "Tr1B.="<<track1b<< //best without constrain after vertex "Tr0C.="<<htrackc0<< //best with constrain if exist "Tr1C.="<<htrackc1<< //best with constrain if exist "Tr0L.="<<track0l<< //longest best "Tr1L.="<<track1l<< //longest best "Esd0.="<<track0->fESDtrack<< // esd track0 params "Esd1.="<<track1->fESDtrack<< // esd track1 params "V0.="<<pvertex<< //vertex properties "V0b.="<<&vertex2<< //vertex properties at "best" track "ND0="<<normdist[itrack0]<< //normalize distance for track0 "ND1="<<normdist[itrack1]<< //normalize distance for track1 "Gold="<<gold<< // // "RejectBase="<<rejectBase<< //rejection in First itteration "OK="<<v0OK<< "rmin="<<rmin<< "sigmad="<<sigmad<< "\n"; } //if (rejectBase) continue; // pvertex->SetStatus(0); // if (rejectBase) { // pvertex->SetStatus(-100); //} if (pvertex->GetPointAngle()>kMinPointAngle2) { pvertex->SetESDindexes(track0->fESDtrack->GetID(),track1->fESDtrack->GetID()); if (v0OK){ // AliV0vertex vertexjuri(*track0,*track1); // vertexjuri.SetESDindexes(track0->fESDtrack->GetID(),track1->fESDtrack->GetID()); // event->AddV0(&vertexjuri); pvertex->SetStatus(100); } event->AddV0MI(pvertex); } } } // // // delete temporary arrays // delete[] minPointAngle; delete[] maxr; delete[] minr; delete[] norm; delete[] normdist; delete[] normdist1; delete[] normdist0; delete[] dist; delete[] itsmap; delete[] helixes; delete pvertex; } void AliITStrackerMI::RefitV02(AliESD *event) { // //try to refit V0s in the third path of the reconstruction // TTreeSRedirector &cstream = *fDebugStreamer; // Int_t nv0s = event->GetNumberOfV0MIs(); Float_t primvertex[3]={GetX(),GetY(),GetZ()}; AliESDV0MI v0temp; for (Int_t iv0 = 0; iv0<nv0s;iv0++){ AliESDV0MI * v0mi = event->GetV0MI(iv0); if (!v0mi) continue; Int_t itrack0 = v0mi->GetIndex(0); Int_t itrack1 = v0mi->GetIndex(1); AliESDtrack *esd0 = event->GetTrack(itrack0); AliESDtrack *esd1 = event->GetTrack(itrack1); if (!esd0||!esd1) continue; AliITStrackMI tpc0(*esd0); AliITStrackMI tpc1(*esd1); Double_t alpha =TMath::ATan2(v0mi->GetXr(1),v0mi->GetXr(0)); if (v0mi->GetRr()>85){ if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ v0temp.SetM(tpc0); v0temp.SetP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetPointAngle()>v0mi->GetPointAngle()){ v0mi->SetM(tpc0); v0mi->SetP(tpc1); v0mi->Update(primvertex); } } continue; } if (v0mi->GetRr()>35){ CorrectForDeadZoneMaterial(&tpc0); CorrectForDeadZoneMaterial(&tpc1); if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ v0temp.SetM(tpc0); v0temp.SetP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetPointAngle()>v0mi->GetPointAngle()){ v0mi->SetM(tpc0); v0mi->SetP(tpc1); v0mi->Update(primvertex); } } continue; } CorrectForDeadZoneMaterial(&tpc0); CorrectForDeadZoneMaterial(&tpc1); // if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ if (RefitAt(v0mi->GetRr(),&tpc0, v0mi->GetClusters(0)) && RefitAt(v0mi->GetRr(),&tpc1, v0mi->GetClusters(1))){ v0temp.SetM(tpc0); v0temp.SetP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetPointAngle()>v0mi->GetPointAngle()){ v0mi->SetM(tpc0); v0mi->SetP(tpc1); v0mi->Update(primvertex); } } } } Setting impact parameters. Updating criteria (M.Ivanov) /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------- // Implementation of the ITS tracker class // It reads AliITSclusterV2 clusters and creates AliITStrackMI tracks // and fills with them the ESD // Origin: Marian Ivanov, CERN, Marian.Ivanov@cern.ch // dEdx analysis by: Boris Batyunya, JINR, Boris.Batiounia@cern.ch // //------------------------------------------------------------------------- #include <TMatrixD.h> #include <TTree.h> #include <TTreeStream.h> #include <TTree.h> #include "AliESD.h" #include "AliESDV0MI.h" #include "AliHelix.h" #include "AliITSclusterV2.h" #include "AliITSgeom.h" #include "AliITStrackerMI.h" ClassImp(AliITStrackerMI) AliITStrackerMI::AliITSlayer AliITStrackerMI::fgLayers[kMaxLayer]; // ITS layers AliITStrackerMI::AliITStrackerMI(const AliITSgeom *geom) : AliTracker() { //-------------------------------------------------------------------- //This is the AliITStrackerMI constructor //-------------------------------------------------------------------- fCoeficients = 0; fAfterV0 = kFALSE; AliITSgeom *g=(AliITSgeom*)geom; Float_t x,y,z; Int_t i; for (i=1; i<kMaxLayer+1; i++) { Int_t nlad=g->GetNladders(i); Int_t ndet=g->GetNdetectors(i); g->GetTrans(i,1,1,x,y,z); Double_t r=TMath::Sqrt(x*x + y*y); Double_t poff=TMath::ATan2(y,x); Double_t zoff=z; g->GetTrans(i,1,2,x,y,z); r += TMath::Sqrt(x*x + y*y); g->GetTrans(i,2,1,x,y,z); r += TMath::Sqrt(x*x + y*y); g->GetTrans(i,2,2,x,y,z); r += TMath::Sqrt(x*x + y*y); r*=0.25; new (fgLayers+i-1) AliITSlayer(r,poff,zoff,nlad,ndet); for (Int_t j=1; j<nlad+1; j++) { for (Int_t k=1; k<ndet+1; k++) { //Fill this layer with detectors Float_t x,y,zshift; g->GetTrans(i,j,k,x,y,zshift); Double_t rot[9]; g->GetRotMatrix(i,j,k,rot); Double_t phi=TMath::ATan2(rot[1],rot[0])+TMath::Pi(); phi+=TMath::Pi()/2; if (i==1) phi+=TMath::Pi(); Double_t cp=TMath::Cos(phi), sp=TMath::Sin(phi); Double_t r=x*cp+y*sp; AliITSdetector &det=fgLayers[i-1].GetDetector((j-1)*ndet + k-1); new(&det) AliITSdetector(r,phi); } } } fI=kMaxLayer; fPass=0; fConstraint[0]=1; fConstraint[1]=0; Double_t xyz[]={kXV,kYV,kZV}, ers[]={kSigmaXV,kSigmaYV,kSigmaZV}; SetVertex(xyz,ers); for (Int_t i=0; i<kMaxLayer; i++) fLayersNotToSkip[i]=kLayersNotToSkip[i]; fLastLayerToTrackTo=kLastLayerToTrackTo; for (Int_t i=0;i<100000;i++){ fBestTrackIndex[i]=0; } // fDebugStreamer = new TTreeSRedirector("ITSdebug.root"); } AliITStrackerMI::~AliITStrackerMI() { // //destructor // if (fCoeficients) delete []fCoeficients; if (fDebugStreamer) { //fDebugStreamer->Close(); delete fDebugStreamer; } } void AliITStrackerMI::SetLayersNotToSkip(Int_t *l) { //-------------------------------------------------------------------- //This function set masks of the layers which must be not skipped //-------------------------------------------------------------------- for (Int_t i=0; i<kMaxLayer; i++) fLayersNotToSkip[i]=l[i]; } Int_t AliITStrackerMI::LoadClusters(TTree *cTree) { //-------------------------------------------------------------------- //This function loads ITS clusters //-------------------------------------------------------------------- TBranch *branch=cTree->GetBranch("Clusters"); if (!branch) { Error("LoadClusters"," can't get the branch !\n"); return 1; } TClonesArray dummy("AliITSclusterV2",10000), *clusters=&dummy; branch->SetAddress(&clusters); Int_t j=0; Int_t detector=0; for (Int_t i=0; i<kMaxLayer; i++) { Int_t ndet=fgLayers[i].GetNdetectors(); Int_t jmax = j + fgLayers[i].GetNladders()*ndet; for (; j<jmax; j++) { if (!cTree->GetEvent(j)) continue; Int_t ncl=clusters->GetEntriesFast(); SignDeltas(clusters,GetZ()); while (ncl--) { AliITSclusterV2 *c=(AliITSclusterV2*)clusters->UncheckedAt(ncl); detector = c->GetDetectorIndex(); fgLayers[i].InsertCluster(new AliITSclusterV2(*c)); } clusters->Delete(); //add dead zone virtual "cluster" if (i<2){ for (Float_t ydead = 0; ydead < 1.31 ; ydead+=(i+1.)*0.018){ Int_t lab[4] = {0,0,0,detector}; Int_t info[3] = {0,0,0}; Float_t hit[5]={0,0,0.004/12.,0.001/12.,0}; if (i==0) hit[0] =ydead-0.4; if (i==1) hit[0]=ydead-3.75; hit[1] =-0.04; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); hit[1]=-7.05; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); hit[1]=-7.15; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); hit[1] =0.06; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); hit[1]=7.05; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); hit[1]=7.25; if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<2.) fgLayers[i].InsertCluster(new AliITSclusterV2(lab, hit, info)); } } } // fgLayers[i].ResetRoad(); //road defined by the cluster density fgLayers[i].SortClusters(); } return 0; } void AliITStrackerMI::UnloadClusters() { //-------------------------------------------------------------------- //This function unloads ITS clusters //-------------------------------------------------------------------- for (Int_t i=0; i<kMaxLayer; i++) fgLayers[i].ResetClusters(); } static Int_t CorrectForDeadZoneMaterial(AliITStrackMI *t) { //-------------------------------------------------------------------- // Correction for the material between the TPC and the ITS // (should it belong to the TPC code ?) //-------------------------------------------------------------------- Double_t riw=80., diw=0.0053, x0iw=30; // TPC inner wall ? Double_t rcd=61., dcd=0.0053, x0cd=30; // TPC "central drum" ? Double_t yr=12.8, dr=0.03; // rods ? Double_t zm=0.2, dm=0.40; // membrane //Double_t rr=52., dr=0.19, x0r=24., yyr=7.77; //rails Double_t rs=50., ds=0.001; // something belonging to the ITS (screen ?) if (t->GetX() > riw) { if (!t->PropagateTo(riw,diw,x0iw)) return 1; if (TMath::Abs(t->GetY())>yr) t->CorrectForMaterial(dr); if (TMath::Abs(t->GetZ())<zm) t->CorrectForMaterial(dm); if (!t->PropagateTo(rcd,dcd,x0cd)) return 1; //Double_t x,y,z; t->GetGlobalXYZat(rr,x,y,z); //if (TMath::Abs(y)<yyr) t->PropagateTo(rr,dr,x0r); if (!t->PropagateTo(rs,ds)) return 1; } else if (t->GetX() < rs) { if (!t->PropagateTo(rs,-ds)) return 1; //Double_t x,y,z; t->GetGlobalXYZat(rr,x,y,z); //if (TMath::Abs(y)<yyr) t->PropagateTo(rr,-dr,x0r); if (!t->PropagateTo(rcd,-dcd,x0cd)) return 1; if (!t->PropagateTo(riw+0.001,-diw,x0iw)) return 1; } else { ::Error("CorrectForDeadZoneMaterial","track is already in the dead zone !"); return 1; } return 0; } Int_t AliITStrackerMI::Clusters2Tracks(AliESD *event) { //-------------------------------------------------------------------- // This functions reconstructs ITS tracks // The clusters must be already loaded ! //-------------------------------------------------------------------- TObjArray itsTracks(15000); fOriginal.Clear(); fEsd = event; // store pointer to the esd {/* Read ESD tracks */ Int_t nentr=event->GetNumberOfTracks(); Info("Clusters2Tracks", "Number of ESD tracks: %d\n", nentr); while (nentr--) { AliESDtrack *esd=event->GetTrack(nentr); if ((esd->GetStatus()&AliESDtrack::kTPCin)==0) continue; if (esd->GetStatus()&AliESDtrack::kTPCout) continue; if (esd->GetStatus()&AliESDtrack::kITSin) continue; if (esd->GetKinkIndex(0)>0) continue; //kink daughter AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("Clusters2Tracks",msg); delete t; continue; } t->fD[0] = t->GetD(GetX(),GetY()); t->fD[1] = t->GetZat(GetX())-GetZ(); Double_t vdist = TMath::Sqrt(t->fD[0]*t->fD[0]+t->fD[1]*t->fD[1]); if (t->GetMass()<0.13) t->SetMass(0.13957); // MI look to the esd - mass hypothesys !!!!!!!!!!! // write expected q t->fExpQ = TMath::Max(0.8*t->fESDtrack->GetTPCsignal(),30.); if (esd->GetV0Index(0)>0 && t->fD[0]<30){ //track - can be V0 according to TPC } else{ if (TMath::Abs(t->fD[0])>10) { delete t; continue; } if (TMath::Abs(vdist)>20) { delete t; continue; } if (TMath::Abs(1/t->Get1Pt())<0.120) { delete t; continue; } if (CorrectForDeadZoneMaterial(t)!=0) { //Warning("Clusters2Tracks", // "failed to correct for the material in the dead zone !\n"); delete t; continue; } } t->fReconstructed = kFALSE; itsTracks.AddLast(t); fOriginal.AddLast(t); } } /* End Read ESD tracks */ itsTracks.Sort(); fOriginal.Sort(); Int_t nentr=itsTracks.GetEntriesFast(); fTrackHypothesys.Expand(nentr); fBestHypothesys.Expand(nentr); MakeCoeficients(nentr); Int_t ntrk=0; for (fPass=0; fPass<2; fPass++) { Int_t &constraint=fConstraint[fPass]; if (constraint<0) continue; for (Int_t i=0; i<nentr; i++) { // cerr<<fPass<<" "<<i<<'\r'; fCurrentEsdTrack = i; AliITStrackMI *t=(AliITStrackMI*)itsTracks.UncheckedAt(i); if (t==0) continue; //this track has been already tracked if (t->fReconstructed&&(t->fNUsed<1.5)) continue; //this track was already "succesfully" reconstructed if ( (TMath::Abs(t->GetD(GetX(),GetY())) >3.) && fConstraint[fPass]) continue; if ( (TMath::Abs(t->GetZat(GetX())-GetZ())>3.) && fConstraint[fPass]) continue; Int_t tpcLabel=t->GetLabel(); //save the TPC track label fI = 6; ResetTrackToFollow(*t); ResetBestTrack(); FollowProlongationTree(t,i,fConstraint[fPass]); SortTrackHypothesys(fCurrentEsdTrack,20,0); //MI change // AliITStrackMI * besttrack = GetBestHypothesys(fCurrentEsdTrack,t,15); if (!besttrack) continue; besttrack->SetLabel(tpcLabel); // besttrack->CookdEdx(); CookdEdx(besttrack); besttrack->fFakeRatio=1.; CookLabel(besttrack,0.); //For comparison only UpdateESDtrack(besttrack,AliESDtrack::kITSin); /* if ( besttrack->GetNumberOfClusters()<6 && fConstraint[fPass]) { continue; } if (besttrack->fChi2MIP[0]+besttrack->fNUsed>3.5) continue; if ( (TMath::Abs(besttrack->fD[0]*besttrack->fD[0]+besttrack->fD[1]*besttrack->fD[1])>0.1) && fConstraint[fPass]) continue; //delete itsTracks.RemoveAt(i); */ if (fConstraint[fPass]&&(!besttrack->IsGoldPrimary())) continue; //to be tracked also without vertex constrain t->fReconstructed = kTRUE; ntrk++; } GetBestHypothesysMIP(itsTracks); } //GetBestHypothesysMIP(itsTracks); UpdateTPCV0(event); FindV02(event); fAfterV0 = kTRUE; //GetBestHypothesysMIP(itsTracks); // itsTracks.Delete(); // Int_t entries = fTrackHypothesys.GetEntriesFast(); for (Int_t ientry=0;ientry<entries;ientry++){ TObjArray * array =(TObjArray*)fTrackHypothesys.UncheckedAt(ientry); if (array) array->Delete(); delete fTrackHypothesys.RemoveAt(ientry); } fTrackHypothesys.Delete(); fBestHypothesys.Delete(); fOriginal.Clear(); delete []fCoeficients; fCoeficients=0; Info("Clusters2Tracks","Number of prolonged tracks: %d\n",ntrk); return 0; } Int_t AliITStrackerMI::PropagateBack(AliESD *event) { //-------------------------------------------------------------------- // This functions propagates reconstructed ITS tracks back // The clusters must be loaded ! //-------------------------------------------------------------------- Int_t nentr=event->GetNumberOfTracks(); Info("PropagateBack", "Number of ESD tracks: %d\n", nentr); Int_t ntrk=0; for (Int_t i=0; i<nentr; i++) { AliESDtrack *esd=event->GetTrack(i); if ((esd->GetStatus()&AliESDtrack::kITSin)==0) continue; if (esd->GetStatus()&AliESDtrack::kITSout) continue; AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("PropagateBack",msg); delete t; continue; } t->fExpQ = TMath::Max(0.8*t->fESDtrack->GetTPCsignal(),30.); ResetTrackToFollow(*t); // propagete to vertex [SR, GSI 17.02.2003] // Start Time measurement [SR, GSI 17.02.2003], corrected by I.Belikov if (fTrackToFollow.PropagateTo(3.,0.0028,65.19)) { if (fTrackToFollow.PropagateToVertex()) { fTrackToFollow.StartTimeIntegral(); } fTrackToFollow.PropagateTo(3.,-0.0028,65.19); } fTrackToFollow.ResetCovariance(); fTrackToFollow.ResetClusters(); if (RefitAt(49.,&fTrackToFollow,t)) { if (CorrectForDeadZoneMaterial(&fTrackToFollow)!=0) { //Warning("PropagateBack", // "failed to correct for the material in the dead zone !\n"); delete t; continue; } fTrackToFollow.SetLabel(t->GetLabel()); //fTrackToFollow.CookdEdx(); CookLabel(&fTrackToFollow,0.); //For comparison only fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSout); //UseClusters(&fTrackToFollow); ntrk++; } delete t; } Info("PropagateBack","Number of back propagated ITS tracks: %d\n",ntrk); return 0; } Int_t AliITStrackerMI::RefitInward(AliESD *event) { //-------------------------------------------------------------------- // This functions refits ITS tracks using the // "inward propagated" TPC tracks // The clusters must be loaded ! //-------------------------------------------------------------------- RefitV02(event); Int_t nentr=event->GetNumberOfTracks(); Info("RefitInward", "Number of ESD tracks: %d\n", nentr); Int_t ntrk=0; for (Int_t i=0; i<nentr; i++) { AliESDtrack *esd=event->GetTrack(i); if ((esd->GetStatus()&AliESDtrack::kITSout) == 0) continue; if (esd->GetStatus()&AliESDtrack::kITSrefit) continue; if (esd->GetStatus()&AliESDtrack::kTPCout) if ((esd->GetStatus()&AliESDtrack::kTPCrefit)==0) continue; AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("RefitInward",msg); delete t; continue; } t->fExpQ = TMath::Max(0.8*t->fESDtrack->GetTPCsignal(),30.); if (CorrectForDeadZoneMaterial(t)!=0) { //Warning("RefitInward", // "failed to correct for the material in the dead zone !\n"); delete t; continue; } ResetTrackToFollow(*t); fTrackToFollow.ResetClusters(); if ((esd->GetStatus()&AliESDtrack::kTPCin)==0) fTrackToFollow.ResetCovariance(); //Refitting... if (RefitAt(3.7, &fTrackToFollow, t)) { fTrackToFollow.SetLabel(t->GetLabel()); // fTrackToFollow.CookdEdx(); CookdEdx(&fTrackToFollow); CookLabel(&fTrackToFollow,0.0); //For comparison only if (fTrackToFollow.PropagateTo(3.,0.0028,65.19)) {//The beam pipe Double_t a=fTrackToFollow.GetAlpha(); Double_t cs=TMath::Cos(a),sn=TMath::Sin(a); Double_t xv= GetX()*cs + GetY()*sn; Double_t yv=-GetX()*sn + GetY()*cs; Double_t c=fTrackToFollow.GetC(), snp=fTrackToFollow.GetSnp(); Double_t x=fTrackToFollow.GetX(), y=fTrackToFollow.GetY(); Double_t tgfv=-(c*(x-xv)-snp)/(c*(y-yv) + TMath::Sqrt(1.-snp*snp)); Double_t fv=TMath::ATan(tgfv); cs=TMath::Cos(fv); sn=TMath::Sin(fv); x = xv*cs + yv*sn; yv=-xv*sn + yv*cs; xv=x; if (fTrackToFollow.Propagate(fv+a,xv)) { fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSrefit); Float_t d=fTrackToFollow.GetD(GetX(),GetY()); Float_t z=fTrackToFollow.GetZ()-GetZ(); fTrackToFollow.GetESDtrack()->SetImpactParameters(d,z); //UseClusters(&fTrackToFollow); { AliITSclusterV2 c; c.SetY(yv); c.SetZ(GetZ()); c.SetSigmaY2(GetSigmaY()*GetSigmaY()); c.SetSigmaZ2(GetSigmaZ()*GetSigmaZ()); Double_t chi2=fTrackToFollow.GetPredictedChi2(&c); //Double_t chi2=GetPredictedChi2MI(&fTrackToFollow,&c,fI); if (chi2<kMaxChi2) if (fTrackToFollow.Update(&c,-chi2,0)) //if (UpdateMI(&fTrackToFollow,&c,-chi2,0)) fTrackToFollow.SetConstrainedESDtrack(chi2); } ntrk++; } } } delete t; } Info("RefitInward","Number of refitted tracks: %d\n",ntrk); return 0; } AliCluster *AliITStrackerMI::GetCluster(Int_t index) const { //-------------------------------------------------------------------- // Return pointer to a given cluster //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; return fgLayers[l].GetCluster(c); } void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdindex, Bool_t constrain) { //-------------------------------------------------------------------- // Follow prolongation tree //-------------------------------------------------------------------- // AliESDtrack * esd = otrack->fESDtrack; if (esd->GetV0Index(0)>0){ // // TEMPORARY SOLLUTION: map V0 indexes to point to proper track // mapping of esd track is different as its track in Containers // Need something more stable // Indexes are set back againg to the ESD track indexes in UpdateTPCV0 for (Int_t i=0;i<3;i++){ Int_t index = esd->GetV0Index(i); if (index==0) break; AliESDV0MI * vertex = fEsd->GetV0MI(index); if (vertex->GetStatus()<0) continue; // rejected V0 // if (esd->GetSign()>0) { vertex->SetIndex(0,esdindex); } else{ vertex->SetIndex(1,esdindex); } } } TObjArray *bestarray = (TObjArray*)fBestHypothesys.At(esdindex); if (!bestarray){ bestarray = new TObjArray(5); fBestHypothesys.AddAt(bestarray,esdindex); } // //setup tree of the prolongations // static AliITStrackMI tracks[7][100]; AliITStrackMI *currenttrack; static AliITStrackMI currenttrack1; static AliITStrackMI currenttrack2; static AliITStrackMI backuptrack; Int_t ntracks[7]; Int_t nindexes[7][100]; Float_t normalizedchi2[100]; for (Int_t ilayer=0;ilayer<6;ilayer++) ntracks[ilayer]=0; otrack->fNSkipped=0; new (&(tracks[6][0])) AliITStrackMI(*otrack); ntracks[6]=1; for (Int_t i=0;i<7;i++) nindexes[i][0]=0; // // // follow prolongations for (Int_t ilayer=5;ilayer>=0;ilayer--){ // AliITSlayer &layer=fgLayers[ilayer]; Double_t r=layer.GetR(); ntracks[ilayer]=0; // // Int_t nskipped=0; Float_t nused =0; for (Int_t itrack =0;itrack<ntracks[ilayer+1];itrack++){ //set current track if (ntracks[ilayer]>=100) break; if (tracks[ilayer+1][nindexes[ilayer+1][itrack]].fNSkipped>0) nskipped++; if (tracks[ilayer+1][nindexes[ilayer+1][itrack]].fNUsed>2.) nused++; if (ntracks[ilayer]>15+ilayer){ if (itrack>1&&tracks[ilayer+1][nindexes[ilayer+1][itrack]].fNSkipped>0 && nskipped>4+ilayer) continue; if (itrack>1&&tracks[ilayer+1][nindexes[ilayer+1][itrack]].fNUsed>2. && nused>3) continue; } new(&currenttrack1) AliITStrackMI(tracks[ilayer+1][nindexes[ilayer+1][itrack]]); if (ilayer==3 || ilayer==1) { Double_t rs=0.5*(fgLayers[ilayer+1].GetR() + r); Double_t d=0.0034, x0=38.6; if (ilayer==1) {rs=9.; d=0.0097; x0=42;} if (!currenttrack1.PropagateTo(rs,d,x0)) { continue; } } // //find intersection with layer Double_t x,y,z; if (!currenttrack1.GetGlobalXYZat(r,x,y,z)) { continue; } Double_t phi=TMath::ATan2(y,x); Int_t idet=layer.FindDetectorIndex(phi,z); if (idet<0) { continue; } //propagate to the intersection const AliITSdetector &det=layer.GetDetector(idet); phi=det.GetPhi(); new(&currenttrack2) AliITStrackMI(currenttrack1); if (!currenttrack1.Propagate(phi,det.GetR())) { continue; } currenttrack2.Propagate(phi,det.GetR()); // currenttrack1.SetDetectorIndex(idet); currenttrack2.SetDetectorIndex(idet); // // Double_t dz=7.5*TMath::Sqrt(currenttrack1.GetSigmaZ2() + 16.*kSigmaZ2[ilayer]); Double_t dy=7.5*TMath::Sqrt(currenttrack1.GetSigmaY2() + 16.*kSigmaY2[ilayer]); // Bool_t isBoundary=kFALSE; if (currenttrack1.GetY()-dy< det.GetYmin()+0.2) isBoundary = kTRUE; if (currenttrack1.GetY()+dy> det.GetYmax()-0.2) isBoundary = kTRUE; if (currenttrack1.GetZ()-dz< det.GetZmin()+0.2) isBoundary = kTRUE; if (currenttrack1.GetZ()+dz> det.GetZmax()-0.2) isBoundary = kTRUE; if (isBoundary){ // track at boundary between detectors Float_t maxtgl = TMath::Abs(currenttrack1.GetTgl()); if (maxtgl>1) maxtgl=1; dz = TMath::Sqrt(dz*dz+0.25*maxtgl*maxtgl); // Float_t maxsnp = TMath::Abs(currenttrack1.GetSnp()); if (maxsnp>0.95) continue; //if (maxsnp>0.5) maxsnp=0.5; dy=TMath::Sqrt(dy*dy+0.25*maxsnp*maxsnp); } Double_t zmin=currenttrack1.GetZ() - dz; Double_t zmax=currenttrack1.GetZ() + dz; Double_t ymin=currenttrack1.GetY() + r*phi - dy; Double_t ymax=currenttrack1.GetY() + r*phi + dy; layer.SelectClusters(zmin,zmax,ymin,ymax); // // loop over all possible prolongations // Double_t msz=1./((currenttrack1.GetSigmaZ2() + 16.*kSigmaZ2[ilayer])); Double_t msy=1./((currenttrack1.GetSigmaY2() + 16.*kSigmaY2[ilayer])); if (constrain){ msy/=60; msz/=60.; } else{ msy/=50; msz/=50.; } // const AliITSclusterV2 *c=0; Int_t ci=-1; Double_t chi2=12345.; Int_t deadzone=0; currenttrack = &currenttrack1; while ((c=layer.GetNextCluster(ci))!=0) { if (ntracks[ilayer]>95) break; //space for skipped clusters Bool_t change =kFALSE; if (c->GetQ()==0 && (deadzone==1)) continue; Int_t idet=c->GetDetectorIndex(); if (currenttrack->GetDetectorIndex()!=idet) { const AliITSdetector &det=layer.GetDetector(idet); Double_t y,z; if (!currenttrack2.GetProlongationFast(det.GetPhi(),det.GetR(),y,z)) continue; Float_t pz = (z - c->GetZ()) , py=(y - c->GetY()); if (pz*pz*msz+py*py*msy>1.) continue; // new (&backuptrack) AliITStrackMI(currenttrack2); change = kTRUE; currenttrack =&currenttrack2; if (!currenttrack->Propagate(det.GetPhi(),det.GetR())) { new (currenttrack) AliITStrackMI(backuptrack); change = kFALSE; continue; } currenttrack->SetDetectorIndex(idet); } else{ Float_t pz = (currenttrack->GetZ() - c->GetZ()) , py=(currenttrack->GetY() - c->GetY()); if (pz*pz*msz+py*py*msy>1.) continue; } chi2=GetPredictedChi2MI(currenttrack,c,ilayer); if (chi2<kMaxChi2s[ilayer]){ if (c->GetQ()==0) deadzone=1; // take dead zone only once if (ntracks[ilayer]>=100) continue; AliITStrackMI * updatetrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(*currenttrack); updatetrack->fClIndex[ilayer]=0; if (change){ new (&currenttrack2) AliITStrackMI(backuptrack); } if (c->GetQ()!=0){ if (!UpdateMI(updatetrack,c,chi2,(ilayer<<28)+ci)) continue; updatetrack->SetSampledEdx(c->GetQ(),updatetrack->GetNumberOfClusters()-1); //b.b. } else { updatetrack->fNDeadZone++; updatetrack->fDeadZoneProbability=GetDeadZoneProbability(updatetrack->GetZ(),TMath::Sqrt(updatetrack->GetSigmaZ2())); } if (c->IsUsed()){ updatetrack->fNUsed++; } Double_t x0; Double_t d=layer.GetThickness(updatetrack->GetY(),updatetrack->GetZ(),x0); updatetrack->CorrectForMaterial(d,x0); if (constrain) { updatetrack->fConstrain = constrain; fI = ilayer; Double_t d=GetEffectiveThickness(0,0); //Think of this !!!! Double_t xyz[]={GetX(),GetY(),GetZ()}; Double_t ptfactor = 1; Double_t ers[]={GetSigmaX()*ptfactor,GetSigmaY()*ptfactor,GetSigmaZ()}; Bool_t isPrim = kTRUE; if (ilayer<4){ updatetrack->fD[0] = updatetrack->GetD(GetX(),GetY()); updatetrack->fD[1] = updatetrack->GetZat(GetX())-GetZ(); if ( TMath::Abs(updatetrack->fD[0]/(1.+ilayer))>0.4 || TMath::Abs(updatetrack->fD[1]/(1.+ilayer))>0.4) isPrim=kFALSE; } if (isPrim) updatetrack->Improve(d,xyz,ers); } //apply vertex constrain ntracks[ilayer]++; } // create new hypothesy } // loop over possible cluster prolongation // if (constrain&&itrack<2&&currenttrack1.fNSkipped==0 && deadzone==0){ if (constrain&&itrack<2&&currenttrack1.fNSkipped==0 && deadzone==0&&ntracks[ilayer]<100){ AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1); vtrack->fClIndex[ilayer]=0; fI = ilayer; Double_t d=GetEffectiveThickness(0,0); //Think of this !!!! Double_t xyz[]={GetX(),GetY(),GetZ()}; Double_t ers[]={GetSigmaX(),GetSigmaY(),GetSigmaZ()}; vtrack->Improve(d,xyz,ers); vtrack->fNSkipped++; ntracks[ilayer]++; } if (constrain&&itrack<1&&TMath::Abs(currenttrack1.fP3)>1.1){ //big theta -- for low mult. runs AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1); vtrack->fClIndex[ilayer]=0; fI = ilayer; Double_t d=GetEffectiveThickness(0,0); //Think of this !!!! Double_t xyz[]={GetX(),GetY(),GetZ()}; Double_t ers[]={GetSigmaX(),GetSigmaY(),GetSigmaZ()}; vtrack->Improve(d,xyz,ers); vtrack->fNDeadZone++; ntracks[ilayer]++; } } //loop over track candidates // // Int_t accepted=0; Int_t golds=0; for (Int_t itrack=0;itrack<ntracks[ilayer];itrack++){ normalizedchi2[itrack] = NormalizedChi2(&tracks[ilayer][itrack],ilayer); if ( normalizedchi2[itrack]<3+0.5*ilayer) golds++; if (ilayer>4) accepted++; else{ if ( constrain && normalizedchi2[itrack]<kMaxNormChi2C[ilayer]+1) accepted++; if (!constrain && normalizedchi2[itrack]<kMaxNormChi2NonC[ilayer]+1) accepted++; } } TMath::Sort(ntracks[ilayer],normalizedchi2,nindexes[ilayer],kFALSE); ntracks[ilayer] = TMath::Min(accepted,7+2*ilayer); if (ntracks[ilayer]<golds+2+ilayer) ntracks[ilayer]=TMath::Min(golds+2+ilayer,accepted); if (ntracks[ilayer]>90) ntracks[ilayer]=90; } //loop over layers //printf("%d\t%d\t%d\t%d\t%d\t%d\n",ntracks[0],ntracks[1],ntracks[2],ntracks[3],ntracks[4],ntracks[5]); Int_t max = constrain? 20: 5; for (Int_t i=0;i<TMath::Min(max,ntracks[0]);i++) { AliITStrackMI & track= tracks[0][nindexes[0][i]]; if (track.GetNumberOfClusters()<2) continue; if (!constrain&&track.fNormChi2[0]>7.)continue; AddTrackHypothesys(new AliITStrackMI(track), esdindex); } for (Int_t i=0;i<TMath::Min(2,ntracks[1]);i++) { AliITStrackMI & track= tracks[1][nindexes[1][i]]; if (track.GetNumberOfClusters()<4) continue; if (!constrain&&track.fNormChi2[1]>7.)continue; if (constrain) track.fNSkipped+=1; if (!constrain) { track.fD[0] = track.GetD(GetX(),GetY()); track.fNSkipped+=4./(4.+8.*TMath::Abs(track.fD[0])); if (track.fN+track.fNDeadZone+track.fNSkipped>6) { track.fNSkipped = 6-track.fN+track.fNDeadZone; } } AddTrackHypothesys(new AliITStrackMI(track), esdindex); } //} if (!constrain){ for (Int_t i=0;i<TMath::Min(2,ntracks[2]);i++) { AliITStrackMI & track= tracks[2][nindexes[2][i]]; if (track.GetNumberOfClusters()<3) continue; if (!constrain&&track.fNormChi2[2]>7.)continue; if (constrain) track.fNSkipped+=2; if (!constrain){ track.fD[0] = track.GetD(GetX(),GetY()); track.fNSkipped+= 7./(7.+8.*TMath::Abs(track.fD[0])); if (track.fN+track.fNDeadZone+track.fNSkipped>6) { track.fNSkipped = 6-track.fN+track.fNDeadZone; } } AddTrackHypothesys(new AliITStrackMI(track), esdindex); } } if (!constrain){ // // register best tracks - important for V0 finder // for (Int_t ilayer=0;ilayer<5;ilayer++){ if (ntracks[ilayer]==0) continue; AliITStrackMI & track= tracks[ilayer][nindexes[ilayer][0]]; if (track.GetNumberOfClusters()<1) continue; CookLabel(&track,0); bestarray->AddAt(new AliITStrackMI(track),ilayer); } } // // update TPC V0 information // if (otrack->fESDtrack->GetV0Index(0)>0){ Float_t fprimvertex[3]={GetX(),GetY(),GetZ()}; for (Int_t i=0;i<3;i++){ Int_t index = otrack->fESDtrack->GetV0Index(i); if (index==0) break; AliESDV0MI * vertex = fEsd->GetV0MI(index); if (vertex->GetStatus()<0) continue; // rejected V0 // if (otrack->fP4>0) { vertex->SetIndex(0,esdindex); } else{ vertex->SetIndex(1,esdindex); } //find nearest layer with track info Int_t nearestold = GetNearestLayer(vertex->GetXrp()); Int_t nearest = nearestold; for (Int_t ilayer =nearest;ilayer<8;ilayer++){ if (ntracks[nearest]==0){ nearest = ilayer; } } // AliITStrackMI & track= tracks[nearest][nindexes[nearest][0]]; if (nearestold<5&&nearest<5){ Bool_t accept = track.fNormChi2[nearest]<10; if (accept){ if (track.fP4>0) { vertex->SetP(track); vertex->Update(fprimvertex); // vertex->SetIndex(0,track.fESDtrack->GetID()); if (track.GetNumberOfClusters()>2) AddTrackHypothesys(new AliITStrackMI(track), esdindex); }else{ vertex->SetM(track); vertex->Update(fprimvertex); //vertex->SetIndex(1,track.fESDtrack->GetID()); if (track.GetNumberOfClusters()>2) AddTrackHypothesys(new AliITStrackMI(track), esdindex); } vertex->SetStatus(vertex->GetStatus()+1); }else{ // vertex->SetStatus(-2); // reject V0 - not enough clusters } } // if (nearestold>3){ // Int_t indexlayer = (ntracks[0]>0)? 0:1; // if (ntracks[indexlayer]>0){ // AliITStrackMI & track= tracks[indexlayer][nindexes[indexlayer][0]]; // if (track.GetNumberOfClusters()>4&&track.fNormChi2[indexlayer]<4){ // vertex->SetStatus(-1); // reject V0 - clusters before // } // } // } } } } AliITStrackerMI::AliITSlayer & AliITStrackerMI::GetLayer(Int_t layer) const { //-------------------------------------------------------------------- // // return fgLayers[layer]; } AliITStrackerMI::AliITSlayer::AliITSlayer() { //-------------------------------------------------------------------- //default AliITSlayer constructor //-------------------------------------------------------------------- fN=0; fDetectors=0; fSkip = 0; fCurrentSlice=-1; for (Int_t i=0; i<kMaxClusterPerLayer;i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } } AliITStrackerMI::AliITSlayer:: AliITSlayer(Double_t r,Double_t p,Double_t z,Int_t nl,Int_t nd) { //-------------------------------------------------------------------- //main AliITSlayer constructor //-------------------------------------------------------------------- fR=r; fPhiOffset=p; fZOffset=z; fNladders=nl; fNdetectors=nd; fDetectors=new AliITSdetector[fNladders*fNdetectors]; fN=0; fI=0; fSkip = 0; fRoad=2*fR*TMath::Sqrt(3.14/1.);//assuming that there's only one cluster } AliITStrackerMI::AliITSlayer::~AliITSlayer() { //-------------------------------------------------------------------- // AliITSlayer destructor //-------------------------------------------------------------------- delete[] fDetectors; for (Int_t i=0; i<fN; i++) delete fClusters[i]; for (Int_t i=0; i<kMaxClusterPerLayer;i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } } void AliITStrackerMI::AliITSlayer::ResetClusters() { //-------------------------------------------------------------------- // This function removes loaded clusters //-------------------------------------------------------------------- for (Int_t i=0; i<fN; i++) delete fClusters[i]; for (Int_t i=0; i<kMaxClusterPerLayer;i++){ fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } fN=0; fI=0; } void AliITStrackerMI::AliITSlayer::ResetWeights() { //-------------------------------------------------------------------- // This function reset weights of the clusters //-------------------------------------------------------------------- for (Int_t i=0; i<kMaxClusterPerLayer;i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } for (Int_t i=0; i<fN;i++) { AliITSclusterV2 * cl = (AliITSclusterV2*)GetCluster(i); if (cl&&cl->IsUsed()) cl->Use(); } } void AliITStrackerMI::AliITSlayer::ResetRoad() { //-------------------------------------------------------------------- // This function calculates the road defined by the cluster density //-------------------------------------------------------------------- Int_t n=0; for (Int_t i=0; i<fN; i++) { if (TMath::Abs(fClusters[i]->GetZ())<fR) n++; } //if (n>1) fRoad=2*fR*TMath::Sqrt(3.14/n); if (n>1) fRoad=2*fR*TMath::Sqrt(3.14/n); } Int_t AliITStrackerMI::AliITSlayer::InsertCluster(AliITSclusterV2 *c) { //-------------------------------------------------------------------- //This function adds a cluster to this layer //-------------------------------------------------------------------- if (fN==kMaxClusterPerLayer) { ::Error("InsertCluster","Too many clusters !\n"); return 1; } fCurrentSlice=-1; fClusters[fN]=c; fN++; AliITSdetector &det=GetDetector(c->GetDetectorIndex()); if (c->GetY()<det.GetYmin()) det.SetYmin(c->GetY()); if (c->GetY()>det.GetYmax()) det.SetYmax(c->GetY()); if (c->GetZ()<det.GetZmin()) det.SetZmin(c->GetZ()); if (c->GetZ()>det.GetZmax()) det.SetZmax(c->GetZ()); return 0; } void AliITStrackerMI::AliITSlayer::SortClusters() { // //sort clusters // AliITSclusterV2 **clusters = new AliITSclusterV2*[fN]; Float_t *z = new Float_t[fN]; Int_t * index = new Int_t[fN]; // for (Int_t i=0;i<fN;i++){ z[i] = fClusters[i]->GetZ(); } TMath::Sort(fN,z,index,kFALSE); for (Int_t i=0;i<fN;i++){ clusters[i] = fClusters[index[i]]; } // for (Int_t i=0;i<fN;i++){ fClusters[i] = clusters[i]; fZ[i] = fClusters[i]->GetZ(); AliITSdetector &det=GetDetector(fClusters[i]->GetDetectorIndex()); Double_t y=fR*det.GetPhi() + fClusters[i]->GetY(); if (y>2.*fR*TMath::Pi()) y -= 2.*fR*TMath::Pi(); fY[i] = y; } delete[] index; delete[] z; delete[] clusters; // fYB[0]=10000000; fYB[1]=-10000000; for (Int_t i=0;i<fN;i++){ if (fY[i]<fYB[0]) fYB[0]=fY[i]; if (fY[i]>fYB[1]) fYB[1]=fY[i]; fClusterIndex[i] = i; } // // fill slices fDy5 = (fYB[1]-fYB[0])/5.; fDy10 = (fYB[1]-fYB[0])/10.; fDy20 = (fYB[1]-fYB[0])/20.; for (Int_t i=0;i<6;i++) fN5[i] =0; for (Int_t i=0;i<11;i++) fN10[i]=0; for (Int_t i=0;i<21;i++) fN20[i]=0; // for (Int_t i=0;i<6;i++) {fBy5[i][0] = fYB[0]+(i-0.75)*fDy5; fBy5[i][1] = fYB[0]+(i+0.75)*fDy5;} for (Int_t i=0;i<11;i++) {fBy10[i][0] = fYB[0]+(i-0.75)*fDy10; fBy10[i][1] = fYB[0]+(i+0.75)*fDy10;} for (Int_t i=0;i<21;i++) {fBy20[i][0] = fYB[0]+(i-0.75)*fDy20; fBy20[i][1] = fYB[0]+(i+0.75)*fDy20;} // // for (Int_t i=0;i<fN;i++) for (Int_t irot=-1;irot<=1;irot++){ Float_t curY = fY[i]+irot*TMath::TwoPi()*fR; // slice 5 for (Int_t slice=0; slice<6;slice++){ if (fBy5[slice][0]<curY && curY<fBy5[slice][1]&&fN5[slice]<kMaxClusterPerLayer5){ fClusters5[slice][fN5[slice]] = fClusters[i]; fY5[slice][fN5[slice]] = curY; fZ5[slice][fN5[slice]] = fZ[i]; fClusterIndex5[slice][fN5[slice]]=i; fN5[slice]++; } } // slice 10 for (Int_t slice=0; slice<11;slice++){ if (fBy10[slice][0]<curY && curY<fBy10[slice][1]&&fN10[slice]<kMaxClusterPerLayer10){ fClusters10[slice][fN10[slice]] = fClusters[i]; fY10[slice][fN10[slice]] = curY; fZ10[slice][fN10[slice]] = fZ[i]; fClusterIndex10[slice][fN10[slice]]=i; fN10[slice]++; } } // slice 20 for (Int_t slice=0; slice<21;slice++){ if (fBy20[slice][0]<curY && curY<fBy20[slice][1]&&fN20[slice]<kMaxClusterPerLayer20){ fClusters20[slice][fN20[slice]] = fClusters[i]; fY20[slice][fN20[slice]] = curY; fZ20[slice][fN20[slice]] = fZ[i]; fClusterIndex20[slice][fN20[slice]]=i; fN20[slice]++; } } } // // consistency check // for (Int_t i=0;i<fN-1;i++){ if (fZ[i]>fZ[i+1]){ printf("Bugg\n"); } } // for (Int_t slice=0;slice<21;slice++) for (Int_t i=0;i<fN20[slice]-1;i++){ if (fZ20[slice][i]>fZ20[slice][i+1]){ printf("Bugg\n"); } } } Int_t AliITStrackerMI::AliITSlayer::FindClusterIndex(Float_t z) const { //-------------------------------------------------------------------- // This function returns the index of the nearest cluster //-------------------------------------------------------------------- Int_t ncl=0; const Float_t *zcl; if (fCurrentSlice<0) { ncl = fN; zcl = fZ; } else{ ncl = fNcs; zcl = fZcs;; } if (ncl==0) return 0; Int_t b=0, e=ncl-1, m=(b+e)/2; for (; b<e; m=(b+e)/2) { // if (z > fClusters[m]->GetZ()) b=m+1; if (z > zcl[m]) b=m+1; else e=m; } return m; } void AliITStrackerMI::AliITSlayer:: SelectClusters(Double_t zmin,Double_t zmax,Double_t ymin, Double_t ymax) { //-------------------------------------------------------------------- // This function sets the "window" //-------------------------------------------------------------------- Double_t circle=2*TMath::Pi()*fR; fYmin = ymin; fYmax =ymax; Float_t ymiddle = (fYmin+fYmax)*0.5; if (ymiddle<fYB[0]) {fYmin+=circle; fYmax+=circle;ymiddle+=circle;} else{ if (ymiddle>fYB[1]) {fYmin-=circle; fYmax-=circle;ymiddle-=circle;} } // fCurrentSlice =-1; // defualt take all fClustersCs = fClusters; fClusterIndexCs = fClusterIndex; fYcs = fY; fZcs = fZ; fNcs = fN; // //is in 20 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy20){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy20); if (slice<0) slice=0; if (slice>20) slice=20; Bool_t isOK = (fYmin>fBy20[slice][0]&&fYmax<fBy20[slice][1]); if (isOK) { fCurrentSlice=slice; fClustersCs = fClusters20[fCurrentSlice]; fClusterIndexCs = fClusterIndex20[fCurrentSlice]; fYcs = fY20[fCurrentSlice]; fZcs = fZ20[fCurrentSlice]; fNcs = fN20[fCurrentSlice]; } } // //is in 10 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy10){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy10); if (slice<0) slice=0; if (slice>10) slice=10; Bool_t isOK = (fYmin>fBy10[slice][0]&&fYmax<fBy10[slice][1]); if (isOK) { fCurrentSlice=slice; fClustersCs = fClusters10[fCurrentSlice]; fClusterIndexCs = fClusterIndex10[fCurrentSlice]; fYcs = fY10[fCurrentSlice]; fZcs = fZ10[fCurrentSlice]; fNcs = fN10[fCurrentSlice]; } } // //is in 5 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy5){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy5); if (slice<0) slice=0; if (slice>5) slice=5; Bool_t isOK = (fYmin>fBy5[slice][0]&&fYmax<fBy5[slice][1]); if ( isOK){ fCurrentSlice=slice; fClustersCs = fClusters5[fCurrentSlice]; fClusterIndexCs = fClusterIndex5[fCurrentSlice]; fYcs = fY5[fCurrentSlice]; fZcs = fZ5[fCurrentSlice]; fNcs = fN5[fCurrentSlice]; } } // fI=FindClusterIndex(zmin); fZmax=zmax; fImax = TMath::Min(FindClusterIndex(zmax)+1,fNcs); fSkip = 0; fAccepted =0; } Int_t AliITStrackerMI::AliITSlayer:: FindDetectorIndex(Double_t phi, Double_t z) const { //-------------------------------------------------------------------- //This function finds the detector crossed by the track //-------------------------------------------------------------------- Double_t dphi=-(phi-fPhiOffset); if (dphi < 0) dphi += 2*TMath::Pi(); else if (dphi >= 2*TMath::Pi()) dphi -= 2*TMath::Pi(); Int_t np=Int_t(dphi*fNladders*0.5/TMath::Pi()+0.5); if (np>=fNladders) np-=fNladders; if (np<0) np+=fNladders; Double_t dz=fZOffset-z; Int_t nz=Int_t(dz*(fNdetectors-1)*0.5/fZOffset+0.5); if (nz>=fNdetectors) return -1; if (nz<0) return -1; return np*fNdetectors + nz; } const AliITSclusterV2 *AliITStrackerMI::AliITSlayer::GetNextCluster(Int_t &ci){ //-------------------------------------------------------------------- // This function returns clusters within the "window" //-------------------------------------------------------------------- if (fCurrentSlice<0){ Double_t rpi2 = 2.*fR*TMath::Pi(); for (Int_t i=fI; i<fImax; i++) { Double_t y = fY[i]; if (fYmax<y) y -= rpi2; if (fYmin>y) y += rpi2; if (y<fYmin) continue; if (y>fYmax) continue; if (fClusters[i]->GetQ()==0&&fSkip==2) continue; ci=i; fI=i+1; return fClusters[i]; } } else{ for (Int_t i=fI; i<fImax; i++) { if (fYcs[i]<fYmin) continue; if (fYcs[i]>fYmax) continue; if (fClustersCs[i]->GetQ()==0&&fSkip==2) continue; ci=fClusterIndexCs[i]; fI=i+1; return fClustersCs[i]; } } return 0; } Double_t AliITStrackerMI::AliITSlayer::GetThickness(Double_t y,Double_t z,Double_t &x0) const { //-------------------------------------------------------------------- //This function returns the layer thickness at this point (units X0) //-------------------------------------------------------------------- Double_t d=0.0085; x0=21.82; if (43<fR&&fR<45) { //SSD2 Double_t dd=0.0034; d=dd; if (TMath::Abs(y-0.00)>3.40) d+=dd; if (TMath::Abs(y-1.90)<0.45) {d+=(0.013-0.0034);} if (TMath::Abs(y+1.90)<0.45) {d+=(0.013-0.0034);} for (Int_t i=0; i<12; i++) { if (TMath::Abs(z-3.9*(i+0.5))<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=0.0034; break; } if (TMath::Abs(z+3.9*(i+0.5))<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=0.0034; break; } if (TMath::Abs(z-3.4-3.9*i)<0.50) {d+=(0.016-0.0034); break;} if (TMath::Abs(z+0.5+3.9*i)<0.50) {d+=(0.016-0.0034); break;} } } else if (37<fR&&fR<41) { //SSD1 Double_t dd=0.0034; d=dd; if (TMath::Abs(y-0.00)>3.40) d+=dd; if (TMath::Abs(y-1.90)<0.45) {d+=(0.013-0.0034);} if (TMath::Abs(y+1.90)<0.45) {d+=(0.013-0.0034);} for (Int_t i=0; i<11; i++) { if (TMath::Abs(z-3.9*i)<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=dd; break; } if (TMath::Abs(z+3.9*i)<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=dd; break; } if (TMath::Abs(z-1.85-3.9*i)<0.50) {d+=(0.016-0.0034); break;} if (TMath::Abs(z+2.05+3.9*i)<0.50) {d+=(0.016-0.0034); break;} } } else if (13<fR&&fR<26) { //SDD Double_t dd=0.0033; d=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; if (TMath::Abs(y-1.80)<0.55) { d+=0.016; for (Int_t j=0; j<20; j++) { if (TMath::Abs(z+0.7+1.47*j)<0.12) {d+=0.08; x0=9.; break;} if (TMath::Abs(z-0.7-1.47*j)<0.12) {d+=0.08; x0=9.; break;} } } if (TMath::Abs(y+1.80)<0.55) { d+=0.016; for (Int_t j=0; j<20; j++) { if (TMath::Abs(z-0.7-1.47*j)<0.12) {d+=0.08; x0=9.; break;} if (TMath::Abs(z+0.7+1.47*j)<0.12) {d+=0.08; x0=9.; break;} } } for (Int_t i=0; i<4; i++) { if (TMath::Abs(z-7.3*i)<0.60) { d+=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; break; } if (TMath::Abs(z+7.3*i)<0.60) { d+=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; break; } } } else if (6<fR&&fR<8) { //SPD2 Double_t dd=0.0063; x0=21.5; d=dd; if (TMath::Abs(y-3.08)>0.5) d+=dd; //if (TMath::Abs(y-3.08)>0.45) d+=dd; if (TMath::Abs(y-3.03)<0.10) {d+=0.014;} } else if (3<fR&&fR<5) { //SPD1 Double_t dd=0.0063; x0=21.5; d=dd; if (TMath::Abs(y+0.21)>0.6) d+=dd; //if (TMath::Abs(y+0.21)>0.45) d+=dd; if (TMath::Abs(y+0.10)<0.10) {d+=0.014;} } return d; } Double_t AliITStrackerMI::GetEffectiveThickness(Double_t y,Double_t z) const { //-------------------------------------------------------------------- //Returns the thickness between the current layer and the vertex (units X0) //-------------------------------------------------------------------- Double_t d=0.0028*3*3; //beam pipe Double_t x0=0; Double_t xn=fgLayers[fI].GetR(); for (Int_t i=0; i<fI; i++) { Double_t xi=fgLayers[i].GetR(); d+=fgLayers[i].GetThickness(y,z,x0)*xi*xi; } if (fI>1) { Double_t xi=9.; d+=0.0097*xi*xi; } if (fI>3) { Double_t xi=0.5*(fgLayers[3].GetR()+fgLayers[4].GetR()); d+=0.0034*xi*xi; } return d/(xn*xn); } Int_t AliITStrackerMI::AliITSlayer::InRoad() const { //-------------------------------------------------------------------- // This function returns number of clusters within the "window" //-------------------------------------------------------------------- Int_t ncl=0; for (Int_t i=fI; i<fN; i++) { const AliITSclusterV2 *c=fClusters[i]; if (c->GetZ() > fZmax) break; if (c->IsUsed()) continue; const AliITSdetector &det=GetDetector(c->GetDetectorIndex()); Double_t y=fR*det.GetPhi() + c->GetY(); if (y>2.*fR*TMath::Pi()) y -= 2*fR*TMath::Pi(); if (y>1.*fR*TMath::Pi() && fYmax<y) y -= 2*fR*TMath::Pi(); if (y<fYmin) continue; if (y>fYmax) continue; ncl++; } return ncl; } Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *t,const AliITStrackMI *c) { //-------------------------------------------------------------------- // This function refits the track "t" at the position "x" using // the clusters from "c" //-------------------------------------------------------------------- Int_t index[kMaxLayer]; Int_t k; for (k=0; k<kMaxLayer; k++) index[k]=-1; Int_t nc=c->GetNumberOfClusters(); for (k=0; k<nc; k++) { Int_t idx=c->GetClusterIndex(k),nl=(idx&0xf0000000)>>28; index[nl]=idx; } Int_t from, to, step; if (xx > t->GetX()) { from=0; to=kMaxLayer; step=+1; } else { from=kMaxLayer-1; to=-1; step=-1; } for (Int_t i=from; i != to; i += step) { AliITSlayer &layer=fgLayers[i]; Double_t r=layer.GetR(); { Double_t hI=i-0.5*step; if (TMath::Abs(hI-1.5)<0.01 || TMath::Abs(hI-3.5)<0.01) { Double_t rs=0.5*(fgLayers[i-step].GetR() + r); Double_t d=0.0034, x0=38.6; if (TMath::Abs(hI-1.5)<0.01) {rs=9.; d=0.0097; x0=42;} if (!t->PropagateTo(rs,-step*d,x0)) { return kFALSE; } } } // remember old position [SR, GSI 18.02.2003] Double_t oldX=0., oldY=0., oldZ=0.; if (t->IsStartedTimeIntegral() && step==1) { t->GetGlobalXYZat(t->GetX(),oldX,oldY,oldZ); } // Double_t x,y,z; if (!t->GetGlobalXYZat(r,x,y,z)) { return kFALSE; } Double_t phi=TMath::ATan2(y,x); Int_t idet=layer.FindDetectorIndex(phi,z); if (idet<0) { return kFALSE; } const AliITSdetector &det=layer.GetDetector(idet); phi=det.GetPhi(); if (!t->Propagate(phi,det.GetR())) { return kFALSE; } t->SetDetectorIndex(idet); const AliITSclusterV2 *cl=0; Double_t maxchi2=1000.*kMaxChi2; Int_t idx=index[i]; if (idx>0) { const AliITSclusterV2 *c=(AliITSclusterV2 *)GetCluster(idx); if (c){ if (idet != c->GetDetectorIndex()) { idet=c->GetDetectorIndex(); const AliITSdetector &det=layer.GetDetector(idet); if (!t->Propagate(det.GetPhi(),det.GetR())) { return kFALSE; } t->SetDetectorIndex(idet); } //Double_t chi2=t->GetPredictedChi2(c); Int_t layer = (idx & 0xf0000000) >> 28;; Double_t chi2=GetPredictedChi2MI(t,c,layer); if (chi2<maxchi2) { cl=c; maxchi2=chi2; } else { return kFALSE; } } } /* if (cl==0) if (t->GetNumberOfClusters()>2) { Double_t dz=4*TMath::Sqrt(t->GetSigmaZ2()+kSigmaZ2[i]); Double_t dy=4*TMath::Sqrt(t->GetSigmaY2()+kSigmaY2[i]); Double_t zmin=t->GetZ() - dz; Double_t zmax=t->GetZ() + dz; Double_t ymin=t->GetY() + phi*r - dy; Double_t ymax=t->GetY() + phi*r + dy; layer.SelectClusters(zmin,zmax,ymin,ymax); const AliITSclusterV2 *c=0; Int_t ci=-1; while ((c=layer.GetNextCluster(ci))!=0) { if (idet != c->GetDetectorIndex()) continue; Double_t chi2=t->GetPredictedChi2(c); if (chi2<maxchi2) { cl=c; maxchi2=chi2; idx=ci; } } } */ if (cl) { //if (!t->Update(cl,maxchi2,idx)) { if (!UpdateMI(t,cl,maxchi2,idx)) { return kFALSE; } t->SetSampledEdx(cl->GetQ(),t->GetNumberOfClusters()-1); } { Double_t x0; Double_t d=layer.GetThickness(t->GetY(),t->GetZ(),x0); t->CorrectForMaterial(-step*d,x0); } // track time update [SR, GSI 17.02.2003] if (t->IsStartedTimeIntegral() && step==1) { Double_t newX, newY, newZ; t->GetGlobalXYZat(t->GetX(),newX,newY,newZ); Double_t dL2 = (oldX-newX)*(oldX-newX) + (oldY-newY)*(oldY-newY) + (oldZ-newZ)*(oldZ-newZ); t->AddTimeStep(TMath::Sqrt(dL2)); } // } if (!t->PropagateTo(xx,0.,0.)) return kFALSE; return kTRUE; } Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *t,const Int_t *clindex) { //-------------------------------------------------------------------- // This function refits the track "t" at the position "x" using // the clusters from array //-------------------------------------------------------------------- Int_t index[kMaxLayer]; Int_t k; for (k=0; k<kMaxLayer; k++) index[k]=-1; // for (k=0; k<kMaxLayer; k++) { index[k]=clindex[k]; } Int_t from, to, step; if (xx > t->GetX()) { from=0; to=kMaxLayer; step=+1; } else { from=kMaxLayer-1; to=-1; step=-1; } for (Int_t i=from; i != to; i += step) { AliITSlayer &layer=fgLayers[i]; Double_t r=layer.GetR(); if (step<0 && xx>r) break; // { Double_t hI=i-0.5*step; if (TMath::Abs(hI-1.5)<0.01 || TMath::Abs(hI-3.5)<0.01) { Double_t rs=0.5*(fgLayers[i-step].GetR() + r); Double_t d=0.0034, x0=38.6; if (TMath::Abs(hI-1.5)<0.01) {rs=9.; d=0.0097; x0=42;} if (!t->PropagateTo(rs,-step*d,x0)) { return kFALSE; } } } // remember old position [SR, GSI 18.02.2003] Double_t oldX=0., oldY=0., oldZ=0.; if (t->IsStartedTimeIntegral() && step==1) { t->GetGlobalXYZat(t->GetX(),oldX,oldY,oldZ); } // Double_t x,y,z; if (!t->GetGlobalXYZat(r,x,y,z)) { return kFALSE; } Double_t phi=TMath::ATan2(y,x); Int_t idet=layer.FindDetectorIndex(phi,z); if (idet<0) { return kFALSE; } const AliITSdetector &det=layer.GetDetector(idet); phi=det.GetPhi(); if (!t->Propagate(phi,det.GetR())) { return kFALSE; } t->SetDetectorIndex(idet); const AliITSclusterV2 *cl=0; Double_t maxchi2=1000.*kMaxChi2; Int_t idx=index[i]; if (idx>0) { const AliITSclusterV2 *c=(AliITSclusterV2 *)GetCluster(idx); if (c){ if (idet != c->GetDetectorIndex()) { idet=c->GetDetectorIndex(); const AliITSdetector &det=layer.GetDetector(idet); if (!t->Propagate(det.GetPhi(),det.GetR())) { return kFALSE; } t->SetDetectorIndex(idet); } //Double_t chi2=t->GetPredictedChi2(c); Int_t layer = (idx & 0xf0000000) >> 28;; Double_t chi2=GetPredictedChi2MI(t,c,layer); if (chi2<maxchi2) { cl=c; maxchi2=chi2; } else { return kFALSE; } } } /* if (cl==0) if (t->GetNumberOfClusters()>2) { Double_t dz=4*TMath::Sqrt(t->GetSigmaZ2()+kSigmaZ2[i]); Double_t dy=4*TMath::Sqrt(t->GetSigmaY2()+kSigmaY2[i]); Double_t zmin=t->GetZ() - dz; Double_t zmax=t->GetZ() + dz; Double_t ymin=t->GetY() + phi*r - dy; Double_t ymax=t->GetY() + phi*r + dy; layer.SelectClusters(zmin,zmax,ymin,ymax); const AliITSclusterV2 *c=0; Int_t ci=-1; while ((c=layer.GetNextCluster(ci))!=0) { if (idet != c->GetDetectorIndex()) continue; Double_t chi2=t->GetPredictedChi2(c); if (chi2<maxchi2) { cl=c; maxchi2=chi2; idx=ci; } } } */ if (cl) { //if (!t->Update(cl,maxchi2,idx)) { if (!UpdateMI(t,cl,maxchi2,idx)) { return kFALSE; } t->SetSampledEdx(cl->GetQ(),t->GetNumberOfClusters()-1); } { Double_t x0; Double_t d=layer.GetThickness(t->GetY(),t->GetZ(),x0); t->CorrectForMaterial(-step*d,x0); } // track time update [SR, GSI 17.02.2003] if (t->IsStartedTimeIntegral() && step==1) { Double_t newX, newY, newZ; t->GetGlobalXYZat(t->GetX(),newX,newY,newZ); Double_t dL2 = (oldX-newX)*(oldX-newX) + (oldY-newY)*(oldY-newY) + (oldZ-newZ)*(oldZ-newZ); t->AddTimeStep(TMath::Sqrt(dL2)); } // } if (!t->PropagateTo(xx,0.,0.)) return kFALSE; return kTRUE; } Double_t AliITStrackerMI::GetNormalizedChi2(AliITStrackMI * track, Int_t mode) { // // calculate normalized chi2 // return NormalizedChi2(track,0); Float_t chi2 = 0; Float_t sum=0; Float_t *erry = GetErrY(fCurrentEsdTrack), *errz = GetErrZ(fCurrentEsdTrack); // track->fdEdxMismatch=0; Float_t dedxmismatch =0; Float_t *ny = GetNy(fCurrentEsdTrack), *nz = GetNz(fCurrentEsdTrack); if (mode<100){ for (Int_t i = 0;i<6;i++){ if (track->fClIndex[i]>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->fSigmaY[i]; cerrz = track->fSigmaZ[i];} cerry*=cerry; cerrz*=cerrz; Float_t cchi2 = (track->fDy[i]*track->fDy[i]/cerry)+(track->fDz[i]*track->fDz[i]/cerrz); if (i>1){ Float_t ratio = track->fNormQ[i]/track->fExpQ; if (ratio<0.5) { cchi2+=(0.5-ratio)*10.; //track->fdEdxMismatch+=(0.5-ratio)*10.; dedxmismatch+=(0.5-ratio)*10.; } } if (i<2 ||i>3){ AliITSclusterV2 * cl = (AliITSclusterV2*)GetCluster( track->fClIndex[i]); Double_t delta = cl->GetNy()+cl->GetNz()-ny[i]-nz[i]; if (delta>1) chi2 +=0.5*TMath::Min(delta/2,2.); if (i<2) chi2+=2*cl->GetDeltaProbability(); } chi2+=cchi2; sum++; } } if (TMath::Abs(track->fdEdxMismatch-dedxmismatch)>0.0001){ track->fdEdxMismatch = dedxmismatch; } } else{ for (Int_t i = 0;i<4;i++){ if (track->fClIndex[i]>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->fSigmaY[i]; cerrz = track->fSigmaZ[i];} cerry*=cerry; cerrz*=cerrz; chi2+= (track->fDy[i]*track->fDy[i]/cerry); chi2+= (track->fDz[i]*track->fDz[i]/cerrz); sum++; } } for (Int_t i = 4;i<6;i++){ if (track->fClIndex[i]>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->fSigmaY[i]; cerrz = track->fSigmaZ[i];} cerry*=cerry; cerrz*=cerrz; Float_t cerryb, cerrzb; if (ny[i+6]>0) {cerryb = erry[i+6]; cerrzb=errz[i+6];} else { cerryb= track->fSigmaY[i+6]; cerrzb = track->fSigmaZ[i+6];} cerryb*=cerryb; cerrzb*=cerrzb; chi2+= TMath::Min((track->fDy[i+6]*track->fDy[i+6]/cerryb),track->fDy[i]*track->fDy[i]/cerry); chi2+= TMath::Min((track->fDz[i+6]*track->fDz[i+6]/cerrzb),track->fDz[i]*track->fDz[i]/cerrz); sum++; } } } if (track->fESDtrack->GetTPCsignal()>85){ Float_t ratio = track->fdEdx/track->fESDtrack->GetTPCsignal(); if (ratio<0.5) { chi2+=(0.5-ratio)*5.; } if (ratio>2){ chi2+=(ratio-2.0)*3; } } // Double_t match = TMath::Sqrt(track->fChi22); if (track->fConstrain) match/=track->GetNumberOfClusters(); if (!track->fConstrain) match/=track->GetNumberOfClusters()-2.; if (match<0) match=0; Float_t deadzonefactor = (track->fNDeadZone>0) ? 3*(1.1-track->fDeadZoneProbability):0.; Double_t normchi2 = 2*track->fNSkipped+match+deadzonefactor+(1+(2*track->fNSkipped+deadzonefactor)/track->GetNumberOfClusters())* (chi2)/TMath::Max(double(sum-track->fNSkipped), 1./(1.+track->fNSkipped)); return normchi2; } Double_t AliITStrackerMI::GetMatchingChi2(AliITStrackMI * track1, AliITStrackMI * track2) { // // return matching chi2 between two tracks AliITStrackMI track3(*track2); track3.Propagate(track1->GetAlpha(),track1->GetX()); TMatrixD vec(5,1); vec(0,0)=track1->fP0-track3.fP0; vec(1,0)=track1->fP1-track3.fP1; vec(2,0)=track1->fP2-track3.fP2; vec(3,0)=track1->fP3-track3.fP3; vec(4,0)=track1->fP4-track3.fP4; // TMatrixD cov(5,5); cov(0,0) = track1->fC00+track3.fC00; cov(1,1) = track1->fC11+track3.fC11; cov(2,2) = track1->fC22+track3.fC22; cov(3,3) = track1->fC33+track3.fC33; cov(4,4) = track1->fC44+track3.fC44; cov(0,1)=cov(1,0) = track1->fC10+track3.fC10; cov(0,2)=cov(2,0) = track1->fC20+track3.fC20; cov(0,3)=cov(3,0) = track1->fC30+track3.fC30; cov(0,4)=cov(4,0) = track1->fC40+track3.fC40; // cov(1,2)=cov(2,1) = track1->fC21+track3.fC21; cov(1,3)=cov(3,1) = track1->fC31+track3.fC31; cov(1,4)=cov(4,1) = track1->fC41+track3.fC41; // cov(2,3)=cov(3,2) = track1->fC32+track3.fC32; cov(2,4)=cov(4,2) = track1->fC42+track3.fC42; // cov(3,4)=cov(4,3) = track1->fC43+track3.fC43; cov.Invert(); TMatrixD vec2(cov,TMatrixD::kMult,vec); TMatrixD chi2(vec2,TMatrixD::kTransposeMult,vec); return chi2(0,0); } Double_t AliITStrackerMI::GetDeadZoneProbability(Double_t zpos, Double_t zerr) { // // return probability that given point - characterized by z position and error is in dead zone // Double_t probability =0; Double_t absz = TMath::Abs(zpos); Double_t nearestz = (absz<2)? 0.:7.1; if (TMath::Abs(absz-nearestz)>0.25+3*zerr) return 0; Double_t zmin=0, zmax=0; if (zpos<-6.){ zmin = -7.25; zmax = -6.95; } if (zpos>6){ zmin = 7.0; zmax =7.3; } if (absz<2){ zmin = -0.75; zmax = 1.5; } probability = (TMath::Erf((zpos-zmin)/zerr) - TMath::Erf((zpos-zmax)/zerr))*0.5; return probability; } Double_t AliITStrackerMI::GetTruncatedChi2(AliITStrackMI * track, Float_t fac) { // // calculate normalized chi2 Float_t chi2[6]; Float_t *erry = GetErrY(fCurrentEsdTrack), *errz = GetErrZ(fCurrentEsdTrack); Float_t ncl = 0; for (Int_t i = 0;i<6;i++){ if (TMath::Abs(track->fDy[i])>0){ chi2[i]= (track->fDy[i]/erry[i])*(track->fDy[i]/erry[i]); chi2[i]+= (track->fDz[i]/errz[i])*(track->fDz[i]/errz[i]); ncl++; } else{chi2[i]=10000;} } Int_t index[6]; TMath::Sort(6,chi2,index,kFALSE); Float_t max = float(ncl)*fac-1.; Float_t sumchi=0, sumweight=0; for (Int_t i=0;i<max+1;i++){ Float_t weight = (i<max)?1.:(max+1.-i); sumchi+=weight*chi2[index[i]]; sumweight+=weight; } Double_t normchi2 = sumchi/sumweight; return normchi2; } Double_t AliITStrackerMI::GetInterpolatedChi2(AliITStrackMI * forwardtrack, AliITStrackMI * backtrack) { // // calculate normalized chi2 // if (forwardtrack->fNUsed>0.3*float(forwardtrack->GetNumberOfClusters())) return 10000; Int_t npoints = 0; Double_t res =0; for (Int_t i=0;i<6;i++){ if ( (backtrack->fSigmaY[i]<0.000000001) || (forwardtrack->fSigmaY[i]<0.000000001)) continue; Double_t sy1 = forwardtrack->fSigmaY[i]; Double_t sz1 = forwardtrack->fSigmaZ[i]; Double_t sy2 = backtrack->fSigmaY[i]; Double_t sz2 = backtrack->fSigmaZ[i]; if (i<2){ sy2=1000.;sz2=1000;} // Double_t dy0 = (forwardtrack->fDy[i]/(sy1*sy1) +backtrack->fDy[i]/(sy2*sy2))/(1./(sy1*sy1)+1./(sy2*sy2)); Double_t dz0 = (forwardtrack->fDz[i]/(sz1*sz1) +backtrack->fDz[i]/(sz2*sz2))/(1./(sz1*sz1)+1./(sz2*sz2)); // Double_t nz0 = dz0*TMath::Sqrt((1./(sz1*sz1)+1./(sz2*sz2))); Double_t ny0 = dy0*TMath::Sqrt((1./(sy1*sy1)+1./(sy2*sy2))); // res+= nz0*nz0+ny0*ny0; npoints++; } if (npoints>1) return TMath::Max(TMath::Abs(0.3*forwardtrack->Get1Pt())-0.5,0.)+ //2*forwardtrack->fNUsed+ res/TMath::Max(double(npoints-forwardtrack->fNSkipped), 1./(1.+forwardtrack->fNSkipped)); return 1000; } Float_t *AliITStrackerMI::GetWeight(Int_t index) { //-------------------------------------------------------------------- // Return pointer to a given cluster //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; return fgLayers[l].GetWeight(c); } void AliITStrackerMI::RegisterClusterTracks(AliITStrackMI* track,Int_t id) { //--------------------------------------------- // register track to the list // if (track->fESDtrack->GetKinkIndex(0)!=0) return; //don't register kink tracks // // for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].fN) continue; for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].fClusterTracks[itrack][c]<0){ fgLayers[l].fClusterTracks[itrack][c]=id; break; } } } } void AliITStrackerMI::UnRegisterClusterTracks(AliITStrackMI* track, Int_t id) { //--------------------------------------------- // unregister track from the list for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].fN) continue; for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].fClusterTracks[itrack][c]==id){ fgLayers[l].fClusterTracks[itrack][c]=-1; } } } } Float_t AliITStrackerMI::GetNumberOfSharedClusters(AliITStrackMI* track,Int_t id, Int_t list[6], AliITSclusterV2 *clist[6]) { //------------------------------------------------------------- //get number of shared clusters //------------------------------------------------------------- Float_t shared=0; for (Int_t i=0;i<6;i++) { list[i]=-1, clist[i]=0;} // mean number of clusters Float_t *ny = GetNy(id), *nz = GetNz(id); for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].fN) continue; if (ny[l]==0){ printf("problem\n"); } AliITSclusterV2 *cl = (AliITSclusterV2*)GetCluster(index); Float_t weight=1; // Float_t deltan = 0; if (l>3&&cl->GetNy()+cl->GetNz()>6) continue; if (l>2&&track->fNormQ[l]/track->fExpQ>3.5) continue; if (l<2 || l>3){ deltan = (cl->GetNy()+cl->GetNz()-ny[l]-nz[l]); } else{ deltan = (cl->GetNz()-nz[l]); } if (deltan>2.0) continue; // extended - highly probable shared cluster weight = 2./TMath::Max(3.+deltan,2.); // for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].fClusterTracks[itrack][c]>=0 && fgLayers[l].fClusterTracks[itrack][c]!=id){ list[l]=index; clist[l] = (AliITSclusterV2*)GetCluster(index); shared+=weight; break; } } } track->fNUsed=shared; return shared; } Int_t AliITStrackerMI::GetOverlapTrack(AliITStrackMI *track, Int_t trackID, Int_t &shared, Int_t clusterlist[6],Int_t overlist[6]) { // // find first shared track // // mean number of clusters Float_t *ny = GetNy(trackID), *nz = GetNz(trackID); // for (Int_t i=0;i<6;i++) overlist[i]=-1; Int_t sharedtrack=100000; Int_t tracks[24],trackindex=0; for (Int_t i=0;i<24;i++) {tracks[i]=-1;} // for (Int_t icluster=0;icluster<6;icluster++){ if (clusterlist[icluster]<0) continue; Int_t index = clusterlist[icluster]; Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (ny[l]==0){ printf("problem\n"); } if (c>fgLayers[l].fN) continue; //if (l>3) continue; AliITSclusterV2 *cl = (AliITSclusterV2*)GetCluster(index); // Float_t deltan = 0; if (l>3&&cl->GetNy()+cl->GetNz()>6) continue; if (l>2&&track->fNormQ[l]/track->fExpQ>3.5) continue; if (l<2 || l>3){ deltan = (cl->GetNy()+cl->GetNz()-ny[l]-nz[l]); } else{ deltan = (cl->GetNz()-nz[l]); } if (deltan>2.0) continue; // extended - highly probable shared cluster // for (Int_t itrack=3;itrack>=0;itrack--){ if (fgLayers[l].fClusterTracks[itrack][c]<0) continue; if (fgLayers[l].fClusterTracks[itrack][c]!=trackID){ tracks[trackindex] = fgLayers[l].fClusterTracks[itrack][c]; trackindex++; } } } if (trackindex==0) return -1; if (trackindex==1){ sharedtrack = tracks[0]; }else{ if (trackindex==2) sharedtrack =TMath::Min(tracks[0],tracks[1]); else{ // Int_t track[24], cluster[24]; for (Int_t i=0;i<trackindex;i++){ track[i]=-1; cluster[i]=0;} Int_t index =0; // for (Int_t i=0;i<trackindex;i++){ if (tracks[i]<0) continue; track[index] = tracks[i]; cluster[index]++; for (Int_t j=i+1;j<trackindex;j++){ if (tracks[j]<0) continue; if (tracks[j]==tracks[i]){ cluster[index]++; tracks[j]=-1; } } index++; } Int_t max=0; for (Int_t i=0;i<index;i++){ if (cluster[index]>max) { sharedtrack=track[index]; max=cluster[index]; } } } } if (sharedtrack>=100000) return -1; // // make list of overlaps shared =0; for (Int_t icluster=0;icluster<6;icluster++){ if (clusterlist[icluster]<0) continue; Int_t index = clusterlist[icluster]; Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].fN) continue; AliITSclusterV2 *cl = (AliITSclusterV2*)GetCluster(index); if (l==0 || l==1){ if (cl->GetNy()>2) continue; if (cl->GetNz()>2) continue; } if (l==4 || l==5){ if (cl->GetNy()>3) continue; if (cl->GetNz()>3) continue; } // for (Int_t itrack=3;itrack>=0;itrack--){ if (fgLayers[l].fClusterTracks[itrack][c]<0) continue; if (fgLayers[l].fClusterTracks[itrack][c]==sharedtrack){ overlist[l]=index; shared++; } } } return sharedtrack; } AliITStrackMI * AliITStrackerMI::GetBest2Tracks(Int_t trackID1, Int_t trackID2, Float_t th0, Float_t th1){ // // try to find track hypothesys without conflicts // with minimal chi2; TClonesArray *arr1 = (TClonesArray*)fTrackHypothesys.At(trackID1); Int_t entries1 = arr1->GetEntriesFast(); TClonesArray *arr2 = (TClonesArray*)fTrackHypothesys.At(trackID2); if (!arr2) return (AliITStrackMI*) arr1->UncheckedAt(0); Int_t entries2 = arr2->GetEntriesFast(); if (entries2<=0) return (AliITStrackMI*) arr1->UncheckedAt(0); // AliITStrackMI * track10=(AliITStrackMI*) arr1->UncheckedAt(0); AliITStrackMI * track20=(AliITStrackMI*) arr2->UncheckedAt(0); if (TMath::Abs(1./track10->Get1Pt())>0.5+TMath::Abs(1/track20->Get1Pt())) return track10; for (Int_t itrack=0;itrack<entries1;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr1->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID1); } // for (Int_t itrack=0;itrack<entries2;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr2->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID2); } Int_t index1=0; Int_t index2=0; Float_t maxconflicts=6; Double_t maxchi2 =1000.; // // get weight of hypothesys - using best hypothesy Double_t w1,w2; Int_t list1[6],list2[6]; AliITSclusterV2 *clist1[6], *clist2[6] ; RegisterClusterTracks(track10,trackID1); RegisterClusterTracks(track20,trackID2); Float_t conflict1 = GetNumberOfSharedClusters(track10,trackID1,list1,clist1); Float_t conflict2 = GetNumberOfSharedClusters(track20,trackID2,list2,clist2); UnRegisterClusterTracks(track10,trackID1); UnRegisterClusterTracks(track20,trackID2); // // normalized chi2 Float_t chi21 =0,chi22=0,ncl1=0,ncl2=0; Float_t nerry[6],nerrz[6]; Float_t *erry1=GetErrY(trackID1),*errz1 = GetErrZ(trackID1); Float_t *erry2=GetErrY(trackID2),*errz2 = GetErrZ(trackID2); for (Int_t i=0;i<6;i++){ if ( (erry1[i]>0) && (erry2[i]>0)) { nerry[i] = TMath::Min(erry1[i],erry2[i]); nerrz[i] = TMath::Min(errz1[i],errz2[i]); }else{ nerry[i] = TMath::Max(erry1[i],erry2[i]); nerrz[i] = TMath::Max(errz1[i],errz2[i]); } if (TMath::Abs(track10->fDy[i])>0.000000000000001){ chi21 += track10->fDy[i]*track10->fDy[i]/(nerry[i]*nerry[i]); chi21 += track10->fDz[i]*track10->fDz[i]/(nerrz[i]*nerrz[i]); ncl1++; } if (TMath::Abs(track20->fDy[i])>0.000000000000001){ chi22 += track20->fDy[i]*track20->fDy[i]/(nerry[i]*nerry[i]); chi22 += track20->fDz[i]*track20->fDz[i]/(nerrz[i]*nerrz[i]); ncl2++; } } chi21/=ncl1; chi22/=ncl2; // // Float_t d1 = TMath::Sqrt(track10->fD[0]*track10->fD[0]+track10->fD[1]*track10->fD[1])+0.1; Float_t d2 = TMath::Sqrt(track20->fD[0]*track20->fD[0]+track20->fD[1]*track20->fD[1])+0.1; Float_t s1 = TMath::Sqrt(track10->GetSigmaY2()*track10->GetSigmaZ2()); Float_t s2 = TMath::Sqrt(track20->GetSigmaY2()*track20->GetSigmaZ2()); // w1 = (d2/(d1+d2)+ 2*s2/(s1+s2)+ +s2/(s1+s2)*0.5*(chi22+2.)/(chi21+chi22+4.) +1.*TMath::Abs(1./track10->Get1Pt())/(TMath::Abs(1./track10->Get1Pt())+TMath::Abs(1./track20->Get1Pt())) ); w2 = (d1/(d1+d2)+ 2*s1/(s1+s2)+ s1/(s1+s2)*0.5*(chi21+2.)/(chi21+chi22+4.) +1.*TMath::Abs(1./track20->Get1Pt())/(TMath::Abs(1./track10->Get1Pt())+TMath::Abs(1./track20->Get1Pt())) ); Double_t sumw = w1+w2; w1/=sumw; w2/=sumw; if (w1<w2*0.5) { w1 = (d2+0.5)/(d1+d2+1.); w2 = (d1+0.5)/(d1+d2+1.); } // Float_t maxmax = w1*track10->fChi2MIP[0]+w2*track20->fChi2MIP[0]+w1*conflict1+w2*conflict2+1.; //Float_t maxconflicts0 = w1*conflict1+w2*conflict2; // // get pair of "best" hypothesys // Float_t * ny1 = GetNy(trackID1), * nz1 = GetNz(trackID1); Float_t * ny2 = GetNy(trackID2), * nz2 = GetNz(trackID2); for (Int_t itrack1=0;itrack1<entries1;itrack1++){ AliITStrackMI * track1=(AliITStrackMI*) arr1->UncheckedAt(itrack1); //if (track1->fFakeRatio>0) continue; RegisterClusterTracks(track1,trackID1); for (Int_t itrack2=0;itrack2<entries2;itrack2++){ AliITStrackMI * track2=(AliITStrackMI*) arr2->UncheckedAt(itrack2); // Float_t current = w1*track1->fChi2MIP[0]+w2*track2->fChi2MIP[0]; //if (track2->fFakeRatio>0) continue; Float_t nskipped=0; RegisterClusterTracks(track2,trackID2); Int_t list1[6],list2[6]; AliITSclusterV2 *clist1[6], *clist2[6] ; Float_t cconflict1 = GetNumberOfSharedClusters(track1,trackID1,list1,clist1); Float_t cconflict2 = GetNumberOfSharedClusters(track2,trackID2,list2,clist2); UnRegisterClusterTracks(track2,trackID2); // if (track1->fConstrain) nskipped+=w1*track1->fNSkipped; if (track2->fConstrain) nskipped+=w2*track2->fNSkipped; if (nskipped>0.5) continue; // //if ( w1*conflict1+w2*conflict2>maxconflicts0) continue; if (conflict1+1<cconflict1) continue; if (conflict2+1<cconflict2) continue; Float_t conflict=0; Float_t sumchi2=0; Float_t sum=0; for (Int_t i=0;i<6;i++){ // Float_t c1 =0.; // conflict coeficients Float_t c2 =0.; if (clist1[i]&&clist2[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist1[i]->GetNy()+clist1[i]->GetNz()-TMath::Max(ny1[i],ny2[i])-TMath::Max(nz1[i],nz2[i])); } else{ deltan = (clist1[i]->GetNz()-TMath::Max(nz1[i],nz2[i])); } c1 = 2./TMath::Max(3.+deltan,2.); c2 = 2./TMath::Max(3.+deltan,2.); } else{ if (clist1[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist1[i]->GetNy()+clist1[i]->GetNz()-ny1[i]-nz1[i]); } else{ deltan = (clist1[i]->GetNz()-nz1[i]); } c1 = 2./TMath::Max(3.+deltan,2.); c2 = 0; } if (clist2[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist2[i]->GetNy()+clist2[i]->GetNz()-ny2[i]-nz2[i]); } else{ deltan = (clist2[i]->GetNz()-nz2[i]); } c2 = 2./TMath::Max(3.+deltan,2.); c1 = 0; } } // Double_t chi21=0,chi22=0; if (TMath::Abs(track1->fDy[i])>0.) { chi21 = (track1->fDy[i]/track1->fSigmaY[i])*(track1->fDy[i]/track1->fSigmaY[i])+ (track1->fDz[i]/track1->fSigmaZ[i])*(track1->fDz[i]/track1->fSigmaZ[i]); //chi21 = (track1->fDy[i]*track1->fDy[i])/(nerry[i]*nerry[i])+ // (track1->fDz[i]*track1->fDz[i])/(nerrz[i]*nerrz[i]); }else{ if (TMath::Abs(track1->fSigmaY[i]>0.)) c1=1; } // if (TMath::Abs(track2->fDy[i])>0.) { chi22 = (track2->fDy[i]/track2->fSigmaY[i])*(track2->fDy[i]/track2->fSigmaY[i])+ (track2->fDz[i]/track2->fSigmaZ[i])*(track2->fDz[i]/track2->fSigmaZ[i]); //chi22 = (track2->fDy[i]*track2->fDy[i])/(nerry[i]*nerry[i])+ // (track2->fDz[i]*track2->fDz[i])/(nerrz[i]*nerrz[i]); } else{ if (TMath::Abs(track2->fSigmaY[i]>0.)) c2=1; } sumchi2+=w1*(1.+c1)*(1+c1)*(chi21+c1)+w2*(1.+c2)*(1+c2)*(chi22+c2); if (chi21>0) sum+=w1; if (chi22>0) sum+=w2; conflict+=(c1+c2); } Double_t norm = sum-w1*track1->fNSkipped-w2*track2->fNSkipped; if (norm<0) norm =1/(w1*track1->fNSkipped+w2*track2->fNSkipped); Double_t normchi2 = 2*conflict+sumchi2/sum; if ( normchi2 <maxchi2 ){ index1 = itrack1; index2 = itrack2; maxconflicts = conflict; maxchi2 = normchi2; } } UnRegisterClusterTracks(track1,trackID1); } // // if (maxconflicts<4 && maxchi2<th0){ if (maxchi2<th0*2.){ Float_t orig = track10->fFakeRatio*track10->GetNumberOfClusters(); AliITStrackMI* track1=(AliITStrackMI*) arr1->UncheckedAt(index1); track1->fChi2MIP[5] = maxconflicts; track1->fChi2MIP[6] = maxchi2; track1->fChi2MIP[7] = 0.01+orig-(track1->fFakeRatio*track1->GetNumberOfClusters()); // track1->UpdateESDtrack(AliESDtrack::kITSin); track1->fChi2MIP[8] = index1; fBestTrackIndex[trackID1] =index1; UpdateESDtrack(track1, AliESDtrack::kITSin); } else if (track10->fChi2MIP[0]<th1){ track10->fChi2MIP[5] = maxconflicts; track10->fChi2MIP[6] = maxchi2; // track10->UpdateESDtrack(AliESDtrack::kITSin); UpdateESDtrack(track10,AliESDtrack::kITSin); } for (Int_t itrack=0;itrack<entries1;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr1->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID1); } // for (Int_t itrack=0;itrack<entries2;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr2->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID2); } if (track10->fConstrain&&track10->fChi2MIP[0]<kMaxChi2PerCluster[0]&&track10->fChi2MIP[1]<kMaxChi2PerCluster[1] &&track10->fChi2MIP[2]<kMaxChi2PerCluster[2]&&track10->fChi2MIP[3]<kMaxChi2PerCluster[3]){ // if (track10->fChi2MIP[0]<kMaxChi2PerCluster[0]&&track10->fChi2MIP[1]<kMaxChi2PerCluster[1] // &&track10->fChi2MIP[2]<kMaxChi2PerCluster[2]&&track10->fChi2MIP[3]<kMaxChi2PerCluster[3]){ RegisterClusterTracks(track10,trackID1); } if (track20->fConstrain&&track20->fChi2MIP[0]<kMaxChi2PerCluster[0]&&track20->fChi2MIP[1]<kMaxChi2PerCluster[1] &&track20->fChi2MIP[2]<kMaxChi2PerCluster[2]&&track20->fChi2MIP[3]<kMaxChi2PerCluster[3]){ //if (track20->fChi2MIP[0]<kMaxChi2PerCluster[0]&&track20->fChi2MIP[1]<kMaxChi2PerCluster[1] // &&track20->fChi2MIP[2]<kMaxChi2PerCluster[2]&&track20->fChi2MIP[3]<kMaxChi2PerCluster[3]){ RegisterClusterTracks(track20,trackID2); } return track10; } void AliITStrackerMI::UseClusters(const AliKalmanTrack *t, Int_t from) const { //-------------------------------------------------------------------- // This function marks clusters assigned to the track //-------------------------------------------------------------------- AliTracker::UseClusters(t,from); AliITSclusterV2 *c=(AliITSclusterV2 *)GetCluster(t->GetClusterIndex(0)); //if (c->GetQ()>2) c->Use(); if (c->GetSigmaZ2()>0.1) c->Use(); c=(AliITSclusterV2 *)GetCluster(t->GetClusterIndex(1)); //if (c->GetQ()>2) c->Use(); if (c->GetSigmaZ2()>0.1) c->Use(); } void AliITStrackerMI::AddTrackHypothesys(AliITStrackMI * track, Int_t esdindex) { //------------------------------------------------------------------ // add track to the list of hypothesys //------------------------------------------------------------------ if (esdindex>=fTrackHypothesys.GetEntriesFast()) fTrackHypothesys.Expand(esdindex*2+10); // TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); if (!array) { array = new TObjArray(10); fTrackHypothesys.AddAt(array,esdindex); } array->AddLast(track); } void AliITStrackerMI::SortTrackHypothesys(Int_t esdindex, Int_t maxcut, Int_t mode) { //------------------------------------------------------------------- // compress array of track hypothesys // keep only maxsize best hypothesys //------------------------------------------------------------------- if (esdindex>fTrackHypothesys.GetEntriesFast()) return; if (! (fTrackHypothesys.At(esdindex)) ) return; TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); Int_t entries = array->GetEntriesFast(); // //- find preliminary besttrack as a reference Float_t minchi2=10000; Int_t maxn=0; AliITStrackMI * besttrack=0; for (Int_t itrack=0;itrack<array->GetEntriesFast();itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (!track) continue; Float_t chi2 = NormalizedChi2(track,0); // Int_t tpcLabel=track->fESDtrack->GetTPCLabel(); track->SetLabel(tpcLabel); CookdEdx(track); track->fFakeRatio=1.; CookLabel(track,0.); //For comparison only // //if (chi2<kMaxChi2PerCluster[0]&&track->fFakeRatio==0){ if (chi2<kMaxChi2PerCluster[0]){ if (track->GetNumberOfClusters()<maxn) continue; maxn = track->GetNumberOfClusters(); if (chi2<minchi2){ minchi2=chi2; besttrack=track; } } else{ if (track->fConstrain || track->fN>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } if (!besttrack) return; // // //take errors of best track as a reference Float_t *erry = GetErrY(esdindex), *errz = GetErrZ(esdindex); Float_t *ny = GetNy(esdindex), *nz = GetNz(esdindex); for (Int_t i=0;i<6;i++) { if (besttrack->fClIndex[i]>0){ erry[i] = besttrack->fSigmaY[i]; erry[i+6] = besttrack->fSigmaY[i+6]; errz[i] = besttrack->fSigmaZ[i]; errz[i+6] = besttrack->fSigmaZ[i+6]; ny[i] = besttrack->fNy[i]; nz[i] = besttrack->fNz[i]; } } // // calculate normalized chi2 // Float_t * chi2 = new Float_t[entries]; Int_t * index = new Int_t[entries]; for (Int_t i=0;i<entries;i++) chi2[i] =10000; for (Int_t itrack=0;itrack<entries;itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (track){ track->fChi2MIP[0] = GetNormalizedChi2(track, mode); if (track->fChi2MIP[0]<kMaxChi2PerCluster[0]) chi2[itrack] = track->fChi2MIP[0]; else{ if (track->fConstrain || track->fN>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } } // TMath::Sort(entries,chi2,index,kFALSE); besttrack = (AliITStrackMI*)array->At(index[0]); if (besttrack&&besttrack->fChi2MIP[0]<kMaxChi2PerCluster[0]){ for (Int_t i=0;i<6;i++){ if (besttrack->fClIndex[i]>0){ erry[i] = besttrack->fSigmaY[i]; erry[i+6] = besttrack->fSigmaY[i+6]; errz[i] = besttrack->fSigmaZ[i]; erry[i+6] = besttrack->fSigmaY[i+6]; ny[i] = besttrack->fNy[i]; nz[i] = besttrack->fNz[i]; } } } // // calculate one more time with updated normalized errors for (Int_t i=0;i<entries;i++) chi2[i] =10000; for (Int_t itrack=0;itrack<entries;itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (track){ track->fChi2MIP[0] = GetNormalizedChi2(track,mode); if (track->fChi2MIP[0]<kMaxChi2PerCluster[0]) chi2[itrack] = track->fChi2MIP[0]-0*(track->GetNumberOfClusters()+track->fNDeadZone); else { if (track->fConstrain || track->fN>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } } entries = array->GetEntriesFast(); // // if (entries>0){ TObjArray * newarray = new TObjArray(); TMath::Sort(entries,chi2,index,kFALSE); besttrack = (AliITStrackMI*)array->At(index[0]); if (besttrack){ // for (Int_t i=0;i<6;i++){ if (besttrack->fNz[i]>0&&besttrack->fNy[i]>0){ erry[i] = besttrack->fSigmaY[i]; erry[i+6] = besttrack->fSigmaY[i+6]; errz[i] = besttrack->fSigmaZ[i]; errz[i+6] = besttrack->fSigmaZ[i+6]; ny[i] = besttrack->fNy[i]; nz[i] = besttrack->fNz[i]; } } besttrack->fChi2MIP[0] = GetNormalizedChi2(besttrack,mode); Float_t minchi2 = TMath::Min(besttrack->fChi2MIP[0]+5.+besttrack->fNUsed, double(kMaxChi2PerCluster[0])); Float_t minn = besttrack->GetNumberOfClusters()-3; Int_t accepted=0; for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(index[i]); if (!track) continue; if (accepted>maxcut) break; track->fChi2MIP[0] = GetNormalizedChi2(track,mode); if (track->fConstrain || track->fN>5){ //keep best short tracks - without vertex constrain if (track->GetNumberOfClusters()<6 && (track->fChi2MIP[0]+track->fNUsed>minchi2)){ delete array->RemoveAt(index[i]); continue; } } Bool_t shortbest = !track->fConstrain && track->fN<6; if ((track->fChi2MIP[0]+track->fNUsed<minchi2 && track->GetNumberOfClusters()>=minn) ||shortbest){ if (!shortbest) accepted++; // newarray->AddLast(array->RemoveAt(index[i])); for (Int_t i=0;i<6;i++){ if (nz[i]==0){ erry[i] = track->fSigmaY[i]; erry[i+6] = track->fSigmaY[i+6]; errz[i] = track->fSigmaZ[i]; errz[i] = track->fSigmaZ[i+6]; ny[i] = track->fNy[i]; nz[i] = track->fNz[i]; } } } else{ delete array->RemoveAt(index[i]); } } array->Delete(); delete fTrackHypothesys.RemoveAt(esdindex); fTrackHypothesys.AddAt(newarray,esdindex); } else{ array->Delete(); delete fTrackHypothesys.RemoveAt(esdindex); } } delete [] chi2; delete [] index; } AliITStrackMI * AliITStrackerMI::GetBestHypothesys(Int_t esdindex, AliITStrackMI * original, Int_t checkmax) { //------------------------------------------------------------- // try to find best hypothesy // currently - minimal chi2 of track+backpropagated track+matching to the tpc track //------------------------------------------------------------- if (fTrackHypothesys.GetEntriesFast()<=esdindex) return 0; TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); if (!array) return 0; Int_t entries = array->GetEntriesFast(); if (!entries) return 0; Float_t minchi2 = 100000; AliITStrackMI * besttrack=0; // AliITStrackMI * backtrack = new AliITStrackMI(*original); AliITStrackMI * forwardtrack = new AliITStrackMI(*original); Double_t xyzv[]={GetX(),GetY(),GetZ()}; Double_t ersv[]={GetSigmaX()/3.,GetSigmaY()/3.,GetSigmaZ()/3.}; // for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; Float_t sigmarfi,sigmaz; GetDCASigma(track,sigmarfi,sigmaz); track->fDnorm[0] = sigmarfi; track->fDnorm[1] = sigmaz; // track->fChi2MIP[1] = 1000000; track->fChi2MIP[2] = 1000000; track->fChi2MIP[3] = 1000000; // // backtrack backtrack = new(backtrack) AliITStrackMI(*track); if (track->fConstrain){ if (!backtrack->PropagateTo(3.,0.0028,65.19)) continue; if (!backtrack->Improve(0,xyzv,ersv)) continue; if (!backtrack->PropagateTo(2.,0.0028,0)) continue; if (!backtrack->Improve(0,xyzv,ersv)) continue; if (!backtrack->PropagateTo(1.,0.0028,0)) continue; if (!backtrack->Improve(0,xyzv,ersv)) continue; if (!backtrack->PropagateToVertex()) continue; backtrack->ResetCovariance(); if (!backtrack->Improve(0,xyzv,ersv)) continue; }else{ backtrack->ResetCovariance(); } backtrack->ResetClusters(); Double_t x = original->GetX(); if (!RefitAt(x,backtrack,track)) continue; // track->fChi2MIP[1] = NormalizedChi2(backtrack,0); //for (Int_t i=2;i<6;i++){track->fDy[i]+=backtrack->fDy[i]; track->fDz[i]+=backtrack->fDz[i];} if (track->fChi2MIP[1]>kMaxChi2PerCluster[1]*6.) continue; track->fChi22 = GetMatchingChi2(backtrack,original); if ((track->fConstrain) && track->fChi22>90.) continue; if ((!track->fConstrain) && track->fChi22>30.) continue; if ( track->fChi22/track->GetNumberOfClusters()>11.) continue; if (!(track->fConstrain)&&track->fChi2MIP[1]>kMaxChi2PerCluster[1]) continue; Bool_t isOK=kTRUE; if(!isOK) continue; // //forward track - without constraint forwardtrack = new(forwardtrack) AliITStrackMI(*original); forwardtrack->ResetClusters(); x = track->GetX(); RefitAt(x,forwardtrack,track); track->fChi2MIP[2] = NormalizedChi2(forwardtrack,0); if (track->fChi2MIP[2]>kMaxChi2PerCluster[2]*6.0) continue; if (!(track->fConstrain)&&track->fChi2MIP[2]>kMaxChi2PerCluster[2]) continue; track->fD[0] = forwardtrack->GetD(GetX(),GetY()); track->fD[1] = forwardtrack->GetZat(GetX())-GetZ(); forwardtrack->fD[0] = track->fD[0]; forwardtrack->fD[1] = track->fD[1]; { Int_t list[6]; AliITSclusterV2* clist[6]; track->fChi2MIP[4] = GetNumberOfSharedClusters(track,esdindex,list,clist); if ( (!track->fConstrain) && track->fChi2MIP[4]>1.0) continue; } track->fChi2MIP[3] = GetInterpolatedChi2(forwardtrack,backtrack); if ( (track->fChi2MIP[3]>6.*kMaxChi2PerCluster[3])) continue; if ( (!track->fConstrain) && (track->fChi2MIP[3]>2*kMaxChi2PerCluster[3])) { track->fChi2MIP[3]=1000; continue; } Double_t chi2 = track->fChi2MIP[0]+track->fNUsed; // for (Int_t ichi=0;ichi<5;ichi++){ forwardtrack->fChi2MIP[ichi] = track->fChi2MIP[ichi]; } if (chi2 < minchi2){ //besttrack = new AliITStrackMI(*forwardtrack); besttrack = track; besttrack->SetLabel(track->GetLabel()); besttrack->fFakeRatio = track->fFakeRatio; minchi2 = chi2; original->fD[0] = forwardtrack->GetD(GetX(),GetY()); original->fD[1] = forwardtrack->GetZat(GetX())-GetZ(); } } delete backtrack; delete forwardtrack; Int_t accepted=0; for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; if (accepted>checkmax || track->fChi2MIP[3]>kMaxChi2PerCluster[3]*6. || (track->GetNumberOfClusters()<besttrack->GetNumberOfClusters()-1.)|| track->fChi2MIP[0]>besttrack->fChi2MIP[0]+2.*besttrack->fNUsed+3.){ if (track->fConstrain || track->fN>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(i); continue; } } else{ accepted++; } } // array->Compress(); SortTrackHypothesys(esdindex,checkmax,1); array = (TObjArray*) fTrackHypothesys.At(esdindex); besttrack = (AliITStrackMI*)array->At(0); if (!besttrack) return 0; besttrack->fChi2MIP[8]=0; fBestTrackIndex[esdindex]=0; entries = array->GetEntriesFast(); AliITStrackMI *longtrack =0; minchi2 =1000; Float_t minn=besttrack->GetNumberOfClusters()+besttrack->fNDeadZone; for (Int_t itrack=entries-1;itrack>0;itrack--){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (!track->fConstrain) continue; if (track->GetNumberOfClusters()+track->fNDeadZone<minn) continue; if (track->fChi2MIP[0]-besttrack->fChi2MIP[0]>0.0) continue; if (track->fChi2MIP[0]>4.) continue; minn = track->GetNumberOfClusters()+track->fNDeadZone; longtrack =track; } //if (longtrack) besttrack=longtrack; Int_t list[6]; AliITSclusterV2 * clist[6]; Float_t shared = GetNumberOfSharedClusters(besttrack,esdindex,list,clist); if (besttrack->fConstrain&&besttrack->fChi2MIP[0]<kMaxChi2PerCluster[0]&&besttrack->fChi2MIP[1]<kMaxChi2PerCluster[1] &&besttrack->fChi2MIP[2]<kMaxChi2PerCluster[2]&&besttrack->fChi2MIP[3]<kMaxChi2PerCluster[3]){ RegisterClusterTracks(besttrack,esdindex); } // // if (shared>0.0){ Int_t nshared; Int_t overlist[6]; Int_t sharedtrack = GetOverlapTrack(besttrack, esdindex, nshared, list, overlist); if (sharedtrack>=0){ // besttrack = GetBest2Tracks(esdindex,sharedtrack,10,5.5); if (besttrack){ shared = GetNumberOfSharedClusters(besttrack,esdindex,list,clist); } else return 0; } } if (shared>2.5) return 0; if (shared>1.0) return besttrack; // // Don't sign clusters if not gold track // if (!besttrack->IsGoldPrimary()) return besttrack; if (besttrack->fESDtrack->GetKinkIndex(0)!=0) return besttrack; //track belong to kink // if (fConstraint[fPass]){ // // sign clusters // Float_t *ny = GetNy(esdindex), *nz = GetNz(esdindex); for (Int_t i=0;i<6;i++){ Int_t index = besttrack->fClIndex[i]; if (index<=0) continue; Int_t ilayer = (index & 0xf0000000) >> 28; if (besttrack->fSigmaY[ilayer]<0.00000000001) continue; AliITSclusterV2 *c = (AliITSclusterV2*)GetCluster(index); if (!c) continue; if (ilayer>3&&c->GetNy()+c->GetNz()>6) continue; if ( (c->GetNy()+c->GetNz() )> ny[i]+nz[i]+0.7) continue; //shared track if ( c->GetNz()> nz[i]+0.7) continue; //shared track if ( ilayer>2&& besttrack->fNormQ[ilayer]/besttrack->fExpQ>1.5) continue; //if ( c->GetNy()> ny[i]+0.7) continue; //shared track Bool_t cansign = kTRUE; for (Int_t itrack=0;itrack<entries; itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; if (track->fChi2MIP[0]>besttrack->fChi2MIP[0]+2.*shared+1.) break; if ( (track->fClIndex[ilayer]>0) && (track->fClIndex[ilayer]!=besttrack->fClIndex[ilayer])){ cansign = kFALSE; break; } } if (cansign){ if (TMath::Abs(besttrack->fDy[ilayer]/besttrack->fSigmaY[ilayer])>3.) continue; if (TMath::Abs(besttrack->fDz[ilayer]/besttrack->fSigmaZ[ilayer])>3.) continue; if (!c->IsUsed()) c->Use(); } } } return besttrack; } void AliITStrackerMI::GetBestHypothesysMIP(TObjArray &itsTracks) { // // get "best" hypothesys // Int_t nentries = itsTracks.GetEntriesFast(); for (Int_t i=0;i<nentries;i++){ AliITStrackMI* track = (AliITStrackMI*)itsTracks.At(i); if (!track) continue; TObjArray * array = (TObjArray*) fTrackHypothesys.At(i); if (!array) continue; if (array->GetEntriesFast()<=0) continue; // AliITStrackMI* longtrack=0; Float_t minn=0; Float_t maxchi2=1000; for (Int_t j=0;j<array->GetEntriesFast();j++){ AliITStrackMI* track = (AliITStrackMI*)array->At(j); if (!track) continue; if (track->fGoldV0) { longtrack = track; //gold V0 track taken break; } if (track->GetNumberOfClusters()+track->fNDeadZone<minn) continue; Float_t chi2 = track->fChi2MIP[0]; if (fAfterV0){ if (!track->fGoldV0&&track->fConstrain==kFALSE) chi2+=5; } if (track->GetNumberOfClusters()+track->fNDeadZone>minn) maxchi2 = track->fChi2MIP[0]; // if (chi2 > maxchi2) continue; minn= track->GetNumberOfClusters()+track->fNDeadZone; maxchi2 = chi2; longtrack=track; } // // // AliITStrackMI * besttrack = (AliITStrackMI*)array->At(0); if (!longtrack) {longtrack = besttrack;} else besttrack= longtrack; // if (besttrack){ Int_t list[6]; AliITSclusterV2 * clist[6]; Float_t shared = GetNumberOfSharedClusters(longtrack,i,list,clist); // track->fNUsed = shared; track->fNSkipped = besttrack->fNSkipped; track->fChi2MIP[0] = besttrack->fChi2MIP[0]; if (shared>0){ Int_t nshared; Int_t overlist[6]; // Int_t sharedtrack = GetOverlapTrack(longtrack, i, nshared, list, overlist); //if (sharedtrack==-1) sharedtrack=0; if (sharedtrack>=0){ besttrack = GetBest2Tracks(i,sharedtrack,10,5.5); } } if (besttrack&&fAfterV0){ UpdateESDtrack(besttrack,AliESDtrack::kITSin); } if (besttrack&&fConstraint[fPass]) UpdateESDtrack(besttrack,AliESDtrack::kITSin); //if (besttrack&&besttrack->fConstrain) // UpdateESDtrack(besttrack,AliESDtrack::kITSin); if (besttrack->fChi2MIP[0]+besttrack->fNUsed>1.5){ if ( (TMath::Abs(besttrack->fD[0])>0.1) && fConstraint[fPass]) { track->fReconstructed= kFALSE; } if ( (TMath::Abs(besttrack->fD[1])>0.1) && fConstraint[fPass]){ track->fReconstructed= kFALSE; } } } } } void AliITStrackerMI::CookLabel(AliITStrackMI *track,Float_t wrong) const { //-------------------------------------------------------------------- //This function "cooks" a track label. If label<0, this track is fake. //-------------------------------------------------------------------- Int_t tpcLabel=-1; if ( track->fESDtrack) tpcLabel = TMath::Abs(track->fESDtrack->GetTPCLabel()); track->fChi2MIP[9]=0; Int_t nwrong=0; for (Int_t i=0;i<track->GetNumberOfClusters();i++){ Int_t cindex = track->GetClusterIndex(i); Int_t l=(cindex & 0xf0000000) >> 28; AliITSclusterV2 *cl = (AliITSclusterV2*)GetCluster(cindex); Int_t isWrong=1; for (Int_t ind=0;ind<3;ind++){ if (tpcLabel>0) if (cl->GetLabel(ind)==tpcLabel) isWrong=0; } track->fChi2MIP[9]+=isWrong*(2<<l); nwrong+=isWrong; } track->fFakeRatio = double(nwrong)/double(track->GetNumberOfClusters()); if (tpcLabel>0){ if (track->fFakeRatio>wrong) track->fLab = -tpcLabel; else track->fLab = tpcLabel; } } void AliITStrackerMI::CookdEdx(AliITStrackMI* track) { // // // Int_t list[6]; //AliITSclusterV2 * clist[6]; // Int_t shared = GetNumberOfSharedClusters(track,index,list,clist); Float_t dedx[4]; Int_t accepted=0; track->fChi2MIP[9]=0; for (Int_t i=0;i<track->GetNumberOfClusters();i++){ Int_t cindex = track->GetClusterIndex(i); Int_t l=(cindex & 0xf0000000) >> 28; AliITSclusterV2 *cl = (AliITSclusterV2*)GetCluster(cindex); Int_t lab = TMath::Abs(track->fESDtrack->GetTPCLabel()); Int_t isWrong=1; for (Int_t ind=0;ind<3;ind++){ if (cl->GetLabel(ind)==lab) isWrong=0; } track->fChi2MIP[9]+=isWrong*(2<<l); if (l<2) continue; //if (l>3 && (cl->GetNy()>4) || (cl->GetNz()>4)) continue; //shared track //if (l>3&& !(cl->GetType()==1||cl->GetType()==10)) continue; //if (l<4&& !(cl->GetType()==1)) continue; dedx[accepted]= track->fdEdxSample[i]; //dedx[accepted]= track->fNormQ[l]; accepted++; } if (accepted<1) { track->SetdEdx(0); return; } Int_t indexes[4]; TMath::Sort(accepted,dedx,indexes,kFALSE); Double_t low=0.; Double_t up=0.51; Double_t nl=low*accepted, nu =up*accepted; Float_t sumamp = 0; Float_t sumweight =0; for (Int_t i=0; i<accepted; i++) { Float_t weight =1; if (i<nl+0.1) weight = TMath::Max(1.-(nl-i),0.); if (i>nu-1) weight = TMath::Max(nu-i,0.); sumamp+= dedx[indexes[i]]*weight; sumweight+=weight; } track->SetdEdx(sumamp/sumweight); } void AliITStrackerMI::MakeCoeficients(Int_t ntracks){ // // if (fCoeficients) delete []fCoeficients; fCoeficients = new Float_t[ntracks*48]; for (Int_t i=0;i<ntracks*48;i++) fCoeficients[i]=-1.; } Double_t AliITStrackerMI::GetPredictedChi2MI(AliITStrackMI* track, const AliITSclusterV2 *cluster,Int_t layer) { // // // Float_t erry,errz; Float_t theta = track->GetTgl(); Float_t phi = track->GetSnp(); phi = TMath::Sqrt(phi*phi/(1.-phi*phi)); GetError(layer,cluster,theta,phi,track->fExpQ,erry,errz); Double_t chi2 = track->GetPredictedChi2MI(cluster->GetY(),cluster->GetZ(),erry,errz); Float_t ny,nz; GetNTeor(layer,cluster, theta,phi,ny,nz); Double_t delta = cluster->GetNy()+cluster->GetNz()-nz-ny; if (delta>1){ chi2+=0.5*TMath::Min(delta/2,2.); chi2+=2.*cluster->GetDeltaProbability(); } // track->fNy[layer] =ny; track->fNz[layer] =nz; track->fSigmaY[layer] = erry; track->fSigmaZ[layer] = errz; //track->fNormQ[layer] = cluster->GetQ()/TMath::Sqrt(1+theta*theta+phi*phi); track->fNormQ[layer] = cluster->GetQ()/TMath::Sqrt((1.+ track->fP3*track->fP3)/(1.- track->fP2*track->fP2)); return chi2; } Int_t AliITStrackerMI::UpdateMI(AliITStrackMI* track, const AliITSclusterV2* cl,Double_t chi2,Int_t index) const { // // // Int_t layer = (index & 0xf0000000) >> 28; track->fClIndex[layer] = index; if ( (layer>1) &&track->fNormQ[layer]/track->fExpQ<0.5 ) { chi2+= (0.5-track->fNormQ[layer]/track->fExpQ)*10.; track->fdEdxMismatch+=(0.5-track->fNormQ[layer]/track->fExpQ)*10.; } return track->UpdateMI(cl->GetY(),cl->GetZ(),track->fSigmaY[layer],track->fSigmaZ[layer],chi2,index); } void AliITStrackerMI::GetNTeor(Int_t layer, const AliITSclusterV2* /*cl*/, Float_t theta, Float_t phi, Float_t &ny, Float_t &nz) { // //get "mean shape" // if (layer==0){ ny = 1.+TMath::Abs(phi)*3.2; nz = 1.+TMath::Abs(theta)*0.34; return; } if (layer==1){ ny = 1.+TMath::Abs(phi)*3.2; nz = 1.+TMath::Abs(theta)*0.28; return; } if (layer>3){ ny = 2.02+TMath::Abs(phi)*1.95; nz = 2.02+TMath::Abs(phi)*2.35; return; } ny = 6.6-2.7*TMath::Abs(phi); nz = 2.8-3.11*TMath::Abs(phi)+0.45*TMath::Abs(theta); } Int_t AliITStrackerMI::GetError(Int_t layer, const AliITSclusterV2*cl, Float_t theta, Float_t phi,Float_t expQ, Float_t &erry, Float_t &errz) { //calculate cluster position error // Float_t nz,ny; GetNTeor(layer, cl,theta,phi,ny,nz); erry = TMath::Sqrt(cl->GetSigmaY2()); errz = TMath::Sqrt(cl->GetSigmaZ2()); // // PIXELS if (layer<2){ if (TMath::Abs(ny-cl->GetNy())>0.6) { if (ny<cl->GetNy()){ erry*=0.4+TMath::Abs(ny-cl->GetNy()); errz*=0.4+TMath::Abs(ny-cl->GetNy()); }else{ erry*=0.7+0.5*TMath::Abs(ny-cl->GetNy()); errz*=0.7+0.5*TMath::Abs(ny-cl->GetNy()); } } if (TMath::Abs(nz-cl->GetNz())>1.) { erry*=TMath::Abs(nz-cl->GetNz()); errz*=TMath::Abs(nz-cl->GetNz()); } erry*=0.85; errz*=0.85; erry= TMath::Min(erry,float(0.005)); errz= TMath::Min(errz,float(0.03)); return 10; } //STRIPS if (layer>3){ //factor 1.8 appears in new simulation // Float_t scale=1.8; if (cl->GetNy()==100||cl->GetNz()==100){ erry = 0.004*scale; errz = 0.2*scale; return 100; } if (cl->GetNy()+cl->GetNz()>12){ erry = 0.06*scale; errz = 0.57*scale; return 100; } Float_t normq = cl->GetQ()/(TMath::Sqrt(1+theta*theta+phi*phi)); Float_t chargematch = TMath::Max(double(normq/expQ),2.); // if (cl->GetType()==1 || cl->GetType()==10 ){ if (chargematch<1.0 || (cl->GetNy()+cl->GetNz()<nz+ny+0.5)){ errz = 0.043*scale; erry = 0.00094*scale; return 101; } if (cl->GetNy()+cl->GetNz()<nz+ny+1.2){ errz = 0.06*scale; erry =0.0013*scale; return 102; } erry = 0.0027*scale; errz = TMath::Min(0.028*(chargematch+cl->GetNy()+cl->GetNz()-nz+ny),0.15)*scale; return 103; } if (cl->GetType()==2 || cl->GetType()==11 ){ erry = TMath::Min(0.0010*(1+chargematch+cl->GetNy()+cl->GetNz()-nz+ny),0.05)*scale; errz = TMath::Min(0.025*(1+chargematch+cl->GetNy()+cl->GetNz()-nz+ny),0.5)*scale; return 104; } if (cl->GetType()>100 ){ if ((chargematch+cl->GetNy()+cl->GetNz()-nz-ny<1.5)){ errz = 0.05*scale; erry = 0.00096*scale; return 105; } if (cl->GetNy()+cl->GetNz()-nz-ny<1){ errz = 0.10*scale; erry = 0.0025*scale; return 106; } errz = TMath::Min(0.05*(chargematch+cl->GetNy()+cl->GetNz()-nz-ny),0.4)*scale; erry = TMath::Min(0.003*(chargematch+cl->GetNy()+cl->GetNz()-nz-ny),0.05)*scale; return 107; } Float_t diff = cl->GetNy()+cl->GetNz()-ny-nz; if (diff<1) diff=1; if (diff>4) diff=4; if (cl->GetType()==5||cl->GetType()==6||cl->GetType()==7||cl->GetType()==8){ errz = 0.14*diff; erry = 0.003*diff; return 108; } erry = 0.04*diff; errz = 0.06*diff; return 109; } //DRIFTS Float_t normq = cl->GetQ()/(TMath::Sqrt(1+theta*theta+phi*phi)); Float_t chargematch = normq/expQ; Float_t factorz=1; Int_t cnz = cl->GetNz()%10; //charge match if (cl->GetType()==1){ if (chargematch<1.25){ erry = 0.0028*(1.+6./cl->GetQ()); // gold clusters } else{ erry = 0.003*chargematch; if (cl->GetNz()==3) erry*=1.5; } if (chargematch<1.0){ errz = 0.0011*(1.+6./cl->GetQ()); } else{ errz = 0.002*(1+2*(chargematch-1.)); } if (cnz>nz+0.6) { erry*=(cnz-nz+0.5); errz*=1.4*(cnz-nz+0.5); } } if (cl->GetType()>1){ if (chargematch<1){ erry = 0.00385*(1.+6./cl->GetQ()); // gold clusters errz = 0.0016*(1.+6./cl->GetQ()); } else{ errz = 0.0014*(1+3*(chargematch-1.)); erry = 0.003*(1+3*(chargematch-1.)); } if (cnz>nz+0.6) { erry*=(cnz-nz+0.5); errz*=1.4*(cnz-nz+0.5); } } if (TMath::Abs(cl->GetY())>2.5){ factorz*=1+2*(TMath::Abs(cl->GetY())-2.5); } if (TMath::Abs(cl->GetY())<1){ factorz*=1.+0.5*TMath::Abs(TMath::Abs(cl->GetY())-1.); } factorz= TMath::Min(factorz,float(4.)); errz*=factorz; erry= TMath::Min(erry,float(0.05)); errz= TMath::Min(errz,float(0.05)); return 200; } void AliITStrackerMI::GetDCASigma(AliITStrackMI* track, Float_t & sigmarfi, Float_t &sigmaz) { // //DCA sigmas parameterization //to be paramterized using external parameters in future // // sigmarfi = 0.004+1.4 *TMath::Abs(track->fP4)+332.*track->fP4*track->fP4; sigmaz = 0.011+4.37*TMath::Abs(track->fP4); } void AliITStrackerMI::SignDeltas( TObjArray *ClusterArray, Float_t vz) { // // Int_t entries = ClusterArray->GetEntriesFast(); if (entries<4) return; AliITSclusterV2* cluster = (AliITSclusterV2*)ClusterArray->At(0); Int_t layer = cluster->GetLayer(); if (layer>1) return; Int_t index[10000]; Int_t ncandidates=0; Float_t r = (layer>0)? 7:4; // for (Int_t i=0;i<entries;i++){ AliITSclusterV2* cl0 = (AliITSclusterV2*)ClusterArray->At(i); Float_t nz = 1+TMath::Abs((cl0->GetZ()-vz)/r); if (cl0->GetNy()+cl0->GetNz()<=5+2*layer+nz) continue; index[ncandidates] = i; //candidate to belong to delta electron track ncandidates++; if (cl0->GetNy()+cl0->GetNz()>9+2*layer+nz) { cl0->SetDeltaProbability(1); } } // // // for (Int_t i=0;i<ncandidates;i++){ AliITSclusterV2* cl0 = (AliITSclusterV2*)ClusterArray->At(index[i]); if (cl0->GetDeltaProbability()>0.8) continue; // Int_t ncl = 0; Float_t y[100],z[100],sumy,sumz,sumy2, sumyz, sumw; sumy=sumz=sumy2=sumyz=sumw=0.0; for (Int_t j=0;j<ncandidates;j++){ if (i==j) continue; AliITSclusterV2* cl1 = (AliITSclusterV2*)ClusterArray->At(index[j]); // Float_t dz = cl0->GetZ()-cl1->GetZ(); Float_t dy = cl0->GetY()-cl1->GetY(); if (TMath::Sqrt(dz*dz+dy*dy)<0.2){ Float_t weight = cl1->GetNy()+cl1->GetNz()-2; y[ncl] = cl1->GetY(); z[ncl] = cl1->GetZ(); sumy+= y[ncl]*weight; sumz+= z[ncl]*weight; sumy2+=y[ncl]*y[ncl]*weight; sumyz+=y[ncl]*z[ncl]*weight; sumw+=weight; ncl++; } } if (ncl<4) continue; Float_t det = sumw*sumy2 - sumy*sumy; Float_t delta=1000; if (TMath::Abs(det)>0.01){ Float_t z0 = (sumy2*sumz - sumy*sumyz)/det; Float_t k = (sumyz*sumw - sumy*sumz)/det; delta = TMath::Abs(cl0->GetZ()-(z0+k*cl0->GetY())); } else{ Float_t z0 = sumyz/sumy; delta = TMath::Abs(cl0->GetZ()-z0); } if ( delta<0.05) { cl0->SetDeltaProbability(1-20.*delta); } } } void AliITStrackerMI::UpdateESDtrack(AliITStrackMI* track, ULong_t flags) const { // // track->UpdateESDtrack(flags); AliITStrackMI * oldtrack = (AliITStrackMI*)(track->fESDtrack->GetITStrack()); if (oldtrack) delete oldtrack; track->fESDtrack->SetITStrack(new AliITStrackMI(*track)); if (TMath::Abs(track->fDnorm[1])<0.000000001){ printf("Problem\n"); } } Int_t AliITStrackerMI::GetNearestLayer(const Double_t *xr) const{ // //Get nearest upper layer close to the point xr. // rough approximation // const Float_t kRadiuses[6]={4,6.5,15.03,24.,38.5,43.7}; Float_t radius = TMath::Sqrt(xr[0]*xr[0]+xr[1]*xr[1]); Int_t res =6; for (Int_t i=0;i<6;i++){ if (radius<kRadiuses[i]){ res =i; break; } } return res; } void AliITStrackerMI::UpdateTPCV0(AliESD *event){ // //try to update, or reject TPC V0s // Int_t nv0s = event->GetNumberOfV0MIs(); Int_t nitstracks = fTrackHypothesys.GetEntriesFast(); for (Int_t i=0;i<nv0s;i++){ AliESDV0MI * vertex = event->GetV0MI(i); Int_t ip = vertex->GetIndex(0); Int_t im = vertex->GetIndex(1); // TObjArray * arrayp = (ip<nitstracks) ? (TObjArray*)fTrackHypothesys.At(ip):0; TObjArray * arraym = (im<nitstracks) ? (TObjArray*)fTrackHypothesys.At(im):0; AliITStrackMI * trackp = (arrayp!=0) ? (AliITStrackMI*)arrayp->At(0):0; AliITStrackMI * trackm = (arraym!=0) ? (AliITStrackMI*)arraym->At(0):0; // // if (trackp){ if (trackp->fN+trackp->fNDeadZone>5.5){ if (trackp->fConstrain&&trackp->fChi2MIP[0]<3) vertex->SetStatus(-100); if (!trackp->fConstrain&&trackp->fChi2MIP[0]<2) vertex->SetStatus(-100); } } if (trackm){ if (trackm->fN+trackm->fNDeadZone>5.5){ if (trackm->fConstrain&&trackm->fChi2MIP[0]<3) vertex->SetStatus(-100); if (!trackm->fConstrain&&trackm->fChi2MIP[0]<2) vertex->SetStatus(-100); } } if (vertex->GetStatus()==-100) continue; // Int_t clayer = GetNearestLayer(vertex->GetXrp()); vertex->SetNBefore(clayer); // vertex->SetChi2Before(9*clayer); // vertex->SetNAfter(6-clayer); // vertex->SetChi2After(0); // // if (clayer >1 ){ // calculate chi2 before vertex Float_t chi2p = 0, chi2m=0; // if (trackp){ for (Int_t ilayer=0;ilayer<clayer;ilayer++){ if (trackp->fClIndex[ilayer]>0){ chi2p+=trackp->fDy[ilayer]*trackp->fDy[ilayer]/(trackp->fSigmaY[ilayer]*trackp->fSigmaY[ilayer])+ trackp->fDz[ilayer]*trackp->fDz[ilayer]/(trackp->fSigmaZ[ilayer]*trackp->fSigmaZ[ilayer]); } else{ chi2p+=9; } } }else{ chi2p = 9*clayer; } // if (trackm){ for (Int_t ilayer=0;ilayer<clayer;ilayer++){ if (trackm->fClIndex[ilayer]>0){ chi2m+=trackm->fDy[ilayer]*trackm->fDy[ilayer]/(trackm->fSigmaY[ilayer]*trackm->fSigmaY[ilayer])+ trackm->fDz[ilayer]*trackm->fDz[ilayer]/(trackm->fSigmaZ[ilayer]*trackm->fSigmaZ[ilayer]); } else{ chi2m+=9; } } }else{ chi2m = 9*clayer; } vertex->SetChi2Before(TMath::Min(chi2p,chi2m)); if (TMath::Min(chi2p,chi2m)/Float_t(clayer)<4) vertex->SetStatus(-10); // track exist before vertex } if (clayer < 5 ){ // calculate chi2 after vertex Float_t chi2p = 0, chi2m=0; // if (trackp&&TMath::Abs(trackp->fP3)<1.){ for (Int_t ilayer=clayer;ilayer<6;ilayer++){ if (trackp->fClIndex[ilayer]>0){ chi2p+=trackp->fDy[ilayer]*trackp->fDy[ilayer]/(trackp->fSigmaY[ilayer]*trackp->fSigmaY[ilayer])+ trackp->fDz[ilayer]*trackp->fDz[ilayer]/(trackp->fSigmaZ[ilayer]*trackp->fSigmaZ[ilayer]); } else{ chi2p+=9; } } }else{ chi2p = 0; } // if (trackm&&TMath::Abs(trackm->fP3)<1.){ for (Int_t ilayer=clayer;ilayer<6;ilayer++){ if (trackm->fClIndex[ilayer]>0){ chi2m+=trackm->fDy[ilayer]*trackm->fDy[ilayer]/(trackm->fSigmaY[ilayer]*trackm->fSigmaY[ilayer])+ trackm->fDz[ilayer]*trackm->fDz[ilayer]/(trackm->fSigmaZ[ilayer]*trackm->fSigmaZ[ilayer]); } else{ chi2m+=9; } } }else{ chi2m = 0; } vertex->SetChi2After(TMath::Max(chi2p,chi2m)); if (TMath::Max(chi2m,chi2p)/Float_t(6-clayer)>9) vertex->SetStatus(-20); // track not found in ITS } } // } void AliITStrackerMI::FindV02(AliESD *event) { // // V0 finder // // Cuts on DCA - R dependent // max distance DCA between 2 tracks cut // maxDist = TMath::Min(kMaxDist,kMaxDist0+pvertex->GetRr()*kMaxDist); // const Float_t kMaxDist0 = 0.1; const Float_t kMaxDist1 = 0.1; const Float_t kMaxDist = 1; const Float_t kMinPointAngle = 0.85; const Float_t kMinPointAngle2 = 0.99; const Float_t kMinR = 0.5; const Float_t kMaxR = 220; //const Float_t kCausality0Cut = 0.19; //const Float_t kLikelihood01Cut = 0.25; //const Float_t kPointAngleCut = 0.9996; const Float_t kCausality0Cut = 0.19; const Float_t kLikelihood01Cut = 0.45; const Float_t kLikelihood1Cut = 0.5; const Float_t kCombinedCut = 0.55; // // TTreeSRedirector &cstream = *fDebugStreamer; Int_t ntracks = event->GetNumberOfTracks(); Int_t nitstracks = fTrackHypothesys.GetEntriesFast(); fOriginal.Expand(ntracks); fTrackHypothesys.Expand(ntracks); fBestHypothesys.Expand(ntracks); // AliHelix * helixes = new AliHelix[ntracks+2]; TObjArray trackarray(ntracks+2); //array with tracks - with vertex constrain TObjArray trackarrayc(ntracks+2); //array of "best tracks" - without vertex constrain TObjArray trackarrayl(ntracks+2); //array of "longest tracks" - without vertex constrain Bool_t * forbidden = new Bool_t [ntracks+2]; Int_t *itsmap = new Int_t [ntracks+2]; Float_t *dist = new Float_t[ntracks+2]; Float_t *normdist0 = new Float_t[ntracks+2]; Float_t *normdist1 = new Float_t[ntracks+2]; Float_t *normdist = new Float_t[ntracks+2]; Float_t *norm = new Float_t[ntracks+2]; Float_t *maxr = new Float_t[ntracks+2]; Float_t *minr = new Float_t[ntracks+2]; Float_t *minPointAngle= new Float_t[ntracks+2]; // AliESDV0MI *pvertex = new AliESDV0MI; AliITStrackMI * dummy= new AliITStrackMI; dummy->SetLabel(0); AliITStrackMI trackat0; //temporary track for DCA calculation // Float_t primvertex[3]={GetX(),GetY(),GetZ()}; // // make its - esd map // for (Int_t itrack=0;itrack<ntracks+2;itrack++) { itsmap[itrack] = -1; forbidden[itrack] = kFALSE; maxr[itrack] = kMaxR; minr[itrack] = kMinR; minPointAngle[itrack] = kMinPointAngle; } for (Int_t itrack=0;itrack<nitstracks;itrack++){ AliITStrackMI * original = (AliITStrackMI*)(fOriginal.At(itrack)); Int_t esdindex = original->fESDtrack->GetID(); itsmap[esdindex] = itrack; } // // create its tracks from esd tracks if not done before // for (Int_t itrack=0;itrack<ntracks;itrack++){ if (itsmap[itrack]>=0) continue; AliITStrackMI * tpctrack = new AliITStrackMI(*(event->GetTrack(itrack))); tpctrack->fD[0] = tpctrack->GetD(GetX(),GetY()); tpctrack->fD[1] = tpctrack->GetZat(GetX())-GetZ(); if (tpctrack->fD[0]<20 && tpctrack->fD[1]<20){ // tracks which can reach inner part of ITS // propagate track to outer its volume - with correction for material CorrectForDeadZoneMaterial(tpctrack); } itsmap[itrack] = nitstracks; fOriginal.AddAt(tpctrack,nitstracks); nitstracks++; } // // fill temporary arrays // for (Int_t itrack=0;itrack<ntracks;itrack++){ AliESDtrack * esdtrack = event->GetTrack(itrack); Int_t itsindex = itsmap[itrack]; AliITStrackMI *original = (AliITStrackMI*)fOriginal.At(itsmap[itrack]); if (!original) continue; AliITStrackMI *bestConst = 0; AliITStrackMI *bestLong = 0; AliITStrackMI *best = 0; // // TObjArray * array = (TObjArray*) fTrackHypothesys.At(itsindex); Int_t hentries = (array==0) ? 0 : array->GetEntriesFast(); // Get best track with vertex constrain for (Int_t ih=0;ih<hentries;ih++){ AliITStrackMI * trackh = (AliITStrackMI*)array->At(ih); if (!trackh->fConstrain) continue; if (!bestConst) bestConst = trackh; if (trackh->fN>5.0){ bestConst = trackh; // full track - with minimal chi2 break; } if (trackh->fN+trackh->fNDeadZone<=bestConst->fN+bestConst->fNDeadZone) continue; bestConst = trackh; break; } // Get best long track without vertex constrain and best track without vertex constrain for (Int_t ih=0;ih<hentries;ih++){ AliITStrackMI * trackh = (AliITStrackMI*)array->At(ih); if (trackh->fConstrain) continue; if (!best) best = trackh; if (!bestLong) bestLong = trackh; if (trackh->fN>5.0){ bestLong = trackh; // full track - with minimal chi2 break; } if (trackh->fN+trackh->fNDeadZone<=bestLong->fN+bestLong->fNDeadZone) continue; bestLong = trackh; } if (!best) { best = original; bestLong = original; } trackat0 = *bestLong; Double_t xx,yy,zz,alpha; bestLong->GetGlobalXYZat(bestLong->GetX(),xx,yy,zz); alpha = TMath::ATan2(yy,xx); trackat0.Propagate(alpha,0); // calculate normalized distances to the vertex // Float_t ptfac = (1.+100.*TMath::Abs(trackat0.fP4)); if ( bestLong->fN>3 ){ dist[itsindex] = trackat0.fP0; norm[itsindex] = ptfac*TMath::Sqrt(trackat0.fC00); normdist0[itsindex] = TMath::Abs(trackat0.fP0/norm[itsindex]); normdist1[itsindex] = TMath::Abs((trackat0.fP1-primvertex[2])/(ptfac*TMath::Sqrt(trackat0.fC11))); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); if (!bestConst){ if (bestLong->fN+bestLong->fNDeadZone<6) normdist[itsindex]*=2.; if (bestLong->fN+bestLong->fNDeadZone<5) normdist[itsindex]*=2.; if (bestLong->fN+bestLong->fNDeadZone<4) normdist[itsindex]*=2.; }else{ if (bestConst->fN+bestConst->fNDeadZone<6) normdist[itsindex]*=1.5; if (bestConst->fN+bestConst->fNDeadZone<5) normdist[itsindex]*=1.5; } } else{ if (bestConst&&bestConst->fN+bestConst->fNDeadZone>4.5){ dist[itsindex] = bestConst->fD[0]; norm[itsindex] = bestConst->fDnorm[0]; normdist0[itsindex] = TMath::Abs(bestConst->fD[0]/norm[itsindex]); normdist1[itsindex] = TMath::Abs(bestConst->fD[0]/norm[itsindex]); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); }else{ dist[itsindex] = trackat0.fP0; norm[itsindex] = ptfac*TMath::Sqrt(trackat0.fC00); normdist0[itsindex] = TMath::Abs(trackat0.fP0/norm[itsindex]); normdist1[itsindex] = TMath::Abs((trackat0.fP1-primvertex[2])/(ptfac*TMath::Sqrt(trackat0.fC11))); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); if (TMath::Abs(trackat0.fP3)>1.05){ if (normdist[itsindex]<3) forbidden[itsindex]=kTRUE; if (normdist[itsindex]>3) { minr[itsindex] = TMath::Max(Float_t(40.),minr[itsindex]); } } } } // //----------------------------------------------------------- //Forbid primary track candidates - // //treetr->SetAlias("forbidden0","Tr0.fN<4&&Tr1.fN+Tr1.fNDeadZone>4.5"); //treetr->SetAlias("forbidden1","ND<3&&Tr1.fN+Tr1.fNDeadZone>5.5"); //treetr->SetAlias("forbidden2","ND<2&&Tr1.fClIndex[0]>0&&Tr1.fClIndex[0]>0"); //treetr->SetAlias("forbidden3","ND<1&&Tr1.fClIndex[0]>0"); //treetr->SetAlias("forbidden4","ND<4&&Tr1.fNormChi2[0]<2"); //treetr->SetAlias("forbidden5","ND<5&&Tr1.fNormChi2[0]<1"); //----------------------------------------------------------- if (bestConst){ if (bestLong->fN<4 && bestConst->fN+bestConst->fNDeadZone>4.5) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<3 && bestConst->fN+bestConst->fNDeadZone>5.5) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<2 && bestConst->fClIndex[0]>0 && bestConst->fClIndex[1]>0 ) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<1 && bestConst->fClIndex[0]>0) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<4 && bestConst->fNormChi2[0]<2) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<5 && bestConst->fNormChi2[0]<1) forbidden[itsindex]=kTRUE; if (bestConst->fNormChi2[0]<2.5) { minPointAngle[itsindex]= 0.9999; maxr[itsindex] = 10; } } // //forbid daughter kink candidates // if (esdtrack->GetKinkIndex(0)>0) forbidden[itsindex] = kTRUE; Bool_t isElectron = kTRUE; Bool_t isProton = kTRUE; Double_t pid[5]; esdtrack->GetESDpid(pid); for (Int_t i=1;i<5;i++){ if (pid[0]<pid[i]) isElectron= kFALSE; if (pid[4]<pid[i]) isProton= kFALSE; } if (isElectron){ forbidden[itsindex]=kFALSE; normdist[itsindex]*=-1; } if (isProton){ if (normdist[itsindex]>2) forbidden[itsindex]=kFALSE; normdist[itsindex]*=-1; } // // Causality cuts in TPC volume // if (esdtrack->GetTPCdensity(0,10) >0.6) maxr[itsindex] = TMath::Min(Float_t(110),maxr[itsindex]); if (esdtrack->GetTPCdensity(10,30)>0.6) maxr[itsindex] = TMath::Min(Float_t(120),maxr[itsindex]); if (esdtrack->GetTPCdensity(20,40)>0.6) maxr[itsindex] = TMath::Min(Float_t(130),maxr[itsindex]); if (esdtrack->GetTPCdensity(30,50)>0.6) maxr[itsindex] = TMath::Min(Float_t(140),maxr[itsindex]); // if (esdtrack->GetTPCdensity(0,60)<0.4&&bestLong->fN<3) minr[itsindex]=100; // // if (kFALSE){ cstream<<"Track"<< "Tr0.="<<best<< "Tr1.="<<((bestConst)? bestConst:dummy)<< "Tr2.="<<bestLong<< "Tr3.="<<&trackat0<< "Esd.="<<esdtrack<< "Dist="<<dist[itsindex]<< "ND0="<<normdist0[itsindex]<< "ND1="<<normdist1[itsindex]<< "ND="<<normdist[itsindex]<< "Pz="<<primvertex[2]<< "Forbid="<<forbidden[itsindex]<< "\n"; // } trackarray.AddAt(best,itsindex); trackarrayc.AddAt(bestConst,itsindex); trackarrayl.AddAt(bestLong,itsindex); new (&helixes[itsindex]) AliHelix(*best); } // // // // first iterration of V0 finder // for (Int_t iesd0=0;iesd0<ntracks;iesd0++){ Int_t itrack0 = itsmap[iesd0]; if (forbidden[itrack0]) continue; AliITStrackMI * btrack0 = (AliITStrackMI*)trackarray.At(itrack0); if (!btrack0) continue; if (btrack0->fP4>0) continue; AliITStrackMI *trackc0 = (AliITStrackMI*)trackarrayc.At(itrack0); // for (Int_t iesd1=0;iesd1<ntracks;iesd1++){ Int_t itrack1 = itsmap[iesd1]; if (forbidden[itrack1]) continue; AliITStrackMI * btrack1 = (AliITStrackMI*)trackarray.At(itrack1); if (!btrack1) continue; if (btrack1->fP4<0) continue; Bool_t isGold = kFALSE; if (TMath::Abs(TMath::Abs(btrack0->GetLabel())-TMath::Abs(btrack1->GetLabel()))==1){ isGold = kTRUE; } AliITStrackMI *trackc1 = (AliITStrackMI*)trackarrayc.At(itrack1); AliHelix &h1 = helixes[itrack0]; AliHelix &h2 = helixes[itrack1]; // // find linear distance Double_t rmin =0; // // // Double_t phase[2][2],radius[2]; Int_t points = h1.GetRPHIintersections(h2, phase, radius); if (points==0) continue; Double_t delta[2]={1000,1000}; rmin = radius[0]; h1.ParabolicDCA(h2,phase[0][0],phase[0][1],radius[0],delta[0]); if (points==2){ if (radius[1]<rmin) rmin = radius[1]; h1.ParabolicDCA(h2,phase[1][0],phase[1][1],radius[1],delta[1]); } rmin = TMath::Sqrt(rmin); Double_t distance = 0; Double_t radiusC = 0; Int_t iphase = 0; if (delta[0]<delta[1]){ distance = TMath::Sqrt(delta[0]); radiusC = TMath::Sqrt(radius[0]); }else{ distance = TMath::Sqrt(delta[1]); radiusC = TMath::Sqrt(radius[1]); iphase=1; } if (radiusC<TMath::Max(minr[itrack0],minr[itrack1])) continue; if (radiusC>TMath::Min(maxr[itrack0],maxr[itrack1])) continue; Float_t maxDist = TMath::Min(kMaxDist,Float_t(kMaxDist0+radiusC*kMaxDist1)); if (distance>maxDist) continue; Float_t pointAngle = h1.GetPointAngle(h2,phase[iphase],primvertex); if (pointAngle<TMath::Max(minPointAngle[itrack0],minPointAngle[itrack1])) continue; // // // Double_t distance = TestV0(h1,h2,pvertex,rmin); // // if (distance>maxDist) continue; // if (pvertex->GetRr()<kMinR) continue; // if (pvertex->GetRr()>kMaxR) continue; AliITStrackMI * track0=btrack0; AliITStrackMI * track1=btrack1; // if (pvertex->GetRr()<3.5){ if (radiusC<3.5){ //use longest tracks inside the pipe track0 = (AliITStrackMI*)trackarrayl.At(itrack0); track1 = (AliITStrackMI*)trackarrayl.At(itrack1); } // // pvertex->SetM(*track0); pvertex->SetP(*track1); pvertex->Update(primvertex); pvertex->SetClusters(track0->fClIndex,track1->fClIndex); // register clusters if (pvertex->GetRr()<kMinR) continue; if (pvertex->GetRr()>kMaxR) continue; if (pvertex->GetPointAngle()<kMinPointAngle) continue; if (pvertex->GetDist2()>maxDist) continue; pvertex->SetLab(0,track0->GetLabel()); pvertex->SetLab(1,track1->GetLabel()); pvertex->SetIndex(0,track0->fESDtrack->GetID()); pvertex->SetIndex(1,track1->fESDtrack->GetID()); // AliITStrackMI * htrackc0 = trackc0 ? trackc0:dummy; AliITStrackMI * htrackc1 = trackc1 ? trackc1:dummy; // // TObjArray * array0b = (TObjArray*)fBestHypothesys.At(itrack0); if (!array0b&&pvertex->GetRr()<40 && TMath::Abs(track0->fP3)<1.1) FollowProlongationTree((AliITStrackMI*)fOriginal.At(itrack0),itrack0, kFALSE); TObjArray * array1b = (TObjArray*)fBestHypothesys.At(itrack1); if (!array1b&&pvertex->GetRr()<40 && TMath::Abs(track1->fP3)<1.1) FollowProlongationTree((AliITStrackMI*)fOriginal.At(itrack1),itrack1, kFALSE); // AliITStrackMI * track0b = (AliITStrackMI*)fOriginal.At(itrack0); AliITStrackMI * track1b = (AliITStrackMI*)fOriginal.At(itrack1); AliITStrackMI * track0l = (AliITStrackMI*)fOriginal.At(itrack0); AliITStrackMI * track1l = (AliITStrackMI*)fOriginal.At(itrack1); Float_t minchi2before0=16; Float_t minchi2before1=16; Float_t minchi2after0 =16; Float_t minchi2after1 =16; Int_t maxLayer = GetNearestLayer(pvertex->GetXrp()); if (array0b) for (Int_t i=0;i<5;i++){ // best track after vertex AliITStrackMI * btrack = (AliITStrackMI*)array0b->At(i); if (!btrack) continue; if (btrack->fN>track0l->fN) track0l = btrack; // if (btrack->fX<pvertex->GetRr()-2.-0.5/(0.1+pvertex->GetAnglep()[2])) { if (btrack->fX<pvertex->GetRr()-2.) { if ( (maxLayer>i+2|| (i==0)) && btrack->fN==(6-i)&&i<3){ Float_t sumchi2= 0; Float_t sumn = 0; if (maxLayer<3){ // take prim vertex as additional measurement if (normdist[itrack0]>0 && htrackc0){ sumchi2 += TMath::Min((3.-maxLayer)*normdist[itrack0]*normdist[itrack0],16.); }else{ sumchi2 += TMath::Min((3.-maxLayer)*(3*normdist[itrack0]*normdist[itrack0]+3.),16.); } sumn += 3-maxLayer; } for (Int_t ilayer=i;ilayer<maxLayer;ilayer++){ sumn+=1.; if (!btrack->fClIndex[ilayer]){ sumchi2+=25; continue; }else{ Int_t c=( btrack->fClIndex[ilayer] & 0x0fffffff); for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[ilayer].fClusterTracks[itrack][c]>=0 && fgLayers[ilayer].fClusterTracks[itrack][c]!=itrack0){ sumchi2+=18.; //shared cluster break; } } sumchi2+=btrack->fDy[ilayer]*btrack->fDy[ilayer]/(btrack->fSigmaY[ilayer]*btrack->fSigmaY[ilayer]); sumchi2+=btrack->fDz[ilayer]*btrack->fDz[ilayer]/(btrack->fSigmaZ[ilayer]*btrack->fSigmaZ[ilayer]); } } sumchi2/=sumn; if (sumchi2<minchi2before0) minchi2before0=sumchi2; } continue; //safety space - Geo manager will give exact layer } track0b = btrack; minchi2after0 = btrack->fNormChi2[i]; break; } if (array1b) for (Int_t i=0;i<5;i++){ // best track after vertex AliITStrackMI * btrack = (AliITStrackMI*)array1b->At(i); if (!btrack) continue; if (btrack->fN>track1l->fN) track1l = btrack; // if (btrack->fX<pvertex->GetRr()-2-0.5/(0.1+pvertex->GetAnglep()[2])){ if (btrack->fX<pvertex->GetRr()-2){ if ((maxLayer>i+2 || (i==0))&&btrack->fN==(6-i)&&(i<3)){ Float_t sumchi2= 0; Float_t sumn = 0; if (maxLayer<3){ // take prim vertex as additional measurement if (normdist[itrack1]>0 && htrackc1){ sumchi2 += TMath::Min((3.-maxLayer)*normdist[itrack1]*normdist[itrack1],16.); }else{ sumchi2 += TMath::Min((3.-maxLayer)*(3*normdist[itrack1]*normdist[itrack1]+3.),16.); } sumn += 3-maxLayer; } for (Int_t ilayer=i;ilayer<maxLayer;ilayer++){ sumn+=1.; if (!btrack->fClIndex[ilayer]){ sumchi2+=30; continue; }else{ Int_t c=( btrack->fClIndex[ilayer] & 0x0fffffff); for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[ilayer].fClusterTracks[itrack][c]>=0 && fgLayers[ilayer].fClusterTracks[itrack][c]!=itrack1){ sumchi2+=18.; //shared cluster break; } } sumchi2+=btrack->fDy[ilayer]*btrack->fDy[ilayer]/(btrack->fSigmaY[ilayer]*btrack->fSigmaY[ilayer]); sumchi2+=btrack->fDz[ilayer]*btrack->fDz[ilayer]/(btrack->fSigmaZ[ilayer]*btrack->fSigmaZ[ilayer]); } } sumchi2/=sumn; if (sumchi2<minchi2before1) minchi2before1=sumchi2; } continue; //safety space - Geo manager will give exact layer } track1b = btrack; minchi2after1 = btrack->fNormChi2[i]; break; } // // position resolution - used for DCA cut Float_t sigmad = track0b->fC00+track0b->fC11+track1b->fC00+track1b->fC11+ (track0b->fX-pvertex->GetRr())*(track0b->fX-pvertex->GetRr())*(track0b->fC22+track0b->fC33)+ (track1b->fX-pvertex->GetRr())*(track1b->fX-pvertex->GetRr())*(track1b->fC22+track1b->fC33); sigmad =TMath::Sqrt(sigmad)+0.04; if (pvertex->GetRr()>50){ Double_t cov0[15],cov1[15]; track0b->fESDtrack->GetInnerExternalCovariance(cov0); track1b->fESDtrack->GetInnerExternalCovariance(cov1); sigmad = cov0[0]+cov0[2]+cov1[0]+cov1[2]+ (80.-pvertex->GetRr())*(80.-pvertex->GetRr())*(cov0[5]+cov0[9])+ (80.-pvertex->GetRr())*(80.-pvertex->GetRr())*(cov1[5]+cov1[9]); sigmad =TMath::Sqrt(sigmad)+0.05; } // AliESDV0MI vertex2; vertex2.SetM(*track0b); vertex2.SetP(*track1b); vertex2.Update(primvertex); if (vertex2.GetDist2()<=pvertex->GetDist2()&&(vertex2.GetPointAngle()>=pvertex->GetPointAngle())){ pvertex->SetM(*track0b); pvertex->SetP(*track1b); pvertex->Update(primvertex); pvertex->SetClusters(track0b->fClIndex,track1b->fClIndex); // register clusters pvertex->SetIndex(0,track0->fESDtrack->GetID()); pvertex->SetIndex(1,track1->fESDtrack->GetID()); } pvertex->SetDistSigma(sigmad); pvertex->SetDistNorm(pvertex->GetDist2()/sigmad); pvertex->SetNormDCAPrim(normdist[itrack0],normdist[itrack1]); // // define likelihhod and causalities // Float_t pa0=1, pa1=1, pb0=0.26, pb1=0.26; if (maxLayer<1){ Float_t fnorm0 = normdist[itrack0]; if (fnorm0<0) fnorm0*=-3; Float_t fnorm1 = normdist[itrack1]; if (fnorm1<0) fnorm1*=-3; if (pvertex->GetAnglep()[2]>0.1 || (pvertex->GetRr()<10.5)&& pvertex->GetAnglep()[2]>0.05 || pvertex->GetRr()<3){ pb0 = TMath::Exp(-TMath::Min(fnorm0,Float_t(16.))/12.); pb1 = TMath::Exp(-TMath::Min(fnorm1,Float_t(16.))/12.); } pvertex->SetChi2Before(normdist[itrack0]); pvertex->SetChi2After(normdist[itrack1]); pvertex->SetNAfter(0); pvertex->SetNBefore(0); }else{ pvertex->SetChi2Before(minchi2before0); pvertex->SetChi2After(minchi2before1); if (pvertex->GetAnglep()[2]>0.1 || ( pvertex->GetRr()<10.5 && pvertex->GetAnglep()[2]>0.05) || pvertex->GetRr()<3){ pb0 = TMath::Exp(-TMath::Min(minchi2before0,Float_t(16))/12.); pb1 = TMath::Exp(-TMath::Min(minchi2before1,Float_t(16))/12.); } pvertex->SetNAfter(maxLayer); pvertex->SetNBefore(maxLayer); } if (pvertex->GetRr()<90){ pa0 *= TMath::Min(track0->fESDtrack->GetTPCdensity(0,60),Float_t(1.)); pa1 *= TMath::Min(track1->fESDtrack->GetTPCdensity(0,60),Float_t(1.)); } if (pvertex->GetRr()<20){ pa0 *= (0.2+TMath::Exp(-TMath::Min(minchi2after0,Float_t(16))/8.))/1.2; pa1 *= (0.2+TMath::Exp(-TMath::Min(minchi2after1,Float_t(16))/8.))/1.2; } // pvertex->SetCausality(pb0,pb1,pa0,pa1); // // Likelihood calculations - apply cuts // Bool_t v0OK = kTRUE; Float_t p12 = pvertex->GetParamP()->GetParameter()[4]*pvertex->GetParamP()->GetParameter()[4]; p12 += pvertex->GetParamM()->GetParameter()[4]*pvertex->GetParamM()->GetParameter()[4]; p12 = TMath::Sqrt(p12); // "mean" momenta Float_t sigmap0 = 0.0001+0.001/(0.1+pvertex->GetRr()); Float_t sigmap = 0.5*sigmap0*(0.6+0.4*p12); // "resolution: of point angle - as a function of radius and momenta Float_t causalityA = (1.0-pvertex->GetCausalityP()[0])*(1.0-pvertex->GetCausalityP()[1]); Float_t causalityB = TMath::Sqrt(TMath::Min(pvertex->GetCausalityP()[2],Float_t(0.7))* TMath::Min(pvertex->GetCausalityP()[3],Float_t(0.7))); // Float_t likelihood0 = (TMath::Exp(-pvertex->GetDistNorm())+0.1) *(pvertex->GetDist2()<0.5)*(pvertex->GetDistNorm()<5); Float_t likelihood1 = TMath::Exp(-(1.0001-pvertex->GetPointAngle())/sigmap)+ 0.4*TMath::Exp(-(1.0001-pvertex->GetPointAngle())/(4.*sigmap))+ 0.4*TMath::Exp(-(1.0001-pvertex->GetPointAngle())/(8.*sigmap))+ 0.1*TMath::Exp(-(1.0001-pvertex->GetPointAngle())/0.01); // if (causalityA<kCausality0Cut) v0OK = kFALSE; if (TMath::Sqrt(likelihood0*likelihood1)<kLikelihood01Cut) v0OK = kFALSE; if (likelihood1<kLikelihood1Cut) v0OK = kFALSE; if (TMath::Power(likelihood0*likelihood1*causalityB,0.33)<kCombinedCut) v0OK = kFALSE; // // if (kFALSE){ Bool_t gold = TMath::Abs(TMath::Abs(track0->GetLabel())-TMath::Abs(track1->GetLabel()))==1; cstream<<"It0"<< "Tr0.="<<track0<< //best without constrain "Tr1.="<<track1<< //best without constrain "Tr0B.="<<track0b<< //best without constrain after vertex "Tr1B.="<<track1b<< //best without constrain after vertex "Tr0C.="<<htrackc0<< //best with constrain if exist "Tr1C.="<<htrackc1<< //best with constrain if exist "Tr0L.="<<track0l<< //longest best "Tr1L.="<<track1l<< //longest best "Esd0.="<<track0->fESDtrack<< // esd track0 params "Esd1.="<<track1->fESDtrack<< // esd track1 params "V0.="<<pvertex<< //vertex properties "V0b.="<<&vertex2<< //vertex properties at "best" track "ND0="<<normdist[itrack0]<< //normalize distance for track0 "ND1="<<normdist[itrack1]<< //normalize distance for track1 "Gold="<<gold<< // // "RejectBase="<<rejectBase<< //rejection in First itteration "OK="<<v0OK<< "rmin="<<rmin<< "sigmad="<<sigmad<< "\n"; } //if (rejectBase) continue; // pvertex->SetStatus(0); // if (rejectBase) { // pvertex->SetStatus(-100); //} if (pvertex->GetPointAngle()>kMinPointAngle2) { pvertex->SetESDindexes(track0->fESDtrack->GetID(),track1->fESDtrack->GetID()); if (v0OK){ // AliV0vertex vertexjuri(*track0,*track1); // vertexjuri.SetESDindexes(track0->fESDtrack->GetID(),track1->fESDtrack->GetID()); // event->AddV0(&vertexjuri); pvertex->SetStatus(100); } event->AddV0MI(pvertex); } } } // // // delete temporary arrays // delete[] minPointAngle; delete[] maxr; delete[] minr; delete[] norm; delete[] normdist; delete[] normdist1; delete[] normdist0; delete[] dist; delete[] itsmap; delete[] helixes; delete pvertex; } void AliITStrackerMI::RefitV02(AliESD *event) { // //try to refit V0s in the third path of the reconstruction // TTreeSRedirector &cstream = *fDebugStreamer; // Int_t nv0s = event->GetNumberOfV0MIs(); Float_t primvertex[3]={GetX(),GetY(),GetZ()}; AliESDV0MI v0temp; for (Int_t iv0 = 0; iv0<nv0s;iv0++){ AliESDV0MI * v0mi = event->GetV0MI(iv0); if (!v0mi) continue; Int_t itrack0 = v0mi->GetIndex(0); Int_t itrack1 = v0mi->GetIndex(1); AliESDtrack *esd0 = event->GetTrack(itrack0); AliESDtrack *esd1 = event->GetTrack(itrack1); if (!esd0||!esd1) continue; AliITStrackMI tpc0(*esd0); AliITStrackMI tpc1(*esd1); Double_t alpha =TMath::ATan2(v0mi->GetXr(1),v0mi->GetXr(0)); if (v0mi->GetRr()>85){ if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ v0temp.SetM(tpc0); v0temp.SetP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetPointAngle()>v0mi->GetPointAngle()){ v0mi->SetM(tpc0); v0mi->SetP(tpc1); v0mi->Update(primvertex); } } continue; } if (v0mi->GetRr()>35){ CorrectForDeadZoneMaterial(&tpc0); CorrectForDeadZoneMaterial(&tpc1); if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ v0temp.SetM(tpc0); v0temp.SetP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetPointAngle()>v0mi->GetPointAngle()){ v0mi->SetM(tpc0); v0mi->SetP(tpc1); v0mi->Update(primvertex); } } continue; } CorrectForDeadZoneMaterial(&tpc0); CorrectForDeadZoneMaterial(&tpc1); // if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ if (RefitAt(v0mi->GetRr(),&tpc0, v0mi->GetClusters(0)) && RefitAt(v0mi->GetRr(),&tpc1, v0mi->GetClusters(1))){ v0temp.SetM(tpc0); v0temp.SetP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetPointAngle()>v0mi->GetPointAngle()){ v0mi->SetM(tpc0); v0mi->SetP(tpc1); v0mi->Update(primvertex); } } } }
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: extrusionbar.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2006-01-10 14:52:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEPARAMETERPARIR_HPP_ #include <com/sun/star/drawing/EnhancedCustomShapeParameterPair.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEPARAMETERTYPE_HPP_ #include <com/sun/star/drawing/EnhancedCustomShapeParameterType.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_SHADEMODE_HPP_ #include <com/sun/star/drawing/ShadeMode.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_ #include <com/sun/star/drawing/Position3D.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_DIRECTION3D_HPP_ #include <com/sun/star/drawing/Direction3D.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_PROJECTIONMODE_HPP_ #include <com/sun/star/drawing/ProjectionMode.hpp> #endif #ifndef _SVDUNDO_HXX #include <svdundo.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SFXREQUEST_HXX #include <sfx2/request.hxx> #endif #ifndef _SFXOBJFACE_HXX #include <sfx2/objface.hxx> #endif #ifndef _SFXVIEWSH_HXX #include <sfx2/viewsh.hxx> #endif #ifndef _SFX_BINDINGS_HXX #include <sfx2/bindings.hxx> #endif #ifndef _SVX_XSFLCLIT_HXX #include "xsflclit.hxx" #endif #ifndef _SVX_DIALMGR_HXX #include "dialmgr.hxx" #endif #ifndef _SVDOASHP_HXX #include "svdoashp.hxx" #endif #ifndef _SVX_DIALOGS_HRC #include "dialogs.hrc" #endif #ifndef _SVDVIEW_HXX #include "svdview.hxx" #endif #define ITEMID_COLOR 0 #ifndef _SVX_COLRITEM_HXX #include "colritem.hxx" #endif #define ITEMID_DOUBLE 0 #include "chrtitem.hxx" #include "extrusionbar.hxx" #include "extrusioncontrols.hxx" using namespace ::svx; using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::uno; /************************************************************************* |* |* Standardinterface deklarieren (Die Slotmap darf nicht leer sein, also |* tragen wir etwas ein, was hier (hoffentlich) nie vorkommt). |* \************************************************************************/ #define ShellClass ExtrusionBar SFX_SLOTMAP(ExtrusionBar) { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; SFX_IMPL_INTERFACE(ExtrusionBar, SfxShell, SVX_RES(RID_SVX_EXTRUSION_BAR)) { SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OBJECT, SVX_RES(RID_SVX_EXTRUSION_BAR) ); } TYPEINIT1( ExtrusionBar, SfxShell ); /************************************************************************* |* |* Standard-Konstruktor |* \************************************************************************/ ExtrusionBar::ExtrusionBar(SfxViewShell* pViewShell ) : SfxShell(pViewShell) { DBG_ASSERT( pViewShell, "svx::ExtrusionBar::ExtrusionBar(), I need a viewshell!" ); if( pViewShell ) SetPool(&pViewShell->GetPool()); SetHelpId( SVX_INTERFACE_EXTRUSION_BAR ); SetName( String( SVX_RES( RID_SVX_EXTRUSION_BAR ))); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ ExtrusionBar::~ExtrusionBar() { SetRepeatTarget(NULL); } void getLightingDirectionDefaults( const Direction3D **pLighting1Defaults, const Direction3D **pLighting2Defaults ) { static const Direction3D aLighting1Defaults[9] = { Direction3D( -50000, -50000, 10000 ), Direction3D( 0, -50000, 10000 ), Direction3D( 50000, -50000, 10000 ), Direction3D( -50000, 0, 10000 ), Direction3D( 0, 0, 10000 ), Direction3D( 50000, 0, 10000 ), Direction3D( -50000, 50000, 10000 ), Direction3D( 0, 50000, 10000 ), Direction3D( 50000, 50000, 10000 ) }; static const Direction3D aLighting2Defaults[9] = { Direction3D( 50000,0, 10000 ), Direction3D( 0, 50000, 10000 ), Direction3D( -50000, 0, 10000 ), Direction3D( 50000, 0, 10000 ), Direction3D( 0, 0, 10000 ), Direction3D( -50000, 0, 10000 ), Direction3D( 50000, 0, 10000 ), Direction3D( 0, -50000, 10000 ), Direction3D( -50000, 0, 10000 ) }; *pLighting1Defaults = (const Direction3D *)aLighting1Defaults; *pLighting2Defaults = (const Direction3D *)aLighting2Defaults; }; static void impl_execute( SdrView* pSdrView, SfxRequest& rReq, SdrCustomShapeGeometryItem& rGeometryItem, SdrObject* pObj ) { static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sProjectionMode( RTL_CONSTASCII_USTRINGPARAM ( "ProjectionMode" ) ); static const rtl::OUString sRotateAngle( RTL_CONSTASCII_USTRINGPARAM ( "RotateAngle" ) ); static const rtl::OUString sViewPoint( RTL_CONSTASCII_USTRINGPARAM ( "ViewPoint" ) ); static const rtl::OUString sOrigin( RTL_CONSTASCII_USTRINGPARAM ( "Origin" ) ); static const rtl::OUString sSkew( RTL_CONSTASCII_USTRINGPARAM ( "Skew" ) ); static const rtl::OUString sDepth( RTL_CONSTASCII_USTRINGPARAM ( "Depth" ) ); sal_uInt16 nSID = rReq.GetSlot(); switch( nSID ) { case SID_EXTRUSION_TOOGLE: { com::sun::star::uno::Any* pAny = rGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) { sal_Bool bOn; (*pAny) >>= bOn; bOn = !bOn; (*pAny) <<= bOn; } else { com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sExtrusion; aPropValue.Value <<= sal_True; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_TILT_DOWN: case SID_EXTRUSION_TILT_UP: case SID_EXTRUSION_TILT_LEFT: case SID_EXTRUSION_TILT_RIGHT: { sal_Bool bHorizontal = ( nSID == SID_EXTRUSION_TILT_DOWN ) || ( nSID == SID_EXTRUSION_TILT_UP ); sal_Int32 nDiff = ( nSID == SID_EXTRUSION_TILT_LEFT ) || ( nSID == SID_EXTRUSION_TILT_UP ) ? 5 : -5; EnhancedCustomShapeParameterPair aRotateAnglePropPair; double fX = 0.0; double fY = 0.0; aRotateAnglePropPair.First.Value <<= fX; aRotateAnglePropPair.First.Type = EnhancedCustomShapeParameterType::NORMAL; aRotateAnglePropPair.Second.Value <<= fY; aRotateAnglePropPair.Second.Type = EnhancedCustomShapeParameterType::NORMAL; com::sun::star::uno::Any* pAny = rGeometryItem.GetPropertyValueByName( sExtrusion, sRotateAngle ); if( pAny && ( *pAny >>= aRotateAnglePropPair ) ) { aRotateAnglePropPair.First.Value >>= fX; aRotateAnglePropPair.Second.Value >>= fY; } if ( bHorizontal ) fX += nDiff; else fY += nDiff; aRotateAnglePropPair.First.Value <<= fX; aRotateAnglePropPair.Second.Value <<= fY; com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sRotateAngle; aPropValue.Value <<= aRotateAnglePropPair; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } break; case SID_EXTRUSION_DIRECTION: { if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_DIRECTION ) == SFX_ITEM_SET ) { sal_Int32 nSkew = ((const SfxInt32Item*)rReq.GetArgs()->GetItem(SID_EXTRUSION_DIRECTION))->GetValue(); sal_Bool bParallel = sal_True; Position3D aViewPoint( 3472, -3472, 25000 ); double fOriginX = 0.50; double fOriginY = -0.50; double fSkewAngle = nSkew; double fSkew = 50.0; switch( nSkew ) { case 135: aViewPoint.PositionY = 3472; fOriginY = 0.50; break; case 90: aViewPoint.PositionX = 0; aViewPoint.PositionY = 3472; fOriginX = 0; fOriginY = -0.50; break; case 45: aViewPoint.PositionX = -3472; aViewPoint.PositionY = 3472; fOriginX = -0.50; fOriginY = 0.50; break; case 180: aViewPoint.PositionY = 0; fOriginY = 0; break; case 0: aViewPoint.PositionX = 0; aViewPoint.PositionY = 0; fOriginX = 0; fOriginY = 0; fSkew = 0.0; break; case -360: aViewPoint.PositionX = -3472; aViewPoint.PositionY = 0; fOriginX = -0.50; fOriginY = 0; break; case -90: aViewPoint.PositionX = 0; fOriginX = 0; break; case -45: aViewPoint.PositionX = -3472; fOriginX = -0.50; break; } com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sViewPoint; aPropValue.Value <<= aViewPoint; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); EnhancedCustomShapeParameterPair aOriginPropPair; aOriginPropPair.First.Value <<= fOriginX; aOriginPropPair.First.Type = EnhancedCustomShapeParameterType::NORMAL; aOriginPropPair.Second.Value <<= fOriginY; aOriginPropPair.Second.Type = EnhancedCustomShapeParameterType::NORMAL; aPropValue.Name = sOrigin; aPropValue.Value <<= aOriginPropPair; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); EnhancedCustomShapeParameterPair aSkewPropPair; aSkewPropPair.First.Value <<= fSkew; aSkewPropPair.First.Type = EnhancedCustomShapeParameterType::NORMAL; aSkewPropPair.Second.Value <<= fSkewAngle; aSkewPropPair.Second.Type = EnhancedCustomShapeParameterType::NORMAL; aPropValue.Name = sSkew; aPropValue.Value <<= aSkewPropPair; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_PROJECTION: { if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_PROJECTION ) == SFX_ITEM_SET ) { sal_Int32 nProjection = ((const SfxInt32Item*)rReq.GetArgs()->GetItem(SID_EXTRUSION_PROJECTION))->GetValue(); ProjectionMode eProjectionMode = nProjection == 1 ? ProjectionMode_PARALLEL : ProjectionMode_PERSPECTIVE; com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sProjectionMode; aPropValue.Value <<= eProjectionMode; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_DEPTH: { if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_DEPTH ) == SFX_ITEM_SET) { double fDepth = ((const SvxDoubleItem*)rReq.GetArgs()->GetItem(SID_EXTRUSION_DEPTH))->GetValue(); double fFraction = 0.0; EnhancedCustomShapeParameterPair aDepthPropPair; aDepthPropPair.First.Value <<= fDepth; aDepthPropPair.First.Type = EnhancedCustomShapeParameterType::NORMAL; aDepthPropPair.Second.Value <<= fFraction; aDepthPropPair.Second.Type = EnhancedCustomShapeParameterType::NORMAL; com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sDepth; aPropValue.Value <<= aDepthPropPair; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_3D_COLOR: { static const rtl::OUString sExtrusionColor( RTL_CONSTASCII_USTRINGPARAM ( "Color" ) ); if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_3D_COLOR ) == SFX_ITEM_SET) { Color aColor( ((const SvxColorItem&)rReq.GetArgs()->Get(SID_EXTRUSION_3D_COLOR)).GetValue() ); const bool bAuto = aColor == COL_AUTO; com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sExtrusionColor; aPropValue.Value <<= bAuto ? sal_False : sal_True; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); if( bAuto ) { pObj->ClearMergedItem( XATTR_SECONDARYFILLCOLOR ); } else { pObj->SetMergedItem( XSecondaryFillColorItem( String(), aColor ) ); } pObj->BroadcastObjectChange(); } } break; case SID_EXTRUSION_SURFACE: { static const rtl::OUString sShadeMode( RTL_CONSTASCII_USTRINGPARAM ( "ShadeMode" ) ); static const rtl::OUString sSpecularity( RTL_CONSTASCII_USTRINGPARAM ( "Specularity" ) ); static const rtl::OUString sDiffusion( RTL_CONSTASCII_USTRINGPARAM ( "Diffusion" ) ); static const rtl::OUString sMetal( RTL_CONSTASCII_USTRINGPARAM ( "Metal" ) ); if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_SURFACE ) == SFX_ITEM_SET) { sal_Int32 nSurface = ((const SfxInt32Item*)rReq.GetArgs()->GetItem(SID_EXTRUSION_SURFACE))->GetValue(); ShadeMode eShadeMode( ShadeMode_FLAT ); sal_Bool bMetal = sal_False; double fSpecularity = 0; double fDiffusion = 0; switch( nSurface ) { case 0: // wireframe eShadeMode = ShadeMode_DRAFT; break; case 1: // matte break; case 2: // plastic fSpecularity = 122.0; break; case 3: // metal bMetal = true; fSpecularity = 122.0; fDiffusion = 122.0; break; } com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sShadeMode; aPropValue.Value <<= eShadeMode; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sMetal; aPropValue.Value <<= bMetal; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sSpecularity; aPropValue.Value <<= fSpecularity; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sDiffusion; aPropValue.Value <<= fDiffusion; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_LIGHTING_INTENSITY: { static const rtl::OUString sBrightness( RTL_CONSTASCII_USTRINGPARAM ( "Brightness" ) ); static const rtl::OUString sLightFace( RTL_CONSTASCII_USTRINGPARAM ( "LightFace" ) ); static const rtl::OUString sFirstLightHarsh( RTL_CONSTASCII_USTRINGPARAM ( "FirstLightHarsh" ) ); static const rtl::OUString sSecondLightHarsh( RTL_CONSTASCII_USTRINGPARAM ( "SecondLightHarsh" ) ); static const rtl::OUString sFirstLightLevel( RTL_CONSTASCII_USTRINGPARAM ( "FirstLightLevel" ) ); static const rtl::OUString sSecondLightLevel( RTL_CONSTASCII_USTRINGPARAM ( "SecondLightLevel" ) ); if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_LIGHTING_INTENSITY ) == SFX_ITEM_SET) { sal_Int32 nLevel = ((const SfxInt32Item*)rReq.GetArgs()->GetItem(SID_EXTRUSION_LIGHTING_INTENSITY))->GetValue(); double fBrightness; sal_Bool bHarsh2; double fLevel1; double fLevel2; switch( nLevel ) { case 0: // bright fBrightness = 34.0; bHarsh2 = sal_False; fLevel1 = 66.0; fLevel2 = 66.0; break; case 1: // normal fBrightness = 15.0; bHarsh2 = sal_False; fLevel1 = 67.0; fLevel2 = 37.0; break; case 2: // dim fBrightness = 6.0; bHarsh2 = sal_True; fLevel1 = 79.0; fLevel2 = 21.0; break; } com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sBrightness; aPropValue.Value <<= fBrightness; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sLightFace; aPropValue.Value <<= sal_True; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sFirstLightHarsh; aPropValue.Value <<= sal_True; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sSecondLightHarsh; aPropValue.Value <<= bHarsh2; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sFirstLightLevel; aPropValue.Value <<= fLevel1; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sSecondLightLevel; aPropValue.Value <<= fLevel2; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_LIGHTING_DIRECTION: { if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_LIGHTING_DIRECTION ) == SFX_ITEM_SET) { sal_Int32 nDirection = ((const SfxInt32Item*)rReq.GetArgs()->GetItem(SID_EXTRUSION_LIGHTING_DIRECTION))->GetValue(); if((nDirection >= 0) && (nDirection < 9)) { const rtl::OUString sFirstLightDirection( RTL_CONSTASCII_USTRINGPARAM ( "FirstLightDirection" ) ); const rtl::OUString sSecondLightDirection( RTL_CONSTASCII_USTRINGPARAM ( "SecondLightDirection" ) ); const Direction3D * pLighting1Defaults; const Direction3D * pLighting2Defaults; getLightingDirectionDefaults( &pLighting1Defaults, &pLighting2Defaults ); com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sFirstLightDirection; aPropValue.Value <<= pLighting1Defaults[nDirection]; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sSecondLightDirection; aPropValue.Value <<= pLighting2Defaults[nDirection]; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } } break; } } void ExtrusionBar::execute( SdrView* pSdrView, SfxRequest& rReq, SfxBindings& rBindings ) { sal_uInt16 nSID = rReq.GetSlot(); sal_uInt16 nStrResId = 0; switch( nSID ) { case SID_EXTRUSION_TOOGLE: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ON_OFF; } // PASSTROUGH case SID_EXTRUSION_TILT_DOWN: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ROTATE_DOWN; } // PASSTROUGH case SID_EXTRUSION_TILT_UP: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ROTATE_UP; } // PASSTROUGH case SID_EXTRUSION_TILT_LEFT: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ROTATE_LEFT; } // PASSTROUGH case SID_EXTRUSION_TILT_RIGHT: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ROTATE_RIGHT; } // PASSTROUGH case SID_EXTRUSION_DIRECTION: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ORIENTATION; } // PASSTROUGH case SID_EXTRUSION_PROJECTION: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_PROJECTION; } // PASSTROUGH case SID_EXTRUSION_DEPTH: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_DEPTH; } // PASSTROUGH case SID_EXTRUSION_3D_COLOR: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_COLOR; } // PASSTROUGH case SID_EXTRUSION_SURFACE: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_SURFACE; } // PASSTROUGH case SID_EXTRUSION_LIGHTING_INTENSITY: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_BRIGHTNESS; } // PASSTROUGH case SID_EXTRUSION_LIGHTING_DIRECTION: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_LIGHTING; const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; for(i=0; i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { String aStr( SVX_RES( nStrResId ) ); pSdrView->BegUndo( aStr ); pSdrView->AddUndo( pSdrView->GetModel()->GetSdrUndoFactory().CreateUndoAttrObject( *pObj ) ); SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); impl_execute( pSdrView, rReq, aGeometryItem, pObj ); pObj->SetMergedItem( aGeometryItem ); pObj->BroadcastObjectChange(); pSdrView->EndUndo(); // simulate a context change: // force SelectionHasChanged() being called // so that extrusion bar will be visible/hidden pSdrView->MarkListHasChanged(); } } } break; case SID_EXTRUSION_DEPTH_DIALOG: if( rReq.GetArgs() && (rReq.GetArgs()->GetItemState( SID_EXTRUSION_DEPTH ) == SFX_ITEM_SET) && (rReq.GetArgs()->GetItemState( SID_ATTR_METRIC ) == SFX_ITEM_SET)) { double fDepth = ((const SvxDoubleItem*)rReq.GetArgs()->GetItem(SID_EXTRUSION_DEPTH))->GetValue(); FieldUnit eUnit = (FieldUnit)((const SfxUInt16Item*)rReq.GetArgs()->GetItem(SID_ATTR_METRIC))->GetValue(); ExtrusionDepthDialog aDlg( 0L, fDepth, eUnit ); USHORT nRet = aDlg.Execute(); if( nRet != 0 ) { fDepth = aDlg.getDepth(); SvxDoubleItem aItem( fDepth, SID_EXTRUSION_DEPTH ); SfxPoolItem* aItems[] = { &aItem, 0 }; rBindings.Execute( SID_EXTRUSION_DEPTH, (const SfxPoolItem**)aItems ); } } break; } if( nSID == SID_EXTRUSION_TOOGLE ) { static USHORT SidArray[] = { SID_EXTRUSION_TILT_DOWN, SID_EXTRUSION_TILT_UP, SID_EXTRUSION_TILT_LEFT, SID_EXTRUSION_TILT_RIGHT, SID_EXTRUSION_DEPTH_FLOATER, SID_EXTRUSION_DIRECTION_FLOATER, SID_EXTRUSION_LIGHTING_FLOATER, SID_EXTRUSION_SURFACE_FLOATER, SID_EXTRUSION_3D_COLOR, SID_EXTRUSION_DEPTH, SID_EXTRUSION_DIRECTION, SID_EXTRUSION_PROJECTION, SID_EXTRUSION_LIGHTING_DIRECTION, SID_EXTRUSION_LIGHTING_INTENSITY, SID_EXTRUSION_SURFACE, 0 }; rBindings.Invalidate( SidArray ); } } void getExtrusionDirectionState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sViewPoint( RTL_CONSTASCII_USTRINGPARAM ( "ViewPoint" ) ); static const rtl::OUString sOrigin( RTL_CONSTASCII_USTRINGPARAM ( "Origin" ) ); static const rtl::OUString sSkew( RTL_CONSTASCII_USTRINGPARAM ( "Skew" ) ); static const rtl::OUString sProjectionMode( RTL_CONSTASCII_USTRINGPARAM ( "ProjectionMode" ) ); com::sun::star::uno::Any* pAny; double fFinalSkewAngle = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) *pAny >>= bHasCustomShape; if( !bHasCustomShape ) continue; } sal_Bool bParallel = sal_True; Position3D aViewPoint( 3472, -3472, 25000 ); double fOriginX = 0.50; double fOriginY = -0.50; double fSkewAngle = -135; double fSkew = 50.0; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sProjectionMode ); sal_Int16 nProjectionMode; if( pAny && ( *pAny >>= nProjectionMode ) ) bParallel = nProjectionMode == ProjectionMode_PARALLEL; if( bParallel ) { EnhancedCustomShapeParameterPair aSkewPropPair; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sSkew ); if( pAny && ( *pAny >>= aSkewPropPair ) ) { aSkewPropPair.First.Value >>= fSkew; aSkewPropPair.Second.Value >>= fSkewAngle; } if ( fSkew == 0.0 ) fSkewAngle = 0.0; else if ( fSkewAngle == 0.0 ) fSkewAngle = -360.0; } else { pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sViewPoint ); if( pAny ) *pAny >>= aViewPoint; EnhancedCustomShapeParameterPair aOriginPropPair; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sOrigin ); if( pAny && ( *pAny >>= aOriginPropPair ) ) { aOriginPropPair.First.Value >>= fOriginX; aOriginPropPair.Second.Value >>= fOriginY; } fSkewAngle = -1; const double e = 0.0001; if( aViewPoint.PositionX > e ) { if( aViewPoint.PositionY > e ) { if( (fOriginX > e ) && ( fOriginY > e ) ) fSkewAngle = 135.0; } else if( aViewPoint.PositionY < -e ) { if( ( fOriginX > e ) && ( fOriginY < -e ) ) fSkewAngle = -135.0; } else { if( ( fOriginX > e ) && ( fOriginY > -e ) && ( fOriginY < e ) ) fSkewAngle = 180.0; } } else if( aViewPoint.PositionX < -e ) { if( aViewPoint.PositionY < -e ) { if( ( fOriginX < -e ) && ( fOriginY < -e ) ) fSkewAngle = -45.0; } else if( aViewPoint.PositionY > e ) { if( ( fOriginX < -e ) && ( fOriginY > e ) ) fSkewAngle = 45.0; } else { if( ( fOriginX < e ) && ( fOriginY > -e ) && ( fOriginY < e ) ) fSkewAngle = -360.0; } } else { if( aViewPoint.PositionY < -e ) { if( ( fOriginX > -e ) && ( fOriginX < e ) && ( fOriginY < -e ) ) fSkewAngle = -90.0; } else if( aViewPoint.PositionY > e ) { if( ( fOriginX > -e ) && ( fOriginX < e ) && ( fOriginY > e ) ) fSkewAngle = 90.0; } else { if( ( fOriginX > -e ) && ( fOriginX < e ) && ( fOriginY > -e ) && ( fOriginY < e ) ) fSkewAngle = 0.0; } } } if( fFinalSkewAngle == -1.0 ) { fFinalSkewAngle = fSkewAngle; } else if( fSkewAngle != fFinalSkewAngle ) { fFinalSkewAngle = -1.0; } if( fFinalSkewAngle == -1.0 ) break; } } if( bHasCustomShape ) rSet.Put( SfxInt32Item( SID_EXTRUSION_DIRECTION, (sal_Int32)fFinalSkewAngle ) ); else rSet.DisableItem( SID_EXTRUSION_DIRECTION ); } void getExtrusionProjectionState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sProjectionMode( RTL_CONSTASCII_USTRINGPARAM ( "ProjectionMode" ) ); com::sun::star::uno::Any* pAny; sal_Int32 nFinalProjection = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { // see if this is an extruded customshape if( !bHasCustomShape ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); Any* pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) *pAny >>= bHasCustomShape; if( !bHasCustomShape ) continue; } SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); sal_Bool bParallel = sal_True; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sProjectionMode ); ProjectionMode eProjectionMode; if( pAny && ( *pAny >>= eProjectionMode ) ) bParallel = eProjectionMode == ProjectionMode_PARALLEL; if( nFinalProjection == -1 ) { nFinalProjection = bParallel; } else if( nFinalProjection != bParallel ) { nFinalProjection = -1; break; } } } if( bHasCustomShape ) rSet.Put( SfxInt32Item( SID_EXTRUSION_PROJECTION, nFinalProjection ) ); else rSet.DisableItem( SID_EXTRUSION_PROJECTION ); } void getExtrusionSurfaceState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sShadeMode( RTL_CONSTASCII_USTRINGPARAM ( "ShadeMode" ) ); static const rtl::OUString sSpecularity( RTL_CONSTASCII_USTRINGPARAM ( "Specularity" ) ); static const rtl::OUString sDiffusion( RTL_CONSTASCII_USTRINGPARAM ( "Diffusion" ) ); static const rtl::OUString sMetal( RTL_CONSTASCII_USTRINGPARAM ( "Metal" ) ); com::sun::star::uno::Any* pAny; sal_Int32 nFinalSurface = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) *pAny >>= bHasCustomShape; if( !bHasCustomShape ) continue; } sal_Int32 nSurface = 0; // wire frame ShadeMode eShadeMode( ShadeMode_FLAT ); pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sShadeMode ); if( pAny ) *pAny >>= eShadeMode; if( eShadeMode == ShadeMode_FLAT ) { sal_Bool bMetal = sal_False; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sMetal ); if( pAny ) *pAny >>= bMetal; if( bMetal ) { nSurface = 3; // metal } else { double fSpecularity = 0; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sSpecularity ); if( pAny ) *pAny >>= fSpecularity; const double e = 0.0001; if( (fSpecularity > -e) && (fSpecularity < e) ) { nSurface = 1; // matte } else { nSurface = 2; // plastic } } } if( nFinalSurface == -1 ) { nFinalSurface = nSurface; } else if( nFinalSurface != nSurface ) { nFinalSurface = -1; break; } } } if( bHasCustomShape ) rSet.Put( SfxInt32Item( SID_EXTRUSION_SURFACE, nFinalSurface ) ); else rSet.DisableItem( SID_EXTRUSION_SURFACE ); } void getExtrusionDepthState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sDepth( RTL_CONSTASCII_USTRINGPARAM ( "Depth" ) ); com::sun::star::uno::Any* pAny; double fFinalDepth = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) *pAny >>= bHasCustomShape; if( !bHasCustomShape ) continue; } double fDepth = 1270.0; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sDepth ); if( pAny ) { EnhancedCustomShapeParameterPair aDepthPropPair; if ( *pAny >>= aDepthPropPair ) aDepthPropPair.First.Value >>= fDepth; } if( fFinalDepth == -1 ) { fFinalDepth = fDepth; } else if( fFinalDepth != fDepth ) { fFinalDepth = -1; break; } } } if( pSdrView->GetModel() ) { FieldUnit eUnit = pSdrView->GetModel()->GetUIUnit(); rSet.Put( SfxUInt16Item( SID_ATTR_METRIC, (USHORT)eUnit ) ); } if( bHasCustomShape ) rSet.Put( SvxDoubleItem( fFinalDepth, SID_EXTRUSION_DEPTH ) ); else rSet.DisableItem( SID_EXTRUSION_DEPTH ); } static bool compare_direction( const Direction3D& d1, const Direction3D& d2 ) { if( ((d1.DirectionX < 0) && (d2.DirectionX < 0)) || ((d1.DirectionX == 0) && (d2.DirectionX == 0)) || ((d1.DirectionX > 0) && (d2.DirectionX > 0)) ) { if( ((d1.DirectionY < 0) && (d2.DirectionY < 0)) || ((d1.DirectionY == 0) && (d2.DirectionY == 0)) || ((d1.DirectionY > 0) && (d2.DirectionY > 0)) ) { if( ((d1.DirectionZ < 0) && (d2.DirectionZ < 0)) || ((d1.DirectionZ == 0) && (d2.DirectionZ == 0)) || ((d1.DirectionZ > 0) && (d2.DirectionZ > 0)) ) { return true; } } } return false; } void getExtrusionLightingDirectionState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sFirstLightDirection( RTL_CONSTASCII_USTRINGPARAM ( "FirstLightDirection" ) ); static const rtl::OUString sSecondLightDirection( RTL_CONSTASCII_USTRINGPARAM ( "SecondLightDirection" ) ); const Direction3D * pLighting1Defaults; const Direction3D * pLighting2Defaults; getLightingDirectionDefaults( &pLighting1Defaults, &pLighting2Defaults ); com::sun::star::uno::Any* pAny; int nFinalDirection = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) *pAny >>= bHasCustomShape; if( !bHasCustomShape ) continue; } Direction3D aFirstLightDirection( 50000, 0, 10000 ); Direction3D aSecondLightDirection( -50000, 0, 10000 ); pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sFirstLightDirection ); if( pAny ) *pAny >>= aFirstLightDirection; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sSecondLightDirection ); if( pAny ) *pAny >>= aSecondLightDirection; int nDirection = -1; int i; for( i = 0; i < 9; i++ ) { if( compare_direction( aFirstLightDirection, pLighting1Defaults[i] ) && compare_direction( aSecondLightDirection, pLighting2Defaults[i] )) { nDirection = i; break; } } if( nFinalDirection == -1 ) { nFinalDirection = nDirection; } else if( nDirection != nFinalDirection ) { nFinalDirection = -1; } if( nFinalDirection == -1 ) break; } } if( bHasCustomShape ) rSet.Put( SfxInt32Item( SID_EXTRUSION_LIGHTING_DIRECTION, (sal_Int32)nFinalDirection ) ); else rSet.DisableItem( SID_EXTRUSION_LIGHTING_DIRECTION ); } void getExtrusionLightingIntensityState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sBrightness( RTL_CONSTASCII_USTRINGPARAM ( "Brightness" ) ); com::sun::star::uno::Any* pAny; int nFinalLevel = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) *pAny >>= bHasCustomShape; if( !bHasCustomShape ) continue; } double fBrightness = 22178.0 / 655.36; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sBrightness ); if( pAny ) *pAny >>= fBrightness; int nLevel; if( fBrightness >= 30.0 ) { nLevel = 0; // Bright } else if( fBrightness >= 10.0 ) { nLevel = 1; // Noraml; } else { nLevel = 2; // Dim } if( nFinalLevel == -1 ) { nFinalLevel = nLevel; } else if( nFinalLevel != nLevel ) { nFinalLevel = -1; break; } } } if( bHasCustomShape ) rSet.Put( SfxInt32Item( SID_EXTRUSION_LIGHTING_INTENSITY, nFinalLevel ) ); else rSet.DisableItem( SID_EXTRUSION_LIGHTING_INTENSITY ); } void getExtrusionColorState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sExtrusionColor( RTL_CONSTASCII_USTRINGPARAM ( "Color" ) ); com::sun::star::uno::Any* pAny; bool bInit = false; bool bAmbigius = false; Color aFinalColor; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) *pAny >>= bHasCustomShape; if( !bHasCustomShape ) continue; } Color aColor; bool bUseColor; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusionColor ); if( pAny ) *pAny >>= bUseColor; if( bUseColor ) { const XSecondaryFillColorItem& rItem = *(XSecondaryFillColorItem*)&(pObj->GetMergedItem( XATTR_SECONDARYFILLCOLOR )); aColor = rItem.GetValue(); } else { aColor = COL_AUTO; } if( !bInit ) { aFinalColor = aColor; bInit = true; } else if( aFinalColor != aColor ) { bAmbigius = true; break; } } } if( bAmbigius ) aFinalColor = COL_AUTO; if( bHasCustomShape ) rSet.Put( SvxColorItem( aFinalColor, SID_EXTRUSION_3D_COLOR ) ); else rSet.DisableItem( SID_EXTRUSION_3D_COLOR ); } namespace svx { bool checkForSelectedCustomShapes( SdrView* pSdrView, bool bOnlyExtruded ) { static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; bool bFound = false; for(i=0;(i<nCount) && !bFound ; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { if( bOnlyExtruded ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); Any* pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) *pAny >>= bFound; } else { bFound = true; } } } return bFound; } } void ExtrusionBar::getState( SdrView* pSdrView, SfxItemSet& rSet ) { if (rSet.GetItemState(SID_EXTRUSION_DIRECTION) != SFX_ITEM_UNKNOWN) { getExtrusionDirectionState( pSdrView, rSet ); } if (rSet.GetItemState(SID_EXTRUSION_PROJECTION) != SFX_ITEM_UNKNOWN) { getExtrusionProjectionState( pSdrView, rSet ); } const bool bOnlyExtrudedCustomShapes = checkForSelectedCustomShapes( pSdrView, true ); if (rSet.GetItemState(SID_EXTRUSION_TILT_DOWN) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_TILT_DOWN ); } if (rSet.GetItemState(SID_EXTRUSION_TILT_DOWN) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_TILT_DOWN ); } if (rSet.GetItemState(SID_EXTRUSION_TILT_UP) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_TILT_UP ); } if (rSet.GetItemState(SID_EXTRUSION_TILT_LEFT) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_TILT_LEFT ); } if (rSet.GetItemState(SID_EXTRUSION_TILT_RIGHT) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_TILT_RIGHT ); } if (rSet.GetItemState(SID_EXTRUSION_3D_COLOR) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_3D_COLOR ); } if (rSet.GetItemState(SID_EXTRUSION_DEPTH_FLOATER) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_DEPTH_FLOATER ); } if (rSet.GetItemState(SID_EXTRUSION_DIRECTION_FLOATER) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_DIRECTION_FLOATER ); } if (rSet.GetItemState(SID_EXTRUSION_LIGHTING_FLOATER) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_LIGHTING_FLOATER ); } if (rSet.GetItemState(SID_EXTRUSION_SURFACE_FLOATER) != SFX_ITEM_UNKNOWN) { if(! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_SURFACE_FLOATER ); } if (rSet.GetItemState(SID_EXTRUSION_TOOGLE) != SFX_ITEM_UNKNOWN) { if( !checkForSelectedCustomShapes( pSdrView, false ) ) rSet.DisableItem( SID_EXTRUSION_TOOGLE ); } if (rSet.GetItemState(SID_EXTRUSION_DEPTH) != SFX_ITEM_UNKNOWN) { getExtrusionDepthState( pSdrView, rSet ); } if (rSet.GetItemState(SID_EXTRUSION_SURFACE) != SFX_ITEM_UNKNOWN) { getExtrusionSurfaceState( pSdrView, rSet ); } if (rSet.GetItemState(SID_EXTRUSION_LIGHTING_INTENSITY) != SFX_ITEM_UNKNOWN) { getExtrusionLightingIntensityState( pSdrView, rSet ); } if (rSet.GetItemState(SID_EXTRUSION_LIGHTING_DIRECTION) != SFX_ITEM_UNKNOWN) { getExtrusionLightingDirectionState( pSdrView, rSet ); } if (rSet.GetItemState(SID_EXTRUSION_3D_COLOR) != SFX_ITEM_UNKNOWN) { getExtrusionColorState( pSdrView, rSet ); } } INTEGRATION: CWS warnings01 (1.11.22); FILE MERGED 2006/05/11 10:05:58 ab 1.11.22.1: #i53898# Removed warnings for unxlngi6/unxlngi6.pro /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: extrusionbar.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2006-06-19 16:52:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEPARAMETERPARIR_HPP_ #include <com/sun/star/drawing/EnhancedCustomShapeParameterPair.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_ENHANCEDCUSTOMSHAPEPARAMETERTYPE_HPP_ #include <com/sun/star/drawing/EnhancedCustomShapeParameterType.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_SHADEMODE_HPP_ #include <com/sun/star/drawing/ShadeMode.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_ #include <com/sun/star/drawing/Position3D.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_DIRECTION3D_HPP_ #include <com/sun/star/drawing/Direction3D.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_PROJECTIONMODE_HPP_ #include <com/sun/star/drawing/ProjectionMode.hpp> #endif #ifndef _SVDUNDO_HXX #include <svdundo.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SFXREQUEST_HXX #include <sfx2/request.hxx> #endif #ifndef _SFXOBJFACE_HXX #include <sfx2/objface.hxx> #endif #ifndef _SFXVIEWSH_HXX #include <sfx2/viewsh.hxx> #endif #ifndef _SFX_BINDINGS_HXX #include <sfx2/bindings.hxx> #endif #ifndef _SVX_XSFLCLIT_HXX #include "xsflclit.hxx" #endif #ifndef _SVX_DIALMGR_HXX #include "dialmgr.hxx" #endif #ifndef _SVDOASHP_HXX #include "svdoashp.hxx" #endif #ifndef _SVX_DIALOGS_HRC #include "dialogs.hrc" #endif #ifndef _SVDVIEW_HXX #include "svdview.hxx" #endif #define ITEMID_COLOR 0 #ifndef _SVX_COLRITEM_HXX #include "colritem.hxx" #endif #define ITEMID_DOUBLE 0 #include "chrtitem.hxx" #include "extrusionbar.hxx" #include "extrusioncontrols.hxx" using namespace ::svx; using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::uno; /************************************************************************* |* |* Standardinterface deklarieren (Die Slotmap darf nicht leer sein, also |* tragen wir etwas ein, was hier (hoffentlich) nie vorkommt). |* \************************************************************************/ #define ShellClass ExtrusionBar SFX_SLOTMAP(ExtrusionBar) { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; SFX_IMPL_INTERFACE(ExtrusionBar, SfxShell, SVX_RES(RID_SVX_EXTRUSION_BAR)) { SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OBJECT, SVX_RES(RID_SVX_EXTRUSION_BAR) ); } TYPEINIT1( ExtrusionBar, SfxShell ); /************************************************************************* |* |* Standard-Konstruktor |* \************************************************************************/ ExtrusionBar::ExtrusionBar(SfxViewShell* pViewShell ) : SfxShell(pViewShell) { DBG_ASSERT( pViewShell, "svx::ExtrusionBar::ExtrusionBar(), I need a viewshell!" ); if( pViewShell ) SetPool(&pViewShell->GetPool()); SetHelpId( SVX_INTERFACE_EXTRUSION_BAR ); SetName( String( SVX_RES( RID_SVX_EXTRUSION_BAR ))); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ ExtrusionBar::~ExtrusionBar() { SetRepeatTarget(NULL); } void getLightingDirectionDefaults( const Direction3D **pLighting1Defaults, const Direction3D **pLighting2Defaults ) { static const Direction3D aLighting1Defaults[9] = { Direction3D( -50000, -50000, 10000 ), Direction3D( 0, -50000, 10000 ), Direction3D( 50000, -50000, 10000 ), Direction3D( -50000, 0, 10000 ), Direction3D( 0, 0, 10000 ), Direction3D( 50000, 0, 10000 ), Direction3D( -50000, 50000, 10000 ), Direction3D( 0, 50000, 10000 ), Direction3D( 50000, 50000, 10000 ) }; static const Direction3D aLighting2Defaults[9] = { Direction3D( 50000,0, 10000 ), Direction3D( 0, 50000, 10000 ), Direction3D( -50000, 0, 10000 ), Direction3D( 50000, 0, 10000 ), Direction3D( 0, 0, 10000 ), Direction3D( -50000, 0, 10000 ), Direction3D( 50000, 0, 10000 ), Direction3D( 0, -50000, 10000 ), Direction3D( -50000, 0, 10000 ) }; *pLighting1Defaults = (const Direction3D *)aLighting1Defaults; *pLighting2Defaults = (const Direction3D *)aLighting2Defaults; }; static void impl_execute( SdrView*, SfxRequest& rReq, SdrCustomShapeGeometryItem& rGeometryItem, SdrObject* pObj ) { static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sProjectionMode( RTL_CONSTASCII_USTRINGPARAM ( "ProjectionMode" ) ); static const rtl::OUString sRotateAngle( RTL_CONSTASCII_USTRINGPARAM ( "RotateAngle" ) ); static const rtl::OUString sViewPoint( RTL_CONSTASCII_USTRINGPARAM ( "ViewPoint" ) ); static const rtl::OUString sOrigin( RTL_CONSTASCII_USTRINGPARAM ( "Origin" ) ); static const rtl::OUString sSkew( RTL_CONSTASCII_USTRINGPARAM ( "Skew" ) ); static const rtl::OUString sDepth( RTL_CONSTASCII_USTRINGPARAM ( "Depth" ) ); sal_uInt16 nSID = rReq.GetSlot(); switch( nSID ) { case SID_EXTRUSION_TOOGLE: { com::sun::star::uno::Any* pAny = rGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) { sal_Bool bOn; (*pAny) >>= bOn; bOn = !bOn; (*pAny) <<= bOn; } else { com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sExtrusion; aPropValue.Value <<= sal_True; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_TILT_DOWN: case SID_EXTRUSION_TILT_UP: case SID_EXTRUSION_TILT_LEFT: case SID_EXTRUSION_TILT_RIGHT: { sal_Bool bHorizontal = ( nSID == SID_EXTRUSION_TILT_DOWN ) || ( nSID == SID_EXTRUSION_TILT_UP ); sal_Int32 nDiff = ( nSID == SID_EXTRUSION_TILT_LEFT ) || ( nSID == SID_EXTRUSION_TILT_UP ) ? 5 : -5; EnhancedCustomShapeParameterPair aRotateAnglePropPair; double fX = 0.0; double fY = 0.0; aRotateAnglePropPair.First.Value <<= fX; aRotateAnglePropPair.First.Type = EnhancedCustomShapeParameterType::NORMAL; aRotateAnglePropPair.Second.Value <<= fY; aRotateAnglePropPair.Second.Type = EnhancedCustomShapeParameterType::NORMAL; com::sun::star::uno::Any* pAny = rGeometryItem.GetPropertyValueByName( sExtrusion, sRotateAngle ); if( pAny && ( *pAny >>= aRotateAnglePropPair ) ) { aRotateAnglePropPair.First.Value >>= fX; aRotateAnglePropPair.Second.Value >>= fY; } if ( bHorizontal ) fX += nDiff; else fY += nDiff; aRotateAnglePropPair.First.Value <<= fX; aRotateAnglePropPair.Second.Value <<= fY; com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sRotateAngle; aPropValue.Value <<= aRotateAnglePropPair; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } break; case SID_EXTRUSION_DIRECTION: { if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_DIRECTION ) == SFX_ITEM_SET ) { sal_Int32 nSkew = ((const SfxInt32Item*)rReq.GetArgs()->GetItem(SID_EXTRUSION_DIRECTION))->GetValue(); Position3D aViewPoint( 3472, -3472, 25000 ); double fOriginX = 0.50; double fOriginY = -0.50; double fSkewAngle = nSkew; double fSkew = 50.0; switch( nSkew ) { case 135: aViewPoint.PositionY = 3472; fOriginY = 0.50; break; case 90: aViewPoint.PositionX = 0; aViewPoint.PositionY = 3472; fOriginX = 0; fOriginY = -0.50; break; case 45: aViewPoint.PositionX = -3472; aViewPoint.PositionY = 3472; fOriginX = -0.50; fOriginY = 0.50; break; case 180: aViewPoint.PositionY = 0; fOriginY = 0; break; case 0: aViewPoint.PositionX = 0; aViewPoint.PositionY = 0; fOriginX = 0; fOriginY = 0; fSkew = 0.0; break; case -360: aViewPoint.PositionX = -3472; aViewPoint.PositionY = 0; fOriginX = -0.50; fOriginY = 0; break; case -90: aViewPoint.PositionX = 0; fOriginX = 0; break; case -45: aViewPoint.PositionX = -3472; fOriginX = -0.50; break; } com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sViewPoint; aPropValue.Value <<= aViewPoint; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); EnhancedCustomShapeParameterPair aOriginPropPair; aOriginPropPair.First.Value <<= fOriginX; aOriginPropPair.First.Type = EnhancedCustomShapeParameterType::NORMAL; aOriginPropPair.Second.Value <<= fOriginY; aOriginPropPair.Second.Type = EnhancedCustomShapeParameterType::NORMAL; aPropValue.Name = sOrigin; aPropValue.Value <<= aOriginPropPair; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); EnhancedCustomShapeParameterPair aSkewPropPair; aSkewPropPair.First.Value <<= fSkew; aSkewPropPair.First.Type = EnhancedCustomShapeParameterType::NORMAL; aSkewPropPair.Second.Value <<= fSkewAngle; aSkewPropPair.Second.Type = EnhancedCustomShapeParameterType::NORMAL; aPropValue.Name = sSkew; aPropValue.Value <<= aSkewPropPair; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_PROJECTION: { if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_PROJECTION ) == SFX_ITEM_SET ) { sal_Int32 nProjection = ((const SfxInt32Item*)rReq.GetArgs()->GetItem(SID_EXTRUSION_PROJECTION))->GetValue(); ProjectionMode eProjectionMode = nProjection == 1 ? ProjectionMode_PARALLEL : ProjectionMode_PERSPECTIVE; com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sProjectionMode; aPropValue.Value <<= eProjectionMode; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_DEPTH: { if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_DEPTH ) == SFX_ITEM_SET) { double fDepth = ((const SvxDoubleItem*)rReq.GetArgs()->GetItem(SID_EXTRUSION_DEPTH))->GetValue(); double fFraction = 0.0; EnhancedCustomShapeParameterPair aDepthPropPair; aDepthPropPair.First.Value <<= fDepth; aDepthPropPair.First.Type = EnhancedCustomShapeParameterType::NORMAL; aDepthPropPair.Second.Value <<= fFraction; aDepthPropPair.Second.Type = EnhancedCustomShapeParameterType::NORMAL; com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sDepth; aPropValue.Value <<= aDepthPropPair; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_3D_COLOR: { static const rtl::OUString sExtrusionColor( RTL_CONSTASCII_USTRINGPARAM ( "Color" ) ); if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_3D_COLOR ) == SFX_ITEM_SET) { Color aColor( ((const SvxColorItem&)rReq.GetArgs()->Get(SID_EXTRUSION_3D_COLOR)).GetValue() ); const bool bAuto = aColor == COL_AUTO; com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sExtrusionColor; aPropValue.Value <<= bAuto ? sal_False : sal_True; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); if( bAuto ) { pObj->ClearMergedItem( XATTR_SECONDARYFILLCOLOR ); } else { pObj->SetMergedItem( XSecondaryFillColorItem( String(), aColor ) ); } pObj->BroadcastObjectChange(); } } break; case SID_EXTRUSION_SURFACE: { static const rtl::OUString sShadeMode( RTL_CONSTASCII_USTRINGPARAM ( "ShadeMode" ) ); static const rtl::OUString sSpecularity( RTL_CONSTASCII_USTRINGPARAM ( "Specularity" ) ); static const rtl::OUString sDiffusion( RTL_CONSTASCII_USTRINGPARAM ( "Diffusion" ) ); static const rtl::OUString sMetal( RTL_CONSTASCII_USTRINGPARAM ( "Metal" ) ); if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_SURFACE ) == SFX_ITEM_SET) { sal_Int32 nSurface = ((const SfxInt32Item*)rReq.GetArgs()->GetItem(SID_EXTRUSION_SURFACE))->GetValue(); ShadeMode eShadeMode( ShadeMode_FLAT ); sal_Bool bMetal = sal_False; double fSpecularity = 0; double fDiffusion = 0; switch( nSurface ) { case 0: // wireframe eShadeMode = ShadeMode_DRAFT; break; case 1: // matte break; case 2: // plastic fSpecularity = 122.0; break; case 3: // metal bMetal = true; fSpecularity = 122.0; fDiffusion = 122.0; break; } com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sShadeMode; aPropValue.Value <<= eShadeMode; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sMetal; aPropValue.Value <<= bMetal; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sSpecularity; aPropValue.Value <<= fSpecularity; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sDiffusion; aPropValue.Value <<= fDiffusion; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_LIGHTING_INTENSITY: { static const rtl::OUString sBrightness( RTL_CONSTASCII_USTRINGPARAM ( "Brightness" ) ); static const rtl::OUString sLightFace( RTL_CONSTASCII_USTRINGPARAM ( "LightFace" ) ); static const rtl::OUString sFirstLightHarsh( RTL_CONSTASCII_USTRINGPARAM ( "FirstLightHarsh" ) ); static const rtl::OUString sSecondLightHarsh( RTL_CONSTASCII_USTRINGPARAM ( "SecondLightHarsh" ) ); static const rtl::OUString sFirstLightLevel( RTL_CONSTASCII_USTRINGPARAM ( "FirstLightLevel" ) ); static const rtl::OUString sSecondLightLevel( RTL_CONSTASCII_USTRINGPARAM ( "SecondLightLevel" ) ); if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_LIGHTING_INTENSITY ) == SFX_ITEM_SET) { sal_Int32 nLevel = ((const SfxInt32Item*)rReq.GetArgs()->GetItem(SID_EXTRUSION_LIGHTING_INTENSITY))->GetValue(); double fBrightness; sal_Bool bHarsh2; double fLevel1; double fLevel2; switch( nLevel ) { case 0: // bright fBrightness = 34.0; bHarsh2 = sal_False; fLevel1 = 66.0; fLevel2 = 66.0; break; case 1: // normal fBrightness = 15.0; bHarsh2 = sal_False; fLevel1 = 67.0; fLevel2 = 37.0; break; case 2: // dim fBrightness = 6.0; bHarsh2 = sal_True; fLevel1 = 79.0; fLevel2 = 21.0; break; } com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sBrightness; aPropValue.Value <<= fBrightness; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sLightFace; aPropValue.Value <<= sal_True; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sFirstLightHarsh; aPropValue.Value <<= sal_True; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sSecondLightHarsh; aPropValue.Value <<= bHarsh2; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sFirstLightLevel; aPropValue.Value <<= fLevel1; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sSecondLightLevel; aPropValue.Value <<= fLevel2; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } break; case SID_EXTRUSION_LIGHTING_DIRECTION: { if( rReq.GetArgs() && rReq.GetArgs()->GetItemState( SID_EXTRUSION_LIGHTING_DIRECTION ) == SFX_ITEM_SET) { sal_Int32 nDirection = ((const SfxInt32Item*)rReq.GetArgs()->GetItem(SID_EXTRUSION_LIGHTING_DIRECTION))->GetValue(); if((nDirection >= 0) && (nDirection < 9)) { const rtl::OUString sFirstLightDirection( RTL_CONSTASCII_USTRINGPARAM ( "FirstLightDirection" ) ); const rtl::OUString sSecondLightDirection( RTL_CONSTASCII_USTRINGPARAM ( "SecondLightDirection" ) ); const Direction3D * pLighting1Defaults; const Direction3D * pLighting2Defaults; getLightingDirectionDefaults( &pLighting1Defaults, &pLighting2Defaults ); com::sun::star::beans::PropertyValue aPropValue; aPropValue.Name = sFirstLightDirection; aPropValue.Value <<= pLighting1Defaults[nDirection]; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); aPropValue.Name = sSecondLightDirection; aPropValue.Value <<= pLighting2Defaults[nDirection]; rGeometryItem.SetPropertyValue( sExtrusion, aPropValue ); } } } break; } } void ExtrusionBar::execute( SdrView* pSdrView, SfxRequest& rReq, SfxBindings& rBindings ) { sal_uInt16 nSID = rReq.GetSlot(); sal_uInt16 nStrResId = 0; switch( nSID ) { case SID_EXTRUSION_TOOGLE: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ON_OFF; } // PASSTROUGH case SID_EXTRUSION_TILT_DOWN: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ROTATE_DOWN; } // PASSTROUGH case SID_EXTRUSION_TILT_UP: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ROTATE_UP; } // PASSTROUGH case SID_EXTRUSION_TILT_LEFT: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ROTATE_LEFT; } // PASSTROUGH case SID_EXTRUSION_TILT_RIGHT: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ROTATE_RIGHT; } // PASSTROUGH case SID_EXTRUSION_DIRECTION: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_ORIENTATION; } // PASSTROUGH case SID_EXTRUSION_PROJECTION: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_PROJECTION; } // PASSTROUGH case SID_EXTRUSION_DEPTH: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_DEPTH; } // PASSTROUGH case SID_EXTRUSION_3D_COLOR: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_COLOR; } // PASSTROUGH case SID_EXTRUSION_SURFACE: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_SURFACE; } // PASSTROUGH case SID_EXTRUSION_LIGHTING_INTENSITY: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_BRIGHTNESS; } // PASSTROUGH case SID_EXTRUSION_LIGHTING_DIRECTION: { if ( !nStrResId ) nStrResId = RID_SVXSTR_UNDO_APPLY_EXTRUSION_LIGHTING; const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; for(i=0; i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { String aStr( SVX_RES( nStrResId ) ); pSdrView->BegUndo( aStr ); pSdrView->AddUndo( pSdrView->GetModel()->GetSdrUndoFactory().CreateUndoAttrObject( *pObj ) ); SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); impl_execute( pSdrView, rReq, aGeometryItem, pObj ); pObj->SetMergedItem( aGeometryItem ); pObj->BroadcastObjectChange(); pSdrView->EndUndo(); // simulate a context change: // force SelectionHasChanged() being called // so that extrusion bar will be visible/hidden pSdrView->MarkListHasChanged(); } } } break; case SID_EXTRUSION_DEPTH_DIALOG: if( rReq.GetArgs() && (rReq.GetArgs()->GetItemState( SID_EXTRUSION_DEPTH ) == SFX_ITEM_SET) && (rReq.GetArgs()->GetItemState( SID_ATTR_METRIC ) == SFX_ITEM_SET)) { double fDepth = ((const SvxDoubleItem*)rReq.GetArgs()->GetItem(SID_EXTRUSION_DEPTH))->GetValue(); FieldUnit eUnit = (FieldUnit)((const SfxUInt16Item*)rReq.GetArgs()->GetItem(SID_ATTR_METRIC))->GetValue(); ExtrusionDepthDialog aDlg( 0L, fDepth, eUnit ); USHORT nRet = aDlg.Execute(); if( nRet != 0 ) { fDepth = aDlg.getDepth(); SvxDoubleItem aItem( fDepth, SID_EXTRUSION_DEPTH ); SfxPoolItem* aItems[] = { &aItem, 0 }; rBindings.Execute( SID_EXTRUSION_DEPTH, (const SfxPoolItem**)aItems ); } } break; } if( nSID == SID_EXTRUSION_TOOGLE ) { static USHORT SidArray[] = { SID_EXTRUSION_TILT_DOWN, SID_EXTRUSION_TILT_UP, SID_EXTRUSION_TILT_LEFT, SID_EXTRUSION_TILT_RIGHT, SID_EXTRUSION_DEPTH_FLOATER, SID_EXTRUSION_DIRECTION_FLOATER, SID_EXTRUSION_LIGHTING_FLOATER, SID_EXTRUSION_SURFACE_FLOATER, SID_EXTRUSION_3D_COLOR, SID_EXTRUSION_DEPTH, SID_EXTRUSION_DIRECTION, SID_EXTRUSION_PROJECTION, SID_EXTRUSION_LIGHTING_DIRECTION, SID_EXTRUSION_LIGHTING_INTENSITY, SID_EXTRUSION_SURFACE, 0 }; rBindings.Invalidate( SidArray ); } } void getExtrusionDirectionState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sViewPoint( RTL_CONSTASCII_USTRINGPARAM ( "ViewPoint" ) ); static const rtl::OUString sOrigin( RTL_CONSTASCII_USTRINGPARAM ( "Origin" ) ); static const rtl::OUString sSkew( RTL_CONSTASCII_USTRINGPARAM ( "Skew" ) ); static const rtl::OUString sProjectionMode( RTL_CONSTASCII_USTRINGPARAM ( "ProjectionMode" ) ); com::sun::star::uno::Any* pAny; double fFinalSkewAngle = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny_ = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny_ ) *pAny_ >>= bHasCustomShape; if( !bHasCustomShape ) continue; } sal_Bool bParallel = sal_True; Position3D aViewPoint( 3472, -3472, 25000 ); double fOriginX = 0.50; double fOriginY = -0.50; double fSkewAngle = -135; double fSkew = 50.0; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sProjectionMode ); sal_Int16 nProjectionMode; if( pAny && ( *pAny >>= nProjectionMode ) ) bParallel = nProjectionMode == ProjectionMode_PARALLEL; if( bParallel ) { EnhancedCustomShapeParameterPair aSkewPropPair; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sSkew ); if( pAny && ( *pAny >>= aSkewPropPair ) ) { aSkewPropPair.First.Value >>= fSkew; aSkewPropPair.Second.Value >>= fSkewAngle; } if ( fSkew == 0.0 ) fSkewAngle = 0.0; else if ( fSkewAngle == 0.0 ) fSkewAngle = -360.0; } else { pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sViewPoint ); if( pAny ) *pAny >>= aViewPoint; EnhancedCustomShapeParameterPair aOriginPropPair; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sOrigin ); if( pAny && ( *pAny >>= aOriginPropPair ) ) { aOriginPropPair.First.Value >>= fOriginX; aOriginPropPair.Second.Value >>= fOriginY; } fSkewAngle = -1; const double e = 0.0001; if( aViewPoint.PositionX > e ) { if( aViewPoint.PositionY > e ) { if( (fOriginX > e ) && ( fOriginY > e ) ) fSkewAngle = 135.0; } else if( aViewPoint.PositionY < -e ) { if( ( fOriginX > e ) && ( fOriginY < -e ) ) fSkewAngle = -135.0; } else { if( ( fOriginX > e ) && ( fOriginY > -e ) && ( fOriginY < e ) ) fSkewAngle = 180.0; } } else if( aViewPoint.PositionX < -e ) { if( aViewPoint.PositionY < -e ) { if( ( fOriginX < -e ) && ( fOriginY < -e ) ) fSkewAngle = -45.0; } else if( aViewPoint.PositionY > e ) { if( ( fOriginX < -e ) && ( fOriginY > e ) ) fSkewAngle = 45.0; } else { if( ( fOriginX < e ) && ( fOriginY > -e ) && ( fOriginY < e ) ) fSkewAngle = -360.0; } } else { if( aViewPoint.PositionY < -e ) { if( ( fOriginX > -e ) && ( fOriginX < e ) && ( fOriginY < -e ) ) fSkewAngle = -90.0; } else if( aViewPoint.PositionY > e ) { if( ( fOriginX > -e ) && ( fOriginX < e ) && ( fOriginY > e ) ) fSkewAngle = 90.0; } else { if( ( fOriginX > -e ) && ( fOriginX < e ) && ( fOriginY > -e ) && ( fOriginY < e ) ) fSkewAngle = 0.0; } } } if( fFinalSkewAngle == -1.0 ) { fFinalSkewAngle = fSkewAngle; } else if( fSkewAngle != fFinalSkewAngle ) { fFinalSkewAngle = -1.0; } if( fFinalSkewAngle == -1.0 ) break; } } if( bHasCustomShape ) rSet.Put( SfxInt32Item( SID_EXTRUSION_DIRECTION, (sal_Int32)fFinalSkewAngle ) ); else rSet.DisableItem( SID_EXTRUSION_DIRECTION ); } void getExtrusionProjectionState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sProjectionMode( RTL_CONSTASCII_USTRINGPARAM ( "ProjectionMode" ) ); com::sun::star::uno::Any* pAny; sal_Int32 nFinalProjection = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { // see if this is an extruded customshape if( !bHasCustomShape ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); Any* pAny_ = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny_ ) *pAny_ >>= bHasCustomShape; if( !bHasCustomShape ) continue; } SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); sal_Bool bParallel = sal_True; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sProjectionMode ); ProjectionMode eProjectionMode; if( pAny && ( *pAny >>= eProjectionMode ) ) bParallel = eProjectionMode == ProjectionMode_PARALLEL; if( nFinalProjection == -1 ) { nFinalProjection = bParallel; } else if( nFinalProjection != bParallel ) { nFinalProjection = -1; break; } } } if( bHasCustomShape ) rSet.Put( SfxInt32Item( SID_EXTRUSION_PROJECTION, nFinalProjection ) ); else rSet.DisableItem( SID_EXTRUSION_PROJECTION ); } void getExtrusionSurfaceState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sShadeMode( RTL_CONSTASCII_USTRINGPARAM ( "ShadeMode" ) ); static const rtl::OUString sSpecularity( RTL_CONSTASCII_USTRINGPARAM ( "Specularity" ) ); static const rtl::OUString sDiffusion( RTL_CONSTASCII_USTRINGPARAM ( "Diffusion" ) ); static const rtl::OUString sMetal( RTL_CONSTASCII_USTRINGPARAM ( "Metal" ) ); com::sun::star::uno::Any* pAny; sal_Int32 nFinalSurface = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny_ = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny_ ) *pAny_ >>= bHasCustomShape; if( !bHasCustomShape ) continue; } sal_Int32 nSurface = 0; // wire frame ShadeMode eShadeMode( ShadeMode_FLAT ); pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sShadeMode ); if( pAny ) *pAny >>= eShadeMode; if( eShadeMode == ShadeMode_FLAT ) { sal_Bool bMetal = sal_False; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sMetal ); if( pAny ) *pAny >>= bMetal; if( bMetal ) { nSurface = 3; // metal } else { double fSpecularity = 0; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sSpecularity ); if( pAny ) *pAny >>= fSpecularity; const double e = 0.0001; if( (fSpecularity > -e) && (fSpecularity < e) ) { nSurface = 1; // matte } else { nSurface = 2; // plastic } } } if( nFinalSurface == -1 ) { nFinalSurface = nSurface; } else if( nFinalSurface != nSurface ) { nFinalSurface = -1; break; } } } if( bHasCustomShape ) rSet.Put( SfxInt32Item( SID_EXTRUSION_SURFACE, nFinalSurface ) ); else rSet.DisableItem( SID_EXTRUSION_SURFACE ); } void getExtrusionDepthState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sDepth( RTL_CONSTASCII_USTRINGPARAM ( "Depth" ) ); com::sun::star::uno::Any* pAny; double fFinalDepth = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny_ = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny_ ) *pAny_ >>= bHasCustomShape; if( !bHasCustomShape ) continue; } double fDepth = 1270.0; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sDepth ); if( pAny ) { EnhancedCustomShapeParameterPair aDepthPropPair; if ( *pAny >>= aDepthPropPair ) aDepthPropPair.First.Value >>= fDepth; } if( fFinalDepth == -1 ) { fFinalDepth = fDepth; } else if( fFinalDepth != fDepth ) { fFinalDepth = -1; break; } } } if( pSdrView->GetModel() ) { FieldUnit eUnit = pSdrView->GetModel()->GetUIUnit(); rSet.Put( SfxUInt16Item( SID_ATTR_METRIC, (USHORT)eUnit ) ); } if( bHasCustomShape ) rSet.Put( SvxDoubleItem( fFinalDepth, SID_EXTRUSION_DEPTH ) ); else rSet.DisableItem( SID_EXTRUSION_DEPTH ); } static bool compare_direction( const Direction3D& d1, const Direction3D& d2 ) { if( ((d1.DirectionX < 0) && (d2.DirectionX < 0)) || ((d1.DirectionX == 0) && (d2.DirectionX == 0)) || ((d1.DirectionX > 0) && (d2.DirectionX > 0)) ) { if( ((d1.DirectionY < 0) && (d2.DirectionY < 0)) || ((d1.DirectionY == 0) && (d2.DirectionY == 0)) || ((d1.DirectionY > 0) && (d2.DirectionY > 0)) ) { if( ((d1.DirectionZ < 0) && (d2.DirectionZ < 0)) || ((d1.DirectionZ == 0) && (d2.DirectionZ == 0)) || ((d1.DirectionZ > 0) && (d2.DirectionZ > 0)) ) { return true; } } } return false; } void getExtrusionLightingDirectionState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sFirstLightDirection( RTL_CONSTASCII_USTRINGPARAM ( "FirstLightDirection" ) ); static const rtl::OUString sSecondLightDirection( RTL_CONSTASCII_USTRINGPARAM ( "SecondLightDirection" ) ); const Direction3D * pLighting1Defaults; const Direction3D * pLighting2Defaults; getLightingDirectionDefaults( &pLighting1Defaults, &pLighting2Defaults ); com::sun::star::uno::Any* pAny; int nFinalDirection = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny_ = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny_ ) *pAny_ >>= bHasCustomShape; if( !bHasCustomShape ) continue; } Direction3D aFirstLightDirection( 50000, 0, 10000 ); Direction3D aSecondLightDirection( -50000, 0, 10000 ); pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sFirstLightDirection ); if( pAny ) *pAny >>= aFirstLightDirection; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sSecondLightDirection ); if( pAny ) *pAny >>= aSecondLightDirection; int nDirection = -1; int j; for( j = 0; j < 9; j++ ) { if( compare_direction( aFirstLightDirection, pLighting1Defaults[j] ) && compare_direction( aSecondLightDirection, pLighting2Defaults[j] )) { nDirection = j; break; } } if( nFinalDirection == -1 ) { nFinalDirection = nDirection; } else if( nDirection != nFinalDirection ) { nFinalDirection = -1; } if( nFinalDirection == -1 ) break; } } if( bHasCustomShape ) rSet.Put( SfxInt32Item( SID_EXTRUSION_LIGHTING_DIRECTION, (sal_Int32)nFinalDirection ) ); else rSet.DisableItem( SID_EXTRUSION_LIGHTING_DIRECTION ); } void getExtrusionLightingIntensityState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sBrightness( RTL_CONSTASCII_USTRINGPARAM ( "Brightness" ) ); com::sun::star::uno::Any* pAny; int nFinalLevel = -1; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny_ = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny_ ) *pAny_ >>= bHasCustomShape; if( !bHasCustomShape ) continue; } double fBrightness = 22178.0 / 655.36; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sBrightness ); if( pAny ) *pAny >>= fBrightness; int nLevel; if( fBrightness >= 30.0 ) { nLevel = 0; // Bright } else if( fBrightness >= 10.0 ) { nLevel = 1; // Noraml; } else { nLevel = 2; // Dim } if( nFinalLevel == -1 ) { nFinalLevel = nLevel; } else if( nFinalLevel != nLevel ) { nFinalLevel = -1; break; } } } if( bHasCustomShape ) rSet.Put( SfxInt32Item( SID_EXTRUSION_LIGHTING_INTENSITY, nFinalLevel ) ); else rSet.DisableItem( SID_EXTRUSION_LIGHTING_INTENSITY ); } void getExtrusionColorState( SdrView* pSdrView, SfxItemSet& rSet ) { const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); static const rtl::OUString sExtrusionColor( RTL_CONSTASCII_USTRINGPARAM ( "Color" ) ); com::sun::star::uno::Any* pAny; bool bInit = false; bool bAmbigius = false; Color aFinalColor; bool bHasCustomShape = false; for(i=0;i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); // see if this is an extruded customshape if( !bHasCustomShape ) { Any* pAny_ = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny_ ) *pAny_ >>= bHasCustomShape; if( !bHasCustomShape ) continue; } Color aColor; bool bUseColor; pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusionColor ); if( pAny ) *pAny >>= bUseColor; if( bUseColor ) { const XSecondaryFillColorItem& rItem = *(XSecondaryFillColorItem*)&(pObj->GetMergedItem( XATTR_SECONDARYFILLCOLOR )); aColor = rItem.GetColorValue(); } else { aColor = COL_AUTO; } if( !bInit ) { aFinalColor = aColor; bInit = true; } else if( aFinalColor != aColor ) { bAmbigius = true; break; } } } if( bAmbigius ) aFinalColor = COL_AUTO; if( bHasCustomShape ) rSet.Put( SvxColorItem( aFinalColor, SID_EXTRUSION_3D_COLOR ) ); else rSet.DisableItem( SID_EXTRUSION_3D_COLOR ); } namespace svx { bool checkForSelectedCustomShapes( SdrView* pSdrView, bool bOnlyExtruded ) { static const rtl::OUString sExtrusion( RTL_CONSTASCII_USTRINGPARAM ( "Extrusion" ) ); const SdrMarkList& rMarkList = pSdrView->GetMarkedObjectList(); ULONG nCount = rMarkList.GetMarkCount(), i; bool bFound = false; for(i=0;(i<nCount) && !bFound ; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetObj(); if( pObj->ISA(SdrObjCustomShape) ) { if( bOnlyExtruded ) { SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pObj->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) ); Any* pAny = aGeometryItem.GetPropertyValueByName( sExtrusion, sExtrusion ); if( pAny ) *pAny >>= bFound; } else { bFound = true; } } } return bFound; } } void ExtrusionBar::getState( SdrView* pSdrView, SfxItemSet& rSet ) { if (rSet.GetItemState(SID_EXTRUSION_DIRECTION) != SFX_ITEM_UNKNOWN) { getExtrusionDirectionState( pSdrView, rSet ); } if (rSet.GetItemState(SID_EXTRUSION_PROJECTION) != SFX_ITEM_UNKNOWN) { getExtrusionProjectionState( pSdrView, rSet ); } const bool bOnlyExtrudedCustomShapes = checkForSelectedCustomShapes( pSdrView, true ); if (rSet.GetItemState(SID_EXTRUSION_TILT_DOWN) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_TILT_DOWN ); } if (rSet.GetItemState(SID_EXTRUSION_TILT_DOWN) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_TILT_DOWN ); } if (rSet.GetItemState(SID_EXTRUSION_TILT_UP) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_TILT_UP ); } if (rSet.GetItemState(SID_EXTRUSION_TILT_LEFT) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_TILT_LEFT ); } if (rSet.GetItemState(SID_EXTRUSION_TILT_RIGHT) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_TILT_RIGHT ); } if (rSet.GetItemState(SID_EXTRUSION_3D_COLOR) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_3D_COLOR ); } if (rSet.GetItemState(SID_EXTRUSION_DEPTH_FLOATER) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_DEPTH_FLOATER ); } if (rSet.GetItemState(SID_EXTRUSION_DIRECTION_FLOATER) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_DIRECTION_FLOATER ); } if (rSet.GetItemState(SID_EXTRUSION_LIGHTING_FLOATER) != SFX_ITEM_UNKNOWN) { if (! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_LIGHTING_FLOATER ); } if (rSet.GetItemState(SID_EXTRUSION_SURFACE_FLOATER) != SFX_ITEM_UNKNOWN) { if(! bOnlyExtrudedCustomShapes) rSet.DisableItem( SID_EXTRUSION_SURFACE_FLOATER ); } if (rSet.GetItemState(SID_EXTRUSION_TOOGLE) != SFX_ITEM_UNKNOWN) { if( !checkForSelectedCustomShapes( pSdrView, false ) ) rSet.DisableItem( SID_EXTRUSION_TOOGLE ); } if (rSet.GetItemState(SID_EXTRUSION_DEPTH) != SFX_ITEM_UNKNOWN) { getExtrusionDepthState( pSdrView, rSet ); } if (rSet.GetItemState(SID_EXTRUSION_SURFACE) != SFX_ITEM_UNKNOWN) { getExtrusionSurfaceState( pSdrView, rSet ); } if (rSet.GetItemState(SID_EXTRUSION_LIGHTING_INTENSITY) != SFX_ITEM_UNKNOWN) { getExtrusionLightingIntensityState( pSdrView, rSet ); } if (rSet.GetItemState(SID_EXTRUSION_LIGHTING_DIRECTION) != SFX_ITEM_UNKNOWN) { getExtrusionLightingDirectionState( pSdrView, rSet ); } if (rSet.GetItemState(SID_EXTRUSION_3D_COLOR) != SFX_ITEM_UNKNOWN) { getExtrusionColorState( pSdrView, rSet ); } }
/************************************************************************** * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // ************************************************************* // Checks the quality assurance // by comparing with reference data // contained in a DB // ------------------------------------------------------------- // W. Ferrarese + P. Cerello Feb 2008 // INFN Torino // --- ROOT system --- #include <TH2.h> #include <TTree.h> // --- Standard library --- // --- AliRoot header files --- #include "AliITSQADataMakerRec.h" #include "AliITSQASPDDataMakerRec.h" #include "AliITSQASDDDataMakerRec.h" #include "AliITSQASSDDataMakerRec.h" #include "AliLog.h" #include "AliQAv1.h" #include "AliQAChecker.h" #include "AliITSQAChecker.h" #include "AliRawReader.h" #include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliESDVertex.h" #include "AliMultiplicity.h" ClassImp(AliITSQADataMakerRec) //____________________________________________________________________________ AliITSQADataMakerRec::AliITSQADataMakerRec(Bool_t kMode, Short_t subDet, Short_t ldc) : AliQADataMakerRec(AliQAv1::GetDetName(AliQAv1::kITS), "ITS Quality Assurance Data Maker"), fkOnline(kMode), fHLTMode(0), fSubDetector(subDet), fLDC(ldc), fSPDDataMaker(NULL), fSDDDataMaker(NULL), fSSDDataMaker(NULL) { //ctor used to discriminate OnLine-Offline analysis if(fSubDetector < 0 || fSubDetector > 3) { AliError("Error: fSubDetector number out of range; return\n"); } // Initialization for RAW data if(fSubDetector == 0 || fSubDetector == 1) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM::Create SPD DataMakerRec\n"); fSPDDataMaker = new AliITSQASPDDataMakerRec(this,fkOnline); } if(fSubDetector == 0 || fSubDetector == 2) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM::Create SDD DataMakerRec\n"); fSDDDataMaker = new AliITSQASDDDataMakerRec(this,fkOnline); if(fkOnline){SetHLTMode(fSDDDataMaker->GetHLTMode()); } } if(fSubDetector == 0 || fSubDetector == 3) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM::Create SSD DataMakerRec\n"); fSSDDataMaker = new AliITSQASSDDataMakerRec(this,fkOnline); } } //____________________________________________________________________________ AliITSQADataMakerRec::~AliITSQADataMakerRec(){ // destructor if(fSPDDataMaker)delete fSPDDataMaker; if(fSDDDataMaker)delete fSDDDataMaker; if(fSSDDataMaker)delete fSSDDataMaker; } //____________________________________________________________________________ AliITSQADataMakerRec::AliITSQADataMakerRec(const AliITSQADataMakerRec& qadm) : AliQADataMakerRec(), fkOnline(qadm.fkOnline), fHLTMode(qadm.fHLTMode), fSubDetector(qadm.fSubDetector), fLDC(qadm.fLDC), fSPDDataMaker(NULL), fSDDDataMaker(NULL), fSSDDataMaker(NULL) { //copy ctor SetName((const char*)qadm.GetName()) ; SetTitle((const char*)qadm.GetTitle()); } //__________________________________________________________________ AliITSQADataMakerRec& AliITSQADataMakerRec::operator = (const AliITSQADataMakerRec& qac ) { // Equal operator. this->~AliITSQADataMakerRec(); new(this) AliITSQADataMakerRec(qac); return *this; } //____________________________________________________________________________ void AliITSQADataMakerRec::StartOfDetectorCycle() { //Detector specific actions at start of cycle AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM::Start of ITS Cycle\n"); if(fSubDetector == 0 || fSubDetector == 1) fSPDDataMaker->StartOfDetectorCycle(); if(fSubDetector == 0 || fSubDetector == 2) fSDDDataMaker->StartOfDetectorCycle(); if(fSubDetector == 0 || fSubDetector == 3) fSSDDataMaker->StartOfDetectorCycle(); } //____________________________________________________________________________ void AliITSQADataMakerRec::EndOfDetectorCycle(AliQAv1::TASKINDEX_t task, TObjArray** list) { // launch the QA checking for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) { SetEventSpecie(specie) ; AliDebug(AliQAv1::GetQADebugLevel(),"AliITSDM instantiates checker with Run(AliQAv1::kITS, task, list[specie])\n"); if(fSubDetector == 0 || fSubDetector == 1) fSPDDataMaker->EndOfDetectorCycle(task, list[specie]); if(fSubDetector == 0 || fSubDetector == 2) fSDDDataMaker->EndOfDetectorCycle(task, list[specie]); if(fSubDetector == 0 || fSubDetector == 3) fSSDDataMaker->EndOfDetectorCycle(task, list[specie]); AliQAChecker *qac = AliQAChecker::Instance(); AliITSQAChecker *qacb = (AliITSQAChecker *) qac->GetDetQAChecker(0); Int_t subdet=GetSubDet(); qacb->SetSubDet(subdet); if(subdet== 0 ){ qacb->SetTaskOffset(fSPDDataMaker->GetOffset(task), fSDDDataMaker->GetOffset(task), fSSDDataMaker->GetOffset(task)); //Setting the offset for the QAChecker list } else if(subdet!=0){ Int_t offset=GetDetTaskOffset(subdet, task); qacb->SetDetTaskOffset(subdet,offset); } qac->Run( AliQAv1::kITS , task, list); } } //____________________________________________________________________________ void AliITSQADataMakerRec::EndOfDetectorCycle(const char * /*fgDataName*/) { //eventually used for different AliQAChecker::Instance()->Run } //____________________________________________________________________________ void AliITSQADataMakerRec::InitRaws() { // Initialization for RAW data if(fSubDetector == 0 || fSubDetector == 1) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SPD InitRaws\n"); fSPDDataMaker->InitRaws(); } if(fSubDetector == 0 || fSubDetector == 2) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SDD InitRaws\n"); fSDDDataMaker->InitRaws(); } if(fSubDetector == 0 || fSubDetector == 3) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SSD InitRaws\n"); fSSDDataMaker->InitRaws(); } } //____________________________________________________________________________ void AliITSQADataMakerRec::MakeRaws(AliRawReader* rawReader) { // Fill QA for RAW if(fSubDetector == 0 || fSubDetector == 1) fSPDDataMaker->MakeRaws(rawReader); if(fSubDetector == 0 || fSubDetector == 2) fSDDDataMaker->MakeRaws(rawReader); if(fSubDetector == 0 || fSubDetector == 3) fSSDDataMaker->MakeRaws(rawReader); } //____________________________________________________________________________ void AliITSQADataMakerRec::InitRecPoints() { // Initialization for RECPOINTS if(fSubDetector == 0 || fSubDetector == 1) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SPD InitRecPoints\n"); fSPDDataMaker->InitRecPoints(); } if(fSubDetector == 0 || fSubDetector == 2) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SDD InitRecPoints\n"); fSDDDataMaker->InitRecPoints(); } if(fSubDetector == 0 || fSubDetector == 3) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SSD InitRecPoints\n"); fSSDDataMaker->InitRecPoints(); } } //____________________________________________________________________________ void AliITSQADataMakerRec::MakeRecPoints(TTree * clustersTree) { // Fill QA for recpoints if(fSubDetector == 0 || fSubDetector == 1) fSPDDataMaker->MakeRecPoints(clustersTree); if(fSubDetector == 0 || fSubDetector == 2) fSDDDataMaker->MakeRecPoints(clustersTree); if(fSubDetector == 0 || fSubDetector == 3) fSSDDataMaker->MakeRecPoints(clustersTree); } //____________________________________________________________________________ void AliITSQADataMakerRec::InitESDs() { // Create ESDs histograms in ESDs subdir Bool_t expertHistogram = kTRUE; TH1F *hESDClustersMI = new TH1F("hESDClustersMI", "N ITS clusters per track (MI); N clusters; Counts", 7, -0.5, 6.5); hESDClustersMI->Sumw2(); hESDClustersMI->SetMinimum(0); Add2ESDsList(hESDClustersMI, 0); TH1F *hESDClusterMapMI = new TH1F("hESDClusterMapMI", "N tracks with point Layer (MI); Layer; N tracks", 6, -0.5, 5.5); hESDClusterMapMI->Sumw2(); hESDClusterMapMI->SetMinimum(0); Add2ESDsList(hESDClusterMapMI, 1, expertHistogram); TH1F *hESDClustersSA = new TH1F("hESDClustersSA", "N ITS clusters per track (SA); N clusters; Counts", 7, -0.5, 6.5); hESDClustersSA->Sumw2(); hESDClustersSA->SetMinimum(0); Add2ESDsList(hESDClustersSA, 2); TH1F *hESDClusterMapSA = new TH1F("hESDClusterMapSA", "N tracks with point Layer (SA); Layer; N tracks", 6, -0.5, 5.5); hESDClusterMapSA->Sumw2(); hESDClusterMapSA->SetMinimum(0); Add2ESDsList(hESDClusterMapSA, 3, expertHistogram); TH1F *hSPDVertexX = new TH1F("hSPDVertexX","SPD Vertex x; x [cm]; N events", 10000,-2,2); hSPDVertexX->Sumw2(); Add2ESDsList(hSPDVertexX, 4); TH1F *hSPDVertexY = new TH1F("hSPDVertexY","SPD Vertex y; y [cm]; N events", 10000,-2,2); hSPDVertexY->Sumw2(); Add2ESDsList(hSPDVertexY, 5); TH1F *hSPDVertexZ = new TH1F("hSPDVertexZ","SPD Vertex Z; z [cm]; N events", 10000,-20,20); hSPDVertexZ->Sumw2(); Add2ESDsList(hSPDVertexZ, 6); TH1F *hSPDVertexContrOverMult = new TH1F("hSPDVertexContrOverMult","SPD Vertex: contributors / multiplicity; N contributors / SPD multiplicity; N events", 100,-4,20); hSPDVertexContrOverMult->Sumw2(); Add2ESDsList(hSPDVertexContrOverMult, 7, expertHistogram); TH1F *hTrkVertexX = new TH1F("hTrkVertexX","ITS+TPC Trk Vertex x; x [cm]; N events", 10000,-2,2); hTrkVertexX->Sumw2(); Add2ESDsList(hTrkVertexX, 8, expertHistogram); TH1F *hTrkVertexY = new TH1F("hTrkVertexY","ITS+TPC Trk Vertex y; y [cm]; N events", 10000,-2,2); hTrkVertexY->Sumw2(); Add2ESDsList(hTrkVertexY, 9, expertHistogram); TH1F *hTrkVertexZ = new TH1F("hTrkVertexZ","ITS+TPC Trk Vertex Z; z [cm]; N events", 10000,-20,20); hTrkVertexZ->Sumw2(); Add2ESDsList(hTrkVertexZ, 10, expertHistogram); TH1F *hTrkVertexContrOverITSrefit5 = new TH1F("hTrkVertexContrOverITSrefit5","ITS+TPC Trk Vertex: contributors / tracks; N contributors / N trks kITSrefit with 5 or 6 clusters; N events", 100,-4,2); hTrkVertexContrOverITSrefit5->Sumw2(); Add2ESDsList(hTrkVertexContrOverITSrefit5, 11, expertHistogram); TH1F *hSPDTrkVertexDeltaX = new TH1F("hSPDTrkVertexDeltaX","Comparison of SPD and Trk vertices: x; xSPD-xTrk [cm]; N events", 1000,-1,1); hSPDTrkVertexDeltaX->Sumw2(); Add2ESDsList(hSPDTrkVertexDeltaX, 12, expertHistogram); TH1F *hSPDTrkVertexDeltaY = new TH1F("hSPDTrkVertexDeltaY","Comparison of SPD and Trk vertices: y; ySPD-yTrk [cm]; N events", 1000,-1,1); hSPDTrkVertexDeltaY->Sumw2(); Add2ESDsList(hSPDTrkVertexDeltaY, 13, expertHistogram); TH1F *hSPDTrkVertexDeltaZ = new TH1F("hSPDTrkVertexDeltaZ","Comparison of SPD and Trk vertices: z; zSPD-zTrk [cm]; N events", 1000,-1,1); hSPDTrkVertexDeltaZ->Sumw2(); Add2ESDsList(hSPDTrkVertexDeltaZ, 14); // SPD Tracklets TH1F* hSPDTracklets = new TH1F("hSPDTracklets","N SPD Tracklets; N tracklets; Counts",300,0.,300.); hSPDTracklets->Sumw2(); Add2ESDsList(hSPDTracklets, 15); TH2F* hSPDTrackletsvsFiredChips0 = new TH2F("hSPDTrackletsvsFiredChips0","N SPD Tracklets vs N FiredChips Layer0", 300,0.,300.,300,0.,300.); hSPDTrackletsvsFiredChips0->GetXaxis()->SetTitle("N SPD Tracklets"); hSPDTrackletsvsFiredChips0->GetYaxis()->SetTitle("N FiredChips Layer0"); hSPDTrackletsvsFiredChips0->Sumw2(); Add2ESDsList(hSPDTrackletsvsFiredChips0, 16, expertHistogram ); TH2F* hSPDTrackletsvsFiredChips1 = new TH2F("hSPDTrackletsvsFiredChips1","N SPD Tracklets vs N FiredChips Layer1", 300,0.,300.,300,0.,300.); hSPDTrackletsvsFiredChips1->GetXaxis()->SetTitle("N SPD Tracklets"); hSPDTrackletsvsFiredChips1->GetYaxis()->SetTitle("N FiredChips Layer1"); hSPDTrackletsvsFiredChips1->Sumw2(); Add2ESDsList(hSPDTrackletsvsFiredChips1, 17, expertHistogram); TH1F* hSPDTrackletsDePhi = new TH1F("hSPDTrackletsDePhi","DeltaPhi SPD Tracklets; DeltaPhi [rad]; N events",200,-0.2,0.2); hSPDTrackletsDePhi->Sumw2(); Add2ESDsList(hSPDTrackletsDePhi, 18); TH1F* hSPDTrackletsPhi = new TH1F("hSPDTrackletsPhi","Phi SPD Tracklets; Phi [rad]; N events",1000,0.,2*TMath::Pi()); hSPDTrackletsPhi->Sumw2(); Add2ESDsList(hSPDTrackletsPhi, 19); TH1F* hSPDTrackletsTheta = new TH1F("hSPDTrackletsTheta","Theta SPD Tracklets; Theta [rad]; N events",500,0.,TMath::Pi()); hSPDTrackletsTheta->Sumw2(); Add2ESDsList(hSPDTrackletsTheta, 20); // map of layers skipped by tracking (set in AliITSRecoParam) TH1F *hESDSkippedLayers = new TH1F("hESDSkippedLayers", "Map of layers skipped by tracking; Layer; Skipped", 6, -0.5, 5.5); hESDSkippedLayers->Sumw2(); hESDSkippedLayers->SetMinimum(0); Add2ESDsList(hESDSkippedLayers, 21, expertHistogram); return; } //____________________________________________________________________________ void AliITSQADataMakerRec::MakeESDs(AliESDEvent *esd) { // Make QA data from ESDs const Int_t nESDTracks = esd->GetNumberOfTracks(); Int_t nITSrefit5 = 0; Int_t idet,status; Float_t xloc,zloc; // loop on tracks for(Int_t i = 0; i < nESDTracks; i++) { AliESDtrack *track = esd->GetTrack(i); Int_t nclsITS = track->GetNcls(0); Bool_t itsrefit=kFALSE,tpcin=kFALSE,itsin=kFALSE; if ((track->GetStatus() & AliESDtrack::kITSrefit)) itsrefit=kTRUE; if ((track->GetStatus() & AliESDtrack::kTPCin)) tpcin=kTRUE; if ((track->GetStatus() & AliESDtrack::kITSin)) itsin=kTRUE; if(nclsITS>=5 && itsrefit) nITSrefit5++; if(tpcin) { GetESDsData(0)->Fill(nclsITS); } if(itsin && !tpcin){ GetESDsData(2)->Fill(nclsITS); } for(Int_t layer=0; layer<6; layer++) { if(TESTBIT(track->GetITSClusterMap(),layer)) { if(tpcin) { GetESDsData(1)->Fill(layer); } else { GetESDsData(3)->Fill(layer); } } track->GetITSModuleIndexInfo(layer,idet,status,xloc,zloc); if(status==3) GetESDsData(21)->SetBinContent(layer,1); } } // end loop on tracks // vertices const AliESDVertex *vtxSPD = esd->GetPrimaryVertexSPD(); const AliESDVertex *vtxTrk = esd->GetPrimaryVertex(); Int_t mult = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetNumberOfTracklets(); if(mult>0) GetESDsData(7)->Fill((Float_t)(vtxSPD->GetNContributors())/(Float_t)mult); if(nITSrefit5>0) GetESDsData(11)->Fill((Float_t)(vtxTrk->GetNIndices())/(Float_t)nITSrefit5); if(vtxSPD->GetNContributors()>0) { GetESDsData(4)->Fill(vtxSPD->GetXv()); GetESDsData(5)->Fill(vtxSPD->GetYv()); GetESDsData(6)->Fill(vtxSPD->GetZv()); } if(vtxTrk->GetNContributors()>0) { GetESDsData(8)->Fill(vtxTrk->GetXv()); GetESDsData(9)->Fill(vtxTrk->GetYv()); GetESDsData(10)->Fill(vtxTrk->GetZv()); } if(vtxSPD->GetNContributors()>0 && vtxTrk->GetNContributors()>0) { GetESDsData(12)->Fill(vtxSPD->GetXv()-vtxTrk->GetXv()); GetESDsData(13)->Fill(vtxSPD->GetYv()-vtxTrk->GetYv()); GetESDsData(14)->Fill(vtxSPD->GetZv()-vtxTrk->GetZv()); } // SPD Tracklets GetESDsData(15)->Fill(mult); Short_t nFiredChips0 = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetNumberOfFiredChips(0); Short_t nFiredChips1 = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetNumberOfFiredChips(1); GetESDsData(16)->Fill(nFiredChips0,mult); GetESDsData(17)->Fill(nFiredChips1,mult); // Loop over tracklets for (Int_t itr=0; itr<mult; ++itr) { Float_t dePhiTr = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetDeltaPhi(itr); Float_t phiTr = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetPhi(itr); Float_t thetaTr = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetTheta(itr); GetESDsData(18)->Fill(dePhiTr); GetESDsData(19)->Fill(phiTr); GetESDsData(20)->Fill(thetaTr); } // end loop on tracklets return; } //_________________________________________________________________ Int_t AliITSQADataMakerRec::GetDetTaskOffset(Int_t subdet,AliQAv1::TASKINDEX_t task) { switch(subdet) { Int_t offset; case 1: offset=fSPDDataMaker->GetOffset(task); return offset; break; case 2: offset=fSDDDataMaker->GetOffset(task); return offset; break; case 3: offset=fSSDDataMaker->GetOffset(task); return offset; break; default: AliWarning("No specific subdetector (SPD, SDD, SSD) selected!! Offset set to zero \n"); offset=0; return offset; break; } //return offset; } esd->Get Vertex changed to esd->GetVertexTracks (A. Dainese) /************************************************************************** * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // ************************************************************* // Checks the quality assurance // by comparing with reference data // contained in a DB // ------------------------------------------------------------- // W. Ferrarese + P. Cerello Feb 2008 // INFN Torino // --- ROOT system --- #include <TH2.h> #include <TTree.h> // --- Standard library --- // --- AliRoot header files --- #include "AliITSQADataMakerRec.h" #include "AliITSQASPDDataMakerRec.h" #include "AliITSQASDDDataMakerRec.h" #include "AliITSQASSDDataMakerRec.h" #include "AliLog.h" #include "AliQAv1.h" #include "AliQAChecker.h" #include "AliITSQAChecker.h" #include "AliRawReader.h" #include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliESDVertex.h" #include "AliMultiplicity.h" ClassImp(AliITSQADataMakerRec) //____________________________________________________________________________ AliITSQADataMakerRec::AliITSQADataMakerRec(Bool_t kMode, Short_t subDet, Short_t ldc) : AliQADataMakerRec(AliQAv1::GetDetName(AliQAv1::kITS), "ITS Quality Assurance Data Maker"), fkOnline(kMode), fHLTMode(0), fSubDetector(subDet), fLDC(ldc), fSPDDataMaker(NULL), fSDDDataMaker(NULL), fSSDDataMaker(NULL) { //ctor used to discriminate OnLine-Offline analysis if(fSubDetector < 0 || fSubDetector > 3) { AliError("Error: fSubDetector number out of range; return\n"); } // Initialization for RAW data if(fSubDetector == 0 || fSubDetector == 1) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM::Create SPD DataMakerRec\n"); fSPDDataMaker = new AliITSQASPDDataMakerRec(this,fkOnline); } if(fSubDetector == 0 || fSubDetector == 2) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM::Create SDD DataMakerRec\n"); fSDDDataMaker = new AliITSQASDDDataMakerRec(this,fkOnline); if(fkOnline){SetHLTMode(fSDDDataMaker->GetHLTMode()); } } if(fSubDetector == 0 || fSubDetector == 3) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM::Create SSD DataMakerRec\n"); fSSDDataMaker = new AliITSQASSDDataMakerRec(this,fkOnline); } } //____________________________________________________________________________ AliITSQADataMakerRec::~AliITSQADataMakerRec(){ // destructor if(fSPDDataMaker)delete fSPDDataMaker; if(fSDDDataMaker)delete fSDDDataMaker; if(fSSDDataMaker)delete fSSDDataMaker; } //____________________________________________________________________________ AliITSQADataMakerRec::AliITSQADataMakerRec(const AliITSQADataMakerRec& qadm) : AliQADataMakerRec(), fkOnline(qadm.fkOnline), fHLTMode(qadm.fHLTMode), fSubDetector(qadm.fSubDetector), fLDC(qadm.fLDC), fSPDDataMaker(NULL), fSDDDataMaker(NULL), fSSDDataMaker(NULL) { //copy ctor SetName((const char*)qadm.GetName()) ; SetTitle((const char*)qadm.GetTitle()); } //__________________________________________________________________ AliITSQADataMakerRec& AliITSQADataMakerRec::operator = (const AliITSQADataMakerRec& qac ) { // Equal operator. this->~AliITSQADataMakerRec(); new(this) AliITSQADataMakerRec(qac); return *this; } //____________________________________________________________________________ void AliITSQADataMakerRec::StartOfDetectorCycle() { //Detector specific actions at start of cycle AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM::Start of ITS Cycle\n"); if(fSubDetector == 0 || fSubDetector == 1) fSPDDataMaker->StartOfDetectorCycle(); if(fSubDetector == 0 || fSubDetector == 2) fSDDDataMaker->StartOfDetectorCycle(); if(fSubDetector == 0 || fSubDetector == 3) fSSDDataMaker->StartOfDetectorCycle(); } //____________________________________________________________________________ void AliITSQADataMakerRec::EndOfDetectorCycle(AliQAv1::TASKINDEX_t task, TObjArray** list) { // launch the QA checking for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) { SetEventSpecie(specie) ; AliDebug(AliQAv1::GetQADebugLevel(),"AliITSDM instantiates checker with Run(AliQAv1::kITS, task, list[specie])\n"); if(fSubDetector == 0 || fSubDetector == 1) fSPDDataMaker->EndOfDetectorCycle(task, list[specie]); if(fSubDetector == 0 || fSubDetector == 2) fSDDDataMaker->EndOfDetectorCycle(task, list[specie]); if(fSubDetector == 0 || fSubDetector == 3) fSSDDataMaker->EndOfDetectorCycle(task, list[specie]); AliQAChecker *qac = AliQAChecker::Instance(); AliITSQAChecker *qacb = (AliITSQAChecker *) qac->GetDetQAChecker(0); Int_t subdet=GetSubDet(); qacb->SetSubDet(subdet); if(subdet== 0 ){ qacb->SetTaskOffset(fSPDDataMaker->GetOffset(task), fSDDDataMaker->GetOffset(task), fSSDDataMaker->GetOffset(task)); //Setting the offset for the QAChecker list } else if(subdet!=0){ Int_t offset=GetDetTaskOffset(subdet, task); qacb->SetDetTaskOffset(subdet,offset); } qac->Run( AliQAv1::kITS , task, list); } } //____________________________________________________________________________ void AliITSQADataMakerRec::EndOfDetectorCycle(const char * /*fgDataName*/) { //eventually used for different AliQAChecker::Instance()->Run } //____________________________________________________________________________ void AliITSQADataMakerRec::InitRaws() { // Initialization for RAW data if(fSubDetector == 0 || fSubDetector == 1) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SPD InitRaws\n"); fSPDDataMaker->InitRaws(); } if(fSubDetector == 0 || fSubDetector == 2) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SDD InitRaws\n"); fSDDDataMaker->InitRaws(); } if(fSubDetector == 0 || fSubDetector == 3) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SSD InitRaws\n"); fSSDDataMaker->InitRaws(); } } //____________________________________________________________________________ void AliITSQADataMakerRec::MakeRaws(AliRawReader* rawReader) { // Fill QA for RAW if(fSubDetector == 0 || fSubDetector == 1) fSPDDataMaker->MakeRaws(rawReader); if(fSubDetector == 0 || fSubDetector == 2) fSDDDataMaker->MakeRaws(rawReader); if(fSubDetector == 0 || fSubDetector == 3) fSSDDataMaker->MakeRaws(rawReader); } //____________________________________________________________________________ void AliITSQADataMakerRec::InitRecPoints() { // Initialization for RECPOINTS if(fSubDetector == 0 || fSubDetector == 1) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SPD InitRecPoints\n"); fSPDDataMaker->InitRecPoints(); } if(fSubDetector == 0 || fSubDetector == 2) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SDD InitRecPoints\n"); fSDDDataMaker->InitRecPoints(); } if(fSubDetector == 0 || fSubDetector == 3) { AliDebug(AliQAv1::GetQADebugLevel(),"AliITSQADM:: SSD InitRecPoints\n"); fSSDDataMaker->InitRecPoints(); } } //____________________________________________________________________________ void AliITSQADataMakerRec::MakeRecPoints(TTree * clustersTree) { // Fill QA for recpoints if(fSubDetector == 0 || fSubDetector == 1) fSPDDataMaker->MakeRecPoints(clustersTree); if(fSubDetector == 0 || fSubDetector == 2) fSDDDataMaker->MakeRecPoints(clustersTree); if(fSubDetector == 0 || fSubDetector == 3) fSSDDataMaker->MakeRecPoints(clustersTree); } //____________________________________________________________________________ void AliITSQADataMakerRec::InitESDs() { // Create ESDs histograms in ESDs subdir Bool_t expertHistogram = kTRUE; TH1F *hESDClustersMI = new TH1F("hESDClustersMI", "N ITS clusters per track (MI); N clusters; Counts", 7, -0.5, 6.5); hESDClustersMI->Sumw2(); hESDClustersMI->SetMinimum(0); Add2ESDsList(hESDClustersMI, 0); TH1F *hESDClusterMapMI = new TH1F("hESDClusterMapMI", "N tracks with point Layer (MI); Layer; N tracks", 6, -0.5, 5.5); hESDClusterMapMI->Sumw2(); hESDClusterMapMI->SetMinimum(0); Add2ESDsList(hESDClusterMapMI, 1, expertHistogram); TH1F *hESDClustersSA = new TH1F("hESDClustersSA", "N ITS clusters per track (SA); N clusters; Counts", 7, -0.5, 6.5); hESDClustersSA->Sumw2(); hESDClustersSA->SetMinimum(0); Add2ESDsList(hESDClustersSA, 2); TH1F *hESDClusterMapSA = new TH1F("hESDClusterMapSA", "N tracks with point Layer (SA); Layer; N tracks", 6, -0.5, 5.5); hESDClusterMapSA->Sumw2(); hESDClusterMapSA->SetMinimum(0); Add2ESDsList(hESDClusterMapSA, 3, expertHistogram); TH1F *hSPDVertexX = new TH1F("hSPDVertexX","SPD Vertex x; x [cm]; N events", 10000,-2,2); hSPDVertexX->Sumw2(); Add2ESDsList(hSPDVertexX, 4); TH1F *hSPDVertexY = new TH1F("hSPDVertexY","SPD Vertex y; y [cm]; N events", 10000,-2,2); hSPDVertexY->Sumw2(); Add2ESDsList(hSPDVertexY, 5); TH1F *hSPDVertexZ = new TH1F("hSPDVertexZ","SPD Vertex Z; z [cm]; N events", 10000,-20,20); hSPDVertexZ->Sumw2(); Add2ESDsList(hSPDVertexZ, 6); TH1F *hSPDVertexContrOverMult = new TH1F("hSPDVertexContrOverMult","SPD Vertex: contributors / multiplicity; N contributors / SPD multiplicity; N events", 100,-4,20); hSPDVertexContrOverMult->Sumw2(); Add2ESDsList(hSPDVertexContrOverMult, 7, expertHistogram); TH1F *hTrkVertexX = new TH1F("hTrkVertexX","ITS+TPC Trk Vertex x; x [cm]; N events", 10000,-2,2); hTrkVertexX->Sumw2(); Add2ESDsList(hTrkVertexX, 8, expertHistogram); TH1F *hTrkVertexY = new TH1F("hTrkVertexY","ITS+TPC Trk Vertex y; y [cm]; N events", 10000,-2,2); hTrkVertexY->Sumw2(); Add2ESDsList(hTrkVertexY, 9, expertHistogram); TH1F *hTrkVertexZ = new TH1F("hTrkVertexZ","ITS+TPC Trk Vertex Z; z [cm]; N events", 10000,-20,20); hTrkVertexZ->Sumw2(); Add2ESDsList(hTrkVertexZ, 10, expertHistogram); TH1F *hTrkVertexContrOverITSrefit5 = new TH1F("hTrkVertexContrOverITSrefit5","ITS+TPC Trk Vertex: contributors / tracks; N contributors / N trks kITSrefit with 5 or 6 clusters; N events", 100,-4,2); hTrkVertexContrOverITSrefit5->Sumw2(); Add2ESDsList(hTrkVertexContrOverITSrefit5, 11, expertHistogram); TH1F *hSPDTrkVertexDeltaX = new TH1F("hSPDTrkVertexDeltaX","Comparison of SPD and Trk vertices: x; xSPD-xTrk [cm]; N events", 1000,-1,1); hSPDTrkVertexDeltaX->Sumw2(); Add2ESDsList(hSPDTrkVertexDeltaX, 12, expertHistogram); TH1F *hSPDTrkVertexDeltaY = new TH1F("hSPDTrkVertexDeltaY","Comparison of SPD and Trk vertices: y; ySPD-yTrk [cm]; N events", 1000,-1,1); hSPDTrkVertexDeltaY->Sumw2(); Add2ESDsList(hSPDTrkVertexDeltaY, 13, expertHistogram); TH1F *hSPDTrkVertexDeltaZ = new TH1F("hSPDTrkVertexDeltaZ","Comparison of SPD and Trk vertices: z; zSPD-zTrk [cm]; N events", 1000,-1,1); hSPDTrkVertexDeltaZ->Sumw2(); Add2ESDsList(hSPDTrkVertexDeltaZ, 14); // SPD Tracklets TH1F* hSPDTracklets = new TH1F("hSPDTracklets","N SPD Tracklets; N tracklets; Counts",300,0.,300.); hSPDTracklets->Sumw2(); Add2ESDsList(hSPDTracklets, 15); TH2F* hSPDTrackletsvsFiredChips0 = new TH2F("hSPDTrackletsvsFiredChips0","N SPD Tracklets vs N FiredChips Layer0", 300,0.,300.,300,0.,300.); hSPDTrackletsvsFiredChips0->GetXaxis()->SetTitle("N SPD Tracklets"); hSPDTrackletsvsFiredChips0->GetYaxis()->SetTitle("N FiredChips Layer0"); hSPDTrackletsvsFiredChips0->Sumw2(); Add2ESDsList(hSPDTrackletsvsFiredChips0, 16, expertHistogram ); TH2F* hSPDTrackletsvsFiredChips1 = new TH2F("hSPDTrackletsvsFiredChips1","N SPD Tracklets vs N FiredChips Layer1", 300,0.,300.,300,0.,300.); hSPDTrackletsvsFiredChips1->GetXaxis()->SetTitle("N SPD Tracklets"); hSPDTrackletsvsFiredChips1->GetYaxis()->SetTitle("N FiredChips Layer1"); hSPDTrackletsvsFiredChips1->Sumw2(); Add2ESDsList(hSPDTrackletsvsFiredChips1, 17, expertHistogram); TH1F* hSPDTrackletsDePhi = new TH1F("hSPDTrackletsDePhi","DeltaPhi SPD Tracklets; DeltaPhi [rad]; N events",200,-0.2,0.2); hSPDTrackletsDePhi->Sumw2(); Add2ESDsList(hSPDTrackletsDePhi, 18); TH1F* hSPDTrackletsPhi = new TH1F("hSPDTrackletsPhi","Phi SPD Tracklets; Phi [rad]; N events",1000,0.,2*TMath::Pi()); hSPDTrackletsPhi->Sumw2(); Add2ESDsList(hSPDTrackletsPhi, 19); TH1F* hSPDTrackletsTheta = new TH1F("hSPDTrackletsTheta","Theta SPD Tracklets; Theta [rad]; N events",500,0.,TMath::Pi()); hSPDTrackletsTheta->Sumw2(); Add2ESDsList(hSPDTrackletsTheta, 20); // map of layers skipped by tracking (set in AliITSRecoParam) TH1F *hESDSkippedLayers = new TH1F("hESDSkippedLayers", "Map of layers skipped by tracking; Layer; Skipped", 6, -0.5, 5.5); hESDSkippedLayers->Sumw2(); hESDSkippedLayers->SetMinimum(0); Add2ESDsList(hESDSkippedLayers, 21, expertHistogram); return; } //____________________________________________________________________________ void AliITSQADataMakerRec::MakeESDs(AliESDEvent *esd) { // Make QA data from ESDs const Int_t nESDTracks = esd->GetNumberOfTracks(); Int_t nITSrefit5 = 0; Int_t idet,status; Float_t xloc,zloc; // loop on tracks for(Int_t i = 0; i < nESDTracks; i++) { AliESDtrack *track = esd->GetTrack(i); Int_t nclsITS = track->GetNcls(0); Bool_t itsrefit=kFALSE,tpcin=kFALSE,itsin=kFALSE; if ((track->GetStatus() & AliESDtrack::kITSrefit)) itsrefit=kTRUE; if ((track->GetStatus() & AliESDtrack::kTPCin)) tpcin=kTRUE; if ((track->GetStatus() & AliESDtrack::kITSin)) itsin=kTRUE; if(nclsITS>=5 && itsrefit) nITSrefit5++; if(tpcin) { GetESDsData(0)->Fill(nclsITS); } if(itsin && !tpcin){ GetESDsData(2)->Fill(nclsITS); } for(Int_t layer=0; layer<6; layer++) { if(TESTBIT(track->GetITSClusterMap(),layer)) { if(tpcin) { GetESDsData(1)->Fill(layer); } else { GetESDsData(3)->Fill(layer); } } track->GetITSModuleIndexInfo(layer,idet,status,xloc,zloc); if(status==3) GetESDsData(21)->SetBinContent(layer,1); } } // end loop on tracks // vertices const AliESDVertex *vtxSPD = esd->GetPrimaryVertexSPD(); const AliESDVertex *vtxTrk = esd->GetPrimaryVertexTracks(); Int_t mult = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetNumberOfTracklets(); if(mult>0) GetESDsData(7)->Fill((Float_t)(vtxSPD->GetNContributors())/(Float_t)mult); if(nITSrefit5>0) GetESDsData(11)->Fill((Float_t)(vtxTrk->GetNIndices())/(Float_t)nITSrefit5); if(vtxSPD->GetNContributors()>0) { GetESDsData(4)->Fill(vtxSPD->GetXv()); GetESDsData(5)->Fill(vtxSPD->GetYv()); GetESDsData(6)->Fill(vtxSPD->GetZv()); } if(vtxTrk->GetNContributors()>0) { GetESDsData(8)->Fill(vtxTrk->GetXv()); GetESDsData(9)->Fill(vtxTrk->GetYv()); GetESDsData(10)->Fill(vtxTrk->GetZv()); } if(vtxSPD->GetNContributors()>0 && vtxTrk->GetNContributors()>0) { GetESDsData(12)->Fill(vtxSPD->GetXv()-vtxTrk->GetXv()); GetESDsData(13)->Fill(vtxSPD->GetYv()-vtxTrk->GetYv()); GetESDsData(14)->Fill(vtxSPD->GetZv()-vtxTrk->GetZv()); } // SPD Tracklets GetESDsData(15)->Fill(mult); Short_t nFiredChips0 = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetNumberOfFiredChips(0); Short_t nFiredChips1 = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetNumberOfFiredChips(1); GetESDsData(16)->Fill(nFiredChips0,mult); GetESDsData(17)->Fill(nFiredChips1,mult); // Loop over tracklets for (Int_t itr=0; itr<mult; ++itr) { Float_t dePhiTr = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetDeltaPhi(itr); Float_t phiTr = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetPhi(itr); Float_t thetaTr = ((AliMultiplicity*)(esd->GetMultiplicity()))->GetTheta(itr); GetESDsData(18)->Fill(dePhiTr); GetESDsData(19)->Fill(phiTr); GetESDsData(20)->Fill(thetaTr); } // end loop on tracklets return; } //_________________________________________________________________ Int_t AliITSQADataMakerRec::GetDetTaskOffset(Int_t subdet,AliQAv1::TASKINDEX_t task) { switch(subdet) { Int_t offset; case 1: offset=fSPDDataMaker->GetOffset(task); return offset; break; case 2: offset=fSDDDataMaker->GetOffset(task); return offset; break; case 3: offset=fSSDDataMaker->GetOffset(task); return offset; break; default: AliWarning("No specific subdetector (SPD, SDD, SSD) selected!! Offset set to zero \n"); offset=0; return offset; break; } //return offset; }
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <hintids.hxx> #include <com/sun/star/lang/Locale.hpp> #include <com/sun/star/linguistic2/XThesaurus.hpp> #include <com/sun/star/linguistic2/ProofreadingResult.hpp> #include <com/sun/star/i18n/TextConversionOption.hpp> #include <linguistic/lngprops.hxx> #include <comphelper/processfactory.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <vcl/msgbox.hxx> #include <svtools/ehdl.hxx> #include <svl/stritem.hxx> #include <sfx2/viewfrm.hxx> #include <sfx2/request.hxx> #include <svx/dlgutil.hxx> #include <svx/dialmgr.hxx> #include <editeng/langitem.hxx> #include <svx/svxerr.hxx> #include <editeng/unolingu.hxx> #include <svx/svxdlg.hxx> #include <editeng/SpellPortions.hxx> #include <swmodule.hxx> #include <swwait.hxx> #include <initui.hxx> #include <uitool.hxx> #include <view.hxx> #include <wrtsh.hxx> #include <basesh.hxx> #include <docsh.hxx> #include <viewopt.hxx> #include <swundo.hxx> #include <hyp.hxx> #include <olmenu.hxx> #include <pam.hxx> #include <edtwin.hxx> #include <crsskip.hxx> #include <ndtxt.hxx> #include <vcl/lstbox.hxx> #include <cmdid.h> #include <globals.hrc> #include <comcore.hrc> #include <view.hrc> #include <hhcwrp.hxx> #include <com/sun/star/frame/XStorable.hpp> #include <com/sun/star/ui/dialogs/XExecutableDialog.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/frame/XDispatch.hpp> #include <com/sun/star/frame/XDispatchProvider.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/util/URL.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/util/URLTransformer.hpp> #include <com/sun/star/util/XURLTransformer.hpp> #include <vcl/svapp.hxx> #include <rtl/ustring.hxx> #include <cppuhelper/bootstrap.hxx> #include "stmenu.hxx" #include <svx/dialogs.hrc> #include <svtools/langtab.hxx> #include <unomid.h> #include <IMark.hxx> #include <xmloff/odffields.hxx> #include <editeng/editerr.hxx> #include <boost/scoped_ptr.hpp> using namespace sw::mark; using namespace ::com::sun::star; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::linguistic2; using namespace ::com::sun::star::smarttags; // Lingu-Dispatcher void SwView::ExecLingu(SfxRequest &rReq) { switch(rReq.GetSlot()) { case SID_THESAURUS: StartThesaurus(); rReq.Ignore(); break; case SID_HANGUL_HANJA_CONVERSION: StartTextConversion( LANGUAGE_KOREAN, LANGUAGE_KOREAN, NULL, i18n::TextConversionOption::CHARACTER_BY_CHARACTER, true ); break; case SID_CHINESE_CONVERSION: { //open ChineseTranslationDialog Reference< XComponentContext > xContext( ::cppu::defaultBootstrap_InitialComponentContext() ); //@todo get context from calc if that has one if(xContext.is()) { Reference< lang::XMultiComponentFactory > xMCF( xContext->getServiceManager() ); if(xMCF.is()) { Reference< ui::dialogs::XExecutableDialog > xDialog( xMCF->createInstanceWithContext( OUString("com.sun.star.linguistic2.ChineseTranslationDialog") , xContext), UNO_QUERY); Reference< lang::XInitialization > xInit( xDialog, UNO_QUERY ); if( xInit.is() ) { // initialize dialog Reference< awt::XWindow > xDialogParentWindow(0); Sequence<Any> aSeq(1); Any* pArray = aSeq.getArray(); PropertyValue aParam; aParam.Name = "ParentWindow"; aParam.Value <<= makeAny(xDialogParentWindow); pArray[0] <<= makeAny(aParam); xInit->initialize( aSeq ); //execute dialog sal_Int16 nDialogRet = xDialog->execute(); if( RET_OK == nDialogRet ) { //get some parameters from the dialog bool bToSimplified = true; bool bUseVariants = true; bool bCommonTerms = true; Reference< beans::XPropertySet > xProp( xDialog, UNO_QUERY ); if( xProp.is() ) { try { xProp->getPropertyValue( "IsDirectionToSimplified" ) >>= bToSimplified; xProp->getPropertyValue( "IsUseCharacterVariants" ) >>= bUseVariants; xProp->getPropertyValue( "IsTranslateCommonTerms" ) >>= bCommonTerms; } catch (const Exception&) { } } //execute translation sal_Int16 nSourceLang = bToSimplified ? LANGUAGE_CHINESE_TRADITIONAL : LANGUAGE_CHINESE_SIMPLIFIED; sal_Int16 nTargetLang = bToSimplified ? LANGUAGE_CHINESE_SIMPLIFIED : LANGUAGE_CHINESE_TRADITIONAL; sal_Int32 nOptions = bUseVariants ? i18n::TextConversionOption::USE_CHARACTER_VARIANTS : 0; if( !bCommonTerms ) nOptions = nOptions | i18n::TextConversionOption::CHARACTER_BY_CHARACTER; vcl::Font aTargetFont = OutputDevice::GetDefaultFont( DefaultFontType::CJK_TEXT, nTargetLang, GetDefaultFontFlags::OnlyOne ); // disallow formatting, updating the view, ... while // converting the document. (saves time) // Also remember the current view and cursor position for later m_pWrtShell->StartAction(); // remember cursor position data for later restoration of the cursor const SwPosition *pPoint = m_pWrtShell->GetCrsr()->GetPoint(); bool bRestoreCursor = pPoint->nNode.GetNode().IsTextNode(); const SwNodeIndex aPointNodeIndex( pPoint->nNode ); sal_Int32 nPointIndex = pPoint->nContent.GetIndex(); // since this conversion is not interactive the whole converted // document should be undone in a single undo step. m_pWrtShell->StartUndo( UNDO_OVERWRITE ); StartTextConversion( nSourceLang, nTargetLang, &aTargetFont, nOptions, false ); m_pWrtShell->EndUndo( UNDO_OVERWRITE ); if (bRestoreCursor) { SwTextNode *pTextNode = aPointNodeIndex.GetNode().GetTextNode(); // check for unexpected error case OSL_ENSURE(pTextNode && pTextNode->GetText().getLength() >= nPointIndex, "text missing: corrupted node?" ); if (!pTextNode || pTextNode->GetText().getLength() < nPointIndex) nPointIndex = 0; // restore cursor to its original position m_pWrtShell->GetCrsr()->GetPoint()->nContent.Assign( pTextNode, nPointIndex ); } // enable all, restore view and cursor position m_pWrtShell->EndAction(); } } Reference< lang::XComponent > xComponent( xDialog, UNO_QUERY ); if( xComponent.is() ) xComponent->dispose(); } } break; } case FN_HYPHENATE_OPT_DLG: HyphenateDocument(); break; default: OSL_ENSURE(false, "wrong Dispatcher"); return; } } // start language specific text conversion void SwView::StartTextConversion( LanguageType nSourceLang, LanguageType nTargetLang, const vcl::Font *pTargetFont, sal_Int32 nOptions, bool bIsInteractive ) { // do not do text conversion if it is active elsewhere if (SwEditShell::HasConvIter()) { return; } SpellKontext(true); const SwViewOption* pVOpt = m_pWrtShell->GetViewOptions(); const bool bOldIdle = pVOpt->IsIdle(); pVOpt->SetIdle( false ); bool bOldIns = m_pWrtShell->IsInsMode(); m_pWrtShell->SetInsMode( true ); const bool bSelection = static_cast<SwCrsrShell*>(m_pWrtShell)->HasSelection() || m_pWrtShell->GetCrsr() != m_pWrtShell->GetCrsr()->GetNext(); const bool bStart = bSelection || m_pWrtShell->IsStartOfDoc(); const bool bOther = !bSelection && !(m_pWrtShell->GetFrmType(0,true) & FrmTypeFlags::BODY); { const uno::Reference< uno::XComponentContext > xContext( comphelper::getProcessComponentContext() ); SwHHCWrapper aWrap( this, xContext, nSourceLang, nTargetLang, pTargetFont, nOptions, bIsInteractive, bStart, bOther, bSelection ); aWrap.Convert(); } m_pWrtShell->SetInsMode( bOldIns ); pVOpt->SetIdle( bOldIdle ); SpellKontext(false); } // spellcheck and text conversion related stuff void SwView::SpellStart( SvxSpellArea eWhich, bool bStartDone, bool bEndDone, SwConversionArgs *pConvArgs ) { Reference< XLinguProperties > xProp = ::GetLinguPropertySet(); bool bIsWrapReverse = !pConvArgs && xProp.is() && xProp->getIsWrapReverse(); SwDocPositions eStart = DOCPOS_START; SwDocPositions eEnd = DOCPOS_END; SwDocPositions eCurr = DOCPOS_CURR; switch ( eWhich ) { case SVX_SPELL_BODY: if( bIsWrapReverse ) eCurr = DOCPOS_END; else eCurr = DOCPOS_START; break; case SVX_SPELL_BODY_END: if( bIsWrapReverse ) { if( bStartDone ) eStart = DOCPOS_CURR; eCurr = DOCPOS_END; } else if( bStartDone ) eCurr = DOCPOS_START; break; case SVX_SPELL_BODY_START: if( !bIsWrapReverse ) { if( bEndDone ) eEnd = DOCPOS_CURR; eCurr = DOCPOS_START; } else if( bEndDone ) eCurr = DOCPOS_END; break; case SVX_SPELL_OTHER: if( bIsWrapReverse ) { eStart = DOCPOS_OTHERSTART; eEnd = DOCPOS_OTHEREND; eCurr = DOCPOS_OTHEREND; } else { eStart = DOCPOS_OTHERSTART; eEnd = DOCPOS_OTHEREND; eCurr = DOCPOS_OTHERSTART; } break; default: OSL_ENSURE( false, "SpellStart with unknown Area" ); } m_pWrtShell->SpellStart( eStart, eEnd, eCurr, pConvArgs ); } // Error message while Spelling // The passed pointer nlang is itself the value void SwView::SpellError(LanguageType eLang) { #if OSL_DEBUG_LEVEL > 1 sal_Bool bFocus = GetEditWin().HasFocus(); #endif int nPend = 0; if ( m_pWrtShell->ActionPend() ) { m_pWrtShell->Push(); m_pWrtShell->ClearMark(); do { m_pWrtShell->EndAction(); ++nPend; } while( m_pWrtShell->ActionPend() ); } OUString aErr(SvtLanguageTable::GetLanguageString( eLang ) ); SwEditWin &rEditWin = GetEditWin(); #if OSL_DEBUG_LEVEL > 1 bFocus = rEditWin.HasFocus(); #endif int nWaitCnt = 0; while( rEditWin.IsWait() ) { rEditWin.LeaveWait(); ++nWaitCnt; } if ( LANGUAGE_NONE == eLang ) ErrorHandler::HandleError( ERRCODE_SVX_LINGU_NOLANGUAGE ); else ErrorHandler::HandleError( *new StringErrorInfo( ERRCODE_SVX_LINGU_LANGUAGENOTEXISTS, aErr ) ); while( nWaitCnt ) { rEditWin.EnterWait(); --nWaitCnt; } #if OSL_DEBUG_LEVEL > 1 bFocus = GetEditWin().HasFocus(); #endif if ( nPend ) { while( nPend-- ) m_pWrtShell->StartAction(); m_pWrtShell->Combine(); } #if OSL_DEBUG_LEVEL > 1 if( !bFocus ) GetEditWin().GrabFocus(); #endif } // Finish spelling and restore cursor void SwView::SpellEnd( SwConversionArgs *pConvArgs ) { m_pWrtShell->SpellEnd( pConvArgs ); if( m_pWrtShell->IsExtMode() ) m_pWrtShell->SetMark(); } void SwView::HyphStart( SvxSpellArea eWhich ) { switch ( eWhich ) { case SVX_SPELL_BODY: m_pWrtShell->HyphStart( DOCPOS_START, DOCPOS_END ); break; case SVX_SPELL_BODY_END: m_pWrtShell->HyphStart( DOCPOS_CURR, DOCPOS_END ); break; case SVX_SPELL_BODY_START: m_pWrtShell->HyphStart( DOCPOS_START, DOCPOS_CURR ); break; case SVX_SPELL_OTHER: m_pWrtShell->HyphStart( DOCPOS_OTHERSTART, DOCPOS_OTHEREND ); break; default: OSL_ENSURE( false, "HyphStart with unknown Area" ); } } // Interactive separation void SwView::HyphenateDocument() { // do not hyphenate if interactive hyphenation is active elsewhere if (SwEditShell::HasHyphIter()) { ScopedVclPtr<MessBox>::Create( nullptr, WB_OK, OUString( SW_RES( STR_HYPH_TITLE ) ), OUString( SW_RES( STR_MULT_INTERACT_HYPH_WARN ) ) )->Execute(); return; } SfxErrorContext aContext( ERRCTX_SVX_LINGU_HYPHENATION, OUString(), m_pEditWin, RID_SVXERRCTX, &DIALOG_MGR() ); Reference< XHyphenator > xHyph( ::GetHyphenator() ); if (!xHyph.is()) { ErrorHandler::HandleError( ERRCODE_SVX_LINGU_LINGUNOTEXISTS ); return; } if (m_pWrtShell->GetSelectionType() & (nsSelectionType::SEL_DRW_TXT|nsSelectionType::SEL_DRW)) { // Hyphenation in a Draw object HyphenateDrawText(); } else { SwViewOption* pVOpt = const_cast<SwViewOption*>(m_pWrtShell->GetViewOptions()); bool bOldIdle = pVOpt->IsIdle(); pVOpt->SetIdle( false ); Reference< XLinguProperties > xProp( ::GetLinguPropertySet() ); m_pWrtShell->StartUndo(UNDO_INSATTR); // valid later bool bHyphSpecial = xProp.is() && xProp->getIsHyphSpecial(); bool bSelection = static_cast<SwCrsrShell*>(m_pWrtShell)->HasSelection() || m_pWrtShell->GetCrsr() != m_pWrtShell->GetCrsr()->GetNext(); bool bOther = m_pWrtShell->HasOtherCnt() && bHyphSpecial && !bSelection; bool bStart = bSelection || ( !bOther && m_pWrtShell->IsStartOfDoc() ); bool bStop = false; if( !bOther && !(m_pWrtShell->GetFrmType(0,true) & FrmTypeFlags::BODY) && !bSelection ) // turned on no special area { // I want also in special areas hyphenation ScopedVclPtrInstance< MessageDialog > aBox(&GetEditWin(), SW_RES(STR_QUERY_SPECIAL_FORCED), VCL_MESSAGE_QUESTION, VCL_BUTTONS_YES_NO); if( aBox->Execute() == RET_YES ) { bOther = true; if (xProp.is()) { xProp->setIsHyphSpecial( sal_True ); } } else bStop = true; // No hyphenation } if( !bStop ) { SwHyphWrapper aWrap( this, xHyph, bStart, bOther, bSelection ); aWrap.SpellDocument(); m_pWrtShell->EndUndo(UNDO_INSATTR); } pVOpt->SetIdle( bOldIdle ); } } bool SwView::IsValidSelectionForThesaurus() const { // must not be a multi-selection, and if it is a selection it needs // to be within a single paragraph const bool bMultiSel = m_pWrtShell->GetCrsr()->IsMultiSelection(); const bool bSelection = static_cast<SwCrsrShell*>(m_pWrtShell)->HasSelection(); return !bMultiSel && (!bSelection || m_pWrtShell->IsSelOnePara() ); } OUString SwView::GetThesaurusLookUpText( bool bSelection ) const { return bSelection ? OUString(m_pWrtShell->GetSelText()) : m_pWrtShell->GetCurWord(); } void SwView::InsertThesaurusSynonym( const OUString &rSynonmText, const OUString &rLookUpText, bool bSelection ) { bool bOldIns = m_pWrtShell->IsInsMode(); m_pWrtShell->SetInsMode( true ); m_pWrtShell->StartAllAction(); m_pWrtShell->StartUndo(UNDO_DELETE); if( !bSelection ) { if(m_pWrtShell->IsEndWrd()) m_pWrtShell->Left(CRSR_SKIP_CELLS, false, 1, false ); m_pWrtShell->SelWrd(); // make sure the selection build later from the data below does not // include "in word" character to the left and right in order to // preserve those. Therefore count those "in words" in order to modify // the selection accordingly. const sal_Unicode* pChar = rLookUpText.getStr(); sal_Int32 nLeft = 0; while (pChar && *pChar++ == CH_TXTATR_INWORD) ++nLeft; pChar = rLookUpText.getLength() ? rLookUpText.getStr() + rLookUpText.getLength() - 1 : 0; sal_Int32 nRight = 0; while (pChar && *pChar-- == CH_TXTATR_INWORD) ++nRight; // adjust existing selection SwPaM *pCrsr = m_pWrtShell->GetCrsr(); pCrsr->GetPoint()->nContent -= nRight; pCrsr->GetMark()->nContent += nLeft; } m_pWrtShell->Insert( rSynonmText ); m_pWrtShell->EndUndo(UNDO_DELETE); m_pWrtShell->EndAllAction(); m_pWrtShell->SetInsMode( bOldIns ); } // Start thesaurus void SwView::StartThesaurus() { if (!IsValidSelectionForThesaurus()) return; SfxErrorContext aContext( ERRCTX_SVX_LINGU_THESAURUS, OUString(), m_pEditWin, RID_SVXERRCTX, &DIALOG_MGR() ); // Determine language LanguageType eLang = m_pWrtShell->GetCurLang(); if( LANGUAGE_SYSTEM == eLang ) eLang = GetAppLanguage(); if( eLang == LANGUAGE_DONTKNOW || eLang == LANGUAGE_NONE ) { SpellError( LANGUAGE_NONE ); return; } SwViewOption* pVOpt = const_cast<SwViewOption*>(m_pWrtShell->GetViewOptions()); bool bOldIdle = pVOpt->IsIdle(); pVOpt->SetIdle( false ); // get initial LookUp text const bool bSelection = static_cast<SwCrsrShell*>(m_pWrtShell)->HasSelection(); OUString aTmp = GetThesaurusLookUpText( bSelection ); Reference< XThesaurus > xThes( ::GetThesaurus() ); if ( !xThes.is() || !xThes->hasLocale( LanguageTag::convertToLocale( eLang ) ) ) SpellError( eLang ); else { boost::scoped_ptr<AbstractThesaurusDialog> pDlg; // create dialog { //Scope for SwWait-Object SwWait aWait( *GetDocShell(), true ); // load library with dialog only on demand ... SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create(); pDlg.reset(pFact->CreateThesaurusDialog( &GetEditWin(), xThes, aTmp, eLang )); } if ( pDlg->Execute()== RET_OK ) InsertThesaurusSynonym( pDlg->GetWord(), aTmp, bSelection ); } pVOpt->SetIdle( bOldIdle ); } // Offer online suggestions //!! Start of extra code for context menu modifying extensions struct ExecuteInfo { uno::Reference< frame::XDispatch > xDispatch; util::URL aTargetURL; uno::Sequence< PropertyValue > aArgs; }; class AsyncExecute { public: DECL_STATIC_LINK( AsyncExecute, ExecuteHdl_Impl, ExecuteInfo* ); }; IMPL_STATIC_LINK( AsyncExecute, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo ) { SolarMutexReleaser aReleaser; try { // Asynchronous execution as this can lead to our own destruction! // Framework can recycle our current frame and the layout manager disposes all user interface // elements if a component gets detached from its frame! pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs ); } catch (const Exception&) { } delete pExecuteInfo; return 0; } //!! End of extra code for context menu modifying extensions bool SwView::ExecSpellPopup(const Point& rPt) { bool bRet = false; const SwViewOption* pVOpt = m_pWrtShell->GetViewOptions(); if( pVOpt->IsOnlineSpell() && !m_pWrtShell->IsSelection()) { if (m_pWrtShell->GetSelectionType() & nsSelectionType::SEL_DRW_TXT) bRet = ExecDrwTextSpellPopup(rPt); else if (!m_pWrtShell->IsSelFrmMode()) { const bool bOldViewLock = m_pWrtShell->IsViewLocked(); m_pWrtShell->LockView( true ); m_pWrtShell->Push(); SwRect aToFill; // decide which variant of the context menu to use... // if neither spell checking nor grammar checking provides suggestions use the // default context menu. bool bUseGrammarContext = false; Reference< XSpellAlternatives > xAlt( m_pWrtShell->GetCorrection(&rPt, aToFill) ); ProofreadingResult aGrammarCheckRes; sal_Int32 nErrorInResult = -1; uno::Sequence< OUString > aSuggestions; bool bCorrectionRes = false; if (!xAlt.is() || xAlt->getAlternatives().getLength() == 0) { sal_Int32 nErrorPosInText = -1; bCorrectionRes = m_pWrtShell->GetGrammarCorrection( aGrammarCheckRes, nErrorPosInText, nErrorInResult, aSuggestions, &rPt, aToFill ); OUString aMessageText; if (nErrorInResult >= 0) aMessageText = aGrammarCheckRes.aErrors[ nErrorInResult ].aShortComment; // we like to use the grammar checking context menu if we either get // some suggestions or at least a comment about the error found... bUseGrammarContext = bCorrectionRes && (aSuggestions.getLength() > 0 || !aMessageText.isEmpty()); } // open respective context menu for spell check or grammar errors with correction suggestions... if ((!bUseGrammarContext && xAlt.is()) || (bUseGrammarContext && bCorrectionRes && aGrammarCheckRes.aErrors.getLength() > 0)) { // get paragraph text OUString aParaText; SwPosition aPoint( *m_pWrtShell->GetCrsr()->GetPoint() ); const SwTextNode *pNode = dynamic_cast< const SwTextNode * >( &aPoint.nNode.GetNode() ); if (pNode) aParaText = pNode->GetText(); // this may include hidden text but that should be Ok else { OSL_FAIL("text node expected but not found" ); } bRet = true; m_pWrtShell->SttSelect(); boost::scoped_ptr< SwSpellPopup > pPopup; if (bUseGrammarContext) { sal_Int32 nPos = aPoint.nContent.GetIndex(); (void) nPos; pPopup.reset(new SwSpellPopup( m_pWrtShell, aGrammarCheckRes, nErrorInResult, aSuggestions, aParaText )); } else pPopup.reset(new SwSpellPopup( m_pWrtShell, xAlt, aParaText )); ui::ContextMenuExecuteEvent aEvent; const Point aPixPos = GetEditWin().LogicToPixel( rPt ); aEvent.SourceWindow = VCLUnoHelper::GetInterface( m_pEditWin ); aEvent.ExecutePosition.X = aPixPos.X(); aEvent.ExecutePosition.Y = aPixPos.Y(); Menu* pMenu = 0; OUString sMenuName = bUseGrammarContext ? OUString("private:resource/GrammarContextMenu") : OUString("private:resource/SpellContextMenu"); if(TryContextMenuInterception( *pPopup, sMenuName, pMenu, aEvent )) { //! happy hacking for context menu modifying extensions of this //! 'custom made' menu... *sigh* (code copied from sfx2 and framework) if ( pMenu ) { const sal_uInt16 nId = static_cast<PopupMenu*>(pMenu)->Execute(m_pEditWin, aPixPos); OUString aCommand = static_cast<PopupMenu*>(pMenu)->GetItemCommand(nId); if (aCommand.isEmpty() ) { if(!ExecuteMenuCommand(dynamic_cast<PopupMenu&>(*pMenu), *GetViewFrame(), nId )) pPopup->Execute(nId); } else { SfxViewFrame *pSfxViewFrame = GetViewFrame(); uno::Reference< frame::XFrame > xFrame; if ( pSfxViewFrame ) xFrame = pSfxViewFrame->GetFrame().GetFrameInterface(); com::sun::star::util::URL aURL; uno::Reference< frame::XDispatchProvider > xDispatchProvider( xFrame, UNO_QUERY ); try { uno::Reference< frame::XDispatch > xDispatch; uno::Reference< util::XURLTransformer > xURLTransformer = util::URLTransformer::create(comphelper::getProcessComponentContext()); aURL.Complete = aCommand; xURLTransformer->parseStrict(aURL); uno::Sequence< beans::PropertyValue > aArgs; xDispatch = xDispatchProvider->queryDispatch( aURL, OUString(), 0 ); if (xDispatch.is()) { // Execute dispatch asynchronously ExecuteInfo* pExecuteInfo = new ExecuteInfo; pExecuteInfo->xDispatch = xDispatch; pExecuteInfo->aTargetURL = aURL; pExecuteInfo->aArgs = aArgs; Application::PostUserEvent( LINK(0, AsyncExecute , ExecuteHdl_Impl), pExecuteInfo ); } } catch (const Exception&) { } } } else { pPopup->Execute( aToFill.SVRect(), m_pEditWin ); } } } m_pWrtShell->Pop( false ); m_pWrtShell->LockView( bOldViewLock ); } } return bRet; } /** Function: ExecSmartTagPopup This function shows the popup menu for smarttag actions. */ bool SwView::ExecSmartTagPopup( const Point& rPt ) { bool bRet = false; const bool bOldViewLock = m_pWrtShell->IsViewLocked(); m_pWrtShell->LockView( true ); m_pWrtShell->Push(); // get word that was clicked on // This data structure maps a smart tag type string to the property bag SwRect aToFill; Sequence< OUString > aSmartTagTypes; Sequence< Reference< container::XStringKeyMap > > aStringKeyMaps; Reference<text::XTextRange> xRange; m_pWrtShell->GetSmartTagTerm( rPt, aToFill, aSmartTagTypes, aStringKeyMaps, xRange); if ( xRange.is() && aSmartTagTypes.getLength() ) { bRet = true; m_pWrtShell->SttSelect(); SwSmartTagPopup aPopup( this, aSmartTagTypes, aStringKeyMaps, xRange ); aPopup.Execute( aToFill.SVRect(), m_pEditWin ); } m_pWrtShell->Pop( false ); m_pWrtShell->LockView( bOldViewLock ); return bRet; } class SwFieldDialog : public FloatingWindow { private: VclPtr<ListBox> aListBox; IFieldmark *pFieldmark; DECL_LINK( MyListBoxHandler, ListBox * ); public: SwFieldDialog( SwEditWin* parent, IFieldmark *fieldBM ); virtual ~SwFieldDialog(); virtual void dispose() SAL_OVERRIDE; }; SwFieldDialog::SwFieldDialog( SwEditWin* parent, IFieldmark *fieldBM ) : FloatingWindow( parent, WB_BORDER | WB_SYSTEMWINDOW ), aListBox(VclPtr<ListBox>::Create(this)), pFieldmark( fieldBM ) { if ( fieldBM != NULL ) { const IFieldmark::parameter_map_t* const pParameters = fieldBM->GetParameters(); OUString sListKey = OUString( ODF_FORMDROPDOWN_LISTENTRY ); IFieldmark::parameter_map_t::const_iterator pListEntries = pParameters->find( sListKey ); if(pListEntries != pParameters->end()) { Sequence< OUString > vListEntries; pListEntries->second >>= vListEntries; for( OUString* pCurrent = vListEntries.getArray(); pCurrent != vListEntries.getArray() + vListEntries.getLength(); ++pCurrent) { aListBox->InsertEntry(*pCurrent); } } // Select the current one OUString sResultKey = OUString( ODF_FORMDROPDOWN_RESULT ); IFieldmark::parameter_map_t::const_iterator pResult = pParameters->find( sResultKey ); if ( pResult != pParameters->end() ) { sal_Int32 nSelection = -1; pResult->second >>= nSelection; aListBox->SelectEntryPos( nSelection ); } } Size lbSize(aListBox->GetOptimalSize()); lbSize.Width()+=50; lbSize.Height()+=20; aListBox->SetSizePixel(lbSize); aListBox->SetSelectHdl( LINK( this, SwFieldDialog, MyListBoxHandler ) ); aListBox->Show(); SetSizePixel( lbSize ); } SwFieldDialog::~SwFieldDialog() { disposeOnce(); } void SwFieldDialog::dispose() { aListBox.disposeAndClear(); FloatingWindow::dispose(); } IMPL_LINK( SwFieldDialog, MyListBoxHandler, ListBox *, pBox ) { short res = 0; if ( !pBox->IsTravelSelect() ) { sal_Int32 selection = pBox->GetSelectEntryPos(); if ( selection >= 0 ) { OUString sKey = OUString( ODF_FORMDROPDOWN_RESULT ); (*pFieldmark->GetParameters())[ sKey ] = makeAny(selection); pFieldmark->Invalidate(); SwView& rView = static_cast<SwEditWin*>( GetParent() )->GetView(); rView.GetDocShell()->SetModified( true ); } EndPopupMode(); res = 1; } return res; } IMPL_LINK_NOARG(SwView, FieldPopupModeEndHdl) { m_pFieldPopup.disposeAndClear(); return 0; } void SwView::ExecFieldPopup( const Point& rPt, IFieldmark *fieldBM ) { const Point aPixPos = GetEditWin().LogicToPixel( rPt ); m_pFieldPopup = VclPtr<SwFieldDialog>::Create( m_pEditWin, fieldBM ); m_pFieldPopup->SetPopupModeEndHdl( LINK( this, SwView, FieldPopupModeEndHdl ) ); Rectangle aRect( m_pEditWin->OutputToScreenPixel( aPixPos ), Size( 0, 0 ) ); m_pFieldPopup->StartPopupMode( aRect, FloatWinPopupFlags::Down|FloatWinPopupFlags::GrabFocus ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ Spell-check wrong-dirty text upon showing context menu. This makes for a better user experience when the idle jobs haven't yet ran on some text to check for spelling. This can happen when the user is on a device with insufficient compute power and/or other idle jobs with higher-priority take precedence. This change leap-frogs the spell-checking idle job when the user might already know they mistyped a word and look for a quick fix via the context menu. Change-Id: Id1f7b4555050ded329ebeb56502f893ee7b2bc35 Reviewed-on: https://gerrit.libreoffice.org/17252 Tested-by: Jenkins <5a4fe08359c7f97380e408c717ef42c86939cd86@libreoffice.org> Reviewed-by: Norbert Thiebaud <4a068946920c47769d700757a47cfec2afcce997@gmail.com> /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <hintids.hxx> #include <com/sun/star/lang/Locale.hpp> #include <com/sun/star/linguistic2/XThesaurus.hpp> #include <com/sun/star/linguistic2/ProofreadingResult.hpp> #include <com/sun/star/i18n/TextConversionOption.hpp> #include <linguistic/lngprops.hxx> #include <comphelper/processfactory.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <vcl/msgbox.hxx> #include <svtools/ehdl.hxx> #include <svl/stritem.hxx> #include <sfx2/viewfrm.hxx> #include <sfx2/request.hxx> #include <svx/dlgutil.hxx> #include <svx/dialmgr.hxx> #include <editeng/langitem.hxx> #include <svx/svxerr.hxx> #include <editeng/unolingu.hxx> #include <svx/svxdlg.hxx> #include <editeng/SpellPortions.hxx> #include <swmodule.hxx> #include <swwait.hxx> #include <initui.hxx> #include <uitool.hxx> #include <view.hxx> #include <wrtsh.hxx> #include <basesh.hxx> #include <docsh.hxx> #include <viewopt.hxx> #include <swundo.hxx> #include <hyp.hxx> #include <olmenu.hxx> #include <pam.hxx> #include <edtwin.hxx> #include <crsskip.hxx> #include <ndtxt.hxx> #include <txtfrm.hxx> #include <vcl/lstbox.hxx> #include <cmdid.h> #include <globals.hrc> #include <comcore.hrc> #include <view.hrc> #include <hhcwrp.hxx> #include <com/sun/star/frame/XStorable.hpp> #include <com/sun/star/ui/dialogs/XExecutableDialog.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/frame/XDispatch.hpp> #include <com/sun/star/frame/XDispatchProvider.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/util/URL.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/util/URLTransformer.hpp> #include <com/sun/star/util/XURLTransformer.hpp> #include <vcl/svapp.hxx> #include <rtl/ustring.hxx> #include <cppuhelper/bootstrap.hxx> #include "stmenu.hxx" #include <svx/dialogs.hrc> #include <svtools/langtab.hxx> #include <unomid.h> #include <IMark.hxx> #include <xmloff/odffields.hxx> #include <editeng/editerr.hxx> #include <boost/scoped_ptr.hpp> using namespace sw::mark; using namespace ::com::sun::star; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::linguistic2; using namespace ::com::sun::star::smarttags; // Lingu-Dispatcher void SwView::ExecLingu(SfxRequest &rReq) { switch(rReq.GetSlot()) { case SID_THESAURUS: StartThesaurus(); rReq.Ignore(); break; case SID_HANGUL_HANJA_CONVERSION: StartTextConversion( LANGUAGE_KOREAN, LANGUAGE_KOREAN, NULL, i18n::TextConversionOption::CHARACTER_BY_CHARACTER, true ); break; case SID_CHINESE_CONVERSION: { //open ChineseTranslationDialog Reference< XComponentContext > xContext( ::cppu::defaultBootstrap_InitialComponentContext() ); //@todo get context from calc if that has one if(xContext.is()) { Reference< lang::XMultiComponentFactory > xMCF( xContext->getServiceManager() ); if(xMCF.is()) { Reference< ui::dialogs::XExecutableDialog > xDialog( xMCF->createInstanceWithContext( OUString("com.sun.star.linguistic2.ChineseTranslationDialog") , xContext), UNO_QUERY); Reference< lang::XInitialization > xInit( xDialog, UNO_QUERY ); if( xInit.is() ) { // initialize dialog Reference< awt::XWindow > xDialogParentWindow(0); Sequence<Any> aSeq(1); Any* pArray = aSeq.getArray(); PropertyValue aParam; aParam.Name = "ParentWindow"; aParam.Value <<= makeAny(xDialogParentWindow); pArray[0] <<= makeAny(aParam); xInit->initialize( aSeq ); //execute dialog sal_Int16 nDialogRet = xDialog->execute(); if( RET_OK == nDialogRet ) { //get some parameters from the dialog bool bToSimplified = true; bool bUseVariants = true; bool bCommonTerms = true; Reference< beans::XPropertySet > xProp( xDialog, UNO_QUERY ); if( xProp.is() ) { try { xProp->getPropertyValue( "IsDirectionToSimplified" ) >>= bToSimplified; xProp->getPropertyValue( "IsUseCharacterVariants" ) >>= bUseVariants; xProp->getPropertyValue( "IsTranslateCommonTerms" ) >>= bCommonTerms; } catch (const Exception&) { } } //execute translation sal_Int16 nSourceLang = bToSimplified ? LANGUAGE_CHINESE_TRADITIONAL : LANGUAGE_CHINESE_SIMPLIFIED; sal_Int16 nTargetLang = bToSimplified ? LANGUAGE_CHINESE_SIMPLIFIED : LANGUAGE_CHINESE_TRADITIONAL; sal_Int32 nOptions = bUseVariants ? i18n::TextConversionOption::USE_CHARACTER_VARIANTS : 0; if( !bCommonTerms ) nOptions = nOptions | i18n::TextConversionOption::CHARACTER_BY_CHARACTER; vcl::Font aTargetFont = OutputDevice::GetDefaultFont( DefaultFontType::CJK_TEXT, nTargetLang, GetDefaultFontFlags::OnlyOne ); // disallow formatting, updating the view, ... while // converting the document. (saves time) // Also remember the current view and cursor position for later m_pWrtShell->StartAction(); // remember cursor position data for later restoration of the cursor const SwPosition *pPoint = m_pWrtShell->GetCrsr()->GetPoint(); bool bRestoreCursor = pPoint->nNode.GetNode().IsTextNode(); const SwNodeIndex aPointNodeIndex( pPoint->nNode ); sal_Int32 nPointIndex = pPoint->nContent.GetIndex(); // since this conversion is not interactive the whole converted // document should be undone in a single undo step. m_pWrtShell->StartUndo( UNDO_OVERWRITE ); StartTextConversion( nSourceLang, nTargetLang, &aTargetFont, nOptions, false ); m_pWrtShell->EndUndo( UNDO_OVERWRITE ); if (bRestoreCursor) { SwTextNode *pTextNode = aPointNodeIndex.GetNode().GetTextNode(); // check for unexpected error case OSL_ENSURE(pTextNode && pTextNode->GetText().getLength() >= nPointIndex, "text missing: corrupted node?" ); if (!pTextNode || pTextNode->GetText().getLength() < nPointIndex) nPointIndex = 0; // restore cursor to its original position m_pWrtShell->GetCrsr()->GetPoint()->nContent.Assign( pTextNode, nPointIndex ); } // enable all, restore view and cursor position m_pWrtShell->EndAction(); } } Reference< lang::XComponent > xComponent( xDialog, UNO_QUERY ); if( xComponent.is() ) xComponent->dispose(); } } break; } case FN_HYPHENATE_OPT_DLG: HyphenateDocument(); break; default: OSL_ENSURE(false, "wrong Dispatcher"); return; } } // start language specific text conversion void SwView::StartTextConversion( LanguageType nSourceLang, LanguageType nTargetLang, const vcl::Font *pTargetFont, sal_Int32 nOptions, bool bIsInteractive ) { // do not do text conversion if it is active elsewhere if (SwEditShell::HasConvIter()) { return; } SpellKontext(true); const SwViewOption* pVOpt = m_pWrtShell->GetViewOptions(); const bool bOldIdle = pVOpt->IsIdle(); pVOpt->SetIdle( false ); bool bOldIns = m_pWrtShell->IsInsMode(); m_pWrtShell->SetInsMode( true ); const bool bSelection = static_cast<SwCrsrShell*>(m_pWrtShell)->HasSelection() || m_pWrtShell->GetCrsr() != m_pWrtShell->GetCrsr()->GetNext(); const bool bStart = bSelection || m_pWrtShell->IsStartOfDoc(); const bool bOther = !bSelection && !(m_pWrtShell->GetFrmType(0,true) & FrmTypeFlags::BODY); { const uno::Reference< uno::XComponentContext > xContext( comphelper::getProcessComponentContext() ); SwHHCWrapper aWrap( this, xContext, nSourceLang, nTargetLang, pTargetFont, nOptions, bIsInteractive, bStart, bOther, bSelection ); aWrap.Convert(); } m_pWrtShell->SetInsMode( bOldIns ); pVOpt->SetIdle( bOldIdle ); SpellKontext(false); } // spellcheck and text conversion related stuff void SwView::SpellStart( SvxSpellArea eWhich, bool bStartDone, bool bEndDone, SwConversionArgs *pConvArgs ) { Reference< XLinguProperties > xProp = ::GetLinguPropertySet(); bool bIsWrapReverse = !pConvArgs && xProp.is() && xProp->getIsWrapReverse(); SwDocPositions eStart = DOCPOS_START; SwDocPositions eEnd = DOCPOS_END; SwDocPositions eCurr = DOCPOS_CURR; switch ( eWhich ) { case SVX_SPELL_BODY: if( bIsWrapReverse ) eCurr = DOCPOS_END; else eCurr = DOCPOS_START; break; case SVX_SPELL_BODY_END: if( bIsWrapReverse ) { if( bStartDone ) eStart = DOCPOS_CURR; eCurr = DOCPOS_END; } else if( bStartDone ) eCurr = DOCPOS_START; break; case SVX_SPELL_BODY_START: if( !bIsWrapReverse ) { if( bEndDone ) eEnd = DOCPOS_CURR; eCurr = DOCPOS_START; } else if( bEndDone ) eCurr = DOCPOS_END; break; case SVX_SPELL_OTHER: if( bIsWrapReverse ) { eStart = DOCPOS_OTHERSTART; eEnd = DOCPOS_OTHEREND; eCurr = DOCPOS_OTHEREND; } else { eStart = DOCPOS_OTHERSTART; eEnd = DOCPOS_OTHEREND; eCurr = DOCPOS_OTHERSTART; } break; default: OSL_ENSURE( false, "SpellStart with unknown Area" ); } m_pWrtShell->SpellStart( eStart, eEnd, eCurr, pConvArgs ); } // Error message while Spelling // The passed pointer nlang is itself the value void SwView::SpellError(LanguageType eLang) { #if OSL_DEBUG_LEVEL > 1 sal_Bool bFocus = GetEditWin().HasFocus(); #endif int nPend = 0; if ( m_pWrtShell->ActionPend() ) { m_pWrtShell->Push(); m_pWrtShell->ClearMark(); do { m_pWrtShell->EndAction(); ++nPend; } while( m_pWrtShell->ActionPend() ); } OUString aErr(SvtLanguageTable::GetLanguageString( eLang ) ); SwEditWin &rEditWin = GetEditWin(); #if OSL_DEBUG_LEVEL > 1 bFocus = rEditWin.HasFocus(); #endif int nWaitCnt = 0; while( rEditWin.IsWait() ) { rEditWin.LeaveWait(); ++nWaitCnt; } if ( LANGUAGE_NONE == eLang ) ErrorHandler::HandleError( ERRCODE_SVX_LINGU_NOLANGUAGE ); else ErrorHandler::HandleError( *new StringErrorInfo( ERRCODE_SVX_LINGU_LANGUAGENOTEXISTS, aErr ) ); while( nWaitCnt ) { rEditWin.EnterWait(); --nWaitCnt; } #if OSL_DEBUG_LEVEL > 1 bFocus = GetEditWin().HasFocus(); #endif if ( nPend ) { while( nPend-- ) m_pWrtShell->StartAction(); m_pWrtShell->Combine(); } #if OSL_DEBUG_LEVEL > 1 if( !bFocus ) GetEditWin().GrabFocus(); #endif } // Finish spelling and restore cursor void SwView::SpellEnd( SwConversionArgs *pConvArgs ) { m_pWrtShell->SpellEnd( pConvArgs ); if( m_pWrtShell->IsExtMode() ) m_pWrtShell->SetMark(); } void SwView::HyphStart( SvxSpellArea eWhich ) { switch ( eWhich ) { case SVX_SPELL_BODY: m_pWrtShell->HyphStart( DOCPOS_START, DOCPOS_END ); break; case SVX_SPELL_BODY_END: m_pWrtShell->HyphStart( DOCPOS_CURR, DOCPOS_END ); break; case SVX_SPELL_BODY_START: m_pWrtShell->HyphStart( DOCPOS_START, DOCPOS_CURR ); break; case SVX_SPELL_OTHER: m_pWrtShell->HyphStart( DOCPOS_OTHERSTART, DOCPOS_OTHEREND ); break; default: OSL_ENSURE( false, "HyphStart with unknown Area" ); } } // Interactive separation void SwView::HyphenateDocument() { // do not hyphenate if interactive hyphenation is active elsewhere if (SwEditShell::HasHyphIter()) { ScopedVclPtr<MessBox>::Create( nullptr, WB_OK, OUString( SW_RES( STR_HYPH_TITLE ) ), OUString( SW_RES( STR_MULT_INTERACT_HYPH_WARN ) ) )->Execute(); return; } SfxErrorContext aContext( ERRCTX_SVX_LINGU_HYPHENATION, OUString(), m_pEditWin, RID_SVXERRCTX, &DIALOG_MGR() ); Reference< XHyphenator > xHyph( ::GetHyphenator() ); if (!xHyph.is()) { ErrorHandler::HandleError( ERRCODE_SVX_LINGU_LINGUNOTEXISTS ); return; } if (m_pWrtShell->GetSelectionType() & (nsSelectionType::SEL_DRW_TXT|nsSelectionType::SEL_DRW)) { // Hyphenation in a Draw object HyphenateDrawText(); } else { SwViewOption* pVOpt = const_cast<SwViewOption*>(m_pWrtShell->GetViewOptions()); bool bOldIdle = pVOpt->IsIdle(); pVOpt->SetIdle( false ); Reference< XLinguProperties > xProp( ::GetLinguPropertySet() ); m_pWrtShell->StartUndo(UNDO_INSATTR); // valid later bool bHyphSpecial = xProp.is() && xProp->getIsHyphSpecial(); bool bSelection = static_cast<SwCrsrShell*>(m_pWrtShell)->HasSelection() || m_pWrtShell->GetCrsr() != m_pWrtShell->GetCrsr()->GetNext(); bool bOther = m_pWrtShell->HasOtherCnt() && bHyphSpecial && !bSelection; bool bStart = bSelection || ( !bOther && m_pWrtShell->IsStartOfDoc() ); bool bStop = false; if( !bOther && !(m_pWrtShell->GetFrmType(0,true) & FrmTypeFlags::BODY) && !bSelection ) // turned on no special area { // I want also in special areas hyphenation ScopedVclPtrInstance< MessageDialog > aBox(&GetEditWin(), SW_RES(STR_QUERY_SPECIAL_FORCED), VCL_MESSAGE_QUESTION, VCL_BUTTONS_YES_NO); if( aBox->Execute() == RET_YES ) { bOther = true; if (xProp.is()) { xProp->setIsHyphSpecial( sal_True ); } } else bStop = true; // No hyphenation } if( !bStop ) { SwHyphWrapper aWrap( this, xHyph, bStart, bOther, bSelection ); aWrap.SpellDocument(); m_pWrtShell->EndUndo(UNDO_INSATTR); } pVOpt->SetIdle( bOldIdle ); } } bool SwView::IsValidSelectionForThesaurus() const { // must not be a multi-selection, and if it is a selection it needs // to be within a single paragraph const bool bMultiSel = m_pWrtShell->GetCrsr()->IsMultiSelection(); const bool bSelection = static_cast<SwCrsrShell*>(m_pWrtShell)->HasSelection(); return !bMultiSel && (!bSelection || m_pWrtShell->IsSelOnePara() ); } OUString SwView::GetThesaurusLookUpText( bool bSelection ) const { return bSelection ? OUString(m_pWrtShell->GetSelText()) : m_pWrtShell->GetCurWord(); } void SwView::InsertThesaurusSynonym( const OUString &rSynonmText, const OUString &rLookUpText, bool bSelection ) { bool bOldIns = m_pWrtShell->IsInsMode(); m_pWrtShell->SetInsMode( true ); m_pWrtShell->StartAllAction(); m_pWrtShell->StartUndo(UNDO_DELETE); if( !bSelection ) { if(m_pWrtShell->IsEndWrd()) m_pWrtShell->Left(CRSR_SKIP_CELLS, false, 1, false ); m_pWrtShell->SelWrd(); // make sure the selection build later from the data below does not // include "in word" character to the left and right in order to // preserve those. Therefore count those "in words" in order to modify // the selection accordingly. const sal_Unicode* pChar = rLookUpText.getStr(); sal_Int32 nLeft = 0; while (pChar && *pChar++ == CH_TXTATR_INWORD) ++nLeft; pChar = rLookUpText.getLength() ? rLookUpText.getStr() + rLookUpText.getLength() - 1 : 0; sal_Int32 nRight = 0; while (pChar && *pChar-- == CH_TXTATR_INWORD) ++nRight; // adjust existing selection SwPaM *pCrsr = m_pWrtShell->GetCrsr(); pCrsr->GetPoint()->nContent -= nRight; pCrsr->GetMark()->nContent += nLeft; } m_pWrtShell->Insert( rSynonmText ); m_pWrtShell->EndUndo(UNDO_DELETE); m_pWrtShell->EndAllAction(); m_pWrtShell->SetInsMode( bOldIns ); } // Start thesaurus void SwView::StartThesaurus() { if (!IsValidSelectionForThesaurus()) return; SfxErrorContext aContext( ERRCTX_SVX_LINGU_THESAURUS, OUString(), m_pEditWin, RID_SVXERRCTX, &DIALOG_MGR() ); // Determine language LanguageType eLang = m_pWrtShell->GetCurLang(); if( LANGUAGE_SYSTEM == eLang ) eLang = GetAppLanguage(); if( eLang == LANGUAGE_DONTKNOW || eLang == LANGUAGE_NONE ) { SpellError( LANGUAGE_NONE ); return; } SwViewOption* pVOpt = const_cast<SwViewOption*>(m_pWrtShell->GetViewOptions()); bool bOldIdle = pVOpt->IsIdle(); pVOpt->SetIdle( false ); // get initial LookUp text const bool bSelection = static_cast<SwCrsrShell*>(m_pWrtShell)->HasSelection(); OUString aTmp = GetThesaurusLookUpText( bSelection ); Reference< XThesaurus > xThes( ::GetThesaurus() ); if ( !xThes.is() || !xThes->hasLocale( LanguageTag::convertToLocale( eLang ) ) ) SpellError( eLang ); else { boost::scoped_ptr<AbstractThesaurusDialog> pDlg; // create dialog { //Scope for SwWait-Object SwWait aWait( *GetDocShell(), true ); // load library with dialog only on demand ... SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create(); pDlg.reset(pFact->CreateThesaurusDialog( &GetEditWin(), xThes, aTmp, eLang )); } if ( pDlg->Execute()== RET_OK ) InsertThesaurusSynonym( pDlg->GetWord(), aTmp, bSelection ); } pVOpt->SetIdle( bOldIdle ); } // Offer online suggestions //!! Start of extra code for context menu modifying extensions struct ExecuteInfo { uno::Reference< frame::XDispatch > xDispatch; util::URL aTargetURL; uno::Sequence< PropertyValue > aArgs; }; class AsyncExecute { public: DECL_STATIC_LINK( AsyncExecute, ExecuteHdl_Impl, ExecuteInfo* ); }; IMPL_STATIC_LINK( AsyncExecute, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo ) { SolarMutexReleaser aReleaser; try { // Asynchronous execution as this can lead to our own destruction! // Framework can recycle our current frame and the layout manager disposes all user interface // elements if a component gets detached from its frame! pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs ); } catch (const Exception&) { } delete pExecuteInfo; return 0; } //!! End of extra code for context menu modifying extensions bool SwView::ExecSpellPopup(const Point& rPt) { bool bRet = false; const SwViewOption* pVOpt = m_pWrtShell->GetViewOptions(); if( pVOpt->IsOnlineSpell() && !m_pWrtShell->IsSelection()) { if (m_pWrtShell->GetSelectionType() & nsSelectionType::SEL_DRW_TXT) bRet = ExecDrwTextSpellPopup(rPt); else if (!m_pWrtShell->IsSelFrmMode()) { const bool bOldViewLock = m_pWrtShell->IsViewLocked(); m_pWrtShell->LockView( true ); m_pWrtShell->Push(); SwRect aToFill; SwCrsrShell *pCrsrShell = static_cast<SwCrsrShell*>(m_pWrtShell); SwPaM *pCrsr = pCrsrShell->GetCrsr(); SwPosition aPoint(*pCrsr->GetPoint()); const SwTextNode *pNode = aPoint.nNode.GetNode().GetTextNode(); // Spell-check in case the idle jobs haven't had a chance to kick in. // This makes it possible to suggest spelling corrections for // wrong words independent of the spell-checking idle job. if (pNode && pNode->IsWrongDirty() && m_pWrtShell->ISA(SwCrsrShell) && !pCrsrShell->IsTableMode() && !pCrsr->HasMark() && !pCrsr->IsMultiSelection()) { SwContentFrm *pFrm = pCrsr->GetContentNode()->getLayoutFrm( pCrsrShell->GetLayout(), &rPt, &aPoint, false); if (pFrm) { SwRect aRepaint(static_cast<SwTextFrm*>(pFrm)->_AutoSpell(nullptr, 0)); if (aRepaint.HasArea()) m_pWrtShell->InvalidateWindows(aRepaint); } } // decide which variant of the context menu to use... // if neither spell checking nor grammar checking provides suggestions use the // default context menu. bool bUseGrammarContext = false; Reference< XSpellAlternatives > xAlt( m_pWrtShell->GetCorrection(&rPt, aToFill) ); ProofreadingResult aGrammarCheckRes; sal_Int32 nErrorInResult = -1; uno::Sequence< OUString > aSuggestions; bool bCorrectionRes = false; if (!xAlt.is() || xAlt->getAlternatives().getLength() == 0) { sal_Int32 nErrorPosInText = -1; bCorrectionRes = m_pWrtShell->GetGrammarCorrection( aGrammarCheckRes, nErrorPosInText, nErrorInResult, aSuggestions, &rPt, aToFill ); OUString aMessageText; if (nErrorInResult >= 0) aMessageText = aGrammarCheckRes.aErrors[ nErrorInResult ].aShortComment; // we like to use the grammar checking context menu if we either get // some suggestions or at least a comment about the error found... bUseGrammarContext = bCorrectionRes && (aSuggestions.getLength() > 0 || !aMessageText.isEmpty()); } // open respective context menu for spell check or grammar errors with correction suggestions... if ((!bUseGrammarContext && xAlt.is()) || (bUseGrammarContext && bCorrectionRes && aGrammarCheckRes.aErrors.getLength() > 0)) { // get paragraph text OUString aParaText; if (pNode) aParaText = pNode->GetText(); // this may include hidden text but that should be Ok else { OSL_FAIL("text node expected but not found" ); } bRet = true; m_pWrtShell->SttSelect(); boost::scoped_ptr< SwSpellPopup > pPopup; if (bUseGrammarContext) { sal_Int32 nPos = aPoint.nContent.GetIndex(); (void) nPos; pPopup.reset(new SwSpellPopup( m_pWrtShell, aGrammarCheckRes, nErrorInResult, aSuggestions, aParaText )); } else pPopup.reset(new SwSpellPopup( m_pWrtShell, xAlt, aParaText )); ui::ContextMenuExecuteEvent aEvent; const Point aPixPos = GetEditWin().LogicToPixel( rPt ); aEvent.SourceWindow = VCLUnoHelper::GetInterface( m_pEditWin ); aEvent.ExecutePosition.X = aPixPos.X(); aEvent.ExecutePosition.Y = aPixPos.Y(); Menu* pMenu = 0; OUString sMenuName = bUseGrammarContext ? OUString("private:resource/GrammarContextMenu") : OUString("private:resource/SpellContextMenu"); if(TryContextMenuInterception( *pPopup, sMenuName, pMenu, aEvent )) { //! happy hacking for context menu modifying extensions of this //! 'custom made' menu... *sigh* (code copied from sfx2 and framework) if ( pMenu ) { const sal_uInt16 nId = static_cast<PopupMenu*>(pMenu)->Execute(m_pEditWin, aPixPos); OUString aCommand = static_cast<PopupMenu*>(pMenu)->GetItemCommand(nId); if (aCommand.isEmpty() ) { if(!ExecuteMenuCommand(dynamic_cast<PopupMenu&>(*pMenu), *GetViewFrame(), nId )) pPopup->Execute(nId); } else { SfxViewFrame *pSfxViewFrame = GetViewFrame(); uno::Reference< frame::XFrame > xFrame; if ( pSfxViewFrame ) xFrame = pSfxViewFrame->GetFrame().GetFrameInterface(); com::sun::star::util::URL aURL; uno::Reference< frame::XDispatchProvider > xDispatchProvider( xFrame, UNO_QUERY ); try { uno::Reference< frame::XDispatch > xDispatch; uno::Reference< util::XURLTransformer > xURLTransformer = util::URLTransformer::create(comphelper::getProcessComponentContext()); aURL.Complete = aCommand; xURLTransformer->parseStrict(aURL); uno::Sequence< beans::PropertyValue > aArgs; xDispatch = xDispatchProvider->queryDispatch( aURL, OUString(), 0 ); if (xDispatch.is()) { // Execute dispatch asynchronously ExecuteInfo* pExecuteInfo = new ExecuteInfo; pExecuteInfo->xDispatch = xDispatch; pExecuteInfo->aTargetURL = aURL; pExecuteInfo->aArgs = aArgs; Application::PostUserEvent( LINK(0, AsyncExecute , ExecuteHdl_Impl), pExecuteInfo ); } } catch (const Exception&) { } } } else { pPopup->Execute( aToFill.SVRect(), m_pEditWin ); } } } m_pWrtShell->Pop( false ); m_pWrtShell->LockView( bOldViewLock ); } } return bRet; } /** Function: ExecSmartTagPopup This function shows the popup menu for smarttag actions. */ bool SwView::ExecSmartTagPopup( const Point& rPt ) { bool bRet = false; const bool bOldViewLock = m_pWrtShell->IsViewLocked(); m_pWrtShell->LockView( true ); m_pWrtShell->Push(); // get word that was clicked on // This data structure maps a smart tag type string to the property bag SwRect aToFill; Sequence< OUString > aSmartTagTypes; Sequence< Reference< container::XStringKeyMap > > aStringKeyMaps; Reference<text::XTextRange> xRange; m_pWrtShell->GetSmartTagTerm( rPt, aToFill, aSmartTagTypes, aStringKeyMaps, xRange); if ( xRange.is() && aSmartTagTypes.getLength() ) { bRet = true; m_pWrtShell->SttSelect(); SwSmartTagPopup aPopup( this, aSmartTagTypes, aStringKeyMaps, xRange ); aPopup.Execute( aToFill.SVRect(), m_pEditWin ); } m_pWrtShell->Pop( false ); m_pWrtShell->LockView( bOldViewLock ); return bRet; } class SwFieldDialog : public FloatingWindow { private: VclPtr<ListBox> aListBox; IFieldmark *pFieldmark; DECL_LINK( MyListBoxHandler, ListBox * ); public: SwFieldDialog( SwEditWin* parent, IFieldmark *fieldBM ); virtual ~SwFieldDialog(); virtual void dispose() SAL_OVERRIDE; }; SwFieldDialog::SwFieldDialog( SwEditWin* parent, IFieldmark *fieldBM ) : FloatingWindow( parent, WB_BORDER | WB_SYSTEMWINDOW ), aListBox(VclPtr<ListBox>::Create(this)), pFieldmark( fieldBM ) { if ( fieldBM != NULL ) { const IFieldmark::parameter_map_t* const pParameters = fieldBM->GetParameters(); OUString sListKey = OUString( ODF_FORMDROPDOWN_LISTENTRY ); IFieldmark::parameter_map_t::const_iterator pListEntries = pParameters->find( sListKey ); if(pListEntries != pParameters->end()) { Sequence< OUString > vListEntries; pListEntries->second >>= vListEntries; for( OUString* pCurrent = vListEntries.getArray(); pCurrent != vListEntries.getArray() + vListEntries.getLength(); ++pCurrent) { aListBox->InsertEntry(*pCurrent); } } // Select the current one OUString sResultKey = OUString( ODF_FORMDROPDOWN_RESULT ); IFieldmark::parameter_map_t::const_iterator pResult = pParameters->find( sResultKey ); if ( pResult != pParameters->end() ) { sal_Int32 nSelection = -1; pResult->second >>= nSelection; aListBox->SelectEntryPos( nSelection ); } } Size lbSize(aListBox->GetOptimalSize()); lbSize.Width()+=50; lbSize.Height()+=20; aListBox->SetSizePixel(lbSize); aListBox->SetSelectHdl( LINK( this, SwFieldDialog, MyListBoxHandler ) ); aListBox->Show(); SetSizePixel( lbSize ); } SwFieldDialog::~SwFieldDialog() { disposeOnce(); } void SwFieldDialog::dispose() { aListBox.disposeAndClear(); FloatingWindow::dispose(); } IMPL_LINK( SwFieldDialog, MyListBoxHandler, ListBox *, pBox ) { short res = 0; if ( !pBox->IsTravelSelect() ) { sal_Int32 selection = pBox->GetSelectEntryPos(); if ( selection >= 0 ) { OUString sKey = OUString( ODF_FORMDROPDOWN_RESULT ); (*pFieldmark->GetParameters())[ sKey ] = makeAny(selection); pFieldmark->Invalidate(); SwView& rView = static_cast<SwEditWin*>( GetParent() )->GetView(); rView.GetDocShell()->SetModified( true ); } EndPopupMode(); res = 1; } return res; } IMPL_LINK_NOARG(SwView, FieldPopupModeEndHdl) { m_pFieldPopup.disposeAndClear(); return 0; } void SwView::ExecFieldPopup( const Point& rPt, IFieldmark *fieldBM ) { const Point aPixPos = GetEditWin().LogicToPixel( rPt ); m_pFieldPopup = VclPtr<SwFieldDialog>::Create( m_pEditWin, fieldBM ); m_pFieldPopup->SetPopupModeEndHdl( LINK( this, SwView, FieldPopupModeEndHdl ) ); Rectangle aRect( m_pEditWin->OutputToScreenPixel( aPixPos ), Size( 0, 0 ) ); m_pFieldPopup->StartPopupMode( aRect, FloatWinPopupFlags::Down|FloatWinPopupFlags::GrabFocus ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/************************************************************************** * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------- // Implementation of the ITS tracker class // It reads AliITSRecPoint clusters and creates AliITStrackMI tracks // and fills with them the ESD // Origin: Marian Ivanov, CERN, Marian.Ivanov@cern.ch // Current support and development: // Andrea Dainese, andrea.dainese@lnl.infn.it // dE/dx analysis by: Boris Batyunya, JINR, Boris.Batiounia@cern.ch // Params moved to AliITSRecoParam by: Andrea Dainese, INFN // Material budget from TGeo by: Ludovic Gaudichet & Andrea Dainese, INFN //------------------------------------------------------------------------- #include <TMatrixD.h> #include <TTree.h> #include <TTreeStream.h> #include <TDatabasePDG.h> #include <TString.h> #include <TRandom.h> #include "AliLog.h" #include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliESDVertex.h" #include "AliV0.h" #include "AliHelix.h" #include "AliITSRecPoint.h" #include "AliITSgeomTGeo.h" #include "AliITSReconstructor.h" #include "AliTrackPointArray.h" #include "AliAlignObj.h" #include "AliITSClusterParam.h" #include "AliCDBManager.h" #include "AliCDBEntry.h" #include "AliITSsegmentation.h" #include "AliITSCalibration.h" #include "AliITSCalibrationSPD.h" #include "AliITSCalibrationSDD.h" #include "AliITSCalibrationSSD.h" #include "AliITSPlaneEff.h" #include "AliITSPlaneEffSPD.h" #include "AliITSPlaneEffSDD.h" #include "AliITSPlaneEffSSD.h" #include "AliITStrackerMI.h" ClassImp(AliITStrackerMI) AliITStrackerMI::AliITSlayer AliITStrackerMI::fgLayers[AliITSgeomTGeo::kNLayers]; // ITS layers AliITStrackerMI::AliITStrackerMI():AliTracker(), fI(0), fBestTrack(), fTrackToFollow(), fTrackHypothesys(), fBestHypothesys(), fOriginal(), fCurrentEsdTrack(), fPass(0), fAfterV0(kFALSE), fLastLayerToTrackTo(0), fCoefficients(0), fEsd(0), fTrackingPhase("Default"), fUseTGeo(3), fNtracks(0), fxOverX0Pipe(-1.), fxTimesRhoPipe(-1.), fxOverX0PipeTrks(0), fxTimesRhoPipeTrks(0), fxOverX0ShieldTrks(0), fxTimesRhoShieldTrks(0), fxOverX0LayerTrks(0), fxTimesRhoLayerTrks(0), fDebugStreamer(0), fITSChannelStatus(0), fDetTypeRec(0), fPlaneEff(0) { //Default constructor Int_t i; for(i=0;i<4;i++) fSPDdetzcentre[i]=0.; for(i=0;i<2;i++) {fxOverX0Shield[i]=-1.;fxTimesRhoShield[i]=-1.;} for(i=0;i<6;i++) {fxOverX0Layer[i]=-1.;fxTimesRhoLayer[i]=-1.;} } //------------------------------------------------------------------------ AliITStrackerMI::AliITStrackerMI(const Char_t *geom) : AliTracker(), fI(AliITSgeomTGeo::GetNLayers()), fBestTrack(), fTrackToFollow(), fTrackHypothesys(), fBestHypothesys(), fOriginal(), fCurrentEsdTrack(), fPass(0), fAfterV0(kFALSE), fLastLayerToTrackTo(AliITSRecoParam::GetLastLayerToTrackTo()), fCoefficients(0), fEsd(0), fTrackingPhase("Default"), fUseTGeo(3), fNtracks(0), fxOverX0Pipe(-1.), fxTimesRhoPipe(-1.), fxOverX0PipeTrks(0), fxTimesRhoPipeTrks(0), fxOverX0ShieldTrks(0), fxTimesRhoShieldTrks(0), fxOverX0LayerTrks(0), fxTimesRhoLayerTrks(0), fDebugStreamer(0), fITSChannelStatus(0), fDetTypeRec(0), fPlaneEff(0) { //-------------------------------------------------------------------- //This is the AliITStrackerMI constructor //-------------------------------------------------------------------- if (geom) { AliWarning("\"geom\" is actually a dummy argument !"); } fCoefficients = 0; fAfterV0 = kFALSE; for (Int_t i=1; i<AliITSgeomTGeo::GetNLayers()+1; i++) { Int_t nlad=AliITSgeomTGeo::GetNLadders(i); Int_t ndet=AliITSgeomTGeo::GetNDetectors(i); Double_t xyz[3], &x=xyz[0], &y=xyz[1], &z=xyz[2]; AliITSgeomTGeo::GetOrigTranslation(i,1,1,xyz); Double_t poff=TMath::ATan2(y,x); Double_t zoff=z; Double_t r=TMath::Sqrt(x*x + y*y); AliITSgeomTGeo::GetOrigTranslation(i,1,2,xyz); r += TMath::Sqrt(x*x + y*y); AliITSgeomTGeo::GetOrigTranslation(i,2,1,xyz); r += TMath::Sqrt(x*x + y*y); AliITSgeomTGeo::GetOrigTranslation(i,2,2,xyz); r += TMath::Sqrt(x*x + y*y); r*=0.25; new (fgLayers+i-1) AliITSlayer(r,poff,zoff,nlad,ndet); for (Int_t j=1; j<nlad+1; j++) { for (Int_t k=1; k<ndet+1; k++) { //Fill this layer with detectors TGeoHMatrix m; AliITSgeomTGeo::GetOrigMatrix(i,j,k,m); const TGeoHMatrix *tm=AliITSgeomTGeo::GetTracking2LocalMatrix(i,j,k); m.Multiply(tm); Double_t txyz[3]={0.}; xyz[0]=0.;xyz[1]=0.;xyz[2]=0.; m.LocalToMaster(txyz,xyz); r=TMath::Sqrt(xyz[0]*xyz[0] + xyz[1]*xyz[1]); Double_t phi=TMath::ATan2(xyz[1],xyz[0]); if (phi<0) phi+=TMath::TwoPi(); else if (phi>=TMath::TwoPi()) phi-=TMath::TwoPi(); AliITSdetector &det=fgLayers[i-1].GetDetector((j-1)*ndet + k-1); new(&det) AliITSdetector(r,phi); // compute the real radius (with misalignment) TGeoHMatrix mmisal(*(AliITSgeomTGeo::GetMatrix(i,j,k))); mmisal.Multiply(tm); xyz[0]=0.;xyz[1]=0.;xyz[2]=0.; mmisal.LocalToMaster(txyz,xyz); Double_t rmisal=TMath::Sqrt(xyz[0]*xyz[0] + xyz[1]*xyz[1]); det.SetRmisal(rmisal); } // end loop on detectors } // end loop on ladders } // end loop on layers fI=AliITSgeomTGeo::GetNLayers(); fPass=0; fConstraint[0]=1; fConstraint[1]=0; Double_t xyzVtx[]={AliITSReconstructor::GetRecoParam()->GetXVdef(), AliITSReconstructor::GetRecoParam()->GetYVdef(), AliITSReconstructor::GetRecoParam()->GetZVdef()}; Double_t ersVtx[]={AliITSReconstructor::GetRecoParam()->GetSigmaXVdef(), AliITSReconstructor::GetRecoParam()->GetSigmaYVdef(), AliITSReconstructor::GetRecoParam()->GetSigmaZVdef()}; SetVertex(xyzVtx,ersVtx); for (Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) fLayersNotToSkip[i]=AliITSRecoParam::GetLayersNotToSkip(i); fLastLayerToTrackTo=AliITSRecoParam::GetLastLayerToTrackTo(); for (Int_t i=0;i<100000;i++){ fBestTrackIndex[i]=0; } // store positions of centre of SPD modules (in z) Double_t tr[3]; AliITSgeomTGeo::GetTranslation(1,1,1,tr); fSPDdetzcentre[0] = tr[2]; AliITSgeomTGeo::GetTranslation(1,1,2,tr); fSPDdetzcentre[1] = tr[2]; AliITSgeomTGeo::GetTranslation(1,1,3,tr); fSPDdetzcentre[2] = tr[2]; AliITSgeomTGeo::GetTranslation(1,1,4,tr); fSPDdetzcentre[3] = tr[2]; fUseTGeo = AliITSReconstructor::GetRecoParam()->GetUseTGeoInTracker(); if(AliITSReconstructor::GetRecoParam()->GetExtendedEtaAcceptance() && fUseTGeo!=1 && fUseTGeo!=3) { AliWarning("fUseTGeo changed to 3 because fExtendedEtaAcceptance is kTRUE"); fUseTGeo = 3; } for(Int_t i=0;i<2;i++) {fxOverX0Shield[i]=-1.;fxTimesRhoShield[i]=-1.;} for(Int_t i=0;i<6;i++) {fxOverX0Layer[i]=-1.;fxTimesRhoLayer[i]=-1.;} fDebugStreamer = new TTreeSRedirector("ITSdebug.root"); // only for plane efficiency evaluation if (AliITSReconstructor::GetRecoParam()->GetComputePlaneEff()) { Int_t iplane=AliITSReconstructor::GetRecoParam()->GetIPlanePlaneEff(); if(AliITSReconstructor::GetRecoParam()->GetLayersToSkip(iplane)) AliWarning(Form("Evaluation of Plane Eff for layer %d will be attempted without removing it from tracker",iplane)); if (iplane<2) fPlaneEff = new AliITSPlaneEffSPD(); else if (iplane<4) fPlaneEff = new AliITSPlaneEffSDD(); else fPlaneEff = new AliITSPlaneEffSSD(); if(AliITSReconstructor::GetRecoParam()->GetReadPlaneEffFromOCDB()) if(!fPlaneEff->ReadFromCDB()) {AliWarning("AliITStrackerMI reading of AliITSPlaneEff from OCDB failed") ;} if(AliITSReconstructor::GetRecoParam()->GetHistoPlaneEff()) fPlaneEff->SetCreateHistos(kTRUE); } } //------------------------------------------------------------------------ AliITStrackerMI::AliITStrackerMI(const AliITStrackerMI &tracker):AliTracker(tracker), fI(tracker.fI), fBestTrack(tracker.fBestTrack), fTrackToFollow(tracker.fTrackToFollow), fTrackHypothesys(tracker.fTrackHypothesys), fBestHypothesys(tracker.fBestHypothesys), fOriginal(tracker.fOriginal), fCurrentEsdTrack(tracker.fCurrentEsdTrack), fPass(tracker.fPass), fAfterV0(tracker.fAfterV0), fLastLayerToTrackTo(tracker.fLastLayerToTrackTo), fCoefficients(tracker.fCoefficients), fEsd(tracker.fEsd), fTrackingPhase(tracker.fTrackingPhase), fUseTGeo(tracker.fUseTGeo), fNtracks(tracker.fNtracks), fxOverX0Pipe(tracker.fxOverX0Pipe), fxTimesRhoPipe(tracker.fxTimesRhoPipe), fxOverX0PipeTrks(0), fxTimesRhoPipeTrks(0), fxOverX0ShieldTrks(0), fxTimesRhoShieldTrks(0), fxOverX0LayerTrks(0), fxTimesRhoLayerTrks(0), fDebugStreamer(tracker.fDebugStreamer), fITSChannelStatus(tracker.fITSChannelStatus), fDetTypeRec(tracker.fDetTypeRec), fPlaneEff(tracker.fPlaneEff) { //Copy constructor Int_t i; for(i=0;i<4;i++) { fSPDdetzcentre[i]=tracker.fSPDdetzcentre[i]; } for(i=0;i<6;i++) { fxOverX0Layer[i]=tracker.fxOverX0Layer[i]; fxTimesRhoLayer[i]=tracker.fxTimesRhoLayer[i]; } for(i=0;i<2;i++) { fxOverX0Shield[i]=tracker.fxOverX0Shield[i]; fxTimesRhoShield[i]=tracker.fxTimesRhoShield[i]; } } //------------------------------------------------------------------------ AliITStrackerMI & AliITStrackerMI::operator=(const AliITStrackerMI &tracker){ //Assignment operator this->~AliITStrackerMI(); new(this) AliITStrackerMI(tracker); return *this; } //------------------------------------------------------------------------ AliITStrackerMI::~AliITStrackerMI() { // //destructor // if (fCoefficients) delete [] fCoefficients; DeleteTrksMaterialLUT(); if (fDebugStreamer) { //fDebugStreamer->Close(); delete fDebugStreamer; } if(fITSChannelStatus) delete fITSChannelStatus; if(fPlaneEff) delete fPlaneEff; } //------------------------------------------------------------------------ void AliITStrackerMI::SetLayersNotToSkip(Int_t *l) { //-------------------------------------------------------------------- //This function set masks of the layers which must be not skipped //-------------------------------------------------------------------- for (Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) fLayersNotToSkip[i]=l[i]; } //------------------------------------------------------------------------ void AliITStrackerMI::ReadBadFromDetTypeRec() { //-------------------------------------------------------------------- //This function read ITS bad detectors, chips, channels from AliITSDetTypeRec //i.e. from OCDB //-------------------------------------------------------------------- if(!AliITSReconstructor::GetRecoParam()->GetUseBadZonesFromOCDB()) return; Info("ReadBadFromDetTypeRec","Reading info about bad ITS detectors and channels"); if(!fDetTypeRec) Error("ReadBadFromDetTypeRec","AliITSDetTypeRec nof found!\n"); // ITS channels map if(fITSChannelStatus) delete fITSChannelStatus; fITSChannelStatus = new AliITSChannelStatus(fDetTypeRec); // ITS detectors and chips Int_t i=0,j=0,k=0,ndet=0; for (i=1; i<AliITSgeomTGeo::GetNLayers()+1; i++) { Int_t nBadDetsPerLayer=0; ndet=AliITSgeomTGeo::GetNDetectors(i); for (j=1; j<AliITSgeomTGeo::GetNLadders(i)+1; j++) { for (k=1; k<ndet+1; k++) { AliITSdetector &det=fgLayers[i-1].GetDetector((j-1)*ndet + k-1); det.ReadBadDetectorAndChips(i-1,(j-1)*ndet + k-1,fDetTypeRec); if(det.IsBad()) {nBadDetsPerLayer++;} } // end loop on detectors } // end loop on ladders Info("ReadBadFromDetTypeRec",Form("Layer %d: %d bad out of %d",i-1,nBadDetsPerLayer,ndet*AliITSgeomTGeo::GetNLadders(i))); } // end loop on layers return; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::LoadClusters(TTree *cTree) { //-------------------------------------------------------------------- //This function loads ITS clusters //-------------------------------------------------------------------- TBranch *branch=cTree->GetBranch("ITSRecPoints"); if (!branch) { Error("LoadClusters"," can't get the branch !\n"); return 1; } static TClonesArray dummy("AliITSRecPoint",10000), *clusters=&dummy; branch->SetAddress(&clusters); Int_t i=0,j=0,ndet=0; Int_t detector=0; for (i=0; i<AliITSgeomTGeo::GetNLayers(); i++) { ndet=fgLayers[i].GetNdetectors(); Int_t jmax = j + fgLayers[i].GetNladders()*ndet; for (; j<jmax; j++) { if (!cTree->GetEvent(j)) continue; Int_t ncl=clusters->GetEntriesFast(); SignDeltas(clusters,GetZ()); while (ncl--) { AliITSRecPoint *c=(AliITSRecPoint*)clusters->UncheckedAt(ncl); detector=c->GetDetectorIndex(); if (!c->Misalign()) AliWarning("Can't misalign this cluster !"); fgLayers[i].InsertCluster(new AliITSRecPoint(*c)); } clusters->Delete(); // add dead zone "virtual" cluster in SPD, if there is a cluster within // zwindow cm from the dead zone if (i<2 && AliITSReconstructor::GetRecoParam()->GetAddVirtualClustersInDeadZone()) { for (Float_t xdead = 0; xdead < AliITSRecoParam::GetSPDdetxlength(); xdead += (i+1.)*AliITSReconstructor::GetRecoParam()->GetXPassDeadZoneHits()) { Int_t lab[4] = {0,0,0,detector}; Int_t info[3] = {0,0,i}; Float_t q = 0.; // this identifies virtual clusters Float_t hit[5] = {xdead, 0., AliITSReconstructor::GetRecoParam()->GetSigmaXDeadZoneHit2(), AliITSReconstructor::GetRecoParam()->GetSigmaZDeadZoneHit2(), q}; Bool_t local = kTRUE; Double_t zwindow = AliITSReconstructor::GetRecoParam()->GetZWindowDeadZone(); hit[1] = fSPDdetzcentre[0]+0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); hit[1] = fSPDdetzcentre[1]-0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); hit[1] = fSPDdetzcentre[1]+0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); hit[1] = fSPDdetzcentre[2]-0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); hit[1] = fSPDdetzcentre[2]+0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); hit[1] = fSPDdetzcentre[3]-0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); } } // "virtual" clusters in SPD } // fgLayers[i].ResetRoad(); //road defined by the cluster density fgLayers[i].SortClusters(); } dummy.Clear(); return 0; } //------------------------------------------------------------------------ void AliITStrackerMI::UnloadClusters() { //-------------------------------------------------------------------- //This function unloads ITS clusters //-------------------------------------------------------------------- for (Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) fgLayers[i].ResetClusters(); } //------------------------------------------------------------------------ void AliITStrackerMI::FillClusterArray(TObjArray* array) const { //-------------------------------------------------------------------- // Publishes all pointers to clusters known to the tracker into the // passed object array. // The ownership is not transfered - the caller is not expected to delete // the clusters. //-------------------------------------------------------------------- for(Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) { for(Int_t icl=0; icl<fgLayers[i].GetNumberOfClusters(); icl++) { AliCluster *cl = (AliCluster*)fgLayers[i].GetCluster(icl); array->AddLast(cl); } } return; } //------------------------------------------------------------------------ static Int_t CorrectForTPCtoITSDeadZoneMaterial(AliITStrackMI *t) { //-------------------------------------------------------------------- // Correction for the material between the TPC and the ITS //-------------------------------------------------------------------- if (t->GetX() > AliITSRecoParam::Getriw()) { // inward direction if (!t->PropagateToTGeo(AliITSRecoParam::Getriw(),1)) return 0;// TPC inner wall if (!t->PropagateToTGeo(AliITSRecoParam::Getrcd(),1)) return 0;// TPC central drum if (!t->PropagateToTGeo(AliITSRecoParam::Getrs(),1)) return 0;// ITS screen } else if (t->GetX() < AliITSRecoParam::Getrs()) { // outward direction if (!t->PropagateToTGeo(AliITSRecoParam::Getrs(),1)) return 0;// ITS screen if (!t->PropagateToTGeo(AliITSRecoParam::Getrcd(),1)) return 0;// TPC central drum if (!t->PropagateToTGeo(AliITSRecoParam::Getriw()+0.001,1)) return 0;// TPC inner wall } else { Error("CorrectForTPCtoITSDeadZoneMaterial","Track is already in the dead zone !"); return 0; } return 1; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::Clusters2Tracks(AliESDEvent *event) { //-------------------------------------------------------------------- // This functions reconstructs ITS tracks // The clusters must be already loaded ! //-------------------------------------------------------------------- fTrackingPhase="Clusters2Tracks"; TObjArray itsTracks(15000); fOriginal.Clear(); fEsd = event; // store pointer to the esd // temporary (for cosmics) if(event->GetVertex()) { TString title = event->GetVertex()->GetTitle(); if(title.Contains("cosmics")) { Double_t xyz[3]={GetX(),GetY(),GetZ()}; Double_t exyz[3]={0.1,0.1,0.1}; SetVertex(xyz,exyz); } } // temporary {/* Read ESD tracks */ Double_t pimass = TDatabasePDG::Instance()->GetParticle(211)->Mass(); Int_t nentr=event->GetNumberOfTracks(); Info("Clusters2Tracks", "Number of ESD tracks: %d\n", nentr); while (nentr--) { AliESDtrack *esd=event->GetTrack(nentr); // ---- for debugging: //if(TMath::Abs(esd->GetX()-83.65)<0.1) { FILE *f=fopen("tpc.dat","a"); fprintf(f,"%f %f %f %f %f %f\n",(Float_t)event->GetEventNumberInFile(),(Float_t)TMath::Abs(esd->GetLabel()),(Float_t)esd->GetX(),(Float_t)esd->GetY(),(Float_t)esd->GetZ(),(Float_t)esd->Pt()); fclose(f); } if ((esd->GetStatus()&AliESDtrack::kTPCin)==0) continue; if (esd->GetStatus()&AliESDtrack::kTPCout) continue; if (esd->GetStatus()&AliESDtrack::kITSin) continue; if (esd->GetKinkIndex(0)>0) continue; //kink daughter AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("Clusters2Tracks",msg); delete t; continue; } t->GetDZ(GetX(),GetY(),GetZ(),t->GetDP()); //I.B. Double_t vdist = TMath::Sqrt(t->GetD(0)*t->GetD(0)+t->GetD(1)*t->GetD(1)); // look at the ESD mass hypothesys ! if (t->GetMass()<0.9*pimass) t->SetMass(pimass); // write expected q t->SetExpQ(TMath::Max(0.8*t->GetESDtrack()->GetTPCsignal(),30.)); if (esd->GetV0Index(0)>0 && t->GetD(0)<AliITSReconstructor::GetRecoParam()->GetMaxDforV0dghtrForProlongation()){ //track - can be V0 according to TPC } else { if (TMath::Abs(t->GetD(0))>AliITSReconstructor::GetRecoParam()->GetMaxDForProlongation()) { delete t; continue; } if (TMath::Abs(vdist)>AliITSReconstructor::GetRecoParam()->GetMaxDZForProlongation()) { delete t; continue; } if (t->Pt()<AliITSReconstructor::GetRecoParam()->GetMinPtForProlongation()) { delete t; continue; } if (!CorrectForTPCtoITSDeadZoneMaterial(t)) { delete t; continue; } } t->SetReconstructed(kFALSE); itsTracks.AddLast(t); fOriginal.AddLast(t); } } /* End Read ESD tracks */ itsTracks.Sort(); fOriginal.Sort(); Int_t nentr=itsTracks.GetEntriesFast(); fTrackHypothesys.Expand(nentr); fBestHypothesys.Expand(nentr); MakeCoefficients(nentr); if(fUseTGeo==3 || fUseTGeo==4) MakeTrksMaterialLUT(event->GetNumberOfTracks()); Int_t ntrk=0; // THE TWO TRACKING PASSES for (fPass=0; fPass<2; fPass++) { Int_t &constraint=fConstraint[fPass]; if (constraint<0) continue; for (fCurrentEsdTrack=0; fCurrentEsdTrack<nentr; fCurrentEsdTrack++) { AliITStrackMI *t=(AliITStrackMI*)itsTracks.UncheckedAt(fCurrentEsdTrack); if (t==0) continue; //this track has been already tracked //cout<<"========== "<<fPass<<" "<<fCurrentEsdTrack<<" =========\n"; if (t->GetReconstructed()&&(t->GetNUsed()<1.5)) continue; //this track was already "succesfully" reconstructed Float_t dz[2]; t->GetDZ(GetX(),GetY(),GetZ(),dz); //I.B. if (fConstraint[fPass]) { if (TMath::Abs(dz[0])>AliITSReconstructor::GetRecoParam()->GetMaxDZToUseConstraint() || TMath::Abs(dz[1])>AliITSReconstructor::GetRecoParam()->GetMaxDZToUseConstraint()) continue; } Int_t tpcLabel=t->GetLabel(); //save the TPC track label AliDebug(2,Form("LABEL %d pass %d",tpcLabel,fPass)); fI = 6; ResetTrackToFollow(*t); ResetBestTrack(); FollowProlongationTree(t,fCurrentEsdTrack,fConstraint[fPass]); SortTrackHypothesys(fCurrentEsdTrack,20,0); //MI change // AliITStrackMI *besttrack = GetBestHypothesys(fCurrentEsdTrack,t,15); if (!besttrack) continue; besttrack->SetLabel(tpcLabel); // besttrack->CookdEdx(); CookdEdx(besttrack); besttrack->SetFakeRatio(1.); CookLabel(besttrack,0.); //For comparison only UpdateESDtrack(besttrack,AliESDtrack::kITSin); if (fConstraint[fPass]&&(!besttrack->IsGoldPrimary())) continue; //to be tracked also without vertex constrain t->SetReconstructed(kTRUE); ntrk++; AliDebug(2,Form("TRACK! (label %d) ncls %d",besttrack->GetLabel(),besttrack->GetNumberOfClusters())); } GetBestHypothesysMIP(itsTracks); } // end loop on the two tracking passes if(event->GetNumberOfV0s()>0) UpdateTPCV0(event); if(AliITSReconstructor::GetRecoParam()->GetFindV0s()) FindV02(event); fAfterV0 = kTRUE; // itsTracks.Delete(); // Int_t entries = fTrackHypothesys.GetEntriesFast(); for (Int_t ientry=0; ientry<entries; ientry++) { TObjArray * array =(TObjArray*)fTrackHypothesys.UncheckedAt(ientry); if (array) array->Delete(); delete fTrackHypothesys.RemoveAt(ientry); } fTrackHypothesys.Delete(); fBestHypothesys.Delete(); fOriginal.Clear(); delete [] fCoefficients; fCoefficients=0; DeleteTrksMaterialLUT(); Info("Clusters2Tracks","Number of prolonged tracks: %d\n",ntrk); fTrackingPhase="Default"; return 0; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::PropagateBack(AliESDEvent *event) { //-------------------------------------------------------------------- // This functions propagates reconstructed ITS tracks back // The clusters must be loaded ! //-------------------------------------------------------------------- fTrackingPhase="PropagateBack"; Int_t nentr=event->GetNumberOfTracks(); Info("PropagateBack", "Number of ESD tracks: %d\n", nentr); Int_t ntrk=0; for (Int_t i=0; i<nentr; i++) { AliESDtrack *esd=event->GetTrack(i); if ((esd->GetStatus()&AliESDtrack::kITSin)==0) continue; if (esd->GetStatus()&AliESDtrack::kITSout) continue; AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("PropagateBack",msg); delete t; continue; } t->SetExpQ(TMath::Max(0.8*t->GetESDtrack()->GetTPCsignal(),30.)); ResetTrackToFollow(*t); // propagate to vertex [SR, GSI 17.02.2003] // Start Time measurement [SR, GSI 17.02.2003], corrected by I.Belikov if (CorrectForPipeMaterial(&fTrackToFollow,"inward")) { if (fTrackToFollow.PropagateToVertex(event->GetVertex())) fTrackToFollow.StartTimeIntegral(); // from vertex to outside pipe CorrectForPipeMaterial(&fTrackToFollow,"outward"); } fTrackToFollow.ResetCovariance(10.); fTrackToFollow.ResetClusters(); if (RefitAt(AliITSRecoParam::GetrInsideITSscreen(),&fTrackToFollow,t)) { if (!CorrectForTPCtoITSDeadZoneMaterial(&fTrackToFollow)) { delete t; continue; } fTrackToFollow.SetLabel(t->GetLabel()); //fTrackToFollow.CookdEdx(); CookLabel(&fTrackToFollow,0.); //For comparison only fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSout); //UseClusters(&fTrackToFollow); ntrk++; } delete t; } Info("PropagateBack","Number of back propagated ITS tracks: %d\n",ntrk); fTrackingPhase="Default"; return 0; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::RefitInward(AliESDEvent *event) { //-------------------------------------------------------------------- // This functions refits ITS tracks using the // "inward propagated" TPC tracks // The clusters must be loaded ! //-------------------------------------------------------------------- fTrackingPhase="RefitInward"; if(AliITSReconstructor::GetRecoParam()->GetFindV0s()) RefitV02(event); Int_t nentr=event->GetNumberOfTracks(); Info("RefitInward", "Number of ESD tracks: %d\n", nentr); Int_t ntrk=0; for (Int_t i=0; i<nentr; i++) { AliESDtrack *esd=event->GetTrack(i); if ((esd->GetStatus()&AliESDtrack::kITSout) == 0) continue; if (esd->GetStatus()&AliESDtrack::kITSrefit) continue; if (esd->GetStatus()&AliESDtrack::kTPCout) if ((esd->GetStatus()&AliESDtrack::kTPCrefit)==0) continue; AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("RefitInward",msg); delete t; continue; } t->SetExpQ(TMath::Max(0.8*t->GetESDtrack()->GetTPCsignal(),30.)); if (!CorrectForTPCtoITSDeadZoneMaterial(t)) { delete t; continue; } ResetTrackToFollow(*t); fTrackToFollow.ResetClusters(); if ((esd->GetStatus()&AliESDtrack::kTPCin)==0) fTrackToFollow.ResetCovariance(10.); //Refitting... Bool_t pe=AliITSReconstructor::GetRecoParam()->GetComputePlaneEff(); AliDebug(2,Form("Refit LABEL %d %d",t->GetLabel(),t->GetNumberOfClusters())); if (RefitAt(AliITSRecoParam::GetrInsideSPD1(),&fTrackToFollow,t,kTRUE,pe)) { AliDebug(2," refit OK"); fTrackToFollow.SetLabel(t->GetLabel()); // fTrackToFollow.CookdEdx(); CookdEdx(&fTrackToFollow); CookLabel(&fTrackToFollow,0.0); //For comparison only //The beam pipe if (CorrectForPipeMaterial(&fTrackToFollow,"inward")) { fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSrefit); AliESDtrack *esdTrack =fTrackToFollow.GetESDtrack(); //printf(" %d\n",esdTrack->GetITSModuleIndex(0)); //esdTrack->UpdateTrackParams(&fTrackToFollow,AliESDtrack::kITSrefit); //original line Float_t r[3]={0.,0.,0.}; Double_t maxD=3.; esdTrack->RelateToVertex(event->GetVertex(),GetBz(r),maxD); ntrk++; } } delete t; } Info("RefitInward","Number of refitted tracks: %d\n",ntrk); fTrackingPhase="Default"; return 0; } //------------------------------------------------------------------------ AliCluster *AliITStrackerMI::GetCluster(Int_t index) const { //-------------------------------------------------------------------- // Return pointer to a given cluster //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; return fgLayers[l].GetCluster(c); } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::GetTrackPoint(Int_t index, AliTrackPoint& p) const { //-------------------------------------------------------------------- // Get track space point with index i //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; AliITSRecPoint *cl = fgLayers[l].GetCluster(c); Int_t idet = cl->GetDetectorIndex(); Float_t xyz[3]; Float_t cov[6]; cl->GetGlobalXYZ(xyz); cl->GetGlobalCov(cov); p.SetXYZ(xyz, cov); p.SetCharge(cl->GetQ()); p.SetDriftTime(cl->GetDriftTime()); AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer; switch (l) { case 0: iLayer = AliGeomManager::kSPD1; break; case 1: iLayer = AliGeomManager::kSPD2; break; case 2: iLayer = AliGeomManager::kSDD1; break; case 3: iLayer = AliGeomManager::kSDD2; break; case 4: iLayer = AliGeomManager::kSSD1; break; case 5: iLayer = AliGeomManager::kSSD2; break; default: AliWarning(Form("Wrong layer index in ITS (%d) !",l)); break; }; UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,idet); p.SetVolumeID((UShort_t)volid); return kTRUE; } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::GetTrackPointTrackingError(Int_t index, AliTrackPoint& p, const AliESDtrack *t) { //-------------------------------------------------------------------- // Get track space point with index i // (assign error estimated during the tracking) //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; const AliITSRecPoint *cl = fgLayers[l].GetCluster(c); Int_t idet = cl->GetDetectorIndex(); const AliITSdetector &det=fgLayers[l].GetDetector(idet); // tgphi and tglambda of the track in tracking frame with alpha=det.GetPhi Float_t detxy[2]; detxy[0] = det.GetR()*TMath::Cos(det.GetPhi()); detxy[1] = det.GetR()*TMath::Sin(det.GetPhi()); Double_t alpha = t->GetAlpha(); Double_t xdetintrackframe = detxy[0]*TMath::Cos(alpha)+detxy[1]*TMath::Sin(alpha); Float_t phi = TMath::ASin(t->GetSnpAt(xdetintrackframe,GetBz())); phi += alpha-det.GetPhi(); Float_t tgphi = TMath::Tan(phi); Float_t tgl = t->GetTgl(); // tgl about const along track Float_t expQ = TMath::Max(0.8*t->GetTPCsignal(),30.); Float_t errlocalx,errlocalz; Bool_t addMisalErr=kFALSE; AliITSClusterParam::GetError(l,cl,tgl,tgphi,expQ,errlocalx,errlocalz,addMisalErr); Float_t xyz[3]; Float_t cov[6]; cl->GetGlobalXYZ(xyz); // cl->GetGlobalCov(cov); Float_t pos[3] = {0.,0.,0.}; AliCluster tmpcl((UShort_t)cl->GetVolumeId(),pos[0],pos[1],pos[2],errlocalx*errlocalx,errlocalz*errlocalz,0); tmpcl.GetGlobalCov(cov); p.SetXYZ(xyz, cov); p.SetCharge(cl->GetQ()); p.SetDriftTime(cl->GetDriftTime()); AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer; switch (l) { case 0: iLayer = AliGeomManager::kSPD1; break; case 1: iLayer = AliGeomManager::kSPD2; break; case 2: iLayer = AliGeomManager::kSDD1; break; case 3: iLayer = AliGeomManager::kSDD2; break; case 4: iLayer = AliGeomManager::kSSD1; break; case 5: iLayer = AliGeomManager::kSSD2; break; default: AliWarning(Form("Wrong layer index in ITS (%d) !",l)); break; }; UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,idet); p.SetVolumeID((UShort_t)volid); return kTRUE; } //------------------------------------------------------------------------ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdindex, Bool_t constrain) { //-------------------------------------------------------------------- // Follow prolongation tree //-------------------------------------------------------------------- // Double_t xyzVtx[]={GetX(),GetY(),GetZ()}; Double_t ersVtx[]={GetSigmaX(),GetSigmaY(),GetSigmaZ()}; AliESDtrack * esd = otrack->GetESDtrack(); if (esd->GetV0Index(0)>0) { // TEMPORARY SOLLUTION: map V0 indexes to point to proper track // mapping of ESD track is different as ITS track in Containers // Need something more stable // Indexes are set back again to the ESD track indexes in UpdateTPCV0 for (Int_t i=0;i<3;i++){ Int_t index = esd->GetV0Index(i); if (index==0) break; AliESDv0 * vertex = fEsd->GetV0(index); if (vertex->GetStatus()<0) continue; // rejected V0 // if (esd->GetSign()>0) { vertex->SetIndex(0,esdindex); } else { vertex->SetIndex(1,esdindex); } } } TObjArray *bestarray = (TObjArray*)fBestHypothesys.At(esdindex); if (!bestarray){ bestarray = new TObjArray(5); fBestHypothesys.AddAt(bestarray,esdindex); } // //setup tree of the prolongations // static AliITStrackMI tracks[7][100]; AliITStrackMI *currenttrack; static AliITStrackMI currenttrack1; static AliITStrackMI currenttrack2; static AliITStrackMI backuptrack; Int_t ntracks[7]; Int_t nindexes[7][100]; Float_t normalizedchi2[100]; for (Int_t ilayer=0;ilayer<6;ilayer++) ntracks[ilayer]=0; otrack->SetNSkipped(0); new (&(tracks[6][0])) AliITStrackMI(*otrack); ntracks[6]=1; for (Int_t i=0;i<7;i++) nindexes[i][0]=0; Int_t modstatus = 1; // found Float_t xloc,zloc; // // // follow prolongations for (Int_t ilayer=5; ilayer>=0; ilayer--) { AliDebug(2,Form("FollowProlongationTree: layer %d",ilayer)); fI = ilayer; // AliITSlayer &layer=fgLayers[ilayer]; Double_t r = layer.GetR(); ntracks[ilayer]=0; // // Int_t nskipped=0; Float_t nused =0; for (Int_t itrack =0; itrack<ntracks[ilayer+1]; itrack++) { //set current track if (ntracks[ilayer]>=100) break; if (tracks[ilayer+1][nindexes[ilayer+1][itrack]].GetNSkipped()>0) nskipped++; if (tracks[ilayer+1][nindexes[ilayer+1][itrack]].GetNUsed()>2.) nused++; if (ntracks[ilayer]>15+ilayer){ if (itrack>1&&tracks[ilayer+1][nindexes[ilayer+1][itrack]].GetNSkipped()>0 && nskipped>4+ilayer) continue; if (itrack>1&&tracks[ilayer+1][nindexes[ilayer+1][itrack]].GetNUsed()>2. && nused>3) continue; } new(&currenttrack1) AliITStrackMI(tracks[ilayer+1][nindexes[ilayer+1][itrack]]); // material between SSD and SDD, SDD and SPD if (ilayer==3) if(!CorrectForShieldMaterial(&currenttrack1,"SDD","inward")) continue; if (ilayer==1) if(!CorrectForShieldMaterial(&currenttrack1,"SPD","inward")) continue; // detector number Double_t phi,z; if (!currenttrack1.GetPhiZat(r,phi,z)) continue; Int_t idet=layer.FindDetectorIndex(phi,z); Double_t trackGlobXYZ1[3]; if (!currenttrack1.GetXYZ(trackGlobXYZ1)) continue; // Get the budget to the primary vertex for the current track being prolonged Double_t budgetToPrimVertex = GetEffectiveThickness(); // check if we allow a prolongation without point Int_t skip = CheckSkipLayer(&currenttrack1,ilayer,idet); if (skip) { AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1); // propagate to the layer radius Double_t xToGo; if (!vtrack->GetLocalXat(r,xToGo)) continue; if(!vtrack->Propagate(xToGo)) continue; // apply correction for material of the current layer CorrectForLayerMaterial(vtrack,ilayer,trackGlobXYZ1,"inward"); vtrack->SetNDeadZone(vtrack->GetNDeadZone()+1); vtrack->SetClIndex(ilayer,0); modstatus = (skip==1 ? 3 : 4); // skipped : out in z if(LocalModuleCoord(ilayer,idet,vtrack,xloc,zloc)) { // local module coords vtrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); } if(constrain) vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx); ntracks[ilayer]++; continue; } // track outside layer acceptance in z if (idet<0) continue; //propagate to the intersection with the detector plane const AliITSdetector &det=layer.GetDetector(idet); new(&currenttrack2) AliITStrackMI(currenttrack1); if (!currenttrack1.Propagate(det.GetPhi(),det.GetR())) continue; if (!currenttrack2.Propagate(det.GetPhi(),det.GetR())) continue; currenttrack1.SetDetectorIndex(idet); currenttrack2.SetDetectorIndex(idet); if(!LocalModuleCoord(ilayer,idet,&currenttrack1,xloc,zloc)) continue; // local module coords //*************** // DEFINITION OF SEARCH ROAD AND CLUSTERS SELECTION // // road in global (rphi,z) [i.e. in tracking ref. system] Double_t zmin,zmax,ymin,ymax; if (!ComputeRoad(&currenttrack1,ilayer,idet,zmin,zmax,ymin,ymax)) continue; // select clusters in road layer.SelectClusters(zmin,zmax,ymin,ymax); //******************** // Define criteria for track-cluster association Double_t msz = currenttrack1.GetSigmaZ2() + AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer); Double_t msy = currenttrack1.GetSigmaY2() + AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer); if (constrain) { msz *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadZC(); msy *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadYC(); } else { msz *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadZNonC(); msy *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadYNonC(); } msz = 1./msz; // 1/RoadZ^2 msy = 1./msy; // 1/RoadY^2 // // // LOOP OVER ALL POSSIBLE TRACK PROLONGATIONS ON THIS LAYER // const AliITSRecPoint *cl=0; Int_t clidx=-1; Double_t chi2trkcl=AliITSReconstructor::GetRecoParam()->GetMaxChi2(); // init with big value Bool_t deadzoneSPD=kFALSE; currenttrack = &currenttrack1; // check if the road contains a dead zone Bool_t noClusters = kFALSE; if (!layer.GetNextCluster(clidx,kTRUE)) noClusters=kTRUE; if (noClusters) AliDebug(2,"no clusters in road"); Double_t dz=0.5*(zmax-zmin); Double_t dy=0.5*(ymax-ymin); Int_t dead = CheckDeadZone(&currenttrack1,ilayer,idet,dz,dy,noClusters); if(dead) AliDebug(2,Form("DEAD (%d)\n",dead)); // create a prolongation without clusters (check also if there are no clusters in the road) if (dead || (noClusters && AliITSReconstructor::GetRecoParam()->GetAllowProlongationWithEmptyRoad())) { AliITStrackMI * updatetrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(*currenttrack); updatetrack->SetClIndex(ilayer,0); if (dead==0) { modstatus = 5; // no cls in road } else if (dead==1) { modstatus = 7; // holes in z in SPD } else if (dead==2 || dead==3) { modstatus = 2; // dead from OCDB } updatetrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); // apply correction for material of the current layer CorrectForLayerMaterial(updatetrack,ilayer,trackGlobXYZ1,"inward"); if (constrain) { // apply vertex constrain updatetrack->SetConstrain(constrain); Bool_t isPrim = kTRUE; if (ilayer<4) { // check that it's close to the vertex updatetrack->GetDZ(GetX(),GetY(),GetZ(),updatetrack->GetDP()); //I.B. if (TMath::Abs(updatetrack->GetD(0)/(1.+ilayer)) > // y AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk() || TMath::Abs(updatetrack->GetD(1)/(1.+ilayer)) > // z AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk()) isPrim=kFALSE; } if (isPrim) updatetrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx); } if (dead) { updatetrack->SetNDeadZone(updatetrack->GetNDeadZone()+1); if (dead==1) { // dead zone at z=0,+-7cm in SPD updatetrack->SetDeadZoneProbability(GetSPDDeadZoneProbability(updatetrack->GetZ(),TMath::Sqrt(updatetrack->GetSigmaZ2()))); deadzoneSPD=kTRUE; } } ntracks[ilayer]++; } clidx=-1; // loop over clusters in the road while ((cl=layer.GetNextCluster(clidx))!=0) { if (ntracks[ilayer]>95) break; //space for skipped clusters Bool_t changedet =kFALSE; if (cl->GetQ()==0 && deadzoneSPD==kTRUE) continue; Int_t idetc=cl->GetDetectorIndex(); if (currenttrack->GetDetectorIndex()==idetc) { // track already on the cluster's detector // take into account misalignment (bring track to real detector plane) Double_t xTrOrig = currenttrack->GetX(); if (!currenttrack->Propagate(xTrOrig+cl->GetX())) continue; // a first cut on track-cluster distance if ( (currenttrack->GetZ()-cl->GetZ())*(currenttrack->GetZ()-cl->GetZ())*msz + (currenttrack->GetY()-cl->GetY())*(currenttrack->GetY()-cl->GetY())*msy > 1. ) { // cluster not associated to track AliDebug(2,"not associated"); continue; } // bring track back to ideal detector plane if (!currenttrack->Propagate(xTrOrig)) continue; } else { // have to move track to cluster's detector const AliITSdetector &detc=layer.GetDetector(idetc); // a first cut on track-cluster distance Double_t y; if (!currenttrack2.GetProlongationFast(detc.GetPhi(),detc.GetR()+cl->GetX(),y,z)) continue; if ( (z-cl->GetZ())*(z-cl->GetZ())*msz + (y-cl->GetY())*(y-cl->GetY())*msy > 1. ) continue; // cluster not associated to track // new (&backuptrack) AliITStrackMI(currenttrack2); changedet = kTRUE; currenttrack =&currenttrack2; if (!currenttrack->Propagate(detc.GetPhi(),detc.GetR())) { new (currenttrack) AliITStrackMI(backuptrack); changedet = kFALSE; continue; } currenttrack->SetDetectorIndex(idetc); // Get again the budget to the primary vertex // for the current track being prolonged, if had to change detector //budgetToPrimVertex = GetEffectiveThickness();// not needed at the moment because anyway we take a mean material for this correction } // calculate track-clusters chi2 chi2trkcl = GetPredictedChi2MI(currenttrack,cl,ilayer); // chi2 cut AliDebug(2,Form("chi2 %f max %f",chi2trkcl,AliITSReconstructor::GetRecoParam()->GetMaxChi2s(ilayer))); if (chi2trkcl < AliITSReconstructor::GetRecoParam()->GetMaxChi2s(ilayer)) { if (cl->GetQ()==0) deadzoneSPD=kTRUE; // only 1 prolongation with virtual cluster if (ntracks[ilayer]>=100) continue; AliITStrackMI * updatetrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(*currenttrack); updatetrack->SetClIndex(ilayer,0); if (changedet) new (&currenttrack2) AliITStrackMI(backuptrack); if (cl->GetQ()!=0) { // real cluster if (!UpdateMI(updatetrack,cl,chi2trkcl,(ilayer<<28)+clidx)) { AliDebug(2,"update failed"); continue; } updatetrack->SetSampledEdx(cl->GetQ(),updatetrack->GetNumberOfClusters()-1); //b.b. modstatus = 1; // found } else { // virtual cluster in dead zone updatetrack->SetNDeadZone(updatetrack->GetNDeadZone()+1); updatetrack->SetDeadZoneProbability(GetSPDDeadZoneProbability(updatetrack->GetZ(),TMath::Sqrt(updatetrack->GetSigmaZ2()))); modstatus = 7; // holes in z in SPD } if (changedet) { Float_t xlocnewdet,zlocnewdet; if(LocalModuleCoord(ilayer,idet,updatetrack,xlocnewdet,zlocnewdet)) { // local module coords updatetrack->SetModuleIndexInfo(ilayer,idet,modstatus,xlocnewdet,zlocnewdet); } } else { updatetrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); } if (cl->IsUsed()) updatetrack->IncrementNUsed(); // apply correction for material of the current layer CorrectForLayerMaterial(updatetrack,ilayer,trackGlobXYZ1,"inward"); if (constrain) { // apply vertex constrain updatetrack->SetConstrain(constrain); Bool_t isPrim = kTRUE; if (ilayer<4) { // check that it's close to the vertex updatetrack->GetDZ(GetX(),GetY(),GetZ(),updatetrack->GetDP()); //I.B. if (TMath::Abs(updatetrack->GetD(0)/(1.+ilayer)) > // y AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk() || TMath::Abs(updatetrack->GetD(1)/(1.+ilayer)) > // z AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk()) isPrim=kFALSE; } if (isPrim) updatetrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx); } //apply vertex constrain ntracks[ilayer]++; } // create new hypothesis else { AliDebug(2,"chi2 too large"); } } // loop over possible prolongations // allow one prolongation without clusters if (constrain && itrack<=1 && currenttrack1.GetNSkipped()==0 && deadzoneSPD==kFALSE && ntracks[ilayer]<100) { AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1); // apply correction for material of the current layer CorrectForLayerMaterial(vtrack,ilayer,trackGlobXYZ1,"inward"); vtrack->SetClIndex(ilayer,0); modstatus = 3; // skipped vtrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx); vtrack->IncrementNSkipped(); ntracks[ilayer]++; } // allow one prolongation without clusters for tracks with |tgl|>1.1 if (constrain && itrack==0 && TMath::Abs(currenttrack1.GetTgl())>1.1) { //big theta - for low flux AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1); // apply correction for material of the current layer CorrectForLayerMaterial(vtrack,ilayer,trackGlobXYZ1,"inward"); vtrack->SetClIndex(ilayer,0); modstatus = 3; // skipped vtrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx); vtrack->SetNDeadZone(vtrack->GetNDeadZone()+1); ntracks[ilayer]++; } } // loop over tracks in layer ilayer+1 //loop over track candidates for the current layer // // Int_t accepted=0; Int_t golden=0; for (Int_t itrack=0;itrack<ntracks[ilayer];itrack++){ normalizedchi2[itrack] = NormalizedChi2(&tracks[ilayer][itrack],ilayer); if (normalizedchi2[itrack] < AliITSReconstructor::GetRecoParam()->GetMaxNormChi2ForGolden(ilayer)) golden++; if (ilayer>4) { accepted++; } else { if (constrain) { // constrain if (normalizedchi2[itrack]<AliITSReconstructor::GetRecoParam()->GetMaxNormChi2C(ilayer)+1) accepted++; } else { // !constrain if (normalizedchi2[itrack]<AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonC(ilayer)+1) accepted++; } } } // sort tracks by increasing normalized chi2 TMath::Sort(ntracks[ilayer],normalizedchi2,nindexes[ilayer],kFALSE); ntracks[ilayer] = TMath::Min(accepted,7+2*ilayer); if (ntracks[ilayer]<golden+2+ilayer) ntracks[ilayer]=TMath::Min(golden+2+ilayer,accepted); if (ntracks[ilayer]>90) ntracks[ilayer]=90; } // end loop over layers // // Now select tracks to be kept // Int_t max = constrain ? 20 : 5; // tracks that reach layer 0 (SPD inner) for (Int_t i=0; i<TMath::Min(max,ntracks[0]); i++) { AliITStrackMI & track= tracks[0][nindexes[0][i]]; if (track.GetNumberOfClusters()<2) continue; if (!constrain && track.GetNormChi2(0) > AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonCForHypothesis()) { continue; } AddTrackHypothesys(new AliITStrackMI(track), esdindex); } // tracks that reach layer 1 (SPD outer) for (Int_t i=0;i<TMath::Min(2,ntracks[1]);i++) { AliITStrackMI & track= tracks[1][nindexes[1][i]]; if (track.GetNumberOfClusters()<4) continue; if (!constrain && track.GetNormChi2(1) > AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonCForHypothesis()) continue; if (constrain) track.IncrementNSkipped(); if (!constrain) { track.SetD(0,track.GetD(GetX(),GetY())); track.SetNSkipped(track.GetNSkipped()+4./(4.+8.*TMath::Abs(track.GetD(0)))); if (track.GetNumberOfClusters()+track.GetNDeadZone()+track.GetNSkipped()>6) { track.SetNSkipped(6-track.GetNumberOfClusters()+track.GetNDeadZone()); } } AddTrackHypothesys(new AliITStrackMI(track), esdindex); } // tracks that reach layer 2 (SDD inner), only during non-constrained pass if (!constrain){ for (Int_t i=0;i<TMath::Min(2,ntracks[2]);i++) { AliITStrackMI & track= tracks[2][nindexes[2][i]]; if (track.GetNumberOfClusters()<3) continue; if (!constrain && track.GetNormChi2(2) > AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonCForHypothesis()) continue; if (constrain) track.SetNSkipped(track.GetNSkipped()+2); if (!constrain){ track.SetD(0,track.GetD(GetX(),GetY())); track.SetNSkipped(track.GetNSkipped()+7./(7.+8.*TMath::Abs(track.GetD(0)))); if (track.GetNumberOfClusters()+track.GetNDeadZone()+track.GetNSkipped()>6) { track.SetNSkipped(6-track.GetNumberOfClusters()+track.GetNDeadZone()); } } AddTrackHypothesys(new AliITStrackMI(track), esdindex); } } if (!constrain) { // // register best track of each layer - important for V0 finder // for (Int_t ilayer=0;ilayer<5;ilayer++){ if (ntracks[ilayer]==0) continue; AliITStrackMI & track= tracks[ilayer][nindexes[ilayer][0]]; if (track.GetNumberOfClusters()<1) continue; CookLabel(&track,0); bestarray->AddAt(new AliITStrackMI(track),ilayer); } } // // update TPC V0 information // if (otrack->GetESDtrack()->GetV0Index(0)>0){ Float_t fprimvertex[3]={GetX(),GetY(),GetZ()}; for (Int_t i=0;i<3;i++){ Int_t index = otrack->GetESDtrack()->GetV0Index(i); if (index==0) break; AliV0 *vertex = (AliV0*)fEsd->GetV0(index); if (vertex->GetStatus()<0) continue; // rejected V0 // if (otrack->GetSign()>0) { vertex->SetIndex(0,esdindex); } else{ vertex->SetIndex(1,esdindex); } //find nearest layer with track info Double_t xrp[3]; vertex->GetXYZ(xrp[0],xrp[1],xrp[2]); //I.B. Int_t nearestold = GetNearestLayer(xrp); //I.B. Int_t nearest = nearestold; for (Int_t ilayer =nearest;ilayer<8;ilayer++){ if (ntracks[nearest]==0){ nearest = ilayer; } } // AliITStrackMI & track= tracks[nearest][nindexes[nearest][0]]; if (nearestold<5&&nearest<5){ Bool_t accept = track.GetNormChi2(nearest)<10; if (accept){ if (track.GetSign()>0) { vertex->SetParamP(track); vertex->Update(fprimvertex); //vertex->SetIndex(0,track.fESDtrack->GetID()); if (track.GetNumberOfClusters()>2) AddTrackHypothesys(new AliITStrackMI(track), esdindex); }else{ vertex->SetParamN(track); vertex->Update(fprimvertex); //vertex->SetIndex(1,track.fESDtrack->GetID()); if (track.GetNumberOfClusters()>2) AddTrackHypothesys(new AliITStrackMI(track), esdindex); } vertex->SetStatus(vertex->GetStatus()+1); }else{ //vertex->SetStatus(-2); // reject V0 - not enough clusters } } } } } //------------------------------------------------------------------------ AliITStrackerMI::AliITSlayer & AliITStrackerMI::GetLayer(Int_t layer) const { //-------------------------------------------------------------------- // // return fgLayers[layer]; } //------------------------------------------------------------------------ AliITStrackerMI::AliITSlayer::AliITSlayer(): fR(0), fPhiOffset(0), fNladders(0), fZOffset(0), fNdetectors(0), fDetectors(0), fN(0), fDy5(0), fDy10(0), fDy20(0), fClustersCs(0), fClusterIndexCs(0), fYcs(0), fZcs(0), fNcs(0), fCurrentSlice(-1), fZmax(0), fYmin(0), fYmax(0), fI(0), fImax(0), fSkip(0), fAccepted(0), fRoad(0){ //-------------------------------------------------------------------- //default AliITSlayer constructor //-------------------------------------------------------------------- for (Int_t i=0; i<AliITSRecoParam::GetMaxClusterPerLayer(); i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } } //------------------------------------------------------------------------ AliITStrackerMI::AliITSlayer:: AliITSlayer(Double_t r,Double_t p,Double_t z,Int_t nl,Int_t nd): fR(r), fPhiOffset(p), fNladders(nl), fZOffset(z), fNdetectors(nd), fDetectors(0), fN(0), fDy5(0), fDy10(0), fDy20(0), fClustersCs(0), fClusterIndexCs(0), fYcs(0), fZcs(0), fNcs(0), fCurrentSlice(-1), fZmax(0), fYmin(0), fYmax(0), fI(0), fImax(0), fSkip(0), fAccepted(0), fRoad(0) { //-------------------------------------------------------------------- //main AliITSlayer constructor //-------------------------------------------------------------------- fDetectors=new AliITSdetector[fNladders*fNdetectors]; fRoad=2*fR*TMath::Sqrt(TMath::Pi()/1.);//assuming that there's only one cluster } //------------------------------------------------------------------------ AliITStrackerMI::AliITSlayer::AliITSlayer(const AliITSlayer& layer): fR(layer.fR), fPhiOffset(layer.fPhiOffset), fNladders(layer.fNladders), fZOffset(layer.fZOffset), fNdetectors(layer.fNdetectors), fDetectors(layer.fDetectors), fN(layer.fN), fDy5(layer.fDy5), fDy10(layer.fDy10), fDy20(layer.fDy20), fClustersCs(layer.fClustersCs), fClusterIndexCs(layer.fClusterIndexCs), fYcs(layer.fYcs), fZcs(layer.fZcs), fNcs(layer.fNcs), fCurrentSlice(layer.fCurrentSlice), fZmax(layer.fZmax), fYmin(layer.fYmin), fYmax(layer.fYmax), fI(layer.fI), fImax(layer.fImax), fSkip(layer.fSkip), fAccepted(layer.fAccepted), fRoad(layer.fRoad){ //Copy constructor } //------------------------------------------------------------------------ AliITStrackerMI::AliITSlayer::~AliITSlayer() { //-------------------------------------------------------------------- // AliITSlayer destructor //-------------------------------------------------------------------- delete [] fDetectors; for (Int_t i=0; i<fN; i++) delete fClusters[i]; for (Int_t i=0; i<AliITSRecoParam::GetMaxClusterPerLayer(); i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSlayer::ResetClusters() { //-------------------------------------------------------------------- // This function removes loaded clusters //-------------------------------------------------------------------- for (Int_t i=0; i<fN; i++) delete fClusters[i]; for (Int_t i=0; i<AliITSRecoParam::GetMaxClusterPerLayer(); i++){ fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } fN=0; fI=0; } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSlayer::ResetWeights() { //-------------------------------------------------------------------- // This function reset weights of the clusters //-------------------------------------------------------------------- for (Int_t i=0; i<AliITSRecoParam::GetMaxClusterPerLayer(); i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } for (Int_t i=0; i<fN;i++) { AliITSRecPoint * cl = (AliITSRecPoint*)GetCluster(i); if (cl&&cl->IsUsed()) cl->Use(); } } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSlayer::ResetRoad() { //-------------------------------------------------------------------- // This function calculates the road defined by the cluster density //-------------------------------------------------------------------- Int_t n=0; for (Int_t i=0; i<fN; i++) { if (TMath::Abs(fClusters[i]->GetZ())<fR) n++; } if (n>1) fRoad=2*fR*TMath::Sqrt(TMath::Pi()/n); } //------------------------------------------------------------------------ Int_t AliITStrackerMI::AliITSlayer::InsertCluster(AliITSRecPoint *cl) { //-------------------------------------------------------------------- //This function adds a cluster to this layer //-------------------------------------------------------------------- if (fN==AliITSRecoParam::GetMaxClusterPerLayer()) { ::Error("InsertCluster","Too many clusters !\n"); return 1; } fCurrentSlice=-1; fClusters[fN]=cl; fN++; AliITSdetector &det=GetDetector(cl->GetDetectorIndex()); if (cl->GetY()<det.GetYmin()) det.SetYmin(cl->GetY()); if (cl->GetY()>det.GetYmax()) det.SetYmax(cl->GetY()); if (cl->GetZ()<det.GetZmin()) det.SetZmin(cl->GetZ()); if (cl->GetZ()>det.GetZmax()) det.SetZmax(cl->GetZ()); return 0; } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSlayer::SortClusters() { // //sort clusters // AliITSRecPoint **clusters = new AliITSRecPoint*[fN]; Float_t *z = new Float_t[fN]; Int_t * index = new Int_t[fN]; // for (Int_t i=0;i<fN;i++){ z[i] = fClusters[i]->GetZ(); } TMath::Sort(fN,z,index,kFALSE); for (Int_t i=0;i<fN;i++){ clusters[i] = fClusters[index[i]]; } // for (Int_t i=0;i<fN;i++){ fClusters[i] = clusters[i]; fZ[i] = fClusters[i]->GetZ(); AliITSdetector &det=GetDetector(fClusters[i]->GetDetectorIndex()); Double_t y=fR*det.GetPhi() + fClusters[i]->GetY(); if (y>2.*fR*TMath::Pi()) y -= 2.*fR*TMath::Pi(); fY[i] = y; } delete[] index; delete[] z; delete[] clusters; // fYB[0]=10000000; fYB[1]=-10000000; for (Int_t i=0;i<fN;i++){ if (fY[i]<fYB[0]) fYB[0]=fY[i]; if (fY[i]>fYB[1]) fYB[1]=fY[i]; fClusterIndex[i] = i; } // // fill slices fDy5 = (fYB[1]-fYB[0])/5.; fDy10 = (fYB[1]-fYB[0])/10.; fDy20 = (fYB[1]-fYB[0])/20.; for (Int_t i=0;i<6;i++) fN5[i] =0; for (Int_t i=0;i<11;i++) fN10[i]=0; for (Int_t i=0;i<21;i++) fN20[i]=0; // for (Int_t i=0;i<6;i++) {fBy5[i][0] = fYB[0]+(i-0.75)*fDy5; fBy5[i][1] = fYB[0]+(i+0.75)*fDy5;} for (Int_t i=0;i<11;i++) {fBy10[i][0] = fYB[0]+(i-0.75)*fDy10; fBy10[i][1] = fYB[0]+(i+0.75)*fDy10;} for (Int_t i=0;i<21;i++) {fBy20[i][0] = fYB[0]+(i-0.75)*fDy20; fBy20[i][1] = fYB[0]+(i+0.75)*fDy20;} // // for (Int_t i=0;i<fN;i++) for (Int_t irot=-1;irot<=1;irot++){ Float_t curY = fY[i]+irot*TMath::TwoPi()*fR; // slice 5 for (Int_t slice=0; slice<6;slice++){ if (fBy5[slice][0]<curY && curY<fBy5[slice][1]&&fN5[slice]<AliITSRecoParam::GetMaxClusterPerLayer5()){ fClusters5[slice][fN5[slice]] = fClusters[i]; fY5[slice][fN5[slice]] = curY; fZ5[slice][fN5[slice]] = fZ[i]; fClusterIndex5[slice][fN5[slice]]=i; fN5[slice]++; } } // slice 10 for (Int_t slice=0; slice<11;slice++){ if (fBy10[slice][0]<curY && curY<fBy10[slice][1]&&fN10[slice]<AliITSRecoParam::GetMaxClusterPerLayer10()){ fClusters10[slice][fN10[slice]] = fClusters[i]; fY10[slice][fN10[slice]] = curY; fZ10[slice][fN10[slice]] = fZ[i]; fClusterIndex10[slice][fN10[slice]]=i; fN10[slice]++; } } // slice 20 for (Int_t slice=0; slice<21;slice++){ if (fBy20[slice][0]<curY && curY<fBy20[slice][1]&&fN20[slice]<AliITSRecoParam::GetMaxClusterPerLayer20()){ fClusters20[slice][fN20[slice]] = fClusters[i]; fY20[slice][fN20[slice]] = curY; fZ20[slice][fN20[slice]] = fZ[i]; fClusterIndex20[slice][fN20[slice]]=i; fN20[slice]++; } } } // // consistency check // for (Int_t i=0;i<fN-1;i++){ if (fZ[i]>fZ[i+1]){ printf("Bug\n"); } } // for (Int_t slice=0;slice<21;slice++) for (Int_t i=0;i<fN20[slice]-1;i++){ if (fZ20[slice][i]>fZ20[slice][i+1]){ printf("Bug\n"); } } } //------------------------------------------------------------------------ Int_t AliITStrackerMI::AliITSlayer::FindClusterIndex(Float_t z) const { //-------------------------------------------------------------------- // This function returns the index of the nearest cluster //-------------------------------------------------------------------- Int_t ncl=0; const Float_t *zcl; if (fCurrentSlice<0) { ncl = fN; zcl = fZ; } else{ ncl = fNcs; zcl = fZcs;; } if (ncl==0) return 0; Int_t b=0, e=ncl-1, m=(b+e)/2; for (; b<e; m=(b+e)/2) { // if (z > fClusters[m]->GetZ()) b=m+1; if (z > zcl[m]) b=m+1; else e=m; } return m; } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::ComputeRoad(AliITStrackMI* track,Int_t ilayer,Int_t idet,Double_t &zmin,Double_t &zmax,Double_t &ymin,Double_t &ymax) const { //-------------------------------------------------------------------- // This function computes the rectangular road for this track //-------------------------------------------------------------------- AliITSdetector &det = fgLayers[ilayer].GetDetector(idet); // take into account the misalignment: propagate track to misaligned detector plane if (!track->Propagate(det.GetPhi(),det.GetRmisal())) return kFALSE; Double_t dz=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadZ()* TMath::Sqrt(track->GetSigmaZ2() + AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer)); Double_t dy=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadY()* TMath::Sqrt(track->GetSigmaY2() + AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer)); // track at boundary between detectors, enlarge road Double_t boundaryWidth=AliITSRecoParam::GetBoundaryWidth(); if ( (track->GetY()-dy < det.GetYmin()+boundaryWidth) || (track->GetY()+dy > det.GetYmax()-boundaryWidth) || (track->GetZ()-dz < det.GetZmin()+boundaryWidth) || (track->GetZ()+dz > det.GetZmax()-boundaryWidth) ) { Float_t tgl = TMath::Abs(track->GetTgl()); if (tgl > 1.) tgl=1.; Double_t deltaXNeighbDets=AliITSRecoParam::GetDeltaXNeighbDets(); dz = TMath::Sqrt(dz*dz+deltaXNeighbDets*deltaXNeighbDets*tgl*tgl); Float_t snp = TMath::Abs(track->GetSnp()); if (snp > AliITSReconstructor::GetRecoParam()->GetMaxSnp()) return kFALSE; dy = TMath::Sqrt(dy*dy+deltaXNeighbDets*deltaXNeighbDets*snp*snp); } // boundary // add to the road a term (up to 2-3 mm) to deal with misalignments dy = TMath::Sqrt(dy*dy + AliITSReconstructor::GetRecoParam()->GetRoadMisal()*AliITSReconstructor::GetRecoParam()->GetRoadMisal()); dz = TMath::Sqrt(dz*dz + AliITSReconstructor::GetRecoParam()->GetRoadMisal()*AliITSReconstructor::GetRecoParam()->GetRoadMisal()); Double_t r = fgLayers[ilayer].GetR(); zmin = track->GetZ() - dz; zmax = track->GetZ() + dz; ymin = track->GetY() + r*det.GetPhi() - dy; ymax = track->GetY() + r*det.GetPhi() + dy; // bring track back to idead detector plane if (!track->Propagate(det.GetPhi(),det.GetR())) return kFALSE; return kTRUE; } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSlayer:: SelectClusters(Double_t zmin,Double_t zmax,Double_t ymin, Double_t ymax) { //-------------------------------------------------------------------- // This function sets the "window" //-------------------------------------------------------------------- Double_t circle=2*TMath::Pi()*fR; fYmin = ymin; fYmax =ymax; Float_t ymiddle = (fYmin+fYmax)*0.5; if (ymiddle<fYB[0]) { fYmin+=circle; fYmax+=circle; ymiddle+=circle; } else if (ymiddle>fYB[1]) { fYmin-=circle; fYmax-=circle; ymiddle-=circle; } // fCurrentSlice =-1; // defualt take all fClustersCs = fClusters; fClusterIndexCs = fClusterIndex; fYcs = fY; fZcs = fZ; fNcs = fN; // //is in 20 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy20){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy20); if (slice<0) slice=0; if (slice>20) slice=20; Bool_t isOK = (fYmin>fBy20[slice][0]&&fYmax<fBy20[slice][1]); if (isOK) { fCurrentSlice=slice; fClustersCs = fClusters20[fCurrentSlice]; fClusterIndexCs = fClusterIndex20[fCurrentSlice]; fYcs = fY20[fCurrentSlice]; fZcs = fZ20[fCurrentSlice]; fNcs = fN20[fCurrentSlice]; } } // //is in 10 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy10){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy10); if (slice<0) slice=0; if (slice>10) slice=10; Bool_t isOK = (fYmin>fBy10[slice][0]&&fYmax<fBy10[slice][1]); if (isOK) { fCurrentSlice=slice; fClustersCs = fClusters10[fCurrentSlice]; fClusterIndexCs = fClusterIndex10[fCurrentSlice]; fYcs = fY10[fCurrentSlice]; fZcs = fZ10[fCurrentSlice]; fNcs = fN10[fCurrentSlice]; } } // //is in 5 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy5){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy5); if (slice<0) slice=0; if (slice>5) slice=5; Bool_t isOK = (fYmin>fBy5[slice][0]&&fYmax<fBy5[slice][1]); if (isOK) { fCurrentSlice=slice; fClustersCs = fClusters5[fCurrentSlice]; fClusterIndexCs = fClusterIndex5[fCurrentSlice]; fYcs = fY5[fCurrentSlice]; fZcs = fZ5[fCurrentSlice]; fNcs = fN5[fCurrentSlice]; } } // fI=FindClusterIndex(zmin); fZmax=zmax; fImax = TMath::Min(FindClusterIndex(zmax)+1,fNcs); fSkip = 0; fAccepted =0; return; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::AliITSlayer:: FindDetectorIndex(Double_t phi, Double_t z) const { //-------------------------------------------------------------------- //This function finds the detector crossed by the track //-------------------------------------------------------------------- Double_t dphi; if (fZOffset<0) // old geometry dphi = -(phi-fPhiOffset); else // new geometry dphi = phi-fPhiOffset; if (dphi < 0) dphi += 2*TMath::Pi(); else if (dphi >= 2*TMath::Pi()) dphi -= 2*TMath::Pi(); Int_t np=Int_t(dphi*fNladders*0.5/TMath::Pi()+0.5); if (np>=fNladders) np-=fNladders; if (np<0) np+=fNladders; Double_t dz=fZOffset-z; Double_t nnz = dz*(fNdetectors-1)*0.5/fZOffset+0.5; Int_t nz = (nnz<0 ? -1 : (Int_t)nnz); if (nz>=fNdetectors) return -1; if (nz<0) return -1; // ad hoc correction for 3rd ladder of SDD inner layer, // which is reversed (rotated by pi around local y) // this correction is OK only from AliITSv11Hybrid onwards if (GetR()>12. && GetR()<20.) { // SDD inner if(np==2) { // 3rd ladder nz = (fNdetectors-1) - nz; } } //printf("ndet %d phi %f z %f np %d nz %d\n",fNdetectors,phi,z,np,nz); return np*fNdetectors + nz; } //------------------------------------------------------------------------ const AliITSRecPoint *AliITStrackerMI::AliITSlayer::GetNextCluster(Int_t &ci,Bool_t test) { //-------------------------------------------------------------------- // This function returns clusters within the "window" //-------------------------------------------------------------------- if (fCurrentSlice<0) { Double_t rpi2 = 2.*fR*TMath::Pi(); for (Int_t i=fI; i<fImax; i++) { Double_t y = fY[i]; if (fYmax<y) y -= rpi2; if (fYmin>y) y += rpi2; if (y<fYmin) continue; if (y>fYmax) continue; if (fClusters[i]->GetQ()==0&&fSkip==2) continue; ci=i; if (!test) fI=i+1; return fClusters[i]; } } else { for (Int_t i=fI; i<fImax; i++) { if (fYcs[i]<fYmin) continue; if (fYcs[i]>fYmax) continue; if (fClustersCs[i]->GetQ()==0&&fSkip==2) continue; ci=fClusterIndexCs[i]; if (!test) fI=i+1; return fClustersCs[i]; } } return 0; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::AliITSlayer::GetThickness(Double_t y,Double_t z,Double_t &x0) const { //-------------------------------------------------------------------- // This function returns the layer thickness at this point (units X0) //-------------------------------------------------------------------- Double_t d=0.0085; x0=AliITSRecoParam::GetX0Air(); if (43<fR&&fR<45) { //SSD2 Double_t dd=0.0034; d=dd; if (TMath::Abs(y-0.00)>3.40) d+=dd; if (TMath::Abs(y-1.90)<0.45) {d+=(0.013-0.0034);} if (TMath::Abs(y+1.90)<0.45) {d+=(0.013-0.0034);} for (Int_t i=0; i<12; i++) { if (TMath::Abs(z-3.9*(i+0.5))<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=0.0034; break; } if (TMath::Abs(z+3.9*(i+0.5))<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=0.0034; break; } if (TMath::Abs(z-3.4-3.9*i)<0.50) {d+=(0.016-0.0034); break;} if (TMath::Abs(z+0.5+3.9*i)<0.50) {d+=(0.016-0.0034); break;} } } else if (37<fR&&fR<41) { //SSD1 Double_t dd=0.0034; d=dd; if (TMath::Abs(y-0.00)>3.40) d+=dd; if (TMath::Abs(y-1.90)<0.45) {d+=(0.013-0.0034);} if (TMath::Abs(y+1.90)<0.45) {d+=(0.013-0.0034);} for (Int_t i=0; i<11; i++) { if (TMath::Abs(z-3.9*i)<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=dd; break; } if (TMath::Abs(z+3.9*i)<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=dd; break; } if (TMath::Abs(z-1.85-3.9*i)<0.50) {d+=(0.016-0.0034); break;} if (TMath::Abs(z+2.05+3.9*i)<0.50) {d+=(0.016-0.0034); break;} } } else if (13<fR&&fR<26) { //SDD Double_t dd=0.0033; d=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; if (TMath::Abs(y-1.80)<0.55) { d+=0.016; for (Int_t j=0; j<20; j++) { if (TMath::Abs(z+0.7+1.47*j)<0.12) {d+=0.08; x0=9.; break;} if (TMath::Abs(z-0.7-1.47*j)<0.12) {d+=0.08; x0=9.; break;} } } if (TMath::Abs(y+1.80)<0.55) { d+=0.016; for (Int_t j=0; j<20; j++) { if (TMath::Abs(z-0.7-1.47*j)<0.12) {d+=0.08; x0=9.; break;} if (TMath::Abs(z+0.7+1.47*j)<0.12) {d+=0.08; x0=9.; break;} } } for (Int_t i=0; i<4; i++) { if (TMath::Abs(z-7.3*i)<0.60) { d+=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; break; } if (TMath::Abs(z+7.3*i)<0.60) { d+=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; break; } } } else if (6<fR&&fR<8) { //SPD2 Double_t dd=0.0063; x0=21.5; d=dd; if (TMath::Abs(y-3.08)>0.5) d+=dd; if (TMath::Abs(y-3.03)<0.10) d+=0.014; } else if (3<fR&&fR<5) { //SPD1 Double_t dd=0.0063; x0=21.5; d=dd; if (TMath::Abs(y+0.21)>0.6) d+=dd; if (TMath::Abs(y+0.10)<0.10) d+=0.014; } return d; } //------------------------------------------------------------------------ AliITStrackerMI::AliITSdetector::AliITSdetector(const AliITSdetector& det): fR(det.fR), fRmisal(det.fRmisal), fPhi(det.fPhi), fSinPhi(det.fSinPhi), fCosPhi(det.fCosPhi), fYmin(det.fYmin), fYmax(det.fYmax), fZmin(det.fZmin), fZmax(det.fZmax), fIsBad(det.fIsBad), fNChips(det.fNChips), fChipIsBad(det.fChipIsBad) { //Copy constructor } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSdetector::ReadBadDetectorAndChips(Int_t ilayer,Int_t idet, AliITSDetTypeRec *detTypeRec) { //-------------------------------------------------------------------- // Read bad detectors and chips from calibration objects in AliITSDetTypeRec //-------------------------------------------------------------------- // In AliITSDetTypeRec, detector numbers go from 0 to 2197 // while in the tracker they start from 0 for each layer for(Int_t il=0; il<ilayer; il++) idet += AliITSgeomTGeo::GetNLadders(il+1)*AliITSgeomTGeo::GetNDetectors(il+1); Int_t detType; if (ilayer==0 || ilayer==1) { // ---------- SPD detType = 0; } else if (ilayer==2 || ilayer==3) { // ---------- SDD detType = 1; } else if (ilayer==4 || ilayer==5) { // ---------- SSD detType = 2; } else { printf("AliITStrackerMI::AliITSdetector::InitBadFromOCDB: Wrong layer number %d\n",ilayer); return; } // Get calibration from AliITSDetTypeRec AliITSCalibration *calib = (AliITSCalibration*)detTypeRec->GetCalibrationModel(idet); calib->SetModuleIndex(idet); AliITSCalibration *calibSPDdead = 0; if(detType==0) calibSPDdead = (AliITSCalibration*)detTypeRec->GetSPDDeadModel(idet); // TEMPORARY if (calib->IsBad() || (detType==0 && calibSPDdead->IsBad())) // TEMPORARY { SetBad(); // printf("lay %d bad %d\n",ilayer,idet); } // Get segmentation from AliITSDetTypeRec AliITSsegmentation *segm = (AliITSsegmentation*)detTypeRec->GetSegmentationModel(detType); // Read info about bad chips fNChips = segm->GetMaximumChipIndex()+1; //printf("ilayer %d detType %d idet %d fNChips %d %d GetNumberOfChips %d\n",ilayer,detType,idet,fNChips,segm->GetMaximumChipIndex(),segm->GetNumberOfChips()); if(fChipIsBad) { delete [] fChipIsBad; fChipIsBad=NULL; } fChipIsBad = new Bool_t[fNChips]; for (Int_t iCh=0;iCh<fNChips;iCh++) { fChipIsBad[iCh] = calib->IsChipBad(iCh); if (detType==0 && calibSPDdead->IsChipBad(iCh)) fChipIsBad[iCh] = kTRUE; // TEMPORARY //if(fChipIsBad[iCh]) {printf("lay %d det %d bad chip %d\n",ilayer,idet,iCh);} } return; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetEffectiveThickness() { //-------------------------------------------------------------------- // Returns the thickness between the current layer and the vertex (units X0) //-------------------------------------------------------------------- if(fUseTGeo!=0) { if(fxOverX0Layer[0]<0) BuildMaterialLUT("Layers"); if(fxOverX0Shield[0]<0) BuildMaterialLUT("Shields"); if(fxOverX0Pipe<0) BuildMaterialLUT("Pipe"); } // beam pipe Double_t dPipe = (fUseTGeo==0 ? AliITSRecoParam::GetdPipe() : fxOverX0Pipe); Double_t d=dPipe*AliITSRecoParam::GetrPipe()*AliITSRecoParam::GetrPipe(); // layers Double_t x0=0; Double_t xn=fgLayers[fI].GetR(); for (Int_t i=0; i<fI; i++) { Double_t xi=fgLayers[i].GetR(); Double_t dLayer = (fUseTGeo==0 ? fgLayers[i].GetThickness(0,0,x0) : fxOverX0Layer[i]); d+=dLayer*xi*xi; } // shields if (fI>1) { Double_t dshieldSPD = (fUseTGeo==0 ? AliITSRecoParam::Getdshield(0) : fxOverX0Shield[0]); d+=dshieldSPD*AliITSRecoParam::GetrInsideShield(0)*AliITSRecoParam::GetrInsideShield(0); } if (fI>3) { Double_t dshieldSDD = (fUseTGeo==0 ? AliITSRecoParam::Getdshield(1) : fxOverX0Shield[1]); d+=dshieldSDD*AliITSRecoParam::GetrInsideShield(1)*AliITSRecoParam::GetrInsideShield(1); } return d/(xn*xn); } //------------------------------------------------------------------------ Int_t AliITStrackerMI::AliITSlayer::InRoad() const { //------------------------------------------------------------------- // This function returns number of clusters within the "window" //-------------------------------------------------------------------- Int_t ncl=0; for (Int_t i=fI; i<fN; i++) { const AliITSRecPoint *c=fClusters[i]; if (c->GetZ() > fZmax) break; if (c->IsUsed()) continue; const AliITSdetector &det=GetDetector(c->GetDetectorIndex()); Double_t y=fR*det.GetPhi() + c->GetY(); if (y>2.*fR*TMath::Pi()) y -= 2*fR*TMath::Pi(); if (y>1.*fR*TMath::Pi() && fYmax<y) y -= 2*fR*TMath::Pi(); if (y<fYmin) continue; if (y>fYmax) continue; ncl++; } return ncl; } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *track, const AliITStrackMI *clusters,Bool_t extra, Bool_t planeeff) { //-------------------------------------------------------------------- // This function refits the track "track" at the position "x" using // the clusters from "clusters" // If "extra"==kTRUE, // the clusters from overlapped modules get attached to "track" // If "planeff"==kTRUE, // special approach for plane efficiency evaluation is applyed //-------------------------------------------------------------------- Int_t index[AliITSgeomTGeo::kNLayers]; Int_t k; for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1; Int_t nc=clusters->GetNumberOfClusters(); for (k=0; k<nc; k++) { Int_t idx=clusters->GetClusterIndex(k); Int_t ilayer=(idx&0xf0000000)>>28; index[ilayer]=idx; } return RefitAt(xx,track,index,extra,planeeff); // call the method below } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *track, const Int_t *clusters,Bool_t extra, Bool_t planeeff) { //-------------------------------------------------------------------- // This function refits the track "track" at the position "x" using // the clusters from array // If "extra"==kTRUE, // the clusters from overlapped modules get attached to "track" // If "planeff"==kTRUE, // special approach for plane efficiency evaluation is applyed //-------------------------------------------------------------------- Int_t index[AliITSgeomTGeo::kNLayers]; Int_t k; for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1; // for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) { index[k]=clusters[k]; } // special for cosmics: check which the innermost layer crossed // by the track Int_t innermostlayer=5; Double_t drphi = TMath::Abs(track->GetD(0.,0.)); for(innermostlayer=0; innermostlayer<AliITSgeomTGeo::GetNLayers(); innermostlayer++) { if(drphi < fgLayers[innermostlayer].GetR()) break; } //printf(" drphi %f innermost %d\n",drphi,innermostlayer); Int_t modstatus=1; // found Float_t xloc,zloc; Int_t from, to, step; if (xx > track->GetX()) { from=innermostlayer; to=AliITSgeomTGeo::GetNLayers(); step=+1; } else { from=AliITSgeomTGeo::GetNLayers()-1; to=innermostlayer-1; step=-1; } TString dir = (step>0 ? "outward" : "inward"); for (Int_t ilayer = from; ilayer != to; ilayer += step) { AliITSlayer &layer=fgLayers[ilayer]; Double_t r=layer.GetR(); if (step<0 && xx>r) break; // material between SSD and SDD, SDD and SPD Double_t hI=ilayer-0.5*step; if (TMath::Abs(hI-3.5)<0.01) // SDDouter if(!CorrectForShieldMaterial(track,"SDD",dir)) return kFALSE; if (TMath::Abs(hI-1.5)<0.01) // SPDouter if(!CorrectForShieldMaterial(track,"SPD",dir)) return kFALSE; // remember old position [SR, GSI 18.02.2003] Double_t oldX=0., oldY=0., oldZ=0.; if (track->IsStartedTimeIntegral() && step==1) { if (!track->GetGlobalXYZat(track->GetX(),oldX,oldY,oldZ)) return kFALSE; } // Double_t oldGlobXYZ[3]; if (!track->GetXYZ(oldGlobXYZ)) return kFALSE; //TMath::Sqrt(track->GetSigmaY2()); Double_t phi,z; if (!track->GetPhiZat(r,phi,z)) return kFALSE; Int_t idet=layer.FindDetectorIndex(phi,z); // check if we allow a prolongation without point for large-eta tracks Int_t skip = CheckSkipLayer(track,ilayer,idet); if (skip==2) { // propagate to the layer radius Double_t xToGo; if (!track->GetLocalXat(r,xToGo)) return kFALSE; if (!track->Propagate(xToGo)) return kFALSE; // apply correction for material of the current layer CorrectForLayerMaterial(track,ilayer,oldGlobXYZ,dir); modstatus = 4; // out in z if(LocalModuleCoord(ilayer,idet,track,xloc,zloc)) { // local module coords track->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); } // track time update [SR, GSI 17.02.2003] if (track->IsStartedTimeIntegral() && step==1) { Double_t newX, newY, newZ; if (!track->GetGlobalXYZat(track->GetX(),newX,newY,newZ)) return kFALSE; Double_t dL2 = (oldX-newX)*(oldX-newX) + (oldY-newY)*(oldY-newY) + (oldZ-newZ)*(oldZ-newZ); track->AddTimeStep(TMath::Sqrt(dL2)); } continue; } if (idet<0) return kFALSE; const AliITSdetector &det=layer.GetDetector(idet); if (!track->Propagate(det.GetPhi(),det.GetR())) return kFALSE; track->SetDetectorIndex(idet); if(!LocalModuleCoord(ilayer,idet,track,xloc,zloc)) return kFALSE; // local module coords Double_t dz,zmin,zmax,dy,ymin,ymax; const AliITSRecPoint *clAcc=0; Double_t maxchi2=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2(); Int_t idx=index[ilayer]; if (idx>=0) { // cluster in this layer modstatus = 6; // no refit const AliITSRecPoint *cl=(AliITSRecPoint *)GetCluster(idx); if (cl) { if (idet != cl->GetDetectorIndex()) { idet=cl->GetDetectorIndex(); const AliITSdetector &detc=layer.GetDetector(idet); if (!track->Propagate(detc.GetPhi(),detc.GetR())) return kFALSE; track->SetDetectorIndex(idet); if(!LocalModuleCoord(ilayer,idet,track,xloc,zloc)) return kFALSE; // local module coords } Int_t cllayer = (idx & 0xf0000000) >> 28;; Double_t chi2=GetPredictedChi2MI(track,cl,cllayer); if (chi2<maxchi2) { clAcc=cl; maxchi2=chi2; modstatus = 1; // found } else { return kFALSE; // } } } else { // no cluster in this layer if (skip==1) { modstatus = 3; // skipped // Plane Eff determination: if (planeeff && ilayer==AliITSReconstructor::GetRecoParam()->GetIPlanePlaneEff()) { if (IsOKForPlaneEff(track,clusters,ilayer)) // only adequate track for plane eff. evaluation UseTrackForPlaneEff(track,ilayer); } } else { modstatus = 5; // no cls in road // check dead if (!ComputeRoad(track,ilayer,idet,zmin,zmax,ymin,ymax)) return kFALSE; dz = 0.5*(zmax-zmin); dy = 0.5*(ymax-ymin); Int_t dead = CheckDeadZone(track,ilayer,idet,dz,dy,kTRUE); if (dead==1) modstatus = 7; // holes in z in SPD if (dead==2 || dead==3) modstatus = 2; // dead from OCDB } } if (clAcc) { if (!UpdateMI(track,clAcc,maxchi2,idx)) return kFALSE; track->SetSampledEdx(clAcc->GetQ(),track->GetNumberOfClusters()-1); } track->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); if (extra) { // search for extra clusters in overlapped modules AliITStrackV2 tmp(*track); if (!ComputeRoad(track,ilayer,idet,zmin,zmax,ymin,ymax)) return kFALSE; layer.SelectClusters(zmin,zmax,ymin,ymax); const AliITSRecPoint *clExtra=0; Int_t ci=-1,cci=-1; Int_t idetExtra=-1; maxchi2=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2(); Double_t tolerance=0.1; while ((clExtra=layer.GetNextCluster(ci))!=0) { // only clusters in another module! (overlaps) idetExtra = clExtra->GetDetectorIndex(); if (idet == idetExtra) continue; const AliITSdetector &detx=layer.GetDetector(idetExtra); if (!tmp.Propagate(detx.GetPhi(),detx.GetR()+clExtra->GetX())) continue; if (TMath::Abs(tmp.GetZ() - clExtra->GetZ()) > tolerance) continue; if (TMath::Abs(tmp.GetY() - clExtra->GetY()) > tolerance) continue; if (!tmp.Propagate(detx.GetPhi(),detx.GetR())) continue; Double_t chi2=tmp.GetPredictedChi2(clExtra); if (chi2<maxchi2) { maxchi2=chi2; cci=ci; } } if (cci>=0) { track->SetExtraCluster(ilayer,(ilayer<<28)+cci); track->SetExtraModule(ilayer,idetExtra); } } // end search for extra clusters in overlapped modules // Correct for material of the current layer if(!CorrectForLayerMaterial(track,ilayer,oldGlobXYZ,dir)) return kFALSE; // track time update [SR, GSI 17.02.2003] if (track->IsStartedTimeIntegral() && step==1) { Double_t newX, newY, newZ; if (!track->GetGlobalXYZat(track->GetX(),newX,newY,newZ)) return kFALSE; Double_t dL2 = (oldX-newX)*(oldX-newX) + (oldY-newY)*(oldY-newY) + (oldZ-newZ)*(oldZ-newZ); track->AddTimeStep(TMath::Sqrt(dL2)); } // } // end loop on layers if (!track->Propagate(xx)) return kFALSE; return kTRUE; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetNormalizedChi2(AliITStrackMI * track, Int_t mode) { // // calculate normalized chi2 // return NormalizedChi2(track,0); Float_t chi2 = 0; Float_t sum=0; Float_t *erry = GetErrY(fCurrentEsdTrack), *errz = GetErrZ(fCurrentEsdTrack); // track->fdEdxMismatch=0; Float_t dedxmismatch =0; Float_t *ny = GetNy(fCurrentEsdTrack), *nz = GetNz(fCurrentEsdTrack); if (mode<100){ for (Int_t i = 0;i<6;i++){ if (track->GetClIndex(i)>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->GetSigmaY(i); cerrz = track->GetSigmaZ(i);} cerry*=cerry; cerrz*=cerrz; Float_t cchi2 = (track->GetDy(i)*track->GetDy(i)/cerry)+(track->GetDz(i)*track->GetDz(i)/cerrz); if (i>1 && AliITSReconstructor::GetRecoParam()->GetUseAmplitudeInfo(i)) { Float_t ratio = track->GetNormQ(i)/track->GetExpQ(); if (ratio<0.5) { cchi2+=(0.5-ratio)*10.; //track->fdEdxMismatch+=(0.5-ratio)*10.; dedxmismatch+=(0.5-ratio)*10.; } } if (i<2 ||i>3){ AliITSRecPoint * cl = (AliITSRecPoint*)GetCluster( track->GetClIndex(i)); Double_t delta = cl->GetNy()+cl->GetNz()-ny[i]-nz[i]; if (delta>1) chi2 +=0.5*TMath::Min(delta/2,2.); if (i<2) chi2+=2*cl->GetDeltaProbability(); } chi2+=cchi2; sum++; } } if (TMath::Abs(track->GetdEdxMismatch()-dedxmismatch)>0.0001){ track->SetdEdxMismatch(dedxmismatch); } } else{ for (Int_t i = 0;i<4;i++){ if (track->GetClIndex(i)>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->GetSigmaY(i); cerrz = track->GetSigmaZ(i);} cerry*=cerry; cerrz*=cerrz; chi2+= (track->GetDy(i)*track->GetDy(i)/cerry); chi2+= (track->GetDz(i)*track->GetDz(i)/cerrz); sum++; } } for (Int_t i = 4;i<6;i++){ if (track->GetClIndex(i)>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->GetSigmaY(i); cerrz = track->GetSigmaZ(i);} cerry*=cerry; cerrz*=cerrz; Float_t cerryb, cerrzb; if (ny[i+6]>0) {cerryb = erry[i+6]; cerrzb=errz[i+6];} else { cerryb= track->GetSigmaY(i+6); cerrzb = track->GetSigmaZ(i+6);} cerryb*=cerryb; cerrzb*=cerrzb; chi2+= TMath::Min((track->GetDy(i+6)*track->GetDy(i+6)/cerryb),track->GetDy(i)*track->GetDy(i)/cerry); chi2+= TMath::Min((track->GetDz(i+6)*track->GetDz(i+6)/cerrzb),track->GetDz(i)*track->GetDz(i)/cerrz); sum++; } } } if (track->GetESDtrack()->GetTPCsignal()>85){ Float_t ratio = track->GetdEdx()/track->GetESDtrack()->GetTPCsignal(); if (ratio<0.5) { chi2+=(0.5-ratio)*5.; } if (ratio>2){ chi2+=(ratio-2.0)*3; } } // Double_t match = TMath::Sqrt(track->GetChi22()); if (track->GetConstrain()) match/=track->GetNumberOfClusters(); if (!track->GetConstrain()) { if (track->GetNumberOfClusters()>2) { match/=track->GetNumberOfClusters()-2.; } else { match=0; } } if (match<0) match=0; Float_t deadzonefactor = (track->GetNDeadZone()>0) ? 3*(1.1-track->GetDeadZoneProbability()):0.; Double_t normchi2 = 2*track->GetNSkipped()+match+deadzonefactor+(1+(2*track->GetNSkipped()+deadzonefactor)/track->GetNumberOfClusters())* (chi2)/TMath::Max(double(sum-track->GetNSkipped()), 1./(1.+track->GetNSkipped())); return normchi2; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetMatchingChi2(AliITStrackMI * track1, AliITStrackMI * track2) { // // return matching chi2 between two tracks Double_t largeChi2=1000.; AliITStrackMI track3(*track2); if (!track3.Propagate(track1->GetAlpha(),track1->GetX())) return largeChi2; TMatrixD vec(5,1); vec(0,0)=track1->GetY() - track3.GetY(); vec(1,0)=track1->GetZ() - track3.GetZ(); vec(2,0)=track1->GetSnp() - track3.GetSnp(); vec(3,0)=track1->GetTgl() - track3.GetTgl(); vec(4,0)=track1->GetSigned1Pt() - track3.GetSigned1Pt(); // TMatrixD cov(5,5); cov(0,0) = track1->GetSigmaY2()+track3.GetSigmaY2(); cov(1,1) = track1->GetSigmaZ2()+track3.GetSigmaZ2(); cov(2,2) = track1->GetSigmaSnp2()+track3.GetSigmaSnp2(); cov(3,3) = track1->GetSigmaTgl2()+track3.GetSigmaTgl2(); cov(4,4) = track1->GetSigma1Pt2()+track3.GetSigma1Pt2(); cov(0,1)=cov(1,0) = track1->GetSigmaZY()+track3.GetSigmaZY(); cov(0,2)=cov(2,0) = track1->GetSigmaSnpY()+track3.GetSigmaSnpY(); cov(0,3)=cov(3,0) = track1->GetSigmaTglY()+track3.GetSigmaTglY(); cov(0,4)=cov(4,0) = track1->GetSigma1PtY()+track3.GetSigma1PtY(); // cov(1,2)=cov(2,1) = track1->GetSigmaSnpZ()+track3.GetSigmaSnpZ(); cov(1,3)=cov(3,1) = track1->GetSigmaTglZ()+track3.GetSigmaTglZ(); cov(1,4)=cov(4,1) = track1->GetSigma1PtZ()+track3.GetSigma1PtZ(); // cov(2,3)=cov(3,2) = track1->GetSigmaTglSnp()+track3.GetSigmaTglSnp(); cov(2,4)=cov(4,2) = track1->GetSigma1PtSnp()+track3.GetSigma1PtSnp(); // cov(3,4)=cov(4,3) = track1->GetSigma1PtTgl()+track3.GetSigma1PtTgl(); cov.Invert(); TMatrixD vec2(cov,TMatrixD::kMult,vec); TMatrixD chi2(vec2,TMatrixD::kTransposeMult,vec); return chi2(0,0); } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetSPDDeadZoneProbability(Double_t zpos, Double_t zerr) { // // return probability that given point (characterized by z position and error) // is in SPD dead zone // Double_t probability = 0.; Double_t absz = TMath::Abs(zpos); Double_t nearestz = (absz<2.) ? 0.5*(fSPDdetzcentre[1]+fSPDdetzcentre[2]) : 0.5*(fSPDdetzcentre[2]+fSPDdetzcentre[3]); if (TMath::Abs(absz-nearestz)>0.25+3.*zerr) return probability; Double_t zmin, zmax; if (zpos<-6.) { // dead zone at z = -7 zmin = fSPDdetzcentre[0] + 0.5*AliITSRecoParam::GetSPDdetzlength(); zmax = fSPDdetzcentre[1] - 0.5*AliITSRecoParam::GetSPDdetzlength(); } else if (zpos>6.) { // dead zone at z = +7 zmin = fSPDdetzcentre[2] + 0.5*AliITSRecoParam::GetSPDdetzlength(); zmax = fSPDdetzcentre[3] - 0.5*AliITSRecoParam::GetSPDdetzlength(); } else if (absz<2.) { // dead zone at z = 0 zmin = fSPDdetzcentre[1] + 0.5*AliITSRecoParam::GetSPDdetzlength(); zmax = fSPDdetzcentre[2] - 0.5*AliITSRecoParam::GetSPDdetzlength(); } else { zmin = 0.; zmax = 0.; } // probability that the true z is in the range [zmin,zmax] (i.e. inside // dead zone) probability = 0.5*( TMath::Erf((zpos-zmin)/zerr/TMath::Sqrt(2.)) - TMath::Erf((zpos-zmax)/zerr/TMath::Sqrt(2.)) ); return probability; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetTruncatedChi2(AliITStrackMI * track, Float_t fac) { // // calculate normalized chi2 Float_t chi2[6]; Float_t *erry = GetErrY(fCurrentEsdTrack), *errz = GetErrZ(fCurrentEsdTrack); Float_t ncl = 0; for (Int_t i = 0;i<6;i++){ if (TMath::Abs(track->GetDy(i))>0){ chi2[i]= (track->GetDy(i)/erry[i])*(track->GetDy(i)/erry[i]); chi2[i]+= (track->GetDz(i)/errz[i])*(track->GetDz(i)/errz[i]); ncl++; } else{chi2[i]=10000;} } Int_t index[6]; TMath::Sort(6,chi2,index,kFALSE); Float_t max = float(ncl)*fac-1.; Float_t sumchi=0, sumweight=0; for (Int_t i=0;i<max+1;i++){ Float_t weight = (i<max)?1.:(max+1.-i); sumchi+=weight*chi2[index[i]]; sumweight+=weight; } Double_t normchi2 = sumchi/sumweight; return normchi2; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetInterpolatedChi2(AliITStrackMI * forwardtrack, AliITStrackMI * backtrack) { // // calculate normalized chi2 // if (forwardtrack->fNUsed>0.3*float(forwardtrack->GetNumberOfClusters())) return 10000; Int_t npoints = 0; Double_t res =0; for (Int_t i=0;i<6;i++){ if ( (backtrack->GetSigmaY(i)<0.000000001) || (forwardtrack->GetSigmaY(i)<0.000000001)) continue; Double_t sy1 = forwardtrack->GetSigmaY(i); Double_t sz1 = forwardtrack->GetSigmaZ(i); Double_t sy2 = backtrack->GetSigmaY(i); Double_t sz2 = backtrack->GetSigmaZ(i); if (i<2){ sy2=1000.;sz2=1000;} // Double_t dy0 = (forwardtrack->GetDy(i)/(sy1*sy1) +backtrack->GetDy(i)/(sy2*sy2))/(1./(sy1*sy1)+1./(sy2*sy2)); Double_t dz0 = (forwardtrack->GetDz(i)/(sz1*sz1) +backtrack->GetDz(i)/(sz2*sz2))/(1./(sz1*sz1)+1./(sz2*sz2)); // Double_t nz0 = dz0*TMath::Sqrt((1./(sz1*sz1)+1./(sz2*sz2))); Double_t ny0 = dy0*TMath::Sqrt((1./(sy1*sy1)+1./(sy2*sy2))); // res+= nz0*nz0+ny0*ny0; npoints++; } if (npoints>1) return TMath::Max(0.3*forwardtrack->OneOverPt()-0.5,0.)+ //2*forwardtrack->fNUsed+ res/TMath::Max(double(npoints-forwardtrack->GetNSkipped()), 1./(1.+forwardtrack->GetNSkipped())); return 1000; } //------------------------------------------------------------------------ Float_t *AliITStrackerMI::GetWeight(Int_t index) { //-------------------------------------------------------------------- // Return pointer to a given cluster //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; return fgLayers[l].GetWeight(c); } //------------------------------------------------------------------------ void AliITStrackerMI::RegisterClusterTracks(AliITStrackMI* track,Int_t id) { //--------------------------------------------- // register track to the list // if (track->GetESDtrack()->GetKinkIndex(0)!=0) return; //don't register kink tracks // // for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].GetNumberOfClusters()) continue; for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].GetClusterTracks(itrack,c)<0){ fgLayers[l].SetClusterTracks(itrack,c,id); break; } } } } //------------------------------------------------------------------------ void AliITStrackerMI::UnRegisterClusterTracks(AliITStrackMI* track, Int_t id) { //--------------------------------------------- // unregister track from the list for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].GetNumberOfClusters()) continue; for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].GetClusterTracks(itrack,c)==id){ fgLayers[l].SetClusterTracks(itrack,c,-1); } } } } //------------------------------------------------------------------------ Float_t AliITStrackerMI::GetNumberOfSharedClusters(AliITStrackMI* track,Int_t id, Int_t list[6], AliITSRecPoint *clist[6]) { //------------------------------------------------------------- //get number of shared clusters //------------------------------------------------------------- Float_t shared=0; for (Int_t i=0;i<6;i++) { list[i]=-1, clist[i]=0;} // mean number of clusters Float_t *ny = GetNy(id), *nz = GetNz(id); for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].GetNumberOfClusters()) continue; if (ny[l]==0){ printf("problem\n"); } AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(index); Float_t weight=1; // Float_t deltan = 0; if (l>3&&cl->GetNy()+cl->GetNz()>6) continue; if (l>2&&AliITSReconstructor::GetRecoParam()->GetUseAmplitudeInfo(l)) if (track->GetNormQ(l)/track->GetExpQ()>3.5) continue; if (l<2 || l>3){ deltan = (cl->GetNy()+cl->GetNz()-ny[l]-nz[l]); } else{ deltan = (cl->GetNz()-nz[l]); } if (deltan>2.0) continue; // extended - highly probable shared cluster weight = 2./TMath::Max(3.+deltan,2.); // for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].GetClusterTracks(itrack,c)>=0 && fgLayers[l].GetClusterTracks(itrack,c)!=id){ list[l]=index; clist[l] = (AliITSRecPoint*)GetCluster(index); shared+=weight; break; } } } track->SetNUsed(shared); return shared; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::GetOverlapTrack(AliITStrackMI *track, Int_t trackID, Int_t &shared, Int_t clusterlist[6],Int_t overlist[6]) { // // find first shared track // // mean number of clusters Float_t *ny = GetNy(trackID), *nz = GetNz(trackID); // for (Int_t i=0;i<6;i++) overlist[i]=-1; Int_t sharedtrack=100000; Int_t tracks[24],trackindex=0; for (Int_t i=0;i<24;i++) {tracks[i]=-1;} // for (Int_t icluster=0;icluster<6;icluster++){ if (clusterlist[icluster]<0) continue; Int_t index = clusterlist[icluster]; Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (ny[l]==0){ printf("problem\n"); } if (c>fgLayers[l].GetNumberOfClusters()) continue; //if (l>3) continue; AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(index); // Float_t deltan = 0; if (l>3&&cl->GetNy()+cl->GetNz()>6) continue; if (l>2&&AliITSReconstructor::GetRecoParam()->GetUseAmplitudeInfo(l)) if (track->GetNormQ(l)/track->GetExpQ()>3.5) continue; if (l<2 || l>3){ deltan = (cl->GetNy()+cl->GetNz()-ny[l]-nz[l]); } else{ deltan = (cl->GetNz()-nz[l]); } if (deltan>2.0) continue; // extended - highly probable shared cluster // for (Int_t itrack=3;itrack>=0;itrack--){ if (fgLayers[l].GetClusterTracks(itrack,c)<0) continue; if (fgLayers[l].GetClusterTracks(itrack,c)!=trackID){ tracks[trackindex] = fgLayers[l].GetClusterTracks(itrack,c); trackindex++; } } } if (trackindex==0) return -1; if (trackindex==1){ sharedtrack = tracks[0]; }else{ if (trackindex==2) sharedtrack =TMath::Min(tracks[0],tracks[1]); else{ // Int_t tracks2[24], cluster[24]; for (Int_t i=0;i<trackindex;i++){ tracks2[i]=-1; cluster[i]=0;} Int_t index =0; // for (Int_t i=0;i<trackindex;i++){ if (tracks[i]<0) continue; tracks2[index] = tracks[i]; cluster[index]++; for (Int_t j=i+1;j<trackindex;j++){ if (tracks[j]<0) continue; if (tracks[j]==tracks[i]){ cluster[index]++; tracks[j]=-1; } } index++; } Int_t max=0; for (Int_t i=0;i<index;i++){ if (cluster[index]>max) { sharedtrack=tracks2[index]; max=cluster[index]; } } } } if (sharedtrack>=100000) return -1; // // make list of overlaps shared =0; for (Int_t icluster=0;icluster<6;icluster++){ if (clusterlist[icluster]<0) continue; Int_t index = clusterlist[icluster]; Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].GetNumberOfClusters()) continue; AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(index); if (l==0 || l==1){ if (cl->GetNy()>2) continue; if (cl->GetNz()>2) continue; } if (l==4 || l==5){ if (cl->GetNy()>3) continue; if (cl->GetNz()>3) continue; } // for (Int_t itrack=3;itrack>=0;itrack--){ if (fgLayers[l].GetClusterTracks(itrack,c)<0) continue; if (fgLayers[l].GetClusterTracks(itrack,c)==sharedtrack){ overlist[l]=index; shared++; } } } return sharedtrack; } //------------------------------------------------------------------------ AliITStrackMI * AliITStrackerMI::GetBest2Tracks(Int_t trackID1, Int_t trackID2, Float_t th0, Float_t th1){ // // try to find track hypothesys without conflicts // with minimal chi2; TClonesArray *arr1 = (TClonesArray*)fTrackHypothesys.At(trackID1); Int_t entries1 = arr1->GetEntriesFast(); TClonesArray *arr2 = (TClonesArray*)fTrackHypothesys.At(trackID2); if (!arr2) return (AliITStrackMI*) arr1->UncheckedAt(0); Int_t entries2 = arr2->GetEntriesFast(); if (entries2<=0) return (AliITStrackMI*) arr1->UncheckedAt(0); // AliITStrackMI * track10=(AliITStrackMI*) arr1->UncheckedAt(0); AliITStrackMI * track20=(AliITStrackMI*) arr2->UncheckedAt(0); if (track10->Pt()>0.5+track20->Pt()) return track10; for (Int_t itrack=0;itrack<entries1;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr1->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID1); } // for (Int_t itrack=0;itrack<entries2;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr2->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID2); } Int_t index1=0; Int_t index2=0; Float_t maxconflicts=6; Double_t maxchi2 =1000.; // // get weight of hypothesys - using best hypothesy Double_t w1,w2; Int_t list1[6],list2[6]; AliITSRecPoint *clist1[6], *clist2[6] ; RegisterClusterTracks(track10,trackID1); RegisterClusterTracks(track20,trackID2); Float_t conflict1 = GetNumberOfSharedClusters(track10,trackID1,list1,clist1); Float_t conflict2 = GetNumberOfSharedClusters(track20,trackID2,list2,clist2); UnRegisterClusterTracks(track10,trackID1); UnRegisterClusterTracks(track20,trackID2); // // normalized chi2 Float_t chi21 =0,chi22=0,ncl1=0,ncl2=0; Float_t nerry[6],nerrz[6]; Float_t *erry1=GetErrY(trackID1),*errz1 = GetErrZ(trackID1); Float_t *erry2=GetErrY(trackID2),*errz2 = GetErrZ(trackID2); for (Int_t i=0;i<6;i++){ if ( (erry1[i]>0) && (erry2[i]>0)) { nerry[i] = TMath::Min(erry1[i],erry2[i]); nerrz[i] = TMath::Min(errz1[i],errz2[i]); }else{ nerry[i] = TMath::Max(erry1[i],erry2[i]); nerrz[i] = TMath::Max(errz1[i],errz2[i]); } if (TMath::Abs(track10->GetDy(i))>0.000000000000001){ chi21 += track10->GetDy(i)*track10->GetDy(i)/(nerry[i]*nerry[i]); chi21 += track10->GetDz(i)*track10->GetDz(i)/(nerrz[i]*nerrz[i]); ncl1++; } if (TMath::Abs(track20->GetDy(i))>0.000000000000001){ chi22 += track20->GetDy(i)*track20->GetDy(i)/(nerry[i]*nerry[i]); chi22 += track20->GetDz(i)*track20->GetDz(i)/(nerrz[i]*nerrz[i]); ncl2++; } } chi21/=ncl1; chi22/=ncl2; // // Float_t d1 = TMath::Sqrt(track10->GetD(0)*track10->GetD(0)+track10->GetD(1)*track10->GetD(1))+0.1; Float_t d2 = TMath::Sqrt(track20->GetD(0)*track20->GetD(0)+track20->GetD(1)*track20->GetD(1))+0.1; Float_t s1 = TMath::Sqrt(track10->GetSigmaY2()*track10->GetSigmaZ2()); Float_t s2 = TMath::Sqrt(track20->GetSigmaY2()*track20->GetSigmaZ2()); // w1 = (d2/(d1+d2)+ 2*s2/(s1+s2)+ +s2/(s1+s2)*0.5*(chi22+2.)/(chi21+chi22+4.) +1.*track10->Pt()/(track10->Pt()+track20->Pt()) ); w2 = (d1/(d1+d2)+ 2*s1/(s1+s2)+ s1/(s1+s2)*0.5*(chi21+2.)/(chi21+chi22+4.) +1.*track20->Pt()/(track10->Pt()+track20->Pt()) ); Double_t sumw = w1+w2; w1/=sumw; w2/=sumw; if (w1<w2*0.5) { w1 = (d2+0.5)/(d1+d2+1.); w2 = (d1+0.5)/(d1+d2+1.); } // Float_t maxmax = w1*track10->fChi2MIP[0]+w2*track20->fChi2MIP[0]+w1*conflict1+w2*conflict2+1.; //Float_t maxconflicts0 = w1*conflict1+w2*conflict2; // // get pair of "best" hypothesys // Float_t * ny1 = GetNy(trackID1), * nz1 = GetNz(trackID1); Float_t * ny2 = GetNy(trackID2), * nz2 = GetNz(trackID2); for (Int_t itrack1=0;itrack1<entries1;itrack1++){ AliITStrackMI * track1=(AliITStrackMI*) arr1->UncheckedAt(itrack1); //if (track1->fFakeRatio>0) continue; RegisterClusterTracks(track1,trackID1); for (Int_t itrack2=0;itrack2<entries2;itrack2++){ AliITStrackMI * track2=(AliITStrackMI*) arr2->UncheckedAt(itrack2); // Float_t current = w1*track1->fChi2MIP[0]+w2*track2->fChi2MIP[0]; //if (track2->fFakeRatio>0) continue; Float_t nskipped=0; RegisterClusterTracks(track2,trackID2); Float_t cconflict1 = GetNumberOfSharedClusters(track1,trackID1,list1,clist1); Float_t cconflict2 = GetNumberOfSharedClusters(track2,trackID2,list2,clist2); UnRegisterClusterTracks(track2,trackID2); // if (track1->GetConstrain()) nskipped+=w1*track1->GetNSkipped(); if (track2->GetConstrain()) nskipped+=w2*track2->GetNSkipped(); if (nskipped>0.5) continue; // //if ( w1*conflict1+w2*conflict2>maxconflicts0) continue; if (conflict1+1<cconflict1) continue; if (conflict2+1<cconflict2) continue; Float_t conflict=0; Float_t sumchi2=0; Float_t sum=0; for (Int_t i=0;i<6;i++){ // Float_t c1 =0.; // conflict coeficients Float_t c2 =0.; if (clist1[i]&&clist2[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist1[i]->GetNy()+clist1[i]->GetNz()-TMath::Max(ny1[i],ny2[i])-TMath::Max(nz1[i],nz2[i])); } else{ deltan = (clist1[i]->GetNz()-TMath::Max(nz1[i],nz2[i])); } c1 = 2./TMath::Max(3.+deltan,2.); c2 = 2./TMath::Max(3.+deltan,2.); } else{ if (clist1[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist1[i]->GetNy()+clist1[i]->GetNz()-ny1[i]-nz1[i]); } else{ deltan = (clist1[i]->GetNz()-nz1[i]); } c1 = 2./TMath::Max(3.+deltan,2.); c2 = 0; } if (clist2[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist2[i]->GetNy()+clist2[i]->GetNz()-ny2[i]-nz2[i]); } else{ deltan = (clist2[i]->GetNz()-nz2[i]); } c2 = 2./TMath::Max(3.+deltan,2.); c1 = 0; } } // chi21=0;chi22=0; if (TMath::Abs(track1->GetDy(i))>0.) { chi21 = (track1->GetDy(i)/track1->GetSigmaY(i))*(track1->GetDy(i)/track1->GetSigmaY(i))+ (track1->GetDz(i)/track1->GetSigmaZ(i))*(track1->GetDz(i)/track1->GetSigmaZ(i)); //chi21 = (track1->fDy[i]*track1->fDy[i])/(nerry[i]*nerry[i])+ // (track1->GetDz(i)*track1->GetDz(i))/(nerrz[i]*nerrz[i]); }else{ if (TMath::Abs(track1->GetSigmaY(i)>0.)) c1=1; } // if (TMath::Abs(track2->GetDy(i))>0.) { chi22 = (track2->GetDy(i)/track2->GetSigmaY(i))*(track2->GetDy(i)/track2->GetSigmaY(i))+ (track2->GetDz(i)/track2->GetSigmaZ(i))*(track2->GetDz(i)/track2->GetSigmaZ(i)); //chi22 = (track2->fDy[i]*track2->fDy[i])/(nerry[i]*nerry[i])+ // (track2->fDz[i]*track2->fDz[i])/(nerrz[i]*nerrz[i]); } else{ if (TMath::Abs(track2->GetSigmaY(i)>0.)) c2=1; } sumchi2+=w1*(1.+c1)*(1+c1)*(chi21+c1)+w2*(1.+c2)*(1+c2)*(chi22+c2); if (chi21>0) sum+=w1; if (chi22>0) sum+=w2; conflict+=(c1+c2); } Double_t norm = sum-w1*track1->GetNSkipped()-w2*track2->GetNSkipped(); if (norm<0) norm =1/(w1*track1->GetNSkipped()+w2*track2->GetNSkipped()); Double_t normchi2 = 2*conflict+sumchi2/sum; if ( normchi2 <maxchi2 ){ index1 = itrack1; index2 = itrack2; maxconflicts = conflict; maxchi2 = normchi2; } } UnRegisterClusterTracks(track1,trackID1); } // // if (maxconflicts<4 && maxchi2<th0){ if (maxchi2<th0*2.){ Float_t orig = track10->GetFakeRatio()*track10->GetNumberOfClusters(); AliITStrackMI* track1=(AliITStrackMI*) arr1->UncheckedAt(index1); track1->SetChi2MIP(5,maxconflicts); track1->SetChi2MIP(6,maxchi2); track1->SetChi2MIP(7,0.01+orig-(track1->GetFakeRatio()*track1->GetNumberOfClusters())); // track1->UpdateESDtrack(AliESDtrack::kITSin); track1->SetChi2MIP(8,index1); fBestTrackIndex[trackID1] =index1; UpdateESDtrack(track1, AliESDtrack::kITSin); } else if (track10->GetChi2MIP(0)<th1){ track10->SetChi2MIP(5,maxconflicts); track10->SetChi2MIP(6,maxchi2); // track10->UpdateESDtrack(AliESDtrack::kITSin); UpdateESDtrack(track10,AliESDtrack::kITSin); } for (Int_t itrack=0;itrack<entries1;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr1->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID1); } // for (Int_t itrack=0;itrack<entries2;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr2->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID2); } if (track10->GetConstrain()&&track10->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&track10->GetChi2MIP(1)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1) &&track10->GetChi2MIP(2)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)&&track10->GetChi2MIP(3)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)){ // if (track10->fChi2MIP[0]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&track10->fChi2MIP[1]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1) // &&track10->fChi2MIP[2]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)&&track10->fChi2MIP[3]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)){ RegisterClusterTracks(track10,trackID1); } if (track20->GetConstrain()&&track20->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&track20->GetChi2MIP(1)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1) &&track20->GetChi2MIP(2)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)&&track20->GetChi2MIP(3)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)){ //if (track20->fChi2MIP[0]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&track20->fChi2MIP[1]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1) // &&track20->fChi2MIP[2]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)&&track20->fChi2MIP[3]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)){ RegisterClusterTracks(track20,trackID2); } return track10; } //------------------------------------------------------------------------ void AliITStrackerMI::UseClusters(const AliKalmanTrack *t, Int_t from) const { //-------------------------------------------------------------------- // This function marks clusters assigned to the track //-------------------------------------------------------------------- AliTracker::UseClusters(t,from); AliITSRecPoint *c=(AliITSRecPoint *)GetCluster(t->GetClusterIndex(0)); //if (c->GetQ()>2) c->Use(); if (c->GetSigmaZ2()>0.1) c->Use(); c=(AliITSRecPoint *)GetCluster(t->GetClusterIndex(1)); //if (c->GetQ()>2) c->Use(); if (c->GetSigmaZ2()>0.1) c->Use(); } //------------------------------------------------------------------------ void AliITStrackerMI::AddTrackHypothesys(AliITStrackMI * track, Int_t esdindex) { //------------------------------------------------------------------ // add track to the list of hypothesys //------------------------------------------------------------------ if (esdindex>=fTrackHypothesys.GetEntriesFast()) fTrackHypothesys.Expand(TMath::Max(fTrackHypothesys.GetSize(),esdindex*2+10)); // TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); if (!array) { array = new TObjArray(10); fTrackHypothesys.AddAt(array,esdindex); } array->AddLast(track); } //------------------------------------------------------------------------ void AliITStrackerMI::SortTrackHypothesys(Int_t esdindex, Int_t maxcut, Int_t mode) { //------------------------------------------------------------------- // compress array of track hypothesys // keep only maxsize best hypothesys //------------------------------------------------------------------- if (esdindex>fTrackHypothesys.GetEntriesFast()) return; if (! (fTrackHypothesys.At(esdindex)) ) return; TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); Int_t entries = array->GetEntriesFast(); // //- find preliminary besttrack as a reference Float_t minchi2=10000; Int_t maxn=0; AliITStrackMI * besttrack=0; for (Int_t itrack=0;itrack<array->GetEntriesFast();itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (!track) continue; Float_t chi2 = NormalizedChi2(track,0); // Int_t tpcLabel=track->GetESDtrack()->GetTPCLabel(); track->SetLabel(tpcLabel); CookdEdx(track); track->SetFakeRatio(1.); CookLabel(track,0.); //For comparison only // //if (chi2<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&track->fFakeRatio==0){ if (chi2<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)){ if (track->GetNumberOfClusters()<maxn) continue; maxn = track->GetNumberOfClusters(); if (chi2<minchi2){ minchi2=chi2; besttrack=track; } } else{ if (track->GetConstrain() || track->GetNumberOfClusters()>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } if (!besttrack) return; // // //take errors of best track as a reference Float_t *erry = GetErrY(esdindex), *errz = GetErrZ(esdindex); Float_t *ny = GetNy(esdindex), *nz = GetNz(esdindex); for (Int_t j=0;j<6;j++) { if (besttrack->GetClIndex(j)>0){ erry[j] = besttrack->GetSigmaY(j); erry[j+6] = besttrack->GetSigmaY(j+6); errz[j] = besttrack->GetSigmaZ(j); errz[j+6] = besttrack->GetSigmaZ(j+6); ny[j] = besttrack->GetNy(j); nz[j] = besttrack->GetNz(j); } } // // calculate normalized chi2 // Float_t * chi2 = new Float_t[entries]; Int_t * index = new Int_t[entries]; for (Int_t i=0;i<entries;i++) chi2[i] =10000; for (Int_t itrack=0;itrack<entries;itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (track){ track->SetChi2MIP(0,GetNormalizedChi2(track, mode)); if (track->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)) chi2[itrack] = track->GetChi2MIP(0); else{ if (track->GetConstrain() || track->GetNumberOfClusters()>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } } // TMath::Sort(entries,chi2,index,kFALSE); besttrack = (AliITStrackMI*)array->At(index[0]); if (besttrack&&besttrack->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)){ for (Int_t j=0;j<6;j++){ if (besttrack->GetClIndex(j)>0){ erry[j] = besttrack->GetSigmaY(j); erry[j+6] = besttrack->GetSigmaY(j+6); errz[j] = besttrack->GetSigmaZ(j); erry[j+6] = besttrack->GetSigmaY(j+6); ny[j] = besttrack->GetNy(j); nz[j] = besttrack->GetNz(j); } } } // // calculate one more time with updated normalized errors for (Int_t i=0;i<entries;i++) chi2[i] =10000; for (Int_t itrack=0;itrack<entries;itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (track){ track->SetChi2MIP(0,GetNormalizedChi2(track,mode)); if (track->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)) chi2[itrack] = track->GetChi2MIP(0)-0*(track->GetNumberOfClusters()+track->GetNDeadZone()); else { if (track->GetConstrain() || track->GetNumberOfClusters()>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } } entries = array->GetEntriesFast(); // // if (entries>0){ TObjArray * newarray = new TObjArray(); TMath::Sort(entries,chi2,index,kFALSE); besttrack = (AliITStrackMI*)array->At(index[0]); if (besttrack){ // for (Int_t j=0;j<6;j++){ if (besttrack->GetNz(j)>0&&besttrack->GetNy(j)>0){ erry[j] = besttrack->GetSigmaY(j); erry[j+6] = besttrack->GetSigmaY(j+6); errz[j] = besttrack->GetSigmaZ(j); errz[j+6] = besttrack->GetSigmaZ(j+6); ny[j] = besttrack->GetNy(j); nz[j] = besttrack->GetNz(j); } } besttrack->SetChi2MIP(0,GetNormalizedChi2(besttrack,mode)); minchi2 = TMath::Min(besttrack->GetChi2MIP(0)+5.+besttrack->GetNUsed(), double(AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0))); Float_t minn = besttrack->GetNumberOfClusters()-3; Int_t accepted=0; for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(index[i]); if (!track) continue; if (accepted>maxcut) break; track->SetChi2MIP(0,GetNormalizedChi2(track,mode)); if (track->GetConstrain() || track->GetNumberOfClusters()>5){ //keep best short tracks - without vertex constrain if (track->GetNumberOfClusters()<6 && (track->GetChi2MIP(0)+track->GetNUsed()>minchi2)){ delete array->RemoveAt(index[i]); continue; } } Bool_t shortbest = !track->GetConstrain() && track->GetNumberOfClusters()<6; if ((track->GetChi2MIP(0)+track->GetNUsed()<minchi2 && track->GetNumberOfClusters()>=minn) ||shortbest){ if (!shortbest) accepted++; // newarray->AddLast(array->RemoveAt(index[i])); for (Int_t j=0;j<6;j++){ if (nz[j]==0){ erry[j] = track->GetSigmaY(j); erry[j+6] = track->GetSigmaY(j+6); errz[j] = track->GetSigmaZ(j); errz[j] = track->GetSigmaZ(j+6); ny[j] = track->GetNy(j); nz[j] = track->GetNz(j); } } } else{ delete array->RemoveAt(index[i]); } } array->Delete(); delete fTrackHypothesys.RemoveAt(esdindex); fTrackHypothesys.AddAt(newarray,esdindex); } else{ array->Delete(); delete fTrackHypothesys.RemoveAt(esdindex); } } delete [] chi2; delete [] index; } //------------------------------------------------------------------------ AliITStrackMI * AliITStrackerMI::GetBestHypothesys(Int_t esdindex, AliITStrackMI * original, Int_t checkmax) { //------------------------------------------------------------- // try to find best hypothesy // currently - minimal chi2 of track+backpropagated track+matching to the tpc track //------------------------------------------------------------- if (fTrackHypothesys.GetEntriesFast()<=esdindex) return 0; TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); if (!array) return 0; Int_t entries = array->GetEntriesFast(); if (!entries) return 0; Float_t minchi2 = 100000; AliITStrackMI * besttrack=0; // AliITStrackMI * backtrack = new AliITStrackMI(*original); AliITStrackMI * forwardtrack = new AliITStrackMI(*original); Double_t xyzVtx[]={GetX(),GetY(),GetZ()}; Double_t ersVtx[]={GetSigmaX()/3.,GetSigmaY()/3.,GetSigmaZ()/3.}; // for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; Float_t sigmarfi,sigmaz; GetDCASigma(track,sigmarfi,sigmaz); track->SetDnorm(0,sigmarfi); track->SetDnorm(1,sigmaz); // track->SetChi2MIP(1,1000000); track->SetChi2MIP(2,1000000); track->SetChi2MIP(3,1000000); // // backtrack backtrack = new(backtrack) AliITStrackMI(*track); if (track->GetConstrain()) { if (!CorrectForPipeMaterial(backtrack,"inward")) continue; if (!backtrack->Improve(0,xyzVtx,ersVtx)) continue; backtrack->ResetCovariance(10.); }else{ backtrack->ResetCovariance(10.); } backtrack->ResetClusters(); Double_t x = original->GetX(); if (!RefitAt(x,backtrack,track)) continue; // track->SetChi2MIP(1,NormalizedChi2(backtrack,0)); //for (Int_t i=2;i<6;i++){track->fDy[i]+=backtrack->fDy[i]; track->fDz[i]+=backtrack->fDz[i];} if (track->GetChi2MIP(1)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1)*6.) continue; track->SetChi22(GetMatchingChi2(backtrack,original)); if ((track->GetConstrain()) && track->GetChi22()>90.) continue; if ((!track->GetConstrain()) && track->GetChi22()>30.) continue; if ( track->GetChi22()/track->GetNumberOfClusters()>11.) continue; if (!(track->GetConstrain())&&track->GetChi2MIP(1)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1)) continue; // //forward track - without constraint forwardtrack = new(forwardtrack) AliITStrackMI(*original); forwardtrack->ResetClusters(); x = track->GetX(); RefitAt(x,forwardtrack,track); track->SetChi2MIP(2,NormalizedChi2(forwardtrack,0)); if (track->GetChi2MIP(2)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)*6.0) continue; if (!(track->GetConstrain())&&track->GetChi2MIP(2)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)) continue; //track->fD[0] = forwardtrack->GetD(GetX(),GetY()); //track->fD[1] = forwardtrack->GetZat(GetX())-GetZ(); forwardtrack->GetDZ(GetX(),GetY(),GetZ(),track->GetDP()); //I.B. forwardtrack->SetD(0,track->GetD(0)); forwardtrack->SetD(1,track->GetD(1)); { Int_t list[6]; AliITSRecPoint* clist[6]; track->SetChi2MIP(4,GetNumberOfSharedClusters(track,esdindex,list,clist)); if ( (!track->GetConstrain()) && track->GetChi2MIP(4)>1.0) continue; } track->SetChi2MIP(3,GetInterpolatedChi2(forwardtrack,backtrack)); if ( (track->GetChi2MIP(3)>6.*AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3))) continue; if ( (!track->GetConstrain()) && (track->GetChi2MIP(3)>2*AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3))) { track->SetChi2MIP(3,1000); continue; } Double_t chi2 = track->GetChi2MIP(0)+track->GetNUsed(); // for (Int_t ichi=0;ichi<5;ichi++){ forwardtrack->SetChi2MIP(ichi, track->GetChi2MIP(ichi)); } if (chi2 < minchi2){ //besttrack = new AliITStrackMI(*forwardtrack); besttrack = track; besttrack->SetLabel(track->GetLabel()); besttrack->SetFakeRatio(track->GetFakeRatio()); minchi2 = chi2; //original->fD[0] = forwardtrack->GetD(GetX(),GetY()); //original->fD[1] = forwardtrack->GetZat(GetX())-GetZ(); forwardtrack->GetDZ(GetX(),GetY(),GetZ(),original->GetDP()); //I.B. } } delete backtrack; delete forwardtrack; Int_t accepted=0; for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; if (accepted>checkmax || track->GetChi2MIP(3)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)*6. || (track->GetNumberOfClusters()<besttrack->GetNumberOfClusters()-1.)|| track->GetChi2MIP(0)>besttrack->GetChi2MIP(0)+2.*besttrack->GetNUsed()+3.){ if (track->GetConstrain() || track->GetNumberOfClusters()>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(i); continue; } } else{ accepted++; } } // array->Compress(); SortTrackHypothesys(esdindex,checkmax,1); array = (TObjArray*) fTrackHypothesys.At(esdindex); if (!array) return 0; // PH What can be the reason? Check SortTrackHypothesys besttrack = (AliITStrackMI*)array->At(0); if (!besttrack) return 0; besttrack->SetChi2MIP(8,0); fBestTrackIndex[esdindex]=0; entries = array->GetEntriesFast(); AliITStrackMI *longtrack =0; minchi2 =1000; Float_t minn=besttrack->GetNumberOfClusters()+besttrack->GetNDeadZone(); for (Int_t itrack=entries-1;itrack>0;itrack--) { AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (!track->GetConstrain()) continue; if (track->GetNumberOfClusters()+track->GetNDeadZone()<minn) continue; if (track->GetChi2MIP(0)-besttrack->GetChi2MIP(0)>0.0) continue; if (track->GetChi2MIP(0)>4.) continue; minn = track->GetNumberOfClusters()+track->GetNDeadZone(); longtrack =track; } //if (longtrack) besttrack=longtrack; Int_t list[6]; AliITSRecPoint * clist[6]; Float_t shared = GetNumberOfSharedClusters(besttrack,esdindex,list,clist); if (besttrack->GetConstrain()&&besttrack->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&besttrack->GetChi2MIP(1)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1) &&besttrack->GetChi2MIP(2)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)&&besttrack->GetChi2MIP(3)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)){ RegisterClusterTracks(besttrack,esdindex); } // // if (shared>0.0){ Int_t nshared; Int_t overlist[6]; Int_t sharedtrack = GetOverlapTrack(besttrack, esdindex, nshared, list, overlist); if (sharedtrack>=0){ // besttrack = GetBest2Tracks(esdindex,sharedtrack,10,5.5); if (besttrack){ shared = GetNumberOfSharedClusters(besttrack,esdindex,list,clist); } else return 0; } } if (shared>2.5) return 0; if (shared>1.0) return besttrack; // // Don't sign clusters if not gold track // if (!besttrack->IsGoldPrimary()) return besttrack; if (besttrack->GetESDtrack()->GetKinkIndex(0)!=0) return besttrack; //track belong to kink // if (fConstraint[fPass]){ // // sign clusters // Float_t *ny = GetNy(esdindex), *nz = GetNz(esdindex); for (Int_t i=0;i<6;i++){ Int_t index = besttrack->GetClIndex(i); if (index<=0) continue; Int_t ilayer = (index & 0xf0000000) >> 28; if (besttrack->GetSigmaY(ilayer)<0.00000000001) continue; AliITSRecPoint *c = (AliITSRecPoint*)GetCluster(index); if (!c) continue; if (ilayer>3&&c->GetNy()+c->GetNz()>6) continue; if ( (c->GetNy()+c->GetNz() )> ny[i]+nz[i]+0.7) continue; //shared track if ( c->GetNz()> nz[i]+0.7) continue; //shared track if ( ilayer>2&& AliITSReconstructor::GetRecoParam()->GetUseAmplitudeInfo(ilayer)) if (besttrack->GetNormQ(ilayer)/besttrack->GetExpQ()>1.5) continue; //if ( c->GetNy()> ny[i]+0.7) continue; //shared track Bool_t cansign = kTRUE; for (Int_t itrack=0;itrack<entries; itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; if (track->GetChi2MIP(0)>besttrack->GetChi2MIP(0)+2.*shared+1.) break; if ( (track->GetClIndex(ilayer)>0) && (track->GetClIndex(ilayer)!=besttrack->GetClIndex(ilayer))){ cansign = kFALSE; break; } } if (cansign){ if (TMath::Abs(besttrack->GetDy(ilayer)/besttrack->GetSigmaY(ilayer))>3.) continue; if (TMath::Abs(besttrack->GetDz(ilayer)/besttrack->GetSigmaZ(ilayer))>3.) continue; if (!c->IsUsed()) c->Use(); } } } return besttrack; } //------------------------------------------------------------------------ void AliITStrackerMI::GetBestHypothesysMIP(TObjArray &itsTracks) { // // get "best" hypothesys // Int_t nentries = itsTracks.GetEntriesFast(); for (Int_t i=0;i<nentries;i++){ AliITStrackMI* track = (AliITStrackMI*)itsTracks.At(i); if (!track) continue; TObjArray * array = (TObjArray*) fTrackHypothesys.At(i); if (!array) continue; if (array->GetEntriesFast()<=0) continue; // AliITStrackMI* longtrack=0; Float_t minn=0; Float_t maxchi2=1000; for (Int_t j=0;j<array->GetEntriesFast();j++){ AliITStrackMI* trackHyp = (AliITStrackMI*)array->At(j); if (!trackHyp) continue; if (trackHyp->GetGoldV0()) { longtrack = trackHyp; //gold V0 track taken break; } if (trackHyp->GetNumberOfClusters()+trackHyp->GetNDeadZone()<minn) continue; Float_t chi2 = trackHyp->GetChi2MIP(0); if (fAfterV0){ if (!trackHyp->GetGoldV0()&&trackHyp->GetConstrain()==kFALSE) chi2+=5; } if (trackHyp->GetNumberOfClusters()+trackHyp->GetNDeadZone()>minn) maxchi2 = trackHyp->GetChi2MIP(0); // if (chi2 > maxchi2) continue; minn= trackHyp->GetNumberOfClusters()+trackHyp->GetNDeadZone(); maxchi2 = chi2; longtrack=trackHyp; } // // // AliITStrackMI * besttrack = (AliITStrackMI*)array->At(0); if (!longtrack) {longtrack = besttrack;} else besttrack= longtrack; // if (besttrack) { Int_t list[6]; AliITSRecPoint * clist[6]; Float_t shared = GetNumberOfSharedClusters(longtrack,i,list,clist); // track->SetNUsed(shared); track->SetNSkipped(besttrack->GetNSkipped()); track->SetChi2MIP(0,besttrack->GetChi2MIP(0)); if (shared>0) { if(!AliITSReconstructor::GetRecoParam()->GetAllowSharedClusters()) continue; Int_t nshared; Int_t overlist[6]; // Int_t sharedtrack = GetOverlapTrack(longtrack, i, nshared, list, overlist); //if (sharedtrack==-1) sharedtrack=0; if (sharedtrack>=0) { besttrack = GetBest2Tracks(i,sharedtrack,10,5.5); } } if (besttrack&&fAfterV0) { UpdateESDtrack(besttrack,AliESDtrack::kITSin); } if (besttrack&&fConstraint[fPass]) UpdateESDtrack(besttrack,AliESDtrack::kITSin); if (besttrack->GetChi2MIP(0)+besttrack->GetNUsed()>1.5 && fConstraint[fPass]) { if ( TMath::Abs(besttrack->GetD(0))>0.1 || TMath::Abs(besttrack->GetD(1))>0.1 ) track->SetReconstructed(kFALSE); } } } } //------------------------------------------------------------------------ void AliITStrackerMI::CookLabel(AliITStrackMI *track,Float_t wrong) const { //-------------------------------------------------------------------- //This function "cooks" a track label. If label<0, this track is fake. //-------------------------------------------------------------------- Int_t tpcLabel=-1; if ( track->GetESDtrack()) tpcLabel = TMath::Abs(track->GetESDtrack()->GetTPCLabel()); track->SetChi2MIP(9,0); Int_t nwrong=0; for (Int_t i=0;i<track->GetNumberOfClusters();i++){ Int_t cindex = track->GetClusterIndex(i); Int_t l=(cindex & 0xf0000000) >> 28; AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(cindex); Int_t isWrong=1; for (Int_t ind=0;ind<3;ind++){ if (tpcLabel>0) if (cl->GetLabel(ind)==tpcLabel) isWrong=0; AliDebug(2,Form("icl %d ilab %d lab %d",i,ind,cl->GetLabel(ind))); } track->SetChi2MIP(9,track->GetChi2MIP(9)+isWrong*(2<<l)); nwrong+=isWrong; } Int_t nclusters = track->GetNumberOfClusters(); if (nclusters > 0) //PH Some tracks don't have any cluster track->SetFakeRatio(double(nwrong)/double(nclusters)); if (tpcLabel>0){ if (track->GetFakeRatio()>wrong) track->SetLabel(-tpcLabel); else track->SetLabel(tpcLabel); } AliDebug(2,Form(" nls %d wrong %d label %d tpcLabel %d\n",nclusters,nwrong,track->GetLabel(),tpcLabel)); } //------------------------------------------------------------------------ void AliITStrackerMI::CookdEdx(AliITStrackMI* track) { // // // Int_t list[6]; //AliITSRecPoint * clist[6]; // Int_t shared = GetNumberOfSharedClusters(track,index,list,clist); Float_t dedx[4]; Int_t accepted=0; track->SetChi2MIP(9,0); for (Int_t i=0;i<track->GetNumberOfClusters();i++){ Int_t cindex = track->GetClusterIndex(i); Int_t l=(cindex & 0xf0000000) >> 28; AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(cindex); Int_t lab = TMath::Abs(track->GetESDtrack()->GetTPCLabel()); Int_t isWrong=1; for (Int_t ind=0;ind<3;ind++){ if (cl->GetLabel(ind)==lab) isWrong=0; } track->SetChi2MIP(9,track->GetChi2MIP(9)+isWrong*(2<<l)); if (l<2) continue; //if (l>3 && (cl->GetNy()>4) || (cl->GetNz()>4)) continue; //shared track //if (l>3&& !(cl->GetType()==1||cl->GetType()==10)) continue; //if (l<4&& !(cl->GetType()==1)) continue; dedx[accepted]= track->GetSampledEdx(i); //dedx[accepted]= track->fNormQ[l]; accepted++; } if (accepted<1) { track->SetdEdx(0); return; } Int_t indexes[4]; TMath::Sort(accepted,dedx,indexes,kFALSE); Double_t low=0.; Double_t up=0.51; Double_t nl=low*accepted, nu =up*accepted; Float_t sumamp = 0; Float_t sumweight =0; for (Int_t i=0; i<accepted; i++) { Float_t weight =1; if (i<nl+0.1) weight = TMath::Max(1.-(nl-i),0.); if (i>nu-1) weight = TMath::Max(nu-i,0.); sumamp+= dedx[indexes[i]]*weight; sumweight+=weight; } track->SetdEdx(sumamp/sumweight); } //------------------------------------------------------------------------ void AliITStrackerMI::MakeCoefficients(Int_t ntracks){ // // if (fCoefficients) delete []fCoefficients; fCoefficients = new Float_t[ntracks*48]; for (Int_t i=0;i<ntracks*48;i++) fCoefficients[i]=-1.; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetPredictedChi2MI(AliITStrackMI* track, const AliITSRecPoint *cluster,Int_t layer) { // // // Float_t erry,errz; Float_t theta = track->GetTgl(); Float_t phi = track->GetSnp(); phi = TMath::Sqrt(phi*phi/(1.-phi*phi)); AliITSClusterParam::GetError(layer,cluster,theta,phi,track->GetExpQ(),erry,errz); AliDebug(2,Form(" chi2: tr-cl %f %f tr X %f cl X %f",track->GetY()-cluster->GetY(),track->GetZ()-cluster->GetZ(),track->GetX(),cluster->GetX())); // Take into account the mis-alignment (bring track to cluster plane) Double_t xTrOrig=track->GetX(); if (!track->Propagate(xTrOrig+cluster->GetX())) return 1000.; AliDebug(2,Form(" chi2: tr-cl %f %f tr X %f cl X %f",track->GetY()-cluster->GetY(),track->GetZ()-cluster->GetZ(),track->GetX(),cluster->GetX())); Double_t chi2 = track->GetPredictedChi2MI(cluster->GetY(),cluster->GetZ(),erry,errz); // Bring the track back to detector plane in ideal geometry // [mis-alignment will be accounted for in UpdateMI()] if (!track->Propagate(xTrOrig)) return 1000.; Float_t ny,nz; AliITSClusterParam::GetNTeor(layer,cluster,theta,phi,ny,nz); Double_t delta = cluster->GetNy()+cluster->GetNz()-nz-ny; if (delta>1){ chi2+=0.5*TMath::Min(delta/2,2.); chi2+=2.*cluster->GetDeltaProbability(); } // track->SetNy(layer,ny); track->SetNz(layer,nz); track->SetSigmaY(layer,erry); track->SetSigmaZ(layer, errz); //track->fNormQ[layer] = cluster->GetQ()/TMath::Sqrt(1+theta*theta+phi*phi); track->SetNormQ(layer,cluster->GetQ()/TMath::Sqrt((1.+ track->GetTgl()*track->GetTgl())/(1.- track->GetSnp()*track->GetSnp()))); return chi2; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::UpdateMI(AliITStrackMI* track, const AliITSRecPoint* cl,Double_t chi2,Int_t index) const { // // // Int_t layer = (index & 0xf0000000) >> 28; track->SetClIndex(layer, index); if (layer>1&&AliITSReconstructor::GetRecoParam()->GetUseAmplitudeInfo(layer)) { if (track->GetNormQ(layer)/track->GetExpQ()<0.5 ) { chi2+= (0.5-track->GetNormQ(layer)/track->GetExpQ())*10.; track->SetdEdxMismatch(track->GetdEdxMismatch()+(0.5-track->GetNormQ(layer)/track->GetExpQ())*10.); } } if (cl->GetQ()<=0) return 0; // ingore the "virtual" clusters // Take into account the mis-alignment (bring track to cluster plane) Double_t xTrOrig=track->GetX(); Float_t clxyz[3]; cl->GetGlobalXYZ(clxyz);Double_t trxyz[3]; track->GetXYZ(trxyz); AliDebug(2,Form("gtr %f %f %f",trxyz[0],trxyz[1],trxyz[2])); AliDebug(2,Form("gcl %f %f %f",clxyz[0],clxyz[1],clxyz[2])); AliDebug(2,Form(" xtr %f xcl %f",track->GetX(),cl->GetX())); if (!track->Propagate(xTrOrig+cl->GetX())) return 0; AliCluster c(*cl); c.SetSigmaY2(track->GetSigmaY(layer)*track->GetSigmaY(layer)); c.SetSigmaZ2(track->GetSigmaZ(layer)*track->GetSigmaZ(layer)); Int_t updated = track->UpdateMI(&c,chi2,index); // Bring the track back to detector plane in ideal geometry if (!track->Propagate(xTrOrig)) return 0; if(!updated) AliDebug(2,"update failed"); return updated; } //------------------------------------------------------------------------ void AliITStrackerMI::GetDCASigma(AliITStrackMI* track, Float_t & sigmarfi, Float_t &sigmaz) { // //DCA sigmas parameterization //to be paramterized using external parameters in future // // sigmarfi = 0.0040+1.4 *TMath::Abs(track->GetC())+332.*track->GetC()*track->GetC(); sigmaz = 0.0110+4.37*TMath::Abs(track->GetC()); } //------------------------------------------------------------------------ void AliITStrackerMI::SignDeltas( TObjArray *ClusterArray, Float_t vz) { // // Int_t entries = ClusterArray->GetEntriesFast(); if (entries<4) return; AliITSRecPoint* cluster = (AliITSRecPoint*)ClusterArray->At(0); Int_t layer = cluster->GetLayer(); if (layer>1) return; Int_t index[10000]; Int_t ncandidates=0; Float_t r = (layer>0)? 7:4; // for (Int_t i=0;i<entries;i++){ AliITSRecPoint* cl0 = (AliITSRecPoint*)ClusterArray->At(i); Float_t nz = 1+TMath::Abs((cl0->GetZ()-vz)/r); if (cl0->GetNy()+cl0->GetNz()<=5+2*layer+nz) continue; index[ncandidates] = i; //candidate to belong to delta electron track ncandidates++; if (cl0->GetNy()+cl0->GetNz()>9+2*layer+nz) { cl0->SetDeltaProbability(1); } } // // // for (Int_t i=0;i<ncandidates;i++){ AliITSRecPoint* cl0 = (AliITSRecPoint*)ClusterArray->At(index[i]); if (cl0->GetDeltaProbability()>0.8) continue; // Int_t ncl = 0; Float_t y[100],z[100],sumy,sumz,sumy2, sumyz, sumw; sumy=sumz=sumy2=sumyz=sumw=0.0; for (Int_t j=0;j<ncandidates;j++){ if (i==j) continue; AliITSRecPoint* cl1 = (AliITSRecPoint*)ClusterArray->At(index[j]); // Float_t dz = cl0->GetZ()-cl1->GetZ(); Float_t dy = cl0->GetY()-cl1->GetY(); if (TMath::Sqrt(dz*dz+dy*dy)<0.2){ Float_t weight = cl1->GetNy()+cl1->GetNz()-2; y[ncl] = cl1->GetY(); z[ncl] = cl1->GetZ(); sumy+= y[ncl]*weight; sumz+= z[ncl]*weight; sumy2+=y[ncl]*y[ncl]*weight; sumyz+=y[ncl]*z[ncl]*weight; sumw+=weight; ncl++; } } if (ncl<4) continue; Float_t det = sumw*sumy2 - sumy*sumy; Float_t delta=1000; if (TMath::Abs(det)>0.01){ Float_t z0 = (sumy2*sumz - sumy*sumyz)/det; Float_t k = (sumyz*sumw - sumy*sumz)/det; delta = TMath::Abs(cl0->GetZ()-(z0+k*cl0->GetY())); } else{ Float_t z0 = sumyz/sumy; delta = TMath::Abs(cl0->GetZ()-z0); } if ( delta<0.05) { cl0->SetDeltaProbability(1-20.*delta); } } } //------------------------------------------------------------------------ void AliITStrackerMI::UpdateESDtrack(AliITStrackMI* track, ULong_t flags) const { // // track->UpdateESDtrack(flags); AliITStrackMI * oldtrack = (AliITStrackMI*)(track->GetESDtrack()->GetITStrack()); if (oldtrack) delete oldtrack; track->GetESDtrack()->SetITStrack(new AliITStrackMI(*track)); if (TMath::Abs(track->GetDnorm(1))<0.000000001){ printf("Problem\n"); } } //------------------------------------------------------------------------ Int_t AliITStrackerMI::GetNearestLayer(const Double_t *xr) const{ // // Get nearest upper layer close to the point xr. // rough approximation // const Float_t kRadiuses[6]={4,6.5,15.03,24.,38.5,43.7}; Float_t radius = TMath::Sqrt(xr[0]*xr[0]+xr[1]*xr[1]); Int_t res =6; for (Int_t i=0;i<6;i++){ if (radius<kRadiuses[i]){ res =i; break; } } return res; } //------------------------------------------------------------------------ void AliITStrackerMI::UpdateTPCV0(AliESDEvent *event){ // //try to update, or reject TPC V0s // Int_t nv0s = event->GetNumberOfV0s(); Int_t nitstracks = fTrackHypothesys.GetEntriesFast(); for (Int_t i=0;i<nv0s;i++){ AliESDv0 * vertex = event->GetV0(i); Int_t ip = vertex->GetIndex(0); Int_t im = vertex->GetIndex(1); // TObjArray * arrayp = (ip<nitstracks) ? (TObjArray*)fTrackHypothesys.At(ip):0; TObjArray * arraym = (im<nitstracks) ? (TObjArray*)fTrackHypothesys.At(im):0; AliITStrackMI * trackp = (arrayp!=0) ? (AliITStrackMI*)arrayp->At(0):0; AliITStrackMI * trackm = (arraym!=0) ? (AliITStrackMI*)arraym->At(0):0; // // if (trackp){ if (trackp->GetNumberOfClusters()+trackp->GetNDeadZone()>5.5){ if (trackp->GetConstrain()&&trackp->GetChi2MIP(0)<3) vertex->SetStatus(-100); if (!trackp->GetConstrain()&&trackp->GetChi2MIP(0)<2) vertex->SetStatus(-100); } } if (trackm){ if (trackm->GetNumberOfClusters()+trackm->GetNDeadZone()>5.5){ if (trackm->GetConstrain()&&trackm->GetChi2MIP(0)<3) vertex->SetStatus(-100); if (!trackm->GetConstrain()&&trackm->GetChi2MIP(0)<2) vertex->SetStatus(-100); } } if (vertex->GetStatus()==-100) continue; // Double_t xrp[3]; vertex->GetXYZ(xrp[0],xrp[1],xrp[2]); //I.B. Int_t clayer = GetNearestLayer(xrp); //I.B. vertex->SetNBefore(clayer); // vertex->SetChi2Before(9*clayer); // vertex->SetNAfter(6-clayer); // vertex->SetChi2After(0); // // if (clayer >1 ){ // calculate chi2 before vertex Float_t chi2p = 0, chi2m=0; // if (trackp){ for (Int_t ilayer=0;ilayer<clayer;ilayer++){ if (trackp->GetClIndex(ilayer)>0){ chi2p+=trackp->GetDy(ilayer)*trackp->GetDy(ilayer)/(trackp->GetSigmaY(ilayer)*trackp->GetSigmaY(ilayer))+ trackp->GetDz(ilayer)*trackp->GetDz(ilayer)/(trackp->GetSigmaZ(ilayer)*trackp->GetSigmaZ(ilayer)); } else{ chi2p+=9; } } }else{ chi2p = 9*clayer; } // if (trackm){ for (Int_t ilayer=0;ilayer<clayer;ilayer++){ if (trackm->GetClIndex(ilayer)>0){ chi2m+=trackm->GetDy(ilayer)*trackm->GetDy(ilayer)/(trackm->GetSigmaY(ilayer)*trackm->GetSigmaY(ilayer))+ trackm->GetDz(ilayer)*trackm->GetDz(ilayer)/(trackm->GetSigmaZ(ilayer)*trackm->GetSigmaZ(ilayer)); } else{ chi2m+=9; } } }else{ chi2m = 9*clayer; } vertex->SetChi2Before(TMath::Min(chi2p,chi2m)); if (TMath::Min(chi2p,chi2m)/Float_t(clayer)<4) vertex->SetStatus(-10); // track exist before vertex } if (clayer < 5 ){ // calculate chi2 after vertex Float_t chi2p = 0, chi2m=0; // if (trackp&&TMath::Abs(trackp->GetTgl())<1.){ for (Int_t ilayer=clayer;ilayer<6;ilayer++){ if (trackp->GetClIndex(ilayer)>0){ chi2p+=trackp->GetDy(ilayer)*trackp->GetDy(ilayer)/(trackp->GetSigmaY(ilayer)*trackp->GetSigmaY(ilayer))+ trackp->GetDz(ilayer)*trackp->GetDz(ilayer)/(trackp->GetSigmaZ(ilayer)*trackp->GetSigmaZ(ilayer)); } else{ chi2p+=9; } } }else{ chi2p = 0; } // if (trackm&&TMath::Abs(trackm->GetTgl())<1.){ for (Int_t ilayer=clayer;ilayer<6;ilayer++){ if (trackm->GetClIndex(ilayer)>0){ chi2m+=trackm->GetDy(ilayer)*trackm->GetDy(ilayer)/(trackm->GetSigmaY(ilayer)*trackm->GetSigmaY(ilayer))+ trackm->GetDz(ilayer)*trackm->GetDz(ilayer)/(trackm->GetSigmaZ(ilayer)*trackm->GetSigmaZ(ilayer)); } else{ chi2m+=9; } } }else{ chi2m = 0; } vertex->SetChi2After(TMath::Max(chi2p,chi2m)); if (TMath::Max(chi2m,chi2p)/Float_t(6-clayer)>9) vertex->SetStatus(-20); // track not found in ITS } } // } //------------------------------------------------------------------------ void AliITStrackerMI::FindV02(AliESDEvent *event) { // // V0 finder // // Cuts on DCA - R dependent // max distance DCA between 2 tracks cut // maxDist = TMath::Min(kMaxDist,kMaxDist0+pvertex->GetRr()*kMaxDist); // const Float_t kMaxDist0 = 0.1; const Float_t kMaxDist1 = 0.1; const Float_t kMaxDist = 1; const Float_t kMinPointAngle = 0.85; const Float_t kMinPointAngle2 = 0.99; const Float_t kMinR = 0.5; const Float_t kMaxR = 220; //const Float_t kCausality0Cut = 0.19; //const Float_t kLikelihood01Cut = 0.25; //const Float_t kPointAngleCut = 0.9996; const Float_t kCausality0Cut = 0.19; const Float_t kLikelihood01Cut = 0.45; const Float_t kLikelihood1Cut = 0.5; const Float_t kCombinedCut = 0.55; // // TTreeSRedirector &cstream = *fDebugStreamer; Int_t ntracks = event->GetNumberOfTracks(); Int_t nitstracks = fTrackHypothesys.GetEntriesFast(); fOriginal.Expand(ntracks); fTrackHypothesys.Expand(ntracks); fBestHypothesys.Expand(ntracks); // AliHelix * helixes = new AliHelix[ntracks+2]; TObjArray trackarray(ntracks+2); //array with tracks - with vertex constrain TObjArray trackarrayc(ntracks+2); //array of "best tracks" - without vertex constrain TObjArray trackarrayl(ntracks+2); //array of "longest tracks" - without vertex constrain Bool_t * forbidden = new Bool_t [ntracks+2]; Int_t *itsmap = new Int_t [ntracks+2]; Float_t *dist = new Float_t[ntracks+2]; Float_t *normdist0 = new Float_t[ntracks+2]; Float_t *normdist1 = new Float_t[ntracks+2]; Float_t *normdist = new Float_t[ntracks+2]; Float_t *norm = new Float_t[ntracks+2]; Float_t *maxr = new Float_t[ntracks+2]; Float_t *minr = new Float_t[ntracks+2]; Float_t *minPointAngle= new Float_t[ntracks+2]; // AliV0 *pvertex = new AliV0; AliITStrackMI * dummy= new AliITStrackMI; dummy->SetLabel(0); AliITStrackMI trackat0; //temporary track for DCA calculation // Float_t primvertex[3]={GetX(),GetY(),GetZ()}; // // make ITS - ESD map // for (Int_t itrack=0;itrack<ntracks+2;itrack++) { itsmap[itrack] = -1; forbidden[itrack] = kFALSE; maxr[itrack] = kMaxR; minr[itrack] = kMinR; minPointAngle[itrack] = kMinPointAngle; } for (Int_t itrack=0;itrack<nitstracks;itrack++){ AliITStrackMI * original = (AliITStrackMI*)(fOriginal.At(itrack)); Int_t esdindex = original->GetESDtrack()->GetID(); itsmap[esdindex] = itrack; } // // create ITS tracks from ESD tracks if not done before // for (Int_t itrack=0;itrack<ntracks;itrack++){ if (itsmap[itrack]>=0) continue; AliITStrackMI * tpctrack = new AliITStrackMI(*(event->GetTrack(itrack))); //tpctrack->fD[0] = tpctrack->GetD(GetX(),GetY()); //tpctrack->fD[1] = tpctrack->GetZat(GetX())-GetZ(); tpctrack->GetDZ(GetX(),GetY(),GetZ(),tpctrack->GetDP()); //I.B. if (tpctrack->GetD(0)<20 && tpctrack->GetD(1)<20){ // tracks which can reach inner part of ITS // propagate track to outer its volume - with correction for material CorrectForTPCtoITSDeadZoneMaterial(tpctrack); } itsmap[itrack] = nitstracks; fOriginal.AddAt(tpctrack,nitstracks); nitstracks++; } // // fill temporary arrays // for (Int_t itrack=0;itrack<ntracks;itrack++){ AliESDtrack * esdtrack = event->GetTrack(itrack); Int_t itsindex = itsmap[itrack]; AliITStrackMI *original = (AliITStrackMI*)fOriginal.At(itsmap[itrack]); if (!original) continue; AliITStrackMI *bestConst = 0; AliITStrackMI *bestLong = 0; AliITStrackMI *best = 0; // // TObjArray * array = (TObjArray*) fTrackHypothesys.At(itsindex); Int_t hentries = (array==0) ? 0 : array->GetEntriesFast(); // Get best track with vertex constrain for (Int_t ih=0;ih<hentries;ih++){ AliITStrackMI * trackh = (AliITStrackMI*)array->At(ih); if (!trackh->GetConstrain()) continue; if (!bestConst) bestConst = trackh; if (trackh->GetNumberOfClusters()>5.0){ bestConst = trackh; // full track - with minimal chi2 break; } if (trackh->GetNumberOfClusters()+trackh->GetNDeadZone()<=bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()) continue; bestConst = trackh; break; } // Get best long track without vertex constrain and best track without vertex constrain for (Int_t ih=0;ih<hentries;ih++){ AliITStrackMI * trackh = (AliITStrackMI*)array->At(ih); if (trackh->GetConstrain()) continue; if (!best) best = trackh; if (!bestLong) bestLong = trackh; if (trackh->GetNumberOfClusters()>5.0){ bestLong = trackh; // full track - with minimal chi2 break; } if (trackh->GetNumberOfClusters()+trackh->GetNDeadZone()<=bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()) continue; bestLong = trackh; } if (!best) { best = original; bestLong = original; } //I.B. trackat0 = *bestLong; new (&trackat0) AliITStrackMI(*bestLong); Double_t xx,yy,zz,alpha; if (!bestLong->GetGlobalXYZat(bestLong->GetX(),xx,yy,zz)) continue; alpha = TMath::ATan2(yy,xx); if (!trackat0.Propagate(alpha,0)) continue; // calculate normalized distances to the vertex // Float_t ptfac = (1.+100.*TMath::Abs(trackat0.GetC())); if ( bestLong->GetNumberOfClusters()>3 ){ dist[itsindex] = trackat0.GetY(); norm[itsindex] = ptfac*TMath::Sqrt(trackat0.GetSigmaY2()); normdist0[itsindex] = TMath::Abs(trackat0.GetY()/norm[itsindex]); normdist1[itsindex] = TMath::Abs((trackat0.GetZ()-primvertex[2])/(ptfac*TMath::Sqrt(trackat0.GetSigmaZ2()))); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); if (!bestConst){ if (bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()<6) normdist[itsindex]*=2.; if (bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()<5) normdist[itsindex]*=2.; if (bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()<4) normdist[itsindex]*=2.; }else{ if (bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()<6) normdist[itsindex]*=1.5; if (bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()<5) normdist[itsindex]*=1.5; } } else{ if (bestConst&&bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()>4.5){ dist[itsindex] = bestConst->GetD(0); norm[itsindex] = bestConst->GetDnorm(0); normdist0[itsindex] = TMath::Abs(bestConst->GetD(0)/norm[itsindex]); normdist1[itsindex] = TMath::Abs(bestConst->GetD(0)/norm[itsindex]); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); }else{ dist[itsindex] = trackat0.GetY(); norm[itsindex] = ptfac*TMath::Sqrt(trackat0.GetSigmaY2()); normdist0[itsindex] = TMath::Abs(trackat0.GetY()/norm[itsindex]); normdist1[itsindex] = TMath::Abs((trackat0.GetZ()-primvertex[2])/(ptfac*TMath::Sqrt(trackat0.GetSigmaZ2()))); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); if (TMath::Abs(trackat0.GetTgl())>1.05){ if (normdist[itsindex]<3) forbidden[itsindex]=kTRUE; if (normdist[itsindex]>3) { minr[itsindex] = TMath::Max(Float_t(40.),minr[itsindex]); } } } } // //----------------------------------------------------------- //Forbid primary track candidates - // //treetr->SetAlias("forbidden0","Tr0.fN<4&&Tr1.fN+Tr1.fNDeadZone>4.5"); //treetr->SetAlias("forbidden1","ND<3&&Tr1.fN+Tr1.fNDeadZone>5.5"); //treetr->SetAlias("forbidden2","ND<2&&Tr1.fClIndex[0]>0&&Tr1.fClIndex[0]>0"); //treetr->SetAlias("forbidden3","ND<1&&Tr1.fClIndex[0]>0"); //treetr->SetAlias("forbidden4","ND<4&&Tr1.fNormChi2[0]<2"); //treetr->SetAlias("forbidden5","ND<5&&Tr1.fNormChi2[0]<1"); //----------------------------------------------------------- if (bestConst){ if (bestLong->GetNumberOfClusters()<4 && bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()>4.5) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<3 && bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()>5.5) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<2 && bestConst->GetClIndex(0)>0 && bestConst->GetClIndex(1)>0 ) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<1 && bestConst->GetClIndex(0)>0) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<4 && bestConst->GetNormChi2(0)<2) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<5 && bestConst->GetNormChi2(0)<1) forbidden[itsindex]=kTRUE; if (bestConst->GetNormChi2(0)<2.5) { minPointAngle[itsindex]= 0.9999; maxr[itsindex] = 10; } } // //forbid daughter kink candidates // if (esdtrack->GetKinkIndex(0)>0) forbidden[itsindex] = kTRUE; Bool_t isElectron = kTRUE; Bool_t isProton = kTRUE; Double_t pid[5]; esdtrack->GetESDpid(pid); for (Int_t i=1;i<5;i++){ if (pid[0]<pid[i]) isElectron= kFALSE; if (pid[4]<pid[i]) isProton= kFALSE; } if (isElectron){ forbidden[itsindex]=kFALSE; normdist[itsindex]*=-1; } if (isProton){ if (normdist[itsindex]>2) forbidden[itsindex]=kFALSE; normdist[itsindex]*=-1; } // // Causality cuts in TPC volume // if (esdtrack->GetTPCdensity(0,10) >0.6) maxr[itsindex] = TMath::Min(Float_t(110),maxr[itsindex]); if (esdtrack->GetTPCdensity(10,30)>0.6) maxr[itsindex] = TMath::Min(Float_t(120),maxr[itsindex]); if (esdtrack->GetTPCdensity(20,40)>0.6) maxr[itsindex] = TMath::Min(Float_t(130),maxr[itsindex]); if (esdtrack->GetTPCdensity(30,50)>0.6) maxr[itsindex] = TMath::Min(Float_t(140),maxr[itsindex]); // if (esdtrack->GetTPCdensity(0,60)<0.4&&bestLong->GetNumberOfClusters()<3) minr[itsindex]=100; // // if (kFALSE){ cstream<<"Track"<< "Tr0.="<<best<< "Tr1.="<<((bestConst)? bestConst:dummy)<< "Tr2.="<<bestLong<< "Tr3.="<<&trackat0<< "Esd.="<<esdtrack<< "Dist="<<dist[itsindex]<< "ND0="<<normdist0[itsindex]<< "ND1="<<normdist1[itsindex]<< "ND="<<normdist[itsindex]<< "Pz="<<primvertex[2]<< "Forbid="<<forbidden[itsindex]<< "\n"; // } trackarray.AddAt(best,itsindex); trackarrayc.AddAt(bestConst,itsindex); trackarrayl.AddAt(bestLong,itsindex); new (&helixes[itsindex]) AliHelix(*best); } // // // // first iterration of V0 finder // for (Int_t iesd0=0;iesd0<ntracks;iesd0++){ Int_t itrack0 = itsmap[iesd0]; if (forbidden[itrack0]) continue; AliITStrackMI * btrack0 = (AliITStrackMI*)trackarray.At(itrack0); if (!btrack0) continue; if (btrack0->GetSign()>0) continue; AliITStrackMI *trackc0 = (AliITStrackMI*)trackarrayc.At(itrack0); // for (Int_t iesd1=0;iesd1<ntracks;iesd1++){ Int_t itrack1 = itsmap[iesd1]; if (forbidden[itrack1]) continue; AliITStrackMI * btrack1 = (AliITStrackMI*)trackarray.At(itrack1); if (!btrack1) continue; if (btrack1->GetSign()<0) continue; Bool_t isGold = kFALSE; if (TMath::Abs(TMath::Abs(btrack0->GetLabel())-TMath::Abs(btrack1->GetLabel()))==1){ isGold = kTRUE; } AliITStrackMI *trackc1 = (AliITStrackMI*)trackarrayc.At(itrack1); AliHelix &h1 = helixes[itrack0]; AliHelix &h2 = helixes[itrack1]; // // find linear distance Double_t rmin =0; // // // Double_t phase[2][2],radius[2]; Int_t points = h1.GetRPHIintersections(h2, phase, radius); if (points==0) continue; Double_t delta[2]={1000000,1000000}; rmin = radius[0]; h1.ParabolicDCA(h2,phase[0][0],phase[0][1],radius[0],delta[0]); if (points==2){ if (radius[1]<rmin) rmin = radius[1]; h1.ParabolicDCA(h2,phase[1][0],phase[1][1],radius[1],delta[1]); } rmin = TMath::Sqrt(rmin); Double_t distance = 0; Double_t radiusC = 0; Int_t iphase = 0; if (points==1 || delta[0]<delta[1]){ distance = TMath::Sqrt(delta[0]); radiusC = TMath::Sqrt(radius[0]); }else{ distance = TMath::Sqrt(delta[1]); radiusC = TMath::Sqrt(radius[1]); iphase=1; } if (radiusC<TMath::Max(minr[itrack0],minr[itrack1])) continue; if (radiusC>TMath::Min(maxr[itrack0],maxr[itrack1])) continue; Float_t maxDist = TMath::Min(kMaxDist,Float_t(kMaxDist0+radiusC*kMaxDist1)); if (distance>maxDist) continue; Float_t pointAngle = h1.GetPointAngle(h2,phase[iphase],primvertex); if (pointAngle<TMath::Max(minPointAngle[itrack0],minPointAngle[itrack1])) continue; // // // Double_t distance = TestV0(h1,h2,pvertex,rmin); // // if (distance>maxDist) continue; // if (pvertex->GetRr()<kMinR) continue; // if (pvertex->GetRr()>kMaxR) continue; AliITStrackMI * track0=btrack0; AliITStrackMI * track1=btrack1; // if (pvertex->GetRr()<3.5){ if (radiusC<3.5){ //use longest tracks inside the pipe track0 = (AliITStrackMI*)trackarrayl.At(itrack0); track1 = (AliITStrackMI*)trackarrayl.At(itrack1); } // // pvertex->SetParamN(*track0); pvertex->SetParamP(*track1); pvertex->Update(primvertex); pvertex->SetClusters(track0->ClIndex(),track1->ClIndex()); // register clusters if (pvertex->GetRr()<kMinR) continue; if (pvertex->GetRr()>kMaxR) continue; if (pvertex->GetV0CosineOfPointingAngle()<kMinPointAngle) continue; //Bo: if (pvertex->GetDist2()>maxDist) continue; if (pvertex->GetDcaV0Daughters()>maxDist) continue; //Bo: pvertex->SetLab(0,track0->GetLabel()); //Bo: pvertex->SetLab(1,track1->GetLabel()); pvertex->SetIndex(0,track0->GetESDtrack()->GetID()); pvertex->SetIndex(1,track1->GetESDtrack()->GetID()); // AliITStrackMI * htrackc0 = trackc0 ? trackc0:dummy; AliITStrackMI * htrackc1 = trackc1 ? trackc1:dummy; // // TObjArray * array0b = (TObjArray*)fBestHypothesys.At(itrack0); if (!array0b&&pvertex->GetRr()<40 && TMath::Abs(track0->GetTgl())<1.1) { fCurrentEsdTrack = itrack0; FollowProlongationTree((AliITStrackMI*)fOriginal.At(itrack0),itrack0, kFALSE); } TObjArray * array1b = (TObjArray*)fBestHypothesys.At(itrack1); if (!array1b&&pvertex->GetRr()<40 && TMath::Abs(track1->GetTgl())<1.1) { fCurrentEsdTrack = itrack1; FollowProlongationTree((AliITStrackMI*)fOriginal.At(itrack1),itrack1, kFALSE); } // AliITStrackMI * track0b = (AliITStrackMI*)fOriginal.At(itrack0); AliITStrackMI * track1b = (AliITStrackMI*)fOriginal.At(itrack1); AliITStrackMI * track0l = (AliITStrackMI*)fOriginal.At(itrack0); AliITStrackMI * track1l = (AliITStrackMI*)fOriginal.At(itrack1); Float_t minchi2before0=16; Float_t minchi2before1=16; Float_t minchi2after0 =16; Float_t minchi2after1 =16; Double_t xrp[3]; pvertex->GetXYZ(xrp[0],xrp[1],xrp[2]); //I.B. Int_t maxLayer = GetNearestLayer(xrp); //I.B. if (array0b) for (Int_t i=0;i<5;i++){ // best track after vertex AliITStrackMI * btrack = (AliITStrackMI*)array0b->At(i); if (!btrack) continue; if (btrack->GetNumberOfClusters()>track0l->GetNumberOfClusters()) track0l = btrack; // if (btrack->fX<pvertex->GetRr()-2.-0.5/(0.1+pvertex->GetAnglep()[2])) { if (btrack->GetX()<pvertex->GetRr()-2.) { if ( (maxLayer>i+2|| (i==0)) && btrack->GetNumberOfClusters()==(6-i)&&i<3){ Float_t sumchi2= 0; Float_t sumn = 0; if (maxLayer<3){ // take prim vertex as additional measurement if (normdist[itrack0]>0 && htrackc0){ sumchi2 += TMath::Min((3.-maxLayer)*normdist[itrack0]*normdist[itrack0],16.); }else{ sumchi2 += TMath::Min((3.-maxLayer)*(3*normdist[itrack0]*normdist[itrack0]+3.),16.); } sumn += 3-maxLayer; } for (Int_t ilayer=i;ilayer<maxLayer;ilayer++){ sumn+=1.; if (!btrack->GetClIndex(ilayer)){ sumchi2+=25; continue; }else{ Int_t c=( btrack->GetClIndex(ilayer) & 0x0fffffff); for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[ilayer].GetClusterTracks(itrack,c)>=0 && fgLayers[ilayer].GetClusterTracks(itrack,c)!=itrack0){ sumchi2+=18.; //shared cluster break; } } sumchi2+=btrack->GetDy(ilayer)*btrack->GetDy(ilayer)/(btrack->GetSigmaY(ilayer)*btrack->GetSigmaY(ilayer)); sumchi2+=btrack->GetDz(ilayer)*btrack->GetDz(ilayer)/(btrack->GetSigmaZ(ilayer)*btrack->GetSigmaZ(ilayer)); } } sumchi2/=sumn; if (sumchi2<minchi2before0) minchi2before0=sumchi2; } continue; //safety space - Geo manager will give exact layer } track0b = btrack; minchi2after0 = btrack->GetNormChi2(i); break; } if (array1b) for (Int_t i=0;i<5;i++){ // best track after vertex AliITStrackMI * btrack = (AliITStrackMI*)array1b->At(i); if (!btrack) continue; if (btrack->GetNumberOfClusters()>track1l->GetNumberOfClusters()) track1l = btrack; // if (btrack->fX<pvertex->GetRr()-2-0.5/(0.1+pvertex->GetAnglep()[2])){ if (btrack->GetX()<pvertex->GetRr()-2){ if ((maxLayer>i+2 || (i==0))&&btrack->GetNumberOfClusters()==(6-i)&&(i<3)){ Float_t sumchi2= 0; Float_t sumn = 0; if (maxLayer<3){ // take prim vertex as additional measurement if (normdist[itrack1]>0 && htrackc1){ sumchi2 += TMath::Min((3.-maxLayer)*normdist[itrack1]*normdist[itrack1],16.); }else{ sumchi2 += TMath::Min((3.-maxLayer)*(3*normdist[itrack1]*normdist[itrack1]+3.),16.); } sumn += 3-maxLayer; } for (Int_t ilayer=i;ilayer<maxLayer;ilayer++){ sumn+=1.; if (!btrack->GetClIndex(ilayer)){ sumchi2+=30; continue; }else{ Int_t c=( btrack->GetClIndex(ilayer) & 0x0fffffff); for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[ilayer].GetClusterTracks(itrack,c)>=0 && fgLayers[ilayer].GetClusterTracks(itrack,c)!=itrack1){ sumchi2+=18.; //shared cluster break; } } sumchi2+=btrack->GetDy(ilayer)*btrack->GetDy(ilayer)/(btrack->GetSigmaY(ilayer)*btrack->GetSigmaY(ilayer)); sumchi2+=btrack->GetDz(ilayer)*btrack->GetDz(ilayer)/(btrack->GetSigmaZ(ilayer)*btrack->GetSigmaZ(ilayer)); } } sumchi2/=sumn; if (sumchi2<minchi2before1) minchi2before1=sumchi2; } continue; //safety space - Geo manager will give exact layer } track1b = btrack; minchi2after1 = btrack->GetNormChi2(i); break; } // // position resolution - used for DCA cut Float_t sigmad = track0b->GetSigmaY2()+track0b->GetSigmaZ2()+track1b->GetSigmaY2()+track1b->GetSigmaZ2()+ (track0b->GetX()-pvertex->GetRr())*(track0b->GetX()-pvertex->GetRr())*(track0b->GetSigmaSnp2()+track0b->GetSigmaTgl2())+ (track1b->GetX()-pvertex->GetRr())*(track1b->GetX()-pvertex->GetRr())*(track1b->GetSigmaSnp2()+track1b->GetSigmaTgl2()); sigmad =TMath::Sqrt(sigmad)+0.04; if (pvertex->GetRr()>50){ Double_t cov0[15],cov1[15]; track0b->GetESDtrack()->GetInnerExternalCovariance(cov0); track1b->GetESDtrack()->GetInnerExternalCovariance(cov1); sigmad = cov0[0]+cov0[2]+cov1[0]+cov1[2]+ (80.-pvertex->GetRr())*(80.-pvertex->GetRr())*(cov0[5]+cov0[9])+ (80.-pvertex->GetRr())*(80.-pvertex->GetRr())*(cov1[5]+cov1[9]); sigmad =TMath::Sqrt(sigmad)+0.05; } // AliV0 vertex2; vertex2.SetParamN(*track0b); vertex2.SetParamP(*track1b); vertex2.Update(primvertex); //Bo: if (vertex2.GetDist2()<=pvertex->GetDist2()&&(vertex2.GetV0CosineOfPointingAngle()>=pvertex->GetV0CosineOfPointingAngle())){ if (vertex2.GetDcaV0Daughters()<=pvertex->GetDcaV0Daughters()&&(vertex2.GetV0CosineOfPointingAngle()>=pvertex->GetV0CosineOfPointingAngle())){ pvertex->SetParamN(*track0b); pvertex->SetParamP(*track1b); pvertex->Update(primvertex); pvertex->SetClusters(track0b->ClIndex(),track1b->ClIndex()); // register clusters pvertex->SetIndex(0,track0->GetESDtrack()->GetID()); pvertex->SetIndex(1,track1->GetESDtrack()->GetID()); } pvertex->SetDistSigma(sigmad); //Bo: pvertex->SetDistNorm(pvertex->GetDist2()/sigmad); pvertex->SetNormDCAPrim(normdist[itrack0],normdist[itrack1]); // // define likelihhod and causalities // Float_t pa0=1, pa1=1, pb0=0.26, pb1=0.26; if (maxLayer<1){ Float_t fnorm0 = normdist[itrack0]; if (fnorm0<0) fnorm0*=-3; Float_t fnorm1 = normdist[itrack1]; if (fnorm1<0) fnorm1*=-3; if ((pvertex->GetAnglep()[2]>0.1) || ( (pvertex->GetRr()<10.5)&& pvertex->GetAnglep()[2]>0.05 ) || (pvertex->GetRr()<3)){ pb0 = TMath::Exp(-TMath::Min(fnorm0,Float_t(16.))/12.); pb1 = TMath::Exp(-TMath::Min(fnorm1,Float_t(16.))/12.); } pvertex->SetChi2Before(normdist[itrack0]); pvertex->SetChi2After(normdist[itrack1]); pvertex->SetNAfter(0); pvertex->SetNBefore(0); }else{ pvertex->SetChi2Before(minchi2before0); pvertex->SetChi2After(minchi2before1); if (pvertex->GetAnglep()[2]>0.1 || ( pvertex->GetRr()<10.5 && pvertex->GetAnglep()[2]>0.05) || pvertex->GetRr()<3){ pb0 = TMath::Exp(-TMath::Min(minchi2before0,Float_t(16))/12.); pb1 = TMath::Exp(-TMath::Min(minchi2before1,Float_t(16))/12.); } pvertex->SetNAfter(maxLayer); pvertex->SetNBefore(maxLayer); } if (pvertex->GetRr()<90){ pa0 *= TMath::Min(track0->GetESDtrack()->GetTPCdensity(0,60),Double_t(1.)); pa1 *= TMath::Min(track1->GetESDtrack()->GetTPCdensity(0,60),Double_t(1.)); } if (pvertex->GetRr()<20){ pa0 *= (0.2+TMath::Exp(-TMath::Min(minchi2after0,Float_t(16))/8.))/1.2; pa1 *= (0.2+TMath::Exp(-TMath::Min(minchi2after1,Float_t(16))/8.))/1.2; } // pvertex->SetCausality(pb0,pb1,pa0,pa1); // // Likelihood calculations - apply cuts // Bool_t v0OK = kTRUE; Float_t p12 = pvertex->GetParamP()->GetParameter()[4]*pvertex->GetParamP()->GetParameter()[4]; p12 += pvertex->GetParamN()->GetParameter()[4]*pvertex->GetParamN()->GetParameter()[4]; p12 = TMath::Sqrt(p12); // "mean" momenta Float_t sigmap0 = 0.0001+0.001/(0.1+pvertex->GetRr()); Float_t sigmap = 0.5*sigmap0*(0.6+0.4*p12); // "resolution: of point angle - as a function of radius and momenta Float_t causalityA = (1.0-pvertex->GetCausalityP()[0])*(1.0-pvertex->GetCausalityP()[1]); Float_t causalityB = TMath::Sqrt(TMath::Min(pvertex->GetCausalityP()[2],Double_t(0.7))* TMath::Min(pvertex->GetCausalityP()[3],Double_t(0.7))); // //Bo: Float_t likelihood0 = (TMath::Exp(-pvertex->GetDistNorm())+0.1) *(pvertex->GetDist2()<0.5)*(pvertex->GetDistNorm()<5); Float_t lDistNorm = pvertex->GetDcaV0Daughters()/pvertex->GetDistSigma(); Float_t likelihood0 = (TMath::Exp(-lDistNorm)+0.1) *(pvertex->GetDcaV0Daughters()<0.5)*(lDistNorm<5); Float_t likelihood1 = TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/sigmap)+ 0.4*TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/(4.*sigmap))+ 0.4*TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/(8.*sigmap))+ 0.1*TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/0.01); // if (causalityA<kCausality0Cut) v0OK = kFALSE; if (TMath::Sqrt(likelihood0*likelihood1)<kLikelihood01Cut) v0OK = kFALSE; if (likelihood1<kLikelihood1Cut) v0OK = kFALSE; if (TMath::Power(likelihood0*likelihood1*causalityB,0.33)<kCombinedCut) v0OK = kFALSE; // // if (kFALSE){ Bool_t gold = TMath::Abs(TMath::Abs(track0->GetLabel())-TMath::Abs(track1->GetLabel()))==1; cstream<<"It0"<< "Tr0.="<<track0<< //best without constrain "Tr1.="<<track1<< //best without constrain "Tr0B.="<<track0b<< //best without constrain after vertex "Tr1B.="<<track1b<< //best without constrain after vertex "Tr0C.="<<htrackc0<< //best with constrain if exist "Tr1C.="<<htrackc1<< //best with constrain if exist "Tr0L.="<<track0l<< //longest best "Tr1L.="<<track1l<< //longest best "Esd0.="<<track0->GetESDtrack()<< // esd track0 params "Esd1.="<<track1->GetESDtrack()<< // esd track1 params "V0.="<<pvertex<< //vertex properties "V0b.="<<&vertex2<< //vertex properties at "best" track "ND0="<<normdist[itrack0]<< //normalize distance for track0 "ND1="<<normdist[itrack1]<< //normalize distance for track1 "Gold="<<gold<< // // "RejectBase="<<rejectBase<< //rejection in First itteration "OK="<<v0OK<< "rmin="<<rmin<< "sigmad="<<sigmad<< "\n"; } //if (rejectBase) continue; // pvertex->SetStatus(0); // if (rejectBase) { // pvertex->SetStatus(-100); //} if (pvertex->GetV0CosineOfPointingAngle()>kMinPointAngle2) { //Bo: pvertex->SetESDindexes(track0->GetESDtrack()->GetID(),track1->GetESDtrack()->GetID()); pvertex->SetIndex(0,track0->GetESDtrack()->GetID());//Bo: consistency 0 for neg pvertex->SetIndex(1,track1->GetESDtrack()->GetID());//Bo: consistency 1 for pos if (v0OK){ // AliV0vertex vertexjuri(*track0,*track1); // vertexjuri.SetESDindexes(track0->fESDtrack->GetID(),track1->fESDtrack->GetID()); // event->AddV0(&vertexjuri); pvertex->SetStatus(100); } pvertex->SetOnFlyStatus(kTRUE); pvertex->ChangeMassHypothesis(kK0Short); event->AddV0(pvertex); } } } // // // delete temporary arrays // delete[] forbidden; delete[] minPointAngle; delete[] maxr; delete[] minr; delete[] norm; delete[] normdist; delete[] normdist1; delete[] normdist0; delete[] dist; delete[] itsmap; delete[] helixes; delete pvertex; } //------------------------------------------------------------------------ void AliITStrackerMI::RefitV02(AliESDEvent *event) { // //try to refit V0s in the third path of the reconstruction // TTreeSRedirector &cstream = *fDebugStreamer; // Int_t nv0s = event->GetNumberOfV0s(); Float_t primvertex[3]={GetX(),GetY(),GetZ()}; AliV0 v0temp; for (Int_t iv0 = 0; iv0<nv0s;iv0++){ AliV0 * v0mi = (AliV0*)event->GetV0(iv0); if (!v0mi) continue; Int_t itrack0 = v0mi->GetIndex(0); Int_t itrack1 = v0mi->GetIndex(1); AliESDtrack *esd0 = event->GetTrack(itrack0); AliESDtrack *esd1 = event->GetTrack(itrack1); if (!esd0||!esd1) continue; AliITStrackMI tpc0(*esd0); AliITStrackMI tpc1(*esd1); Double_t x,y,z; v0mi->GetXYZ(x,y,z); //I.B. Double_t alpha =TMath::ATan2(y,x); //I.B. if (v0mi->GetRr()>85){ if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ v0temp.SetParamN(tpc0); v0temp.SetParamP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; //Bo: if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ if (v0temp.GetDcaV0Daughters()<v0mi->GetDcaV0Daughters() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ v0mi->SetParamN(tpc0); v0mi->SetParamP(tpc1); v0mi->Update(primvertex); } } continue; } if (v0mi->GetRr()>35){ CorrectForTPCtoITSDeadZoneMaterial(&tpc0); CorrectForTPCtoITSDeadZoneMaterial(&tpc1); if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ v0temp.SetParamN(tpc0); v0temp.SetParamP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; //Bo: if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ if (v0temp.GetDcaV0Daughters()<v0mi->GetDcaV0Daughters() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ v0mi->SetParamN(tpc0); v0mi->SetParamP(tpc1); v0mi->Update(primvertex); } } continue; } CorrectForTPCtoITSDeadZoneMaterial(&tpc0); CorrectForTPCtoITSDeadZoneMaterial(&tpc1); // if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ if (RefitAt(v0mi->GetRr(),&tpc0, v0mi->GetClusters(0)) && RefitAt(v0mi->GetRr(),&tpc1, v0mi->GetClusters(1))){ v0temp.SetParamN(tpc0); v0temp.SetParamP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; //Bo: if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ if (v0temp.GetDcaV0Daughters()<v0mi->GetDcaV0Daughters() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ v0mi->SetParamN(tpc0); v0mi->SetParamP(tpc1); v0mi->Update(primvertex); } } } } //------------------------------------------------------------------------ void AliITStrackerMI::BuildMaterialLUT(TString material) { //-------------------------------------------------------------------- // Fill a look-up table with mean material //-------------------------------------------------------------------- Int_t n=1000; Double_t mparam[7]; Double_t point1[3],point2[3]; Double_t phi,cosphi,sinphi,z; // 0-5 layers, 6 pipe, 7-8 shields Double_t rmin[9]={ 3.5, 5.5,13.0,22.0,35.0,41.0, 2.0, 8.0,25.0}; Double_t rmax[9]={ 5.5, 8.0,17.0,26.0,41.0,47.0, 3.0,10.5,30.0}; Int_t ifirst=0,ilast=0; if(material.Contains("Pipe")) { ifirst=6; ilast=6; } else if(material.Contains("Shields")) { ifirst=7; ilast=8; } else if(material.Contains("Layers")) { ifirst=0; ilast=5; } else { Error("BuildMaterialLUT","Wrong layer name\n"); } for(Int_t imat=ifirst; imat<=ilast; imat++) { Double_t param[5]={0.,0.,0.,0.,0.}; for (Int_t i=0; i<n; i++) { phi = 2.*TMath::Pi()*gRandom->Rndm(); cosphi = TMath::Cos(phi); sinphi = TMath::Sin(phi); z = 14.*(-1.+2.*gRandom->Rndm()); // SPD barrel point1[0] = rmin[imat]*cosphi; point1[1] = rmin[imat]*sinphi; point1[2] = z; point2[0] = rmax[imat]*cosphi; point2[1] = rmax[imat]*sinphi; point2[2] = z; AliTracker::MeanMaterialBudget(point1,point2,mparam); for(Int_t j=0;j<5;j++) param[j]+=mparam[j]; } for(Int_t j=0;j<5;j++) param[j]/=(Float_t)n; if(imat<=5) { fxOverX0Layer[imat] = param[1]; fxTimesRhoLayer[imat] = param[0]*param[4]; } else if(imat==6) { fxOverX0Pipe = param[1]; fxTimesRhoPipe = param[0]*param[4]; } else if(imat==7) { fxOverX0Shield[0] = param[1]; fxTimesRhoShield[0] = param[0]*param[4]; } else if(imat==8) { fxOverX0Shield[1] = param[1]; fxTimesRhoShield[1] = param[0]*param[4]; } } /* printf("%s\n",material.Data()); printf("%f %f\n",fxOverX0Pipe,fxTimesRhoPipe); printf("%f %f\n",fxOverX0Shield[0],fxTimesRhoShield[0]); printf("%f %f\n",fxOverX0Shield[1],fxTimesRhoShield[1]); printf("%f %f\n",fxOverX0Layer[0],fxTimesRhoLayer[0]); printf("%f %f\n",fxOverX0Layer[1],fxTimesRhoLayer[1]); printf("%f %f\n",fxOverX0Layer[2],fxTimesRhoLayer[2]); printf("%f %f\n",fxOverX0Layer[3],fxTimesRhoLayer[3]); printf("%f %f\n",fxOverX0Layer[4],fxTimesRhoLayer[4]); printf("%f %f\n",fxOverX0Layer[5],fxTimesRhoLayer[5]); */ return; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::CorrectForPipeMaterial(AliITStrackMI *t, TString direction) { //------------------------------------------------------------------- // Propagate beyond beam pipe and correct for material // (material budget in different ways according to fUseTGeo value) //------------------------------------------------------------------- // Define budget mode: // 0: material from AliITSRecoParam (hard coded) // 1: material from TGeo in one step (on the fly) // 2: material from lut // 3: material from TGeo in one step (same for all hypotheses) Int_t mode; switch(fUseTGeo) { case 0: mode=0; break; case 1: mode=1; break; case 2: mode=2; break; case 3: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=1; } break; case 4: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=2; } break; default: mode=0; break; } if(fTrackingPhase.Contains("Default")) mode=0; Int_t index=fCurrentEsdTrack; Float_t dir = (direction.Contains("inward") ? 1. : -1.); Double_t rToGo=(dir>0 ? AliITSRecoParam::GetrInsidePipe() : AliITSRecoParam::GetrOutsidePipe()); Double_t xToGo; if (!t->GetLocalXat(rToGo,xToGo)) return 0; Double_t xOverX0,x0,lengthTimesMeanDensity; Bool_t anglecorr=kTRUE; switch(mode) { case 0: xOverX0 = AliITSRecoParam::GetdPipe(); x0 = AliITSRecoParam::GetX0Be(); lengthTimesMeanDensity = xOverX0*x0; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 1: if (!t->PropagateToTGeo(xToGo,1)) return 0; break; case 2: if(fxOverX0Pipe<0) BuildMaterialLUT("Pipe"); xOverX0 = fxOverX0Pipe; lengthTimesMeanDensity = fxTimesRhoPipe; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 3: if(!fxOverX0PipeTrks || index<0 || index>=fNtracks) Error("CorrectForPipeMaterial","Incorrect usage of UseTGeo option!\n"); if(fxOverX0PipeTrks[index]<0) { if (!t->PropagateToTGeo(xToGo,1,xOverX0,lengthTimesMeanDensity)) return 0; Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/ (1.-t->GetSnp()*t->GetSnp())); fxOverX0PipeTrks[index] = TMath::Abs(xOverX0)/angle; fxTimesRhoPipeTrks[index] = TMath::Abs(lengthTimesMeanDensity)/angle; return 1; } xOverX0 = fxOverX0PipeTrks[index]; lengthTimesMeanDensity = fxTimesRhoPipeTrks[index]; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; } return 1; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::CorrectForShieldMaterial(AliITStrackMI *t, TString shield, TString direction) { //------------------------------------------------------------------- // Propagate beyond SPD or SDD shield and correct for material // (material budget in different ways according to fUseTGeo value) //------------------------------------------------------------------- // Define budget mode: // 0: material from AliITSRecoParam (hard coded) // 1: material from TGeo in steps of X cm (on the fly) // X = AliITSRecoParam::GetStepSizeTGeo() // 2: material from lut // 3: material from TGeo in one step (same for all hypotheses) Int_t mode; switch(fUseTGeo) { case 0: mode=0; break; case 1: mode=1; break; case 2: mode=2; break; case 3: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=1; } break; case 4: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=2; } break; default: mode=0; break; } if(fTrackingPhase.Contains("Default")) mode=0; Float_t dir = (direction.Contains("inward") ? 1. : -1.); Double_t rToGo; Int_t shieldindex=0; if (shield.Contains("SDD")) { // SDDouter rToGo=(dir>0 ? AliITSRecoParam::GetrInsideShield(1) : AliITSRecoParam::GetrOutsideShield(1)); shieldindex=1; } else if (shield.Contains("SPD")) { // SPDouter rToGo=(dir>0 ? AliITSRecoParam::GetrInsideShield(0) : AliITSRecoParam::GetrOutsideShield(0)); shieldindex=0; } else { Error("CorrectForShieldMaterial"," Wrong shield name\n"); return 0; } Double_t xToGo; if (!t->GetLocalXat(rToGo,xToGo)) return 0; Int_t index=2*fCurrentEsdTrack+shieldindex; Double_t xOverX0,x0,lengthTimesMeanDensity; Bool_t anglecorr=kTRUE; Int_t nsteps=1; switch(mode) { case 0: xOverX0 = AliITSRecoParam::Getdshield(shieldindex); x0 = AliITSRecoParam::GetX0shield(shieldindex); lengthTimesMeanDensity = xOverX0*x0; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 1: nsteps= (Int_t)(TMath::Abs(t->GetX()-xToGo)/AliITSReconstructor::GetRecoParam()->GetStepSizeTGeo())+1; if (!t->PropagateToTGeo(xToGo,nsteps)) return 0; // cross the material and apply correction break; case 2: if(fxOverX0Shield[shieldindex]<0) BuildMaterialLUT("Shields"); xOverX0 = fxOverX0Shield[shieldindex]; lengthTimesMeanDensity = fxTimesRhoShield[shieldindex]; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 3: if(!fxOverX0ShieldTrks || index<0 || index>=2*fNtracks) Error("CorrectForShieldMaterial","Incorrect usage of UseTGeo option!\n"); if(fxOverX0ShieldTrks[index]<0) { if (!t->PropagateToTGeo(xToGo,1,xOverX0,lengthTimesMeanDensity)) return 0; Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/ (1.-t->GetSnp()*t->GetSnp())); fxOverX0ShieldTrks[index] = TMath::Abs(xOverX0)/angle; fxTimesRhoShieldTrks[index] = TMath::Abs(lengthTimesMeanDensity)/angle; return 1; } xOverX0 = fxOverX0ShieldTrks[index]; lengthTimesMeanDensity = fxTimesRhoShieldTrks[index]; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; } return 1; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::CorrectForLayerMaterial(AliITStrackMI *t, Int_t layerindex, Double_t oldGlobXYZ[3], TString direction) { //------------------------------------------------------------------- // Propagate beyond layer and correct for material // (material budget in different ways according to fUseTGeo value) //------------------------------------------------------------------- // Define budget mode: // 0: material from AliITSRecoParam (hard coded) // 1: material from TGeo in stepsof X cm (on the fly) // X = AliITSRecoParam::GetStepSizeTGeo() // 2: material from lut // 3: material from TGeo in one step (same for all hypotheses) Int_t mode; switch(fUseTGeo) { case 0: mode=0; break; case 1: mode=1; break; case 2: mode=2; break; case 3: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=1; } break; case 4: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=2; } break; default: mode=0; break; } if(fTrackingPhase.Contains("Default")) mode=0; Float_t dir = (direction.Contains("inward") ? 1. : -1.); Double_t r=fgLayers[layerindex].GetR(); Double_t deltar=(layerindex<2 ? 0.10*r : 0.05*r); Double_t rToGo=TMath::Sqrt(t->GetX()*t->GetX()+t->GetY()*t->GetY())-deltar*dir; Double_t xToGo; if (!t->GetLocalXat(rToGo,xToGo)) return 0; Int_t index=6*fCurrentEsdTrack+layerindex; Double_t xOverX0=0.0,x0=0.0,lengthTimesMeanDensity=0.0; Double_t mparam[7]; Bool_t anglecorr=kTRUE; Int_t nsteps=1; switch(mode) { case 0: xOverX0 = fgLayers[layerindex].GetThickness(t->GetY(),t->GetZ(),x0); lengthTimesMeanDensity = xOverX0*x0; // Bring the track beyond the material if (!t->Propagate(xToGo)) return 0; lengthTimesMeanDensity *= dir; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 1: Double_t rOld=TMath::Sqrt(oldGlobXYZ[0]*oldGlobXYZ[0]+oldGlobXYZ[1]*oldGlobXYZ[1]); Double_t xOld; if (!t->GetLocalXat(rOld,xOld)) return 0; if (!t->Propagate(xOld)) return 0; // back before material (no correction) nsteps = (Int_t)(TMath::Abs(xOld-xToGo)/AliITSReconstructor::GetRecoParam()->GetStepSizeTGeo())+1; if (!t->PropagateToTGeo(xToGo,nsteps)) return 0; // cross the material and apply correction break; case 2: if(fxOverX0Layer[layerindex]<0) BuildMaterialLUT("Layers"); xOverX0 = fxOverX0Layer[layerindex]; lengthTimesMeanDensity = fxTimesRhoLayer[layerindex]; // Bring the track beyond the material if (!t->Propagate(xToGo)) return 0; lengthTimesMeanDensity *= dir; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 3: if(!fxOverX0LayerTrks || index<0 || index>=6*fNtracks) Error("CorrectForLayerMaterial","Incorrect usage of UseTGeo option!\n"); // Bring the track beyond the material if (!t->Propagate(xToGo)) return 0; Double_t globXYZ[3]; if (!t->GetXYZ(globXYZ)) return 0; if (fxOverX0LayerTrks[index]<0) { AliTracker::MeanMaterialBudget(oldGlobXYZ,globXYZ,mparam); if(mparam[1]>900000) return 0; Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/ (1.-t->GetSnp()*t->GetSnp())); xOverX0=mparam[1]/angle; lengthTimesMeanDensity=mparam[0]*mparam[4]/angle; fxOverX0LayerTrks[index] = TMath::Abs(xOverX0); fxTimesRhoLayerTrks[index] = TMath::Abs(lengthTimesMeanDensity); } xOverX0 = fxOverX0LayerTrks[index]; lengthTimesMeanDensity = fxTimesRhoLayerTrks[index]; lengthTimesMeanDensity *= dir; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; } return 1; } //------------------------------------------------------------------------ void AliITStrackerMI::MakeTrksMaterialLUT(Int_t ntracks) { //----------------------------------------------------------------- // Initialize LUT for storing material for each prolonged track //----------------------------------------------------------------- fxOverX0PipeTrks = new Float_t[ntracks]; fxTimesRhoPipeTrks = new Float_t[ntracks]; fxOverX0ShieldTrks = new Float_t[ntracks*2]; fxTimesRhoShieldTrks = new Float_t[ntracks*2]; fxOverX0LayerTrks = new Float_t[ntracks*6]; fxTimesRhoLayerTrks = new Float_t[ntracks*6]; for(Int_t i=0; i<ntracks; i++) { fxOverX0PipeTrks[i] = -1.; fxTimesRhoPipeTrks[i] = -1.; } for(Int_t j=0; j<ntracks*2; j++) { fxOverX0ShieldTrks[j] = -1.; fxTimesRhoShieldTrks[j] = -1.; } for(Int_t k=0; k<ntracks*6; k++) { fxOverX0LayerTrks[k] = -1.; fxTimesRhoLayerTrks[k] = -1.; } fNtracks = ntracks; return; } //------------------------------------------------------------------------ void AliITStrackerMI::DeleteTrksMaterialLUT() { //----------------------------------------------------------------- // Delete LUT for storing material for each prolonged track //----------------------------------------------------------------- if(fxOverX0PipeTrks) { delete [] fxOverX0PipeTrks; fxOverX0PipeTrks = 0; } if(fxOverX0ShieldTrks) { delete [] fxOverX0ShieldTrks; fxOverX0ShieldTrks = 0; } if(fxOverX0LayerTrks) { delete [] fxOverX0LayerTrks; fxOverX0LayerTrks = 0; } if(fxTimesRhoPipeTrks) { delete [] fxTimesRhoPipeTrks; fxTimesRhoPipeTrks = 0; } if(fxTimesRhoShieldTrks) { delete [] fxTimesRhoShieldTrks; fxTimesRhoShieldTrks = 0; } if(fxTimesRhoLayerTrks) { delete [] fxTimesRhoLayerTrks; fxTimesRhoLayerTrks = 0; } return; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::CheckSkipLayer(AliITStrackMI *track, Int_t ilayer,Int_t idet) const { //----------------------------------------------------------------- // This method is used to decide whether to allow a prolongation // without clusters, because we want to skip the layer. // In this case the return value is > 0: // return 1: the user requested to skip a layer // return 2: track outside z acceptance of SSD/SDD and will cross both SPD //----------------------------------------------------------------- if (AliITSReconstructor::GetRecoParam()->GetLayersToSkip(ilayer)) return 1; if (idet<0 && ilayer>1 && AliITSReconstructor::GetRecoParam()->GetExtendedEtaAcceptance()) { // check if track will cross SPD outer layer Double_t phiAtSPD2,zAtSPD2; if (track->GetPhiZat(fgLayers[1].GetR(),phiAtSPD2,zAtSPD2)) { if (TMath::Abs(zAtSPD2)<2.*AliITSRecoParam::GetSPDdetzlength()) return 2; } } return 0; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::CheckDeadZone(AliITStrackMI *track, Int_t ilayer,Int_t idet, Double_t dz,Double_t dy, Bool_t noClusters) const { //----------------------------------------------------------------- // This method is used to decide whether to allow a prolongation // without clusters, because there is a dead zone in the road. // In this case the return value is > 0: // return 1: dead zone at z=0,+-7cm in SPD // return 2: all road is "bad" (dead or noisy) from the OCDB // return 3: something "bad" (dead or noisy) from the OCDB //----------------------------------------------------------------- // check dead zones at z=0,+-7cm in the SPD if (ilayer<2 && !AliITSReconstructor::GetRecoParam()->GetAddVirtualClustersInDeadZone()) { Double_t zmindead[3]={fSPDdetzcentre[0] + 0.5*AliITSRecoParam::GetSPDdetzlength(), fSPDdetzcentre[1] + 0.5*AliITSRecoParam::GetSPDdetzlength(), fSPDdetzcentre[2] + 0.5*AliITSRecoParam::GetSPDdetzlength()}; Double_t zmaxdead[3]={fSPDdetzcentre[1] - 0.5*AliITSRecoParam::GetSPDdetzlength(), fSPDdetzcentre[2] - 0.5*AliITSRecoParam::GetSPDdetzlength(), fSPDdetzcentre[3] - 0.5*AliITSRecoParam::GetSPDdetzlength()}; for (Int_t i=0; i<3; i++) if (track->GetZ()-dz<zmaxdead[i] && track->GetZ()+dz>zmindead[i]) { AliDebug(2,Form("crack SPD %d",ilayer)); return 1; } } // check bad zones from OCDB if (!AliITSReconstructor::GetRecoParam()->GetUseBadZonesFromOCDB()) return 0; if (idet<0) return 0; AliITSdetector &det=fgLayers[ilayer].GetDetector(idet); Int_t detType=-1; Float_t detSizeFactorX=0.0001,detSizeFactorZ=0.0001; if (ilayer==0 || ilayer==1) { // ---------- SPD detType = 0; } else if (ilayer==2 || ilayer==3) { // ---------- SDD detType = 1; detSizeFactorX *= 2.; } else if (ilayer==4 || ilayer==5) { // ---------- SSD detType = 2; } AliITSsegmentation *segm = (AliITSsegmentation*)fDetTypeRec->GetSegmentationModel(detType); if (detType==2) segm->SetLayer(ilayer+1); Float_t detSizeX = detSizeFactorX*segm->Dx(); Float_t detSizeZ = detSizeFactorZ*segm->Dz(); // check if the road overlaps with bad chips Float_t xloc,zloc; LocalModuleCoord(ilayer,idet,track,xloc,zloc); Float_t zlocmin = zloc-dz; Float_t zlocmax = zloc+dz; Float_t xlocmin = xloc-dy; Float_t xlocmax = xloc+dy; Int_t chipsInRoad[100]; // check if road goes out of detector Bool_t touchNeighbourDet=kFALSE; if (TMath::Abs(xlocmin)>0.5*detSizeX) {xlocmin=-0.5*detSizeX; touchNeighbourDet=kTRUE;} if (TMath::Abs(xlocmax)>0.5*detSizeX) {xlocmax=+0.5*detSizeX; touchNeighbourDet=kTRUE;} if (TMath::Abs(zlocmin)>0.5*detSizeZ) {zlocmin=-0.5*detSizeZ; touchNeighbourDet=kTRUE;} if (TMath::Abs(zlocmax)>0.5*detSizeZ) {zlocmax=+0.5*detSizeZ; touchNeighbourDet=kTRUE;} AliDebug(2,Form("layer %d det %d zmim zmax %f %f xmin xmax %f %f %f %f",ilayer,idet,zlocmin,zlocmax,xlocmin,xlocmax,detSizeZ,detSizeX)); // check if this detector is bad if (det.IsBad()) { AliDebug(2,Form("lay %d bad detector %d",ilayer,idet)); if(!touchNeighbourDet) { return 2; // all detectors in road are bad } else { return 3; // at least one is bad } } Int_t nChipsInRoad = segm->GetChipsInLocalWindow(chipsInRoad,zlocmin,zlocmax,xlocmin,xlocmax); AliDebug(2,Form("lay %d nChipsInRoad %d",ilayer,nChipsInRoad)); if (!nChipsInRoad) return 0; Bool_t anyBad=kFALSE,anyGood=kFALSE; for (Int_t iCh=0; iCh<nChipsInRoad; iCh++) { if (chipsInRoad[iCh]<0 || chipsInRoad[iCh]>det.GetNChips()-1) continue; AliDebug(2,Form(" chip %d bad %d",chipsInRoad[iCh],(Int_t)det.IsChipBad(chipsInRoad[iCh]))); if (det.IsChipBad(chipsInRoad[iCh])) { anyBad=kTRUE; } else { anyGood=kTRUE; } } if (!anyGood) { if(!touchNeighbourDet) { AliDebug(2,"all bad in road"); return 2; // all chips in road are bad } else { return 3; // at least a bad chip in road } } if (anyBad) { AliDebug(2,"at least a bad in road"); return 3; // at least a bad chip in road } if (!AliITSReconstructor::GetRecoParam()->GetUseSingleBadChannelsFromOCDB() || ilayer==4 || ilayer==5 // SSD || !noClusters) return 0; // There are no clusters in road: check if there is at least // a bad SPD pixel or SDD anode Int_t idetInITS=idet; for(Int_t l=0;l<ilayer;l++) idetInITS+=AliITSgeomTGeo::GetNLadders(l+1)*AliITSgeomTGeo::GetNDetectors(l+1); if (fITSChannelStatus->AnyBadInRoad(idetInITS,zlocmin,zlocmax,xlocmin,xlocmax)) { AliDebug(2,Form("Bad channel in det %d of layer %d\n",idet,ilayer)); return 3; } //if (fITSChannelStatus->FractionOfBadInRoad(idet,zlocmin,zlocmax,xlocmin,xlocmax) > AliITSReconstructor::GetRecoParam()->GetMinFractionOfBadInRoad()) return 3; return 0; } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::LocalModuleCoord(Int_t ilayer,Int_t idet, AliITStrackMI *track, Float_t &xloc,Float_t &zloc) const { //----------------------------------------------------------------- // Gives position of track in local module ref. frame //----------------------------------------------------------------- xloc=0.; zloc=0.; if(idet<0) return kFALSE; Int_t ndet=AliITSgeomTGeo::GetNDetectors(ilayer+1); // layers from 1 to 6 Int_t lad = Int_t(idet/ndet) + 1; Int_t det = idet - (lad-1)*ndet + 1; Double_t xyzGlob[3],xyzLoc[3]; AliITSdetector &detector = fgLayers[ilayer].GetDetector(idet); // take into account the misalignment: xyz at real detector plane if(!track->GetXYZAt(detector.GetRmisal(),GetBz(),xyzGlob)) return kFALSE; if(!AliITSgeomTGeo::GlobalToLocal(ilayer+1,lad,det,xyzGlob,xyzLoc)) return kFALSE; xloc = (Float_t)xyzLoc[0]; zloc = (Float_t)xyzLoc[2]; return kTRUE; } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::IsOKForPlaneEff(AliITStrackMI* track, const Int_t *clusters, Int_t ilayer) const { // // Method to be optimized further: // Aim: decide whether a track can be used for PlaneEff evaluation // the decision is taken based on the track quality at the layer under study // no information on the clusters on this layer has to be used // The criterium is to reject tracks at boundaries between basic block (e.g. SPD chip) // the cut is done on number of sigmas from the boundaries // // Input: Actual track, layer [0,5] under study // Output: none // Return: kTRUE if this is a good track // // it will apply a pre-selection to obtain good quality tracks. // Here also you will have the possibility to put a control on the // impact point of the track on the basic block, in order to exclude border regions // this will be done by calling a proper method of the AliITSPlaneEff class. // // input: AliITStrackMI* track, ilayer= layer number [0,5] // return: Bool_t -> kTRUE if usable track, kFALSE if not usable. // Int_t index[AliITSgeomTGeo::kNLayers]; Int_t k; for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1; // for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) { index[k]=clusters[k]; } if(!fPlaneEff) {AliWarning("IsOKForPlaneEff: null pointer to AliITSPlaneEff"); return kFALSE;} AliITSlayer &layer=fgLayers[ilayer]; Double_t r=layer.GetR(); AliITStrackMI tmp(*track); // require a minimal number of cluster in other layers and eventually clusters in closest layers Int_t ncl=0; for(Int_t lay=AliITSgeomTGeo::kNLayers-1;lay>ilayer;lay--) { AliDebug(2,Form("trak=%d lay=%d ; index=%d ESD label= %d",tmp.GetLabel(),lay, tmp.GetClIndex(lay),((AliESDtrack*)tmp.GetESDtrack())->GetLabel())) ; if (tmp.GetClIndex(lay)>0) ncl++; } Bool_t nextout = kFALSE; if(ilayer==AliITSgeomTGeo::kNLayers-1) nextout=kTRUE; // you are already on the outermost layer else nextout = ((tmp.GetClIndex(ilayer+1)>0)? kTRUE : kFALSE ); Bool_t nextin = kFALSE; if(ilayer==0) nextin=kTRUE; // you are already on the innermost layer else nextin = ((index[ilayer-1]>=0)? kTRUE : kFALSE ); if(ncl<AliITSgeomTGeo::kNLayers-(ilayer+1)-AliITSReconstructor::GetRecoParam()->GetMaxMissingClustersPlaneEff()) return kFALSE; if(AliITSReconstructor::GetRecoParam()->GetRequireClusterInOuterLayerPlaneEff() && !nextout) return kFALSE; if(AliITSReconstructor::GetRecoParam()->GetRequireClusterInInnerLayerPlaneEff() && !nextin) return kFALSE; if(tmp.Pt() < AliITSReconstructor::GetRecoParam()->GetMinPtPlaneEff()) return kFALSE; // if(AliITSReconstructor::GetRecoParam()->GetOnlyConstraintPlaneEff() && !tmp.GetConstrain()) return kFALSE; // detector number Double_t phi,z; if (!tmp.GetPhiZat(r,phi,z)) return kFALSE; Int_t idet=layer.FindDetectorIndex(phi,z); if(idet<0) { AliInfo(Form("cannot find detector")); return kFALSE;} // here check if it has good Chi Square. //propagate to the intersection with the detector plane const AliITSdetector &det=layer.GetDetector(idet); if (!tmp.Propagate(det.GetPhi(),det.GetR())) return kFALSE; Float_t locx; // Float_t locz; // if(!LocalModuleCoord(ilayer,idet,&tmp,locx,locz)) return kFALSE; UInt_t key=fPlaneEff->GetKeyFromDetLocCoord(ilayer,idet,locx,locz); if(key>fPlaneEff->Nblock()) return kFALSE; Float_t blockXmn,blockXmx,blockZmn,blockZmx; if (!fPlaneEff->GetBlockBoundaries(key,blockXmn,blockXmx,blockZmn,blockZmx)) return kFALSE; //*************** // DEFINITION OF SEARCH ROAD FOR accepting a track // //For the time being they are hard-wired, later on from AliITSRecoParam // Double_t nsigx=AliITSRecoParam::GetNSigXFarFromBoundary(); // Double_t nsigz=AliITSRecoParam::GetNSigZFarFromBoundary(); Double_t nsigz=4; Double_t nsigx=4; Double_t dx=nsigx*TMath::Sqrt(tmp.GetSigmaY2()); // those are precisions in the tracking reference system Double_t dz=nsigz*TMath::Sqrt(tmp.GetSigmaZ2()); // Use it also for the module reference system, as it is // done for RecPoints // exclude tracks at boundary between detectors //Double_t boundaryWidth=AliITSRecoParam::GetBoundaryWidthPlaneEff(); Double_t boundaryWidth=0; // for the time being hard-wired, later on from AliITSRecoParam AliDebug(2,Form("Tracking: track impact x=%f, y=%f, z=%f",tmp.GetX(), tmp.GetY(), tmp.GetZ())); AliDebug(2,Form("Local: track impact x=%f, z=%f",locx,locz)); AliDebug(2,Form("Search Road. Tracking: dy=%f , dz=%f",dx,dz)); if ( (locx-dx < blockXmn+boundaryWidth) || (locx+dx > blockXmx-boundaryWidth) || (locz-dz < blockZmn+boundaryWidth) || (locz+dz > blockZmx-boundaryWidth) ) return kFALSE; return kTRUE; } //------------------------------------------------------------------------ void AliITStrackerMI::UseTrackForPlaneEff(AliITStrackMI* track, Int_t ilayer) { // // This Method has to be optimized! For the time-being it uses the same criteria // as those used in the search of extra clusters for overlapping modules. // // Method Purpose: estabilish whether a track has produced a recpoint or not // in the layer under study (For Plane efficiency) // // inputs: AliITStrackMI* track (pointer to a usable track) // outputs: none // side effects: update (by 1 count) the Plane Efficiency statistics of the basic block // traversed by this very track. In details: // - if a cluster can be associated to the track then call // AliITSPlaneEff::UpDatePlaneEff(key,kTRUE); // - if not, the AliITSPlaneEff::UpDatePlaneEff(key,kFALSE) is called // if(!fPlaneEff) {AliWarning("UseTrackForPlaneEff: null pointer to AliITSPlaneEff"); return;} AliITSlayer &layer=fgLayers[ilayer]; Double_t r=layer.GetR(); AliITStrackMI tmp(*track); // detector number Double_t phi,z; if (!tmp.GetPhiZat(r,phi,z)) return; Int_t idet=layer.FindDetectorIndex(phi,z); if(idet<0) { AliInfo(Form("cannot find detector")); return;} //propagate to the intersection with the detector plane const AliITSdetector &det=layer.GetDetector(idet); if (!tmp.Propagate(det.GetPhi(),det.GetR())) return; //*************** // DEFINITION OF SEARCH ROAD FOR CLUSTERS SELECTION // Double_t dz=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadZ()* TMath::Sqrt(tmp.GetSigmaZ2() + AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer)); Double_t dy=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadY()* TMath::Sqrt(tmp.GetSigmaY2() + AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer)); // road in global (rphi,z) [i.e. in tracking ref. system] Double_t zmin = tmp.GetZ() - dz; Double_t zmax = tmp.GetZ() + dz; Double_t ymin = tmp.GetY() + r*det.GetPhi() - dy; Double_t ymax = tmp.GetY() + r*det.GetPhi() + dy; // select clusters in road layer.SelectClusters(zmin,zmax,ymin,ymax); // Define criteria for track-cluster association Double_t msz = tmp.GetSigmaZ2() + AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer); Double_t msy = tmp.GetSigmaY2() + AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer); if (tmp.GetConstrain()) { msz *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadZC(); msy *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadYC(); } else { msz *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadZNonC(); msy *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadYNonC(); } msz = 1./msz; // 1/RoadZ^2 msy = 1./msy; // 1/RoadY^2 // const AliITSRecPoint *cl=0; Int_t clidx=-1, ci=-1; Int_t idetc=-1; Double_t chi2trkcl=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2(); //Double_t tolerance=0.2; /*while ((cl=layer.GetNextCluster(clidx))!=0) { idetc = cl->GetDetectorIndex(); if(idet!=idetc) continue; //Int_t ilay = cl->GetLayer(); if (TMath::Abs(tmp.GetZ() - cl->GetZ()) > tolerance) continue; if (TMath::Abs(tmp.GetY() - cl->GetY()) > tolerance) continue; Double_t chi2=tmp.GetPredictedChi2(cl); if (chi2<chi2trkcl) { chi2trkcl=chi2; ci=clidx; } }*/ Float_t locx; // Float_t locz; // if(!LocalModuleCoord(ilayer,idet,&tmp,locx,locz)) return; // AliDebug(2,Form("ilayer= %d, idet=%d, x= %f, z=%f",ilayer,idet,locx,locz)); UInt_t key=fPlaneEff->GetKeyFromDetLocCoord(ilayer,idet,locx,locz); if(key>fPlaneEff->Nblock()) return; Bool_t found=kFALSE; //if (ci>=0) { Double_t chi2; while ((cl=layer.GetNextCluster(clidx))!=0) { idetc = cl->GetDetectorIndex(); if(idet!=idetc) continue; // here real control to see whether the cluster can be associated to the track. // cluster not associated to track if ( (tmp.GetZ()-cl->GetZ())*(tmp.GetZ()-cl->GetZ())*msz + (tmp.GetY()-cl->GetY())*(tmp.GetY()-cl->GetY())*msy > 1. ) continue; // calculate track-clusters chi2 chi2 = GetPredictedChi2MI(&tmp,cl,ilayer); // note that this method change track tmp // in particular, the error associated to the cluster //Double_t chi2 = tmp.GetPredictedChi(cl); // this method does not change track tmp // chi2 cut if (chi2 > AliITSReconstructor::GetRecoParam()->GetMaxChi2s(ilayer)) continue; found=kTRUE; if (chi2<chi2trkcl) { chi2trkcl=chi2; ci=clidx; } // this just to trace which cluster is selected // track->SetExtraCluster(ilayer,(ilayer<<28)+ci); // track->SetExtraModule(ilayer,idetExtra); } if(!fPlaneEff->UpDatePlaneEff(found,key)) AliWarning(Form("UseTrackForPlaneEff: cannot UpDate PlaneEff for key=%d",key)); if(fPlaneEff->GetCreateHistos()&& AliITSReconstructor::GetRecoParam()->GetHistoPlaneEff()) { Float_t tr[4]={99999.,99999.,9999.,9999.}; // initialize to high values Float_t clu[4]={-99999.,-99999.,9999.,9999.}; // (in some cases GetCov fails) Int_t cltype[2]={-999,-999}; tr[0]=locx; tr[1]=locz; tr[2]=TMath::Sqrt(tmp.GetSigmaY2()); // those are precisions in the tracking reference system tr[3]=TMath::Sqrt(tmp.GetSigmaZ2()); // Use it also for the module reference system, as it is if (found){ clu[0]=layer.GetCluster(ci)->GetDetLocalX(); clu[1]=layer.GetCluster(ci)->GetDetLocalZ(); cltype[0]=layer.GetCluster(ci)->GetNy(); cltype[1]=layer.GetCluster(ci)->GetNz(); // Without the following 6 lines you would retrieve the nominal error of a cluster (e.g. for the SPD: // X->50/sqrt(12)=14 micron Z->450/sqrt(12)= 120 micron) // Within AliTrackerMI/AliTrackMI the error on the cluster is associated to the AliITStrackMI (fSigmaY,Z) // It is computed properly by calling the method // AliITStrackerMI::GetPredictedChi2MI(AliITStrackMI* track, const AliITSRecPoint *cluster,Int_t layer) // T //Double_t x=0.5*(tmp.GetX()+layer.GetCluster(ci)->GetX()); // Take into account the mis-alignment //if (tmp.PropagateTo(x,0.,0.)) { chi2=GetPredictedChi2MI(&tmp,layer.GetCluster(ci),ilayer); AliCluster c(*layer.GetCluster(ci)); c.SetSigmaY2(tmp.GetSigmaY(ilayer)*tmp.GetSigmaY(ilayer)); c.SetSigmaZ2(tmp.GetSigmaZ(ilayer)*tmp.GetSigmaZ(ilayer)); //if (layer.GetCluster(ci)->GetGlobalCov(cov)) // by using this, instead, you got nominal cluster errors clu[2]=TMath::Sqrt(c.GetSigmaY2()); clu[3]=TMath::Sqrt(c.GetSigmaZ2()); //} } fPlaneEff->FillHistos(key,found,tr,clu,cltype); } return; } bug fix (Savannah bug 45461) /************************************************************************** * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------- // Implementation of the ITS tracker class // It reads AliITSRecPoint clusters and creates AliITStrackMI tracks // and fills with them the ESD // Origin: Marian Ivanov, CERN, Marian.Ivanov@cern.ch // Current support and development: // Andrea Dainese, andrea.dainese@lnl.infn.it // dE/dx analysis by: Boris Batyunya, JINR, Boris.Batiounia@cern.ch // Params moved to AliITSRecoParam by: Andrea Dainese, INFN // Material budget from TGeo by: Ludovic Gaudichet & Andrea Dainese, INFN //------------------------------------------------------------------------- #include <TMatrixD.h> #include <TTree.h> #include <TTreeStream.h> #include <TDatabasePDG.h> #include <TString.h> #include <TRandom.h> #include "AliLog.h" #include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliESDVertex.h" #include "AliV0.h" #include "AliHelix.h" #include "AliITSRecPoint.h" #include "AliITSgeomTGeo.h" #include "AliITSReconstructor.h" #include "AliTrackPointArray.h" #include "AliAlignObj.h" #include "AliITSClusterParam.h" #include "AliCDBManager.h" #include "AliCDBEntry.h" #include "AliITSsegmentation.h" #include "AliITSCalibration.h" #include "AliITSCalibrationSPD.h" #include "AliITSCalibrationSDD.h" #include "AliITSCalibrationSSD.h" #include "AliITSPlaneEff.h" #include "AliITSPlaneEffSPD.h" #include "AliITSPlaneEffSDD.h" #include "AliITSPlaneEffSSD.h" #include "AliITStrackerMI.h" ClassImp(AliITStrackerMI) AliITStrackerMI::AliITSlayer AliITStrackerMI::fgLayers[AliITSgeomTGeo::kNLayers]; // ITS layers AliITStrackerMI::AliITStrackerMI():AliTracker(), fI(0), fBestTrack(), fTrackToFollow(), fTrackHypothesys(), fBestHypothesys(), fOriginal(), fCurrentEsdTrack(), fPass(0), fAfterV0(kFALSE), fLastLayerToTrackTo(0), fCoefficients(0), fEsd(0), fTrackingPhase("Default"), fUseTGeo(3), fNtracks(0), fxOverX0Pipe(-1.), fxTimesRhoPipe(-1.), fxOverX0PipeTrks(0), fxTimesRhoPipeTrks(0), fxOverX0ShieldTrks(0), fxTimesRhoShieldTrks(0), fxOverX0LayerTrks(0), fxTimesRhoLayerTrks(0), fDebugStreamer(0), fITSChannelStatus(0), fDetTypeRec(0), fPlaneEff(0) { //Default constructor Int_t i; for(i=0;i<4;i++) fSPDdetzcentre[i]=0.; for(i=0;i<2;i++) {fxOverX0Shield[i]=-1.;fxTimesRhoShield[i]=-1.;} for(i=0;i<6;i++) {fxOverX0Layer[i]=-1.;fxTimesRhoLayer[i]=-1.;} } //------------------------------------------------------------------------ AliITStrackerMI::AliITStrackerMI(const Char_t *geom) : AliTracker(), fI(AliITSgeomTGeo::GetNLayers()), fBestTrack(), fTrackToFollow(), fTrackHypothesys(), fBestHypothesys(), fOriginal(), fCurrentEsdTrack(), fPass(0), fAfterV0(kFALSE), fLastLayerToTrackTo(AliITSRecoParam::GetLastLayerToTrackTo()), fCoefficients(0), fEsd(0), fTrackingPhase("Default"), fUseTGeo(3), fNtracks(0), fxOverX0Pipe(-1.), fxTimesRhoPipe(-1.), fxOverX0PipeTrks(0), fxTimesRhoPipeTrks(0), fxOverX0ShieldTrks(0), fxTimesRhoShieldTrks(0), fxOverX0LayerTrks(0), fxTimesRhoLayerTrks(0), fDebugStreamer(0), fITSChannelStatus(0), fDetTypeRec(0), fPlaneEff(0) { //-------------------------------------------------------------------- //This is the AliITStrackerMI constructor //-------------------------------------------------------------------- if (geom) { AliWarning("\"geom\" is actually a dummy argument !"); } fCoefficients = 0; fAfterV0 = kFALSE; for (Int_t i=1; i<AliITSgeomTGeo::GetNLayers()+1; i++) { Int_t nlad=AliITSgeomTGeo::GetNLadders(i); Int_t ndet=AliITSgeomTGeo::GetNDetectors(i); Double_t xyz[3], &x=xyz[0], &y=xyz[1], &z=xyz[2]; AliITSgeomTGeo::GetOrigTranslation(i,1,1,xyz); Double_t poff=TMath::ATan2(y,x); Double_t zoff=z; Double_t r=TMath::Sqrt(x*x + y*y); AliITSgeomTGeo::GetOrigTranslation(i,1,2,xyz); r += TMath::Sqrt(x*x + y*y); AliITSgeomTGeo::GetOrigTranslation(i,2,1,xyz); r += TMath::Sqrt(x*x + y*y); AliITSgeomTGeo::GetOrigTranslation(i,2,2,xyz); r += TMath::Sqrt(x*x + y*y); r*=0.25; new (fgLayers+i-1) AliITSlayer(r,poff,zoff,nlad,ndet); for (Int_t j=1; j<nlad+1; j++) { for (Int_t k=1; k<ndet+1; k++) { //Fill this layer with detectors TGeoHMatrix m; AliITSgeomTGeo::GetOrigMatrix(i,j,k,m); const TGeoHMatrix *tm=AliITSgeomTGeo::GetTracking2LocalMatrix(i,j,k); m.Multiply(tm); Double_t txyz[3]={0.}; xyz[0]=0.;xyz[1]=0.;xyz[2]=0.; m.LocalToMaster(txyz,xyz); r=TMath::Sqrt(xyz[0]*xyz[0] + xyz[1]*xyz[1]); Double_t phi=TMath::ATan2(xyz[1],xyz[0]); if (phi<0) phi+=TMath::TwoPi(); else if (phi>=TMath::TwoPi()) phi-=TMath::TwoPi(); AliITSdetector &det=fgLayers[i-1].GetDetector((j-1)*ndet + k-1); new(&det) AliITSdetector(r,phi); // compute the real radius (with misalignment) TGeoHMatrix mmisal(*(AliITSgeomTGeo::GetMatrix(i,j,k))); mmisal.Multiply(tm); xyz[0]=0.;xyz[1]=0.;xyz[2]=0.; mmisal.LocalToMaster(txyz,xyz); Double_t rmisal=TMath::Sqrt(xyz[0]*xyz[0] + xyz[1]*xyz[1]); det.SetRmisal(rmisal); } // end loop on detectors } // end loop on ladders } // end loop on layers fI=AliITSgeomTGeo::GetNLayers(); fPass=0; fConstraint[0]=1; fConstraint[1]=0; Double_t xyzVtx[]={AliITSReconstructor::GetRecoParam()->GetXVdef(), AliITSReconstructor::GetRecoParam()->GetYVdef(), AliITSReconstructor::GetRecoParam()->GetZVdef()}; Double_t ersVtx[]={AliITSReconstructor::GetRecoParam()->GetSigmaXVdef(), AliITSReconstructor::GetRecoParam()->GetSigmaYVdef(), AliITSReconstructor::GetRecoParam()->GetSigmaZVdef()}; SetVertex(xyzVtx,ersVtx); for (Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) fLayersNotToSkip[i]=AliITSRecoParam::GetLayersNotToSkip(i); fLastLayerToTrackTo=AliITSRecoParam::GetLastLayerToTrackTo(); for (Int_t i=0;i<100000;i++){ fBestTrackIndex[i]=0; } // store positions of centre of SPD modules (in z) Double_t tr[3]; AliITSgeomTGeo::GetTranslation(1,1,1,tr); fSPDdetzcentre[0] = tr[2]; AliITSgeomTGeo::GetTranslation(1,1,2,tr); fSPDdetzcentre[1] = tr[2]; AliITSgeomTGeo::GetTranslation(1,1,3,tr); fSPDdetzcentre[2] = tr[2]; AliITSgeomTGeo::GetTranslation(1,1,4,tr); fSPDdetzcentre[3] = tr[2]; fUseTGeo = AliITSReconstructor::GetRecoParam()->GetUseTGeoInTracker(); if(AliITSReconstructor::GetRecoParam()->GetExtendedEtaAcceptance() && fUseTGeo!=1 && fUseTGeo!=3) { AliWarning("fUseTGeo changed to 3 because fExtendedEtaAcceptance is kTRUE"); fUseTGeo = 3; } for(Int_t i=0;i<2;i++) {fxOverX0Shield[i]=-1.;fxTimesRhoShield[i]=-1.;} for(Int_t i=0;i<6;i++) {fxOverX0Layer[i]=-1.;fxTimesRhoLayer[i]=-1.;} fDebugStreamer = new TTreeSRedirector("ITSdebug.root"); // only for plane efficiency evaluation if (AliITSReconstructor::GetRecoParam()->GetComputePlaneEff()) { Int_t iplane=AliITSReconstructor::GetRecoParam()->GetIPlanePlaneEff(); if(AliITSReconstructor::GetRecoParam()->GetLayersToSkip(iplane)) AliWarning(Form("Evaluation of Plane Eff for layer %d will be attempted without removing it from tracker",iplane)); if (iplane<2) fPlaneEff = new AliITSPlaneEffSPD(); else if (iplane<4) fPlaneEff = new AliITSPlaneEffSDD(); else fPlaneEff = new AliITSPlaneEffSSD(); if(AliITSReconstructor::GetRecoParam()->GetReadPlaneEffFromOCDB()) if(!fPlaneEff->ReadFromCDB()) {AliWarning("AliITStrackerMI reading of AliITSPlaneEff from OCDB failed") ;} if(AliITSReconstructor::GetRecoParam()->GetHistoPlaneEff()) fPlaneEff->SetCreateHistos(kTRUE); } } //------------------------------------------------------------------------ AliITStrackerMI::AliITStrackerMI(const AliITStrackerMI &tracker):AliTracker(tracker), fI(tracker.fI), fBestTrack(tracker.fBestTrack), fTrackToFollow(tracker.fTrackToFollow), fTrackHypothesys(tracker.fTrackHypothesys), fBestHypothesys(tracker.fBestHypothesys), fOriginal(tracker.fOriginal), fCurrentEsdTrack(tracker.fCurrentEsdTrack), fPass(tracker.fPass), fAfterV0(tracker.fAfterV0), fLastLayerToTrackTo(tracker.fLastLayerToTrackTo), fCoefficients(tracker.fCoefficients), fEsd(tracker.fEsd), fTrackingPhase(tracker.fTrackingPhase), fUseTGeo(tracker.fUseTGeo), fNtracks(tracker.fNtracks), fxOverX0Pipe(tracker.fxOverX0Pipe), fxTimesRhoPipe(tracker.fxTimesRhoPipe), fxOverX0PipeTrks(0), fxTimesRhoPipeTrks(0), fxOverX0ShieldTrks(0), fxTimesRhoShieldTrks(0), fxOverX0LayerTrks(0), fxTimesRhoLayerTrks(0), fDebugStreamer(tracker.fDebugStreamer), fITSChannelStatus(tracker.fITSChannelStatus), fDetTypeRec(tracker.fDetTypeRec), fPlaneEff(tracker.fPlaneEff) { //Copy constructor Int_t i; for(i=0;i<4;i++) { fSPDdetzcentre[i]=tracker.fSPDdetzcentre[i]; } for(i=0;i<6;i++) { fxOverX0Layer[i]=tracker.fxOverX0Layer[i]; fxTimesRhoLayer[i]=tracker.fxTimesRhoLayer[i]; } for(i=0;i<2;i++) { fxOverX0Shield[i]=tracker.fxOverX0Shield[i]; fxTimesRhoShield[i]=tracker.fxTimesRhoShield[i]; } } //------------------------------------------------------------------------ AliITStrackerMI & AliITStrackerMI::operator=(const AliITStrackerMI &tracker){ //Assignment operator this->~AliITStrackerMI(); new(this) AliITStrackerMI(tracker); return *this; } //------------------------------------------------------------------------ AliITStrackerMI::~AliITStrackerMI() { // //destructor // if (fCoefficients) delete [] fCoefficients; DeleteTrksMaterialLUT(); if (fDebugStreamer) { //fDebugStreamer->Close(); delete fDebugStreamer; } if(fITSChannelStatus) delete fITSChannelStatus; if(fPlaneEff) delete fPlaneEff; } //------------------------------------------------------------------------ void AliITStrackerMI::SetLayersNotToSkip(Int_t *l) { //-------------------------------------------------------------------- //This function set masks of the layers which must be not skipped //-------------------------------------------------------------------- for (Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) fLayersNotToSkip[i]=l[i]; } //------------------------------------------------------------------------ void AliITStrackerMI::ReadBadFromDetTypeRec() { //-------------------------------------------------------------------- //This function read ITS bad detectors, chips, channels from AliITSDetTypeRec //i.e. from OCDB //-------------------------------------------------------------------- if(!AliITSReconstructor::GetRecoParam()->GetUseBadZonesFromOCDB()) return; Info("ReadBadFromDetTypeRec","Reading info about bad ITS detectors and channels"); if(!fDetTypeRec) Error("ReadBadFromDetTypeRec","AliITSDetTypeRec nof found!\n"); // ITS channels map if(fITSChannelStatus) delete fITSChannelStatus; fITSChannelStatus = new AliITSChannelStatus(fDetTypeRec); // ITS detectors and chips Int_t i=0,j=0,k=0,ndet=0; for (i=1; i<AliITSgeomTGeo::GetNLayers()+1; i++) { Int_t nBadDetsPerLayer=0; ndet=AliITSgeomTGeo::GetNDetectors(i); for (j=1; j<AliITSgeomTGeo::GetNLadders(i)+1; j++) { for (k=1; k<ndet+1; k++) { AliITSdetector &det=fgLayers[i-1].GetDetector((j-1)*ndet + k-1); det.ReadBadDetectorAndChips(i-1,(j-1)*ndet + k-1,fDetTypeRec); if(det.IsBad()) {nBadDetsPerLayer++;} } // end loop on detectors } // end loop on ladders Info("ReadBadFromDetTypeRec",Form("Layer %d: %d bad out of %d",i-1,nBadDetsPerLayer,ndet*AliITSgeomTGeo::GetNLadders(i))); } // end loop on layers return; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::LoadClusters(TTree *cTree) { //-------------------------------------------------------------------- //This function loads ITS clusters //-------------------------------------------------------------------- TBranch *branch=cTree->GetBranch("ITSRecPoints"); if (!branch) { Error("LoadClusters"," can't get the branch !\n"); return 1; } static TClonesArray dummy("AliITSRecPoint",10000), *clusters=&dummy; branch->SetAddress(&clusters); Int_t i=0,j=0,ndet=0; Int_t detector=0; for (i=0; i<AliITSgeomTGeo::GetNLayers(); i++) { ndet=fgLayers[i].GetNdetectors(); Int_t jmax = j + fgLayers[i].GetNladders()*ndet; for (; j<jmax; j++) { if (!cTree->GetEvent(j)) continue; Int_t ncl=clusters->GetEntriesFast(); SignDeltas(clusters,GetZ()); while (ncl--) { AliITSRecPoint *c=(AliITSRecPoint*)clusters->UncheckedAt(ncl); detector=c->GetDetectorIndex(); if (!c->Misalign()) AliWarning("Can't misalign this cluster !"); fgLayers[i].InsertCluster(new AliITSRecPoint(*c)); } clusters->Delete(); // add dead zone "virtual" cluster in SPD, if there is a cluster within // zwindow cm from the dead zone if (i<2 && AliITSReconstructor::GetRecoParam()->GetAddVirtualClustersInDeadZone()) { for (Float_t xdead = 0; xdead < AliITSRecoParam::GetSPDdetxlength(); xdead += (i+1.)*AliITSReconstructor::GetRecoParam()->GetXPassDeadZoneHits()) { Int_t lab[4] = {0,0,0,detector}; Int_t info[3] = {0,0,i}; Float_t q = 0.; // this identifies virtual clusters Float_t hit[5] = {xdead, 0., AliITSReconstructor::GetRecoParam()->GetSigmaXDeadZoneHit2(), AliITSReconstructor::GetRecoParam()->GetSigmaZDeadZoneHit2(), q}; Bool_t local = kTRUE; Double_t zwindow = AliITSReconstructor::GetRecoParam()->GetZWindowDeadZone(); hit[1] = fSPDdetzcentre[0]+0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); hit[1] = fSPDdetzcentre[1]-0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); hit[1] = fSPDdetzcentre[1]+0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); hit[1] = fSPDdetzcentre[2]-0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); hit[1] = fSPDdetzcentre[2]+0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); hit[1] = fSPDdetzcentre[3]-0.5*AliITSRecoParam::GetSPDdetzlength(); if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local)); } } // "virtual" clusters in SPD } // fgLayers[i].ResetRoad(); //road defined by the cluster density fgLayers[i].SortClusters(); } dummy.Clear(); return 0; } //------------------------------------------------------------------------ void AliITStrackerMI::UnloadClusters() { //-------------------------------------------------------------------- //This function unloads ITS clusters //-------------------------------------------------------------------- for (Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) fgLayers[i].ResetClusters(); } //------------------------------------------------------------------------ void AliITStrackerMI::FillClusterArray(TObjArray* array) const { //-------------------------------------------------------------------- // Publishes all pointers to clusters known to the tracker into the // passed object array. // The ownership is not transfered - the caller is not expected to delete // the clusters. //-------------------------------------------------------------------- for(Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) { for(Int_t icl=0; icl<fgLayers[i].GetNumberOfClusters(); icl++) { AliCluster *cl = (AliCluster*)fgLayers[i].GetCluster(icl); array->AddLast(cl); } } return; } //------------------------------------------------------------------------ static Int_t CorrectForTPCtoITSDeadZoneMaterial(AliITStrackMI *t) { //-------------------------------------------------------------------- // Correction for the material between the TPC and the ITS //-------------------------------------------------------------------- if (t->GetX() > AliITSRecoParam::Getriw()) { // inward direction if (!t->PropagateToTGeo(AliITSRecoParam::Getriw(),1)) return 0;// TPC inner wall if (!t->PropagateToTGeo(AliITSRecoParam::Getrcd(),1)) return 0;// TPC central drum if (!t->PropagateToTGeo(AliITSRecoParam::Getrs(),1)) return 0;// ITS screen } else if (t->GetX() < AliITSRecoParam::Getrs()) { // outward direction if (!t->PropagateToTGeo(AliITSRecoParam::Getrs(),1)) return 0;// ITS screen if (!t->PropagateToTGeo(AliITSRecoParam::Getrcd(),1)) return 0;// TPC central drum if (!t->PropagateToTGeo(AliITSRecoParam::Getriw()+0.001,1)) return 0;// TPC inner wall } else { Error("CorrectForTPCtoITSDeadZoneMaterial","Track is already in the dead zone !"); return 0; } return 1; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::Clusters2Tracks(AliESDEvent *event) { //-------------------------------------------------------------------- // This functions reconstructs ITS tracks // The clusters must be already loaded ! //-------------------------------------------------------------------- fTrackingPhase="Clusters2Tracks"; TObjArray itsTracks(15000); fOriginal.Clear(); fEsd = event; // store pointer to the esd // temporary (for cosmics) if(event->GetVertex()) { TString title = event->GetVertex()->GetTitle(); if(title.Contains("cosmics")) { Double_t xyz[3]={GetX(),GetY(),GetZ()}; Double_t exyz[3]={0.1,0.1,0.1}; SetVertex(xyz,exyz); } } // temporary {/* Read ESD tracks */ Double_t pimass = TDatabasePDG::Instance()->GetParticle(211)->Mass(); Int_t nentr=event->GetNumberOfTracks(); Info("Clusters2Tracks", "Number of ESD tracks: %d\n", nentr); while (nentr--) { AliESDtrack *esd=event->GetTrack(nentr); // ---- for debugging: //if(TMath::Abs(esd->GetX()-83.65)<0.1) { FILE *f=fopen("tpc.dat","a"); fprintf(f,"%f %f %f %f %f %f\n",(Float_t)event->GetEventNumberInFile(),(Float_t)TMath::Abs(esd->GetLabel()),(Float_t)esd->GetX(),(Float_t)esd->GetY(),(Float_t)esd->GetZ(),(Float_t)esd->Pt()); fclose(f); } if ((esd->GetStatus()&AliESDtrack::kTPCin)==0) continue; if (esd->GetStatus()&AliESDtrack::kTPCout) continue; if (esd->GetStatus()&AliESDtrack::kITSin) continue; if (esd->GetKinkIndex(0)>0) continue; //kink daughter AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("Clusters2Tracks",msg); delete t; continue; } t->GetDZ(GetX(),GetY(),GetZ(),t->GetDP()); //I.B. Double_t vdist = TMath::Sqrt(t->GetD(0)*t->GetD(0)+t->GetD(1)*t->GetD(1)); // look at the ESD mass hypothesys ! if (t->GetMass()<0.9*pimass) t->SetMass(pimass); // write expected q t->SetExpQ(TMath::Max(0.8*t->GetESDtrack()->GetTPCsignal(),30.)); if (esd->GetV0Index(0)>0 && t->GetD(0)<AliITSReconstructor::GetRecoParam()->GetMaxDforV0dghtrForProlongation()){ //track - can be V0 according to TPC } else { if (TMath::Abs(t->GetD(0))>AliITSReconstructor::GetRecoParam()->GetMaxDForProlongation()) { delete t; continue; } if (TMath::Abs(vdist)>AliITSReconstructor::GetRecoParam()->GetMaxDZForProlongation()) { delete t; continue; } if (t->Pt()<AliITSReconstructor::GetRecoParam()->GetMinPtForProlongation()) { delete t; continue; } if (!CorrectForTPCtoITSDeadZoneMaterial(t)) { delete t; continue; } } t->SetReconstructed(kFALSE); itsTracks.AddLast(t); fOriginal.AddLast(t); } } /* End Read ESD tracks */ itsTracks.Sort(); fOriginal.Sort(); Int_t nentr=itsTracks.GetEntriesFast(); fTrackHypothesys.Expand(nentr); fBestHypothesys.Expand(nentr); MakeCoefficients(nentr); if(fUseTGeo==3 || fUseTGeo==4) MakeTrksMaterialLUT(event->GetNumberOfTracks()); Int_t ntrk=0; // THE TWO TRACKING PASSES for (fPass=0; fPass<2; fPass++) { Int_t &constraint=fConstraint[fPass]; if (constraint<0) continue; for (fCurrentEsdTrack=0; fCurrentEsdTrack<nentr; fCurrentEsdTrack++) { AliITStrackMI *t=(AliITStrackMI*)itsTracks.UncheckedAt(fCurrentEsdTrack); if (t==0) continue; //this track has been already tracked //cout<<"========== "<<fPass<<" "<<fCurrentEsdTrack<<" =========\n"; if (t->GetReconstructed()&&(t->GetNUsed()<1.5)) continue; //this track was already "succesfully" reconstructed Float_t dz[2]; t->GetDZ(GetX(),GetY(),GetZ(),dz); //I.B. if (fConstraint[fPass]) { if (TMath::Abs(dz[0])>AliITSReconstructor::GetRecoParam()->GetMaxDZToUseConstraint() || TMath::Abs(dz[1])>AliITSReconstructor::GetRecoParam()->GetMaxDZToUseConstraint()) continue; } Int_t tpcLabel=t->GetLabel(); //save the TPC track label AliDebug(2,Form("LABEL %d pass %d",tpcLabel,fPass)); fI = 6; ResetTrackToFollow(*t); ResetBestTrack(); FollowProlongationTree(t,fCurrentEsdTrack,fConstraint[fPass]); SortTrackHypothesys(fCurrentEsdTrack,20,0); //MI change // AliITStrackMI *besttrack = GetBestHypothesys(fCurrentEsdTrack,t,15); if (!besttrack) continue; besttrack->SetLabel(tpcLabel); // besttrack->CookdEdx(); CookdEdx(besttrack); besttrack->SetFakeRatio(1.); CookLabel(besttrack,0.); //For comparison only UpdateESDtrack(besttrack,AliESDtrack::kITSin); if (fConstraint[fPass]&&(!besttrack->IsGoldPrimary())) continue; //to be tracked also without vertex constrain t->SetReconstructed(kTRUE); ntrk++; AliDebug(2,Form("TRACK! (label %d) ncls %d",besttrack->GetLabel(),besttrack->GetNumberOfClusters())); } GetBestHypothesysMIP(itsTracks); } // end loop on the two tracking passes if(event->GetNumberOfV0s()>0) UpdateTPCV0(event); if(AliITSReconstructor::GetRecoParam()->GetFindV0s()) FindV02(event); fAfterV0 = kTRUE; // itsTracks.Delete(); // Int_t entries = fTrackHypothesys.GetEntriesFast(); for (Int_t ientry=0; ientry<entries; ientry++) { TObjArray * array =(TObjArray*)fTrackHypothesys.UncheckedAt(ientry); if (array) array->Delete(); delete fTrackHypothesys.RemoveAt(ientry); } fTrackHypothesys.Delete(); fBestHypothesys.Delete(); fOriginal.Clear(); delete [] fCoefficients; fCoefficients=0; DeleteTrksMaterialLUT(); Info("Clusters2Tracks","Number of prolonged tracks: %d\n",ntrk); fTrackingPhase="Default"; return 0; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::PropagateBack(AliESDEvent *event) { //-------------------------------------------------------------------- // This functions propagates reconstructed ITS tracks back // The clusters must be loaded ! //-------------------------------------------------------------------- fTrackingPhase="PropagateBack"; Int_t nentr=event->GetNumberOfTracks(); Info("PropagateBack", "Number of ESD tracks: %d\n", nentr); Int_t ntrk=0; for (Int_t i=0; i<nentr; i++) { AliESDtrack *esd=event->GetTrack(i); if ((esd->GetStatus()&AliESDtrack::kITSin)==0) continue; if (esd->GetStatus()&AliESDtrack::kITSout) continue; AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("PropagateBack",msg); delete t; continue; } t->SetExpQ(TMath::Max(0.8*t->GetESDtrack()->GetTPCsignal(),30.)); ResetTrackToFollow(*t); // propagate to vertex [SR, GSI 17.02.2003] // Start Time measurement [SR, GSI 17.02.2003], corrected by I.Belikov if (CorrectForPipeMaterial(&fTrackToFollow,"inward")) { if (fTrackToFollow.PropagateToVertex(event->GetVertex())) fTrackToFollow.StartTimeIntegral(); // from vertex to outside pipe CorrectForPipeMaterial(&fTrackToFollow,"outward"); } fTrackToFollow.ResetCovariance(10.); fTrackToFollow.ResetClusters(); if (RefitAt(AliITSRecoParam::GetrInsideITSscreen(),&fTrackToFollow,t)) { if (!CorrectForTPCtoITSDeadZoneMaterial(&fTrackToFollow)) { delete t; continue; } fTrackToFollow.SetLabel(t->GetLabel()); //fTrackToFollow.CookdEdx(); CookLabel(&fTrackToFollow,0.); //For comparison only fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSout); //UseClusters(&fTrackToFollow); ntrk++; } delete t; } Info("PropagateBack","Number of back propagated ITS tracks: %d\n",ntrk); fTrackingPhase="Default"; return 0; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::RefitInward(AliESDEvent *event) { //-------------------------------------------------------------------- // This functions refits ITS tracks using the // "inward propagated" TPC tracks // The clusters must be loaded ! //-------------------------------------------------------------------- fTrackingPhase="RefitInward"; if(AliITSReconstructor::GetRecoParam()->GetFindV0s()) RefitV02(event); Int_t nentr=event->GetNumberOfTracks(); Info("RefitInward", "Number of ESD tracks: %d\n", nentr); Int_t ntrk=0; for (Int_t i=0; i<nentr; i++) { AliESDtrack *esd=event->GetTrack(i); if ((esd->GetStatus()&AliESDtrack::kITSout) == 0) continue; if (esd->GetStatus()&AliESDtrack::kITSrefit) continue; if (esd->GetStatus()&AliESDtrack::kTPCout) if ((esd->GetStatus()&AliESDtrack::kTPCrefit)==0) continue; AliITStrackMI *t=0; try { t=new AliITStrackMI(*esd); } catch (const Char_t *msg) { //Warning("RefitInward",msg); delete t; continue; } t->SetExpQ(TMath::Max(0.8*t->GetESDtrack()->GetTPCsignal(),30.)); if (!CorrectForTPCtoITSDeadZoneMaterial(t)) { delete t; continue; } ResetTrackToFollow(*t); fTrackToFollow.ResetClusters(); if ((esd->GetStatus()&AliESDtrack::kTPCin)==0) fTrackToFollow.ResetCovariance(10.); //Refitting... Bool_t pe=AliITSReconstructor::GetRecoParam()->GetComputePlaneEff(); AliDebug(2,Form("Refit LABEL %d %d",t->GetLabel(),t->GetNumberOfClusters())); if (RefitAt(AliITSRecoParam::GetrInsideSPD1(),&fTrackToFollow,t,kTRUE,pe)) { AliDebug(2," refit OK"); fTrackToFollow.SetLabel(t->GetLabel()); // fTrackToFollow.CookdEdx(); CookdEdx(&fTrackToFollow); CookLabel(&fTrackToFollow,0.0); //For comparison only //The beam pipe if (CorrectForPipeMaterial(&fTrackToFollow,"inward")) { fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSrefit); AliESDtrack *esdTrack =fTrackToFollow.GetESDtrack(); //printf(" %d\n",esdTrack->GetITSModuleIndex(0)); //esdTrack->UpdateTrackParams(&fTrackToFollow,AliESDtrack::kITSrefit); //original line Float_t r[3]={0.,0.,0.}; Double_t maxD=3.; esdTrack->RelateToVertex(event->GetVertex(),GetBz(r),maxD); ntrk++; } } delete t; } Info("RefitInward","Number of refitted tracks: %d\n",ntrk); fTrackingPhase="Default"; return 0; } //------------------------------------------------------------------------ AliCluster *AliITStrackerMI::GetCluster(Int_t index) const { //-------------------------------------------------------------------- // Return pointer to a given cluster //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; return fgLayers[l].GetCluster(c); } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::GetTrackPoint(Int_t index, AliTrackPoint& p) const { //-------------------------------------------------------------------- // Get track space point with index i //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; AliITSRecPoint *cl = fgLayers[l].GetCluster(c); Int_t idet = cl->GetDetectorIndex(); Float_t xyz[3]; Float_t cov[6]; cl->GetGlobalXYZ(xyz); cl->GetGlobalCov(cov); p.SetXYZ(xyz, cov); p.SetCharge(cl->GetQ()); p.SetDriftTime(cl->GetDriftTime()); AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer; switch (l) { case 0: iLayer = AliGeomManager::kSPD1; break; case 1: iLayer = AliGeomManager::kSPD2; break; case 2: iLayer = AliGeomManager::kSDD1; break; case 3: iLayer = AliGeomManager::kSDD2; break; case 4: iLayer = AliGeomManager::kSSD1; break; case 5: iLayer = AliGeomManager::kSSD2; break; default: AliWarning(Form("Wrong layer index in ITS (%d) !",l)); break; }; UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,idet); p.SetVolumeID((UShort_t)volid); return kTRUE; } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::GetTrackPointTrackingError(Int_t index, AliTrackPoint& p, const AliESDtrack *t) { //-------------------------------------------------------------------- // Get track space point with index i // (assign error estimated during the tracking) //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; const AliITSRecPoint *cl = fgLayers[l].GetCluster(c); Int_t idet = cl->GetDetectorIndex(); const AliITSdetector &det=fgLayers[l].GetDetector(idet); // tgphi and tglambda of the track in tracking frame with alpha=det.GetPhi Float_t detxy[2]; detxy[0] = det.GetR()*TMath::Cos(det.GetPhi()); detxy[1] = det.GetR()*TMath::Sin(det.GetPhi()); Double_t alpha = t->GetAlpha(); Double_t xdetintrackframe = detxy[0]*TMath::Cos(alpha)+detxy[1]*TMath::Sin(alpha); Float_t phi = TMath::ASin(t->GetSnpAt(xdetintrackframe,GetBz())); phi += alpha-det.GetPhi(); Float_t tgphi = TMath::Tan(phi); Float_t tgl = t->GetTgl(); // tgl about const along track Float_t expQ = TMath::Max(0.8*t->GetTPCsignal(),30.); Float_t errlocalx,errlocalz; Bool_t addMisalErr=kFALSE; AliITSClusterParam::GetError(l,cl,tgl,tgphi,expQ,errlocalx,errlocalz,addMisalErr); Float_t xyz[3]; Float_t cov[6]; cl->GetGlobalXYZ(xyz); // cl->GetGlobalCov(cov); Float_t pos[3] = {0.,0.,0.}; AliCluster tmpcl((UShort_t)cl->GetVolumeId(),pos[0],pos[1],pos[2],errlocalx*errlocalx,errlocalz*errlocalz,0); tmpcl.GetGlobalCov(cov); p.SetXYZ(xyz, cov); p.SetCharge(cl->GetQ()); p.SetDriftTime(cl->GetDriftTime()); AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer; switch (l) { case 0: iLayer = AliGeomManager::kSPD1; break; case 1: iLayer = AliGeomManager::kSPD2; break; case 2: iLayer = AliGeomManager::kSDD1; break; case 3: iLayer = AliGeomManager::kSDD2; break; case 4: iLayer = AliGeomManager::kSSD1; break; case 5: iLayer = AliGeomManager::kSSD2; break; default: AliWarning(Form("Wrong layer index in ITS (%d) !",l)); break; }; UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,idet); p.SetVolumeID((UShort_t)volid); return kTRUE; } //------------------------------------------------------------------------ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdindex, Bool_t constrain) { //-------------------------------------------------------------------- // Follow prolongation tree //-------------------------------------------------------------------- // Double_t xyzVtx[]={GetX(),GetY(),GetZ()}; Double_t ersVtx[]={GetSigmaX(),GetSigmaY(),GetSigmaZ()}; AliESDtrack * esd = otrack->GetESDtrack(); if (esd->GetV0Index(0)>0) { // TEMPORARY SOLLUTION: map V0 indexes to point to proper track // mapping of ESD track is different as ITS track in Containers // Need something more stable // Indexes are set back again to the ESD track indexes in UpdateTPCV0 for (Int_t i=0;i<3;i++){ Int_t index = esd->GetV0Index(i); if (index==0) break; AliESDv0 * vertex = fEsd->GetV0(index); if (vertex->GetStatus()<0) continue; // rejected V0 // if (esd->GetSign()>0) { vertex->SetIndex(0,esdindex); } else { vertex->SetIndex(1,esdindex); } } } TObjArray *bestarray = (TObjArray*)fBestHypothesys.At(esdindex); if (!bestarray){ bestarray = new TObjArray(5); fBestHypothesys.AddAt(bestarray,esdindex); } // //setup tree of the prolongations // static AliITStrackMI tracks[7][100]; AliITStrackMI *currenttrack; static AliITStrackMI currenttrack1; static AliITStrackMI currenttrack2; static AliITStrackMI backuptrack; Int_t ntracks[7]; Int_t nindexes[7][100]; Float_t normalizedchi2[100]; for (Int_t ilayer=0;ilayer<6;ilayer++) ntracks[ilayer]=0; otrack->SetNSkipped(0); new (&(tracks[6][0])) AliITStrackMI(*otrack); ntracks[6]=1; for (Int_t i=0;i<7;i++) nindexes[i][0]=0; Int_t modstatus = 1; // found Float_t xloc,zloc; // // // follow prolongations for (Int_t ilayer=5; ilayer>=0; ilayer--) { AliDebug(2,Form("FollowProlongationTree: layer %d",ilayer)); fI = ilayer; // AliITSlayer &layer=fgLayers[ilayer]; Double_t r = layer.GetR(); ntracks[ilayer]=0; // // Int_t nskipped=0; Float_t nused =0; for (Int_t itrack =0; itrack<ntracks[ilayer+1]; itrack++) { //set current track if (ntracks[ilayer]>=100) break; if (tracks[ilayer+1][nindexes[ilayer+1][itrack]].GetNSkipped()>0) nskipped++; if (tracks[ilayer+1][nindexes[ilayer+1][itrack]].GetNUsed()>2.) nused++; if (ntracks[ilayer]>15+ilayer){ if (itrack>1&&tracks[ilayer+1][nindexes[ilayer+1][itrack]].GetNSkipped()>0 && nskipped>4+ilayer) continue; if (itrack>1&&tracks[ilayer+1][nindexes[ilayer+1][itrack]].GetNUsed()>2. && nused>3) continue; } new(&currenttrack1) AliITStrackMI(tracks[ilayer+1][nindexes[ilayer+1][itrack]]); // material between SSD and SDD, SDD and SPD if (ilayer==3) if(!CorrectForShieldMaterial(&currenttrack1,"SDD","inward")) continue; if (ilayer==1) if(!CorrectForShieldMaterial(&currenttrack1,"SPD","inward")) continue; // detector number Double_t phi,z; if (!currenttrack1.GetPhiZat(r,phi,z)) continue; Int_t idet=layer.FindDetectorIndex(phi,z); Double_t trackGlobXYZ1[3]; if (!currenttrack1.GetXYZ(trackGlobXYZ1)) continue; // Get the budget to the primary vertex for the current track being prolonged Double_t budgetToPrimVertex = GetEffectiveThickness(); // check if we allow a prolongation without point Int_t skip = CheckSkipLayer(&currenttrack1,ilayer,idet); if (skip) { AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1); // propagate to the layer radius Double_t xToGo; if (!vtrack->GetLocalXat(r,xToGo)) continue; if(!vtrack->Propagate(xToGo)) continue; // apply correction for material of the current layer CorrectForLayerMaterial(vtrack,ilayer,trackGlobXYZ1,"inward"); vtrack->SetNDeadZone(vtrack->GetNDeadZone()+1); vtrack->SetClIndex(ilayer,0); modstatus = (skip==1 ? 3 : 4); // skipped : out in z if(LocalModuleCoord(ilayer,idet,vtrack,xloc,zloc)) { // local module coords vtrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); } if(constrain) vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx); ntracks[ilayer]++; continue; } // track outside layer acceptance in z if (idet<0) continue; //propagate to the intersection with the detector plane const AliITSdetector &det=layer.GetDetector(idet); new(&currenttrack2) AliITStrackMI(currenttrack1); if (!currenttrack1.Propagate(det.GetPhi(),det.GetR())) continue; if (!currenttrack2.Propagate(det.GetPhi(),det.GetR())) continue; currenttrack1.SetDetectorIndex(idet); currenttrack2.SetDetectorIndex(idet); if(!LocalModuleCoord(ilayer,idet,&currenttrack1,xloc,zloc)) continue; // local module coords //*************** // DEFINITION OF SEARCH ROAD AND CLUSTERS SELECTION // // road in global (rphi,z) [i.e. in tracking ref. system] Double_t zmin,zmax,ymin,ymax; if (!ComputeRoad(&currenttrack1,ilayer,idet,zmin,zmax,ymin,ymax)) continue; // select clusters in road layer.SelectClusters(zmin,zmax,ymin,ymax); //******************** // Define criteria for track-cluster association Double_t msz = currenttrack1.GetSigmaZ2() + AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer); Double_t msy = currenttrack1.GetSigmaY2() + AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer); if (constrain) { msz *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadZC(); msy *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadYC(); } else { msz *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadZNonC(); msy *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadYNonC(); } msz = 1./msz; // 1/RoadZ^2 msy = 1./msy; // 1/RoadY^2 // // // LOOP OVER ALL POSSIBLE TRACK PROLONGATIONS ON THIS LAYER // const AliITSRecPoint *cl=0; Int_t clidx=-1; Double_t chi2trkcl=AliITSReconstructor::GetRecoParam()->GetMaxChi2(); // init with big value Bool_t deadzoneSPD=kFALSE; currenttrack = &currenttrack1; // check if the road contains a dead zone Bool_t noClusters = kFALSE; if (!layer.GetNextCluster(clidx,kTRUE)) noClusters=kTRUE; if (noClusters) AliDebug(2,"no clusters in road"); Double_t dz=0.5*(zmax-zmin); Double_t dy=0.5*(ymax-ymin); Int_t dead = CheckDeadZone(&currenttrack1,ilayer,idet,dz,dy,noClusters); if(dead) AliDebug(2,Form("DEAD (%d)\n",dead)); // create a prolongation without clusters (check also if there are no clusters in the road) if (dead || (noClusters && AliITSReconstructor::GetRecoParam()->GetAllowProlongationWithEmptyRoad())) { AliITStrackMI * updatetrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(*currenttrack); updatetrack->SetClIndex(ilayer,0); if (dead==0) { modstatus = 5; // no cls in road } else if (dead==1) { modstatus = 7; // holes in z in SPD } else if (dead==2 || dead==3) { modstatus = 2; // dead from OCDB } updatetrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); // apply correction for material of the current layer CorrectForLayerMaterial(updatetrack,ilayer,trackGlobXYZ1,"inward"); if (constrain) { // apply vertex constrain updatetrack->SetConstrain(constrain); Bool_t isPrim = kTRUE; if (ilayer<4) { // check that it's close to the vertex updatetrack->GetDZ(GetX(),GetY(),GetZ(),updatetrack->GetDP()); //I.B. if (TMath::Abs(updatetrack->GetD(0)/(1.+ilayer)) > // y AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk() || TMath::Abs(updatetrack->GetD(1)/(1.+ilayer)) > // z AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk()) isPrim=kFALSE; } if (isPrim) updatetrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx); } if (dead) { updatetrack->SetNDeadZone(updatetrack->GetNDeadZone()+1); if (dead==1) { // dead zone at z=0,+-7cm in SPD updatetrack->SetDeadZoneProbability(GetSPDDeadZoneProbability(updatetrack->GetZ(),TMath::Sqrt(updatetrack->GetSigmaZ2()))); deadzoneSPD=kTRUE; } } ntracks[ilayer]++; } clidx=-1; // loop over clusters in the road while ((cl=layer.GetNextCluster(clidx))!=0) { if (ntracks[ilayer]>95) break; //space for skipped clusters Bool_t changedet =kFALSE; if (cl->GetQ()==0 && deadzoneSPD==kTRUE) continue; Int_t idetc=cl->GetDetectorIndex(); if (currenttrack->GetDetectorIndex()==idetc) { // track already on the cluster's detector // take into account misalignment (bring track to real detector plane) Double_t xTrOrig = currenttrack->GetX(); if (!currenttrack->Propagate(xTrOrig+cl->GetX())) continue; // a first cut on track-cluster distance if ( (currenttrack->GetZ()-cl->GetZ())*(currenttrack->GetZ()-cl->GetZ())*msz + (currenttrack->GetY()-cl->GetY())*(currenttrack->GetY()-cl->GetY())*msy > 1. ) { // cluster not associated to track AliDebug(2,"not associated"); continue; } // bring track back to ideal detector plane if (!currenttrack->Propagate(xTrOrig)) continue; } else { // have to move track to cluster's detector const AliITSdetector &detc=layer.GetDetector(idetc); // a first cut on track-cluster distance Double_t y; if (!currenttrack2.GetProlongationFast(detc.GetPhi(),detc.GetR()+cl->GetX(),y,z)) continue; if ( (z-cl->GetZ())*(z-cl->GetZ())*msz + (y-cl->GetY())*(y-cl->GetY())*msy > 1. ) continue; // cluster not associated to track // new (&backuptrack) AliITStrackMI(currenttrack2); changedet = kTRUE; currenttrack =&currenttrack2; if (!currenttrack->Propagate(detc.GetPhi(),detc.GetR())) { new (currenttrack) AliITStrackMI(backuptrack); changedet = kFALSE; continue; } currenttrack->SetDetectorIndex(idetc); // Get again the budget to the primary vertex // for the current track being prolonged, if had to change detector //budgetToPrimVertex = GetEffectiveThickness();// not needed at the moment because anyway we take a mean material for this correction } // calculate track-clusters chi2 chi2trkcl = GetPredictedChi2MI(currenttrack,cl,ilayer); // chi2 cut AliDebug(2,Form("chi2 %f max %f",chi2trkcl,AliITSReconstructor::GetRecoParam()->GetMaxChi2s(ilayer))); if (chi2trkcl < AliITSReconstructor::GetRecoParam()->GetMaxChi2s(ilayer)) { if (cl->GetQ()==0) deadzoneSPD=kTRUE; // only 1 prolongation with virtual cluster if (ntracks[ilayer]>=100) continue; AliITStrackMI * updatetrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(*currenttrack); updatetrack->SetClIndex(ilayer,0); if (changedet) new (&currenttrack2) AliITStrackMI(backuptrack); if (cl->GetQ()!=0) { // real cluster if (!UpdateMI(updatetrack,cl,chi2trkcl,(ilayer<<28)+clidx)) { AliDebug(2,"update failed"); continue; } updatetrack->SetSampledEdx(cl->GetQ(),updatetrack->GetNumberOfClusters()-1); //b.b. modstatus = 1; // found } else { // virtual cluster in dead zone updatetrack->SetNDeadZone(updatetrack->GetNDeadZone()+1); updatetrack->SetDeadZoneProbability(GetSPDDeadZoneProbability(updatetrack->GetZ(),TMath::Sqrt(updatetrack->GetSigmaZ2()))); modstatus = 7; // holes in z in SPD } if (changedet) { Float_t xlocnewdet,zlocnewdet; if(LocalModuleCoord(ilayer,idet,updatetrack,xlocnewdet,zlocnewdet)) { // local module coords updatetrack->SetModuleIndexInfo(ilayer,idet,modstatus,xlocnewdet,zlocnewdet); } } else { updatetrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); } if (cl->IsUsed()) updatetrack->IncrementNUsed(); // apply correction for material of the current layer CorrectForLayerMaterial(updatetrack,ilayer,trackGlobXYZ1,"inward"); if (constrain) { // apply vertex constrain updatetrack->SetConstrain(constrain); Bool_t isPrim = kTRUE; if (ilayer<4) { // check that it's close to the vertex updatetrack->GetDZ(GetX(),GetY(),GetZ(),updatetrack->GetDP()); //I.B. if (TMath::Abs(updatetrack->GetD(0)/(1.+ilayer)) > // y AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk() || TMath::Abs(updatetrack->GetD(1)/(1.+ilayer)) > // z AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk()) isPrim=kFALSE; } if (isPrim) updatetrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx); } //apply vertex constrain ntracks[ilayer]++; } // create new hypothesis else { AliDebug(2,"chi2 too large"); } } // loop over possible prolongations // allow one prolongation without clusters if (constrain && itrack<=1 && currenttrack1.GetNSkipped()==0 && deadzoneSPD==kFALSE && ntracks[ilayer]<100) { AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1); // apply correction for material of the current layer CorrectForLayerMaterial(vtrack,ilayer,trackGlobXYZ1,"inward"); vtrack->SetClIndex(ilayer,0); modstatus = 3; // skipped vtrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx); vtrack->IncrementNSkipped(); ntracks[ilayer]++; } // allow one prolongation without clusters for tracks with |tgl|>1.1 if (constrain && itrack==0 && TMath::Abs(currenttrack1.GetTgl())>1.1) { //big theta - for low flux AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1); // apply correction for material of the current layer CorrectForLayerMaterial(vtrack,ilayer,trackGlobXYZ1,"inward"); vtrack->SetClIndex(ilayer,0); modstatus = 3; // skipped vtrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx); vtrack->SetNDeadZone(vtrack->GetNDeadZone()+1); ntracks[ilayer]++; } } // loop over tracks in layer ilayer+1 //loop over track candidates for the current layer // // Int_t accepted=0; Int_t golden=0; for (Int_t itrack=0;itrack<ntracks[ilayer];itrack++){ normalizedchi2[itrack] = NormalizedChi2(&tracks[ilayer][itrack],ilayer); if (normalizedchi2[itrack] < AliITSReconstructor::GetRecoParam()->GetMaxNormChi2ForGolden(ilayer)) golden++; if (ilayer>4) { accepted++; } else { if (constrain) { // constrain if (normalizedchi2[itrack]<AliITSReconstructor::GetRecoParam()->GetMaxNormChi2C(ilayer)+1) accepted++; } else { // !constrain if (normalizedchi2[itrack]<AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonC(ilayer)+1) accepted++; } } } // sort tracks by increasing normalized chi2 TMath::Sort(ntracks[ilayer],normalizedchi2,nindexes[ilayer],kFALSE); ntracks[ilayer] = TMath::Min(accepted,7+2*ilayer); if (ntracks[ilayer]<golden+2+ilayer) ntracks[ilayer]=TMath::Min(golden+2+ilayer,accepted); if (ntracks[ilayer]>90) ntracks[ilayer]=90; } // end loop over layers // // Now select tracks to be kept // Int_t max = constrain ? 20 : 5; // tracks that reach layer 0 (SPD inner) for (Int_t i=0; i<TMath::Min(max,ntracks[0]); i++) { AliITStrackMI & track= tracks[0][nindexes[0][i]]; if (track.GetNumberOfClusters()<2) continue; if (!constrain && track.GetNormChi2(0) > AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonCForHypothesis()) { continue; } AddTrackHypothesys(new AliITStrackMI(track), esdindex); } // tracks that reach layer 1 (SPD outer) for (Int_t i=0;i<TMath::Min(2,ntracks[1]);i++) { AliITStrackMI & track= tracks[1][nindexes[1][i]]; if (track.GetNumberOfClusters()<4) continue; if (!constrain && track.GetNormChi2(1) > AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonCForHypothesis()) continue; if (constrain) track.IncrementNSkipped(); if (!constrain) { track.SetD(0,track.GetD(GetX(),GetY())); track.SetNSkipped(track.GetNSkipped()+4./(4.+8.*TMath::Abs(track.GetD(0)))); if (track.GetNumberOfClusters()+track.GetNDeadZone()+track.GetNSkipped()>6) { track.SetNSkipped(6-track.GetNumberOfClusters()+track.GetNDeadZone()); } } AddTrackHypothesys(new AliITStrackMI(track), esdindex); } // tracks that reach layer 2 (SDD inner), only during non-constrained pass if (!constrain){ for (Int_t i=0;i<TMath::Min(2,ntracks[2]);i++) { AliITStrackMI & track= tracks[2][nindexes[2][i]]; if (track.GetNumberOfClusters()<3) continue; if (!constrain && track.GetNormChi2(2) > AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonCForHypothesis()) continue; if (constrain) track.SetNSkipped(track.GetNSkipped()+2); if (!constrain){ track.SetD(0,track.GetD(GetX(),GetY())); track.SetNSkipped(track.GetNSkipped()+7./(7.+8.*TMath::Abs(track.GetD(0)))); if (track.GetNumberOfClusters()+track.GetNDeadZone()+track.GetNSkipped()>6) { track.SetNSkipped(6-track.GetNumberOfClusters()+track.GetNDeadZone()); } } AddTrackHypothesys(new AliITStrackMI(track), esdindex); } } if (!constrain) { // // register best track of each layer - important for V0 finder // for (Int_t ilayer=0;ilayer<5;ilayer++){ if (ntracks[ilayer]==0) continue; AliITStrackMI & track= tracks[ilayer][nindexes[ilayer][0]]; if (track.GetNumberOfClusters()<1) continue; CookLabel(&track,0); bestarray->AddAt(new AliITStrackMI(track),ilayer); } } // // update TPC V0 information // if (otrack->GetESDtrack()->GetV0Index(0)>0){ Float_t fprimvertex[3]={GetX(),GetY(),GetZ()}; for (Int_t i=0;i<3;i++){ Int_t index = otrack->GetESDtrack()->GetV0Index(i); if (index==0) break; AliV0 *vertex = (AliV0*)fEsd->GetV0(index); if (vertex->GetStatus()<0) continue; // rejected V0 // if (otrack->GetSign()>0) { vertex->SetIndex(0,esdindex); } else{ vertex->SetIndex(1,esdindex); } //find nearest layer with track info Double_t xrp[3]; vertex->GetXYZ(xrp[0],xrp[1],xrp[2]); //I.B. Int_t nearestold = GetNearestLayer(xrp); //I.B. Int_t nearest = nearestold; for (Int_t ilayer =nearest;ilayer<8;ilayer++){ if (ntracks[nearest]==0){ nearest = ilayer; } } // AliITStrackMI & track= tracks[nearest][nindexes[nearest][0]]; if (nearestold<5&&nearest<5){ Bool_t accept = track.GetNormChi2(nearest)<10; if (accept){ if (track.GetSign()>0) { vertex->SetParamP(track); vertex->Update(fprimvertex); //vertex->SetIndex(0,track.fESDtrack->GetID()); if (track.GetNumberOfClusters()>2) AddTrackHypothesys(new AliITStrackMI(track), esdindex); }else{ vertex->SetParamN(track); vertex->Update(fprimvertex); //vertex->SetIndex(1,track.fESDtrack->GetID()); if (track.GetNumberOfClusters()>2) AddTrackHypothesys(new AliITStrackMI(track), esdindex); } vertex->SetStatus(vertex->GetStatus()+1); }else{ //vertex->SetStatus(-2); // reject V0 - not enough clusters } } } } } //------------------------------------------------------------------------ AliITStrackerMI::AliITSlayer & AliITStrackerMI::GetLayer(Int_t layer) const { //-------------------------------------------------------------------- // // return fgLayers[layer]; } //------------------------------------------------------------------------ AliITStrackerMI::AliITSlayer::AliITSlayer(): fR(0), fPhiOffset(0), fNladders(0), fZOffset(0), fNdetectors(0), fDetectors(0), fN(0), fDy5(0), fDy10(0), fDy20(0), fClustersCs(0), fClusterIndexCs(0), fYcs(0), fZcs(0), fNcs(0), fCurrentSlice(-1), fZmax(0), fYmin(0), fYmax(0), fI(0), fImax(0), fSkip(0), fAccepted(0), fRoad(0){ //-------------------------------------------------------------------- //default AliITSlayer constructor //-------------------------------------------------------------------- for (Int_t i=0; i<AliITSRecoParam::GetMaxClusterPerLayer(); i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } } //------------------------------------------------------------------------ AliITStrackerMI::AliITSlayer:: AliITSlayer(Double_t r,Double_t p,Double_t z,Int_t nl,Int_t nd): fR(r), fPhiOffset(p), fNladders(nl), fZOffset(z), fNdetectors(nd), fDetectors(0), fN(0), fDy5(0), fDy10(0), fDy20(0), fClustersCs(0), fClusterIndexCs(0), fYcs(0), fZcs(0), fNcs(0), fCurrentSlice(-1), fZmax(0), fYmin(0), fYmax(0), fI(0), fImax(0), fSkip(0), fAccepted(0), fRoad(0) { //-------------------------------------------------------------------- //main AliITSlayer constructor //-------------------------------------------------------------------- fDetectors=new AliITSdetector[fNladders*fNdetectors]; fRoad=2*fR*TMath::Sqrt(TMath::Pi()/1.);//assuming that there's only one cluster } //------------------------------------------------------------------------ AliITStrackerMI::AliITSlayer::AliITSlayer(const AliITSlayer& layer): fR(layer.fR), fPhiOffset(layer.fPhiOffset), fNladders(layer.fNladders), fZOffset(layer.fZOffset), fNdetectors(layer.fNdetectors), fDetectors(layer.fDetectors), fN(layer.fN), fDy5(layer.fDy5), fDy10(layer.fDy10), fDy20(layer.fDy20), fClustersCs(layer.fClustersCs), fClusterIndexCs(layer.fClusterIndexCs), fYcs(layer.fYcs), fZcs(layer.fZcs), fNcs(layer.fNcs), fCurrentSlice(layer.fCurrentSlice), fZmax(layer.fZmax), fYmin(layer.fYmin), fYmax(layer.fYmax), fI(layer.fI), fImax(layer.fImax), fSkip(layer.fSkip), fAccepted(layer.fAccepted), fRoad(layer.fRoad){ //Copy constructor } //------------------------------------------------------------------------ AliITStrackerMI::AliITSlayer::~AliITSlayer() { //-------------------------------------------------------------------- // AliITSlayer destructor //-------------------------------------------------------------------- delete [] fDetectors; for (Int_t i=0; i<fN; i++) delete fClusters[i]; for (Int_t i=0; i<AliITSRecoParam::GetMaxClusterPerLayer(); i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSlayer::ResetClusters() { //-------------------------------------------------------------------- // This function removes loaded clusters //-------------------------------------------------------------------- for (Int_t i=0; i<fN; i++) delete fClusters[i]; for (Int_t i=0; i<AliITSRecoParam::GetMaxClusterPerLayer(); i++){ fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } fN=0; fI=0; } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSlayer::ResetWeights() { //-------------------------------------------------------------------- // This function reset weights of the clusters //-------------------------------------------------------------------- for (Int_t i=0; i<AliITSRecoParam::GetMaxClusterPerLayer(); i++) { fClusterWeight[i]=0; fClusterTracks[0][i]=-1; fClusterTracks[1][i]=-1; fClusterTracks[2][i]=-1; fClusterTracks[3][i]=-1; } for (Int_t i=0; i<fN;i++) { AliITSRecPoint * cl = (AliITSRecPoint*)GetCluster(i); if (cl&&cl->IsUsed()) cl->Use(); } } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSlayer::ResetRoad() { //-------------------------------------------------------------------- // This function calculates the road defined by the cluster density //-------------------------------------------------------------------- Int_t n=0; for (Int_t i=0; i<fN; i++) { if (TMath::Abs(fClusters[i]->GetZ())<fR) n++; } if (n>1) fRoad=2*fR*TMath::Sqrt(TMath::Pi()/n); } //------------------------------------------------------------------------ Int_t AliITStrackerMI::AliITSlayer::InsertCluster(AliITSRecPoint *cl) { //-------------------------------------------------------------------- //This function adds a cluster to this layer //-------------------------------------------------------------------- if (fN==AliITSRecoParam::GetMaxClusterPerLayer()) { ::Error("InsertCluster","Too many clusters !\n"); return 1; } fCurrentSlice=-1; fClusters[fN]=cl; fN++; AliITSdetector &det=GetDetector(cl->GetDetectorIndex()); if (cl->GetY()<det.GetYmin()) det.SetYmin(cl->GetY()); if (cl->GetY()>det.GetYmax()) det.SetYmax(cl->GetY()); if (cl->GetZ()<det.GetZmin()) det.SetZmin(cl->GetZ()); if (cl->GetZ()>det.GetZmax()) det.SetZmax(cl->GetZ()); return 0; } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSlayer::SortClusters() { // //sort clusters // AliITSRecPoint **clusters = new AliITSRecPoint*[fN]; Float_t *z = new Float_t[fN]; Int_t * index = new Int_t[fN]; // for (Int_t i=0;i<fN;i++){ z[i] = fClusters[i]->GetZ(); } TMath::Sort(fN,z,index,kFALSE); for (Int_t i=0;i<fN;i++){ clusters[i] = fClusters[index[i]]; } // for (Int_t i=0;i<fN;i++){ fClusters[i] = clusters[i]; fZ[i] = fClusters[i]->GetZ(); AliITSdetector &det=GetDetector(fClusters[i]->GetDetectorIndex()); Double_t y=fR*det.GetPhi() + fClusters[i]->GetY(); if (y>2.*fR*TMath::Pi()) y -= 2.*fR*TMath::Pi(); fY[i] = y; } delete[] index; delete[] z; delete[] clusters; // fYB[0]=10000000; fYB[1]=-10000000; for (Int_t i=0;i<fN;i++){ if (fY[i]<fYB[0]) fYB[0]=fY[i]; if (fY[i]>fYB[1]) fYB[1]=fY[i]; fClusterIndex[i] = i; } // // fill slices fDy5 = (fYB[1]-fYB[0])/5.; fDy10 = (fYB[1]-fYB[0])/10.; fDy20 = (fYB[1]-fYB[0])/20.; for (Int_t i=0;i<6;i++) fN5[i] =0; for (Int_t i=0;i<11;i++) fN10[i]=0; for (Int_t i=0;i<21;i++) fN20[i]=0; // for (Int_t i=0;i<6;i++) {fBy5[i][0] = fYB[0]+(i-0.75)*fDy5; fBy5[i][1] = fYB[0]+(i+0.75)*fDy5;} for (Int_t i=0;i<11;i++) {fBy10[i][0] = fYB[0]+(i-0.75)*fDy10; fBy10[i][1] = fYB[0]+(i+0.75)*fDy10;} for (Int_t i=0;i<21;i++) {fBy20[i][0] = fYB[0]+(i-0.75)*fDy20; fBy20[i][1] = fYB[0]+(i+0.75)*fDy20;} // // for (Int_t i=0;i<fN;i++) for (Int_t irot=-1;irot<=1;irot++){ Float_t curY = fY[i]+irot*TMath::TwoPi()*fR; // slice 5 for (Int_t slice=0; slice<6;slice++){ if (fBy5[slice][0]<curY && curY<fBy5[slice][1]&&fN5[slice]<AliITSRecoParam::GetMaxClusterPerLayer5()){ fClusters5[slice][fN5[slice]] = fClusters[i]; fY5[slice][fN5[slice]] = curY; fZ5[slice][fN5[slice]] = fZ[i]; fClusterIndex5[slice][fN5[slice]]=i; fN5[slice]++; } } // slice 10 for (Int_t slice=0; slice<11;slice++){ if (fBy10[slice][0]<curY && curY<fBy10[slice][1]&&fN10[slice]<AliITSRecoParam::GetMaxClusterPerLayer10()){ fClusters10[slice][fN10[slice]] = fClusters[i]; fY10[slice][fN10[slice]] = curY; fZ10[slice][fN10[slice]] = fZ[i]; fClusterIndex10[slice][fN10[slice]]=i; fN10[slice]++; } } // slice 20 for (Int_t slice=0; slice<21;slice++){ if (fBy20[slice][0]<curY && curY<fBy20[slice][1]&&fN20[slice]<AliITSRecoParam::GetMaxClusterPerLayer20()){ fClusters20[slice][fN20[slice]] = fClusters[i]; fY20[slice][fN20[slice]] = curY; fZ20[slice][fN20[slice]] = fZ[i]; fClusterIndex20[slice][fN20[slice]]=i; fN20[slice]++; } } } // // consistency check // for (Int_t i=0;i<fN-1;i++){ if (fZ[i]>fZ[i+1]){ printf("Bug\n"); } } // for (Int_t slice=0;slice<21;slice++) for (Int_t i=0;i<fN20[slice]-1;i++){ if (fZ20[slice][i]>fZ20[slice][i+1]){ printf("Bug\n"); } } } //------------------------------------------------------------------------ Int_t AliITStrackerMI::AliITSlayer::FindClusterIndex(Float_t z) const { //-------------------------------------------------------------------- // This function returns the index of the nearest cluster //-------------------------------------------------------------------- Int_t ncl=0; const Float_t *zcl; if (fCurrentSlice<0) { ncl = fN; zcl = fZ; } else{ ncl = fNcs; zcl = fZcs;; } if (ncl==0) return 0; Int_t b=0, e=ncl-1, m=(b+e)/2; for (; b<e; m=(b+e)/2) { // if (z > fClusters[m]->GetZ()) b=m+1; if (z > zcl[m]) b=m+1; else e=m; } return m; } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::ComputeRoad(AliITStrackMI* track,Int_t ilayer,Int_t idet,Double_t &zmin,Double_t &zmax,Double_t &ymin,Double_t &ymax) const { //-------------------------------------------------------------------- // This function computes the rectangular road for this track //-------------------------------------------------------------------- AliITSdetector &det = fgLayers[ilayer].GetDetector(idet); // take into account the misalignment: propagate track to misaligned detector plane if (!track->Propagate(det.GetPhi(),det.GetRmisal())) return kFALSE; Double_t dz=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadZ()* TMath::Sqrt(track->GetSigmaZ2() + AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer)); Double_t dy=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadY()* TMath::Sqrt(track->GetSigmaY2() + AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer)); // track at boundary between detectors, enlarge road Double_t boundaryWidth=AliITSRecoParam::GetBoundaryWidth(); if ( (track->GetY()-dy < det.GetYmin()+boundaryWidth) || (track->GetY()+dy > det.GetYmax()-boundaryWidth) || (track->GetZ()-dz < det.GetZmin()+boundaryWidth) || (track->GetZ()+dz > det.GetZmax()-boundaryWidth) ) { Float_t tgl = TMath::Abs(track->GetTgl()); if (tgl > 1.) tgl=1.; Double_t deltaXNeighbDets=AliITSRecoParam::GetDeltaXNeighbDets(); dz = TMath::Sqrt(dz*dz+deltaXNeighbDets*deltaXNeighbDets*tgl*tgl); Float_t snp = TMath::Abs(track->GetSnp()); if (snp > AliITSReconstructor::GetRecoParam()->GetMaxSnp()) return kFALSE; dy = TMath::Sqrt(dy*dy+deltaXNeighbDets*deltaXNeighbDets*snp*snp); } // boundary // add to the road a term (up to 2-3 mm) to deal with misalignments dy = TMath::Sqrt(dy*dy + AliITSReconstructor::GetRecoParam()->GetRoadMisal()*AliITSReconstructor::GetRecoParam()->GetRoadMisal()); dz = TMath::Sqrt(dz*dz + AliITSReconstructor::GetRecoParam()->GetRoadMisal()*AliITSReconstructor::GetRecoParam()->GetRoadMisal()); Double_t r = fgLayers[ilayer].GetR(); zmin = track->GetZ() - dz; zmax = track->GetZ() + dz; ymin = track->GetY() + r*det.GetPhi() - dy; ymax = track->GetY() + r*det.GetPhi() + dy; // bring track back to idead detector plane if (!track->Propagate(det.GetPhi(),det.GetR())) return kFALSE; return kTRUE; } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSlayer:: SelectClusters(Double_t zmin,Double_t zmax,Double_t ymin, Double_t ymax) { //-------------------------------------------------------------------- // This function sets the "window" //-------------------------------------------------------------------- Double_t circle=2*TMath::Pi()*fR; fYmin = ymin; fYmax =ymax; Float_t ymiddle = (fYmin+fYmax)*0.5; if (ymiddle<fYB[0]) { fYmin+=circle; fYmax+=circle; ymiddle+=circle; } else if (ymiddle>fYB[1]) { fYmin-=circle; fYmax-=circle; ymiddle-=circle; } // fCurrentSlice =-1; // defualt take all fClustersCs = fClusters; fClusterIndexCs = fClusterIndex; fYcs = fY; fZcs = fZ; fNcs = fN; // //is in 20 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy20){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy20); if (slice<0) slice=0; if (slice>20) slice=20; Bool_t isOK = (fYmin>fBy20[slice][0]&&fYmax<fBy20[slice][1]); if (isOK) { fCurrentSlice=slice; fClustersCs = fClusters20[fCurrentSlice]; fClusterIndexCs = fClusterIndex20[fCurrentSlice]; fYcs = fY20[fCurrentSlice]; fZcs = fZ20[fCurrentSlice]; fNcs = fN20[fCurrentSlice]; } } // //is in 10 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy10){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy10); if (slice<0) slice=0; if (slice>10) slice=10; Bool_t isOK = (fYmin>fBy10[slice][0]&&fYmax<fBy10[slice][1]); if (isOK) { fCurrentSlice=slice; fClustersCs = fClusters10[fCurrentSlice]; fClusterIndexCs = fClusterIndex10[fCurrentSlice]; fYcs = fY10[fCurrentSlice]; fZcs = fZ10[fCurrentSlice]; fNcs = fN10[fCurrentSlice]; } } // //is in 5 slice? if (fCurrentSlice<0&&TMath::Abs(fYmax-fYmin)<1.49*fDy5){ Int_t slice = int(0.5+(ymiddle-fYB[0])/fDy5); if (slice<0) slice=0; if (slice>5) slice=5; Bool_t isOK = (fYmin>fBy5[slice][0]&&fYmax<fBy5[slice][1]); if (isOK) { fCurrentSlice=slice; fClustersCs = fClusters5[fCurrentSlice]; fClusterIndexCs = fClusterIndex5[fCurrentSlice]; fYcs = fY5[fCurrentSlice]; fZcs = fZ5[fCurrentSlice]; fNcs = fN5[fCurrentSlice]; } } // fI=FindClusterIndex(zmin); fZmax=zmax; fImax = TMath::Min(FindClusterIndex(zmax)+1,fNcs); fSkip = 0; fAccepted =0; return; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::AliITSlayer:: FindDetectorIndex(Double_t phi, Double_t z) const { //-------------------------------------------------------------------- //This function finds the detector crossed by the track //-------------------------------------------------------------------- Double_t dphi; if (fZOffset<0) // old geometry dphi = -(phi-fPhiOffset); else // new geometry dphi = phi-fPhiOffset; if (dphi < 0) dphi += 2*TMath::Pi(); else if (dphi >= 2*TMath::Pi()) dphi -= 2*TMath::Pi(); Int_t np=Int_t(dphi*fNladders*0.5/TMath::Pi()+0.5); if (np>=fNladders) np-=fNladders; if (np<0) np+=fNladders; Double_t dz=fZOffset-z; Double_t nnz = dz*(fNdetectors-1)*0.5/fZOffset+0.5; Int_t nz = (nnz<0 ? -1 : (Int_t)nnz); if (nz>=fNdetectors) return -1; if (nz<0) return -1; // ad hoc correction for 3rd ladder of SDD inner layer, // which is reversed (rotated by pi around local y) // this correction is OK only from AliITSv11Hybrid onwards if (GetR()>12. && GetR()<20.) { // SDD inner if(np==2) { // 3rd ladder nz = (fNdetectors-1) - nz; } } //printf("ndet %d phi %f z %f np %d nz %d\n",fNdetectors,phi,z,np,nz); return np*fNdetectors + nz; } //------------------------------------------------------------------------ const AliITSRecPoint *AliITStrackerMI::AliITSlayer::GetNextCluster(Int_t &ci,Bool_t test) { //-------------------------------------------------------------------- // This function returns clusters within the "window" //-------------------------------------------------------------------- if (fCurrentSlice<0) { Double_t rpi2 = 2.*fR*TMath::Pi(); for (Int_t i=fI; i<fImax; i++) { Double_t y = fY[i]; if (fYmax<y) y -= rpi2; if (fYmin>y) y += rpi2; if (y<fYmin) continue; if (y>fYmax) continue; if (fClusters[i]->GetQ()==0&&fSkip==2) continue; ci=i; if (!test) fI=i+1; return fClusters[i]; } } else { for (Int_t i=fI; i<fImax; i++) { if (fYcs[i]<fYmin) continue; if (fYcs[i]>fYmax) continue; if (fClustersCs[i]->GetQ()==0&&fSkip==2) continue; ci=fClusterIndexCs[i]; if (!test) fI=i+1; return fClustersCs[i]; } } return 0; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::AliITSlayer::GetThickness(Double_t y,Double_t z,Double_t &x0) const { //-------------------------------------------------------------------- // This function returns the layer thickness at this point (units X0) //-------------------------------------------------------------------- Double_t d=0.0085; x0=AliITSRecoParam::GetX0Air(); if (43<fR&&fR<45) { //SSD2 Double_t dd=0.0034; d=dd; if (TMath::Abs(y-0.00)>3.40) d+=dd; if (TMath::Abs(y-1.90)<0.45) {d+=(0.013-0.0034);} if (TMath::Abs(y+1.90)<0.45) {d+=(0.013-0.0034);} for (Int_t i=0; i<12; i++) { if (TMath::Abs(z-3.9*(i+0.5))<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=0.0034; break; } if (TMath::Abs(z+3.9*(i+0.5))<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=0.0034; break; } if (TMath::Abs(z-3.4-3.9*i)<0.50) {d+=(0.016-0.0034); break;} if (TMath::Abs(z+0.5+3.9*i)<0.50) {d+=(0.016-0.0034); break;} } } else if (37<fR&&fR<41) { //SSD1 Double_t dd=0.0034; d=dd; if (TMath::Abs(y-0.00)>3.40) d+=dd; if (TMath::Abs(y-1.90)<0.45) {d+=(0.013-0.0034);} if (TMath::Abs(y+1.90)<0.45) {d+=(0.013-0.0034);} for (Int_t i=0; i<11; i++) { if (TMath::Abs(z-3.9*i)<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=dd; break; } if (TMath::Abs(z+3.9*i)<0.15) { if (TMath::Abs(y-0.00)>3.40) d+=dd; d+=dd; break; } if (TMath::Abs(z-1.85-3.9*i)<0.50) {d+=(0.016-0.0034); break;} if (TMath::Abs(z+2.05+3.9*i)<0.50) {d+=(0.016-0.0034); break;} } } else if (13<fR&&fR<26) { //SDD Double_t dd=0.0033; d=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; if (TMath::Abs(y-1.80)<0.55) { d+=0.016; for (Int_t j=0; j<20; j++) { if (TMath::Abs(z+0.7+1.47*j)<0.12) {d+=0.08; x0=9.; break;} if (TMath::Abs(z-0.7-1.47*j)<0.12) {d+=0.08; x0=9.; break;} } } if (TMath::Abs(y+1.80)<0.55) { d+=0.016; for (Int_t j=0; j<20; j++) { if (TMath::Abs(z-0.7-1.47*j)<0.12) {d+=0.08; x0=9.; break;} if (TMath::Abs(z+0.7+1.47*j)<0.12) {d+=0.08; x0=9.; break;} } } for (Int_t i=0; i<4; i++) { if (TMath::Abs(z-7.3*i)<0.60) { d+=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; break; } if (TMath::Abs(z+7.3*i)<0.60) { d+=dd; if (TMath::Abs(y-0.00)>3.30) d+=dd; break; } } } else if (6<fR&&fR<8) { //SPD2 Double_t dd=0.0063; x0=21.5; d=dd; if (TMath::Abs(y-3.08)>0.5) d+=dd; if (TMath::Abs(y-3.03)<0.10) d+=0.014; } else if (3<fR&&fR<5) { //SPD1 Double_t dd=0.0063; x0=21.5; d=dd; if (TMath::Abs(y+0.21)>0.6) d+=dd; if (TMath::Abs(y+0.10)<0.10) d+=0.014; } return d; } //------------------------------------------------------------------------ AliITStrackerMI::AliITSdetector::AliITSdetector(const AliITSdetector& det): fR(det.fR), fRmisal(det.fRmisal), fPhi(det.fPhi), fSinPhi(det.fSinPhi), fCosPhi(det.fCosPhi), fYmin(det.fYmin), fYmax(det.fYmax), fZmin(det.fZmin), fZmax(det.fZmax), fIsBad(det.fIsBad), fNChips(det.fNChips), fChipIsBad(det.fChipIsBad) { //Copy constructor } //------------------------------------------------------------------------ void AliITStrackerMI::AliITSdetector::ReadBadDetectorAndChips(Int_t ilayer,Int_t idet, AliITSDetTypeRec *detTypeRec) { //-------------------------------------------------------------------- // Read bad detectors and chips from calibration objects in AliITSDetTypeRec //-------------------------------------------------------------------- // In AliITSDetTypeRec, detector numbers go from 0 to 2197 // while in the tracker they start from 0 for each layer for(Int_t il=0; il<ilayer; il++) idet += AliITSgeomTGeo::GetNLadders(il+1)*AliITSgeomTGeo::GetNDetectors(il+1); Int_t detType; if (ilayer==0 || ilayer==1) { // ---------- SPD detType = 0; } else if (ilayer==2 || ilayer==3) { // ---------- SDD detType = 1; } else if (ilayer==4 || ilayer==5) { // ---------- SSD detType = 2; } else { printf("AliITStrackerMI::AliITSdetector::InitBadFromOCDB: Wrong layer number %d\n",ilayer); return; } // Get calibration from AliITSDetTypeRec AliITSCalibration *calib = (AliITSCalibration*)detTypeRec->GetCalibrationModel(idet); calib->SetModuleIndex(idet); AliITSCalibration *calibSPDdead = 0; if(detType==0) calibSPDdead = (AliITSCalibration*)detTypeRec->GetSPDDeadModel(idet); // TEMPORARY if (calib->IsBad() || (detType==0 && calibSPDdead->IsBad())) // TEMPORARY { SetBad(); // printf("lay %d bad %d\n",ilayer,idet); } // Get segmentation from AliITSDetTypeRec AliITSsegmentation *segm = (AliITSsegmentation*)detTypeRec->GetSegmentationModel(detType); // Read info about bad chips fNChips = segm->GetMaximumChipIndex()+1; //printf("ilayer %d detType %d idet %d fNChips %d %d GetNumberOfChips %d\n",ilayer,detType,idet,fNChips,segm->GetMaximumChipIndex(),segm->GetNumberOfChips()); if(fChipIsBad) { delete [] fChipIsBad; fChipIsBad=NULL; } fChipIsBad = new Bool_t[fNChips]; for (Int_t iCh=0;iCh<fNChips;iCh++) { fChipIsBad[iCh] = calib->IsChipBad(iCh); if (detType==0 && calibSPDdead->IsChipBad(iCh)) fChipIsBad[iCh] = kTRUE; // TEMPORARY //if(fChipIsBad[iCh]) {printf("lay %d det %d bad chip %d\n",ilayer,idet,iCh);} } return; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetEffectiveThickness() { //-------------------------------------------------------------------- // Returns the thickness between the current layer and the vertex (units X0) //-------------------------------------------------------------------- if(fUseTGeo!=0) { if(fxOverX0Layer[0]<0) BuildMaterialLUT("Layers"); if(fxOverX0Shield[0]<0) BuildMaterialLUT("Shields"); if(fxOverX0Pipe<0) BuildMaterialLUT("Pipe"); } // beam pipe Double_t dPipe = (fUseTGeo==0 ? AliITSRecoParam::GetdPipe() : fxOverX0Pipe); Double_t d=dPipe*AliITSRecoParam::GetrPipe()*AliITSRecoParam::GetrPipe(); // layers Double_t x0=0; Double_t xn=fgLayers[fI].GetR(); for (Int_t i=0; i<fI; i++) { Double_t xi=fgLayers[i].GetR(); Double_t dLayer = (fUseTGeo==0 ? fgLayers[i].GetThickness(0,0,x0) : fxOverX0Layer[i]); d+=dLayer*xi*xi; } // shields if (fI>1) { Double_t dshieldSPD = (fUseTGeo==0 ? AliITSRecoParam::Getdshield(0) : fxOverX0Shield[0]); d+=dshieldSPD*AliITSRecoParam::GetrInsideShield(0)*AliITSRecoParam::GetrInsideShield(0); } if (fI>3) { Double_t dshieldSDD = (fUseTGeo==0 ? AliITSRecoParam::Getdshield(1) : fxOverX0Shield[1]); d+=dshieldSDD*AliITSRecoParam::GetrInsideShield(1)*AliITSRecoParam::GetrInsideShield(1); } return d/(xn*xn); } //------------------------------------------------------------------------ Int_t AliITStrackerMI::AliITSlayer::InRoad() const { //------------------------------------------------------------------- // This function returns number of clusters within the "window" //-------------------------------------------------------------------- Int_t ncl=0; for (Int_t i=fI; i<fN; i++) { const AliITSRecPoint *c=fClusters[i]; if (c->GetZ() > fZmax) break; if (c->IsUsed()) continue; const AliITSdetector &det=GetDetector(c->GetDetectorIndex()); Double_t y=fR*det.GetPhi() + c->GetY(); if (y>2.*fR*TMath::Pi()) y -= 2*fR*TMath::Pi(); if (y>1.*fR*TMath::Pi() && fYmax<y) y -= 2*fR*TMath::Pi(); if (y<fYmin) continue; if (y>fYmax) continue; ncl++; } return ncl; } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *track, const AliITStrackMI *clusters,Bool_t extra, Bool_t planeeff) { //-------------------------------------------------------------------- // This function refits the track "track" at the position "x" using // the clusters from "clusters" // If "extra"==kTRUE, // the clusters from overlapped modules get attached to "track" // If "planeff"==kTRUE, // special approach for plane efficiency evaluation is applyed //-------------------------------------------------------------------- Int_t index[AliITSgeomTGeo::kNLayers]; Int_t k; for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1; Int_t nc=clusters->GetNumberOfClusters(); for (k=0; k<nc; k++) { Int_t idx=clusters->GetClusterIndex(k); Int_t ilayer=(idx&0xf0000000)>>28; index[ilayer]=idx; } return RefitAt(xx,track,index,extra,planeeff); // call the method below } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *track, const Int_t *clusters,Bool_t extra, Bool_t planeeff) { //-------------------------------------------------------------------- // This function refits the track "track" at the position "x" using // the clusters from array // If "extra"==kTRUE, // the clusters from overlapped modules get attached to "track" // If "planeff"==kTRUE, // special approach for plane efficiency evaluation is applyed //-------------------------------------------------------------------- Int_t index[AliITSgeomTGeo::kNLayers]; Int_t k; for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1; // for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) { index[k]=clusters[k]; } // special for cosmics: check which the innermost layer crossed // by the track Int_t innermostlayer=5; Double_t drphi = TMath::Abs(track->GetD(0.,0.)); for(innermostlayer=0; innermostlayer<AliITSgeomTGeo::GetNLayers(); innermostlayer++) { if(drphi < fgLayers[innermostlayer].GetR()) break; } //printf(" drphi %f innermost %d\n",drphi,innermostlayer); Int_t modstatus=1; // found Float_t xloc,zloc; Int_t from, to, step; if (xx > track->GetX()) { from=innermostlayer; to=AliITSgeomTGeo::GetNLayers(); step=+1; } else { from=AliITSgeomTGeo::GetNLayers()-1; to=innermostlayer-1; step=-1; } TString dir = (step>0 ? "outward" : "inward"); for (Int_t ilayer = from; ilayer != to; ilayer += step) { AliITSlayer &layer=fgLayers[ilayer]; Double_t r=layer.GetR(); if (step<0 && xx>r) break; // material between SSD and SDD, SDD and SPD Double_t hI=ilayer-0.5*step; if (TMath::Abs(hI-3.5)<0.01) // SDDouter if(!CorrectForShieldMaterial(track,"SDD",dir)) return kFALSE; if (TMath::Abs(hI-1.5)<0.01) // SPDouter if(!CorrectForShieldMaterial(track,"SPD",dir)) return kFALSE; // remember old position [SR, GSI 18.02.2003] Double_t oldX=0., oldY=0., oldZ=0.; if (track->IsStartedTimeIntegral() && step==1) { if (!track->GetGlobalXYZat(track->GetX(),oldX,oldY,oldZ)) return kFALSE; } // Double_t oldGlobXYZ[3]; if (!track->GetXYZ(oldGlobXYZ)) return kFALSE; //TMath::Sqrt(track->GetSigmaY2()); Double_t phi,z; if (!track->GetPhiZat(r,phi,z)) return kFALSE; Int_t idet=layer.FindDetectorIndex(phi,z); // check if we allow a prolongation without point for large-eta tracks Int_t skip = CheckSkipLayer(track,ilayer,idet); if (skip==2) { // propagate to the layer radius Double_t xToGo; if (!track->GetLocalXat(r,xToGo)) return kFALSE; if (!track->Propagate(xToGo)) return kFALSE; // apply correction for material of the current layer CorrectForLayerMaterial(track,ilayer,oldGlobXYZ,dir); modstatus = 4; // out in z if(LocalModuleCoord(ilayer,idet,track,xloc,zloc)) { // local module coords track->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); } // track time update [SR, GSI 17.02.2003] if (track->IsStartedTimeIntegral() && step==1) { Double_t newX, newY, newZ; if (!track->GetGlobalXYZat(track->GetX(),newX,newY,newZ)) return kFALSE; Double_t dL2 = (oldX-newX)*(oldX-newX) + (oldY-newY)*(oldY-newY) + (oldZ-newZ)*(oldZ-newZ); track->AddTimeStep(TMath::Sqrt(dL2)); } continue; } if (idet<0) return kFALSE; const AliITSdetector &det=layer.GetDetector(idet); if (!track->Propagate(det.GetPhi(),det.GetR())) return kFALSE; track->SetDetectorIndex(idet); if(!LocalModuleCoord(ilayer,idet,track,xloc,zloc)) return kFALSE; // local module coords Double_t dz,zmin,zmax,dy,ymin,ymax; const AliITSRecPoint *clAcc=0; Double_t maxchi2=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2(); Int_t idx=index[ilayer]; if (idx>=0) { // cluster in this layer modstatus = 6; // no refit const AliITSRecPoint *cl=(AliITSRecPoint *)GetCluster(idx); if (cl) { if (idet != cl->GetDetectorIndex()) { idet=cl->GetDetectorIndex(); const AliITSdetector &detc=layer.GetDetector(idet); if (!track->Propagate(detc.GetPhi(),detc.GetR())) return kFALSE; track->SetDetectorIndex(idet); if(!LocalModuleCoord(ilayer,idet,track,xloc,zloc)) return kFALSE; // local module coords } Int_t cllayer = (idx & 0xf0000000) >> 28;; Double_t chi2=GetPredictedChi2MI(track,cl,cllayer); if (chi2<maxchi2) { clAcc=cl; maxchi2=chi2; modstatus = 1; // found } else { return kFALSE; // } } } else { // no cluster in this layer if (skip==1) { modstatus = 3; // skipped // Plane Eff determination: if (planeeff && ilayer==AliITSReconstructor::GetRecoParam()->GetIPlanePlaneEff()) { if (IsOKForPlaneEff(track,clusters,ilayer)) // only adequate track for plane eff. evaluation UseTrackForPlaneEff(track,ilayer); } } else { modstatus = 5; // no cls in road // check dead if (!ComputeRoad(track,ilayer,idet,zmin,zmax,ymin,ymax)) return kFALSE; dz = 0.5*(zmax-zmin); dy = 0.5*(ymax-ymin); Int_t dead = CheckDeadZone(track,ilayer,idet,dz,dy,kTRUE); if (dead==1) modstatus = 7; // holes in z in SPD if (dead==2 || dead==3) modstatus = 2; // dead from OCDB } } if (clAcc) { if (!UpdateMI(track,clAcc,maxchi2,idx)) return kFALSE; track->SetSampledEdx(clAcc->GetQ(),track->GetNumberOfClusters()-1); } track->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc); if (extra) { // search for extra clusters in overlapped modules AliITStrackV2 tmp(*track); if (!ComputeRoad(track,ilayer,idet,zmin,zmax,ymin,ymax)) return kFALSE; layer.SelectClusters(zmin,zmax,ymin,ymax); const AliITSRecPoint *clExtra=0; Int_t ci=-1,cci=-1; Int_t idetExtra=-1; maxchi2=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2(); Double_t tolerance=0.1; while ((clExtra=layer.GetNextCluster(ci))!=0) { // only clusters in another module! (overlaps) idetExtra = clExtra->GetDetectorIndex(); if (idet == idetExtra) continue; const AliITSdetector &detx=layer.GetDetector(idetExtra); if (!tmp.Propagate(detx.GetPhi(),detx.GetR()+clExtra->GetX())) continue; if (TMath::Abs(tmp.GetZ() - clExtra->GetZ()) > tolerance) continue; if (TMath::Abs(tmp.GetY() - clExtra->GetY()) > tolerance) continue; if (!tmp.Propagate(detx.GetPhi(),detx.GetR())) continue; Double_t chi2=tmp.GetPredictedChi2(clExtra); if (chi2<maxchi2) { maxchi2=chi2; cci=ci; } } if (cci>=0) { track->SetExtraCluster(ilayer,(ilayer<<28)+cci); track->SetExtraModule(ilayer,idetExtra); } } // end search for extra clusters in overlapped modules // Correct for material of the current layer if(!CorrectForLayerMaterial(track,ilayer,oldGlobXYZ,dir)) return kFALSE; // track time update [SR, GSI 17.02.2003] if (track->IsStartedTimeIntegral() && step==1) { Double_t newX, newY, newZ; if (!track->GetGlobalXYZat(track->GetX(),newX,newY,newZ)) return kFALSE; Double_t dL2 = (oldX-newX)*(oldX-newX) + (oldY-newY)*(oldY-newY) + (oldZ-newZ)*(oldZ-newZ); track->AddTimeStep(TMath::Sqrt(dL2)); } // } // end loop on layers if (!track->Propagate(xx)) return kFALSE; return kTRUE; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetNormalizedChi2(AliITStrackMI * track, Int_t mode) { // // calculate normalized chi2 // return NormalizedChi2(track,0); Float_t chi2 = 0; Float_t sum=0; Float_t *erry = GetErrY(fCurrentEsdTrack), *errz = GetErrZ(fCurrentEsdTrack); // track->fdEdxMismatch=0; Float_t dedxmismatch =0; Float_t *ny = GetNy(fCurrentEsdTrack), *nz = GetNz(fCurrentEsdTrack); if (mode<100){ for (Int_t i = 0;i<6;i++){ if (track->GetClIndex(i)>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->GetSigmaY(i); cerrz = track->GetSigmaZ(i);} cerry*=cerry; cerrz*=cerrz; Float_t cchi2 = (track->GetDy(i)*track->GetDy(i)/cerry)+(track->GetDz(i)*track->GetDz(i)/cerrz); if (i>1 && AliITSReconstructor::GetRecoParam()->GetUseAmplitudeInfo(i)) { Float_t ratio = track->GetNormQ(i)/track->GetExpQ(); if (ratio<0.5) { cchi2+=(0.5-ratio)*10.; //track->fdEdxMismatch+=(0.5-ratio)*10.; dedxmismatch+=(0.5-ratio)*10.; } } if (i<2 ||i>3){ AliITSRecPoint * cl = (AliITSRecPoint*)GetCluster( track->GetClIndex(i)); Double_t delta = cl->GetNy()+cl->GetNz()-ny[i]-nz[i]; if (delta>1) chi2 +=0.5*TMath::Min(delta/2,2.); if (i<2) chi2+=2*cl->GetDeltaProbability(); } chi2+=cchi2; sum++; } } if (TMath::Abs(track->GetdEdxMismatch()-dedxmismatch)>0.0001){ track->SetdEdxMismatch(dedxmismatch); } } else{ for (Int_t i = 0;i<4;i++){ if (track->GetClIndex(i)>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->GetSigmaY(i); cerrz = track->GetSigmaZ(i);} cerry*=cerry; cerrz*=cerrz; chi2+= (track->GetDy(i)*track->GetDy(i)/cerry); chi2+= (track->GetDz(i)*track->GetDz(i)/cerrz); sum++; } } for (Int_t i = 4;i<6;i++){ if (track->GetClIndex(i)>0){ Float_t cerry, cerrz; if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];} else { cerry= track->GetSigmaY(i); cerrz = track->GetSigmaZ(i);} cerry*=cerry; cerrz*=cerrz; Float_t cerryb, cerrzb; if (ny[i+6]>0) {cerryb = erry[i+6]; cerrzb=errz[i+6];} else { cerryb= track->GetSigmaY(i+6); cerrzb = track->GetSigmaZ(i+6);} cerryb*=cerryb; cerrzb*=cerrzb; chi2+= TMath::Min((track->GetDy(i+6)*track->GetDy(i+6)/cerryb),track->GetDy(i)*track->GetDy(i)/cerry); chi2+= TMath::Min((track->GetDz(i+6)*track->GetDz(i+6)/cerrzb),track->GetDz(i)*track->GetDz(i)/cerrz); sum++; } } } if (track->GetESDtrack()->GetTPCsignal()>85){ Float_t ratio = track->GetdEdx()/track->GetESDtrack()->GetTPCsignal(); if (ratio<0.5) { chi2+=(0.5-ratio)*5.; } if (ratio>2){ chi2+=(ratio-2.0)*3; } } // Double_t match = TMath::Sqrt(track->GetChi22()); if (track->GetConstrain()) match/=track->GetNumberOfClusters(); if (!track->GetConstrain()) { if (track->GetNumberOfClusters()>2) { match/=track->GetNumberOfClusters()-2.; } else { match=0; } } if (match<0) match=0; Float_t deadzonefactor = (track->GetNDeadZone()>0) ? 3*(1.1-track->GetDeadZoneProbability()):0.; Double_t normchi2 = 2*track->GetNSkipped()+match+deadzonefactor+(1+(2*track->GetNSkipped()+deadzonefactor)/track->GetNumberOfClusters())* (chi2)/TMath::Max(double(sum-track->GetNSkipped()), 1./(1.+track->GetNSkipped())); return normchi2; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetMatchingChi2(AliITStrackMI * track1, AliITStrackMI * track2) { // // return matching chi2 between two tracks Double_t largeChi2=1000.; AliITStrackMI track3(*track2); if (!track3.Propagate(track1->GetAlpha(),track1->GetX())) return largeChi2; TMatrixD vec(5,1); vec(0,0)=track1->GetY() - track3.GetY(); vec(1,0)=track1->GetZ() - track3.GetZ(); vec(2,0)=track1->GetSnp() - track3.GetSnp(); vec(3,0)=track1->GetTgl() - track3.GetTgl(); vec(4,0)=track1->GetSigned1Pt() - track3.GetSigned1Pt(); // TMatrixD cov(5,5); cov(0,0) = track1->GetSigmaY2()+track3.GetSigmaY2(); cov(1,1) = track1->GetSigmaZ2()+track3.GetSigmaZ2(); cov(2,2) = track1->GetSigmaSnp2()+track3.GetSigmaSnp2(); cov(3,3) = track1->GetSigmaTgl2()+track3.GetSigmaTgl2(); cov(4,4) = track1->GetSigma1Pt2()+track3.GetSigma1Pt2(); cov(0,1)=cov(1,0) = track1->GetSigmaZY()+track3.GetSigmaZY(); cov(0,2)=cov(2,0) = track1->GetSigmaSnpY()+track3.GetSigmaSnpY(); cov(0,3)=cov(3,0) = track1->GetSigmaTglY()+track3.GetSigmaTglY(); cov(0,4)=cov(4,0) = track1->GetSigma1PtY()+track3.GetSigma1PtY(); // cov(1,2)=cov(2,1) = track1->GetSigmaSnpZ()+track3.GetSigmaSnpZ(); cov(1,3)=cov(3,1) = track1->GetSigmaTglZ()+track3.GetSigmaTglZ(); cov(1,4)=cov(4,1) = track1->GetSigma1PtZ()+track3.GetSigma1PtZ(); // cov(2,3)=cov(3,2) = track1->GetSigmaTglSnp()+track3.GetSigmaTglSnp(); cov(2,4)=cov(4,2) = track1->GetSigma1PtSnp()+track3.GetSigma1PtSnp(); // cov(3,4)=cov(4,3) = track1->GetSigma1PtTgl()+track3.GetSigma1PtTgl(); cov.Invert(); TMatrixD vec2(cov,TMatrixD::kMult,vec); TMatrixD chi2(vec2,TMatrixD::kTransposeMult,vec); return chi2(0,0); } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetSPDDeadZoneProbability(Double_t zpos, Double_t zerr) { // // return probability that given point (characterized by z position and error) // is in SPD dead zone // Double_t probability = 0.; Double_t absz = TMath::Abs(zpos); Double_t nearestz = (absz<2.) ? 0.5*(fSPDdetzcentre[1]+fSPDdetzcentre[2]) : 0.5*(fSPDdetzcentre[2]+fSPDdetzcentre[3]); if (TMath::Abs(absz-nearestz)>0.25+3.*zerr) return probability; Double_t zmin, zmax; if (zpos<-6.) { // dead zone at z = -7 zmin = fSPDdetzcentre[0] + 0.5*AliITSRecoParam::GetSPDdetzlength(); zmax = fSPDdetzcentre[1] - 0.5*AliITSRecoParam::GetSPDdetzlength(); } else if (zpos>6.) { // dead zone at z = +7 zmin = fSPDdetzcentre[2] + 0.5*AliITSRecoParam::GetSPDdetzlength(); zmax = fSPDdetzcentre[3] - 0.5*AliITSRecoParam::GetSPDdetzlength(); } else if (absz<2.) { // dead zone at z = 0 zmin = fSPDdetzcentre[1] + 0.5*AliITSRecoParam::GetSPDdetzlength(); zmax = fSPDdetzcentre[2] - 0.5*AliITSRecoParam::GetSPDdetzlength(); } else { zmin = 0.; zmax = 0.; } // probability that the true z is in the range [zmin,zmax] (i.e. inside // dead zone) probability = 0.5*( TMath::Erf((zpos-zmin)/zerr/TMath::Sqrt(2.)) - TMath::Erf((zpos-zmax)/zerr/TMath::Sqrt(2.)) ); return probability; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetTruncatedChi2(AliITStrackMI * track, Float_t fac) { // // calculate normalized chi2 Float_t chi2[6]; Float_t *erry = GetErrY(fCurrentEsdTrack), *errz = GetErrZ(fCurrentEsdTrack); Float_t ncl = 0; for (Int_t i = 0;i<6;i++){ if (TMath::Abs(track->GetDy(i))>0){ chi2[i]= (track->GetDy(i)/erry[i])*(track->GetDy(i)/erry[i]); chi2[i]+= (track->GetDz(i)/errz[i])*(track->GetDz(i)/errz[i]); ncl++; } else{chi2[i]=10000;} } Int_t index[6]; TMath::Sort(6,chi2,index,kFALSE); Float_t max = float(ncl)*fac-1.; Float_t sumchi=0, sumweight=0; for (Int_t i=0;i<max+1;i++){ Float_t weight = (i<max)?1.:(max+1.-i); sumchi+=weight*chi2[index[i]]; sumweight+=weight; } Double_t normchi2 = sumchi/sumweight; return normchi2; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetInterpolatedChi2(AliITStrackMI * forwardtrack, AliITStrackMI * backtrack) { // // calculate normalized chi2 // if (forwardtrack->fNUsed>0.3*float(forwardtrack->GetNumberOfClusters())) return 10000; Int_t npoints = 0; Double_t res =0; for (Int_t i=0;i<6;i++){ if ( (backtrack->GetSigmaY(i)<0.000000001) || (forwardtrack->GetSigmaY(i)<0.000000001)) continue; Double_t sy1 = forwardtrack->GetSigmaY(i); Double_t sz1 = forwardtrack->GetSigmaZ(i); Double_t sy2 = backtrack->GetSigmaY(i); Double_t sz2 = backtrack->GetSigmaZ(i); if (i<2){ sy2=1000.;sz2=1000;} // Double_t dy0 = (forwardtrack->GetDy(i)/(sy1*sy1) +backtrack->GetDy(i)/(sy2*sy2))/(1./(sy1*sy1)+1./(sy2*sy2)); Double_t dz0 = (forwardtrack->GetDz(i)/(sz1*sz1) +backtrack->GetDz(i)/(sz2*sz2))/(1./(sz1*sz1)+1./(sz2*sz2)); // Double_t nz0 = dz0*TMath::Sqrt((1./(sz1*sz1)+1./(sz2*sz2))); Double_t ny0 = dy0*TMath::Sqrt((1./(sy1*sy1)+1./(sy2*sy2))); // res+= nz0*nz0+ny0*ny0; npoints++; } if (npoints>1) return TMath::Max(0.3*forwardtrack->OneOverPt()-0.5,0.)+ //2*forwardtrack->fNUsed+ res/TMath::Max(double(npoints-forwardtrack->GetNSkipped()), 1./(1.+forwardtrack->GetNSkipped())); return 1000; } //------------------------------------------------------------------------ Float_t *AliITStrackerMI::GetWeight(Int_t index) { //-------------------------------------------------------------------- // Return pointer to a given cluster //-------------------------------------------------------------------- Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; return fgLayers[l].GetWeight(c); } //------------------------------------------------------------------------ void AliITStrackerMI::RegisterClusterTracks(AliITStrackMI* track,Int_t id) { //--------------------------------------------- // register track to the list // if (track->GetESDtrack()->GetKinkIndex(0)!=0) return; //don't register kink tracks // // for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].GetNumberOfClusters()) continue; for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].GetClusterTracks(itrack,c)<0){ fgLayers[l].SetClusterTracks(itrack,c,id); break; } } } } //------------------------------------------------------------------------ void AliITStrackerMI::UnRegisterClusterTracks(AliITStrackMI* track, Int_t id) { //--------------------------------------------- // unregister track from the list for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].GetNumberOfClusters()) continue; for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].GetClusterTracks(itrack,c)==id){ fgLayers[l].SetClusterTracks(itrack,c,-1); } } } } //------------------------------------------------------------------------ Float_t AliITStrackerMI::GetNumberOfSharedClusters(AliITStrackMI* track,Int_t id, Int_t list[6], AliITSRecPoint *clist[6]) { //------------------------------------------------------------- //get number of shared clusters //------------------------------------------------------------- Float_t shared=0; for (Int_t i=0;i<6;i++) { list[i]=-1, clist[i]=0;} // mean number of clusters Float_t *ny = GetNy(id), *nz = GetNz(id); for (Int_t icluster=0;icluster<track->GetNumberOfClusters();icluster++){ Int_t index = track->GetClusterIndex(icluster); Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].GetNumberOfClusters()) continue; if (ny[l]==0){ printf("problem\n"); } AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(index); Float_t weight=1; // Float_t deltan = 0; if (l>3&&cl->GetNy()+cl->GetNz()>6) continue; if (l>2&&AliITSReconstructor::GetRecoParam()->GetUseAmplitudeInfo(l)) if (track->GetNormQ(l)/track->GetExpQ()>3.5) continue; if (l<2 || l>3){ deltan = (cl->GetNy()+cl->GetNz()-ny[l]-nz[l]); } else{ deltan = (cl->GetNz()-nz[l]); } if (deltan>2.0) continue; // extended - highly probable shared cluster weight = 2./TMath::Max(3.+deltan,2.); // for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[l].GetClusterTracks(itrack,c)>=0 && fgLayers[l].GetClusterTracks(itrack,c)!=id){ list[l]=index; clist[l] = (AliITSRecPoint*)GetCluster(index); shared+=weight; break; } } } track->SetNUsed(shared); return shared; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::GetOverlapTrack(AliITStrackMI *track, Int_t trackID, Int_t &shared, Int_t clusterlist[6],Int_t overlist[6]) { // // find first shared track // // mean number of clusters Float_t *ny = GetNy(trackID), *nz = GetNz(trackID); // for (Int_t i=0;i<6;i++) overlist[i]=-1; Int_t sharedtrack=100000; Int_t tracks[24],trackindex=0; for (Int_t i=0;i<24;i++) {tracks[i]=-1;} // for (Int_t icluster=0;icluster<6;icluster++){ if (clusterlist[icluster]<0) continue; Int_t index = clusterlist[icluster]; Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (ny[l]==0){ printf("problem\n"); } if (c>fgLayers[l].GetNumberOfClusters()) continue; //if (l>3) continue; AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(index); // Float_t deltan = 0; if (l>3&&cl->GetNy()+cl->GetNz()>6) continue; if (l>2&&AliITSReconstructor::GetRecoParam()->GetUseAmplitudeInfo(l)) if (track->GetNormQ(l)/track->GetExpQ()>3.5) continue; if (l<2 || l>3){ deltan = (cl->GetNy()+cl->GetNz()-ny[l]-nz[l]); } else{ deltan = (cl->GetNz()-nz[l]); } if (deltan>2.0) continue; // extended - highly probable shared cluster // for (Int_t itrack=3;itrack>=0;itrack--){ if (fgLayers[l].GetClusterTracks(itrack,c)<0) continue; if (fgLayers[l].GetClusterTracks(itrack,c)!=trackID){ tracks[trackindex] = fgLayers[l].GetClusterTracks(itrack,c); trackindex++; } } } if (trackindex==0) return -1; if (trackindex==1){ sharedtrack = tracks[0]; }else{ if (trackindex==2) sharedtrack =TMath::Min(tracks[0],tracks[1]); else{ // Int_t tracks2[24], cluster[24]; for (Int_t i=0;i<trackindex;i++){ tracks2[i]=-1; cluster[i]=0;} Int_t index =0; // for (Int_t i=0;i<trackindex;i++){ if (tracks[i]<0) continue; tracks2[index] = tracks[i]; cluster[index]++; for (Int_t j=i+1;j<trackindex;j++){ if (tracks[j]<0) continue; if (tracks[j]==tracks[i]){ cluster[index]++; tracks[j]=-1; } } index++; } Int_t max=0; for (Int_t i=0;i<index;i++){ if (cluster[index]>max) { sharedtrack=tracks2[index]; max=cluster[index]; } } } } if (sharedtrack>=100000) return -1; // // make list of overlaps shared =0; for (Int_t icluster=0;icluster<6;icluster++){ if (clusterlist[icluster]<0) continue; Int_t index = clusterlist[icluster]; Int_t l=(index & 0xf0000000) >> 28; Int_t c=(index & 0x0fffffff) >> 00; if (c>fgLayers[l].GetNumberOfClusters()) continue; AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(index); if (l==0 || l==1){ if (cl->GetNy()>2) continue; if (cl->GetNz()>2) continue; } if (l==4 || l==5){ if (cl->GetNy()>3) continue; if (cl->GetNz()>3) continue; } // for (Int_t itrack=3;itrack>=0;itrack--){ if (fgLayers[l].GetClusterTracks(itrack,c)<0) continue; if (fgLayers[l].GetClusterTracks(itrack,c)==sharedtrack){ overlist[l]=index; shared++; } } } return sharedtrack; } //------------------------------------------------------------------------ AliITStrackMI * AliITStrackerMI::GetBest2Tracks(Int_t trackID1, Int_t trackID2, Float_t th0, Float_t th1){ // // try to find track hypothesys without conflicts // with minimal chi2; TClonesArray *arr1 = (TClonesArray*)fTrackHypothesys.At(trackID1); Int_t entries1 = arr1->GetEntriesFast(); TClonesArray *arr2 = (TClonesArray*)fTrackHypothesys.At(trackID2); if (!arr2) return (AliITStrackMI*) arr1->UncheckedAt(0); Int_t entries2 = arr2->GetEntriesFast(); if (entries2<=0) return (AliITStrackMI*) arr1->UncheckedAt(0); // AliITStrackMI * track10=(AliITStrackMI*) arr1->UncheckedAt(0); AliITStrackMI * track20=(AliITStrackMI*) arr2->UncheckedAt(0); if (track10->Pt()>0.5+track20->Pt()) return track10; for (Int_t itrack=0;itrack<entries1;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr1->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID1); } // for (Int_t itrack=0;itrack<entries2;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr2->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID2); } Int_t index1=0; Int_t index2=0; Float_t maxconflicts=6; Double_t maxchi2 =1000.; // // get weight of hypothesys - using best hypothesy Double_t w1,w2; Int_t list1[6],list2[6]; AliITSRecPoint *clist1[6], *clist2[6] ; RegisterClusterTracks(track10,trackID1); RegisterClusterTracks(track20,trackID2); Float_t conflict1 = GetNumberOfSharedClusters(track10,trackID1,list1,clist1); Float_t conflict2 = GetNumberOfSharedClusters(track20,trackID2,list2,clist2); UnRegisterClusterTracks(track10,trackID1); UnRegisterClusterTracks(track20,trackID2); // // normalized chi2 Float_t chi21 =0,chi22=0,ncl1=0,ncl2=0; Float_t nerry[6],nerrz[6]; Float_t *erry1=GetErrY(trackID1),*errz1 = GetErrZ(trackID1); Float_t *erry2=GetErrY(trackID2),*errz2 = GetErrZ(trackID2); for (Int_t i=0;i<6;i++){ if ( (erry1[i]>0) && (erry2[i]>0)) { nerry[i] = TMath::Min(erry1[i],erry2[i]); nerrz[i] = TMath::Min(errz1[i],errz2[i]); }else{ nerry[i] = TMath::Max(erry1[i],erry2[i]); nerrz[i] = TMath::Max(errz1[i],errz2[i]); } if (TMath::Abs(track10->GetDy(i))>0.000000000000001){ chi21 += track10->GetDy(i)*track10->GetDy(i)/(nerry[i]*nerry[i]); chi21 += track10->GetDz(i)*track10->GetDz(i)/(nerrz[i]*nerrz[i]); ncl1++; } if (TMath::Abs(track20->GetDy(i))>0.000000000000001){ chi22 += track20->GetDy(i)*track20->GetDy(i)/(nerry[i]*nerry[i]); chi22 += track20->GetDz(i)*track20->GetDz(i)/(nerrz[i]*nerrz[i]); ncl2++; } } chi21/=ncl1; chi22/=ncl2; // // Float_t d1 = TMath::Sqrt(track10->GetD(0)*track10->GetD(0)+track10->GetD(1)*track10->GetD(1))+0.1; Float_t d2 = TMath::Sqrt(track20->GetD(0)*track20->GetD(0)+track20->GetD(1)*track20->GetD(1))+0.1; Float_t s1 = TMath::Sqrt(track10->GetSigmaY2()*track10->GetSigmaZ2()); Float_t s2 = TMath::Sqrt(track20->GetSigmaY2()*track20->GetSigmaZ2()); // w1 = (d2/(d1+d2)+ 2*s2/(s1+s2)+ +s2/(s1+s2)*0.5*(chi22+2.)/(chi21+chi22+4.) +1.*track10->Pt()/(track10->Pt()+track20->Pt()) ); w2 = (d1/(d1+d2)+ 2*s1/(s1+s2)+ s1/(s1+s2)*0.5*(chi21+2.)/(chi21+chi22+4.) +1.*track20->Pt()/(track10->Pt()+track20->Pt()) ); Double_t sumw = w1+w2; w1/=sumw; w2/=sumw; if (w1<w2*0.5) { w1 = (d2+0.5)/(d1+d2+1.); w2 = (d1+0.5)/(d1+d2+1.); } // Float_t maxmax = w1*track10->fChi2MIP[0]+w2*track20->fChi2MIP[0]+w1*conflict1+w2*conflict2+1.; //Float_t maxconflicts0 = w1*conflict1+w2*conflict2; // // get pair of "best" hypothesys // Float_t * ny1 = GetNy(trackID1), * nz1 = GetNz(trackID1); Float_t * ny2 = GetNy(trackID2), * nz2 = GetNz(trackID2); for (Int_t itrack1=0;itrack1<entries1;itrack1++){ AliITStrackMI * track1=(AliITStrackMI*) arr1->UncheckedAt(itrack1); //if (track1->fFakeRatio>0) continue; RegisterClusterTracks(track1,trackID1); for (Int_t itrack2=0;itrack2<entries2;itrack2++){ AliITStrackMI * track2=(AliITStrackMI*) arr2->UncheckedAt(itrack2); // Float_t current = w1*track1->fChi2MIP[0]+w2*track2->fChi2MIP[0]; //if (track2->fFakeRatio>0) continue; Float_t nskipped=0; RegisterClusterTracks(track2,trackID2); Float_t cconflict1 = GetNumberOfSharedClusters(track1,trackID1,list1,clist1); Float_t cconflict2 = GetNumberOfSharedClusters(track2,trackID2,list2,clist2); UnRegisterClusterTracks(track2,trackID2); // if (track1->GetConstrain()) nskipped+=w1*track1->GetNSkipped(); if (track2->GetConstrain()) nskipped+=w2*track2->GetNSkipped(); if (nskipped>0.5) continue; // //if ( w1*conflict1+w2*conflict2>maxconflicts0) continue; if (conflict1+1<cconflict1) continue; if (conflict2+1<cconflict2) continue; Float_t conflict=0; Float_t sumchi2=0; Float_t sum=0; for (Int_t i=0;i<6;i++){ // Float_t c1 =0.; // conflict coeficients Float_t c2 =0.; if (clist1[i]&&clist2[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist1[i]->GetNy()+clist1[i]->GetNz()-TMath::Max(ny1[i],ny2[i])-TMath::Max(nz1[i],nz2[i])); } else{ deltan = (clist1[i]->GetNz()-TMath::Max(nz1[i],nz2[i])); } c1 = 2./TMath::Max(3.+deltan,2.); c2 = 2./TMath::Max(3.+deltan,2.); } else{ if (clist1[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist1[i]->GetNy()+clist1[i]->GetNz()-ny1[i]-nz1[i]); } else{ deltan = (clist1[i]->GetNz()-nz1[i]); } c1 = 2./TMath::Max(3.+deltan,2.); c2 = 0; } if (clist2[i]){ Float_t deltan = 0; if (i<2 || i>3){ deltan = (clist2[i]->GetNy()+clist2[i]->GetNz()-ny2[i]-nz2[i]); } else{ deltan = (clist2[i]->GetNz()-nz2[i]); } c2 = 2./TMath::Max(3.+deltan,2.); c1 = 0; } } // chi21=0;chi22=0; if (TMath::Abs(track1->GetDy(i))>0.) { chi21 = (track1->GetDy(i)/track1->GetSigmaY(i))*(track1->GetDy(i)/track1->GetSigmaY(i))+ (track1->GetDz(i)/track1->GetSigmaZ(i))*(track1->GetDz(i)/track1->GetSigmaZ(i)); //chi21 = (track1->fDy[i]*track1->fDy[i])/(nerry[i]*nerry[i])+ // (track1->GetDz(i)*track1->GetDz(i))/(nerrz[i]*nerrz[i]); }else{ if (TMath::Abs(track1->GetSigmaY(i)>0.)) c1=1; } // if (TMath::Abs(track2->GetDy(i))>0.) { chi22 = (track2->GetDy(i)/track2->GetSigmaY(i))*(track2->GetDy(i)/track2->GetSigmaY(i))+ (track2->GetDz(i)/track2->GetSigmaZ(i))*(track2->GetDz(i)/track2->GetSigmaZ(i)); //chi22 = (track2->fDy[i]*track2->fDy[i])/(nerry[i]*nerry[i])+ // (track2->fDz[i]*track2->fDz[i])/(nerrz[i]*nerrz[i]); } else{ if (TMath::Abs(track2->GetSigmaY(i)>0.)) c2=1; } sumchi2+=w1*(1.+c1)*(1+c1)*(chi21+c1)+w2*(1.+c2)*(1+c2)*(chi22+c2); if (chi21>0) sum+=w1; if (chi22>0) sum+=w2; conflict+=(c1+c2); } Double_t norm = sum-w1*track1->GetNSkipped()-w2*track2->GetNSkipped(); if (norm<0) norm =1/(w1*track1->GetNSkipped()+w2*track2->GetNSkipped()); Double_t normchi2 = 2*conflict+sumchi2/sum; if ( normchi2 <maxchi2 ){ index1 = itrack1; index2 = itrack2; maxconflicts = conflict; maxchi2 = normchi2; } } UnRegisterClusterTracks(track1,trackID1); } // // if (maxconflicts<4 && maxchi2<th0){ if (maxchi2<th0*2.){ Float_t orig = track10->GetFakeRatio()*track10->GetNumberOfClusters(); AliITStrackMI* track1=(AliITStrackMI*) arr1->UncheckedAt(index1); track1->SetChi2MIP(5,maxconflicts); track1->SetChi2MIP(6,maxchi2); track1->SetChi2MIP(7,0.01+orig-(track1->GetFakeRatio()*track1->GetNumberOfClusters())); // track1->UpdateESDtrack(AliESDtrack::kITSin); track1->SetChi2MIP(8,index1); fBestTrackIndex[trackID1] =index1; UpdateESDtrack(track1, AliESDtrack::kITSin); } else if (track10->GetChi2MIP(0)<th1){ track10->SetChi2MIP(5,maxconflicts); track10->SetChi2MIP(6,maxchi2); // track10->UpdateESDtrack(AliESDtrack::kITSin); UpdateESDtrack(track10,AliESDtrack::kITSin); } for (Int_t itrack=0;itrack<entries1;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr1->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID1); } // for (Int_t itrack=0;itrack<entries2;itrack++){ AliITStrackMI * track=(AliITStrackMI*) arr2->UncheckedAt(itrack); UnRegisterClusterTracks(track,trackID2); } if (track10->GetConstrain()&&track10->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&track10->GetChi2MIP(1)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1) &&track10->GetChi2MIP(2)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)&&track10->GetChi2MIP(3)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)){ // if (track10->fChi2MIP[0]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&track10->fChi2MIP[1]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1) // &&track10->fChi2MIP[2]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)&&track10->fChi2MIP[3]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)){ RegisterClusterTracks(track10,trackID1); } if (track20->GetConstrain()&&track20->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&track20->GetChi2MIP(1)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1) &&track20->GetChi2MIP(2)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)&&track20->GetChi2MIP(3)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)){ //if (track20->fChi2MIP[0]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&track20->fChi2MIP[1]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1) // &&track20->fChi2MIP[2]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)&&track20->fChi2MIP[3]<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)){ RegisterClusterTracks(track20,trackID2); } return track10; } //------------------------------------------------------------------------ void AliITStrackerMI::UseClusters(const AliKalmanTrack *t, Int_t from) const { //-------------------------------------------------------------------- // This function marks clusters assigned to the track //-------------------------------------------------------------------- AliTracker::UseClusters(t,from); AliITSRecPoint *c=(AliITSRecPoint *)GetCluster(t->GetClusterIndex(0)); //if (c->GetQ()>2) c->Use(); if (c->GetSigmaZ2()>0.1) c->Use(); c=(AliITSRecPoint *)GetCluster(t->GetClusterIndex(1)); //if (c->GetQ()>2) c->Use(); if (c->GetSigmaZ2()>0.1) c->Use(); } //------------------------------------------------------------------------ void AliITStrackerMI::AddTrackHypothesys(AliITStrackMI * track, Int_t esdindex) { //------------------------------------------------------------------ // add track to the list of hypothesys //------------------------------------------------------------------ if (esdindex>=fTrackHypothesys.GetEntriesFast()) fTrackHypothesys.Expand(TMath::Max(fTrackHypothesys.GetSize(),esdindex*2+10)); // TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); if (!array) { array = new TObjArray(10); fTrackHypothesys.AddAt(array,esdindex); } array->AddLast(track); } //------------------------------------------------------------------------ void AliITStrackerMI::SortTrackHypothesys(Int_t esdindex, Int_t maxcut, Int_t mode) { //------------------------------------------------------------------- // compress array of track hypothesys // keep only maxsize best hypothesys //------------------------------------------------------------------- if (esdindex>fTrackHypothesys.GetEntriesFast()) return; if (! (fTrackHypothesys.At(esdindex)) ) return; TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); Int_t entries = array->GetEntriesFast(); // //- find preliminary besttrack as a reference Float_t minchi2=10000; Int_t maxn=0; AliITStrackMI * besttrack=0; for (Int_t itrack=0;itrack<array->GetEntriesFast();itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (!track) continue; Float_t chi2 = NormalizedChi2(track,0); // Int_t tpcLabel=track->GetESDtrack()->GetTPCLabel(); track->SetLabel(tpcLabel); CookdEdx(track); track->SetFakeRatio(1.); CookLabel(track,0.); //For comparison only // //if (chi2<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&track->fFakeRatio==0){ if (chi2<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)){ if (track->GetNumberOfClusters()<maxn) continue; maxn = track->GetNumberOfClusters(); if (chi2<minchi2){ minchi2=chi2; besttrack=track; } } else{ if (track->GetConstrain() || track->GetNumberOfClusters()>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } if (!besttrack) return; // // //take errors of best track as a reference Float_t *erry = GetErrY(esdindex), *errz = GetErrZ(esdindex); Float_t *ny = GetNy(esdindex), *nz = GetNz(esdindex); for (Int_t j=0;j<6;j++) { if (besttrack->GetClIndex(j)>0){ erry[j] = besttrack->GetSigmaY(j); erry[j+6] = besttrack->GetSigmaY(j+6); errz[j] = besttrack->GetSigmaZ(j); errz[j+6] = besttrack->GetSigmaZ(j+6); ny[j] = besttrack->GetNy(j); nz[j] = besttrack->GetNz(j); } } // // calculate normalized chi2 // Float_t * chi2 = new Float_t[entries]; Int_t * index = new Int_t[entries]; for (Int_t i=0;i<entries;i++) chi2[i] =10000; for (Int_t itrack=0;itrack<entries;itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (track){ track->SetChi2MIP(0,GetNormalizedChi2(track, mode)); if (track->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)) chi2[itrack] = track->GetChi2MIP(0); else{ if (track->GetConstrain() || track->GetNumberOfClusters()>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } } // TMath::Sort(entries,chi2,index,kFALSE); besttrack = (AliITStrackMI*)array->At(index[0]); if (besttrack&&besttrack->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)){ for (Int_t j=0;j<6;j++){ if (besttrack->GetClIndex(j)>0){ erry[j] = besttrack->GetSigmaY(j); erry[j+6] = besttrack->GetSigmaY(j+6); errz[j] = besttrack->GetSigmaZ(j); erry[j+6] = besttrack->GetSigmaY(j+6); ny[j] = besttrack->GetNy(j); nz[j] = besttrack->GetNz(j); } } } // // calculate one more time with updated normalized errors for (Int_t i=0;i<entries;i++) chi2[i] =10000; for (Int_t itrack=0;itrack<entries;itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (track){ track->SetChi2MIP(0,GetNormalizedChi2(track,mode)); if (track->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)) chi2[itrack] = track->GetChi2MIP(0)-0*(track->GetNumberOfClusters()+track->GetNDeadZone()); else { if (track->GetConstrain() || track->GetNumberOfClusters()>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(itrack); } } } } entries = array->GetEntriesFast(); // // if (entries>0){ TObjArray * newarray = new TObjArray(); TMath::Sort(entries,chi2,index,kFALSE); besttrack = (AliITStrackMI*)array->At(index[0]); if (besttrack){ // for (Int_t j=0;j<6;j++){ if (besttrack->GetNz(j)>0&&besttrack->GetNy(j)>0){ erry[j] = besttrack->GetSigmaY(j); erry[j+6] = besttrack->GetSigmaY(j+6); errz[j] = besttrack->GetSigmaZ(j); errz[j+6] = besttrack->GetSigmaZ(j+6); ny[j] = besttrack->GetNy(j); nz[j] = besttrack->GetNz(j); } } besttrack->SetChi2MIP(0,GetNormalizedChi2(besttrack,mode)); minchi2 = TMath::Min(besttrack->GetChi2MIP(0)+5.+besttrack->GetNUsed(), double(AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0))); Float_t minn = besttrack->GetNumberOfClusters()-3; Int_t accepted=0; for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(index[i]); if (!track) continue; if (accepted>maxcut) break; track->SetChi2MIP(0,GetNormalizedChi2(track,mode)); if (track->GetConstrain() || track->GetNumberOfClusters()>5){ //keep best short tracks - without vertex constrain if (track->GetNumberOfClusters()<6 && (track->GetChi2MIP(0)+track->GetNUsed()>minchi2)){ delete array->RemoveAt(index[i]); continue; } } Bool_t shortbest = !track->GetConstrain() && track->GetNumberOfClusters()<6; if ((track->GetChi2MIP(0)+track->GetNUsed()<minchi2 && track->GetNumberOfClusters()>=minn) ||shortbest){ if (!shortbest) accepted++; // newarray->AddLast(array->RemoveAt(index[i])); for (Int_t j=0;j<6;j++){ if (nz[j]==0){ erry[j] = track->GetSigmaY(j); erry[j+6] = track->GetSigmaY(j+6); errz[j] = track->GetSigmaZ(j); errz[j] = track->GetSigmaZ(j+6); ny[j] = track->GetNy(j); nz[j] = track->GetNz(j); } } } else{ delete array->RemoveAt(index[i]); } } array->Delete(); delete fTrackHypothesys.RemoveAt(esdindex); fTrackHypothesys.AddAt(newarray,esdindex); } else{ array->Delete(); delete fTrackHypothesys.RemoveAt(esdindex); } } delete [] chi2; delete [] index; } //------------------------------------------------------------------------ AliITStrackMI * AliITStrackerMI::GetBestHypothesys(Int_t esdindex, AliITStrackMI * original, Int_t checkmax) { //------------------------------------------------------------- // try to find best hypothesy // currently - minimal chi2 of track+backpropagated track+matching to the tpc track //------------------------------------------------------------- if (fTrackHypothesys.GetEntriesFast()<=esdindex) return 0; TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex); if (!array) return 0; Int_t entries = array->GetEntriesFast(); if (!entries) return 0; Float_t minchi2 = 100000; AliITStrackMI * besttrack=0; // AliITStrackMI * backtrack = new AliITStrackMI(*original); AliITStrackMI * forwardtrack = new AliITStrackMI(*original); Double_t xyzVtx[]={GetX(),GetY(),GetZ()}; Double_t ersVtx[]={GetSigmaX()/3.,GetSigmaY()/3.,GetSigmaZ()/3.}; // for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; Float_t sigmarfi,sigmaz; GetDCASigma(track,sigmarfi,sigmaz); track->SetDnorm(0,sigmarfi); track->SetDnorm(1,sigmaz); // track->SetChi2MIP(1,1000000); track->SetChi2MIP(2,1000000); track->SetChi2MIP(3,1000000); // // backtrack backtrack = new(backtrack) AliITStrackMI(*track); if (track->GetConstrain()) { if (!CorrectForPipeMaterial(backtrack,"inward")) continue; if (!backtrack->Improve(0,xyzVtx,ersVtx)) continue; backtrack->ResetCovariance(10.); }else{ backtrack->ResetCovariance(10.); } backtrack->ResetClusters(); Double_t x = original->GetX(); if (!RefitAt(x,backtrack,track)) continue; // track->SetChi2MIP(1,NormalizedChi2(backtrack,0)); //for (Int_t i=2;i<6;i++){track->fDy[i]+=backtrack->fDy[i]; track->fDz[i]+=backtrack->fDz[i];} if (track->GetChi2MIP(1)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1)*6.) continue; track->SetChi22(GetMatchingChi2(backtrack,original)); if ((track->GetConstrain()) && track->GetChi22()>90.) continue; if ((!track->GetConstrain()) && track->GetChi22()>30.) continue; if ( track->GetChi22()/track->GetNumberOfClusters()>11.) continue; if (!(track->GetConstrain())&&track->GetChi2MIP(1)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1)) continue; // //forward track - without constraint forwardtrack = new(forwardtrack) AliITStrackMI(*original); forwardtrack->ResetClusters(); x = track->GetX(); RefitAt(x,forwardtrack,track); track->SetChi2MIP(2,NormalizedChi2(forwardtrack,0)); if (track->GetChi2MIP(2)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)*6.0) continue; if (!(track->GetConstrain())&&track->GetChi2MIP(2)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)) continue; //track->fD[0] = forwardtrack->GetD(GetX(),GetY()); //track->fD[1] = forwardtrack->GetZat(GetX())-GetZ(); forwardtrack->GetDZ(GetX(),GetY(),GetZ(),track->GetDP()); //I.B. forwardtrack->SetD(0,track->GetD(0)); forwardtrack->SetD(1,track->GetD(1)); { Int_t list[6]; AliITSRecPoint* clist[6]; track->SetChi2MIP(4,GetNumberOfSharedClusters(track,esdindex,list,clist)); if ( (!track->GetConstrain()) && track->GetChi2MIP(4)>1.0) continue; } track->SetChi2MIP(3,GetInterpolatedChi2(forwardtrack,backtrack)); if ( (track->GetChi2MIP(3)>6.*AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3))) continue; if ( (!track->GetConstrain()) && (track->GetChi2MIP(3)>2*AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3))) { track->SetChi2MIP(3,1000); continue; } Double_t chi2 = track->GetChi2MIP(0)+track->GetNUsed(); // for (Int_t ichi=0;ichi<5;ichi++){ forwardtrack->SetChi2MIP(ichi, track->GetChi2MIP(ichi)); } if (chi2 < minchi2){ //besttrack = new AliITStrackMI(*forwardtrack); besttrack = track; besttrack->SetLabel(track->GetLabel()); besttrack->SetFakeRatio(track->GetFakeRatio()); minchi2 = chi2; //original->fD[0] = forwardtrack->GetD(GetX(),GetY()); //original->fD[1] = forwardtrack->GetZat(GetX())-GetZ(); forwardtrack->GetDZ(GetX(),GetY(),GetZ(),original->GetDP()); //I.B. } } delete backtrack; delete forwardtrack; Int_t accepted=0; for (Int_t i=0;i<entries;i++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; if (accepted>checkmax || track->GetChi2MIP(3)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)*6. || (track->GetNumberOfClusters()<besttrack->GetNumberOfClusters()-1.)|| track->GetChi2MIP(0)>besttrack->GetChi2MIP(0)+2.*besttrack->GetNUsed()+3.){ if (track->GetConstrain() || track->GetNumberOfClusters()>5){ //keep best short tracks - without vertex constrain delete array->RemoveAt(i); continue; } } else{ accepted++; } } // array->Compress(); SortTrackHypothesys(esdindex,checkmax,1); array = (TObjArray*) fTrackHypothesys.At(esdindex); if (!array) return 0; // PH What can be the reason? Check SortTrackHypothesys besttrack = (AliITStrackMI*)array->At(0); if (!besttrack) return 0; besttrack->SetChi2MIP(8,0); fBestTrackIndex[esdindex]=0; entries = array->GetEntriesFast(); AliITStrackMI *longtrack =0; minchi2 =1000; Float_t minn=besttrack->GetNumberOfClusters()+besttrack->GetNDeadZone(); for (Int_t itrack=entries-1;itrack>0;itrack--) { AliITStrackMI * track = (AliITStrackMI*)array->At(itrack); if (!track->GetConstrain()) continue; if (track->GetNumberOfClusters()+track->GetNDeadZone()<minn) continue; if (track->GetChi2MIP(0)-besttrack->GetChi2MIP(0)>0.0) continue; if (track->GetChi2MIP(0)>4.) continue; minn = track->GetNumberOfClusters()+track->GetNDeadZone(); longtrack =track; } //if (longtrack) besttrack=longtrack; Int_t list[6]; AliITSRecPoint * clist[6]; Float_t shared = GetNumberOfSharedClusters(besttrack,esdindex,list,clist); if (besttrack->GetConstrain()&&besttrack->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)&&besttrack->GetChi2MIP(1)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(1) &&besttrack->GetChi2MIP(2)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(2)&&besttrack->GetChi2MIP(3)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)){ RegisterClusterTracks(besttrack,esdindex); } // // if (shared>0.0){ Int_t nshared; Int_t overlist[6]; Int_t sharedtrack = GetOverlapTrack(besttrack, esdindex, nshared, list, overlist); if (sharedtrack>=0){ // besttrack = GetBest2Tracks(esdindex,sharedtrack,10,5.5); if (besttrack){ shared = GetNumberOfSharedClusters(besttrack,esdindex,list,clist); } else return 0; } } if (shared>2.5) return 0; if (shared>1.0) return besttrack; // // Don't sign clusters if not gold track // if (!besttrack->IsGoldPrimary()) return besttrack; if (besttrack->GetESDtrack()->GetKinkIndex(0)!=0) return besttrack; //track belong to kink // if (fConstraint[fPass]){ // // sign clusters // Float_t *ny = GetNy(esdindex), *nz = GetNz(esdindex); for (Int_t i=0;i<6;i++){ Int_t index = besttrack->GetClIndex(i); if (index<=0) continue; Int_t ilayer = (index & 0xf0000000) >> 28; if (besttrack->GetSigmaY(ilayer)<0.00000000001) continue; AliITSRecPoint *c = (AliITSRecPoint*)GetCluster(index); if (!c) continue; if (ilayer>3&&c->GetNy()+c->GetNz()>6) continue; if ( (c->GetNy()+c->GetNz() )> ny[i]+nz[i]+0.7) continue; //shared track if ( c->GetNz()> nz[i]+0.7) continue; //shared track if ( ilayer>2&& AliITSReconstructor::GetRecoParam()->GetUseAmplitudeInfo(ilayer)) if (besttrack->GetNormQ(ilayer)/besttrack->GetExpQ()>1.5) continue; //if ( c->GetNy()> ny[i]+0.7) continue; //shared track Bool_t cansign = kTRUE; for (Int_t itrack=0;itrack<entries; itrack++){ AliITStrackMI * track = (AliITStrackMI*)array->At(i); if (!track) continue; if (track->GetChi2MIP(0)>besttrack->GetChi2MIP(0)+2.*shared+1.) break; if ( (track->GetClIndex(ilayer)>0) && (track->GetClIndex(ilayer)!=besttrack->GetClIndex(ilayer))){ cansign = kFALSE; break; } } if (cansign){ if (TMath::Abs(besttrack->GetDy(ilayer)/besttrack->GetSigmaY(ilayer))>3.) continue; if (TMath::Abs(besttrack->GetDz(ilayer)/besttrack->GetSigmaZ(ilayer))>3.) continue; if (!c->IsUsed()) c->Use(); } } } return besttrack; } //------------------------------------------------------------------------ void AliITStrackerMI::GetBestHypothesysMIP(TObjArray &itsTracks) { // // get "best" hypothesys // Int_t nentries = itsTracks.GetEntriesFast(); for (Int_t i=0;i<nentries;i++){ AliITStrackMI* track = (AliITStrackMI*)itsTracks.At(i); if (!track) continue; TObjArray * array = (TObjArray*) fTrackHypothesys.At(i); if (!array) continue; if (array->GetEntriesFast()<=0) continue; // AliITStrackMI* longtrack=0; Float_t minn=0; Float_t maxchi2=1000; for (Int_t j=0;j<array->GetEntriesFast();j++){ AliITStrackMI* trackHyp = (AliITStrackMI*)array->At(j); if (!trackHyp) continue; if (trackHyp->GetGoldV0()) { longtrack = trackHyp; //gold V0 track taken break; } if (trackHyp->GetNumberOfClusters()+trackHyp->GetNDeadZone()<minn) continue; Float_t chi2 = trackHyp->GetChi2MIP(0); if (fAfterV0){ if (!trackHyp->GetGoldV0()&&trackHyp->GetConstrain()==kFALSE) chi2+=5; } if (trackHyp->GetNumberOfClusters()+trackHyp->GetNDeadZone()>minn) maxchi2 = trackHyp->GetChi2MIP(0); // if (chi2 > maxchi2) continue; minn= trackHyp->GetNumberOfClusters()+trackHyp->GetNDeadZone(); maxchi2 = chi2; longtrack=trackHyp; } // // // AliITStrackMI * besttrack = (AliITStrackMI*)array->At(0); if (!longtrack) {longtrack = besttrack;} else besttrack= longtrack; // if (besttrack) { Int_t list[6]; AliITSRecPoint * clist[6]; Float_t shared = GetNumberOfSharedClusters(longtrack,i,list,clist); // track->SetNUsed(shared); track->SetNSkipped(besttrack->GetNSkipped()); track->SetChi2MIP(0,besttrack->GetChi2MIP(0)); if (shared>0) { if(!AliITSReconstructor::GetRecoParam()->GetAllowSharedClusters()) continue; Int_t nshared; Int_t overlist[6]; // Int_t sharedtrack = GetOverlapTrack(longtrack, i, nshared, list, overlist); //if (sharedtrack==-1) sharedtrack=0; if (sharedtrack>=0) { besttrack = GetBest2Tracks(i,sharedtrack,10,5.5); } } if (besttrack&&fAfterV0) { UpdateESDtrack(besttrack,AliESDtrack::kITSin); } if (besttrack&&fConstraint[fPass]) UpdateESDtrack(besttrack,AliESDtrack::kITSin); if (besttrack->GetChi2MIP(0)+besttrack->GetNUsed()>1.5 && fConstraint[fPass]) { if ( TMath::Abs(besttrack->GetD(0))>0.1 || TMath::Abs(besttrack->GetD(1))>0.1 ) track->SetReconstructed(kFALSE); } } } } //------------------------------------------------------------------------ void AliITStrackerMI::CookLabel(AliITStrackMI *track,Float_t wrong) const { //-------------------------------------------------------------------- //This function "cooks" a track label. If label<0, this track is fake. //-------------------------------------------------------------------- Int_t tpcLabel=-1; if ( track->GetESDtrack()) tpcLabel = TMath::Abs(track->GetESDtrack()->GetTPCLabel()); track->SetChi2MIP(9,0); Int_t nwrong=0; for (Int_t i=0;i<track->GetNumberOfClusters();i++){ Int_t cindex = track->GetClusterIndex(i); Int_t l=(cindex & 0xf0000000) >> 28; AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(cindex); Int_t isWrong=1; for (Int_t ind=0;ind<3;ind++){ if (tpcLabel>0) if (cl->GetLabel(ind)==tpcLabel) isWrong=0; AliDebug(2,Form("icl %d ilab %d lab %d",i,ind,cl->GetLabel(ind))); } track->SetChi2MIP(9,track->GetChi2MIP(9)+isWrong*(2<<l)); nwrong+=isWrong; } Int_t nclusters = track->GetNumberOfClusters(); if (nclusters > 0) //PH Some tracks don't have any cluster track->SetFakeRatio(double(nwrong)/double(nclusters)); if (tpcLabel>0){ if (track->GetFakeRatio()>wrong) track->SetLabel(-tpcLabel); else track->SetLabel(tpcLabel); } AliDebug(2,Form(" nls %d wrong %d label %d tpcLabel %d\n",nclusters,nwrong,track->GetLabel(),tpcLabel)); } //------------------------------------------------------------------------ void AliITStrackerMI::CookdEdx(AliITStrackMI* track) { // // // Int_t list[6]; //AliITSRecPoint * clist[6]; // Int_t shared = GetNumberOfSharedClusters(track,index,list,clist); Float_t dedx[4]; Int_t accepted=0; track->SetChi2MIP(9,0); for (Int_t i=0;i<track->GetNumberOfClusters();i++){ Int_t cindex = track->GetClusterIndex(i); Int_t l=(cindex & 0xf0000000) >> 28; AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(cindex); Int_t lab = TMath::Abs(track->GetESDtrack()->GetTPCLabel()); Int_t isWrong=1; for (Int_t ind=0;ind<3;ind++){ if (cl->GetLabel(ind)==lab) isWrong=0; } track->SetChi2MIP(9,track->GetChi2MIP(9)+isWrong*(2<<l)); if (l<2) continue; //if (l>3 && (cl->GetNy()>4) || (cl->GetNz()>4)) continue; //shared track //if (l>3&& !(cl->GetType()==1||cl->GetType()==10)) continue; //if (l<4&& !(cl->GetType()==1)) continue; dedx[accepted]= track->GetSampledEdx(i); //dedx[accepted]= track->fNormQ[l]; accepted++; } if (accepted<1) { track->SetdEdx(0); return; } Int_t indexes[4]; TMath::Sort(accepted,dedx,indexes,kFALSE); Double_t low=0.; Double_t up=0.51; Double_t nl=low*accepted, nu =up*accepted; Float_t sumamp = 0; Float_t sumweight =0; for (Int_t i=0; i<accepted; i++) { Float_t weight =1; if (i<nl+0.1) weight = TMath::Max(1.-(nl-i),0.); if (i>nu-1) weight = TMath::Max(nu-i,0.); sumamp+= dedx[indexes[i]]*weight; sumweight+=weight; } track->SetdEdx(sumamp/sumweight); } //------------------------------------------------------------------------ void AliITStrackerMI::MakeCoefficients(Int_t ntracks){ // // if (fCoefficients) delete []fCoefficients; fCoefficients = new Float_t[ntracks*48]; for (Int_t i=0;i<ntracks*48;i++) fCoefficients[i]=-1.; } //------------------------------------------------------------------------ Double_t AliITStrackerMI::GetPredictedChi2MI(AliITStrackMI* track, const AliITSRecPoint *cluster,Int_t layer) { // // // Float_t erry,errz; Float_t theta = track->GetTgl(); Float_t phi = track->GetSnp(); phi = TMath::Sqrt(phi*phi/(1.-phi*phi)); AliITSClusterParam::GetError(layer,cluster,theta,phi,track->GetExpQ(),erry,errz); AliDebug(2,Form(" chi2: tr-cl %f %f tr X %f cl X %f",track->GetY()-cluster->GetY(),track->GetZ()-cluster->GetZ(),track->GetX(),cluster->GetX())); // Take into account the mis-alignment (bring track to cluster plane) Double_t xTrOrig=track->GetX(); if (!track->Propagate(xTrOrig+cluster->GetX())) return 1000.; AliDebug(2,Form(" chi2: tr-cl %f %f tr X %f cl X %f",track->GetY()-cluster->GetY(),track->GetZ()-cluster->GetZ(),track->GetX(),cluster->GetX())); Double_t chi2 = track->GetPredictedChi2MI(cluster->GetY(),cluster->GetZ(),erry,errz); // Bring the track back to detector plane in ideal geometry // [mis-alignment will be accounted for in UpdateMI()] if (!track->Propagate(xTrOrig)) return 1000.; Float_t ny,nz; AliITSClusterParam::GetNTeor(layer,cluster,theta,phi,ny,nz); Double_t delta = cluster->GetNy()+cluster->GetNz()-nz-ny; if (delta>1){ chi2+=0.5*TMath::Min(delta/2,2.); chi2+=2.*cluster->GetDeltaProbability(); } // track->SetNy(layer,ny); track->SetNz(layer,nz); track->SetSigmaY(layer,erry); track->SetSigmaZ(layer, errz); //track->fNormQ[layer] = cluster->GetQ()/TMath::Sqrt(1+theta*theta+phi*phi); track->SetNormQ(layer,cluster->GetQ()/TMath::Sqrt((1.+ track->GetTgl()*track->GetTgl())/(1.- track->GetSnp()*track->GetSnp()))); return chi2; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::UpdateMI(AliITStrackMI* track, const AliITSRecPoint* cl,Double_t chi2,Int_t index) const { // // // Int_t layer = (index & 0xf0000000) >> 28; track->SetClIndex(layer, index); if (layer>1&&AliITSReconstructor::GetRecoParam()->GetUseAmplitudeInfo(layer)) { if (track->GetNormQ(layer)/track->GetExpQ()<0.5 ) { chi2+= (0.5-track->GetNormQ(layer)/track->GetExpQ())*10.; track->SetdEdxMismatch(track->GetdEdxMismatch()+(0.5-track->GetNormQ(layer)/track->GetExpQ())*10.); } } if (cl->GetQ()<=0) return 0; // ingore the "virtual" clusters // Take into account the mis-alignment (bring track to cluster plane) Double_t xTrOrig=track->GetX(); Float_t clxyz[3]; cl->GetGlobalXYZ(clxyz);Double_t trxyz[3]; track->GetXYZ(trxyz); AliDebug(2,Form("gtr %f %f %f",trxyz[0],trxyz[1],trxyz[2])); AliDebug(2,Form("gcl %f %f %f",clxyz[0],clxyz[1],clxyz[2])); AliDebug(2,Form(" xtr %f xcl %f",track->GetX(),cl->GetX())); if (!track->Propagate(xTrOrig+cl->GetX())) return 0; AliCluster c(*cl); c.SetSigmaY2(track->GetSigmaY(layer)*track->GetSigmaY(layer)); c.SetSigmaZ2(track->GetSigmaZ(layer)*track->GetSigmaZ(layer)); Int_t updated = track->UpdateMI(&c,chi2,index); // Bring the track back to detector plane in ideal geometry if (!track->Propagate(xTrOrig)) return 0; if(!updated) AliDebug(2,"update failed"); return updated; } //------------------------------------------------------------------------ void AliITStrackerMI::GetDCASigma(AliITStrackMI* track, Float_t & sigmarfi, Float_t &sigmaz) { // //DCA sigmas parameterization //to be paramterized using external parameters in future // // sigmarfi = 0.0040+1.4 *TMath::Abs(track->GetC())+332.*track->GetC()*track->GetC(); sigmaz = 0.0110+4.37*TMath::Abs(track->GetC()); } //------------------------------------------------------------------------ void AliITStrackerMI::SignDeltas( TObjArray *ClusterArray, Float_t vz) { // // Int_t entries = ClusterArray->GetEntriesFast(); if (entries<4) return; AliITSRecPoint* cluster = (AliITSRecPoint*)ClusterArray->At(0); Int_t layer = cluster->GetLayer(); if (layer>1) return; Int_t index[10000]; Int_t ncandidates=0; Float_t r = (layer>0)? 7:4; // for (Int_t i=0;i<entries;i++){ AliITSRecPoint* cl0 = (AliITSRecPoint*)ClusterArray->At(i); Float_t nz = 1+TMath::Abs((cl0->GetZ()-vz)/r); if (cl0->GetNy()+cl0->GetNz()<=5+2*layer+nz) continue; index[ncandidates] = i; //candidate to belong to delta electron track ncandidates++; if (cl0->GetNy()+cl0->GetNz()>9+2*layer+nz) { cl0->SetDeltaProbability(1); } } // // // for (Int_t i=0;i<ncandidates;i++){ AliITSRecPoint* cl0 = (AliITSRecPoint*)ClusterArray->At(index[i]); if (cl0->GetDeltaProbability()>0.8) continue; // Int_t ncl = 0; Float_t y[100],z[100],sumy,sumz,sumy2, sumyz, sumw; sumy=sumz=sumy2=sumyz=sumw=0.0; for (Int_t j=0;j<ncandidates;j++){ if (i==j) continue; AliITSRecPoint* cl1 = (AliITSRecPoint*)ClusterArray->At(index[j]); // Float_t dz = cl0->GetZ()-cl1->GetZ(); Float_t dy = cl0->GetY()-cl1->GetY(); if (TMath::Sqrt(dz*dz+dy*dy)<0.2){ Float_t weight = cl1->GetNy()+cl1->GetNz()-2; y[ncl] = cl1->GetY(); z[ncl] = cl1->GetZ(); sumy+= y[ncl]*weight; sumz+= z[ncl]*weight; sumy2+=y[ncl]*y[ncl]*weight; sumyz+=y[ncl]*z[ncl]*weight; sumw+=weight; ncl++; } } if (ncl<4) continue; Float_t det = sumw*sumy2 - sumy*sumy; Float_t delta=1000; if (TMath::Abs(det)>0.01){ Float_t z0 = (sumy2*sumz - sumy*sumyz)/det; Float_t k = (sumyz*sumw - sumy*sumz)/det; delta = TMath::Abs(cl0->GetZ()-(z0+k*cl0->GetY())); } else{ Float_t z0 = sumyz/sumy; delta = TMath::Abs(cl0->GetZ()-z0); } if ( delta<0.05) { cl0->SetDeltaProbability(1-20.*delta); } } } //------------------------------------------------------------------------ void AliITStrackerMI::UpdateESDtrack(AliITStrackMI* track, ULong_t flags) const { // // track->UpdateESDtrack(flags); AliITStrackMI * oldtrack = (AliITStrackMI*)(track->GetESDtrack()->GetITStrack()); if (oldtrack) delete oldtrack; track->GetESDtrack()->SetITStrack(new AliITStrackMI(*track)); if (TMath::Abs(track->GetDnorm(1))<0.000000001){ printf("Problem\n"); } } //------------------------------------------------------------------------ Int_t AliITStrackerMI::GetNearestLayer(const Double_t *xr) const{ // // Get nearest upper layer close to the point xr. // rough approximation // const Float_t kRadiuses[6]={4,6.5,15.03,24.,38.5,43.7}; Float_t radius = TMath::Sqrt(xr[0]*xr[0]+xr[1]*xr[1]); Int_t res =6; for (Int_t i=0;i<6;i++){ if (radius<kRadiuses[i]){ res =i; break; } } return res; } //------------------------------------------------------------------------ void AliITStrackerMI::UpdateTPCV0(AliESDEvent *event){ // //try to update, or reject TPC V0s // Int_t nv0s = event->GetNumberOfV0s(); Int_t nitstracks = fTrackHypothesys.GetEntriesFast(); for (Int_t i=0;i<nv0s;i++){ AliESDv0 * vertex = event->GetV0(i); Int_t ip = vertex->GetIndex(0); Int_t im = vertex->GetIndex(1); // TObjArray * arrayp = (ip<nitstracks) ? (TObjArray*)fTrackHypothesys.At(ip):0; TObjArray * arraym = (im<nitstracks) ? (TObjArray*)fTrackHypothesys.At(im):0; AliITStrackMI * trackp = (arrayp!=0) ? (AliITStrackMI*)arrayp->At(0):0; AliITStrackMI * trackm = (arraym!=0) ? (AliITStrackMI*)arraym->At(0):0; // // if (trackp){ if (trackp->GetNumberOfClusters()+trackp->GetNDeadZone()>5.5){ if (trackp->GetConstrain()&&trackp->GetChi2MIP(0)<3) vertex->SetStatus(-100); if (!trackp->GetConstrain()&&trackp->GetChi2MIP(0)<2) vertex->SetStatus(-100); } } if (trackm){ if (trackm->GetNumberOfClusters()+trackm->GetNDeadZone()>5.5){ if (trackm->GetConstrain()&&trackm->GetChi2MIP(0)<3) vertex->SetStatus(-100); if (!trackm->GetConstrain()&&trackm->GetChi2MIP(0)<2) vertex->SetStatus(-100); } } if (vertex->GetStatus()==-100) continue; // Double_t xrp[3]; vertex->GetXYZ(xrp[0],xrp[1],xrp[2]); //I.B. Int_t clayer = GetNearestLayer(xrp); //I.B. vertex->SetNBefore(clayer); // vertex->SetChi2Before(9*clayer); // vertex->SetNAfter(6-clayer); // vertex->SetChi2After(0); // // if (clayer >1 ){ // calculate chi2 before vertex Float_t chi2p = 0, chi2m=0; // if (trackp){ for (Int_t ilayer=0;ilayer<clayer;ilayer++){ if (trackp->GetClIndex(ilayer)>0){ chi2p+=trackp->GetDy(ilayer)*trackp->GetDy(ilayer)/(trackp->GetSigmaY(ilayer)*trackp->GetSigmaY(ilayer))+ trackp->GetDz(ilayer)*trackp->GetDz(ilayer)/(trackp->GetSigmaZ(ilayer)*trackp->GetSigmaZ(ilayer)); } else{ chi2p+=9; } } }else{ chi2p = 9*clayer; } // if (trackm){ for (Int_t ilayer=0;ilayer<clayer;ilayer++){ if (trackm->GetClIndex(ilayer)>0){ chi2m+=trackm->GetDy(ilayer)*trackm->GetDy(ilayer)/(trackm->GetSigmaY(ilayer)*trackm->GetSigmaY(ilayer))+ trackm->GetDz(ilayer)*trackm->GetDz(ilayer)/(trackm->GetSigmaZ(ilayer)*trackm->GetSigmaZ(ilayer)); } else{ chi2m+=9; } } }else{ chi2m = 9*clayer; } vertex->SetChi2Before(TMath::Min(chi2p,chi2m)); if (TMath::Min(chi2p,chi2m)/Float_t(clayer)<4) vertex->SetStatus(-10); // track exist before vertex } if (clayer < 5 ){ // calculate chi2 after vertex Float_t chi2p = 0, chi2m=0; // if (trackp&&TMath::Abs(trackp->GetTgl())<1.){ for (Int_t ilayer=clayer;ilayer<6;ilayer++){ if (trackp->GetClIndex(ilayer)>0){ chi2p+=trackp->GetDy(ilayer)*trackp->GetDy(ilayer)/(trackp->GetSigmaY(ilayer)*trackp->GetSigmaY(ilayer))+ trackp->GetDz(ilayer)*trackp->GetDz(ilayer)/(trackp->GetSigmaZ(ilayer)*trackp->GetSigmaZ(ilayer)); } else{ chi2p+=9; } } }else{ chi2p = 0; } // if (trackm&&TMath::Abs(trackm->GetTgl())<1.){ for (Int_t ilayer=clayer;ilayer<6;ilayer++){ if (trackm->GetClIndex(ilayer)>0){ chi2m+=trackm->GetDy(ilayer)*trackm->GetDy(ilayer)/(trackm->GetSigmaY(ilayer)*trackm->GetSigmaY(ilayer))+ trackm->GetDz(ilayer)*trackm->GetDz(ilayer)/(trackm->GetSigmaZ(ilayer)*trackm->GetSigmaZ(ilayer)); } else{ chi2m+=9; } } }else{ chi2m = 0; } vertex->SetChi2After(TMath::Max(chi2p,chi2m)); if (TMath::Max(chi2m,chi2p)/Float_t(6-clayer)>9) vertex->SetStatus(-20); // track not found in ITS } } // } //------------------------------------------------------------------------ void AliITStrackerMI::FindV02(AliESDEvent *event) { // // V0 finder // // Cuts on DCA - R dependent // max distance DCA between 2 tracks cut // maxDist = TMath::Min(kMaxDist,kMaxDist0+pvertex->GetRr()*kMaxDist); // const Float_t kMaxDist0 = 0.1; const Float_t kMaxDist1 = 0.1; const Float_t kMaxDist = 1; const Float_t kMinPointAngle = 0.85; const Float_t kMinPointAngle2 = 0.99; const Float_t kMinR = 0.5; const Float_t kMaxR = 220; //const Float_t kCausality0Cut = 0.19; //const Float_t kLikelihood01Cut = 0.25; //const Float_t kPointAngleCut = 0.9996; const Float_t kCausality0Cut = 0.19; const Float_t kLikelihood01Cut = 0.45; const Float_t kLikelihood1Cut = 0.5; const Float_t kCombinedCut = 0.55; // // TTreeSRedirector &cstream = *fDebugStreamer; Int_t ntracks = event->GetNumberOfTracks(); Int_t nitstracks = fTrackHypothesys.GetEntriesFast(); fOriginal.Expand(ntracks); fTrackHypothesys.Expand(ntracks); fBestHypothesys.Expand(ntracks); // AliHelix * helixes = new AliHelix[ntracks+2]; TObjArray trackarray(ntracks+2); //array with tracks - with vertex constrain TObjArray trackarrayc(ntracks+2); //array of "best tracks" - without vertex constrain TObjArray trackarrayl(ntracks+2); //array of "longest tracks" - without vertex constrain Bool_t * forbidden = new Bool_t [ntracks+2]; Int_t *itsmap = new Int_t [ntracks+2]; Float_t *dist = new Float_t[ntracks+2]; Float_t *normdist0 = new Float_t[ntracks+2]; Float_t *normdist1 = new Float_t[ntracks+2]; Float_t *normdist = new Float_t[ntracks+2]; Float_t *norm = new Float_t[ntracks+2]; Float_t *maxr = new Float_t[ntracks+2]; Float_t *minr = new Float_t[ntracks+2]; Float_t *minPointAngle= new Float_t[ntracks+2]; // AliV0 *pvertex = new AliV0; AliITStrackMI * dummy= new AliITStrackMI; dummy->SetLabel(0); AliITStrackMI trackat0; //temporary track for DCA calculation // Float_t primvertex[3]={GetX(),GetY(),GetZ()}; // // make ITS - ESD map // for (Int_t itrack=0;itrack<ntracks+2;itrack++) { itsmap[itrack] = -1; forbidden[itrack] = kFALSE; maxr[itrack] = kMaxR; minr[itrack] = kMinR; minPointAngle[itrack] = kMinPointAngle; } for (Int_t itrack=0;itrack<nitstracks;itrack++){ AliITStrackMI * original = (AliITStrackMI*)(fOriginal.At(itrack)); Int_t esdindex = original->GetESDtrack()->GetID(); itsmap[esdindex] = itrack; } // // create ITS tracks from ESD tracks if not done before // for (Int_t itrack=0;itrack<ntracks;itrack++){ if (itsmap[itrack]>=0) continue; AliITStrackMI * tpctrack = new AliITStrackMI(*(event->GetTrack(itrack))); //tpctrack->fD[0] = tpctrack->GetD(GetX(),GetY()); //tpctrack->fD[1] = tpctrack->GetZat(GetX())-GetZ(); tpctrack->GetDZ(GetX(),GetY(),GetZ(),tpctrack->GetDP()); //I.B. if (tpctrack->GetD(0)<20 && tpctrack->GetD(1)<20){ // tracks which can reach inner part of ITS // propagate track to outer its volume - with correction for material CorrectForTPCtoITSDeadZoneMaterial(tpctrack); } itsmap[itrack] = nitstracks; fOriginal.AddAt(tpctrack,nitstracks); nitstracks++; } // // fill temporary arrays // for (Int_t itrack=0;itrack<ntracks;itrack++){ AliESDtrack * esdtrack = event->GetTrack(itrack); Int_t itsindex = itsmap[itrack]; AliITStrackMI *original = (AliITStrackMI*)fOriginal.At(itsmap[itrack]); if (!original) continue; AliITStrackMI *bestConst = 0; AliITStrackMI *bestLong = 0; AliITStrackMI *best = 0; // // TObjArray * array = (TObjArray*) fTrackHypothesys.At(itsindex); Int_t hentries = (array==0) ? 0 : array->GetEntriesFast(); // Get best track with vertex constrain for (Int_t ih=0;ih<hentries;ih++){ AliITStrackMI * trackh = (AliITStrackMI*)array->At(ih); if (!trackh->GetConstrain()) continue; if (!bestConst) bestConst = trackh; if (trackh->GetNumberOfClusters()>5.0){ bestConst = trackh; // full track - with minimal chi2 break; } if (trackh->GetNumberOfClusters()+trackh->GetNDeadZone()<=bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()) continue; bestConst = trackh; break; } // Get best long track without vertex constrain and best track without vertex constrain for (Int_t ih=0;ih<hentries;ih++){ AliITStrackMI * trackh = (AliITStrackMI*)array->At(ih); if (trackh->GetConstrain()) continue; if (!best) best = trackh; if (!bestLong) bestLong = trackh; if (trackh->GetNumberOfClusters()>5.0){ bestLong = trackh; // full track - with minimal chi2 break; } if (trackh->GetNumberOfClusters()+trackh->GetNDeadZone()<=bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()) continue; bestLong = trackh; } if (!best) { best = original; bestLong = original; } //I.B. trackat0 = *bestLong; new (&trackat0) AliITStrackMI(*bestLong); Double_t xx,yy,zz,alpha; if (!bestLong->GetGlobalXYZat(bestLong->GetX(),xx,yy,zz)) continue; alpha = TMath::ATan2(yy,xx); if (!trackat0.Propagate(alpha,0)) continue; // calculate normalized distances to the vertex // Float_t ptfac = (1.+100.*TMath::Abs(trackat0.GetC())); if ( bestLong->GetNumberOfClusters()>3 ){ dist[itsindex] = trackat0.GetY(); norm[itsindex] = ptfac*TMath::Sqrt(trackat0.GetSigmaY2()); normdist0[itsindex] = TMath::Abs(trackat0.GetY()/norm[itsindex]); normdist1[itsindex] = TMath::Abs((trackat0.GetZ()-primvertex[2])/(ptfac*TMath::Sqrt(trackat0.GetSigmaZ2()))); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); if (!bestConst){ if (bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()<6) normdist[itsindex]*=2.; if (bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()<5) normdist[itsindex]*=2.; if (bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()<4) normdist[itsindex]*=2.; }else{ if (bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()<6) normdist[itsindex]*=1.5; if (bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()<5) normdist[itsindex]*=1.5; } } else{ if (bestConst&&bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()>4.5){ dist[itsindex] = bestConst->GetD(0); norm[itsindex] = bestConst->GetDnorm(0); normdist0[itsindex] = TMath::Abs(bestConst->GetD(0)/norm[itsindex]); normdist1[itsindex] = TMath::Abs(bestConst->GetD(0)/norm[itsindex]); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); }else{ dist[itsindex] = trackat0.GetY(); norm[itsindex] = ptfac*TMath::Sqrt(trackat0.GetSigmaY2()); normdist0[itsindex] = TMath::Abs(trackat0.GetY()/norm[itsindex]); normdist1[itsindex] = TMath::Abs((trackat0.GetZ()-primvertex[2])/(ptfac*TMath::Sqrt(trackat0.GetSigmaZ2()))); normdist[itsindex] = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]); if (TMath::Abs(trackat0.GetTgl())>1.05){ if (normdist[itsindex]<3) forbidden[itsindex]=kTRUE; if (normdist[itsindex]>3) { minr[itsindex] = TMath::Max(Float_t(40.),minr[itsindex]); } } } } // //----------------------------------------------------------- //Forbid primary track candidates - // //treetr->SetAlias("forbidden0","Tr0.fN<4&&Tr1.fN+Tr1.fNDeadZone>4.5"); //treetr->SetAlias("forbidden1","ND<3&&Tr1.fN+Tr1.fNDeadZone>5.5"); //treetr->SetAlias("forbidden2","ND<2&&Tr1.fClIndex[0]>0&&Tr1.fClIndex[0]>0"); //treetr->SetAlias("forbidden3","ND<1&&Tr1.fClIndex[0]>0"); //treetr->SetAlias("forbidden4","ND<4&&Tr1.fNormChi2[0]<2"); //treetr->SetAlias("forbidden5","ND<5&&Tr1.fNormChi2[0]<1"); //----------------------------------------------------------- if (bestConst){ if (bestLong->GetNumberOfClusters()<4 && bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()>4.5) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<3 && bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()>5.5) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<2 && bestConst->GetClIndex(0)>0 && bestConst->GetClIndex(1)>0 ) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<1 && bestConst->GetClIndex(0)>0) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<4 && bestConst->GetNormChi2(0)<2) forbidden[itsindex]=kTRUE; if (normdist[itsindex]<5 && bestConst->GetNormChi2(0)<1) forbidden[itsindex]=kTRUE; if (bestConst->GetNormChi2(0)<2.5) { minPointAngle[itsindex]= 0.9999; maxr[itsindex] = 10; } } // //forbid daughter kink candidates // if (esdtrack->GetKinkIndex(0)>0) forbidden[itsindex] = kTRUE; Bool_t isElectron = kTRUE; Bool_t isProton = kTRUE; Double_t pid[5]; esdtrack->GetESDpid(pid); for (Int_t i=1;i<5;i++){ if (pid[0]<pid[i]) isElectron= kFALSE; if (pid[4]<pid[i]) isProton= kFALSE; } if (isElectron){ forbidden[itsindex]=kFALSE; normdist[itsindex]*=-1; } if (isProton){ if (normdist[itsindex]>2) forbidden[itsindex]=kFALSE; normdist[itsindex]*=-1; } // // Causality cuts in TPC volume // if (esdtrack->GetTPCdensity(0,10) >0.6) maxr[itsindex] = TMath::Min(Float_t(110),maxr[itsindex]); if (esdtrack->GetTPCdensity(10,30)>0.6) maxr[itsindex] = TMath::Min(Float_t(120),maxr[itsindex]); if (esdtrack->GetTPCdensity(20,40)>0.6) maxr[itsindex] = TMath::Min(Float_t(130),maxr[itsindex]); if (esdtrack->GetTPCdensity(30,50)>0.6) maxr[itsindex] = TMath::Min(Float_t(140),maxr[itsindex]); // if (esdtrack->GetTPCdensity(0,60)<0.4&&bestLong->GetNumberOfClusters()<3) minr[itsindex]=100; // // if (kFALSE){ cstream<<"Track"<< "Tr0.="<<best<< "Tr1.="<<((bestConst)? bestConst:dummy)<< "Tr2.="<<bestLong<< "Tr3.="<<&trackat0<< "Esd.="<<esdtrack<< "Dist="<<dist[itsindex]<< "ND0="<<normdist0[itsindex]<< "ND1="<<normdist1[itsindex]<< "ND="<<normdist[itsindex]<< "Pz="<<primvertex[2]<< "Forbid="<<forbidden[itsindex]<< "\n"; // } trackarray.AddAt(best,itsindex); trackarrayc.AddAt(bestConst,itsindex); trackarrayl.AddAt(bestLong,itsindex); new (&helixes[itsindex]) AliHelix(*best); } // // // // first iterration of V0 finder // for (Int_t iesd0=0;iesd0<ntracks;iesd0++){ Int_t itrack0 = itsmap[iesd0]; if (forbidden[itrack0]) continue; AliITStrackMI * btrack0 = (AliITStrackMI*)trackarray.At(itrack0); if (!btrack0) continue; if (btrack0->GetSign()>0) continue; AliITStrackMI *trackc0 = (AliITStrackMI*)trackarrayc.At(itrack0); // for (Int_t iesd1=0;iesd1<ntracks;iesd1++){ Int_t itrack1 = itsmap[iesd1]; if (forbidden[itrack1]) continue; AliITStrackMI * btrack1 = (AliITStrackMI*)trackarray.At(itrack1); if (!btrack1) continue; if (btrack1->GetSign()<0) continue; Bool_t isGold = kFALSE; if (TMath::Abs(TMath::Abs(btrack0->GetLabel())-TMath::Abs(btrack1->GetLabel()))==1){ isGold = kTRUE; } AliITStrackMI *trackc1 = (AliITStrackMI*)trackarrayc.At(itrack1); AliHelix &h1 = helixes[itrack0]; AliHelix &h2 = helixes[itrack1]; // // find linear distance Double_t rmin =0; // // // Double_t phase[2][2],radius[2]; Int_t points = h1.GetRPHIintersections(h2, phase, radius); if (points==0) continue; Double_t delta[2]={1000000,1000000}; rmin = radius[0]; h1.ParabolicDCA(h2,phase[0][0],phase[0][1],radius[0],delta[0]); if (points==2){ if (radius[1]<rmin) rmin = radius[1]; h1.ParabolicDCA(h2,phase[1][0],phase[1][1],radius[1],delta[1]); } rmin = TMath::Sqrt(rmin); Double_t distance = 0; Double_t radiusC = 0; Int_t iphase = 0; if (points==1 || delta[0]<delta[1]){ distance = TMath::Sqrt(delta[0]); radiusC = TMath::Sqrt(radius[0]); }else{ distance = TMath::Sqrt(delta[1]); radiusC = TMath::Sqrt(radius[1]); iphase=1; } if (radiusC<TMath::Max(minr[itrack0],minr[itrack1])) continue; if (radiusC>TMath::Min(maxr[itrack0],maxr[itrack1])) continue; Float_t maxDist = TMath::Min(kMaxDist,Float_t(kMaxDist0+radiusC*kMaxDist1)); if (distance>maxDist) continue; Float_t pointAngle = h1.GetPointAngle(h2,phase[iphase],primvertex); if (pointAngle<TMath::Max(minPointAngle[itrack0],minPointAngle[itrack1])) continue; // // // Double_t distance = TestV0(h1,h2,pvertex,rmin); // // if (distance>maxDist) continue; // if (pvertex->GetRr()<kMinR) continue; // if (pvertex->GetRr()>kMaxR) continue; AliITStrackMI * track0=btrack0; AliITStrackMI * track1=btrack1; // if (pvertex->GetRr()<3.5){ if (radiusC<3.5){ //use longest tracks inside the pipe track0 = (AliITStrackMI*)trackarrayl.At(itrack0); track1 = (AliITStrackMI*)trackarrayl.At(itrack1); } // // pvertex->SetParamN(*track0); pvertex->SetParamP(*track1); pvertex->Update(primvertex); pvertex->SetClusters(track0->ClIndex(),track1->ClIndex()); // register clusters if (pvertex->GetRr()<kMinR) continue; if (pvertex->GetRr()>kMaxR) continue; if (pvertex->GetV0CosineOfPointingAngle()<kMinPointAngle) continue; //Bo: if (pvertex->GetDist2()>maxDist) continue; if (pvertex->GetDcaV0Daughters()>maxDist) continue; //Bo: pvertex->SetLab(0,track0->GetLabel()); //Bo: pvertex->SetLab(1,track1->GetLabel()); pvertex->SetIndex(0,track0->GetESDtrack()->GetID()); pvertex->SetIndex(1,track1->GetESDtrack()->GetID()); // AliITStrackMI * htrackc0 = trackc0 ? trackc0:dummy; AliITStrackMI * htrackc1 = trackc1 ? trackc1:dummy; // // TObjArray * array0b = (TObjArray*)fBestHypothesys.At(itrack0); if (!array0b&&pvertex->GetRr()<40 && TMath::Abs(track0->GetTgl())<1.1) { fCurrentEsdTrack = itrack0; FollowProlongationTree((AliITStrackMI*)fOriginal.At(itrack0),itrack0, kFALSE); } TObjArray * array1b = (TObjArray*)fBestHypothesys.At(itrack1); if (!array1b&&pvertex->GetRr()<40 && TMath::Abs(track1->GetTgl())<1.1) { fCurrentEsdTrack = itrack1; FollowProlongationTree((AliITStrackMI*)fOriginal.At(itrack1),itrack1, kFALSE); } // AliITStrackMI * track0b = (AliITStrackMI*)fOriginal.At(itrack0); AliITStrackMI * track1b = (AliITStrackMI*)fOriginal.At(itrack1); AliITStrackMI * track0l = (AliITStrackMI*)fOriginal.At(itrack0); AliITStrackMI * track1l = (AliITStrackMI*)fOriginal.At(itrack1); Float_t minchi2before0=16; Float_t minchi2before1=16; Float_t minchi2after0 =16; Float_t minchi2after1 =16; Double_t xrp[3]; pvertex->GetXYZ(xrp[0],xrp[1],xrp[2]); //I.B. Int_t maxLayer = GetNearestLayer(xrp); //I.B. if (array0b) for (Int_t i=0;i<5;i++){ // best track after vertex AliITStrackMI * btrack = (AliITStrackMI*)array0b->At(i); if (!btrack) continue; if (btrack->GetNumberOfClusters()>track0l->GetNumberOfClusters()) track0l = btrack; // if (btrack->fX<pvertex->GetRr()-2.-0.5/(0.1+pvertex->GetAnglep()[2])) { if (btrack->GetX()<pvertex->GetRr()-2.) { if ( (maxLayer>i+2|| (i==0)) && btrack->GetNumberOfClusters()==(6-i)&&i<3){ Float_t sumchi2= 0; Float_t sumn = 0; if (maxLayer<3){ // take prim vertex as additional measurement if (normdist[itrack0]>0 && htrackc0){ sumchi2 += TMath::Min((3.-maxLayer)*normdist[itrack0]*normdist[itrack0],16.); }else{ sumchi2 += TMath::Min((3.-maxLayer)*(3*normdist[itrack0]*normdist[itrack0]+3.),16.); } sumn += 3-maxLayer; } for (Int_t ilayer=i;ilayer<maxLayer;ilayer++){ sumn+=1.; if (!btrack->GetClIndex(ilayer)){ sumchi2+=25; continue; }else{ Int_t c=( btrack->GetClIndex(ilayer) & 0x0fffffff); for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[ilayer].GetClusterTracks(itrack,c)>=0 && fgLayers[ilayer].GetClusterTracks(itrack,c)!=itrack0){ sumchi2+=18.; //shared cluster break; } } sumchi2+=btrack->GetDy(ilayer)*btrack->GetDy(ilayer)/(btrack->GetSigmaY(ilayer)*btrack->GetSigmaY(ilayer)); sumchi2+=btrack->GetDz(ilayer)*btrack->GetDz(ilayer)/(btrack->GetSigmaZ(ilayer)*btrack->GetSigmaZ(ilayer)); } } sumchi2/=sumn; if (sumchi2<minchi2before0) minchi2before0=sumchi2; } continue; //safety space - Geo manager will give exact layer } track0b = btrack; minchi2after0 = btrack->GetNormChi2(i); break; } if (array1b) for (Int_t i=0;i<5;i++){ // best track after vertex AliITStrackMI * btrack = (AliITStrackMI*)array1b->At(i); if (!btrack) continue; if (btrack->GetNumberOfClusters()>track1l->GetNumberOfClusters()) track1l = btrack; // if (btrack->fX<pvertex->GetRr()-2-0.5/(0.1+pvertex->GetAnglep()[2])){ if (btrack->GetX()<pvertex->GetRr()-2){ if ((maxLayer>i+2 || (i==0))&&btrack->GetNumberOfClusters()==(6-i)&&(i<3)){ Float_t sumchi2= 0; Float_t sumn = 0; if (maxLayer<3){ // take prim vertex as additional measurement if (normdist[itrack1]>0 && htrackc1){ sumchi2 += TMath::Min((3.-maxLayer)*normdist[itrack1]*normdist[itrack1],16.); }else{ sumchi2 += TMath::Min((3.-maxLayer)*(3*normdist[itrack1]*normdist[itrack1]+3.),16.); } sumn += 3-maxLayer; } for (Int_t ilayer=i;ilayer<maxLayer;ilayer++){ sumn+=1.; if (!btrack->GetClIndex(ilayer)){ sumchi2+=30; continue; }else{ Int_t c=( btrack->GetClIndex(ilayer) & 0x0fffffff); for (Int_t itrack=0;itrack<4;itrack++){ if (fgLayers[ilayer].GetClusterTracks(itrack,c)>=0 && fgLayers[ilayer].GetClusterTracks(itrack,c)!=itrack1){ sumchi2+=18.; //shared cluster break; } } sumchi2+=btrack->GetDy(ilayer)*btrack->GetDy(ilayer)/(btrack->GetSigmaY(ilayer)*btrack->GetSigmaY(ilayer)); sumchi2+=btrack->GetDz(ilayer)*btrack->GetDz(ilayer)/(btrack->GetSigmaZ(ilayer)*btrack->GetSigmaZ(ilayer)); } } sumchi2/=sumn; if (sumchi2<minchi2before1) minchi2before1=sumchi2; } continue; //safety space - Geo manager will give exact layer } track1b = btrack; minchi2after1 = btrack->GetNormChi2(i); break; } // // position resolution - used for DCA cut Float_t sigmad = track0b->GetSigmaY2()+track0b->GetSigmaZ2()+track1b->GetSigmaY2()+track1b->GetSigmaZ2()+ (track0b->GetX()-pvertex->GetRr())*(track0b->GetX()-pvertex->GetRr())*(track0b->GetSigmaSnp2()+track0b->GetSigmaTgl2())+ (track1b->GetX()-pvertex->GetRr())*(track1b->GetX()-pvertex->GetRr())*(track1b->GetSigmaSnp2()+track1b->GetSigmaTgl2()); sigmad =TMath::Sqrt(sigmad)+0.04; if (pvertex->GetRr()>50){ Double_t cov0[15],cov1[15]; track0b->GetESDtrack()->GetInnerExternalCovariance(cov0); track1b->GetESDtrack()->GetInnerExternalCovariance(cov1); sigmad = cov0[0]+cov0[2]+cov1[0]+cov1[2]+ (80.-pvertex->GetRr())*(80.-pvertex->GetRr())*(cov0[5]+cov0[9])+ (80.-pvertex->GetRr())*(80.-pvertex->GetRr())*(cov1[5]+cov1[9]); sigmad =TMath::Sqrt(sigmad)+0.05; } // AliV0 vertex2; vertex2.SetParamN(*track0b); vertex2.SetParamP(*track1b); vertex2.Update(primvertex); //Bo: if (vertex2.GetDist2()<=pvertex->GetDist2()&&(vertex2.GetV0CosineOfPointingAngle()>=pvertex->GetV0CosineOfPointingAngle())){ if (vertex2.GetDcaV0Daughters()<=pvertex->GetDcaV0Daughters()&&(vertex2.GetV0CosineOfPointingAngle()>=pvertex->GetV0CosineOfPointingAngle())){ pvertex->SetParamN(*track0b); pvertex->SetParamP(*track1b); pvertex->Update(primvertex); pvertex->SetClusters(track0b->ClIndex(),track1b->ClIndex()); // register clusters pvertex->SetIndex(0,track0->GetESDtrack()->GetID()); pvertex->SetIndex(1,track1->GetESDtrack()->GetID()); } pvertex->SetDistSigma(sigmad); //Bo: pvertex->SetDistNorm(pvertex->GetDist2()/sigmad); pvertex->SetNormDCAPrim(normdist[itrack0],normdist[itrack1]); // // define likelihhod and causalities // Float_t pa0=1, pa1=1, pb0=0.26, pb1=0.26; if (maxLayer<1){ Float_t fnorm0 = normdist[itrack0]; if (fnorm0<0) fnorm0*=-3; Float_t fnorm1 = normdist[itrack1]; if (fnorm1<0) fnorm1*=-3; if ((pvertex->GetAnglep()[2]>0.1) || ( (pvertex->GetRr()<10.5)&& pvertex->GetAnglep()[2]>0.05 ) || (pvertex->GetRr()<3)){ pb0 = TMath::Exp(-TMath::Min(fnorm0,Float_t(16.))/12.); pb1 = TMath::Exp(-TMath::Min(fnorm1,Float_t(16.))/12.); } pvertex->SetChi2Before(normdist[itrack0]); pvertex->SetChi2After(normdist[itrack1]); pvertex->SetNAfter(0); pvertex->SetNBefore(0); }else{ pvertex->SetChi2Before(minchi2before0); pvertex->SetChi2After(minchi2before1); if (pvertex->GetAnglep()[2]>0.1 || ( pvertex->GetRr()<10.5 && pvertex->GetAnglep()[2]>0.05) || pvertex->GetRr()<3){ pb0 = TMath::Exp(-TMath::Min(minchi2before0,Float_t(16))/12.); pb1 = TMath::Exp(-TMath::Min(minchi2before1,Float_t(16))/12.); } pvertex->SetNAfter(maxLayer); pvertex->SetNBefore(maxLayer); } if (pvertex->GetRr()<90){ pa0 *= TMath::Min(track0->GetESDtrack()->GetTPCdensity(0,60),Double_t(1.)); pa1 *= TMath::Min(track1->GetESDtrack()->GetTPCdensity(0,60),Double_t(1.)); } if (pvertex->GetRr()<20){ pa0 *= (0.2+TMath::Exp(-TMath::Min(minchi2after0,Float_t(16))/8.))/1.2; pa1 *= (0.2+TMath::Exp(-TMath::Min(minchi2after1,Float_t(16))/8.))/1.2; } // pvertex->SetCausality(pb0,pb1,pa0,pa1); // // Likelihood calculations - apply cuts // Bool_t v0OK = kTRUE; Float_t p12 = pvertex->GetParamP()->GetParameter()[4]*pvertex->GetParamP()->GetParameter()[4]; p12 += pvertex->GetParamN()->GetParameter()[4]*pvertex->GetParamN()->GetParameter()[4]; p12 = TMath::Sqrt(p12); // "mean" momenta Float_t sigmap0 = 0.0001+0.001/(0.1+pvertex->GetRr()); Float_t sigmap = 0.5*sigmap0*(0.6+0.4*p12); // "resolution: of point angle - as a function of radius and momenta Float_t causalityA = (1.0-pvertex->GetCausalityP()[0])*(1.0-pvertex->GetCausalityP()[1]); Float_t causalityB = TMath::Sqrt(TMath::Min(pvertex->GetCausalityP()[2],Double_t(0.7))* TMath::Min(pvertex->GetCausalityP()[3],Double_t(0.7))); // //Bo: Float_t likelihood0 = (TMath::Exp(-pvertex->GetDistNorm())+0.1) *(pvertex->GetDist2()<0.5)*(pvertex->GetDistNorm()<5); Float_t lDistNorm = pvertex->GetDcaV0Daughters()/pvertex->GetDistSigma(); Float_t likelihood0 = (TMath::Exp(-lDistNorm)+0.1) *(pvertex->GetDcaV0Daughters()<0.5)*(lDistNorm<5); Float_t likelihood1 = TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/sigmap)+ 0.4*TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/(4.*sigmap))+ 0.4*TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/(8.*sigmap))+ 0.1*TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/0.01); // if (causalityA<kCausality0Cut) v0OK = kFALSE; if (TMath::Sqrt(likelihood0*likelihood1)<kLikelihood01Cut) v0OK = kFALSE; if (likelihood1<kLikelihood1Cut) v0OK = kFALSE; if (TMath::Power(likelihood0*likelihood1*causalityB,0.33)<kCombinedCut) v0OK = kFALSE; // // if (kFALSE){ Bool_t gold = TMath::Abs(TMath::Abs(track0->GetLabel())-TMath::Abs(track1->GetLabel()))==1; cstream<<"It0"<< "Tr0.="<<track0<< //best without constrain "Tr1.="<<track1<< //best without constrain "Tr0B.="<<track0b<< //best without constrain after vertex "Tr1B.="<<track1b<< //best without constrain after vertex "Tr0C.="<<htrackc0<< //best with constrain if exist "Tr1C.="<<htrackc1<< //best with constrain if exist "Tr0L.="<<track0l<< //longest best "Tr1L.="<<track1l<< //longest best "Esd0.="<<track0->GetESDtrack()<< // esd track0 params "Esd1.="<<track1->GetESDtrack()<< // esd track1 params "V0.="<<pvertex<< //vertex properties "V0b.="<<&vertex2<< //vertex properties at "best" track "ND0="<<normdist[itrack0]<< //normalize distance for track0 "ND1="<<normdist[itrack1]<< //normalize distance for track1 "Gold="<<gold<< // // "RejectBase="<<rejectBase<< //rejection in First itteration "OK="<<v0OK<< "rmin="<<rmin<< "sigmad="<<sigmad<< "\n"; } //if (rejectBase) continue; // pvertex->SetStatus(0); // if (rejectBase) { // pvertex->SetStatus(-100); //} if (pvertex->GetV0CosineOfPointingAngle()>kMinPointAngle2) { //Bo: pvertex->SetESDindexes(track0->GetESDtrack()->GetID(),track1->GetESDtrack()->GetID()); pvertex->SetIndex(0,track0->GetESDtrack()->GetID());//Bo: consistency 0 for neg pvertex->SetIndex(1,track1->GetESDtrack()->GetID());//Bo: consistency 1 for pos if (v0OK){ // AliV0vertex vertexjuri(*track0,*track1); // vertexjuri.SetESDindexes(track0->fESDtrack->GetID(),track1->fESDtrack->GetID()); // event->AddV0(&vertexjuri); pvertex->SetStatus(100); } pvertex->SetOnFlyStatus(kTRUE); pvertex->ChangeMassHypothesis(kK0Short); event->AddV0(pvertex); } } } // // // delete temporary arrays // delete[] forbidden; delete[] minPointAngle; delete[] maxr; delete[] minr; delete[] norm; delete[] normdist; delete[] normdist1; delete[] normdist0; delete[] dist; delete[] itsmap; delete[] helixes; delete pvertex; } //------------------------------------------------------------------------ void AliITStrackerMI::RefitV02(AliESDEvent *event) { // //try to refit V0s in the third path of the reconstruction // TTreeSRedirector &cstream = *fDebugStreamer; // Int_t nv0s = event->GetNumberOfV0s(); Float_t primvertex[3]={GetX(),GetY(),GetZ()}; AliV0 v0temp; for (Int_t iv0 = 0; iv0<nv0s;iv0++){ AliV0 * v0mi = (AliV0*)event->GetV0(iv0); if (!v0mi) continue; Int_t itrack0 = v0mi->GetIndex(0); Int_t itrack1 = v0mi->GetIndex(1); AliESDtrack *esd0 = event->GetTrack(itrack0); AliESDtrack *esd1 = event->GetTrack(itrack1); if (!esd0||!esd1) continue; AliITStrackMI tpc0(*esd0); AliITStrackMI tpc1(*esd1); Double_t x,y,z; v0mi->GetXYZ(x,y,z); //I.B. Double_t alpha =TMath::ATan2(y,x); //I.B. if (v0mi->GetRr()>85){ if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ v0temp.SetParamN(tpc0); v0temp.SetParamP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; //Bo: if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ if (v0temp.GetDcaV0Daughters()<v0mi->GetDcaV0Daughters() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ v0mi->SetParamN(tpc0); v0mi->SetParamP(tpc1); v0mi->Update(primvertex); } } continue; } if (v0mi->GetRr()>35){ CorrectForTPCtoITSDeadZoneMaterial(&tpc0); CorrectForTPCtoITSDeadZoneMaterial(&tpc1); if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ v0temp.SetParamN(tpc0); v0temp.SetParamP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; //Bo: if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ if (v0temp.GetDcaV0Daughters()<v0mi->GetDcaV0Daughters() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ v0mi->SetParamN(tpc0); v0mi->SetParamP(tpc1); v0mi->Update(primvertex); } } continue; } CorrectForTPCtoITSDeadZoneMaterial(&tpc0); CorrectForTPCtoITSDeadZoneMaterial(&tpc1); // if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){ if (RefitAt(v0mi->GetRr(),&tpc0, v0mi->GetClusters(0)) && RefitAt(v0mi->GetRr(),&tpc1, v0mi->GetClusters(1))){ v0temp.SetParamN(tpc0); v0temp.SetParamP(tpc1); v0temp.Update(primvertex); if (kFALSE) cstream<<"Refit"<< "V0.="<<v0mi<< "V0refit.="<<&v0temp<< "Tr0.="<<&tpc0<< "Tr1.="<<&tpc1<< "\n"; //Bo: if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ if (v0temp.GetDcaV0Daughters()<v0mi->GetDcaV0Daughters() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){ v0mi->SetParamN(tpc0); v0mi->SetParamP(tpc1); v0mi->Update(primvertex); } } } } //------------------------------------------------------------------------ void AliITStrackerMI::BuildMaterialLUT(TString material) { //-------------------------------------------------------------------- // Fill a look-up table with mean material //-------------------------------------------------------------------- Int_t n=1000; Double_t mparam[7]; Double_t point1[3],point2[3]; Double_t phi,cosphi,sinphi,z; // 0-5 layers, 6 pipe, 7-8 shields Double_t rmin[9]={ 3.5, 5.5,13.0,22.0,35.0,41.0, 2.0, 8.0,25.0}; Double_t rmax[9]={ 5.5, 8.0,17.0,26.0,41.0,47.0, 3.0,10.5,30.0}; Int_t ifirst=0,ilast=0; if(material.Contains("Pipe")) { ifirst=6; ilast=6; } else if(material.Contains("Shields")) { ifirst=7; ilast=8; } else if(material.Contains("Layers")) { ifirst=0; ilast=5; } else { Error("BuildMaterialLUT","Wrong layer name\n"); } for(Int_t imat=ifirst; imat<=ilast; imat++) { Double_t param[5]={0.,0.,0.,0.,0.}; for (Int_t i=0; i<n; i++) { phi = 2.*TMath::Pi()*gRandom->Rndm(); cosphi = TMath::Cos(phi); sinphi = TMath::Sin(phi); z = 14.*(-1.+2.*gRandom->Rndm()); // SPD barrel point1[0] = rmin[imat]*cosphi; point1[1] = rmin[imat]*sinphi; point1[2] = z; point2[0] = rmax[imat]*cosphi; point2[1] = rmax[imat]*sinphi; point2[2] = z; AliTracker::MeanMaterialBudget(point1,point2,mparam); for(Int_t j=0;j<5;j++) param[j]+=mparam[j]; } for(Int_t j=0;j<5;j++) param[j]/=(Float_t)n; if(imat<=5) { fxOverX0Layer[imat] = param[1]; fxTimesRhoLayer[imat] = param[0]*param[4]; } else if(imat==6) { fxOverX0Pipe = param[1]; fxTimesRhoPipe = param[0]*param[4]; } else if(imat==7) { fxOverX0Shield[0] = param[1]; fxTimesRhoShield[0] = param[0]*param[4]; } else if(imat==8) { fxOverX0Shield[1] = param[1]; fxTimesRhoShield[1] = param[0]*param[4]; } } /* printf("%s\n",material.Data()); printf("%f %f\n",fxOverX0Pipe,fxTimesRhoPipe); printf("%f %f\n",fxOverX0Shield[0],fxTimesRhoShield[0]); printf("%f %f\n",fxOverX0Shield[1],fxTimesRhoShield[1]); printf("%f %f\n",fxOverX0Layer[0],fxTimesRhoLayer[0]); printf("%f %f\n",fxOverX0Layer[1],fxTimesRhoLayer[1]); printf("%f %f\n",fxOverX0Layer[2],fxTimesRhoLayer[2]); printf("%f %f\n",fxOverX0Layer[3],fxTimesRhoLayer[3]); printf("%f %f\n",fxOverX0Layer[4],fxTimesRhoLayer[4]); printf("%f %f\n",fxOverX0Layer[5],fxTimesRhoLayer[5]); */ return; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::CorrectForPipeMaterial(AliITStrackMI *t, TString direction) { //------------------------------------------------------------------- // Propagate beyond beam pipe and correct for material // (material budget in different ways according to fUseTGeo value) //------------------------------------------------------------------- // Define budget mode: // 0: material from AliITSRecoParam (hard coded) // 1: material from TGeo in one step (on the fly) // 2: material from lut // 3: material from TGeo in one step (same for all hypotheses) Int_t mode; switch(fUseTGeo) { case 0: mode=0; break; case 1: mode=1; break; case 2: mode=2; break; case 3: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=1; } break; case 4: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=2; } break; default: mode=0; break; } if(fTrackingPhase.Contains("Default")) mode=0; Int_t index=fCurrentEsdTrack; Float_t dir = (direction.Contains("inward") ? 1. : -1.); Double_t rToGo=(dir>0 ? AliITSRecoParam::GetrInsidePipe() : AliITSRecoParam::GetrOutsidePipe()); Double_t xToGo; if (!t->GetLocalXat(rToGo,xToGo)) return 0; Double_t xOverX0,x0,lengthTimesMeanDensity; Bool_t anglecorr=kTRUE; switch(mode) { case 0: xOverX0 = AliITSRecoParam::GetdPipe(); x0 = AliITSRecoParam::GetX0Be(); lengthTimesMeanDensity = xOverX0*x0; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 1: if (!t->PropagateToTGeo(xToGo,1)) return 0; break; case 2: if(fxOverX0Pipe<0) BuildMaterialLUT("Pipe"); xOverX0 = fxOverX0Pipe; lengthTimesMeanDensity = fxTimesRhoPipe; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 3: if(!fxOverX0PipeTrks || index<0 || index>=fNtracks) Error("CorrectForPipeMaterial","Incorrect usage of UseTGeo option!\n"); if(fxOverX0PipeTrks[index]<0) { if (!t->PropagateToTGeo(xToGo,1,xOverX0,lengthTimesMeanDensity)) return 0; Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/ (1.-t->GetSnp()*t->GetSnp())); fxOverX0PipeTrks[index] = TMath::Abs(xOverX0)/angle; fxTimesRhoPipeTrks[index] = TMath::Abs(lengthTimesMeanDensity)/angle; return 1; } xOverX0 = fxOverX0PipeTrks[index]; lengthTimesMeanDensity = fxTimesRhoPipeTrks[index]; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; } return 1; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::CorrectForShieldMaterial(AliITStrackMI *t, TString shield, TString direction) { //------------------------------------------------------------------- // Propagate beyond SPD or SDD shield and correct for material // (material budget in different ways according to fUseTGeo value) //------------------------------------------------------------------- // Define budget mode: // 0: material from AliITSRecoParam (hard coded) // 1: material from TGeo in steps of X cm (on the fly) // X = AliITSRecoParam::GetStepSizeTGeo() // 2: material from lut // 3: material from TGeo in one step (same for all hypotheses) Int_t mode; switch(fUseTGeo) { case 0: mode=0; break; case 1: mode=1; break; case 2: mode=2; break; case 3: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=1; } break; case 4: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=2; } break; default: mode=0; break; } if(fTrackingPhase.Contains("Default")) mode=0; Float_t dir = (direction.Contains("inward") ? 1. : -1.); Double_t rToGo; Int_t shieldindex=0; if (shield.Contains("SDD")) { // SDDouter rToGo=(dir>0 ? AliITSRecoParam::GetrInsideShield(1) : AliITSRecoParam::GetrOutsideShield(1)); shieldindex=1; } else if (shield.Contains("SPD")) { // SPDouter rToGo=(dir>0 ? AliITSRecoParam::GetrInsideShield(0) : AliITSRecoParam::GetrOutsideShield(0)); shieldindex=0; } else { Error("CorrectForShieldMaterial"," Wrong shield name\n"); return 0; } Double_t xToGo; if (!t->GetLocalXat(rToGo,xToGo)) return 0; Int_t index=2*fCurrentEsdTrack+shieldindex; Double_t xOverX0,x0,lengthTimesMeanDensity; Bool_t anglecorr=kTRUE; Int_t nsteps=1; switch(mode) { case 0: xOverX0 = AliITSRecoParam::Getdshield(shieldindex); x0 = AliITSRecoParam::GetX0shield(shieldindex); lengthTimesMeanDensity = xOverX0*x0; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 1: nsteps= (Int_t)(TMath::Abs(t->GetX()-xToGo)/AliITSReconstructor::GetRecoParam()->GetStepSizeTGeo())+1; if (!t->PropagateToTGeo(xToGo,nsteps)) return 0; // cross the material and apply correction break; case 2: if(fxOverX0Shield[shieldindex]<0) BuildMaterialLUT("Shields"); xOverX0 = fxOverX0Shield[shieldindex]; lengthTimesMeanDensity = fxTimesRhoShield[shieldindex]; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 3: if(!fxOverX0ShieldTrks || index<0 || index>=2*fNtracks) Error("CorrectForShieldMaterial","Incorrect usage of UseTGeo option!\n"); if(fxOverX0ShieldTrks[index]<0) { if (!t->PropagateToTGeo(xToGo,1,xOverX0,lengthTimesMeanDensity)) return 0; Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/ (1.-t->GetSnp()*t->GetSnp())); fxOverX0ShieldTrks[index] = TMath::Abs(xOverX0)/angle; fxTimesRhoShieldTrks[index] = TMath::Abs(lengthTimesMeanDensity)/angle; return 1; } xOverX0 = fxOverX0ShieldTrks[index]; lengthTimesMeanDensity = fxTimesRhoShieldTrks[index]; lengthTimesMeanDensity *= dir; if (!t->Propagate(xToGo)) return 0; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; } return 1; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::CorrectForLayerMaterial(AliITStrackMI *t, Int_t layerindex, Double_t oldGlobXYZ[3], TString direction) { //------------------------------------------------------------------- // Propagate beyond layer and correct for material // (material budget in different ways according to fUseTGeo value) //------------------------------------------------------------------- // Define budget mode: // 0: material from AliITSRecoParam (hard coded) // 1: material from TGeo in stepsof X cm (on the fly) // X = AliITSRecoParam::GetStepSizeTGeo() // 2: material from lut // 3: material from TGeo in one step (same for all hypotheses) Int_t mode; switch(fUseTGeo) { case 0: mode=0; break; case 1: mode=1; break; case 2: mode=2; break; case 3: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=1; } break; case 4: if(fTrackingPhase.Contains("Clusters2Tracks")) { mode=3; } else { mode=2; } break; default: mode=0; break; } if(fTrackingPhase.Contains("Default")) mode=0; Float_t dir = (direction.Contains("inward") ? 1. : -1.); Double_t r=fgLayers[layerindex].GetR(); Double_t deltar=(layerindex<2 ? 0.10*r : 0.05*r); Double_t rToGo=TMath::Sqrt(t->GetX()*t->GetX()+t->GetY()*t->GetY())-deltar*dir; Double_t xToGo; if (!t->GetLocalXat(rToGo,xToGo)) return 0; Int_t index=6*fCurrentEsdTrack+layerindex; Double_t xOverX0=0.0,x0=0.0,lengthTimesMeanDensity=0.0; Double_t mparam[7]; Bool_t anglecorr=kTRUE; Int_t nsteps=1; Double_t rOld,xOld; switch(mode) { case 0: xOverX0 = fgLayers[layerindex].GetThickness(t->GetY(),t->GetZ(),x0); lengthTimesMeanDensity = xOverX0*x0; // Bring the track beyond the material if (!t->Propagate(xToGo)) return 0; lengthTimesMeanDensity *= dir; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 1: rOld=TMath::Sqrt(oldGlobXYZ[0]*oldGlobXYZ[0]+oldGlobXYZ[1]*oldGlobXYZ[1]); if (!t->GetLocalXat(rOld,xOld)) return 0; if (!t->Propagate(xOld)) return 0; // back before material (no correction) nsteps = (Int_t)(TMath::Abs(xOld-xToGo)/AliITSReconstructor::GetRecoParam()->GetStepSizeTGeo())+1; if (!t->PropagateToTGeo(xToGo,nsteps)) return 0; // cross the material and apply correction break; case 2: if(fxOverX0Layer[layerindex]<0) BuildMaterialLUT("Layers"); xOverX0 = fxOverX0Layer[layerindex]; lengthTimesMeanDensity = fxTimesRhoLayer[layerindex]; // Bring the track beyond the material if (!t->Propagate(xToGo)) return 0; lengthTimesMeanDensity *= dir; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; case 3: if(!fxOverX0LayerTrks || index<0 || index>=6*fNtracks) Error("CorrectForLayerMaterial","Incorrect usage of UseTGeo option!\n"); // Bring the track beyond the material if (!t->Propagate(xToGo)) return 0; Double_t globXYZ[3]; if (!t->GetXYZ(globXYZ)) return 0; if (fxOverX0LayerTrks[index]<0) { AliTracker::MeanMaterialBudget(oldGlobXYZ,globXYZ,mparam); if(mparam[1]>900000) return 0; Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/ (1.-t->GetSnp()*t->GetSnp())); xOverX0=mparam[1]/angle; lengthTimesMeanDensity=mparam[0]*mparam[4]/angle; fxOverX0LayerTrks[index] = TMath::Abs(xOverX0); fxTimesRhoLayerTrks[index] = TMath::Abs(lengthTimesMeanDensity); } xOverX0 = fxOverX0LayerTrks[index]; lengthTimesMeanDensity = fxTimesRhoLayerTrks[index]; lengthTimesMeanDensity *= dir; if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0; break; } return 1; } //------------------------------------------------------------------------ void AliITStrackerMI::MakeTrksMaterialLUT(Int_t ntracks) { //----------------------------------------------------------------- // Initialize LUT for storing material for each prolonged track //----------------------------------------------------------------- fxOverX0PipeTrks = new Float_t[ntracks]; fxTimesRhoPipeTrks = new Float_t[ntracks]; fxOverX0ShieldTrks = new Float_t[ntracks*2]; fxTimesRhoShieldTrks = new Float_t[ntracks*2]; fxOverX0LayerTrks = new Float_t[ntracks*6]; fxTimesRhoLayerTrks = new Float_t[ntracks*6]; for(Int_t i=0; i<ntracks; i++) { fxOverX0PipeTrks[i] = -1.; fxTimesRhoPipeTrks[i] = -1.; } for(Int_t j=0; j<ntracks*2; j++) { fxOverX0ShieldTrks[j] = -1.; fxTimesRhoShieldTrks[j] = -1.; } for(Int_t k=0; k<ntracks*6; k++) { fxOverX0LayerTrks[k] = -1.; fxTimesRhoLayerTrks[k] = -1.; } fNtracks = ntracks; return; } //------------------------------------------------------------------------ void AliITStrackerMI::DeleteTrksMaterialLUT() { //----------------------------------------------------------------- // Delete LUT for storing material for each prolonged track //----------------------------------------------------------------- if(fxOverX0PipeTrks) { delete [] fxOverX0PipeTrks; fxOverX0PipeTrks = 0; } if(fxOverX0ShieldTrks) { delete [] fxOverX0ShieldTrks; fxOverX0ShieldTrks = 0; } if(fxOverX0LayerTrks) { delete [] fxOverX0LayerTrks; fxOverX0LayerTrks = 0; } if(fxTimesRhoPipeTrks) { delete [] fxTimesRhoPipeTrks; fxTimesRhoPipeTrks = 0; } if(fxTimesRhoShieldTrks) { delete [] fxTimesRhoShieldTrks; fxTimesRhoShieldTrks = 0; } if(fxTimesRhoLayerTrks) { delete [] fxTimesRhoLayerTrks; fxTimesRhoLayerTrks = 0; } return; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::CheckSkipLayer(AliITStrackMI *track, Int_t ilayer,Int_t idet) const { //----------------------------------------------------------------- // This method is used to decide whether to allow a prolongation // without clusters, because we want to skip the layer. // In this case the return value is > 0: // return 1: the user requested to skip a layer // return 2: track outside z acceptance of SSD/SDD and will cross both SPD //----------------------------------------------------------------- if (AliITSReconstructor::GetRecoParam()->GetLayersToSkip(ilayer)) return 1; if (idet<0 && ilayer>1 && AliITSReconstructor::GetRecoParam()->GetExtendedEtaAcceptance()) { // check if track will cross SPD outer layer Double_t phiAtSPD2,zAtSPD2; if (track->GetPhiZat(fgLayers[1].GetR(),phiAtSPD2,zAtSPD2)) { if (TMath::Abs(zAtSPD2)<2.*AliITSRecoParam::GetSPDdetzlength()) return 2; } } return 0; } //------------------------------------------------------------------------ Int_t AliITStrackerMI::CheckDeadZone(AliITStrackMI *track, Int_t ilayer,Int_t idet, Double_t dz,Double_t dy, Bool_t noClusters) const { //----------------------------------------------------------------- // This method is used to decide whether to allow a prolongation // without clusters, because there is a dead zone in the road. // In this case the return value is > 0: // return 1: dead zone at z=0,+-7cm in SPD // return 2: all road is "bad" (dead or noisy) from the OCDB // return 3: something "bad" (dead or noisy) from the OCDB //----------------------------------------------------------------- // check dead zones at z=0,+-7cm in the SPD if (ilayer<2 && !AliITSReconstructor::GetRecoParam()->GetAddVirtualClustersInDeadZone()) { Double_t zmindead[3]={fSPDdetzcentre[0] + 0.5*AliITSRecoParam::GetSPDdetzlength(), fSPDdetzcentre[1] + 0.5*AliITSRecoParam::GetSPDdetzlength(), fSPDdetzcentre[2] + 0.5*AliITSRecoParam::GetSPDdetzlength()}; Double_t zmaxdead[3]={fSPDdetzcentre[1] - 0.5*AliITSRecoParam::GetSPDdetzlength(), fSPDdetzcentre[2] - 0.5*AliITSRecoParam::GetSPDdetzlength(), fSPDdetzcentre[3] - 0.5*AliITSRecoParam::GetSPDdetzlength()}; for (Int_t i=0; i<3; i++) if (track->GetZ()-dz<zmaxdead[i] && track->GetZ()+dz>zmindead[i]) { AliDebug(2,Form("crack SPD %d",ilayer)); return 1; } } // check bad zones from OCDB if (!AliITSReconstructor::GetRecoParam()->GetUseBadZonesFromOCDB()) return 0; if (idet<0) return 0; AliITSdetector &det=fgLayers[ilayer].GetDetector(idet); Int_t detType=-1; Float_t detSizeFactorX=0.0001,detSizeFactorZ=0.0001; if (ilayer==0 || ilayer==1) { // ---------- SPD detType = 0; } else if (ilayer==2 || ilayer==3) { // ---------- SDD detType = 1; detSizeFactorX *= 2.; } else if (ilayer==4 || ilayer==5) { // ---------- SSD detType = 2; } AliITSsegmentation *segm = (AliITSsegmentation*)fDetTypeRec->GetSegmentationModel(detType); if (detType==2) segm->SetLayer(ilayer+1); Float_t detSizeX = detSizeFactorX*segm->Dx(); Float_t detSizeZ = detSizeFactorZ*segm->Dz(); // check if the road overlaps with bad chips Float_t xloc,zloc; LocalModuleCoord(ilayer,idet,track,xloc,zloc); Float_t zlocmin = zloc-dz; Float_t zlocmax = zloc+dz; Float_t xlocmin = xloc-dy; Float_t xlocmax = xloc+dy; Int_t chipsInRoad[100]; // check if road goes out of detector Bool_t touchNeighbourDet=kFALSE; if (TMath::Abs(xlocmin)>0.5*detSizeX) {xlocmin=-0.5*detSizeX; touchNeighbourDet=kTRUE;} if (TMath::Abs(xlocmax)>0.5*detSizeX) {xlocmax=+0.5*detSizeX; touchNeighbourDet=kTRUE;} if (TMath::Abs(zlocmin)>0.5*detSizeZ) {zlocmin=-0.5*detSizeZ; touchNeighbourDet=kTRUE;} if (TMath::Abs(zlocmax)>0.5*detSizeZ) {zlocmax=+0.5*detSizeZ; touchNeighbourDet=kTRUE;} AliDebug(2,Form("layer %d det %d zmim zmax %f %f xmin xmax %f %f %f %f",ilayer,idet,zlocmin,zlocmax,xlocmin,xlocmax,detSizeZ,detSizeX)); // check if this detector is bad if (det.IsBad()) { AliDebug(2,Form("lay %d bad detector %d",ilayer,idet)); if(!touchNeighbourDet) { return 2; // all detectors in road are bad } else { return 3; // at least one is bad } } Int_t nChipsInRoad = segm->GetChipsInLocalWindow(chipsInRoad,zlocmin,zlocmax,xlocmin,xlocmax); AliDebug(2,Form("lay %d nChipsInRoad %d",ilayer,nChipsInRoad)); if (!nChipsInRoad) return 0; Bool_t anyBad=kFALSE,anyGood=kFALSE; for (Int_t iCh=0; iCh<nChipsInRoad; iCh++) { if (chipsInRoad[iCh]<0 || chipsInRoad[iCh]>det.GetNChips()-1) continue; AliDebug(2,Form(" chip %d bad %d",chipsInRoad[iCh],(Int_t)det.IsChipBad(chipsInRoad[iCh]))); if (det.IsChipBad(chipsInRoad[iCh])) { anyBad=kTRUE; } else { anyGood=kTRUE; } } if (!anyGood) { if(!touchNeighbourDet) { AliDebug(2,"all bad in road"); return 2; // all chips in road are bad } else { return 3; // at least a bad chip in road } } if (anyBad) { AliDebug(2,"at least a bad in road"); return 3; // at least a bad chip in road } if (!AliITSReconstructor::GetRecoParam()->GetUseSingleBadChannelsFromOCDB() || ilayer==4 || ilayer==5 // SSD || !noClusters) return 0; // There are no clusters in road: check if there is at least // a bad SPD pixel or SDD anode Int_t idetInITS=idet; for(Int_t l=0;l<ilayer;l++) idetInITS+=AliITSgeomTGeo::GetNLadders(l+1)*AliITSgeomTGeo::GetNDetectors(l+1); if (fITSChannelStatus->AnyBadInRoad(idetInITS,zlocmin,zlocmax,xlocmin,xlocmax)) { AliDebug(2,Form("Bad channel in det %d of layer %d\n",idet,ilayer)); return 3; } //if (fITSChannelStatus->FractionOfBadInRoad(idet,zlocmin,zlocmax,xlocmin,xlocmax) > AliITSReconstructor::GetRecoParam()->GetMinFractionOfBadInRoad()) return 3; return 0; } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::LocalModuleCoord(Int_t ilayer,Int_t idet, AliITStrackMI *track, Float_t &xloc,Float_t &zloc) const { //----------------------------------------------------------------- // Gives position of track in local module ref. frame //----------------------------------------------------------------- xloc=0.; zloc=0.; if(idet<0) return kFALSE; Int_t ndet=AliITSgeomTGeo::GetNDetectors(ilayer+1); // layers from 1 to 6 Int_t lad = Int_t(idet/ndet) + 1; Int_t det = idet - (lad-1)*ndet + 1; Double_t xyzGlob[3],xyzLoc[3]; AliITSdetector &detector = fgLayers[ilayer].GetDetector(idet); // take into account the misalignment: xyz at real detector plane if(!track->GetXYZAt(detector.GetRmisal(),GetBz(),xyzGlob)) return kFALSE; if(!AliITSgeomTGeo::GlobalToLocal(ilayer+1,lad,det,xyzGlob,xyzLoc)) return kFALSE; xloc = (Float_t)xyzLoc[0]; zloc = (Float_t)xyzLoc[2]; return kTRUE; } //------------------------------------------------------------------------ Bool_t AliITStrackerMI::IsOKForPlaneEff(AliITStrackMI* track, const Int_t *clusters, Int_t ilayer) const { // // Method to be optimized further: // Aim: decide whether a track can be used for PlaneEff evaluation // the decision is taken based on the track quality at the layer under study // no information on the clusters on this layer has to be used // The criterium is to reject tracks at boundaries between basic block (e.g. SPD chip) // the cut is done on number of sigmas from the boundaries // // Input: Actual track, layer [0,5] under study // Output: none // Return: kTRUE if this is a good track // // it will apply a pre-selection to obtain good quality tracks. // Here also you will have the possibility to put a control on the // impact point of the track on the basic block, in order to exclude border regions // this will be done by calling a proper method of the AliITSPlaneEff class. // // input: AliITStrackMI* track, ilayer= layer number [0,5] // return: Bool_t -> kTRUE if usable track, kFALSE if not usable. // Int_t index[AliITSgeomTGeo::kNLayers]; Int_t k; for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1; // for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) { index[k]=clusters[k]; } if(!fPlaneEff) {AliWarning("IsOKForPlaneEff: null pointer to AliITSPlaneEff"); return kFALSE;} AliITSlayer &layer=fgLayers[ilayer]; Double_t r=layer.GetR(); AliITStrackMI tmp(*track); // require a minimal number of cluster in other layers and eventually clusters in closest layers Int_t ncl=0; for(Int_t lay=AliITSgeomTGeo::kNLayers-1;lay>ilayer;lay--) { AliDebug(2,Form("trak=%d lay=%d ; index=%d ESD label= %d",tmp.GetLabel(),lay, tmp.GetClIndex(lay),((AliESDtrack*)tmp.GetESDtrack())->GetLabel())) ; if (tmp.GetClIndex(lay)>0) ncl++; } Bool_t nextout = kFALSE; if(ilayer==AliITSgeomTGeo::kNLayers-1) nextout=kTRUE; // you are already on the outermost layer else nextout = ((tmp.GetClIndex(ilayer+1)>0)? kTRUE : kFALSE ); Bool_t nextin = kFALSE; if(ilayer==0) nextin=kTRUE; // you are already on the innermost layer else nextin = ((index[ilayer-1]>=0)? kTRUE : kFALSE ); if(ncl<AliITSgeomTGeo::kNLayers-(ilayer+1)-AliITSReconstructor::GetRecoParam()->GetMaxMissingClustersPlaneEff()) return kFALSE; if(AliITSReconstructor::GetRecoParam()->GetRequireClusterInOuterLayerPlaneEff() && !nextout) return kFALSE; if(AliITSReconstructor::GetRecoParam()->GetRequireClusterInInnerLayerPlaneEff() && !nextin) return kFALSE; if(tmp.Pt() < AliITSReconstructor::GetRecoParam()->GetMinPtPlaneEff()) return kFALSE; // if(AliITSReconstructor::GetRecoParam()->GetOnlyConstraintPlaneEff() && !tmp.GetConstrain()) return kFALSE; // detector number Double_t phi,z; if (!tmp.GetPhiZat(r,phi,z)) return kFALSE; Int_t idet=layer.FindDetectorIndex(phi,z); if(idet<0) { AliInfo(Form("cannot find detector")); return kFALSE;} // here check if it has good Chi Square. //propagate to the intersection with the detector plane const AliITSdetector &det=layer.GetDetector(idet); if (!tmp.Propagate(det.GetPhi(),det.GetR())) return kFALSE; Float_t locx; // Float_t locz; // if(!LocalModuleCoord(ilayer,idet,&tmp,locx,locz)) return kFALSE; UInt_t key=fPlaneEff->GetKeyFromDetLocCoord(ilayer,idet,locx,locz); if(key>fPlaneEff->Nblock()) return kFALSE; Float_t blockXmn,blockXmx,blockZmn,blockZmx; if (!fPlaneEff->GetBlockBoundaries(key,blockXmn,blockXmx,blockZmn,blockZmx)) return kFALSE; //*************** // DEFINITION OF SEARCH ROAD FOR accepting a track // //For the time being they are hard-wired, later on from AliITSRecoParam // Double_t nsigx=AliITSRecoParam::GetNSigXFarFromBoundary(); // Double_t nsigz=AliITSRecoParam::GetNSigZFarFromBoundary(); Double_t nsigz=4; Double_t nsigx=4; Double_t dx=nsigx*TMath::Sqrt(tmp.GetSigmaY2()); // those are precisions in the tracking reference system Double_t dz=nsigz*TMath::Sqrt(tmp.GetSigmaZ2()); // Use it also for the module reference system, as it is // done for RecPoints // exclude tracks at boundary between detectors //Double_t boundaryWidth=AliITSRecoParam::GetBoundaryWidthPlaneEff(); Double_t boundaryWidth=0; // for the time being hard-wired, later on from AliITSRecoParam AliDebug(2,Form("Tracking: track impact x=%f, y=%f, z=%f",tmp.GetX(), tmp.GetY(), tmp.GetZ())); AliDebug(2,Form("Local: track impact x=%f, z=%f",locx,locz)); AliDebug(2,Form("Search Road. Tracking: dy=%f , dz=%f",dx,dz)); if ( (locx-dx < blockXmn+boundaryWidth) || (locx+dx > blockXmx-boundaryWidth) || (locz-dz < blockZmn+boundaryWidth) || (locz+dz > blockZmx-boundaryWidth) ) return kFALSE; return kTRUE; } //------------------------------------------------------------------------ void AliITStrackerMI::UseTrackForPlaneEff(AliITStrackMI* track, Int_t ilayer) { // // This Method has to be optimized! For the time-being it uses the same criteria // as those used in the search of extra clusters for overlapping modules. // // Method Purpose: estabilish whether a track has produced a recpoint or not // in the layer under study (For Plane efficiency) // // inputs: AliITStrackMI* track (pointer to a usable track) // outputs: none // side effects: update (by 1 count) the Plane Efficiency statistics of the basic block // traversed by this very track. In details: // - if a cluster can be associated to the track then call // AliITSPlaneEff::UpDatePlaneEff(key,kTRUE); // - if not, the AliITSPlaneEff::UpDatePlaneEff(key,kFALSE) is called // if(!fPlaneEff) {AliWarning("UseTrackForPlaneEff: null pointer to AliITSPlaneEff"); return;} AliITSlayer &layer=fgLayers[ilayer]; Double_t r=layer.GetR(); AliITStrackMI tmp(*track); // detector number Double_t phi,z; if (!tmp.GetPhiZat(r,phi,z)) return; Int_t idet=layer.FindDetectorIndex(phi,z); if(idet<0) { AliInfo(Form("cannot find detector")); return;} //propagate to the intersection with the detector plane const AliITSdetector &det=layer.GetDetector(idet); if (!tmp.Propagate(det.GetPhi(),det.GetR())) return; //*************** // DEFINITION OF SEARCH ROAD FOR CLUSTERS SELECTION // Double_t dz=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadZ()* TMath::Sqrt(tmp.GetSigmaZ2() + AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer)); Double_t dy=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadY()* TMath::Sqrt(tmp.GetSigmaY2() + AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer)); // road in global (rphi,z) [i.e. in tracking ref. system] Double_t zmin = tmp.GetZ() - dz; Double_t zmax = tmp.GetZ() + dz; Double_t ymin = tmp.GetY() + r*det.GetPhi() - dy; Double_t ymax = tmp.GetY() + r*det.GetPhi() + dy; // select clusters in road layer.SelectClusters(zmin,zmax,ymin,ymax); // Define criteria for track-cluster association Double_t msz = tmp.GetSigmaZ2() + AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()* AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer); Double_t msy = tmp.GetSigmaY2() + AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()* AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer); if (tmp.GetConstrain()) { msz *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadZC(); msy *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadYC(); } else { msz *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadZNonC(); msy *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadYNonC(); } msz = 1./msz; // 1/RoadZ^2 msy = 1./msy; // 1/RoadY^2 // const AliITSRecPoint *cl=0; Int_t clidx=-1, ci=-1; Int_t idetc=-1; Double_t chi2trkcl=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2(); //Double_t tolerance=0.2; /*while ((cl=layer.GetNextCluster(clidx))!=0) { idetc = cl->GetDetectorIndex(); if(idet!=idetc) continue; //Int_t ilay = cl->GetLayer(); if (TMath::Abs(tmp.GetZ() - cl->GetZ()) > tolerance) continue; if (TMath::Abs(tmp.GetY() - cl->GetY()) > tolerance) continue; Double_t chi2=tmp.GetPredictedChi2(cl); if (chi2<chi2trkcl) { chi2trkcl=chi2; ci=clidx; } }*/ Float_t locx; // Float_t locz; // if(!LocalModuleCoord(ilayer,idet,&tmp,locx,locz)) return; // AliDebug(2,Form("ilayer= %d, idet=%d, x= %f, z=%f",ilayer,idet,locx,locz)); UInt_t key=fPlaneEff->GetKeyFromDetLocCoord(ilayer,idet,locx,locz); if(key>fPlaneEff->Nblock()) return; Bool_t found=kFALSE; //if (ci>=0) { Double_t chi2; while ((cl=layer.GetNextCluster(clidx))!=0) { idetc = cl->GetDetectorIndex(); if(idet!=idetc) continue; // here real control to see whether the cluster can be associated to the track. // cluster not associated to track if ( (tmp.GetZ()-cl->GetZ())*(tmp.GetZ()-cl->GetZ())*msz + (tmp.GetY()-cl->GetY())*(tmp.GetY()-cl->GetY())*msy > 1. ) continue; // calculate track-clusters chi2 chi2 = GetPredictedChi2MI(&tmp,cl,ilayer); // note that this method change track tmp // in particular, the error associated to the cluster //Double_t chi2 = tmp.GetPredictedChi(cl); // this method does not change track tmp // chi2 cut if (chi2 > AliITSReconstructor::GetRecoParam()->GetMaxChi2s(ilayer)) continue; found=kTRUE; if (chi2<chi2trkcl) { chi2trkcl=chi2; ci=clidx; } // this just to trace which cluster is selected // track->SetExtraCluster(ilayer,(ilayer<<28)+ci); // track->SetExtraModule(ilayer,idetExtra); } if(!fPlaneEff->UpDatePlaneEff(found,key)) AliWarning(Form("UseTrackForPlaneEff: cannot UpDate PlaneEff for key=%d",key)); if(fPlaneEff->GetCreateHistos()&& AliITSReconstructor::GetRecoParam()->GetHistoPlaneEff()) { Float_t tr[4]={99999.,99999.,9999.,9999.}; // initialize to high values Float_t clu[4]={-99999.,-99999.,9999.,9999.}; // (in some cases GetCov fails) Int_t cltype[2]={-999,-999}; tr[0]=locx; tr[1]=locz; tr[2]=TMath::Sqrt(tmp.GetSigmaY2()); // those are precisions in the tracking reference system tr[3]=TMath::Sqrt(tmp.GetSigmaZ2()); // Use it also for the module reference system, as it is if (found){ clu[0]=layer.GetCluster(ci)->GetDetLocalX(); clu[1]=layer.GetCluster(ci)->GetDetLocalZ(); cltype[0]=layer.GetCluster(ci)->GetNy(); cltype[1]=layer.GetCluster(ci)->GetNz(); // Without the following 6 lines you would retrieve the nominal error of a cluster (e.g. for the SPD: // X->50/sqrt(12)=14 micron Z->450/sqrt(12)= 120 micron) // Within AliTrackerMI/AliTrackMI the error on the cluster is associated to the AliITStrackMI (fSigmaY,Z) // It is computed properly by calling the method // AliITStrackerMI::GetPredictedChi2MI(AliITStrackMI* track, const AliITSRecPoint *cluster,Int_t layer) // T //Double_t x=0.5*(tmp.GetX()+layer.GetCluster(ci)->GetX()); // Take into account the mis-alignment //if (tmp.PropagateTo(x,0.,0.)) { chi2=GetPredictedChi2MI(&tmp,layer.GetCluster(ci),ilayer); AliCluster c(*layer.GetCluster(ci)); c.SetSigmaY2(tmp.GetSigmaY(ilayer)*tmp.GetSigmaY(ilayer)); c.SetSigmaZ2(tmp.GetSigmaZ(ilayer)*tmp.GetSigmaZ(ilayer)); //if (layer.GetCluster(ci)->GetGlobalCov(cov)) // by using this, instead, you got nominal cluster errors clu[2]=TMath::Sqrt(c.GetSigmaY2()); clu[3]=TMath::Sqrt(c.GetSigmaZ2()); //} } fPlaneEff->FillHistos(key,found,tr,clu,cltype); } return; }
/*************************************************************************/ /* os_x11.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "os_x11.h" #include "core/os/dir_access.h" #include "core/print_string.h" #include "detect_prime.h" #include "drivers/gles2/rasterizer_gles2.h" #include "drivers/gles3/rasterizer_gles3.h" #include "key_mapping_x11.h" #include "main/main.h" #include "servers/visual/visual_server_raster.h" #include "servers/visual/visual_server_wrap_mt.h" #ifdef HAVE_MNTENT #include <mntent.h> #endif #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <X11/Xatom.h> #include <X11/Xutil.h> #include <X11/extensions/Xinerama.h> #include <X11/extensions/shape.h> // ICCCM #define WM_NormalState 1L // window normal state #define WM_IconicState 3L // window minimized // EWMH #define _NET_WM_STATE_REMOVE 0L // remove/unset property #define _NET_WM_STATE_ADD 1L // add/set property #define _NET_WM_STATE_TOGGLE 2L // toggle property #include <dlfcn.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> //stupid linux.h #ifdef KEY_TAB #undef KEY_TAB #endif #undef CursorShape #include <X11/XKBlib.h> // 2.2 is the first release with multitouch #define XINPUT_CLIENT_VERSION_MAJOR 2 #define XINPUT_CLIENT_VERSION_MINOR 2 #define VALUATOR_ABSX 0 #define VALUATOR_ABSY 1 #define VALUATOR_PRESSURE 2 #define VALUATOR_TILTX 3 #define VALUATOR_TILTY 4 static const double abs_resolution_mult = 10000.0; static const double abs_resolution_range_mult = 10.0; void OS_X11::initialize_core() { crash_handler.initialize(); OS_Unix::initialize_core(); } int OS_X11::get_current_video_driver() const { return video_driver_index; } Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { long im_event_mask = 0; last_button_state = 0; xmbstring = nullptr; x11_window = 0; last_click_ms = 0; last_click_button_index = -1; last_click_pos = Point2(-100, -100); args = OS::get_singleton()->get_cmdline_args(); current_videomode = p_desired; main_loop = nullptr; last_timestamp = 0; last_mouse_pos_valid = false; last_keyrelease_time = 0; xdnd_version = 0; XInitThreads(); /** XLIB INITIALIZATION **/ x11_display = XOpenDisplay(nullptr); if (!x11_display) { ERR_PRINT("X11 Display is not available"); return ERR_UNAVAILABLE; } char *modifiers = nullptr; Bool xkb_dar = False; XAutoRepeatOn(x11_display); xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, nullptr); // Try to support IME if detectable auto-repeat is supported if (xkb_dar == True) { #ifdef X_HAVE_UTF8_STRING // Xutf8LookupString will be used later instead of XmbLookupString before // the multibyte sequences can be converted to unicode string. modifiers = XSetLocaleModifiers(""); #endif } if (modifiers == nullptr) { if (is_stdout_verbose()) { WARN_PRINT("IME is disabled"); } XSetLocaleModifiers("@im=none"); WARN_PRINT("Error setting locale modifiers"); } const char *err; xrr_get_monitors = nullptr; xrr_free_monitors = nullptr; int xrandr_major = 0; int xrandr_minor = 0; int event_base, error_base; xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base); xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY); if (!xrandr_handle) { err = dlerror(); // For some arcane reason, NetBSD now ships libXrandr.so.3 while the rest of the world has libXrandr.so.2... // In case this happens for other X11 platforms in the future, let's give it a try too before failing. xrandr_handle = dlopen("libXrandr.so.3", RTLD_LAZY); if (!xrandr_handle) { fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err); } } else { XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor); if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) { xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors"); if (!xrr_get_monitors) { err = dlerror(); fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err); } else { xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors"); if (!xrr_free_monitors) { err = dlerror(); fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err); xrr_get_monitors = nullptr; } } } } if (!refresh_device_info()) { OS::get_singleton()->alert("Your system does not support XInput 2.\n" "Please upgrade your distribution.", "Unable to initialize XInput"); return ERR_UNAVAILABLE; } xim = XOpenIM(x11_display, nullptr, nullptr, nullptr); if (xim == nullptr) { WARN_PRINT("XOpenIM failed"); xim_style = 0L; } else { ::XIMCallback im_destroy_callback; im_destroy_callback.client_data = (::XPointer)(this); im_destroy_callback.callback = (::XIMProc)(xim_destroy_callback); if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback, NULL) != nullptr) { WARN_PRINT("Error setting XIM destroy callback"); } ::XIMStyles *xim_styles = nullptr; xim_style = 0L; char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL); if (imvalret != nullptr || xim_styles == nullptr) { fprintf(stderr, "Input method doesn't support any styles\n"); } if (xim_styles) { xim_style = 0L; for (int i = 0; i < xim_styles->count_styles; i++) { if (xim_styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) { xim_style = xim_styles->supported_styles[i]; break; } } XFree(xim_styles); } XFree(imvalret); } /* char* windowid = getenv("GODOT_WINDOWID"); if (windowid) { //freopen("/home/punto/stdout", "w", stdout); //reopen("/home/punto/stderr", "w", stderr); x11_window = atol(windowid); XWindowAttributes xwa; XGetWindowAttributes(x11_display,x11_window,&xwa); current_videomode.width = xwa.width; current_videomode.height = xwa.height; }; */ // maybe contextgl wants to be in charge of creating the window #if defined(OPENGL_ENABLED) if (getenv("DRI_PRIME") == nullptr) { int use_prime = -1; if (getenv("PRIMUS_DISPLAY") || getenv("PRIMUS_libGLd") || getenv("PRIMUS_libGLa") || getenv("PRIMUS_libGL") || getenv("PRIMUS_LOAD_GLOBAL") || getenv("BUMBLEBEE_SOCKET")) { print_verbose("Optirun/primusrun detected. Skipping GPU detection"); use_prime = 0; } // Some tools use fake libGL libraries and have them override the real one using // LD_LIBRARY_PATH, so we skip them. *But* Steam also sets LD_LIBRARY_PATH for its // runtime and includes system `/lib` and `/lib64`... so ignore Steam. if (use_prime == -1 && getenv("LD_LIBRARY_PATH") && !getenv("STEAM_RUNTIME_LIBRARY_PATH")) { String ld_library_path(getenv("LD_LIBRARY_PATH")); Vector<String> libraries = ld_library_path.split(":"); for (int i = 0; i < libraries.size(); ++i) { if (FileAccess::exists(libraries[i] + "/libGL.so.1") || FileAccess::exists(libraries[i] + "/libGL.so")) { print_verbose("Custom libGL override detected. Skipping GPU detection"); use_prime = 0; } } } if (use_prime == -1) { print_verbose("Detecting GPUs, set DRI_PRIME in the environment to override GPU detection logic."); use_prime = detect_prime(); } if (use_prime) { print_line("Found discrete GPU, setting DRI_PRIME=1 to use it."); print_line("Note: Set DRI_PRIME=0 in the environment to disable Godot from using the discrete GPU."); setenv("DRI_PRIME", "1", 1); } } ContextGL_X11::ContextType opengl_api_type = ContextGL_X11::GLES_3_0_COMPATIBLE; if (p_video_driver == VIDEO_DRIVER_GLES2) { opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; } bool editor = Engine::get_singleton()->is_editor_hint(); bool gl_initialization_error = false; context_gl = nullptr; while (!context_gl) { context_gl = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, opengl_api_type)); if (context_gl->initialize() != OK) { memdelete(context_gl); context_gl = nullptr; if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) { if (p_video_driver == VIDEO_DRIVER_GLES2) { gl_initialization_error = true; break; } p_video_driver = VIDEO_DRIVER_GLES2; opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; } else { gl_initialization_error = true; break; } } } while (true) { if (opengl_api_type == ContextGL_X11::GLES_3_0_COMPATIBLE) { if (RasterizerGLES3::is_viable() == OK) { RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); break; } else { if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) { p_video_driver = VIDEO_DRIVER_GLES2; opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; continue; } else { gl_initialization_error = true; break; } } } if (opengl_api_type == ContextGL_X11::GLES_2_0_COMPATIBLE) { if (RasterizerGLES2::is_viable() == OK) { RasterizerGLES2::register_config(); RasterizerGLES2::make_current(); break; } else { gl_initialization_error = true; break; } } } if (gl_initialization_error) { OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n" "Please update your drivers or if you have a very old or integrated GPU, upgrade it.\n" "If you have updated your graphics drivers recently, try rebooting.\n" "Alternatively, you can force software rendering by running Godot with the `LIBGL_ALWAYS_SOFTWARE=1`\n" "environment variable set, but this will be very slow.", "Unable to initialize Video driver"); return ERR_UNAVAILABLE; } video_driver_index = p_video_driver; context_gl->set_use_vsync(current_videomode.use_vsync); #endif visual_server = memnew(VisualServerRaster); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); } if (current_videomode.maximized) { current_videomode.maximized = false; set_window_maximized(true); // borderless fullscreen window mode } else if (current_videomode.fullscreen) { current_videomode.fullscreen = false; set_window_fullscreen(true); } else if (current_videomode.borderless_window) { Hints hints; Atom property; hints.flags = 2; hints.decorations = 0; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } // make PID known to X11 { const long pid = this->get_process_id(); Atom net_wm_pid = XInternAtom(x11_display, "_NET_WM_PID", False); if (net_wm_pid != None) { XChangeProperty(x11_display, x11_window, net_wm_pid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1); } } // disable resizable window if (!current_videomode.resizable && !current_videomode.fullscreen) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = PMinSize | PMaxSize; XWindowAttributes xwa; if (current_videomode.fullscreen) { XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa); } else { XGetWindowAttributes(x11_display, x11_window, &xwa); } xsh->min_width = xwa.width; xsh->max_width = xwa.width; xsh->min_height = xwa.height; xsh->max_height = xwa.height; XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); } if (current_videomode.always_on_top) { current_videomode.always_on_top = false; set_window_always_on_top(true); } ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE); ERR_FAIL_COND_V(x11_window == 0, ERR_UNAVAILABLE); XSetWindowAttributes new_attr; new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask | Button1MotionMask | Button2MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask | ButtonMotionMask | KeymapStateMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | SubstructureNotifyMask | SubstructureRedirectMask | FocusChangeMask | PropertyChangeMask | ColormapChangeMask | OwnerGrabButtonMask | im_event_mask; XChangeWindowAttributes(x11_display, x11_window, CWEventMask, &new_attr); static unsigned char all_mask_data[XIMaskLen(XI_LASTEVENT)] = {}; static unsigned char all_master_mask_data[XIMaskLen(XI_LASTEVENT)] = {}; xi.all_event_mask.deviceid = XIAllDevices; xi.all_event_mask.mask_len = sizeof(all_mask_data); xi.all_event_mask.mask = all_mask_data; xi.all_master_event_mask.deviceid = XIAllMasterDevices; xi.all_master_event_mask.mask_len = sizeof(all_master_mask_data); xi.all_master_event_mask.mask = all_master_mask_data; XISetMask(xi.all_event_mask.mask, XI_HierarchyChanged); XISetMask(xi.all_master_event_mask.mask, XI_DeviceChanged); XISetMask(xi.all_master_event_mask.mask, XI_RawMotion); #ifdef TOUCH_ENABLED if (xi.touch_devices.size()) { XISetMask(xi.all_event_mask.mask, XI_TouchBegin); XISetMask(xi.all_event_mask.mask, XI_TouchUpdate); XISetMask(xi.all_event_mask.mask, XI_TouchEnd); XISetMask(xi.all_event_mask.mask, XI_TouchOwnership); } #endif XISelectEvents(x11_display, x11_window, &xi.all_event_mask, 1); XISelectEvents(x11_display, DefaultRootWindow(x11_display), &xi.all_master_event_mask, 1); // Disabled by now since grabbing also blocks mouse events // (they are received as extended events instead of standard events) /*XIClearMask(xi.touch_event_mask.mask, XI_TouchOwnership); // Grab touch devices to avoid OS gesture interference for (int i = 0; i < xi.touch_devices.size(); ++i) { XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask); }*/ /* set the titlebar name */ XStoreName(x11_display, x11_window, "Godot"); wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true); XSetWMProtocols(x11_display, x11_window, &wm_delete, 1); im_active = false; im_position = Vector2(); if (xim && xim_style) { xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, x11_window, XNFocusWindow, x11_window, (char *)nullptr); if (XGetICValues(xic, XNFilterEvents, &im_event_mask, NULL) != nullptr) { WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value"); XDestroyIC(xic); xic = nullptr; } if (xic) { XUnsetICFocus(xic); } else { WARN_PRINT("XCreateIC couldn't create xic"); } } else { xic = nullptr; WARN_PRINT("XCreateIC couldn't create xic"); } cursor_size = XcursorGetDefaultSize(x11_display); cursor_theme = XcursorGetTheme(x11_display); if (!cursor_theme) { print_verbose("XcursorGetTheme could not get cursor theme"); cursor_theme = "default"; } for (int i = 0; i < CURSOR_MAX; i++) { cursors[i] = None; img[i] = nullptr; } current_cursor = CURSOR_ARROW; for (int i = 0; i < CURSOR_MAX; i++) { static const char *cursor_file[] = { "left_ptr", "xterm", "hand2", "cross", "watch", "left_ptr_watch", "fleur", "hand1", "X_cursor", "sb_v_double_arrow", "sb_h_double_arrow", "size_bdiag", "size_fdiag", "hand1", "sb_v_double_arrow", "sb_h_double_arrow", "question_arrow" }; img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size); if (img[i]) { cursors[i] = XcursorImageLoadCursor(x11_display, img[i]); } else { print_verbose("Failed loading custom cursor: " + String(cursor_file[i])); } } { // Creating an empty/transparent cursor // Create 1x1 bitmap Pixmap cursormask = XCreatePixmap(x11_display, RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1); // Fill with zero XGCValues xgc; xgc.function = GXclear; GC gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc); XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1); // Color value doesn't matter. Mask zero means no foreground or background will be drawn XColor col = {}; Cursor cursor = XCreatePixmapCursor(x11_display, cursormask, // source (using cursor mask as placeholder, since it'll all be ignored) cursormask, // mask &col, &col, 0, 0); XFreePixmap(x11_display, cursormask); XFreeGC(x11_display, gc); if (cursor == None) { ERR_PRINT("FAILED CREATING CURSOR"); } null_cursor = cursor; } set_cursor_shape(CURSOR_BUSY); //Set Xdnd (drag & drop) support Atom XdndAware = XInternAtom(x11_display, "XdndAware", False); Atom version = 5; if (XdndAware != None) { XChangeProperty(x11_display, x11_window, XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&version, 1); } xdnd_enter = XInternAtom(x11_display, "XdndEnter", False); xdnd_position = XInternAtom(x11_display, "XdndPosition", False); xdnd_status = XInternAtom(x11_display, "XdndStatus", False); xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False); xdnd_drop = XInternAtom(x11_display, "XdndDrop", False); xdnd_finished = XInternAtom(x11_display, "XdndFinished", False); xdnd_selection = XInternAtom(x11_display, "XdndSelection", False); requested = None; visual_server->init(); AudioDriverManager::initialize(p_audio_driver); input = memnew(InputDefault); window_has_focus = true; // Set focus to true at init #ifdef JOYDEV_ENABLED joypad = memnew(JoypadLinux(input)); #endif power_manager = memnew(PowerX11); if (p_desired.layered) { set_window_per_pixel_transparency_enabled(true); } XEvent xevent; while (XPending(x11_display) > 0) { XNextEvent(x11_display, &xevent); if (xevent.type == ConfigureNotify) { _window_changed(&xevent); } } events_thread.start(_poll_events_thread, this); update_real_mouse_position(); return OK; } bool OS_X11::refresh_device_info() { int event_base, error_base; print_verbose("XInput: Refreshing devices."); if (!XQueryExtension(x11_display, "XInputExtension", &xi.opcode, &event_base, &error_base)) { print_verbose("XInput extension not available. Please upgrade your distribution."); return false; } int xi_major_query = XINPUT_CLIENT_VERSION_MAJOR; int xi_minor_query = XINPUT_CLIENT_VERSION_MINOR; if (XIQueryVersion(x11_display, &xi_major_query, &xi_minor_query) != Success) { print_verbose(vformat("XInput 2 not available (server supports %d.%d).", xi_major_query, xi_minor_query)); xi.opcode = 0; return false; } if (xi_major_query < XINPUT_CLIENT_VERSION_MAJOR || (xi_major_query == XINPUT_CLIENT_VERSION_MAJOR && xi_minor_query < XINPUT_CLIENT_VERSION_MINOR)) { print_verbose(vformat("XInput %d.%d not available (server supports %d.%d). Touch input unavailable.", XINPUT_CLIENT_VERSION_MAJOR, XINPUT_CLIENT_VERSION_MINOR, xi_major_query, xi_minor_query)); } xi.absolute_devices.clear(); xi.touch_devices.clear(); int dev_count; XIDeviceInfo *info = XIQueryDevice(x11_display, XIAllDevices, &dev_count); for (int i = 0; i < dev_count; i++) { XIDeviceInfo *dev = &info[i]; if (!dev->enabled) { continue; } if (!(dev->use == XIMasterPointer || dev->use == XIFloatingSlave)) { continue; } bool direct_touch = false; bool absolute_mode = false; int resolution_x = 0; int resolution_y = 0; double abs_x_min = 0; double abs_x_max = 0; double abs_y_min = 0; double abs_y_max = 0; double pressure_min = 0; double pressure_max = 0; double tilt_x_min = 0; double tilt_x_max = 0; double tilt_y_min = 0; double tilt_y_max = 0; for (int j = 0; j < dev->num_classes; j++) { #ifdef TOUCH_ENABLED if (dev->classes[j]->type == XITouchClass && ((XITouchClassInfo *)dev->classes[j])->mode == XIDirectTouch) { direct_touch = true; } #endif if (dev->classes[j]->type == XIValuatorClass) { XIValuatorClassInfo *class_info = (XIValuatorClassInfo *)dev->classes[j]; if (class_info->number == VALUATOR_ABSX && class_info->mode == XIModeAbsolute) { resolution_x = class_info->resolution; abs_x_min = class_info->min; abs_y_max = class_info->max; absolute_mode = true; } else if (class_info->number == VALUATOR_ABSY && class_info->mode == XIModeAbsolute) { resolution_y = class_info->resolution; abs_y_min = class_info->min; abs_y_max = class_info->max; absolute_mode = true; } else if (class_info->number == VALUATOR_PRESSURE && class_info->mode == XIModeAbsolute) { pressure_min = class_info->min; pressure_max = class_info->max; } else if (class_info->number == VALUATOR_TILTX && class_info->mode == XIModeAbsolute) { tilt_x_min = class_info->min; tilt_x_max = class_info->max; } else if (class_info->number == VALUATOR_TILTY && class_info->mode == XIModeAbsolute) { tilt_x_min = class_info->min; tilt_x_max = class_info->max; } } } if (direct_touch) { xi.touch_devices.push_back(dev->deviceid); print_verbose("XInput: Using touch device: " + String(dev->name)); } if (absolute_mode) { // If no resolution was reported, use the min/max ranges. if (resolution_x <= 0) { resolution_x = (abs_x_max - abs_x_min) * abs_resolution_range_mult; } if (resolution_y <= 0) { resolution_y = (abs_y_max - abs_y_min) * abs_resolution_range_mult; } xi.absolute_devices[dev->deviceid] = Vector2(abs_resolution_mult / resolution_x, abs_resolution_mult / resolution_y); print_verbose("XInput: Absolute pointing device: " + String(dev->name)); } xi.pressure = 0; xi.pen_pressure_range[dev->deviceid] = Vector2(pressure_min, pressure_max); xi.pen_tilt_x_range[dev->deviceid] = Vector2(tilt_x_min, tilt_x_max); xi.pen_tilt_y_range[dev->deviceid] = Vector2(tilt_y_min, tilt_y_max); } XIFreeDeviceInfo(info); #ifdef TOUCH_ENABLED if (!xi.touch_devices.size()) { print_verbose("XInput: No touch devices found."); } #endif return true; } void OS_X11::xim_destroy_callback(::XIM im, ::XPointer client_data, ::XPointer call_data) { WARN_PRINT("Input method stopped"); OS_X11 *os = reinterpret_cast<OS_X11 *>(client_data); os->xim = nullptr; os->xic = nullptr; } void OS_X11::set_ime_active(const bool p_active) { im_active = p_active; if (!xic) { return; } // Block events polling while changing input focus // because it triggers some event polling internally. if (p_active) { { MutexLock mutex_lock(events_mutex); XSetICFocus(xic); } set_ime_position(im_position); } else { MutexLock mutex_lock(events_mutex); XUnsetICFocus(xic); } } void OS_X11::set_ime_position(const Point2 &p_pos) { im_position = p_pos; if (!xic) { return; } ::XPoint spot; spot.x = short(p_pos.x); spot.y = short(p_pos.y); XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, NULL); { // Block events polling during this call // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XSetICValues(xic, XNPreeditAttributes, preedit_attr, NULL); } XFree(preedit_attr); } String OS_X11::get_unique_id() const { static String machine_id; if (machine_id.empty()) { if (FileAccess *f = FileAccess::open("/etc/machine-id", FileAccess::READ)) { while (machine_id.empty() && !f->eof_reached()) { machine_id = f->get_line().strip_edges(); } f->close(); memdelete(f); } } return machine_id; } void OS_X11::finalize() { events_thread_done = true; events_thread.wait_to_finish(); if (main_loop) { memdelete(main_loop); } main_loop = nullptr; /* if (debugger_connection_console) { memdelete(debugger_connection_console); } */ #ifdef ALSAMIDI_ENABLED driver_alsamidi.close(); #endif #ifdef JOYDEV_ENABLED memdelete(joypad); #endif xi.touch_devices.clear(); xi.state.clear(); memdelete(input); cursors_cache.clear(); visual_server->finish(); memdelete(visual_server); //memdelete(rasterizer); memdelete(power_manager); if (xrandr_handle) { dlclose(xrandr_handle); } if (!OS::get_singleton()->is_no_window_mode_enabled()) { XUnmapWindow(x11_display, x11_window); } XDestroyWindow(x11_display, x11_window); #if defined(OPENGL_ENABLED) memdelete(context_gl); #endif for (int i = 0; i < CURSOR_MAX; i++) { if (cursors[i] != None) { XFreeCursor(x11_display, cursors[i]); } if (img[i] != nullptr) { XcursorImageDestroy(img[i]); } }; if (xic) { XDestroyIC(xic); } if (xim) { XCloseIM(xim); } XCloseDisplay(x11_display); if (xmbstring) { memfree(xmbstring); } args.clear(); } void OS_X11::set_mouse_mode(MouseMode p_mode) { if (p_mode == mouse_mode) { return; } if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) { XUngrabPointer(x11_display, CurrentTime); } // The only modes that show a cursor are VISIBLE and CONFINED bool showCursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED); if (showCursor) { XDefineCursor(x11_display, x11_window, cursors[current_cursor]); // show cursor } else { XDefineCursor(x11_display, x11_window, null_cursor); // hide cursor } mouse_mode = p_mode; if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) { //flush pending motion events flush_mouse_motion(); if (XGrabPointer( x11_display, x11_window, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime) != GrabSuccess) { ERR_PRINT("NO GRAB"); } if (mouse_mode == MOUSE_MODE_CAPTURED) { center.x = current_videomode.width / 2; center.y = current_videomode.height / 2; XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)center.x, (int)center.y); input->set_mouse_position(center); } } else { do_mouse_warp = false; } XFlush(x11_display); } void OS_X11::warp_mouse_position(const Point2 &p_to) { if (mouse_mode == MOUSE_MODE_CAPTURED) { last_mouse_pos = p_to; } else { /*XWindowAttributes xwa; XGetWindowAttributes(x11_display, x11_window, &xwa); printf("%d %d\n", xwa.x, xwa.y); needed? */ XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)p_to.x, (int)p_to.y); } } void OS_X11::flush_mouse_motion() { // Block events polling while flushing motion events. MutexLock mutex_lock(events_mutex); for (uint32_t event_index = 0; event_index < polled_events.size(); ++event_index) { XEvent &event = polled_events[event_index]; if (XGetEventData(x11_display, &event.xcookie) && event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) { XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data; if (event_data->evtype == XI_RawMotion) { XFreeEventData(x11_display, &event.xcookie); polled_events.remove(event_index--); continue; } XFreeEventData(x11_display, &event.xcookie); break; } } xi.relative_motion.x = 0; xi.relative_motion.y = 0; } OS::MouseMode OS_X11::get_mouse_mode() const { return mouse_mode; } int OS_X11::get_mouse_button_state() const { return last_button_state; } Point2 OS_X11::get_mouse_position() const { return last_mouse_pos; } bool OS_X11::get_window_per_pixel_transparency_enabled() const { if (!is_layered_allowed()) { return false; } return layered_window; } void OS_X11::set_window_per_pixel_transparency_enabled(bool p_enabled) { if (!is_layered_allowed()) { return; } if (layered_window != p_enabled) { if (p_enabled) { layered_window = true; } else { layered_window = false; } } } void OS_X11::set_window_title(const String &p_title) { XStoreName(x11_display, x11_window, p_title.utf8().get_data()); Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false); Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false); if (_net_wm_name != None && utf8_string != None) { XChangeProperty(x11_display, x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length()); } } void OS_X11::set_window_mouse_passthrough(const PoolVector2Array &p_region) { int event_base, error_base; const Bool ext_okay = XShapeQueryExtension(x11_display, &event_base, &error_base); if (ext_okay) { Region region; if (p_region.size() == 0) { region = XCreateRegion(); XRectangle rect; rect.x = 0; rect.y = 0; rect.width = get_real_window_size().x; rect.height = get_real_window_size().y; XUnionRectWithRegion(&rect, region, region); } else { XPoint *points = (XPoint *)memalloc(sizeof(XPoint) * p_region.size()); for (int i = 0; i < p_region.size(); i++) { points[i].x = p_region[i].x; points[i].y = p_region[i].y; } region = XPolygonRegion(points, p_region.size(), EvenOddRule); memfree(points); } XShapeCombineRegion(x11_display, x11_window, ShapeInput, 0, 0, region, ShapeSet); XDestroyRegion(region); } } void OS_X11::set_video_mode(const VideoMode &p_video_mode, int p_screen) { } OS::VideoMode OS_X11::get_video_mode(int p_screen) const { return current_videomode; } void OS_X11::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const { } void OS_X11::set_wm_fullscreen(bool p_enabled) { if (p_enabled && !get_borderless_window()) { // remove decorations if the window is not already borderless Hints hints; Atom property; hints.flags = 2; hints.decorations = 0; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } if (p_enabled && !is_window_resizable()) { // Set the window as resizable to prevent window managers to ignore the fullscreen state flag. XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); } // Using EWMH -- Extended Window Manager Hints XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.xclient.data.l[1] = wm_fullscreen; xev.xclient.data.l[2] = 0; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); // set bypass compositor hint Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False); unsigned long compositing_disable_on = p_enabled ? 1 : 0; if (bypass_compositor != None) { XChangeProperty(x11_display, x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1); } XFlush(x11_display); if (!p_enabled) { // Reset the non-resizable flags if we un-set these before. Size2 size = get_window_size(); XSizeHints *xsh; xsh = XAllocSizeHints(); if (!is_window_resizable()) { xsh->flags = PMinSize | PMaxSize; xsh->min_width = size.x; xsh->max_width = size.x; xsh->min_height = size.y; xsh->max_height = size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); // put back or remove decorations according to the last set borderless state Hints hints; Atom property; hints.flags = 2; hints.decorations = current_videomode.borderless_window ? 0 : 1; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } } void OS_X11::set_wm_above(bool p_enabled) { Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False); XClientMessageEvent xev; memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.window = x11_window; xev.message_type = wm_state; xev.format = 32; xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.data.l[1] = wm_above; xev.data.l[3] = 1; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev); } int OS_X11::get_screen_count() const { // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) { return 0; } int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); XFree(xsi); return count; } int OS_X11::get_current_screen() const { int x, y; Window child; XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child); int count = get_screen_count(); for (int i = 0; i < count; i++) { Point2i pos = get_screen_position(i); Size2i size = get_screen_size(i); if ((x >= pos.x && x < pos.x + size.width) && (y >= pos.y && y < pos.y + size.height)) { return i; } } return 0; } void OS_X11::set_current_screen(int p_screen) { if (p_screen == -1) { p_screen = get_current_screen(); } // Check if screen is valid ERR_FAIL_INDEX(p_screen, get_screen_count()); if (current_videomode.fullscreen) { Point2i position = get_screen_position(p_screen); Size2i size = get_screen_size(p_screen); XMoveResizeWindow(x11_display, x11_window, position.x, position.y, size.x, size.y); } else { if (p_screen != get_current_screen()) { Point2i position = get_screen_position(p_screen); XMoveWindow(x11_display, x11_window, position.x, position.y); } } } Point2 OS_X11::get_screen_position(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) { return Point2i(0, 0); } int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); // Check if screen is valid ERR_FAIL_INDEX_V(p_screen, count, Point2i(0, 0)); Point2i position = Point2i(xsi[p_screen].x_org, xsi[p_screen].y_org); XFree(xsi); return position; } Size2 OS_X11::get_screen_size(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) { return Size2i(0, 0); } int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); // Check if screen is valid ERR_FAIL_INDEX_V(p_screen, count, Size2i(0, 0)); Size2i size = Point2i(xsi[p_screen].width, xsi[p_screen].height); XFree(xsi); return size; } int OS_X11::get_screen_dpi(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } //invalid screen? ERR_FAIL_INDEX_V(p_screen, get_screen_count(), 0); //Get physical monitor Dimensions through XRandR and calculate dpi Size2 sc = get_screen_size(p_screen); if (xrandr_ext_ok) { int count = 0; if (xrr_get_monitors) { xrr_monitor_info *monitors = xrr_get_monitors(x11_display, x11_window, true, &count); if (p_screen < count) { double xdpi = sc.width / (double)monitors[p_screen].mwidth * 25.4; double ydpi = sc.height / (double)monitors[p_screen].mheight * 25.4; xrr_free_monitors(monitors); return (xdpi + ydpi) / 2; } xrr_free_monitors(monitors); } else if (p_screen == 0) { XRRScreenSize *sizes = XRRSizes(x11_display, 0, &count); if (sizes) { double xdpi = sc.width / (double)sizes[0].mwidth * 25.4; double ydpi = sc.height / (double)sizes[0].mheight * 25.4; return (xdpi + ydpi) / 2; } } } int width_mm = DisplayWidthMM(x11_display, p_screen); int height_mm = DisplayHeightMM(x11_display, p_screen); double xdpi = (width_mm ? sc.width / (double)width_mm * 25.4 : 0); double ydpi = (height_mm ? sc.height / (double)height_mm * 25.4 : 0); if (xdpi || ydpi) { return (xdpi + ydpi) / (xdpi && ydpi ? 2 : 1); } //could not get dpi return 96; } Point2 OS_X11::get_window_position() const { int x, y; Window child; XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child); return Point2i(x, y); } void OS_X11::set_window_position(const Point2 &p_position) { int x = 0; int y = 0; if (!get_borderless_window()) { //exclude window decorations XSync(x11_display, False); Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (format == 32 && len == 4) { long *extents = (long *)data; x = extents[0]; y = extents[2]; } XFree(data); } } } XMoveWindow(x11_display, x11_window, p_position.x - x, p_position.y - y); update_real_mouse_position(); } Size2 OS_X11::get_window_size() const { // Use current_videomode width and height instead of XGetWindowAttributes // since right after a XResizeWindow the attributes may not be updated yet return Size2i(current_videomode.width, current_videomode.height); } Size2 OS_X11::get_real_window_size() const { XWindowAttributes xwa; XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); int w = xwa.width; int h = xwa.height; Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (format == 32 && len == 4) { long *extents = (long *)data; w += extents[0] + extents[1]; // left, right h += extents[2] + extents[3]; // top, bottom } XFree(data); } } return Size2(w, h); } Size2 OS_X11::get_max_window_size() const { return max_size; } Size2 OS_X11::get_min_window_size() const { return min_size; } void OS_X11::set_min_window_size(const Size2 p_size) { if ((p_size != Size2()) && (max_size != Size2()) && ((p_size.x > max_size.x) || (p_size.y > max_size.y))) { ERR_PRINT("Minimum window size can't be larger than maximum window size!"); return; } min_size = p_size; if (is_window_resizable()) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); XFlush(x11_display); } } void OS_X11::set_max_window_size(const Size2 p_size) { if ((p_size != Size2()) && ((p_size.x < min_size.x) || (p_size.y < min_size.y))) { ERR_PRINT("Maximum window size can't be smaller than minimum window size!"); return; } max_size = p_size; if (is_window_resizable()) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); XFlush(x11_display); } } void OS_X11::set_window_size(const Size2 p_size) { if (current_videomode.width == p_size.width && current_videomode.height == p_size.height) { return; } XWindowAttributes xwa; XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); int old_w = xwa.width; int old_h = xwa.height; Size2 size = p_size; size.x = MAX(1, size.x); size.y = MAX(1, size.y); // If window resizable is disabled we need to update the attributes first XSizeHints *xsh; xsh = XAllocSizeHints(); if (!is_window_resizable()) { xsh->flags = PMinSize | PMaxSize; xsh->min_width = size.x; xsh->max_width = size.x; xsh->min_height = size.y; xsh->max_height = size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); // Resize the window XResizeWindow(x11_display, x11_window, size.x, size.y); // Update our videomode width and height current_videomode.width = size.x; current_videomode.height = size.y; for (int timeout = 0; timeout < 50; ++timeout) { XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); if (old_w != xwa.width || old_h != xwa.height) { break; } usleep(10000); } } void OS_X11::set_window_fullscreen(bool p_enabled) { if (current_videomode.fullscreen == p_enabled) { return; } if (layered_window) { set_window_per_pixel_transparency_enabled(false); } if (p_enabled && current_videomode.always_on_top) { // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity) set_window_maximized(true); } set_wm_fullscreen(p_enabled); if (!p_enabled && current_videomode.always_on_top) { // Restore set_window_maximized(false); } if (!p_enabled) { set_window_position(last_position_before_fs); } else { last_position_before_fs = get_window_position(); } current_videomode.fullscreen = p_enabled; } bool OS_X11::is_window_fullscreen() const { return current_videomode.fullscreen; } void OS_X11::set_window_resizable(bool p_enabled) { XSizeHints *xsh; xsh = XAllocSizeHints(); if (!p_enabled) { Size2 size = get_window_size(); xsh->flags = PMinSize | PMaxSize; xsh->min_width = size.x; xsh->max_width = size.x; xsh->min_height = size.y; xsh->max_height = size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); current_videomode.resizable = p_enabled; XFlush(x11_display); } bool OS_X11::is_window_resizable() const { return current_videomode.resizable; } void OS_X11::set_window_minimized(bool p_enabled) { if (is_no_window_mode_enabled()) { return; } // Using ICCCM -- Inter-Client Communication Conventions Manual XEvent xev; Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_change; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? WM_IconicState : WM_NormalState; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = _NET_WM_STATE_ADD; xev.xclient.data.l[1] = wm_hidden; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); } bool OS_X11::is_window_minimized() const { // Using ICCCM -- Inter-Client Communication Conventions Manual Atom property = XInternAtom(x11_display, "WM_STATE", True); if (property == None) { return false; } Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; bool retval = false; int result = XGetWindowProperty( x11_display, x11_window, property, 0, 32, False, AnyPropertyType, &type, &format, &len, &remaining, &data); if (result == Success) { long *state = (long *)data; if (state[0] == WM_IconicState) { retval = true; } XFree(data); } return retval; } void OS_X11::set_window_maximized(bool p_enabled) { if (is_no_window_mode_enabled()) { return; } if (is_window_maximized() == p_enabled) { return; } // Using EWMH -- Extended Window Manager Hints XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False); Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.xclient.data.l[1] = wm_max_horz; xev.xclient.data.l[2] = wm_max_vert; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); if (p_enabled && is_window_maximize_allowed()) { // Wait for effective resizing (so the GLX context is too). // Give up after 0.5s, it's not going to happen on this WM. // https://github.com/godotengine/godot/issues/19978 for (int attempt = 0; !is_window_maximized() && attempt < 50; attempt++) { usleep(10000); } } maximized = p_enabled; } // Just a helper to reduce code duplication in `is_window_maximize_allowed` // and `is_window_maximized`. bool OS_X11::window_maximize_check(const char *p_atom_name) const { Atom property = XInternAtom(x11_display, p_atom_name, False); Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; bool retval = false; if (property == None) { return false; } int result = XGetWindowProperty( x11_display, x11_window, property, 0, 1024, False, XA_ATOM, &type, &format, &len, &remaining, &data); if (result == Success) { Atom *atoms = (Atom *)data; Atom wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False); Atom wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_VERT", False); bool found_wm_act_max_horz = false; bool found_wm_act_max_vert = false; for (uint64_t i = 0; i < len; i++) { if (atoms[i] == wm_act_max_horz) { found_wm_act_max_horz = true; } if (atoms[i] == wm_act_max_vert) { found_wm_act_max_vert = true; } if (found_wm_act_max_horz || found_wm_act_max_vert) { retval = true; break; } } XFree(data); } return retval; } bool OS_X11::is_window_maximize_allowed() const { return window_maximize_check("_NET_WM_ALLOWED_ACTIONS"); } bool OS_X11::is_window_maximized() const { // Using EWMH -- Extended Window Manager Hints return window_maximize_check("_NET_WM_STATE"); } void OS_X11::set_window_always_on_top(bool p_enabled) { if (is_window_always_on_top() == p_enabled) { return; } if (p_enabled && current_videomode.fullscreen) { // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity) set_window_maximized(true); } set_wm_above(p_enabled); if (!p_enabled && !current_videomode.fullscreen) { // Restore set_window_maximized(false); } current_videomode.always_on_top = p_enabled; } bool OS_X11::is_window_always_on_top() const { return current_videomode.always_on_top; } bool OS_X11::is_window_focused() const { return window_focused; } void OS_X11::set_borderless_window(bool p_borderless) { if (get_borderless_window() == p_borderless) { return; } current_videomode.borderless_window = p_borderless; Hints hints; Atom property; hints.flags = 2; hints.decorations = current_videomode.borderless_window ? 0 : 1; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } // Preserve window size set_window_size(Size2(current_videomode.width, current_videomode.height)); } bool OS_X11::get_borderless_window() { bool borderless = current_videomode.borderless_window; Atom prop = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (data && (format == 32) && (len >= 5)) { borderless = !((Hints *)data)->decorations; } XFree(data); } } return borderless; } void OS_X11::request_attention() { // Using EWMH -- Extended Window Manager Hints // // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE // Will be unset by the window manager after user react on the request for attention XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = _NET_WM_STATE_ADD; xev.xclient.data.l[1] = wm_attention; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(x11_display); } void *OS_X11::get_native_handle(int p_handle_type) { switch (p_handle_type) { case APPLICATION_HANDLE: return nullptr; // Do we have a value to return here? case DISPLAY_HANDLE: return (void *)x11_display; case WINDOW_HANDLE: return (void *)x11_window; case WINDOW_VIEW: return nullptr; // Do we have a value to return here? case OPENGL_CONTEXT: return context_gl->get_glx_context(); default: return nullptr; } } void OS_X11::get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) { state->set_shift((p_x11_state & ShiftMask)); state->set_control((p_x11_state & ControlMask)); state->set_alt((p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/)); //altgr should not count as alt state->set_metakey((p_x11_state & Mod4Mask)); } unsigned int OS_X11::get_mouse_button_state(unsigned int p_x11_button, int p_x11_type) { unsigned int mask = 1 << (p_x11_button - 1); if (p_x11_type == ButtonPress) { last_button_state |= mask; } else { last_button_state &= ~mask; } return last_button_state; } void OS_X11::_handle_key_event(XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo) { // X11 functions don't know what const is XKeyEvent *xkeyevent = p_event; // This code was pretty difficult to write. // The docs stink and every toolkit seems to // do it in a different way. /* Phase 1, obtain a proper keysym */ // This was also very difficult to figure out. // You'd expect you could just use Keysym provided by // XKeycodeToKeysym to obtain internationalized // input.. WRONG!! // you must use XLookupString (???) which not only wastes // cycles generating an unnecessary string, but also // still works in half the cases. (won't handle deadkeys) // For more complex input methods (deadkeys and more advanced) // you have to use XmbLookupString (??). // So.. then you have to chosse which of both results // you want to keep. // This is a real bizarreness and cpu waster. KeySym keysym_keycode = 0; // keysym used to find a keycode KeySym keysym_unicode = 0; // keysym used to find unicode // XLookupString returns keysyms usable as nice scancodes/ char str[256 + 1]; XKeyEvent xkeyevent_no_mod = *xkeyevent; xkeyevent_no_mod.state &= ~ShiftMask; xkeyevent_no_mod.state &= ~ControlMask; XLookupString(xkeyevent, str, 256, &keysym_unicode, nullptr); XLookupString(&xkeyevent_no_mod, nullptr, 0, &keysym_keycode, nullptr); // Meanwhile, XLookupString returns keysyms useful for unicode. if (!xmbstring) { // keep a temporary buffer for the string xmbstring = (char *)memalloc(sizeof(char) * 8); xmblen = 8; } if (xkeyevent->type == KeyPress && xic) { Status status; #ifdef X_HAVE_UTF8_STRING int utf8len = 8; char *utf8string = (char *)memalloc(sizeof(char) * utf8len); int utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string, utf8len - 1, &keysym_unicode, &status); if (status == XBufferOverflow) { utf8len = utf8bytes + 1; utf8string = (char *)memrealloc(utf8string, utf8len); utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string, utf8len - 1, &keysym_unicode, &status); } utf8string[utf8bytes] = '\0'; if (status == XLookupChars) { bool keypress = xkeyevent->type == KeyPress; unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode); unsigned int physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode); if (keycode >= 'a' && keycode <= 'z') { keycode -= 'a' - 'A'; } String tmp; tmp.parse_utf8(utf8string, utf8bytes); for (int i = 0; i < tmp.length(); i++) { Ref<InputEventKey> k; k.instance(); if (physical_keycode == 0 && keycode == 0 && tmp[i] == 0) { continue; } if (keycode == 0) { keycode = physical_keycode; } get_key_modifier_state(xkeyevent->state, k); k->set_unicode(tmp[i]); k->set_pressed(keypress); k->set_scancode(keycode); k->set_physical_scancode(physical_keycode); k->set_echo(false); if (k->get_scancode() == KEY_BACKTAB) { //make it consistent across platforms. k->set_scancode(KEY_TAB); k->set_physical_scancode(KEY_TAB); k->set_shift(true); } input->parse_input_event(k); } memfree(utf8string); return; } memfree(utf8string); #else do { int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status); xmbstring[mnbytes] = '\0'; if (status == XBufferOverflow) { xmblen = mnbytes + 1; xmbstring = (char *)memrealloc(xmbstring, xmblen); } } while (status == XBufferOverflow); #endif } /* Phase 2, obtain a pigui keycode from the keysym */ // KeyMappingX11 just translated the X11 keysym to a PIGUI // keysym, so it works in all platforms the same. unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode); unsigned int physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode); /* Phase 3, obtain a unicode character from the keysym */ // KeyMappingX11 also translates keysym to unicode. // It does a binary search on a table to translate // most properly. unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0; /* Phase 4, determine if event must be filtered */ // This seems to be a side-effect of using XIM. // XFilterEvent looks like a core X11 function, // but it's actually just used to see if we must // ignore a deadkey, or events XIM determines // must not reach the actual gui. // Guess it was a design problem of the extension bool keypress = xkeyevent->type == KeyPress; if (physical_keycode == 0 && keycode == 0 && unicode == 0) { return; } if (keycode == 0) { keycode = physical_keycode; } /* Phase 5, determine modifier mask */ // No problems here, except I had no way to // know Mod1 was ALT and Mod4 was META (applekey/winkey) // just tried Mods until i found them. //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask)); Ref<InputEventKey> k; k.instance(); get_key_modifier_state(xkeyevent->state, k); /* Phase 6, determine echo character */ // Echo characters in X11 are a keyrelease and a keypress // one after the other with the (almot) same timestamp. // To detect them, i compare to the next event in list and // check that their difference in time is below a threshold. if (xkeyevent->type != KeyPress) { p_echo = false; // make sure there are events pending, // so this call won't block. if (p_event_index + 1 < p_events.size()) { XEvent &peek_event = p_events[p_event_index + 1]; // I'm using a threshold of 5 msecs, // since sometimes there seems to be a little // jitter. I'm still not convinced that all this approach // is correct, but the xorg developers are // not very helpful today. ::Time tresh = ABSDIFF(peek_event.xkey.time, xkeyevent->time); if (peek_event.type == KeyPress && tresh < 5) { KeySym rk; XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, nullptr); if (rk == keysym_keycode) { // Consume to next event. ++p_event_index; _handle_key_event((XKeyEvent *)&peek_event, p_events, p_event_index, true); return; //ignore current, echo next } } // use the time from peek_event so it always works } // save the time to check for echo when keypress happens } /* Phase 7, send event to Window */ k->set_pressed(keypress); if (keycode >= 'a' && keycode <= 'z') { keycode -= 'a' - 'A'; } k->set_scancode(keycode); k->set_physical_scancode(physical_keycode); k->set_unicode(unicode); k->set_echo(p_echo); if (k->get_scancode() == KEY_BACKTAB) { //make it consistent across platforms. k->set_scancode(KEY_TAB); k->set_physical_scancode(KEY_TAB); k->set_shift(true); } //don't set mod state if modifier keys are released by themselves //else event.is_action() will not work correctly here if (!k->is_pressed()) { if (k->get_scancode() == KEY_SHIFT) { k->set_shift(false); } else if (k->get_scancode() == KEY_CONTROL) { k->set_control(false); } else if (k->get_scancode() == KEY_ALT) { k->set_alt(false); } else if (k->get_scancode() == KEY_META) { k->set_metakey(false); } } bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_scancode()); if (k->is_pressed()) { if (last_is_pressed) { k->set_echo(true); } } //printf("key: %x\n",k->get_scancode()); input->parse_input_event(k); } Atom OS_X11::_process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property) const { if (p_target == XInternAtom(x11_display, "TARGETS", 0)) { // Request to list all supported targets. Atom data[9]; data[0] = XInternAtom(x11_display, "TARGETS", 0); data[1] = XInternAtom(x11_display, "SAVE_TARGETS", 0); data[2] = XInternAtom(x11_display, "MULTIPLE", 0); data[3] = XInternAtom(x11_display, "UTF8_STRING", 0); data[4] = XInternAtom(x11_display, "COMPOUND_TEXT", 0); data[5] = XInternAtom(x11_display, "TEXT", 0); data[6] = XA_STRING; data[7] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0); data[8] = XInternAtom(x11_display, "text/plain", 0); XChangeProperty(x11_display, p_requestor, p_property, XA_ATOM, 32, PropModeReplace, (unsigned char *)&data, sizeof(data) / sizeof(data[0])); return p_property; } else if (p_target == XInternAtom(x11_display, "SAVE_TARGETS", 0)) { // Request to check if SAVE_TARGETS is supported, nothing special to do. XChangeProperty(x11_display, p_requestor, p_property, XInternAtom(x11_display, "NULL", False), 32, PropModeReplace, nullptr, 0); return p_property; } else if (p_target == XInternAtom(x11_display, "UTF8_STRING", 0) || p_target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) || p_target == XInternAtom(x11_display, "TEXT", 0) || p_target == XA_STRING || p_target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) || p_target == XInternAtom(x11_display, "text/plain", 0)) { // Directly using internal clipboard because we know our window // is the owner during a selection request. CharString clip = OS::get_clipboard().utf8(); XChangeProperty(x11_display, p_requestor, p_property, p_target, 8, PropModeReplace, (unsigned char *)clip.get_data(), clip.length()); return p_property; } else { char *target_name = XGetAtomName(x11_display, p_target); printf("Target '%s' not supported.\n", target_name); if (target_name) { XFree(target_name); } return None; } } void OS_X11::_handle_selection_request_event(XSelectionRequestEvent *p_event) const { XEvent respond; if (p_event->target == XInternAtom(x11_display, "MULTIPLE", 0)) { // Request for multiple target conversions at once. Atom atom_pair = XInternAtom(x11_display, "ATOM_PAIR", False); respond.xselection.property = None; Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, p_event->requestor, p_event->property, 0, LONG_MAX, False, atom_pair, &type, &format, &len, &remaining, &data) == Success) { if ((len >= 2) && data) { Atom *targets = (Atom *)data; for (uint64_t i = 0; i < len; i += 2) { Atom target = targets[i]; Atom &property = targets[i + 1]; property = _process_selection_request_target(target, p_event->requestor, property); } XChangeProperty(x11_display, p_event->requestor, p_event->property, atom_pair, 32, PropModeReplace, (unsigned char *)targets, len); respond.xselection.property = p_event->property; } XFree(data); } } else { // Request for target conversion. respond.xselection.property = _process_selection_request_target(p_event->target, p_event->requestor, p_event->property); } respond.xselection.type = SelectionNotify; respond.xselection.display = p_event->display; respond.xselection.requestor = p_event->requestor; respond.xselection.selection = p_event->selection; respond.xselection.target = p_event->target; respond.xselection.time = p_event->time; XSendEvent(x11_display, p_event->requestor, True, NoEventMask, &respond); XFlush(x11_display); } struct Property { unsigned char *data; int format, nitems; Atom type; }; static Property read_property(Display *p_display, Window p_window, Atom p_property) { Atom actual_type = None; int actual_format = 0; unsigned long nitems = 0; unsigned long bytes_after = 0; unsigned char *ret = nullptr; int read_bytes = 1024; //Keep trying to read the property until there are no //bytes unread. if (p_property != None) { do { if (ret != nullptr) { XFree(ret); } XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType, &actual_type, &actual_format, &nitems, &bytes_after, &ret); read_bytes *= 2; } while (bytes_after != 0); } Property p = { ret, actual_format, (int)nitems, actual_type }; return p; } static Atom pick_target_from_list(Display *p_display, Atom *p_list, int p_count) { static const char *target_type = "text/uri-list"; for (int i = 0; i < p_count; i++) { Atom atom = p_list[i]; if (atom != None && String(XGetAtomName(p_display, atom)) == target_type) { return atom; } } return None; } static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) { static const char *target_type = "text/uri-list"; if (p_t1 != None && String(XGetAtomName(p_disp, p_t1)) == target_type) { return p_t1; } if (p_t2 != None && String(XGetAtomName(p_disp, p_t2)) == target_type) { return p_t2; } if (p_t3 != None && String(XGetAtomName(p_disp, p_t3)) == target_type) { return p_t3; } return None; } void OS_X11::_window_changed(XEvent *event) { if (xic) { // Not portable. set_ime_position(Point2(0, 1)); } if ((event->xconfigure.width == current_videomode.width) && (event->xconfigure.height == current_videomode.height)) { return; } current_videomode.width = event->xconfigure.width; current_videomode.height = event->xconfigure.height; } void OS_X11::_poll_events_thread(void *ud) { OS_X11 *os = (OS_X11 *)ud; os->_poll_events(); } Bool OS_X11::_predicate_all_events(Display *display, XEvent *event, XPointer arg) { // Just accept all events. return True; } bool OS_X11::_wait_for_events() const { int x11_fd = ConnectionNumber(x11_display); fd_set in_fds; XFlush(x11_display); FD_ZERO(&in_fds); FD_SET(x11_fd, &in_fds); struct timeval tv; tv.tv_usec = 0; tv.tv_sec = 1; // Wait for next event or timeout. int num_ready_fds = select(x11_fd + 1, &in_fds, nullptr, nullptr, &tv); if (num_ready_fds > 0) { // Event received. return true; } else { // Error or timeout. if (num_ready_fds < 0) { ERR_PRINT("_wait_for_events: select error: " + itos(errno)); } return false; } } void OS_X11::_poll_events() { while (!events_thread_done) { _wait_for_events(); // Process events from the queue. { MutexLock mutex_lock(events_mutex); // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_all_events, nullptr)) { // Check if the input manager wants to process the event. if (XFilterEvent(&ev, None)) { // Event has been filtered by the Input Manager, // it has to be ignored and a new one will be received. continue; } // Handle selection request events directly in the event thread, because // communication through the x server takes several events sent back and forth // and we don't want to block other programs while processing only one each frame. if (ev.type == SelectionRequest) { _handle_selection_request_event(&(ev.xselectionrequest)); continue; } polled_events.push_back(ev); } } } } void OS_X11::process_xevents() { //printf("checking events %i\n", XPending(x11_display)); do_mouse_warp = false; // Is the current mouse mode one where it needs to be grabbed. bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED; xi.pressure = 0; xi.tilt = Vector2(); xi.pressure_supported = false; LocalVector<XEvent> events; { // Block events polling while flushing events. MutexLock mutex_lock(events_mutex); events = polled_events; polled_events.clear(); } for (uint32_t event_index = 0; event_index < events.size(); ++event_index) { XEvent &event = events[event_index]; if (XGetEventData(x11_display, &event.xcookie)) { if (event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) { XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data; int index = event_data->detail; Vector2 pos = Vector2(event_data->event_x, event_data->event_y); switch (event_data->evtype) { case XI_HierarchyChanged: case XI_DeviceChanged: { refresh_device_info(); } break; case XI_RawMotion: { XIRawEvent *raw_event = (XIRawEvent *)event_data; int device_id = raw_event->deviceid; // Determine the axis used (called valuators in XInput for some forsaken reason) // Mask is a bitmask indicating which axes are involved. // We are interested in the values of axes 0 and 1. if (raw_event->valuators.mask_len <= 0) { break; } const double *values = raw_event->raw_values; double rel_x = 0.0; double rel_y = 0.0; if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSX)) { rel_x = *values; values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSY)) { rel_y = *values; values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_PRESSURE)) { Map<int, Vector2>::Element *pen_pressure = xi.pen_pressure_range.find(device_id); if (pen_pressure) { Vector2 pen_pressure_range = pen_pressure->value(); if (pen_pressure_range != Vector2()) { xi.pressure_supported = true; xi.pressure = (*values - pen_pressure_range[0]) / (pen_pressure_range[1] - pen_pressure_range[0]); } } values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTX)) { Map<int, Vector2>::Element *pen_tilt_x = xi.pen_tilt_x_range.find(device_id); if (pen_tilt_x) { Vector2 pen_tilt_x_range = pen_tilt_x->value(); if (pen_tilt_x_range != Vector2()) { xi.tilt.x = ((*values - pen_tilt_x_range[0]) / (pen_tilt_x_range[1] - pen_tilt_x_range[0])) * 2 - 1; } } values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTY)) { Map<int, Vector2>::Element *pen_tilt_y = xi.pen_tilt_y_range.find(device_id); if (pen_tilt_y) { Vector2 pen_tilt_y_range = pen_tilt_y->value(); if (pen_tilt_y_range != Vector2()) { xi.tilt.y = ((*values - pen_tilt_y_range[0]) / (pen_tilt_y_range[1] - pen_tilt_y_range[0])) * 2 - 1; } } values++; } // https://bugs.freedesktop.org/show_bug.cgi?id=71609 // http://lists.libsdl.org/pipermail/commits-libsdl.org/2015-June/000282.html if (raw_event->time == xi.last_relative_time && rel_x == xi.relative_motion.x && rel_y == xi.relative_motion.y) { break; // Flush duplicate to avoid overly fast motion } xi.old_raw_pos.x = xi.raw_pos.x; xi.old_raw_pos.y = xi.raw_pos.y; xi.raw_pos.x = rel_x; xi.raw_pos.y = rel_y; Map<int, Vector2>::Element *abs_info = xi.absolute_devices.find(device_id); if (abs_info) { // Absolute mode device Vector2 mult = abs_info->value(); xi.relative_motion.x += (xi.raw_pos.x - xi.old_raw_pos.x) * mult.x; xi.relative_motion.y += (xi.raw_pos.y - xi.old_raw_pos.y) * mult.y; } else { // Relative mode device xi.relative_motion.x = xi.raw_pos.x; xi.relative_motion.y = xi.raw_pos.y; } xi.last_relative_time = raw_event->time; } break; #ifdef TOUCH_ENABLED case XI_TouchBegin: // Fall-through // Disabled hand-in-hand with the grabbing //XIAllowTouchEvents(x11_display, event_data->deviceid, event_data->detail, x11_window, XIAcceptTouch); case XI_TouchEnd: { bool is_begin = event_data->evtype == XI_TouchBegin; Ref<InputEventScreenTouch> st; st.instance(); st->set_index(index); st->set_position(pos); st->set_pressed(is_begin); if (is_begin) { if (xi.state.has(index)) { // Defensive break; } xi.state[index] = pos; if (xi.state.size() == 1) { // X11 may send a motion event when a touch gesture begins, that would result // in a spurious mouse motion event being sent to Godot; remember it to be able to filter it out xi.mouse_pos_to_filter = pos; } input->parse_input_event(st); } else { if (!xi.state.has(index)) { // Defensive break; } xi.state.erase(index); input->parse_input_event(st); } } break; case XI_TouchUpdate: { Map<int, Vector2>::Element *curr_pos_elem = xi.state.find(index); if (!curr_pos_elem) { // Defensive break; } if (curr_pos_elem->value() != pos) { Ref<InputEventScreenDrag> sd; sd.instance(); sd->set_index(index); sd->set_position(pos); sd->set_relative(pos - curr_pos_elem->value()); input->parse_input_event(sd); curr_pos_elem->value() = pos; } } break; #endif } } } XFreeEventData(x11_display, &event.xcookie); switch (event.type) { case Expose: Main::force_redraw(); break; case NoExpose: minimized = true; break; case VisibilityNotify: { XVisibilityEvent *visibility = (XVisibilityEvent *)&event; minimized = (visibility->state == VisibilityFullyObscured); } break; case LeaveNotify: { if (main_loop && !mouse_mode_grab) { main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT); } } break; case EnterNotify: { if (main_loop && !mouse_mode_grab) { main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER); } } break; case FocusIn: minimized = false; window_has_focus = true; main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); window_focused = true; if (mouse_mode_grab) { // Show and update the cursor if confined and the window regained focus. if (mouse_mode == MOUSE_MODE_CONFINED) { XUndefineCursor(x11_display, x11_window); } else if (mouse_mode == MOUSE_MODE_CAPTURED) { // or re-hide it in captured mode XDefineCursor(x11_display, x11_window, null_cursor); } XGrabPointer( x11_display, x11_window, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime); } #ifdef TOUCH_ENABLED // Grab touch devices to avoid OS gesture interference /*for (int i = 0; i < xi.touch_devices.size(); ++i) { XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask); }*/ #endif if (xic) { // Block events polling while changing input focus // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XSetICFocus(xic); } break; case FocusOut: window_has_focus = false; input->release_pressed_events(); main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); window_focused = false; if (mouse_mode_grab) { //dear X11, I try, I really try, but you never work, you do whathever you want. if (mouse_mode == MOUSE_MODE_CAPTURED) { // Show the cursor if we're in captured mode so it doesn't look weird. XUndefineCursor(x11_display, x11_window); } XUngrabPointer(x11_display, CurrentTime); } #ifdef TOUCH_ENABLED // Ungrab touch devices so input works as usual while we are unfocused /*for (int i = 0; i < xi.touch_devices.size(); ++i) { XIUngrabDevice(x11_display, xi.touch_devices[i], CurrentTime); }*/ // Release every pointer to avoid sticky points for (Map<int, Vector2>::Element *E = xi.state.front(); E; E = E->next()) { Ref<InputEventScreenTouch> st; st.instance(); st->set_index(E->key()); st->set_position(E->get()); input->parse_input_event(st); } xi.state.clear(); #endif if (xic) { // Block events polling while changing input focus // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XUnsetICFocus(xic); } break; case ConfigureNotify: _window_changed(&event); break; case ButtonPress: case ButtonRelease: { /* exit in case of a mouse button press */ last_timestamp = event.xbutton.time; if (mouse_mode == MOUSE_MODE_CAPTURED) { event.xbutton.x = last_mouse_pos.x; event.xbutton.y = last_mouse_pos.y; } Ref<InputEventMouseButton> mb; mb.instance(); get_key_modifier_state(event.xbutton.state, mb); mb->set_button_index(event.xbutton.button); if (mb->get_button_index() == 2) { mb->set_button_index(3); } else if (mb->get_button_index() == 3) { mb->set_button_index(2); } mb->set_button_mask(get_mouse_button_state(mb->get_button_index(), event.xbutton.type)); mb->set_position(Vector2(event.xbutton.x, event.xbutton.y)); mb->set_global_position(mb->get_position()); mb->set_pressed((event.type == ButtonPress)); if (event.type == ButtonPress) { uint64_t diff = get_ticks_usec() / 1000 - last_click_ms; if (mb->get_button_index() == last_click_button_index) { if (diff < 400 && Point2(last_click_pos).distance_to(Point2(event.xbutton.x, event.xbutton.y)) < 5) { last_click_ms = 0; last_click_pos = Point2(-100, -100); last_click_button_index = -1; mb->set_doubleclick(true); } } else if (mb->get_button_index() < 4 || mb->get_button_index() > 7) { last_click_button_index = mb->get_button_index(); } if (!mb->is_doubleclick()) { last_click_ms += diff; last_click_pos = Point2(event.xbutton.x, event.xbutton.y); } } input->parse_input_event(mb); } break; case MotionNotify: { // The X11 API requires filtering one-by-one through the motion // notify events, in order to figure out which event is the one // generated by warping the mouse pointer. while (true) { if (mouse_mode == MOUSE_MODE_CAPTURED && event.xmotion.x == current_videomode.width / 2 && event.xmotion.y == current_videomode.height / 2) { //this is likely the warp event since it was warped here center = Vector2(event.xmotion.x, event.xmotion.y); break; } if (event_index + 1 < events.size()) { const XEvent &next_event = events[event_index + 1]; if (next_event.type == MotionNotify) { ++event_index; event = next_event; } else { break; } } else { break; } } last_timestamp = event.xmotion.time; // Motion is also simple. // A little hack is in order // to be able to send relative motion events. Point2 pos(event.xmotion.x, event.xmotion.y); // Avoidance of spurious mouse motion (see handling of touch) bool filter = false; // Adding some tolerance to match better Point2i to Vector2 if (xi.state.size() && Vector2(pos).distance_squared_to(xi.mouse_pos_to_filter) < 2) { filter = true; } // Invalidate to avoid filtering a possible legitimate similar event coming later xi.mouse_pos_to_filter = Vector2(1e10, 1e10); if (filter) { break; } if (mouse_mode == MOUSE_MODE_CAPTURED) { if (xi.relative_motion.x == 0 && xi.relative_motion.y == 0) { break; } Point2i new_center = pos; pos = last_mouse_pos + xi.relative_motion; center = new_center; do_mouse_warp = window_has_focus; // warp the cursor if we're focused in } if (!last_mouse_pos_valid) { last_mouse_pos = pos; last_mouse_pos_valid = true; } // Hackish but relative mouse motion is already handled in the RawMotion event. // RawMotion does not provide the absolute mouse position (whereas MotionNotify does). // Therefore, RawMotion cannot be the authority on absolute mouse position. // RawMotion provides more precision than MotionNotify, which doesn't sense subpixel motion. // Therefore, MotionNotify cannot be the authority on relative mouse motion. // This means we need to take a combined approach... Point2 rel; // Only use raw input if in capture mode. Otherwise use the classic behavior. if (mouse_mode == MOUSE_MODE_CAPTURED) { rel = xi.relative_motion; } else { rel = pos - last_mouse_pos; } // Reset to prevent lingering motion xi.relative_motion.x = 0; xi.relative_motion.y = 0; if (mouse_mode == MOUSE_MODE_CAPTURED) { pos = Point2i(current_videomode.width / 2, current_videomode.height / 2); } Ref<InputEventMouseMotion> mm; mm.instance(); if (xi.pressure_supported) { mm->set_pressure(xi.pressure); } else { mm->set_pressure((get_mouse_button_state() & (1 << (BUTTON_LEFT - 1))) ? 1.0f : 0.0f); } mm->set_tilt(xi.tilt); // Make the absolute position integral so it doesn't look _too_ weird :) Point2i posi(pos); get_key_modifier_state(event.xmotion.state, mm); mm->set_button_mask(get_mouse_button_state()); mm->set_position(posi); mm->set_global_position(posi); input->set_mouse_position(posi); mm->set_speed(input->get_last_mouse_speed()); mm->set_relative(rel); last_mouse_pos = pos; // printf("rel: %d,%d\n", rel.x, rel.y ); // Don't propagate the motion event unless we have focus // this is so that the relative motion doesn't get messed up // after we regain focus. if (window_has_focus || !mouse_mode_grab) { input->parse_input_event(mm); } } break; case KeyPress: case KeyRelease: { last_timestamp = event.xkey.time; // key event is a little complex, so // it will be handled in its own function. _handle_key_event((XKeyEvent *)&event, events, event_index); } break; case SelectionNotify: if (event.xselection.target == requested) { Property p = read_property(x11_display, x11_window, XInternAtom(x11_display, "PRIMARY", 0)); Vector<String> files = String((char *)p.data).split("\n", false); for (int i = 0; i < files.size(); i++) { files.write[i] = files[i].replace("file://", "").http_unescape().strip_edges(); } main_loop->drop_files(files); //Reply that all is well. XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = x11_display; m.window = xdnd_source_window; m.message_type = xdnd_finished; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = 1; m.data.l[2] = xdnd_action_copy; //We only ever copy. XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m); } break; case ClientMessage: if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete) { main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST); } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) { //File(s) have been dragged over the window, check for supported target (text/uri-list) xdnd_version = (event.xclient.data.l[1] >> 24); Window source = event.xclient.data.l[0]; bool more_than_3 = event.xclient.data.l[1] & 1; if (more_than_3) { Property p = read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False)); requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems); } else { requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]); } } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) { //xdnd position event, reply with an XDND status message //just depending on type of data for now XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = event.xclient.display; m.window = event.xclient.data.l[0]; m.message_type = xdnd_status; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = (requested != None); m.data.l[2] = 0; //empty rectangle m.data.l[3] = 0; m.data.l[4] = xdnd_action_copy; XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m); XFlush(x11_display); } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) { if (requested != None) { xdnd_source_window = event.xclient.data.l[0]; if (xdnd_version >= 1) { XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, event.xclient.data.l[2]); } else { XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, CurrentTime); } } else { //Reply that we're not interested. XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = event.xclient.display; m.window = event.xclient.data.l[0]; m.message_type = xdnd_finished; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = 0; m.data.l[2] = None; //Failed. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m); } } break; default: break; } } XFlush(x11_display); if (do_mouse_warp) { XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)current_videomode.width / 2, (int)current_videomode.height / 2); /* Window root, child; int root_x, root_y; int win_x, win_y; unsigned int mask; XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask ); printf("Root: %d,%d\n", root_x, root_y); printf("Win: %d,%d\n", win_x, win_y); */ } input->flush_buffered_events(); } MainLoop *OS_X11::get_main_loop() const { return main_loop; } void OS_X11::delete_main_loop() { // Send owned clipboard data to clipboard manager before exit. // This has to be done here because the clipboard data is cleared before finalize(). _clipboard_transfer_ownership(XA_PRIMARY, x11_window); _clipboard_transfer_ownership(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window); if (main_loop) { memdelete(main_loop); } main_loop = nullptr; } void OS_X11::set_main_loop(MainLoop *p_main_loop) { main_loop = p_main_loop; input->set_main_loop(p_main_loop); } bool OS_X11::can_draw() const { return !minimized; }; void OS_X11::set_clipboard(const String &p_text) { { // The clipboard content can be accessed while polling for events. MutexLock mutex_lock(events_mutex); OS::set_clipboard(p_text); } XSetSelectionOwner(x11_display, XA_PRIMARY, x11_window, CurrentTime); XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), x11_window, CurrentTime); }; Bool OS_X11::_predicate_clipboard_selection(Display *display, XEvent *event, XPointer arg) { if (event->type == SelectionNotify && event->xselection.requestor == *(Window *)arg) { return True; } else { return False; } } Bool OS_X11::_predicate_clipboard_incr(Display *display, XEvent *event, XPointer arg) { if (event->type == PropertyNotify && event->xproperty.state == PropertyNewValue) { return True; } else { return False; } } String OS_X11::_get_clipboard_impl(Atom p_source, Window x11_window, Atom target) const { String ret; Window selection_owner = XGetSelectionOwner(x11_display, p_source); if (selection_owner == x11_window) { return OS::get_clipboard(); } if (selection_owner != None) { // Block events polling while processing selection events. MutexLock mutex_lock(events_mutex); Atom selection = XA_PRIMARY; XConvertSelection(x11_display, p_source, target, selection, x11_window, CurrentTime); XFlush(x11_display); // Blocking wait for predicate to be True and remove the event from the queue. XEvent event; XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window); // Do not get any data, see how much data is there. Atom type; int format, result; unsigned long len, bytes_left, dummy; unsigned char *data; XGetWindowProperty(x11_display, x11_window, selection, // Tricky.. 0, 0, // offset - len 0, // Delete 0==FALSE AnyPropertyType, // flag &type, // return type &format, // return format &len, &bytes_left, // data length &data); if (data) { XFree(data); } if (type == XInternAtom(x11_display, "INCR", 0)) { // Data is going to be received incrementally. LocalVector<uint8_t> incr_data; uint32_t data_size = 0; bool success = false; // Delete INCR property to notify the owner. XDeleteProperty(x11_display, x11_window, type); // Process events from the queue. bool done = false; while (!done) { if (!_wait_for_events()) { // Error or timeout, abort. break; } // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, nullptr)) { result = XGetWindowProperty(x11_display, x11_window, selection, // selection type 0, LONG_MAX, // offset - len True, // delete property to notify the owner AnyPropertyType, // flag &type, // return type &format, // return format &len, &bytes_left, // data length &data); if (result == Success) { if (data && (len > 0)) { uint32_t prev_size = incr_data.size(); if (prev_size == 0) { // First property contains initial data size. unsigned long initial_size = *(unsigned long *)data; incr_data.resize(initial_size); } else { // New chunk, resize to be safe and append data. incr_data.resize(MAX(data_size + len, prev_size)); memcpy(incr_data.ptr() + data_size, data, len); data_size += len; } } else { // Last chunk, process finished. done = true; success = true; } } else { printf("Failed to get selection data chunk.\n"); done = true; } if (data) { XFree(data); } if (done) { break; } } } if (success && (data_size > 0)) { ret.parse_utf8((const char *)incr_data.ptr(), data_size); } } else if (bytes_left > 0) { // Data is ready and can be processed all at once. result = XGetWindowProperty(x11_display, x11_window, selection, 0, bytes_left, 0, AnyPropertyType, &type, &format, &len, &dummy, &data); if (result == Success) { ret.parse_utf8((const char *)data); } else { printf("Failed to get selection data.\n"); } if (data) { XFree(data); } } } return ret; } String OS_X11::_get_clipboard(Atom p_source, Window x11_window) const { String ret; Atom utf8_atom = XInternAtom(x11_display, "UTF8_STRING", True); if (utf8_atom != None) { ret = _get_clipboard_impl(p_source, x11_window, utf8_atom); } if (ret.empty()) { ret = _get_clipboard_impl(p_source, x11_window, XA_STRING); } return ret; } String OS_X11::get_clipboard() const { String ret; ret = _get_clipboard(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window); if (ret.empty()) { ret = _get_clipboard(XA_PRIMARY, x11_window); }; return ret; } Bool OS_X11::_predicate_clipboard_save_targets(Display *display, XEvent *event, XPointer arg) { if (event->xany.window == *(Window *)arg) { return (event->type == SelectionRequest) || (event->type == SelectionNotify); } else { return False; } } void OS_X11::_clipboard_transfer_ownership(Atom p_source, Window x11_window) const { Window selection_owner = XGetSelectionOwner(x11_display, p_source); if (selection_owner != x11_window) { return; } // Block events polling while processing selection events. MutexLock mutex_lock(events_mutex); Atom clipboard_manager = XInternAtom(x11_display, "CLIPBOARD_MANAGER", False); Atom save_targets = XInternAtom(x11_display, "SAVE_TARGETS", False); XConvertSelection(x11_display, clipboard_manager, save_targets, None, x11_window, CurrentTime); // Process events from the queue. while (true) { if (!_wait_for_events()) { // Error or timeout, abort. break; } // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_save_targets, (XPointer)&x11_window)) { switch (ev.type) { case SelectionRequest: _handle_selection_request_event(&(ev.xselectionrequest)); break; case SelectionNotify: { if (ev.xselection.target == save_targets) { // Once SelectionNotify is received, we're done whether it succeeded or not. return; } break; } } } } } String OS_X11::get_name() const { return "X11"; } Error OS_X11::shell_open(String p_uri) { Error ok; int err_code; List<String> args; args.push_back(p_uri); // Agnostic ok = execute("xdg-open", args, true, nullptr, nullptr, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } // GNOME args.push_front("open"); // The command is `gio open`, so we need to add it to args ok = execute("gio", args, true, nullptr, nullptr, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } args.pop_front(); ok = execute("gvfs-open", args, true, nullptr, nullptr, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } // KDE ok = execute("kde-open5", args, true, nullptr, nullptr, &err_code); if (ok == OK && !err_code) { return OK; } ok = execute("kde-open", args, true, nullptr, nullptr, &err_code); return !err_code ? ok : FAILED; } bool OS_X11::_check_internal_feature_support(const String &p_feature) { return p_feature == "pc"; } String OS_X11::get_config_path() const { if (has_environment("XDG_CONFIG_HOME")) { if (get_environment("XDG_CONFIG_HOME").is_abs_path()) { return get_environment("XDG_CONFIG_HOME"); } else { WARN_PRINT_ONCE("`XDG_CONFIG_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.config` or `.` per the XDG Base Directory specification."); } } if (has_environment("HOME")) { return get_environment("HOME").plus_file(".config"); } return "."; } String OS_X11::get_data_path() const { if (has_environment("XDG_DATA_HOME")) { if (get_environment("XDG_DATA_HOME").is_abs_path()) { return get_environment("XDG_DATA_HOME"); } else { WARN_PRINT_ONCE("`XDG_DATA_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.local/share` or `get_config_path()` per the XDG Base Directory specification."); } } if (has_environment("HOME")) { return get_environment("HOME").plus_file(".local/share"); } return get_config_path(); } String OS_X11::get_cache_path() const { if (has_environment("XDG_CACHE_HOME")) { if (get_environment("XDG_CACHE_HOME").is_abs_path()) { return get_environment("XDG_CACHE_HOME"); } else { WARN_PRINT_ONCE("`XDG_CACHE_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.cache` or `get_config_path()` per the XDG Base Directory specification."); } } if (has_environment("HOME")) { return get_environment("HOME").plus_file(".cache"); } return get_config_path(); } String OS_X11::get_system_dir(SystemDir p_dir, bool p_shared_storage) const { String xdgparam; switch (p_dir) { case SYSTEM_DIR_DESKTOP: { xdgparam = "DESKTOP"; } break; case SYSTEM_DIR_DCIM: { xdgparam = "PICTURES"; } break; case SYSTEM_DIR_DOCUMENTS: { xdgparam = "DOCUMENTS"; } break; case SYSTEM_DIR_DOWNLOADS: { xdgparam = "DOWNLOAD"; } break; case SYSTEM_DIR_MOVIES: { xdgparam = "VIDEOS"; } break; case SYSTEM_DIR_MUSIC: { xdgparam = "MUSIC"; } break; case SYSTEM_DIR_PICTURES: { xdgparam = "PICTURES"; } break; case SYSTEM_DIR_RINGTONES: { xdgparam = "MUSIC"; } break; } String pipe; List<String> arg; arg.push_back(xdgparam); Error err = const_cast<OS_X11 *>(this)->execute("xdg-user-dir", arg, true, nullptr, &pipe); if (err != OK) { return "."; } return pipe.strip_edges(); } void OS_X11::move_window_to_foreground() { XEvent xev; Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = net_active_window; xev.xclient.format = 32; xev.xclient.data.l[0] = 1; xev.xclient.data.l[1] = CurrentTime; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(x11_display); } void OS_X11::set_cursor_shape(CursorShape p_shape) { ERR_FAIL_INDEX(p_shape, CURSOR_MAX); if (p_shape == current_cursor) { return; } if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) { if (cursors[p_shape] != None) { XDefineCursor(x11_display, x11_window, cursors[p_shape]); } else if (cursors[CURSOR_ARROW] != None) { XDefineCursor(x11_display, x11_window, cursors[CURSOR_ARROW]); } } current_cursor = p_shape; } OS::CursorShape OS_X11::get_cursor_shape() const { return current_cursor; } void OS_X11::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) { if (p_cursor.is_valid()) { Map<CursorShape, Vector<Variant>>::Element *cursor_c = cursors_cache.find(p_shape); if (cursor_c) { if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) { set_cursor_shape(p_shape); return; } cursors_cache.erase(p_shape); } Ref<Texture> texture = p_cursor; Ref<AtlasTexture> atlas_texture = p_cursor; Ref<Image> image; Size2 texture_size; Rect2 atlas_rect; if (texture.is_valid()) { image = texture->get_data(); } if (!image.is_valid() && atlas_texture.is_valid()) { texture = atlas_texture->get_atlas(); atlas_rect.size.width = texture->get_width(); atlas_rect.size.height = texture->get_height(); atlas_rect.position.x = atlas_texture->get_region().position.x; atlas_rect.position.y = atlas_texture->get_region().position.y; texture_size.width = atlas_texture->get_region().size.x; texture_size.height = atlas_texture->get_region().size.y; } else if (image.is_valid()) { texture_size.width = texture->get_width(); texture_size.height = texture->get_height(); } ERR_FAIL_COND(!texture.is_valid()); ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0); ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256); ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height); image = texture->get_data(); ERR_FAIL_COND(!image.is_valid()); // Create the cursor structure XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height); XcursorUInt image_size = texture_size.width * texture_size.height; XcursorDim size = sizeof(XcursorPixel) * image_size; cursor_image->version = 1; cursor_image->size = size; cursor_image->xhot = p_hotspot.x; cursor_image->yhot = p_hotspot.y; // allocate memory to contain the whole file cursor_image->pixels = (XcursorPixel *)memalloc(size); image->lock(); for (XcursorPixel index = 0; index < image_size; index++) { int row_index = floor(index / texture_size.width) + atlas_rect.position.y; int column_index = (index % int(texture_size.width)) + atlas_rect.position.x; if (atlas_texture.is_valid()) { column_index = MIN(column_index, atlas_rect.size.width - 1); row_index = MIN(row_index, atlas_rect.size.height - 1); } *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32(); } image->unlock(); ERR_FAIL_COND(cursor_image->pixels == nullptr); // Save it for a further usage cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image); Vector<Variant> params; params.push_back(p_cursor); params.push_back(p_hotspot); cursors_cache.insert(p_shape, params); if (p_shape == current_cursor) { if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) { XDefineCursor(x11_display, x11_window, cursors[p_shape]); } } memfree(cursor_image->pixels); XcursorImageDestroy(cursor_image); } else { // Reset to default system cursor if (img[p_shape]) { cursors[p_shape] = XcursorImageLoadCursor(x11_display, img[p_shape]); } CursorShape c = current_cursor; current_cursor = CURSOR_MAX; set_cursor_shape(c); cursors_cache.erase(p_shape); } } void OS_X11::release_rendering_thread() { #if defined(OPENGL_ENABLED) context_gl->release_current(); #endif } void OS_X11::make_rendering_thread() { #if defined(OPENGL_ENABLED) context_gl->make_current(); #endif } void OS_X11::swap_buffers() { #if defined(OPENGL_ENABLED) context_gl->swap_buffers(); #endif } void OS_X11::alert(const String &p_alert, const String &p_title) { if (is_no_window_mode_enabled()) { print_line("ALERT: " + p_title + ": " + p_alert); return; } const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" }; String path = get_environment("PATH"); Vector<String> path_elems = path.split(":", false); String program; for (int i = 0; i < path_elems.size(); i++) { for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) { String tested_path = path_elems[i].plus_file(message_programs[k]); if (FileAccess::exists(tested_path)) { program = tested_path; break; } } if (program.length()) { break; } } List<String> args; if (program.ends_with("zenity")) { args.push_back("--error"); args.push_back("--width"); args.push_back("500"); args.push_back("--title"); args.push_back(p_title); args.push_back("--text"); args.push_back(p_alert); } if (program.ends_with("kdialog")) { args.push_back("--error"); args.push_back(p_alert); args.push_back("--title"); args.push_back(p_title); } if (program.ends_with("Xdialog")) { args.push_back("--title"); args.push_back(p_title); args.push_back("--msgbox"); args.push_back(p_alert); args.push_back("0"); args.push_back("0"); } if (program.ends_with("xmessage")) { args.push_back("-center"); args.push_back("-title"); args.push_back(p_title); args.push_back(p_alert); } if (program.length()) { execute(program, args, true); } else { print_line(p_alert); } } bool g_set_icon_error = false; int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) { g_set_icon_error = true; return 0; } void OS_X11::set_icon(const Ref<Image> &p_icon) { int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler); Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False); if (p_icon.is_valid()) { Ref<Image> img = p_icon->duplicate(); img->convert(Image::FORMAT_RGBA8); while (true) { int w = img->get_width(); int h = img->get_height(); if (g_set_icon_error) { g_set_icon_error = false; WARN_PRINT("Icon too large, attempting to resize icon."); int new_width, new_height; if (w > h) { new_width = w / 2; new_height = h * new_width / w; } else { new_height = h / 2; new_width = w * new_height / h; } w = new_width; h = new_height; if (!w || !h) { WARN_PRINT("Unable to set icon."); break; } img->resize(w, h, Image::INTERPOLATE_CUBIC); } // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits Vector<long> pd; pd.resize(2 + w * h); pd.write[0] = w; pd.write[1] = h; PoolVector<uint8_t>::Read r = img->get_data().read(); long *wr = &pd.write[2]; uint8_t const *pr = r.ptr(); for (int i = 0; i < w * h; i++) { long v = 0; // A R G B v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2]; *wr++ = v; pr += 4; } if (net_wm_icon != None) { XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size()); } if (!g_set_icon_error) { break; } } } else { XDeleteProperty(x11_display, x11_window, net_wm_icon); } XFlush(x11_display); XSetErrorHandler(oldHandler); } void OS_X11::force_process_input() { process_xevents(); // get rid of pending events #ifdef JOYDEV_ENABLED joypad->process_joypads(); #endif } void OS_X11::run() { force_quit = false; if (!main_loop) { return; } main_loop->init(); //uint64_t last_ticks=get_ticks_usec(); //int frames=0; //uint64_t frame=0; while (!force_quit) { process_xevents(); // get rid of pending events #ifdef JOYDEV_ENABLED joypad->process_joypads(); #endif if (Main::iteration()) { break; } }; main_loop->finish(); } bool OS_X11::is_joy_known(int p_device) { return input->is_joy_mapped(p_device); } String OS_X11::get_joy_guid(int p_device) const { return input->get_joy_guid_remapped(p_device); } void OS_X11::_set_use_vsync(bool p_enable) { #if defined(OPENGL_ENABLED) if (context_gl) { context_gl->set_use_vsync(p_enable); } #endif } /* bool OS_X11::is_vsync_enabled() const { if (context_gl) return context_gl->is_using_vsync(); return true; } */ void OS_X11::set_context(int p_context) { XClassHint *classHint = XAllocClassHint(); if (classHint) { CharString name_str; switch (p_context) { case CONTEXT_EDITOR: name_str = "Godot_Editor"; break; case CONTEXT_PROJECTMAN: name_str = "Godot_ProjectList"; break; case CONTEXT_ENGINE: name_str = "Godot_Engine"; break; } CharString class_str; if (p_context == CONTEXT_ENGINE) { String config_name = GLOBAL_GET("application/config/name"); if (config_name.length() == 0) { class_str = "Godot_Engine"; } else { class_str = config_name.utf8(); } } else { class_str = "Godot"; } classHint->res_class = class_str.ptrw(); classHint->res_name = name_str.ptrw(); XSetClassHint(x11_display, x11_window, classHint); XFree(classHint); } } OS::PowerState OS_X11::get_power_state() { return power_manager->get_power_state(); } int OS_X11::get_power_seconds_left() { return power_manager->get_power_seconds_left(); } int OS_X11::get_power_percent_left() { return power_manager->get_power_percent_left(); } void OS_X11::disable_crash_handler() { crash_handler.disable(); } bool OS_X11::is_disable_crash_handler() const { return crash_handler.is_disabled(); } static String get_mountpoint(const String &p_path) { struct stat s; if (stat(p_path.utf8().get_data(), &s)) { return ""; } #ifdef HAVE_MNTENT dev_t dev = s.st_dev; FILE *fd = setmntent("/proc/mounts", "r"); if (!fd) { return ""; } struct mntent mnt; char buf[1024]; size_t buflen = 1024; while (getmntent_r(fd, &mnt, buf, buflen)) { if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) { endmntent(fd); return String(mnt.mnt_dir); } } endmntent(fd); #endif return ""; } Error OS_X11::move_to_trash(const String &p_path) { int err_code; List<String> args; args.push_back(p_path); args.push_front("trash"); // The command is `gio trash <file_name>` so we need to add it to args. Error result = execute("gio", args, true, nullptr, nullptr, &err_code); // For GNOME based machines. if (result == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } args.pop_front(); args.push_front("move"); args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`. result = execute("kioclient5", args, true, nullptr, nullptr, &err_code); // For KDE based machines. if (result == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } args.pop_front(); args.pop_back(); result = execute("gvfs-trash", args, true, nullptr, nullptr, &err_code); // For older Linux machines. if (result == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } // If the commands `kioclient5`, `gio` or `gvfs-trash` don't exist on the system we do it manually. String trash_path = ""; String mnt = get_mountpoint(p_path); // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can. if (mnt != "") { String path(mnt + "/.Trash-" + itos(getuid())); struct stat s; if (!stat(path.utf8().get_data(), &s)) { trash_path = path; } } // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can. if (trash_path == "") { char *dhome = getenv("XDG_DATA_HOME"); if (dhome) { trash_path = String(dhome) + "/Trash"; } } // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can. if (trash_path == "") { char *home = getenv("HOME"); if (home) { trash_path = String(home) + "/.local/share/Trash"; } } // Issue an error if none of the previous locations is appropriate for the trash can. ERR_FAIL_COND_V_MSG(trash_path == "", FAILED, "Could not determine the trash can location"); // Create needed directories for decided trash can location. { DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); Error err = dir_access->make_dir_recursive(trash_path); // Issue an error if trash can is not created proprely. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\""); err = dir_access->make_dir_recursive(trash_path + "/files"); ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"/files"); err = dir_access->make_dir_recursive(trash_path + "/info"); ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"/info"); memdelete(dir_access); } // The trash can is successfully created, now we check that we don't exceed our file name length limit. // If the file name is too long trim it so we can add the identifying number and ".trashinfo". // Assumes that the file name length limit is 255 characters. String file_name = basename(p_path.utf8().get_data()); if (file_name.length() > 240) { file_name = file_name.substr(0, file_name.length() - 15); } String dest_path = trash_path + "/files/" + file_name; struct stat buff; int id_number = 0; String fn = file_name; // Checks if a resource with the same name already exist in the trash can, // if there is, add an identifying number to our resource's name. while (stat(dest_path.utf8().get_data(), &buff) == 0) { id_number++; // Added a limit to check for identically named files already on the trash can // if there are too many it could make the editor unresponsive. ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can."); fn = file_name + "." + itos(id_number); dest_path = trash_path + "/files/" + fn; } file_name = fn; // Generates the .trashinfo file OS::Date date = OS::get_singleton()->get_date(false); OS::Time time = OS::get_singleton()->get_time(false); String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", date.year, (int)date.month, date.day, time.hour, time.min); timestamp = vformat("%s%02d", timestamp, time.sec); // vformat only supports up to 6 arguments. String trash_info = "[Trash Info]\nPath=" + p_path.http_escape() + "\nDeletionDate=" + timestamp + "\n"; { Error err; FileAccess *file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err); ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file:" + trash_path + "/info/" + file_name + ".trashinfo"); file->store_string(trash_info); file->close(); // Rename our resource before moving it to the trash can. DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); err = dir_access->rename(p_path, p_path.get_base_dir() + "/" + file_name); ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + p_path + "\""); memdelete(dir_access); } // Move the given resource to the trash can. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints. List<String> mv_args; mv_args.push_back(p_path.get_base_dir() + "/" + file_name); mv_args.push_back(trash_path + "/files"); { int retval; Error err = execute("mv", mv_args, true, nullptr, nullptr, &retval); // Issue an error if "mv" failed to move the given resource to the trash can. if (err != OK || retval != 0) { ERR_PRINT("move_to_trash: Could not move the resource \"" + p_path + "\" to the trash can \"" + trash_path + "/files\""); DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); err = dir_access->rename(p_path.get_base_dir() + "/" + file_name, p_path); memdelete(dir_access); ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename " + p_path.get_base_dir() + "/" + file_name + " back to its original name:" + p_path); return FAILED; } } return OK; } OS::LatinKeyboardVariant OS_X11::get_latin_keyboard_variant() const { XkbDescRec *xkbdesc = XkbAllocKeyboard(); ERR_FAIL_COND_V(!xkbdesc, LATIN_KEYBOARD_QWERTY); XkbGetNames(x11_display, XkbSymbolsNameMask, xkbdesc); ERR_FAIL_COND_V(!xkbdesc->names, LATIN_KEYBOARD_QWERTY); ERR_FAIL_COND_V(!xkbdesc->names->symbols, LATIN_KEYBOARD_QWERTY); char *layout = XGetAtomName(x11_display, xkbdesc->names->symbols); ERR_FAIL_COND_V(!layout, LATIN_KEYBOARD_QWERTY); Vector<String> info = String(layout).split("+"); ERR_FAIL_INDEX_V(1, info.size(), LATIN_KEYBOARD_QWERTY); if (info[1].find("colemak") != -1) { return LATIN_KEYBOARD_COLEMAK; } else if (info[1].find("qwertz") != -1) { return LATIN_KEYBOARD_QWERTZ; } else if (info[1].find("azerty") != -1) { return LATIN_KEYBOARD_AZERTY; } else if (info[1].find("qzerty") != -1) { return LATIN_KEYBOARD_QZERTY; } else if (info[1].find("dvorak") != -1) { return LATIN_KEYBOARD_DVORAK; } else if (info[1].find("neo") != -1) { return LATIN_KEYBOARD_NEO; } return LATIN_KEYBOARD_QWERTY; } int OS_X11::keyboard_get_layout_count() const { int _group_count = 0; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); const Atom *groups = kbd->names->groups; if (kbd->ctrls != nullptr) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } XkbFreeKeyboard(kbd, 0, true); } return _group_count; } int OS_X11::keyboard_get_current_layout() const { XkbStateRec state; XkbGetState(x11_display, XkbUseCoreKbd, &state); return state.group; } void OS_X11::keyboard_set_current_layout(int p_index) { ERR_FAIL_INDEX(p_index, keyboard_get_layout_count()); XkbLockGroup(x11_display, XkbUseCoreKbd, p_index); } String OS_X11::keyboard_get_layout_language(int p_index) const { String ret; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); XkbGetNames(x11_display, XkbGroupNamesMask, kbd); int _group_count = 0; const Atom *groups = kbd->names->groups; if (kbd->ctrls != nullptr) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } Atom names = kbd->names->symbols; if (names != None) { char *name = XGetAtomName(x11_display, names); Vector<String> info = String(name).split("+"); if (p_index >= 0 && p_index < _group_count) { if (p_index + 1 < info.size()) { ret = info[p_index + 1]; // Skip "pc" at the start and "inet"/"group" at the end of symbols. } else { ret = "en"; // No symbol for layout fallback to "en". } } else { ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ")."); } XFree(name); } XkbFreeKeyboard(kbd, 0, true); } return ret.substr(0, 2); } String OS_X11::keyboard_get_layout_name(int p_index) const { String ret; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); XkbGetNames(x11_display, XkbGroupNamesMask, kbd); int _group_count = 0; const Atom *groups = kbd->names->groups; if (kbd->ctrls != nullptr) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } if (p_index >= 0 && p_index < _group_count) { char *full_name = XGetAtomName(x11_display, groups[p_index]); ret.parse_utf8(full_name); XFree(full_name); } else { ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ")."); } XkbFreeKeyboard(kbd, 0, true); } return ret; } void OS_X11::update_real_mouse_position() { Window root_return, child_return; int root_x, root_y, win_x, win_y; unsigned int mask_return; Bool xquerypointer_result = XQueryPointer(x11_display, x11_window, &root_return, &child_return, &root_x, &root_y, &win_x, &win_y, &mask_return); if (xquerypointer_result) { if (win_x > 0 && win_y > 0 && win_x <= current_videomode.width && win_y <= current_videomode.height) { last_mouse_pos.x = win_x; last_mouse_pos.y = win_y; last_mouse_pos_valid = true; input->set_mouse_position(last_mouse_pos); } } } OS_X11::OS_X11() { #ifdef PULSEAUDIO_ENABLED AudioDriverManager::add_driver(&driver_pulseaudio); #endif #ifdef ALSA_ENABLED AudioDriverManager::add_driver(&driver_alsa); #endif xi.opcode = 0; xi.last_relative_time = 0; layered_window = false; minimized = false; window_focused = true; xim_style = 0L; mouse_mode = MOUSE_MODE_VISIBLE; last_position_before_fs = Vector2(); } use .get_file() instead of basename(3) On OpenBSD the compiler complains that calling basename(3) would lose const qualifier. basename(3) is defined as char *basename(char *); and can, accorgindly to the POSIX.1, modify the passed string. This uses the .get_file() method. The check is necessary because file_name could be a directory, in which case .get_file() would return an empty string. The .get_base_dir().get_file() idiom is already used. The usage of get_file() and the check were suggested by theraot, thanks! (cherry picked from commit a3384b7461005260d0dd5c8f05df28ee842442de) /*************************************************************************/ /* os_x11.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "os_x11.h" #include "core/os/dir_access.h" #include "core/print_string.h" #include "detect_prime.h" #include "drivers/gles2/rasterizer_gles2.h" #include "drivers/gles3/rasterizer_gles3.h" #include "key_mapping_x11.h" #include "main/main.h" #include "servers/visual/visual_server_raster.h" #include "servers/visual/visual_server_wrap_mt.h" #ifdef HAVE_MNTENT #include <mntent.h> #endif #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <X11/Xatom.h> #include <X11/Xutil.h> #include <X11/extensions/Xinerama.h> #include <X11/extensions/shape.h> // ICCCM #define WM_NormalState 1L // window normal state #define WM_IconicState 3L // window minimized // EWMH #define _NET_WM_STATE_REMOVE 0L // remove/unset property #define _NET_WM_STATE_ADD 1L // add/set property #define _NET_WM_STATE_TOGGLE 2L // toggle property #include <dlfcn.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> //stupid linux.h #ifdef KEY_TAB #undef KEY_TAB #endif #undef CursorShape #include <X11/XKBlib.h> // 2.2 is the first release with multitouch #define XINPUT_CLIENT_VERSION_MAJOR 2 #define XINPUT_CLIENT_VERSION_MINOR 2 #define VALUATOR_ABSX 0 #define VALUATOR_ABSY 1 #define VALUATOR_PRESSURE 2 #define VALUATOR_TILTX 3 #define VALUATOR_TILTY 4 static const double abs_resolution_mult = 10000.0; static const double abs_resolution_range_mult = 10.0; void OS_X11::initialize_core() { crash_handler.initialize(); OS_Unix::initialize_core(); } int OS_X11::get_current_video_driver() const { return video_driver_index; } Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { long im_event_mask = 0; last_button_state = 0; xmbstring = nullptr; x11_window = 0; last_click_ms = 0; last_click_button_index = -1; last_click_pos = Point2(-100, -100); args = OS::get_singleton()->get_cmdline_args(); current_videomode = p_desired; main_loop = nullptr; last_timestamp = 0; last_mouse_pos_valid = false; last_keyrelease_time = 0; xdnd_version = 0; XInitThreads(); /** XLIB INITIALIZATION **/ x11_display = XOpenDisplay(nullptr); if (!x11_display) { ERR_PRINT("X11 Display is not available"); return ERR_UNAVAILABLE; } char *modifiers = nullptr; Bool xkb_dar = False; XAutoRepeatOn(x11_display); xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, nullptr); // Try to support IME if detectable auto-repeat is supported if (xkb_dar == True) { #ifdef X_HAVE_UTF8_STRING // Xutf8LookupString will be used later instead of XmbLookupString before // the multibyte sequences can be converted to unicode string. modifiers = XSetLocaleModifiers(""); #endif } if (modifiers == nullptr) { if (is_stdout_verbose()) { WARN_PRINT("IME is disabled"); } XSetLocaleModifiers("@im=none"); WARN_PRINT("Error setting locale modifiers"); } const char *err; xrr_get_monitors = nullptr; xrr_free_monitors = nullptr; int xrandr_major = 0; int xrandr_minor = 0; int event_base, error_base; xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base); xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY); if (!xrandr_handle) { err = dlerror(); // For some arcane reason, NetBSD now ships libXrandr.so.3 while the rest of the world has libXrandr.so.2... // In case this happens for other X11 platforms in the future, let's give it a try too before failing. xrandr_handle = dlopen("libXrandr.so.3", RTLD_LAZY); if (!xrandr_handle) { fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err); } } else { XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor); if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) { xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors"); if (!xrr_get_monitors) { err = dlerror(); fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err); } else { xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors"); if (!xrr_free_monitors) { err = dlerror(); fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err); xrr_get_monitors = nullptr; } } } } if (!refresh_device_info()) { OS::get_singleton()->alert("Your system does not support XInput 2.\n" "Please upgrade your distribution.", "Unable to initialize XInput"); return ERR_UNAVAILABLE; } xim = XOpenIM(x11_display, nullptr, nullptr, nullptr); if (xim == nullptr) { WARN_PRINT("XOpenIM failed"); xim_style = 0L; } else { ::XIMCallback im_destroy_callback; im_destroy_callback.client_data = (::XPointer)(this); im_destroy_callback.callback = (::XIMProc)(xim_destroy_callback); if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback, NULL) != nullptr) { WARN_PRINT("Error setting XIM destroy callback"); } ::XIMStyles *xim_styles = nullptr; xim_style = 0L; char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL); if (imvalret != nullptr || xim_styles == nullptr) { fprintf(stderr, "Input method doesn't support any styles\n"); } if (xim_styles) { xim_style = 0L; for (int i = 0; i < xim_styles->count_styles; i++) { if (xim_styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) { xim_style = xim_styles->supported_styles[i]; break; } } XFree(xim_styles); } XFree(imvalret); } /* char* windowid = getenv("GODOT_WINDOWID"); if (windowid) { //freopen("/home/punto/stdout", "w", stdout); //reopen("/home/punto/stderr", "w", stderr); x11_window = atol(windowid); XWindowAttributes xwa; XGetWindowAttributes(x11_display,x11_window,&xwa); current_videomode.width = xwa.width; current_videomode.height = xwa.height; }; */ // maybe contextgl wants to be in charge of creating the window #if defined(OPENGL_ENABLED) if (getenv("DRI_PRIME") == nullptr) { int use_prime = -1; if (getenv("PRIMUS_DISPLAY") || getenv("PRIMUS_libGLd") || getenv("PRIMUS_libGLa") || getenv("PRIMUS_libGL") || getenv("PRIMUS_LOAD_GLOBAL") || getenv("BUMBLEBEE_SOCKET")) { print_verbose("Optirun/primusrun detected. Skipping GPU detection"); use_prime = 0; } // Some tools use fake libGL libraries and have them override the real one using // LD_LIBRARY_PATH, so we skip them. *But* Steam also sets LD_LIBRARY_PATH for its // runtime and includes system `/lib` and `/lib64`... so ignore Steam. if (use_prime == -1 && getenv("LD_LIBRARY_PATH") && !getenv("STEAM_RUNTIME_LIBRARY_PATH")) { String ld_library_path(getenv("LD_LIBRARY_PATH")); Vector<String> libraries = ld_library_path.split(":"); for (int i = 0; i < libraries.size(); ++i) { if (FileAccess::exists(libraries[i] + "/libGL.so.1") || FileAccess::exists(libraries[i] + "/libGL.so")) { print_verbose("Custom libGL override detected. Skipping GPU detection"); use_prime = 0; } } } if (use_prime == -1) { print_verbose("Detecting GPUs, set DRI_PRIME in the environment to override GPU detection logic."); use_prime = detect_prime(); } if (use_prime) { print_line("Found discrete GPU, setting DRI_PRIME=1 to use it."); print_line("Note: Set DRI_PRIME=0 in the environment to disable Godot from using the discrete GPU."); setenv("DRI_PRIME", "1", 1); } } ContextGL_X11::ContextType opengl_api_type = ContextGL_X11::GLES_3_0_COMPATIBLE; if (p_video_driver == VIDEO_DRIVER_GLES2) { opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; } bool editor = Engine::get_singleton()->is_editor_hint(); bool gl_initialization_error = false; context_gl = nullptr; while (!context_gl) { context_gl = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, opengl_api_type)); if (context_gl->initialize() != OK) { memdelete(context_gl); context_gl = nullptr; if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) { if (p_video_driver == VIDEO_DRIVER_GLES2) { gl_initialization_error = true; break; } p_video_driver = VIDEO_DRIVER_GLES2; opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; } else { gl_initialization_error = true; break; } } } while (true) { if (opengl_api_type == ContextGL_X11::GLES_3_0_COMPATIBLE) { if (RasterizerGLES3::is_viable() == OK) { RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); break; } else { if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) { p_video_driver = VIDEO_DRIVER_GLES2; opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; continue; } else { gl_initialization_error = true; break; } } } if (opengl_api_type == ContextGL_X11::GLES_2_0_COMPATIBLE) { if (RasterizerGLES2::is_viable() == OK) { RasterizerGLES2::register_config(); RasterizerGLES2::make_current(); break; } else { gl_initialization_error = true; break; } } } if (gl_initialization_error) { OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n" "Please update your drivers or if you have a very old or integrated GPU, upgrade it.\n" "If you have updated your graphics drivers recently, try rebooting.\n" "Alternatively, you can force software rendering by running Godot with the `LIBGL_ALWAYS_SOFTWARE=1`\n" "environment variable set, but this will be very slow.", "Unable to initialize Video driver"); return ERR_UNAVAILABLE; } video_driver_index = p_video_driver; context_gl->set_use_vsync(current_videomode.use_vsync); #endif visual_server = memnew(VisualServerRaster); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); } if (current_videomode.maximized) { current_videomode.maximized = false; set_window_maximized(true); // borderless fullscreen window mode } else if (current_videomode.fullscreen) { current_videomode.fullscreen = false; set_window_fullscreen(true); } else if (current_videomode.borderless_window) { Hints hints; Atom property; hints.flags = 2; hints.decorations = 0; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } // make PID known to X11 { const long pid = this->get_process_id(); Atom net_wm_pid = XInternAtom(x11_display, "_NET_WM_PID", False); if (net_wm_pid != None) { XChangeProperty(x11_display, x11_window, net_wm_pid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1); } } // disable resizable window if (!current_videomode.resizable && !current_videomode.fullscreen) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = PMinSize | PMaxSize; XWindowAttributes xwa; if (current_videomode.fullscreen) { XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa); } else { XGetWindowAttributes(x11_display, x11_window, &xwa); } xsh->min_width = xwa.width; xsh->max_width = xwa.width; xsh->min_height = xwa.height; xsh->max_height = xwa.height; XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); } if (current_videomode.always_on_top) { current_videomode.always_on_top = false; set_window_always_on_top(true); } ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE); ERR_FAIL_COND_V(x11_window == 0, ERR_UNAVAILABLE); XSetWindowAttributes new_attr; new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask | Button1MotionMask | Button2MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask | ButtonMotionMask | KeymapStateMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | SubstructureNotifyMask | SubstructureRedirectMask | FocusChangeMask | PropertyChangeMask | ColormapChangeMask | OwnerGrabButtonMask | im_event_mask; XChangeWindowAttributes(x11_display, x11_window, CWEventMask, &new_attr); static unsigned char all_mask_data[XIMaskLen(XI_LASTEVENT)] = {}; static unsigned char all_master_mask_data[XIMaskLen(XI_LASTEVENT)] = {}; xi.all_event_mask.deviceid = XIAllDevices; xi.all_event_mask.mask_len = sizeof(all_mask_data); xi.all_event_mask.mask = all_mask_data; xi.all_master_event_mask.deviceid = XIAllMasterDevices; xi.all_master_event_mask.mask_len = sizeof(all_master_mask_data); xi.all_master_event_mask.mask = all_master_mask_data; XISetMask(xi.all_event_mask.mask, XI_HierarchyChanged); XISetMask(xi.all_master_event_mask.mask, XI_DeviceChanged); XISetMask(xi.all_master_event_mask.mask, XI_RawMotion); #ifdef TOUCH_ENABLED if (xi.touch_devices.size()) { XISetMask(xi.all_event_mask.mask, XI_TouchBegin); XISetMask(xi.all_event_mask.mask, XI_TouchUpdate); XISetMask(xi.all_event_mask.mask, XI_TouchEnd); XISetMask(xi.all_event_mask.mask, XI_TouchOwnership); } #endif XISelectEvents(x11_display, x11_window, &xi.all_event_mask, 1); XISelectEvents(x11_display, DefaultRootWindow(x11_display), &xi.all_master_event_mask, 1); // Disabled by now since grabbing also blocks mouse events // (they are received as extended events instead of standard events) /*XIClearMask(xi.touch_event_mask.mask, XI_TouchOwnership); // Grab touch devices to avoid OS gesture interference for (int i = 0; i < xi.touch_devices.size(); ++i) { XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask); }*/ /* set the titlebar name */ XStoreName(x11_display, x11_window, "Godot"); wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true); XSetWMProtocols(x11_display, x11_window, &wm_delete, 1); im_active = false; im_position = Vector2(); if (xim && xim_style) { xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, x11_window, XNFocusWindow, x11_window, (char *)nullptr); if (XGetICValues(xic, XNFilterEvents, &im_event_mask, NULL) != nullptr) { WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value"); XDestroyIC(xic); xic = nullptr; } if (xic) { XUnsetICFocus(xic); } else { WARN_PRINT("XCreateIC couldn't create xic"); } } else { xic = nullptr; WARN_PRINT("XCreateIC couldn't create xic"); } cursor_size = XcursorGetDefaultSize(x11_display); cursor_theme = XcursorGetTheme(x11_display); if (!cursor_theme) { print_verbose("XcursorGetTheme could not get cursor theme"); cursor_theme = "default"; } for (int i = 0; i < CURSOR_MAX; i++) { cursors[i] = None; img[i] = nullptr; } current_cursor = CURSOR_ARROW; for (int i = 0; i < CURSOR_MAX; i++) { static const char *cursor_file[] = { "left_ptr", "xterm", "hand2", "cross", "watch", "left_ptr_watch", "fleur", "hand1", "X_cursor", "sb_v_double_arrow", "sb_h_double_arrow", "size_bdiag", "size_fdiag", "hand1", "sb_v_double_arrow", "sb_h_double_arrow", "question_arrow" }; img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size); if (img[i]) { cursors[i] = XcursorImageLoadCursor(x11_display, img[i]); } else { print_verbose("Failed loading custom cursor: " + String(cursor_file[i])); } } { // Creating an empty/transparent cursor // Create 1x1 bitmap Pixmap cursormask = XCreatePixmap(x11_display, RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1); // Fill with zero XGCValues xgc; xgc.function = GXclear; GC gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc); XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1); // Color value doesn't matter. Mask zero means no foreground or background will be drawn XColor col = {}; Cursor cursor = XCreatePixmapCursor(x11_display, cursormask, // source (using cursor mask as placeholder, since it'll all be ignored) cursormask, // mask &col, &col, 0, 0); XFreePixmap(x11_display, cursormask); XFreeGC(x11_display, gc); if (cursor == None) { ERR_PRINT("FAILED CREATING CURSOR"); } null_cursor = cursor; } set_cursor_shape(CURSOR_BUSY); //Set Xdnd (drag & drop) support Atom XdndAware = XInternAtom(x11_display, "XdndAware", False); Atom version = 5; if (XdndAware != None) { XChangeProperty(x11_display, x11_window, XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&version, 1); } xdnd_enter = XInternAtom(x11_display, "XdndEnter", False); xdnd_position = XInternAtom(x11_display, "XdndPosition", False); xdnd_status = XInternAtom(x11_display, "XdndStatus", False); xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False); xdnd_drop = XInternAtom(x11_display, "XdndDrop", False); xdnd_finished = XInternAtom(x11_display, "XdndFinished", False); xdnd_selection = XInternAtom(x11_display, "XdndSelection", False); requested = None; visual_server->init(); AudioDriverManager::initialize(p_audio_driver); input = memnew(InputDefault); window_has_focus = true; // Set focus to true at init #ifdef JOYDEV_ENABLED joypad = memnew(JoypadLinux(input)); #endif power_manager = memnew(PowerX11); if (p_desired.layered) { set_window_per_pixel_transparency_enabled(true); } XEvent xevent; while (XPending(x11_display) > 0) { XNextEvent(x11_display, &xevent); if (xevent.type == ConfigureNotify) { _window_changed(&xevent); } } events_thread.start(_poll_events_thread, this); update_real_mouse_position(); return OK; } bool OS_X11::refresh_device_info() { int event_base, error_base; print_verbose("XInput: Refreshing devices."); if (!XQueryExtension(x11_display, "XInputExtension", &xi.opcode, &event_base, &error_base)) { print_verbose("XInput extension not available. Please upgrade your distribution."); return false; } int xi_major_query = XINPUT_CLIENT_VERSION_MAJOR; int xi_minor_query = XINPUT_CLIENT_VERSION_MINOR; if (XIQueryVersion(x11_display, &xi_major_query, &xi_minor_query) != Success) { print_verbose(vformat("XInput 2 not available (server supports %d.%d).", xi_major_query, xi_minor_query)); xi.opcode = 0; return false; } if (xi_major_query < XINPUT_CLIENT_VERSION_MAJOR || (xi_major_query == XINPUT_CLIENT_VERSION_MAJOR && xi_minor_query < XINPUT_CLIENT_VERSION_MINOR)) { print_verbose(vformat("XInput %d.%d not available (server supports %d.%d). Touch input unavailable.", XINPUT_CLIENT_VERSION_MAJOR, XINPUT_CLIENT_VERSION_MINOR, xi_major_query, xi_minor_query)); } xi.absolute_devices.clear(); xi.touch_devices.clear(); int dev_count; XIDeviceInfo *info = XIQueryDevice(x11_display, XIAllDevices, &dev_count); for (int i = 0; i < dev_count; i++) { XIDeviceInfo *dev = &info[i]; if (!dev->enabled) { continue; } if (!(dev->use == XIMasterPointer || dev->use == XIFloatingSlave)) { continue; } bool direct_touch = false; bool absolute_mode = false; int resolution_x = 0; int resolution_y = 0; double abs_x_min = 0; double abs_x_max = 0; double abs_y_min = 0; double abs_y_max = 0; double pressure_min = 0; double pressure_max = 0; double tilt_x_min = 0; double tilt_x_max = 0; double tilt_y_min = 0; double tilt_y_max = 0; for (int j = 0; j < dev->num_classes; j++) { #ifdef TOUCH_ENABLED if (dev->classes[j]->type == XITouchClass && ((XITouchClassInfo *)dev->classes[j])->mode == XIDirectTouch) { direct_touch = true; } #endif if (dev->classes[j]->type == XIValuatorClass) { XIValuatorClassInfo *class_info = (XIValuatorClassInfo *)dev->classes[j]; if (class_info->number == VALUATOR_ABSX && class_info->mode == XIModeAbsolute) { resolution_x = class_info->resolution; abs_x_min = class_info->min; abs_y_max = class_info->max; absolute_mode = true; } else if (class_info->number == VALUATOR_ABSY && class_info->mode == XIModeAbsolute) { resolution_y = class_info->resolution; abs_y_min = class_info->min; abs_y_max = class_info->max; absolute_mode = true; } else if (class_info->number == VALUATOR_PRESSURE && class_info->mode == XIModeAbsolute) { pressure_min = class_info->min; pressure_max = class_info->max; } else if (class_info->number == VALUATOR_TILTX && class_info->mode == XIModeAbsolute) { tilt_x_min = class_info->min; tilt_x_max = class_info->max; } else if (class_info->number == VALUATOR_TILTY && class_info->mode == XIModeAbsolute) { tilt_x_min = class_info->min; tilt_x_max = class_info->max; } } } if (direct_touch) { xi.touch_devices.push_back(dev->deviceid); print_verbose("XInput: Using touch device: " + String(dev->name)); } if (absolute_mode) { // If no resolution was reported, use the min/max ranges. if (resolution_x <= 0) { resolution_x = (abs_x_max - abs_x_min) * abs_resolution_range_mult; } if (resolution_y <= 0) { resolution_y = (abs_y_max - abs_y_min) * abs_resolution_range_mult; } xi.absolute_devices[dev->deviceid] = Vector2(abs_resolution_mult / resolution_x, abs_resolution_mult / resolution_y); print_verbose("XInput: Absolute pointing device: " + String(dev->name)); } xi.pressure = 0; xi.pen_pressure_range[dev->deviceid] = Vector2(pressure_min, pressure_max); xi.pen_tilt_x_range[dev->deviceid] = Vector2(tilt_x_min, tilt_x_max); xi.pen_tilt_y_range[dev->deviceid] = Vector2(tilt_y_min, tilt_y_max); } XIFreeDeviceInfo(info); #ifdef TOUCH_ENABLED if (!xi.touch_devices.size()) { print_verbose("XInput: No touch devices found."); } #endif return true; } void OS_X11::xim_destroy_callback(::XIM im, ::XPointer client_data, ::XPointer call_data) { WARN_PRINT("Input method stopped"); OS_X11 *os = reinterpret_cast<OS_X11 *>(client_data); os->xim = nullptr; os->xic = nullptr; } void OS_X11::set_ime_active(const bool p_active) { im_active = p_active; if (!xic) { return; } // Block events polling while changing input focus // because it triggers some event polling internally. if (p_active) { { MutexLock mutex_lock(events_mutex); XSetICFocus(xic); } set_ime_position(im_position); } else { MutexLock mutex_lock(events_mutex); XUnsetICFocus(xic); } } void OS_X11::set_ime_position(const Point2 &p_pos) { im_position = p_pos; if (!xic) { return; } ::XPoint spot; spot.x = short(p_pos.x); spot.y = short(p_pos.y); XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, NULL); { // Block events polling during this call // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XSetICValues(xic, XNPreeditAttributes, preedit_attr, NULL); } XFree(preedit_attr); } String OS_X11::get_unique_id() const { static String machine_id; if (machine_id.empty()) { if (FileAccess *f = FileAccess::open("/etc/machine-id", FileAccess::READ)) { while (machine_id.empty() && !f->eof_reached()) { machine_id = f->get_line().strip_edges(); } f->close(); memdelete(f); } } return machine_id; } void OS_X11::finalize() { events_thread_done = true; events_thread.wait_to_finish(); if (main_loop) { memdelete(main_loop); } main_loop = nullptr; /* if (debugger_connection_console) { memdelete(debugger_connection_console); } */ #ifdef ALSAMIDI_ENABLED driver_alsamidi.close(); #endif #ifdef JOYDEV_ENABLED memdelete(joypad); #endif xi.touch_devices.clear(); xi.state.clear(); memdelete(input); cursors_cache.clear(); visual_server->finish(); memdelete(visual_server); //memdelete(rasterizer); memdelete(power_manager); if (xrandr_handle) { dlclose(xrandr_handle); } if (!OS::get_singleton()->is_no_window_mode_enabled()) { XUnmapWindow(x11_display, x11_window); } XDestroyWindow(x11_display, x11_window); #if defined(OPENGL_ENABLED) memdelete(context_gl); #endif for (int i = 0; i < CURSOR_MAX; i++) { if (cursors[i] != None) { XFreeCursor(x11_display, cursors[i]); } if (img[i] != nullptr) { XcursorImageDestroy(img[i]); } }; if (xic) { XDestroyIC(xic); } if (xim) { XCloseIM(xim); } XCloseDisplay(x11_display); if (xmbstring) { memfree(xmbstring); } args.clear(); } void OS_X11::set_mouse_mode(MouseMode p_mode) { if (p_mode == mouse_mode) { return; } if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) { XUngrabPointer(x11_display, CurrentTime); } // The only modes that show a cursor are VISIBLE and CONFINED bool showCursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED); if (showCursor) { XDefineCursor(x11_display, x11_window, cursors[current_cursor]); // show cursor } else { XDefineCursor(x11_display, x11_window, null_cursor); // hide cursor } mouse_mode = p_mode; if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) { //flush pending motion events flush_mouse_motion(); if (XGrabPointer( x11_display, x11_window, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime) != GrabSuccess) { ERR_PRINT("NO GRAB"); } if (mouse_mode == MOUSE_MODE_CAPTURED) { center.x = current_videomode.width / 2; center.y = current_videomode.height / 2; XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)center.x, (int)center.y); input->set_mouse_position(center); } } else { do_mouse_warp = false; } XFlush(x11_display); } void OS_X11::warp_mouse_position(const Point2 &p_to) { if (mouse_mode == MOUSE_MODE_CAPTURED) { last_mouse_pos = p_to; } else { /*XWindowAttributes xwa; XGetWindowAttributes(x11_display, x11_window, &xwa); printf("%d %d\n", xwa.x, xwa.y); needed? */ XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)p_to.x, (int)p_to.y); } } void OS_X11::flush_mouse_motion() { // Block events polling while flushing motion events. MutexLock mutex_lock(events_mutex); for (uint32_t event_index = 0; event_index < polled_events.size(); ++event_index) { XEvent &event = polled_events[event_index]; if (XGetEventData(x11_display, &event.xcookie) && event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) { XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data; if (event_data->evtype == XI_RawMotion) { XFreeEventData(x11_display, &event.xcookie); polled_events.remove(event_index--); continue; } XFreeEventData(x11_display, &event.xcookie); break; } } xi.relative_motion.x = 0; xi.relative_motion.y = 0; } OS::MouseMode OS_X11::get_mouse_mode() const { return mouse_mode; } int OS_X11::get_mouse_button_state() const { return last_button_state; } Point2 OS_X11::get_mouse_position() const { return last_mouse_pos; } bool OS_X11::get_window_per_pixel_transparency_enabled() const { if (!is_layered_allowed()) { return false; } return layered_window; } void OS_X11::set_window_per_pixel_transparency_enabled(bool p_enabled) { if (!is_layered_allowed()) { return; } if (layered_window != p_enabled) { if (p_enabled) { layered_window = true; } else { layered_window = false; } } } void OS_X11::set_window_title(const String &p_title) { XStoreName(x11_display, x11_window, p_title.utf8().get_data()); Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false); Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false); if (_net_wm_name != None && utf8_string != None) { XChangeProperty(x11_display, x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length()); } } void OS_X11::set_window_mouse_passthrough(const PoolVector2Array &p_region) { int event_base, error_base; const Bool ext_okay = XShapeQueryExtension(x11_display, &event_base, &error_base); if (ext_okay) { Region region; if (p_region.size() == 0) { region = XCreateRegion(); XRectangle rect; rect.x = 0; rect.y = 0; rect.width = get_real_window_size().x; rect.height = get_real_window_size().y; XUnionRectWithRegion(&rect, region, region); } else { XPoint *points = (XPoint *)memalloc(sizeof(XPoint) * p_region.size()); for (int i = 0; i < p_region.size(); i++) { points[i].x = p_region[i].x; points[i].y = p_region[i].y; } region = XPolygonRegion(points, p_region.size(), EvenOddRule); memfree(points); } XShapeCombineRegion(x11_display, x11_window, ShapeInput, 0, 0, region, ShapeSet); XDestroyRegion(region); } } void OS_X11::set_video_mode(const VideoMode &p_video_mode, int p_screen) { } OS::VideoMode OS_X11::get_video_mode(int p_screen) const { return current_videomode; } void OS_X11::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const { } void OS_X11::set_wm_fullscreen(bool p_enabled) { if (p_enabled && !get_borderless_window()) { // remove decorations if the window is not already borderless Hints hints; Atom property; hints.flags = 2; hints.decorations = 0; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } if (p_enabled && !is_window_resizable()) { // Set the window as resizable to prevent window managers to ignore the fullscreen state flag. XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); } // Using EWMH -- Extended Window Manager Hints XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.xclient.data.l[1] = wm_fullscreen; xev.xclient.data.l[2] = 0; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); // set bypass compositor hint Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False); unsigned long compositing_disable_on = p_enabled ? 1 : 0; if (bypass_compositor != None) { XChangeProperty(x11_display, x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1); } XFlush(x11_display); if (!p_enabled) { // Reset the non-resizable flags if we un-set these before. Size2 size = get_window_size(); XSizeHints *xsh; xsh = XAllocSizeHints(); if (!is_window_resizable()) { xsh->flags = PMinSize | PMaxSize; xsh->min_width = size.x; xsh->max_width = size.x; xsh->min_height = size.y; xsh->max_height = size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); // put back or remove decorations according to the last set borderless state Hints hints; Atom property; hints.flags = 2; hints.decorations = current_videomode.borderless_window ? 0 : 1; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } } } void OS_X11::set_wm_above(bool p_enabled) { Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False); XClientMessageEvent xev; memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.window = x11_window; xev.message_type = wm_state; xev.format = 32; xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.data.l[1] = wm_above; xev.data.l[3] = 1; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev); } int OS_X11::get_screen_count() const { // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) { return 0; } int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); XFree(xsi); return count; } int OS_X11::get_current_screen() const { int x, y; Window child; XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child); int count = get_screen_count(); for (int i = 0; i < count; i++) { Point2i pos = get_screen_position(i); Size2i size = get_screen_size(i); if ((x >= pos.x && x < pos.x + size.width) && (y >= pos.y && y < pos.y + size.height)) { return i; } } return 0; } void OS_X11::set_current_screen(int p_screen) { if (p_screen == -1) { p_screen = get_current_screen(); } // Check if screen is valid ERR_FAIL_INDEX(p_screen, get_screen_count()); if (current_videomode.fullscreen) { Point2i position = get_screen_position(p_screen); Size2i size = get_screen_size(p_screen); XMoveResizeWindow(x11_display, x11_window, position.x, position.y, size.x, size.y); } else { if (p_screen != get_current_screen()) { Point2i position = get_screen_position(p_screen); XMoveWindow(x11_display, x11_window, position.x, position.y); } } } Point2 OS_X11::get_screen_position(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) { return Point2i(0, 0); } int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); // Check if screen is valid ERR_FAIL_INDEX_V(p_screen, count, Point2i(0, 0)); Point2i position = Point2i(xsi[p_screen].x_org, xsi[p_screen].y_org); XFree(xsi); return position; } Size2 OS_X11::get_screen_size(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } // Using Xinerama Extension int event_base, error_base; const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base); if (!ext_okay) { return Size2i(0, 0); } int count; XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count); // Check if screen is valid ERR_FAIL_INDEX_V(p_screen, count, Size2i(0, 0)); Size2i size = Point2i(xsi[p_screen].width, xsi[p_screen].height); XFree(xsi); return size; } int OS_X11::get_screen_dpi(int p_screen) const { if (p_screen == -1) { p_screen = get_current_screen(); } //invalid screen? ERR_FAIL_INDEX_V(p_screen, get_screen_count(), 0); //Get physical monitor Dimensions through XRandR and calculate dpi Size2 sc = get_screen_size(p_screen); if (xrandr_ext_ok) { int count = 0; if (xrr_get_monitors) { xrr_monitor_info *monitors = xrr_get_monitors(x11_display, x11_window, true, &count); if (p_screen < count) { double xdpi = sc.width / (double)monitors[p_screen].mwidth * 25.4; double ydpi = sc.height / (double)monitors[p_screen].mheight * 25.4; xrr_free_monitors(monitors); return (xdpi + ydpi) / 2; } xrr_free_monitors(monitors); } else if (p_screen == 0) { XRRScreenSize *sizes = XRRSizes(x11_display, 0, &count); if (sizes) { double xdpi = sc.width / (double)sizes[0].mwidth * 25.4; double ydpi = sc.height / (double)sizes[0].mheight * 25.4; return (xdpi + ydpi) / 2; } } } int width_mm = DisplayWidthMM(x11_display, p_screen); int height_mm = DisplayHeightMM(x11_display, p_screen); double xdpi = (width_mm ? sc.width / (double)width_mm * 25.4 : 0); double ydpi = (height_mm ? sc.height / (double)height_mm * 25.4 : 0); if (xdpi || ydpi) { return (xdpi + ydpi) / (xdpi && ydpi ? 2 : 1); } //could not get dpi return 96; } Point2 OS_X11::get_window_position() const { int x, y; Window child; XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child); return Point2i(x, y); } void OS_X11::set_window_position(const Point2 &p_position) { int x = 0; int y = 0; if (!get_borderless_window()) { //exclude window decorations XSync(x11_display, False); Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (format == 32 && len == 4) { long *extents = (long *)data; x = extents[0]; y = extents[2]; } XFree(data); } } } XMoveWindow(x11_display, x11_window, p_position.x - x, p_position.y - y); update_real_mouse_position(); } Size2 OS_X11::get_window_size() const { // Use current_videomode width and height instead of XGetWindowAttributes // since right after a XResizeWindow the attributes may not be updated yet return Size2i(current_videomode.width, current_videomode.height); } Size2 OS_X11::get_real_window_size() const { XWindowAttributes xwa; XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); int w = xwa.width; int h = xwa.height; Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (format == 32 && len == 4) { long *extents = (long *)data; w += extents[0] + extents[1]; // left, right h += extents[2] + extents[3]; // top, bottom } XFree(data); } } return Size2(w, h); } Size2 OS_X11::get_max_window_size() const { return max_size; } Size2 OS_X11::get_min_window_size() const { return min_size; } void OS_X11::set_min_window_size(const Size2 p_size) { if ((p_size != Size2()) && (max_size != Size2()) && ((p_size.x > max_size.x) || (p_size.y > max_size.y))) { ERR_PRINT("Minimum window size can't be larger than maximum window size!"); return; } min_size = p_size; if (is_window_resizable()) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); XFlush(x11_display); } } void OS_X11::set_max_window_size(const Size2 p_size) { if ((p_size != Size2()) && ((p_size.x < min_size.x) || (p_size.y < min_size.y))) { ERR_PRINT("Maximum window size can't be smaller than minimum window size!"); return; } max_size = p_size; if (is_window_resizable()) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); XFlush(x11_display); } } void OS_X11::set_window_size(const Size2 p_size) { if (current_videomode.width == p_size.width && current_videomode.height == p_size.height) { return; } XWindowAttributes xwa; XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); int old_w = xwa.width; int old_h = xwa.height; Size2 size = p_size; size.x = MAX(1, size.x); size.y = MAX(1, size.y); // If window resizable is disabled we need to update the attributes first XSizeHints *xsh; xsh = XAllocSizeHints(); if (!is_window_resizable()) { xsh->flags = PMinSize | PMaxSize; xsh->min_width = size.x; xsh->max_width = size.x; xsh->min_height = size.y; xsh->max_height = size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); // Resize the window XResizeWindow(x11_display, x11_window, size.x, size.y); // Update our videomode width and height current_videomode.width = size.x; current_videomode.height = size.y; for (int timeout = 0; timeout < 50; ++timeout) { XSync(x11_display, False); XGetWindowAttributes(x11_display, x11_window, &xwa); if (old_w != xwa.width || old_h != xwa.height) { break; } usleep(10000); } } void OS_X11::set_window_fullscreen(bool p_enabled) { if (current_videomode.fullscreen == p_enabled) { return; } if (layered_window) { set_window_per_pixel_transparency_enabled(false); } if (p_enabled && current_videomode.always_on_top) { // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity) set_window_maximized(true); } set_wm_fullscreen(p_enabled); if (!p_enabled && current_videomode.always_on_top) { // Restore set_window_maximized(false); } if (!p_enabled) { set_window_position(last_position_before_fs); } else { last_position_before_fs = get_window_position(); } current_videomode.fullscreen = p_enabled; } bool OS_X11::is_window_fullscreen() const { return current_videomode.fullscreen; } void OS_X11::set_window_resizable(bool p_enabled) { XSizeHints *xsh; xsh = XAllocSizeHints(); if (!p_enabled) { Size2 size = get_window_size(); xsh->flags = PMinSize | PMaxSize; xsh->min_width = size.x; xsh->max_width = size.x; xsh->min_height = size.y; xsh->max_height = size.y; } else { xsh->flags = 0L; if (min_size != Size2()) { xsh->flags |= PMinSize; xsh->min_width = min_size.x; xsh->min_height = min_size.y; } if (max_size != Size2()) { xsh->flags |= PMaxSize; xsh->max_width = max_size.x; xsh->max_height = max_size.y; } } XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); current_videomode.resizable = p_enabled; XFlush(x11_display); } bool OS_X11::is_window_resizable() const { return current_videomode.resizable; } void OS_X11::set_window_minimized(bool p_enabled) { if (is_no_window_mode_enabled()) { return; } // Using ICCCM -- Inter-Client Communication Conventions Manual XEvent xev; Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_change; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? WM_IconicState : WM_NormalState; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = _NET_WM_STATE_ADD; xev.xclient.data.l[1] = wm_hidden; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); } bool OS_X11::is_window_minimized() const { // Using ICCCM -- Inter-Client Communication Conventions Manual Atom property = XInternAtom(x11_display, "WM_STATE", True); if (property == None) { return false; } Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; bool retval = false; int result = XGetWindowProperty( x11_display, x11_window, property, 0, 32, False, AnyPropertyType, &type, &format, &len, &remaining, &data); if (result == Success) { long *state = (long *)data; if (state[0] == WM_IconicState) { retval = true; } XFree(data); } return retval; } void OS_X11::set_window_maximized(bool p_enabled) { if (is_no_window_mode_enabled()) { return; } if (is_window_maximized() == p_enabled) { return; } // Using EWMH -- Extended Window Manager Hints XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False); Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE; xev.xclient.data.l[1] = wm_max_horz; xev.xclient.data.l[2] = wm_max_vert; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); if (p_enabled && is_window_maximize_allowed()) { // Wait for effective resizing (so the GLX context is too). // Give up after 0.5s, it's not going to happen on this WM. // https://github.com/godotengine/godot/issues/19978 for (int attempt = 0; !is_window_maximized() && attempt < 50; attempt++) { usleep(10000); } } maximized = p_enabled; } // Just a helper to reduce code duplication in `is_window_maximize_allowed` // and `is_window_maximized`. bool OS_X11::window_maximize_check(const char *p_atom_name) const { Atom property = XInternAtom(x11_display, p_atom_name, False); Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; bool retval = false; if (property == None) { return false; } int result = XGetWindowProperty( x11_display, x11_window, property, 0, 1024, False, XA_ATOM, &type, &format, &len, &remaining, &data); if (result == Success) { Atom *atoms = (Atom *)data; Atom wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False); Atom wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_VERT", False); bool found_wm_act_max_horz = false; bool found_wm_act_max_vert = false; for (uint64_t i = 0; i < len; i++) { if (atoms[i] == wm_act_max_horz) { found_wm_act_max_horz = true; } if (atoms[i] == wm_act_max_vert) { found_wm_act_max_vert = true; } if (found_wm_act_max_horz || found_wm_act_max_vert) { retval = true; break; } } XFree(data); } return retval; } bool OS_X11::is_window_maximize_allowed() const { return window_maximize_check("_NET_WM_ALLOWED_ACTIONS"); } bool OS_X11::is_window_maximized() const { // Using EWMH -- Extended Window Manager Hints return window_maximize_check("_NET_WM_STATE"); } void OS_X11::set_window_always_on_top(bool p_enabled) { if (is_window_always_on_top() == p_enabled) { return; } if (p_enabled && current_videomode.fullscreen) { // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity) set_window_maximized(true); } set_wm_above(p_enabled); if (!p_enabled && !current_videomode.fullscreen) { // Restore set_window_maximized(false); } current_videomode.always_on_top = p_enabled; } bool OS_X11::is_window_always_on_top() const { return current_videomode.always_on_top; } bool OS_X11::is_window_focused() const { return window_focused; } void OS_X11::set_borderless_window(bool p_borderless) { if (get_borderless_window() == p_borderless) { return; } current_videomode.borderless_window = p_borderless; Hints hints; Atom property; hints.flags = 2; hints.decorations = current_videomode.borderless_window ? 0 : 1; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (property != None) { XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } // Preserve window size set_window_size(Size2(current_videomode.width, current_videomode.height)); } bool OS_X11::get_borderless_window() { bool borderless = current_videomode.borderless_window; Atom prop = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); if (prop != None) { Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (data && (format == 32) && (len >= 5)) { borderless = !((Hints *)data)->decorations; } XFree(data); } } return borderless; } void OS_X11::request_attention() { // Using EWMH -- Extended Window Manager Hints // // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE // Will be unset by the window manager after user react on the request for attention XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = _NET_WM_STATE_ADD; xev.xclient.data.l[1] = wm_attention; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(x11_display); } void *OS_X11::get_native_handle(int p_handle_type) { switch (p_handle_type) { case APPLICATION_HANDLE: return nullptr; // Do we have a value to return here? case DISPLAY_HANDLE: return (void *)x11_display; case WINDOW_HANDLE: return (void *)x11_window; case WINDOW_VIEW: return nullptr; // Do we have a value to return here? case OPENGL_CONTEXT: return context_gl->get_glx_context(); default: return nullptr; } } void OS_X11::get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) { state->set_shift((p_x11_state & ShiftMask)); state->set_control((p_x11_state & ControlMask)); state->set_alt((p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/)); //altgr should not count as alt state->set_metakey((p_x11_state & Mod4Mask)); } unsigned int OS_X11::get_mouse_button_state(unsigned int p_x11_button, int p_x11_type) { unsigned int mask = 1 << (p_x11_button - 1); if (p_x11_type == ButtonPress) { last_button_state |= mask; } else { last_button_state &= ~mask; } return last_button_state; } void OS_X11::_handle_key_event(XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo) { // X11 functions don't know what const is XKeyEvent *xkeyevent = p_event; // This code was pretty difficult to write. // The docs stink and every toolkit seems to // do it in a different way. /* Phase 1, obtain a proper keysym */ // This was also very difficult to figure out. // You'd expect you could just use Keysym provided by // XKeycodeToKeysym to obtain internationalized // input.. WRONG!! // you must use XLookupString (???) which not only wastes // cycles generating an unnecessary string, but also // still works in half the cases. (won't handle deadkeys) // For more complex input methods (deadkeys and more advanced) // you have to use XmbLookupString (??). // So.. then you have to chosse which of both results // you want to keep. // This is a real bizarreness and cpu waster. KeySym keysym_keycode = 0; // keysym used to find a keycode KeySym keysym_unicode = 0; // keysym used to find unicode // XLookupString returns keysyms usable as nice scancodes/ char str[256 + 1]; XKeyEvent xkeyevent_no_mod = *xkeyevent; xkeyevent_no_mod.state &= ~ShiftMask; xkeyevent_no_mod.state &= ~ControlMask; XLookupString(xkeyevent, str, 256, &keysym_unicode, nullptr); XLookupString(&xkeyevent_no_mod, nullptr, 0, &keysym_keycode, nullptr); // Meanwhile, XLookupString returns keysyms useful for unicode. if (!xmbstring) { // keep a temporary buffer for the string xmbstring = (char *)memalloc(sizeof(char) * 8); xmblen = 8; } if (xkeyevent->type == KeyPress && xic) { Status status; #ifdef X_HAVE_UTF8_STRING int utf8len = 8; char *utf8string = (char *)memalloc(sizeof(char) * utf8len); int utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string, utf8len - 1, &keysym_unicode, &status); if (status == XBufferOverflow) { utf8len = utf8bytes + 1; utf8string = (char *)memrealloc(utf8string, utf8len); utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string, utf8len - 1, &keysym_unicode, &status); } utf8string[utf8bytes] = '\0'; if (status == XLookupChars) { bool keypress = xkeyevent->type == KeyPress; unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode); unsigned int physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode); if (keycode >= 'a' && keycode <= 'z') { keycode -= 'a' - 'A'; } String tmp; tmp.parse_utf8(utf8string, utf8bytes); for (int i = 0; i < tmp.length(); i++) { Ref<InputEventKey> k; k.instance(); if (physical_keycode == 0 && keycode == 0 && tmp[i] == 0) { continue; } if (keycode == 0) { keycode = physical_keycode; } get_key_modifier_state(xkeyevent->state, k); k->set_unicode(tmp[i]); k->set_pressed(keypress); k->set_scancode(keycode); k->set_physical_scancode(physical_keycode); k->set_echo(false); if (k->get_scancode() == KEY_BACKTAB) { //make it consistent across platforms. k->set_scancode(KEY_TAB); k->set_physical_scancode(KEY_TAB); k->set_shift(true); } input->parse_input_event(k); } memfree(utf8string); return; } memfree(utf8string); #else do { int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status); xmbstring[mnbytes] = '\0'; if (status == XBufferOverflow) { xmblen = mnbytes + 1; xmbstring = (char *)memrealloc(xmbstring, xmblen); } } while (status == XBufferOverflow); #endif } /* Phase 2, obtain a pigui keycode from the keysym */ // KeyMappingX11 just translated the X11 keysym to a PIGUI // keysym, so it works in all platforms the same. unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode); unsigned int physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode); /* Phase 3, obtain a unicode character from the keysym */ // KeyMappingX11 also translates keysym to unicode. // It does a binary search on a table to translate // most properly. unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0; /* Phase 4, determine if event must be filtered */ // This seems to be a side-effect of using XIM. // XFilterEvent looks like a core X11 function, // but it's actually just used to see if we must // ignore a deadkey, or events XIM determines // must not reach the actual gui. // Guess it was a design problem of the extension bool keypress = xkeyevent->type == KeyPress; if (physical_keycode == 0 && keycode == 0 && unicode == 0) { return; } if (keycode == 0) { keycode = physical_keycode; } /* Phase 5, determine modifier mask */ // No problems here, except I had no way to // know Mod1 was ALT and Mod4 was META (applekey/winkey) // just tried Mods until i found them. //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask)); Ref<InputEventKey> k; k.instance(); get_key_modifier_state(xkeyevent->state, k); /* Phase 6, determine echo character */ // Echo characters in X11 are a keyrelease and a keypress // one after the other with the (almot) same timestamp. // To detect them, i compare to the next event in list and // check that their difference in time is below a threshold. if (xkeyevent->type != KeyPress) { p_echo = false; // make sure there are events pending, // so this call won't block. if (p_event_index + 1 < p_events.size()) { XEvent &peek_event = p_events[p_event_index + 1]; // I'm using a threshold of 5 msecs, // since sometimes there seems to be a little // jitter. I'm still not convinced that all this approach // is correct, but the xorg developers are // not very helpful today. ::Time tresh = ABSDIFF(peek_event.xkey.time, xkeyevent->time); if (peek_event.type == KeyPress && tresh < 5) { KeySym rk; XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, nullptr); if (rk == keysym_keycode) { // Consume to next event. ++p_event_index; _handle_key_event((XKeyEvent *)&peek_event, p_events, p_event_index, true); return; //ignore current, echo next } } // use the time from peek_event so it always works } // save the time to check for echo when keypress happens } /* Phase 7, send event to Window */ k->set_pressed(keypress); if (keycode >= 'a' && keycode <= 'z') { keycode -= 'a' - 'A'; } k->set_scancode(keycode); k->set_physical_scancode(physical_keycode); k->set_unicode(unicode); k->set_echo(p_echo); if (k->get_scancode() == KEY_BACKTAB) { //make it consistent across platforms. k->set_scancode(KEY_TAB); k->set_physical_scancode(KEY_TAB); k->set_shift(true); } //don't set mod state if modifier keys are released by themselves //else event.is_action() will not work correctly here if (!k->is_pressed()) { if (k->get_scancode() == KEY_SHIFT) { k->set_shift(false); } else if (k->get_scancode() == KEY_CONTROL) { k->set_control(false); } else if (k->get_scancode() == KEY_ALT) { k->set_alt(false); } else if (k->get_scancode() == KEY_META) { k->set_metakey(false); } } bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_scancode()); if (k->is_pressed()) { if (last_is_pressed) { k->set_echo(true); } } //printf("key: %x\n",k->get_scancode()); input->parse_input_event(k); } Atom OS_X11::_process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property) const { if (p_target == XInternAtom(x11_display, "TARGETS", 0)) { // Request to list all supported targets. Atom data[9]; data[0] = XInternAtom(x11_display, "TARGETS", 0); data[1] = XInternAtom(x11_display, "SAVE_TARGETS", 0); data[2] = XInternAtom(x11_display, "MULTIPLE", 0); data[3] = XInternAtom(x11_display, "UTF8_STRING", 0); data[4] = XInternAtom(x11_display, "COMPOUND_TEXT", 0); data[5] = XInternAtom(x11_display, "TEXT", 0); data[6] = XA_STRING; data[7] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0); data[8] = XInternAtom(x11_display, "text/plain", 0); XChangeProperty(x11_display, p_requestor, p_property, XA_ATOM, 32, PropModeReplace, (unsigned char *)&data, sizeof(data) / sizeof(data[0])); return p_property; } else if (p_target == XInternAtom(x11_display, "SAVE_TARGETS", 0)) { // Request to check if SAVE_TARGETS is supported, nothing special to do. XChangeProperty(x11_display, p_requestor, p_property, XInternAtom(x11_display, "NULL", False), 32, PropModeReplace, nullptr, 0); return p_property; } else if (p_target == XInternAtom(x11_display, "UTF8_STRING", 0) || p_target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) || p_target == XInternAtom(x11_display, "TEXT", 0) || p_target == XA_STRING || p_target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) || p_target == XInternAtom(x11_display, "text/plain", 0)) { // Directly using internal clipboard because we know our window // is the owner during a selection request. CharString clip = OS::get_clipboard().utf8(); XChangeProperty(x11_display, p_requestor, p_property, p_target, 8, PropModeReplace, (unsigned char *)clip.get_data(), clip.length()); return p_property; } else { char *target_name = XGetAtomName(x11_display, p_target); printf("Target '%s' not supported.\n", target_name); if (target_name) { XFree(target_name); } return None; } } void OS_X11::_handle_selection_request_event(XSelectionRequestEvent *p_event) const { XEvent respond; if (p_event->target == XInternAtom(x11_display, "MULTIPLE", 0)) { // Request for multiple target conversions at once. Atom atom_pair = XInternAtom(x11_display, "ATOM_PAIR", False); respond.xselection.property = None; Atom type; int format; unsigned long len; unsigned long remaining; unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, p_event->requestor, p_event->property, 0, LONG_MAX, False, atom_pair, &type, &format, &len, &remaining, &data) == Success) { if ((len >= 2) && data) { Atom *targets = (Atom *)data; for (uint64_t i = 0; i < len; i += 2) { Atom target = targets[i]; Atom &property = targets[i + 1]; property = _process_selection_request_target(target, p_event->requestor, property); } XChangeProperty(x11_display, p_event->requestor, p_event->property, atom_pair, 32, PropModeReplace, (unsigned char *)targets, len); respond.xselection.property = p_event->property; } XFree(data); } } else { // Request for target conversion. respond.xselection.property = _process_selection_request_target(p_event->target, p_event->requestor, p_event->property); } respond.xselection.type = SelectionNotify; respond.xselection.display = p_event->display; respond.xselection.requestor = p_event->requestor; respond.xselection.selection = p_event->selection; respond.xselection.target = p_event->target; respond.xselection.time = p_event->time; XSendEvent(x11_display, p_event->requestor, True, NoEventMask, &respond); XFlush(x11_display); } struct Property { unsigned char *data; int format, nitems; Atom type; }; static Property read_property(Display *p_display, Window p_window, Atom p_property) { Atom actual_type = None; int actual_format = 0; unsigned long nitems = 0; unsigned long bytes_after = 0; unsigned char *ret = nullptr; int read_bytes = 1024; //Keep trying to read the property until there are no //bytes unread. if (p_property != None) { do { if (ret != nullptr) { XFree(ret); } XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType, &actual_type, &actual_format, &nitems, &bytes_after, &ret); read_bytes *= 2; } while (bytes_after != 0); } Property p = { ret, actual_format, (int)nitems, actual_type }; return p; } static Atom pick_target_from_list(Display *p_display, Atom *p_list, int p_count) { static const char *target_type = "text/uri-list"; for (int i = 0; i < p_count; i++) { Atom atom = p_list[i]; if (atom != None && String(XGetAtomName(p_display, atom)) == target_type) { return atom; } } return None; } static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) { static const char *target_type = "text/uri-list"; if (p_t1 != None && String(XGetAtomName(p_disp, p_t1)) == target_type) { return p_t1; } if (p_t2 != None && String(XGetAtomName(p_disp, p_t2)) == target_type) { return p_t2; } if (p_t3 != None && String(XGetAtomName(p_disp, p_t3)) == target_type) { return p_t3; } return None; } void OS_X11::_window_changed(XEvent *event) { if (xic) { // Not portable. set_ime_position(Point2(0, 1)); } if ((event->xconfigure.width == current_videomode.width) && (event->xconfigure.height == current_videomode.height)) { return; } current_videomode.width = event->xconfigure.width; current_videomode.height = event->xconfigure.height; } void OS_X11::_poll_events_thread(void *ud) { OS_X11 *os = (OS_X11 *)ud; os->_poll_events(); } Bool OS_X11::_predicate_all_events(Display *display, XEvent *event, XPointer arg) { // Just accept all events. return True; } bool OS_X11::_wait_for_events() const { int x11_fd = ConnectionNumber(x11_display); fd_set in_fds; XFlush(x11_display); FD_ZERO(&in_fds); FD_SET(x11_fd, &in_fds); struct timeval tv; tv.tv_usec = 0; tv.tv_sec = 1; // Wait for next event or timeout. int num_ready_fds = select(x11_fd + 1, &in_fds, nullptr, nullptr, &tv); if (num_ready_fds > 0) { // Event received. return true; } else { // Error or timeout. if (num_ready_fds < 0) { ERR_PRINT("_wait_for_events: select error: " + itos(errno)); } return false; } } void OS_X11::_poll_events() { while (!events_thread_done) { _wait_for_events(); // Process events from the queue. { MutexLock mutex_lock(events_mutex); // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_all_events, nullptr)) { // Check if the input manager wants to process the event. if (XFilterEvent(&ev, None)) { // Event has been filtered by the Input Manager, // it has to be ignored and a new one will be received. continue; } // Handle selection request events directly in the event thread, because // communication through the x server takes several events sent back and forth // and we don't want to block other programs while processing only one each frame. if (ev.type == SelectionRequest) { _handle_selection_request_event(&(ev.xselectionrequest)); continue; } polled_events.push_back(ev); } } } } void OS_X11::process_xevents() { //printf("checking events %i\n", XPending(x11_display)); do_mouse_warp = false; // Is the current mouse mode one where it needs to be grabbed. bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED; xi.pressure = 0; xi.tilt = Vector2(); xi.pressure_supported = false; LocalVector<XEvent> events; { // Block events polling while flushing events. MutexLock mutex_lock(events_mutex); events = polled_events; polled_events.clear(); } for (uint32_t event_index = 0; event_index < events.size(); ++event_index) { XEvent &event = events[event_index]; if (XGetEventData(x11_display, &event.xcookie)) { if (event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) { XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data; int index = event_data->detail; Vector2 pos = Vector2(event_data->event_x, event_data->event_y); switch (event_data->evtype) { case XI_HierarchyChanged: case XI_DeviceChanged: { refresh_device_info(); } break; case XI_RawMotion: { XIRawEvent *raw_event = (XIRawEvent *)event_data; int device_id = raw_event->deviceid; // Determine the axis used (called valuators in XInput for some forsaken reason) // Mask is a bitmask indicating which axes are involved. // We are interested in the values of axes 0 and 1. if (raw_event->valuators.mask_len <= 0) { break; } const double *values = raw_event->raw_values; double rel_x = 0.0; double rel_y = 0.0; if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSX)) { rel_x = *values; values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSY)) { rel_y = *values; values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_PRESSURE)) { Map<int, Vector2>::Element *pen_pressure = xi.pen_pressure_range.find(device_id); if (pen_pressure) { Vector2 pen_pressure_range = pen_pressure->value(); if (pen_pressure_range != Vector2()) { xi.pressure_supported = true; xi.pressure = (*values - pen_pressure_range[0]) / (pen_pressure_range[1] - pen_pressure_range[0]); } } values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTX)) { Map<int, Vector2>::Element *pen_tilt_x = xi.pen_tilt_x_range.find(device_id); if (pen_tilt_x) { Vector2 pen_tilt_x_range = pen_tilt_x->value(); if (pen_tilt_x_range != Vector2()) { xi.tilt.x = ((*values - pen_tilt_x_range[0]) / (pen_tilt_x_range[1] - pen_tilt_x_range[0])) * 2 - 1; } } values++; } if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTY)) { Map<int, Vector2>::Element *pen_tilt_y = xi.pen_tilt_y_range.find(device_id); if (pen_tilt_y) { Vector2 pen_tilt_y_range = pen_tilt_y->value(); if (pen_tilt_y_range != Vector2()) { xi.tilt.y = ((*values - pen_tilt_y_range[0]) / (pen_tilt_y_range[1] - pen_tilt_y_range[0])) * 2 - 1; } } values++; } // https://bugs.freedesktop.org/show_bug.cgi?id=71609 // http://lists.libsdl.org/pipermail/commits-libsdl.org/2015-June/000282.html if (raw_event->time == xi.last_relative_time && rel_x == xi.relative_motion.x && rel_y == xi.relative_motion.y) { break; // Flush duplicate to avoid overly fast motion } xi.old_raw_pos.x = xi.raw_pos.x; xi.old_raw_pos.y = xi.raw_pos.y; xi.raw_pos.x = rel_x; xi.raw_pos.y = rel_y; Map<int, Vector2>::Element *abs_info = xi.absolute_devices.find(device_id); if (abs_info) { // Absolute mode device Vector2 mult = abs_info->value(); xi.relative_motion.x += (xi.raw_pos.x - xi.old_raw_pos.x) * mult.x; xi.relative_motion.y += (xi.raw_pos.y - xi.old_raw_pos.y) * mult.y; } else { // Relative mode device xi.relative_motion.x = xi.raw_pos.x; xi.relative_motion.y = xi.raw_pos.y; } xi.last_relative_time = raw_event->time; } break; #ifdef TOUCH_ENABLED case XI_TouchBegin: // Fall-through // Disabled hand-in-hand with the grabbing //XIAllowTouchEvents(x11_display, event_data->deviceid, event_data->detail, x11_window, XIAcceptTouch); case XI_TouchEnd: { bool is_begin = event_data->evtype == XI_TouchBegin; Ref<InputEventScreenTouch> st; st.instance(); st->set_index(index); st->set_position(pos); st->set_pressed(is_begin); if (is_begin) { if (xi.state.has(index)) { // Defensive break; } xi.state[index] = pos; if (xi.state.size() == 1) { // X11 may send a motion event when a touch gesture begins, that would result // in a spurious mouse motion event being sent to Godot; remember it to be able to filter it out xi.mouse_pos_to_filter = pos; } input->parse_input_event(st); } else { if (!xi.state.has(index)) { // Defensive break; } xi.state.erase(index); input->parse_input_event(st); } } break; case XI_TouchUpdate: { Map<int, Vector2>::Element *curr_pos_elem = xi.state.find(index); if (!curr_pos_elem) { // Defensive break; } if (curr_pos_elem->value() != pos) { Ref<InputEventScreenDrag> sd; sd.instance(); sd->set_index(index); sd->set_position(pos); sd->set_relative(pos - curr_pos_elem->value()); input->parse_input_event(sd); curr_pos_elem->value() = pos; } } break; #endif } } } XFreeEventData(x11_display, &event.xcookie); switch (event.type) { case Expose: Main::force_redraw(); break; case NoExpose: minimized = true; break; case VisibilityNotify: { XVisibilityEvent *visibility = (XVisibilityEvent *)&event; minimized = (visibility->state == VisibilityFullyObscured); } break; case LeaveNotify: { if (main_loop && !mouse_mode_grab) { main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT); } } break; case EnterNotify: { if (main_loop && !mouse_mode_grab) { main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER); } } break; case FocusIn: minimized = false; window_has_focus = true; main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); window_focused = true; if (mouse_mode_grab) { // Show and update the cursor if confined and the window regained focus. if (mouse_mode == MOUSE_MODE_CONFINED) { XUndefineCursor(x11_display, x11_window); } else if (mouse_mode == MOUSE_MODE_CAPTURED) { // or re-hide it in captured mode XDefineCursor(x11_display, x11_window, null_cursor); } XGrabPointer( x11_display, x11_window, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime); } #ifdef TOUCH_ENABLED // Grab touch devices to avoid OS gesture interference /*for (int i = 0; i < xi.touch_devices.size(); ++i) { XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask); }*/ #endif if (xic) { // Block events polling while changing input focus // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XSetICFocus(xic); } break; case FocusOut: window_has_focus = false; input->release_pressed_events(); main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); window_focused = false; if (mouse_mode_grab) { //dear X11, I try, I really try, but you never work, you do whathever you want. if (mouse_mode == MOUSE_MODE_CAPTURED) { // Show the cursor if we're in captured mode so it doesn't look weird. XUndefineCursor(x11_display, x11_window); } XUngrabPointer(x11_display, CurrentTime); } #ifdef TOUCH_ENABLED // Ungrab touch devices so input works as usual while we are unfocused /*for (int i = 0; i < xi.touch_devices.size(); ++i) { XIUngrabDevice(x11_display, xi.touch_devices[i], CurrentTime); }*/ // Release every pointer to avoid sticky points for (Map<int, Vector2>::Element *E = xi.state.front(); E; E = E->next()) { Ref<InputEventScreenTouch> st; st.instance(); st->set_index(E->key()); st->set_position(E->get()); input->parse_input_event(st); } xi.state.clear(); #endif if (xic) { // Block events polling while changing input focus // because it triggers some event polling internally. MutexLock mutex_lock(events_mutex); XUnsetICFocus(xic); } break; case ConfigureNotify: _window_changed(&event); break; case ButtonPress: case ButtonRelease: { /* exit in case of a mouse button press */ last_timestamp = event.xbutton.time; if (mouse_mode == MOUSE_MODE_CAPTURED) { event.xbutton.x = last_mouse_pos.x; event.xbutton.y = last_mouse_pos.y; } Ref<InputEventMouseButton> mb; mb.instance(); get_key_modifier_state(event.xbutton.state, mb); mb->set_button_index(event.xbutton.button); if (mb->get_button_index() == 2) { mb->set_button_index(3); } else if (mb->get_button_index() == 3) { mb->set_button_index(2); } mb->set_button_mask(get_mouse_button_state(mb->get_button_index(), event.xbutton.type)); mb->set_position(Vector2(event.xbutton.x, event.xbutton.y)); mb->set_global_position(mb->get_position()); mb->set_pressed((event.type == ButtonPress)); if (event.type == ButtonPress) { uint64_t diff = get_ticks_usec() / 1000 - last_click_ms; if (mb->get_button_index() == last_click_button_index) { if (diff < 400 && Point2(last_click_pos).distance_to(Point2(event.xbutton.x, event.xbutton.y)) < 5) { last_click_ms = 0; last_click_pos = Point2(-100, -100); last_click_button_index = -1; mb->set_doubleclick(true); } } else if (mb->get_button_index() < 4 || mb->get_button_index() > 7) { last_click_button_index = mb->get_button_index(); } if (!mb->is_doubleclick()) { last_click_ms += diff; last_click_pos = Point2(event.xbutton.x, event.xbutton.y); } } input->parse_input_event(mb); } break; case MotionNotify: { // The X11 API requires filtering one-by-one through the motion // notify events, in order to figure out which event is the one // generated by warping the mouse pointer. while (true) { if (mouse_mode == MOUSE_MODE_CAPTURED && event.xmotion.x == current_videomode.width / 2 && event.xmotion.y == current_videomode.height / 2) { //this is likely the warp event since it was warped here center = Vector2(event.xmotion.x, event.xmotion.y); break; } if (event_index + 1 < events.size()) { const XEvent &next_event = events[event_index + 1]; if (next_event.type == MotionNotify) { ++event_index; event = next_event; } else { break; } } else { break; } } last_timestamp = event.xmotion.time; // Motion is also simple. // A little hack is in order // to be able to send relative motion events. Point2 pos(event.xmotion.x, event.xmotion.y); // Avoidance of spurious mouse motion (see handling of touch) bool filter = false; // Adding some tolerance to match better Point2i to Vector2 if (xi.state.size() && Vector2(pos).distance_squared_to(xi.mouse_pos_to_filter) < 2) { filter = true; } // Invalidate to avoid filtering a possible legitimate similar event coming later xi.mouse_pos_to_filter = Vector2(1e10, 1e10); if (filter) { break; } if (mouse_mode == MOUSE_MODE_CAPTURED) { if (xi.relative_motion.x == 0 && xi.relative_motion.y == 0) { break; } Point2i new_center = pos; pos = last_mouse_pos + xi.relative_motion; center = new_center; do_mouse_warp = window_has_focus; // warp the cursor if we're focused in } if (!last_mouse_pos_valid) { last_mouse_pos = pos; last_mouse_pos_valid = true; } // Hackish but relative mouse motion is already handled in the RawMotion event. // RawMotion does not provide the absolute mouse position (whereas MotionNotify does). // Therefore, RawMotion cannot be the authority on absolute mouse position. // RawMotion provides more precision than MotionNotify, which doesn't sense subpixel motion. // Therefore, MotionNotify cannot be the authority on relative mouse motion. // This means we need to take a combined approach... Point2 rel; // Only use raw input if in capture mode. Otherwise use the classic behavior. if (mouse_mode == MOUSE_MODE_CAPTURED) { rel = xi.relative_motion; } else { rel = pos - last_mouse_pos; } // Reset to prevent lingering motion xi.relative_motion.x = 0; xi.relative_motion.y = 0; if (mouse_mode == MOUSE_MODE_CAPTURED) { pos = Point2i(current_videomode.width / 2, current_videomode.height / 2); } Ref<InputEventMouseMotion> mm; mm.instance(); if (xi.pressure_supported) { mm->set_pressure(xi.pressure); } else { mm->set_pressure((get_mouse_button_state() & (1 << (BUTTON_LEFT - 1))) ? 1.0f : 0.0f); } mm->set_tilt(xi.tilt); // Make the absolute position integral so it doesn't look _too_ weird :) Point2i posi(pos); get_key_modifier_state(event.xmotion.state, mm); mm->set_button_mask(get_mouse_button_state()); mm->set_position(posi); mm->set_global_position(posi); input->set_mouse_position(posi); mm->set_speed(input->get_last_mouse_speed()); mm->set_relative(rel); last_mouse_pos = pos; // printf("rel: %d,%d\n", rel.x, rel.y ); // Don't propagate the motion event unless we have focus // this is so that the relative motion doesn't get messed up // after we regain focus. if (window_has_focus || !mouse_mode_grab) { input->parse_input_event(mm); } } break; case KeyPress: case KeyRelease: { last_timestamp = event.xkey.time; // key event is a little complex, so // it will be handled in its own function. _handle_key_event((XKeyEvent *)&event, events, event_index); } break; case SelectionNotify: if (event.xselection.target == requested) { Property p = read_property(x11_display, x11_window, XInternAtom(x11_display, "PRIMARY", 0)); Vector<String> files = String((char *)p.data).split("\n", false); for (int i = 0; i < files.size(); i++) { files.write[i] = files[i].replace("file://", "").http_unescape().strip_edges(); } main_loop->drop_files(files); //Reply that all is well. XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = x11_display; m.window = xdnd_source_window; m.message_type = xdnd_finished; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = 1; m.data.l[2] = xdnd_action_copy; //We only ever copy. XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m); } break; case ClientMessage: if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete) { main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST); } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) { //File(s) have been dragged over the window, check for supported target (text/uri-list) xdnd_version = (event.xclient.data.l[1] >> 24); Window source = event.xclient.data.l[0]; bool more_than_3 = event.xclient.data.l[1] & 1; if (more_than_3) { Property p = read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False)); requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems); } else { requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]); } } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) { //xdnd position event, reply with an XDND status message //just depending on type of data for now XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = event.xclient.display; m.window = event.xclient.data.l[0]; m.message_type = xdnd_status; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = (requested != None); m.data.l[2] = 0; //empty rectangle m.data.l[3] = 0; m.data.l[4] = xdnd_action_copy; XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m); XFlush(x11_display); } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) { if (requested != None) { xdnd_source_window = event.xclient.data.l[0]; if (xdnd_version >= 1) { XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, event.xclient.data.l[2]); } else { XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, CurrentTime); } } else { //Reply that we're not interested. XClientMessageEvent m; memset(&m, 0, sizeof(m)); m.type = ClientMessage; m.display = event.xclient.display; m.window = event.xclient.data.l[0]; m.message_type = xdnd_finished; m.format = 32; m.data.l[0] = x11_window; m.data.l[1] = 0; m.data.l[2] = None; //Failed. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m); } } break; default: break; } } XFlush(x11_display); if (do_mouse_warp) { XWarpPointer(x11_display, None, x11_window, 0, 0, 0, 0, (int)current_videomode.width / 2, (int)current_videomode.height / 2); /* Window root, child; int root_x, root_y; int win_x, win_y; unsigned int mask; XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask ); printf("Root: %d,%d\n", root_x, root_y); printf("Win: %d,%d\n", win_x, win_y); */ } input->flush_buffered_events(); } MainLoop *OS_X11::get_main_loop() const { return main_loop; } void OS_X11::delete_main_loop() { // Send owned clipboard data to clipboard manager before exit. // This has to be done here because the clipboard data is cleared before finalize(). _clipboard_transfer_ownership(XA_PRIMARY, x11_window); _clipboard_transfer_ownership(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window); if (main_loop) { memdelete(main_loop); } main_loop = nullptr; } void OS_X11::set_main_loop(MainLoop *p_main_loop) { main_loop = p_main_loop; input->set_main_loop(p_main_loop); } bool OS_X11::can_draw() const { return !minimized; }; void OS_X11::set_clipboard(const String &p_text) { { // The clipboard content can be accessed while polling for events. MutexLock mutex_lock(events_mutex); OS::set_clipboard(p_text); } XSetSelectionOwner(x11_display, XA_PRIMARY, x11_window, CurrentTime); XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), x11_window, CurrentTime); }; Bool OS_X11::_predicate_clipboard_selection(Display *display, XEvent *event, XPointer arg) { if (event->type == SelectionNotify && event->xselection.requestor == *(Window *)arg) { return True; } else { return False; } } Bool OS_X11::_predicate_clipboard_incr(Display *display, XEvent *event, XPointer arg) { if (event->type == PropertyNotify && event->xproperty.state == PropertyNewValue) { return True; } else { return False; } } String OS_X11::_get_clipboard_impl(Atom p_source, Window x11_window, Atom target) const { String ret; Window selection_owner = XGetSelectionOwner(x11_display, p_source); if (selection_owner == x11_window) { return OS::get_clipboard(); } if (selection_owner != None) { // Block events polling while processing selection events. MutexLock mutex_lock(events_mutex); Atom selection = XA_PRIMARY; XConvertSelection(x11_display, p_source, target, selection, x11_window, CurrentTime); XFlush(x11_display); // Blocking wait for predicate to be True and remove the event from the queue. XEvent event; XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window); // Do not get any data, see how much data is there. Atom type; int format, result; unsigned long len, bytes_left, dummy; unsigned char *data; XGetWindowProperty(x11_display, x11_window, selection, // Tricky.. 0, 0, // offset - len 0, // Delete 0==FALSE AnyPropertyType, // flag &type, // return type &format, // return format &len, &bytes_left, // data length &data); if (data) { XFree(data); } if (type == XInternAtom(x11_display, "INCR", 0)) { // Data is going to be received incrementally. LocalVector<uint8_t> incr_data; uint32_t data_size = 0; bool success = false; // Delete INCR property to notify the owner. XDeleteProperty(x11_display, x11_window, type); // Process events from the queue. bool done = false; while (!done) { if (!_wait_for_events()) { // Error or timeout, abort. break; } // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, nullptr)) { result = XGetWindowProperty(x11_display, x11_window, selection, // selection type 0, LONG_MAX, // offset - len True, // delete property to notify the owner AnyPropertyType, // flag &type, // return type &format, // return format &len, &bytes_left, // data length &data); if (result == Success) { if (data && (len > 0)) { uint32_t prev_size = incr_data.size(); if (prev_size == 0) { // First property contains initial data size. unsigned long initial_size = *(unsigned long *)data; incr_data.resize(initial_size); } else { // New chunk, resize to be safe and append data. incr_data.resize(MAX(data_size + len, prev_size)); memcpy(incr_data.ptr() + data_size, data, len); data_size += len; } } else { // Last chunk, process finished. done = true; success = true; } } else { printf("Failed to get selection data chunk.\n"); done = true; } if (data) { XFree(data); } if (done) { break; } } } if (success && (data_size > 0)) { ret.parse_utf8((const char *)incr_data.ptr(), data_size); } } else if (bytes_left > 0) { // Data is ready and can be processed all at once. result = XGetWindowProperty(x11_display, x11_window, selection, 0, bytes_left, 0, AnyPropertyType, &type, &format, &len, &dummy, &data); if (result == Success) { ret.parse_utf8((const char *)data); } else { printf("Failed to get selection data.\n"); } if (data) { XFree(data); } } } return ret; } String OS_X11::_get_clipboard(Atom p_source, Window x11_window) const { String ret; Atom utf8_atom = XInternAtom(x11_display, "UTF8_STRING", True); if (utf8_atom != None) { ret = _get_clipboard_impl(p_source, x11_window, utf8_atom); } if (ret.empty()) { ret = _get_clipboard_impl(p_source, x11_window, XA_STRING); } return ret; } String OS_X11::get_clipboard() const { String ret; ret = _get_clipboard(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window); if (ret.empty()) { ret = _get_clipboard(XA_PRIMARY, x11_window); }; return ret; } Bool OS_X11::_predicate_clipboard_save_targets(Display *display, XEvent *event, XPointer arg) { if (event->xany.window == *(Window *)arg) { return (event->type == SelectionRequest) || (event->type == SelectionNotify); } else { return False; } } void OS_X11::_clipboard_transfer_ownership(Atom p_source, Window x11_window) const { Window selection_owner = XGetSelectionOwner(x11_display, p_source); if (selection_owner != x11_window) { return; } // Block events polling while processing selection events. MutexLock mutex_lock(events_mutex); Atom clipboard_manager = XInternAtom(x11_display, "CLIPBOARD_MANAGER", False); Atom save_targets = XInternAtom(x11_display, "SAVE_TARGETS", False); XConvertSelection(x11_display, clipboard_manager, save_targets, None, x11_window, CurrentTime); // Process events from the queue. while (true) { if (!_wait_for_events()) { // Error or timeout, abort. break; } // Non-blocking wait for next event and remove it from the queue. XEvent ev; while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_save_targets, (XPointer)&x11_window)) { switch (ev.type) { case SelectionRequest: _handle_selection_request_event(&(ev.xselectionrequest)); break; case SelectionNotify: { if (ev.xselection.target == save_targets) { // Once SelectionNotify is received, we're done whether it succeeded or not. return; } break; } } } } } String OS_X11::get_name() const { return "X11"; } Error OS_X11::shell_open(String p_uri) { Error ok; int err_code; List<String> args; args.push_back(p_uri); // Agnostic ok = execute("xdg-open", args, true, nullptr, nullptr, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } // GNOME args.push_front("open"); // The command is `gio open`, so we need to add it to args ok = execute("gio", args, true, nullptr, nullptr, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } args.pop_front(); ok = execute("gvfs-open", args, true, nullptr, nullptr, &err_code); if (ok == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } // KDE ok = execute("kde-open5", args, true, nullptr, nullptr, &err_code); if (ok == OK && !err_code) { return OK; } ok = execute("kde-open", args, true, nullptr, nullptr, &err_code); return !err_code ? ok : FAILED; } bool OS_X11::_check_internal_feature_support(const String &p_feature) { return p_feature == "pc"; } String OS_X11::get_config_path() const { if (has_environment("XDG_CONFIG_HOME")) { if (get_environment("XDG_CONFIG_HOME").is_abs_path()) { return get_environment("XDG_CONFIG_HOME"); } else { WARN_PRINT_ONCE("`XDG_CONFIG_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.config` or `.` per the XDG Base Directory specification."); } } if (has_environment("HOME")) { return get_environment("HOME").plus_file(".config"); } return "."; } String OS_X11::get_data_path() const { if (has_environment("XDG_DATA_HOME")) { if (get_environment("XDG_DATA_HOME").is_abs_path()) { return get_environment("XDG_DATA_HOME"); } else { WARN_PRINT_ONCE("`XDG_DATA_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.local/share` or `get_config_path()` per the XDG Base Directory specification."); } } if (has_environment("HOME")) { return get_environment("HOME").plus_file(".local/share"); } return get_config_path(); } String OS_X11::get_cache_path() const { if (has_environment("XDG_CACHE_HOME")) { if (get_environment("XDG_CACHE_HOME").is_abs_path()) { return get_environment("XDG_CACHE_HOME"); } else { WARN_PRINT_ONCE("`XDG_CACHE_HOME` is a relative path. Ignoring its value and falling back to `$HOME/.cache` or `get_config_path()` per the XDG Base Directory specification."); } } if (has_environment("HOME")) { return get_environment("HOME").plus_file(".cache"); } return get_config_path(); } String OS_X11::get_system_dir(SystemDir p_dir, bool p_shared_storage) const { String xdgparam; switch (p_dir) { case SYSTEM_DIR_DESKTOP: { xdgparam = "DESKTOP"; } break; case SYSTEM_DIR_DCIM: { xdgparam = "PICTURES"; } break; case SYSTEM_DIR_DOCUMENTS: { xdgparam = "DOCUMENTS"; } break; case SYSTEM_DIR_DOWNLOADS: { xdgparam = "DOWNLOAD"; } break; case SYSTEM_DIR_MOVIES: { xdgparam = "VIDEOS"; } break; case SYSTEM_DIR_MUSIC: { xdgparam = "MUSIC"; } break; case SYSTEM_DIR_PICTURES: { xdgparam = "PICTURES"; } break; case SYSTEM_DIR_RINGTONES: { xdgparam = "MUSIC"; } break; } String pipe; List<String> arg; arg.push_back(xdgparam); Error err = const_cast<OS_X11 *>(this)->execute("xdg-user-dir", arg, true, nullptr, &pipe); if (err != OK) { return "."; } return pipe.strip_edges(); } void OS_X11::move_window_to_foreground() { XEvent xev; Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = net_active_window; xev.xclient.format = 32; xev.xclient.data.l[0] = 1; xev.xclient.data.l[1] = CurrentTime; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(x11_display); } void OS_X11::set_cursor_shape(CursorShape p_shape) { ERR_FAIL_INDEX(p_shape, CURSOR_MAX); if (p_shape == current_cursor) { return; } if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) { if (cursors[p_shape] != None) { XDefineCursor(x11_display, x11_window, cursors[p_shape]); } else if (cursors[CURSOR_ARROW] != None) { XDefineCursor(x11_display, x11_window, cursors[CURSOR_ARROW]); } } current_cursor = p_shape; } OS::CursorShape OS_X11::get_cursor_shape() const { return current_cursor; } void OS_X11::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) { if (p_cursor.is_valid()) { Map<CursorShape, Vector<Variant>>::Element *cursor_c = cursors_cache.find(p_shape); if (cursor_c) { if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) { set_cursor_shape(p_shape); return; } cursors_cache.erase(p_shape); } Ref<Texture> texture = p_cursor; Ref<AtlasTexture> atlas_texture = p_cursor; Ref<Image> image; Size2 texture_size; Rect2 atlas_rect; if (texture.is_valid()) { image = texture->get_data(); } if (!image.is_valid() && atlas_texture.is_valid()) { texture = atlas_texture->get_atlas(); atlas_rect.size.width = texture->get_width(); atlas_rect.size.height = texture->get_height(); atlas_rect.position.x = atlas_texture->get_region().position.x; atlas_rect.position.y = atlas_texture->get_region().position.y; texture_size.width = atlas_texture->get_region().size.x; texture_size.height = atlas_texture->get_region().size.y; } else if (image.is_valid()) { texture_size.width = texture->get_width(); texture_size.height = texture->get_height(); } ERR_FAIL_COND(!texture.is_valid()); ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0); ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256); ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height); image = texture->get_data(); ERR_FAIL_COND(!image.is_valid()); // Create the cursor structure XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height); XcursorUInt image_size = texture_size.width * texture_size.height; XcursorDim size = sizeof(XcursorPixel) * image_size; cursor_image->version = 1; cursor_image->size = size; cursor_image->xhot = p_hotspot.x; cursor_image->yhot = p_hotspot.y; // allocate memory to contain the whole file cursor_image->pixels = (XcursorPixel *)memalloc(size); image->lock(); for (XcursorPixel index = 0; index < image_size; index++) { int row_index = floor(index / texture_size.width) + atlas_rect.position.y; int column_index = (index % int(texture_size.width)) + atlas_rect.position.x; if (atlas_texture.is_valid()) { column_index = MIN(column_index, atlas_rect.size.width - 1); row_index = MIN(row_index, atlas_rect.size.height - 1); } *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32(); } image->unlock(); ERR_FAIL_COND(cursor_image->pixels == nullptr); // Save it for a further usage cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image); Vector<Variant> params; params.push_back(p_cursor); params.push_back(p_hotspot); cursors_cache.insert(p_shape, params); if (p_shape == current_cursor) { if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) { XDefineCursor(x11_display, x11_window, cursors[p_shape]); } } memfree(cursor_image->pixels); XcursorImageDestroy(cursor_image); } else { // Reset to default system cursor if (img[p_shape]) { cursors[p_shape] = XcursorImageLoadCursor(x11_display, img[p_shape]); } CursorShape c = current_cursor; current_cursor = CURSOR_MAX; set_cursor_shape(c); cursors_cache.erase(p_shape); } } void OS_X11::release_rendering_thread() { #if defined(OPENGL_ENABLED) context_gl->release_current(); #endif } void OS_X11::make_rendering_thread() { #if defined(OPENGL_ENABLED) context_gl->make_current(); #endif } void OS_X11::swap_buffers() { #if defined(OPENGL_ENABLED) context_gl->swap_buffers(); #endif } void OS_X11::alert(const String &p_alert, const String &p_title) { if (is_no_window_mode_enabled()) { print_line("ALERT: " + p_title + ": " + p_alert); return; } const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" }; String path = get_environment("PATH"); Vector<String> path_elems = path.split(":", false); String program; for (int i = 0; i < path_elems.size(); i++) { for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) { String tested_path = path_elems[i].plus_file(message_programs[k]); if (FileAccess::exists(tested_path)) { program = tested_path; break; } } if (program.length()) { break; } } List<String> args; if (program.ends_with("zenity")) { args.push_back("--error"); args.push_back("--width"); args.push_back("500"); args.push_back("--title"); args.push_back(p_title); args.push_back("--text"); args.push_back(p_alert); } if (program.ends_with("kdialog")) { args.push_back("--error"); args.push_back(p_alert); args.push_back("--title"); args.push_back(p_title); } if (program.ends_with("Xdialog")) { args.push_back("--title"); args.push_back(p_title); args.push_back("--msgbox"); args.push_back(p_alert); args.push_back("0"); args.push_back("0"); } if (program.ends_with("xmessage")) { args.push_back("-center"); args.push_back("-title"); args.push_back(p_title); args.push_back(p_alert); } if (program.length()) { execute(program, args, true); } else { print_line(p_alert); } } bool g_set_icon_error = false; int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) { g_set_icon_error = true; return 0; } void OS_X11::set_icon(const Ref<Image> &p_icon) { int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler); Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False); if (p_icon.is_valid()) { Ref<Image> img = p_icon->duplicate(); img->convert(Image::FORMAT_RGBA8); while (true) { int w = img->get_width(); int h = img->get_height(); if (g_set_icon_error) { g_set_icon_error = false; WARN_PRINT("Icon too large, attempting to resize icon."); int new_width, new_height; if (w > h) { new_width = w / 2; new_height = h * new_width / w; } else { new_height = h / 2; new_width = w * new_height / h; } w = new_width; h = new_height; if (!w || !h) { WARN_PRINT("Unable to set icon."); break; } img->resize(w, h, Image::INTERPOLATE_CUBIC); } // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits Vector<long> pd; pd.resize(2 + w * h); pd.write[0] = w; pd.write[1] = h; PoolVector<uint8_t>::Read r = img->get_data().read(); long *wr = &pd.write[2]; uint8_t const *pr = r.ptr(); for (int i = 0; i < w * h; i++) { long v = 0; // A R G B v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2]; *wr++ = v; pr += 4; } if (net_wm_icon != None) { XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size()); } if (!g_set_icon_error) { break; } } } else { XDeleteProperty(x11_display, x11_window, net_wm_icon); } XFlush(x11_display); XSetErrorHandler(oldHandler); } void OS_X11::force_process_input() { process_xevents(); // get rid of pending events #ifdef JOYDEV_ENABLED joypad->process_joypads(); #endif } void OS_X11::run() { force_quit = false; if (!main_loop) { return; } main_loop->init(); //uint64_t last_ticks=get_ticks_usec(); //int frames=0; //uint64_t frame=0; while (!force_quit) { process_xevents(); // get rid of pending events #ifdef JOYDEV_ENABLED joypad->process_joypads(); #endif if (Main::iteration()) { break; } }; main_loop->finish(); } bool OS_X11::is_joy_known(int p_device) { return input->is_joy_mapped(p_device); } String OS_X11::get_joy_guid(int p_device) const { return input->get_joy_guid_remapped(p_device); } void OS_X11::_set_use_vsync(bool p_enable) { #if defined(OPENGL_ENABLED) if (context_gl) { context_gl->set_use_vsync(p_enable); } #endif } /* bool OS_X11::is_vsync_enabled() const { if (context_gl) return context_gl->is_using_vsync(); return true; } */ void OS_X11::set_context(int p_context) { XClassHint *classHint = XAllocClassHint(); if (classHint) { CharString name_str; switch (p_context) { case CONTEXT_EDITOR: name_str = "Godot_Editor"; break; case CONTEXT_PROJECTMAN: name_str = "Godot_ProjectList"; break; case CONTEXT_ENGINE: name_str = "Godot_Engine"; break; } CharString class_str; if (p_context == CONTEXT_ENGINE) { String config_name = GLOBAL_GET("application/config/name"); if (config_name.length() == 0) { class_str = "Godot_Engine"; } else { class_str = config_name.utf8(); } } else { class_str = "Godot"; } classHint->res_class = class_str.ptrw(); classHint->res_name = name_str.ptrw(); XSetClassHint(x11_display, x11_window, classHint); XFree(classHint); } } OS::PowerState OS_X11::get_power_state() { return power_manager->get_power_state(); } int OS_X11::get_power_seconds_left() { return power_manager->get_power_seconds_left(); } int OS_X11::get_power_percent_left() { return power_manager->get_power_percent_left(); } void OS_X11::disable_crash_handler() { crash_handler.disable(); } bool OS_X11::is_disable_crash_handler() const { return crash_handler.is_disabled(); } static String get_mountpoint(const String &p_path) { struct stat s; if (stat(p_path.utf8().get_data(), &s)) { return ""; } #ifdef HAVE_MNTENT dev_t dev = s.st_dev; FILE *fd = setmntent("/proc/mounts", "r"); if (!fd) { return ""; } struct mntent mnt; char buf[1024]; size_t buflen = 1024; while (getmntent_r(fd, &mnt, buf, buflen)) { if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) { endmntent(fd); return String(mnt.mnt_dir); } } endmntent(fd); #endif return ""; } Error OS_X11::move_to_trash(const String &p_path) { int err_code; List<String> args; args.push_back(p_path); args.push_front("trash"); // The command is `gio trash <file_name>` so we need to add it to args. Error result = execute("gio", args, true, nullptr, nullptr, &err_code); // For GNOME based machines. if (result == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } args.pop_front(); args.push_front("move"); args.push_back("trash:/"); // The command is `kioclient5 move <file_name> trash:/`. result = execute("kioclient5", args, true, nullptr, nullptr, &err_code); // For KDE based machines. if (result == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } args.pop_front(); args.pop_back(); result = execute("gvfs-trash", args, true, nullptr, nullptr, &err_code); // For older Linux machines. if (result == OK && !err_code) { return OK; } else if (err_code == 2) { return ERR_FILE_NOT_FOUND; } // If the commands `kioclient5`, `gio` or `gvfs-trash` don't exist on the system we do it manually. String trash_path = ""; String mnt = get_mountpoint(p_path); // If there is a directory "[Mountpoint]/.Trash-[UID], use it as the trash can. if (mnt != "") { String path(mnt + "/.Trash-" + itos(getuid())); struct stat s; if (!stat(path.utf8().get_data(), &s)) { trash_path = path; } } // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash" as the trash can. if (trash_path == "") { char *dhome = getenv("XDG_DATA_HOME"); if (dhome) { trash_path = String(dhome) + "/Trash"; } } // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash" as the trash can. if (trash_path == "") { char *home = getenv("HOME"); if (home) { trash_path = String(home) + "/.local/share/Trash"; } } // Issue an error if none of the previous locations is appropriate for the trash can. ERR_FAIL_COND_V_MSG(trash_path == "", FAILED, "Could not determine the trash can location"); // Create needed directories for decided trash can location. { DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); Error err = dir_access->make_dir_recursive(trash_path); // Issue an error if trash can is not created proprely. ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\""); err = dir_access->make_dir_recursive(trash_path + "/files"); ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"/files"); err = dir_access->make_dir_recursive(trash_path + "/info"); ERR_FAIL_COND_V_MSG(err != OK, err, "Could not create the trash path \"" + trash_path + "\"/info"); memdelete(dir_access); } // The trash can is successfully created, now we check that we don't exceed our file name length limit. // If the file name is too long trim it so we can add the identifying number and ".trashinfo". // Assumes that the file name length limit is 255 characters. String file_name = p_path.get_file(); if (file_name.length() == 0) { file_name = p_path.get_base_dir().get_file(); } if (file_name.length() > 240) { file_name = file_name.substr(0, file_name.length() - 15); } String dest_path = trash_path + "/files/" + file_name; struct stat buff; int id_number = 0; String fn = file_name; // Checks if a resource with the same name already exist in the trash can, // if there is, add an identifying number to our resource's name. while (stat(dest_path.utf8().get_data(), &buff) == 0) { id_number++; // Added a limit to check for identically named files already on the trash can // if there are too many it could make the editor unresponsive. ERR_FAIL_COND_V_MSG(id_number > 99, FAILED, "Too many identically named resources already in the trash can."); fn = file_name + "." + itos(id_number); dest_path = trash_path + "/files/" + fn; } file_name = fn; // Generates the .trashinfo file OS::Date date = OS::get_singleton()->get_date(false); OS::Time time = OS::get_singleton()->get_time(false); String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", date.year, (int)date.month, date.day, time.hour, time.min); timestamp = vformat("%s%02d", timestamp, time.sec); // vformat only supports up to 6 arguments. String trash_info = "[Trash Info]\nPath=" + p_path.http_escape() + "\nDeletionDate=" + timestamp + "\n"; { Error err; FileAccess *file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err); ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file:" + trash_path + "/info/" + file_name + ".trashinfo"); file->store_string(trash_info); file->close(); // Rename our resource before moving it to the trash can. DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); err = dir_access->rename(p_path, p_path.get_base_dir() + "/" + file_name); ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + p_path + "\""); memdelete(dir_access); } // Move the given resource to the trash can. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints. List<String> mv_args; mv_args.push_back(p_path.get_base_dir() + "/" + file_name); mv_args.push_back(trash_path + "/files"); { int retval; Error err = execute("mv", mv_args, true, nullptr, nullptr, &retval); // Issue an error if "mv" failed to move the given resource to the trash can. if (err != OK || retval != 0) { ERR_PRINT("move_to_trash: Could not move the resource \"" + p_path + "\" to the trash can \"" + trash_path + "/files\""); DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); err = dir_access->rename(p_path.get_base_dir() + "/" + file_name, p_path); memdelete(dir_access); ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename " + p_path.get_base_dir() + "/" + file_name + " back to its original name:" + p_path); return FAILED; } } return OK; } OS::LatinKeyboardVariant OS_X11::get_latin_keyboard_variant() const { XkbDescRec *xkbdesc = XkbAllocKeyboard(); ERR_FAIL_COND_V(!xkbdesc, LATIN_KEYBOARD_QWERTY); XkbGetNames(x11_display, XkbSymbolsNameMask, xkbdesc); ERR_FAIL_COND_V(!xkbdesc->names, LATIN_KEYBOARD_QWERTY); ERR_FAIL_COND_V(!xkbdesc->names->symbols, LATIN_KEYBOARD_QWERTY); char *layout = XGetAtomName(x11_display, xkbdesc->names->symbols); ERR_FAIL_COND_V(!layout, LATIN_KEYBOARD_QWERTY); Vector<String> info = String(layout).split("+"); ERR_FAIL_INDEX_V(1, info.size(), LATIN_KEYBOARD_QWERTY); if (info[1].find("colemak") != -1) { return LATIN_KEYBOARD_COLEMAK; } else if (info[1].find("qwertz") != -1) { return LATIN_KEYBOARD_QWERTZ; } else if (info[1].find("azerty") != -1) { return LATIN_KEYBOARD_AZERTY; } else if (info[1].find("qzerty") != -1) { return LATIN_KEYBOARD_QZERTY; } else if (info[1].find("dvorak") != -1) { return LATIN_KEYBOARD_DVORAK; } else if (info[1].find("neo") != -1) { return LATIN_KEYBOARD_NEO; } return LATIN_KEYBOARD_QWERTY; } int OS_X11::keyboard_get_layout_count() const { int _group_count = 0; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); const Atom *groups = kbd->names->groups; if (kbd->ctrls != nullptr) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } XkbFreeKeyboard(kbd, 0, true); } return _group_count; } int OS_X11::keyboard_get_current_layout() const { XkbStateRec state; XkbGetState(x11_display, XkbUseCoreKbd, &state); return state.group; } void OS_X11::keyboard_set_current_layout(int p_index) { ERR_FAIL_INDEX(p_index, keyboard_get_layout_count()); XkbLockGroup(x11_display, XkbUseCoreKbd, p_index); } String OS_X11::keyboard_get_layout_language(int p_index) const { String ret; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); XkbGetNames(x11_display, XkbGroupNamesMask, kbd); int _group_count = 0; const Atom *groups = kbd->names->groups; if (kbd->ctrls != nullptr) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } Atom names = kbd->names->symbols; if (names != None) { char *name = XGetAtomName(x11_display, names); Vector<String> info = String(name).split("+"); if (p_index >= 0 && p_index < _group_count) { if (p_index + 1 < info.size()) { ret = info[p_index + 1]; // Skip "pc" at the start and "inet"/"group" at the end of symbols. } else { ret = "en"; // No symbol for layout fallback to "en". } } else { ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ")."); } XFree(name); } XkbFreeKeyboard(kbd, 0, true); } return ret.substr(0, 2); } String OS_X11::keyboard_get_layout_name(int p_index) const { String ret; XkbDescRec *kbd = XkbAllocKeyboard(); if (kbd) { kbd->dpy = x11_display; XkbGetControls(x11_display, XkbAllControlsMask, kbd); XkbGetNames(x11_display, XkbSymbolsNameMask, kbd); XkbGetNames(x11_display, XkbGroupNamesMask, kbd); int _group_count = 0; const Atom *groups = kbd->names->groups; if (kbd->ctrls != nullptr) { _group_count = kbd->ctrls->num_groups; } else { while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) { _group_count++; } } if (p_index >= 0 && p_index < _group_count) { char *full_name = XGetAtomName(x11_display, groups[p_index]); ret.parse_utf8(full_name); XFree(full_name); } else { ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ")."); } XkbFreeKeyboard(kbd, 0, true); } return ret; } void OS_X11::update_real_mouse_position() { Window root_return, child_return; int root_x, root_y, win_x, win_y; unsigned int mask_return; Bool xquerypointer_result = XQueryPointer(x11_display, x11_window, &root_return, &child_return, &root_x, &root_y, &win_x, &win_y, &mask_return); if (xquerypointer_result) { if (win_x > 0 && win_y > 0 && win_x <= current_videomode.width && win_y <= current_videomode.height) { last_mouse_pos.x = win_x; last_mouse_pos.y = win_y; last_mouse_pos_valid = true; input->set_mouse_position(last_mouse_pos); } } } OS_X11::OS_X11() { #ifdef PULSEAUDIO_ENABLED AudioDriverManager::add_driver(&driver_pulseaudio); #endif #ifdef ALSA_ENABLED AudioDriverManager::add_driver(&driver_alsa); #endif xi.opcode = 0; xi.last_relative_time = 0; layered_window = false; minimized = false; window_focused = true; xim_style = 0L; mouse_mode = MOUSE_MODE_VISIBLE; last_position_before_fs = Vector2(); }
// ========================================================================== // Image File Reading Support Functions // - requires the Magick++ development libraries: http://www.imagemagick.org // // Note: This file will not compile by itself! The snippets below are meant // to be added to the template application distributed for Assignment #1. // You may use this code (or not) however you see fit for your work. // // Author: Sonny Chan, University of Calgary // Date: January 2016 // ========================================================================== #include <Magick++.h> // -------------------------------------------------------------------------- // Functions to set up OpenGL objects for storing image data struct MyTexture { // OpenGL names for array buffer objects, vertex array object GLuint textureName; // dimensions of the image stored in this texture GLuint width, height; // initialize object names to zero (OpenGL reserved value) MyTexture() : textureName(0), width(0), height(0) {} }; // use the Magick++ library to load an image with a given file name into // an OpenGL rectangle texture bool InitializeTexture(MyTexture *texture, const string &imageFileName) { Magick::Image myImage; // try to read the provided image file try { myImage.read(imageFileName); } catch (Magick::Error &error) { cout << "Magick++ failed to read image " << imageFileName << endl; cout << "ERROR: " << error.what() << endl; return false; } // store the image width and height into the texture structure texture->width = myImage.columns(); texture->height = myImage.rows(); // create a Magick++ pixel cache from the image for direct access to data Magick::Pixels pixelCache(myImage); Magick::PixelPacket *pixels; pixels = pixelCache.get(0, 0, texture->width, texture->height); // determine the number of stored bytes per pixel channel in the cache GLenum channelDataType; switch (sizeof(Magick::Quantum)) { case 4: channelDataType = GL_UNSIGNED_INT; break; case 2: channelDataType = GL_UNSIGNED_SHORT; break; default: channelDataType = GL_UNSIGNED_BYTE; } // create a texture name to associate our image data with if (!texture->textureName) glGenTextures(1, &texture->textureName); // bind the texture as a "rectangle" to access using image pixel coordinates glBindTexture(GL_TEXTURE_RECTANGLE, texture->textureName); // send image pixel data to OpenGL texture memory glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGB, texture->width, texture->height, 0, GL_BGRA, channelDataType, pixels); // unbind this texture glBindTexture(GL_TEXTURE_RECTANGLE, 0); return !CheckGLErrors(); } Removed ImageReader.cpp
// Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #ifndef PARALLEL_LOOP_HPP #define PARALLEL_LOOP_HPP #include "CompletionEvent.hpp" #include "ConditionVariable.hpp" #include "Message.hpp" #include "MessagePool.hpp" #include "Tasking.hpp" #include "Addressing.hpp" #include "Communicator.hpp" #include "GlobalCompletionEvent.hpp" #include "Barrier.hpp" #include "Collective.hpp" #include "function_traits.hpp" /// Flag: loop_threshold /// /// Iterations of `forall` loops *may* be run in parallel. A complete loop is decomposed into /// separate (parallel) tasks by recursively splitting the number of iterations in half. This /// parameter specifies the threshold where the decomposition ends, and the remaining iterations /// are run serially in a single task. This global threshold is used by all parallel loops by /// default, unless overridden statically as the `Threshold` template parameter in any of the /// parallel loop functions. DECLARE_int64(loop_threshold); namespace Grappa { namespace impl { /// Declares that the loop threshold should be determined by the `loop_threshold` command-line flag. /// (default for loop decompositions) const int64_t USE_LOOP_THRESHOLD_FLAG = 0; // TODO: figure out way to put these different kinds of loop_decomposition // Need to template on the now-templated task spawn function. /// Does recursive loop decomposition, subdividing iterations by 2 until reaching /// the threshold and serializing the remaining iterations at each leaf. /// Note: this is an internal primitive for spawning tasks and does not synchronize on spawned tasks. /// /// This version spawns *private* tasks all the way down. template< int64_t Threshold = USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void loop_decomposition_private(int64_t start, int64_t iterations, F loop_body) { DVLOG(4) << "< " << start << " : " << iterations << ">"; DVLOG(4) << "sizeof(loop_body) = " << sizeof(loop_body); if (iterations == 0) { return; } else if ((Threshold == USE_LOOP_THRESHOLD_FLAG && iterations <= FLAGS_loop_threshold) || iterations <= Threshold) { loop_body(start, iterations); return; } else { // spawn right half int64_t rstart = start+(iterations+1)/2, riters = iterations/2; auto t = [rstart, riters, loop_body] { loop_decomposition_private<Threshold,F>(rstart, riters, loop_body); }; // static_assert(sizeof(t)<=24,"privateTask too big"); privateTask(t); // left side here loop_decomposition_private<Threshold,F>(start, (iterations+1)/2, loop_body); } } /// Does recursive loop decomposition, subdividing iterations by 2 until reaching /// the threshold and serializing the remaining iterations at each leaf. /// Note: this is an internal primitive for spawning tasks and does not synchronize on spawned tasks. /// /// This version spawns *public* tasks all the way down. /// /// Optionally enrolls/completes spawned tasks with a GlobalCompletionEvent if specified /// (need to do this in decomposition because we want to enroll/complete with GCE where /// each task is spawned so work spawned by stolen tasks can complete locally. /// /// Note: this will add 16 bytes to the loop_body functor for loop decomposition (start /// niters) and synchronization, allowing the `loop_body` to have 8 bytes of /// user-defined storage. /// /// warning: truncates int64_t's to 48 bits--should be enough for most problem sizes. template< GlobalCompletionEvent * GCE = nullptr, int64_t Threshold = USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void loop_decomposition_public(int64_t start, int64_t iterations, F loop_body) { DVLOG(4) << "< " << start << " : " << iterations << ">"; if (iterations == 0) { return; } else if ((Threshold == USE_LOOP_THRESHOLD_FLAG && iterations <= FLAGS_loop_threshold) || iterations <= Threshold) { loop_body(start, iterations); return; } else { // spawn right half int64_t rstart = start+(iterations+1)/2, riters = iterations/2; Core origin = mycore(); // pack these 3 into 14 bytes so we still have room for a full 8-byte word from user // (also need to count 2 bytes from lambda overhead or something) struct { long rstart:48, riters:48, origin:16; } packed = { rstart, riters, origin }; if (GCE) GCE->enroll(); publicTask([packed, loop_body] { loop_decomposition_public<GCE,Threshold,F>(packed.rstart, packed.riters, loop_body); if (GCE) complete(make_global(GCE,packed.origin)); }); // left side here loop_decomposition_public<GCE,Threshold,F>(start, (iterations+1)/2, loop_body); } } extern CompletionEvent local_ce; extern GlobalCompletionEvent local_gce; } /// Blocking parallel for loop, spawns only private tasks. Synchronizes itself with /// either a given static CompletionEvent (template param) or the local builtin one. /// /// Intended to be used for a loop of local tasks, often used as a primitive (along /// with `on_all_cores`) in global loops. /// /// Subject to "may-parallelism", @see `loop_threshold`. /// /// @warning { All calls to forall_here will share the same CompletionEvent by default, /// so only one should be called at once per core. } /// /// Also note: a single copy of `loop_body` is passed by reference to all of the child /// tasks, so be sure not to modify anything in the functor /// (TODO: figure out how to enforce this for all kinds of functors) template<CompletionEvent * CE = &impl::local_ce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void forall_here(int64_t start, int64_t iters, F loop_body) { CE->enroll(iters); impl::loop_decomposition_private<Threshold>(start, iters, // passing loop_body by ref to avoid copying potentially large functors many times in decomposition // also keeps task args < 24 bytes, preventing it from needing to be heap-allocated [&loop_body](int64_t s, int64_t n) { loop_body(s, n); CE->complete(n); }); CE->wait(); } /// Non-blocking parallel loop with privateTasks. Takes pointer to a functor which /// is shared by all child tasks. Enrolls tasks with specified GlobalCompletionEvent. /// /// Intended for spawning local tasks from within another GCE synchronization scheme /// (another parallel loop or otherwise). /// /// Note: this now takes a pointer to a functor so we can pass a pointer to the one /// functor to all child tasks rather than making lots of copies. Therefore, it /// should be alright to make the functor as large as desired. /// /// Subject to "may-parallelism", @see `loop_threshold`. template<GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void forall_here_async(int64_t start, int64_t iters, const F * loop_ptr) { GCE->enroll(iters); impl::loop_decomposition_private<Threshold>(start, iters, // passing loop_body by ref to avoid copying potentially large functors many times in decomposition // also keeps task args < 24 bytes, preventing it from needing to be heap-allocated [loop_ptr](int64_t s, int64_t n) { (*loop_ptr)(s, n); GCE->complete(n); }); } /// Non-blocking version of `forall_here`, does recursive decomposition of loop locally, /// but synchronization is up to you. /// /// Subject to "may-parallelism", @see `loop_threshold`. /// /// Note: this also cannot guarantee that `loop_body` will be in scope, so it passes it /// by copy to spawned tasks. /// Also uses impl::loop_decomposition_public, which adds 16 bytes to functor, so `loop_body` /// should be kept to 8 bytes for performance. template< GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void forall_here_async_public(int64_t start, int64_t iters, F loop_body) { if (GCE) GCE->enroll(); impl::loop_decomposition_public<GCE,Threshold>(start, iters, [loop_body](int64_t start, int64_t iters) { loop_body(start, iters); }); if (GCE) GCE->complete(); } /// Spread iterations evenly (block-distributed) across all the cores, using recursive /// decomposition with private tasks (so will not be load-balanced). Blocks until all /// iterations on all cores complete. /// /// Subject to "may-parallelism", @see `loop_threshold`. template<CompletionEvent * CE = &impl::local_ce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr)> void forall_global_private(int64_t start, int64_t iters, F loop_body) { on_all_cores([start,iters,loop_body]{ range_t r = blockDist(start, start+iters, mycore(), cores()); forall_here<CE,Threshold>(r.start, r.end-r.start, loop_body); }); } /// Spread iterations evenly (block-distributed) across all the cores, using recursive /// decomposition with public tasks (that may moved to a different core for load-balancing). /// Blocks until all iterations on all cores complete. /// /// Note: `loop_body` will be copied to each core and that single copied is shared by all /// public tasks under this GlobalCompletionEvent. /// /// Subject to "may-parallelism", @see `loop_threshold`. template<GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr)> void forall_global_public(int64_t start, int64_t iters, F loop_body) { // note: loop_decomp uses 2*8-byte values to specify range. We additionally track originating // core. So to avoid exceeding 3*8-byte task size, we save the loop body once on each core // (on `on_all_cores` task's stack) and embed the pointer to it in GCE, so each public task // can look it up when run, wherever it is. on_all_cores([start,iters,loop_body]{ // GCE->reset(); GCE->set_shared_ptr(&loop_body); // need to initialize this on all nodes before any tasks start // may as well do this before the barrier too, but it shouldn't matter range_t r = blockDist(start, start+iters, mycore(), cores()); barrier(); forall_here_async_public<GCE,Threshold>(r.start, r.end-r.start, [](int64_t s, int64_t n) { auto& loop_body = *GCE->get_shared_ptr<F>(); loop_body(s,n); } ); GCE->wait(); // keeps captured `loop_body` around for child tasks from any core to use GCE->set_shared_ptr(nullptr); }); } /// Parallel loop over a global array. Spawned from a single core, fans out and runs /// tasks on elements that are local to each core. /// /// Subject to "may-parallelism", @see `loop_threshold`. /// /// Takes an optional pointer to a global static `GlobalCompletionEvent` as a template /// parameter to allow for programmer-specified task joining (to potentially allow /// more than one in flight simultaneously, though this call is itself blocking. /// /// takes a lambda/functor that operates on a range of iterations: /// void(int64_t first_index, int64_t niters, T * first_element) /// /// Warning: you cannot simply increment `first_index` `niters` times and get the /// correct global index because a single task may span more than one block. template< typename T, GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > // type_traits magic to make this verison work for 3-arg functors typename std::enable_if< function_traits<F>::arity == 3, void >::type forall_localized(GlobalAddress<T> base, int64_t nelems, F loop_body) { static_assert(block_size % sizeof(T) == 0, "forall_localized requires size of objects to evenly divide into block_size"); GCE->enroll(cores()); // make sure everyone has to check in, even if they don't have any work Core origin = mycore(); on_all_cores([base, nelems, loop_body, origin]{ // GCE->reset(); // barrier(); T* local_base = base.localize(); T* local_end = (base+nelems).localize(); auto n = local_end - local_base; auto f = [loop_body, local_base, base](int64_t start, int64_t iters) { auto laddr = make_linear(local_base+start); loop_body(laddr-base, iters, local_base+start); }; forall_here_async<GCE,Threshold>(0, n, &f); complete(make_global(GCE,origin)); GCE->wait(); }); } /// Alternate version of forall_localized that takes a lambda/functor with signature: /// void(int64_t index, T& element) /// (internally wraps this call in a loop and passes to the other version of forall_localized) /// /// This is meant to make it easy to make a loop where you don't care about amortizing /// anything for a single task. If you would like to do something that will be used by /// multiple iterations, use the other version of Grappa::forall_localized that takes a /// lambda that operates on a range. template< typename T, GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > // type_traits magic to make this verison work for 2-arg functors typename std::enable_if< function_traits<F>::arity == 2, void >::type forall_localized(GlobalAddress<T> base, int64_t nelems, F loop_body) { forall_localized(base, nelems, [loop_body,base](int64_t start, int64_t niters, T * first) { auto block_elems = block_size / sizeof(T); auto a = make_linear(first); auto n_to_boundary = a.block_max() - a; auto index = start; for (int64_t i=0; i<niters; i++,index++,n_to_boundary--) { if (n_to_boundary == 0) { index += block_elems * (cores()-1); n_to_boundary = block_elems; } loop_body(index, first[i]); } }); } /// Asynchronous version of Grappa::forall_localized (enrolls with GCE, does not block). /// /// Spawns tasks to on cores that *may contain elements* of the part of a linear array /// from base[0]-base[nelems]. /// /// loop_body functor should be of the form: /// void(int64_t index, T& element) template< GlobalCompletionEvent * GCE = &impl::local_gce, typename T = decltype(nullptr), int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void forall_localized_async(GlobalAddress<T> base, int64_t nelems, F loop_body) { Core nc = cores(); Core fc; int64_t nbytes = nelems*sizeof(T); GlobalAddress<int64_t> end = base+nelems; if (nelems > 0) { fc = 1; } size_t block_elems = block_size / sizeof(T); int64_t nfirstcore = base.block_max() - base; int64_t n = nelems - nfirstcore; if (n > 0) { int64_t nrest = n / block_elems; if (nrest >= nc-1) { fc = nc; } else { fc += nrest; if ((end - end.block_min()) && end.node() != base.node()) { fc += 1; } } } Core origin = mycore(); Core start_core = base.node(); MessagePool pool(cores() * sizeof(Message<std::function<void(GlobalAddress<T>,int64_t,F)>>)); GCE->enroll(fc); for (Core i=0; i<fc; i++) { pool.send_message((start_core+i)%nc, [base,nelems,loop_body,origin] { // TODO: make this not heap-allocate the task. privateTask([base,nelems,loop_body,origin] { T* local_base = base.localize(); T* local_end = (base+nelems).localize(); size_t n = local_end - local_base; CompletionEvent ce(n); auto f = [base,loop_body, &ce](int64_t start, int64_t iters) { T* local_base = base.localize(); auto laddr = make_linear(local_base+start); for (int64_t i=start; i<start+iters; i++) { // TODO: check if this is inlined and if this loop is unrollable loop_body(laddr-base, local_base[i]); } ce.complete(iters); }; forall_here_async<GCE,Threshold>(0, n, &f); ce.wait(); complete(make_global(GCE,origin)); }); }); } } } // namespace Grappa #endif Reorder forall_localized params to ease specifing GCE // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #ifndef PARALLEL_LOOP_HPP #define PARALLEL_LOOP_HPP #include "CompletionEvent.hpp" #include "ConditionVariable.hpp" #include "Message.hpp" #include "MessagePool.hpp" #include "Tasking.hpp" #include "Addressing.hpp" #include "Communicator.hpp" #include "GlobalCompletionEvent.hpp" #include "Barrier.hpp" #include "Collective.hpp" #include "function_traits.hpp" /// Flag: loop_threshold /// /// Iterations of `forall` loops *may* be run in parallel. A complete loop is decomposed into /// separate (parallel) tasks by recursively splitting the number of iterations in half. This /// parameter specifies the threshold where the decomposition ends, and the remaining iterations /// are run serially in a single task. This global threshold is used by all parallel loops by /// default, unless overridden statically as the `Threshold` template parameter in any of the /// parallel loop functions. DECLARE_int64(loop_threshold); namespace Grappa { namespace impl { /// Declares that the loop threshold should be determined by the `loop_threshold` command-line flag. /// (default for loop decompositions) const int64_t USE_LOOP_THRESHOLD_FLAG = 0; // TODO: figure out way to put these different kinds of loop_decomposition // Need to template on the now-templated task spawn function. /// Does recursive loop decomposition, subdividing iterations by 2 until reaching /// the threshold and serializing the remaining iterations at each leaf. /// Note: this is an internal primitive for spawning tasks and does not synchronize on spawned tasks. /// /// This version spawns *private* tasks all the way down. template< int64_t Threshold = USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void loop_decomposition_private(int64_t start, int64_t iterations, F loop_body) { DVLOG(4) << "< " << start << " : " << iterations << ">"; DVLOG(4) << "sizeof(loop_body) = " << sizeof(loop_body); if (iterations == 0) { return; } else if ((Threshold == USE_LOOP_THRESHOLD_FLAG && iterations <= FLAGS_loop_threshold) || iterations <= Threshold) { loop_body(start, iterations); return; } else { // spawn right half int64_t rstart = start+(iterations+1)/2, riters = iterations/2; auto t = [rstart, riters, loop_body] { loop_decomposition_private<Threshold,F>(rstart, riters, loop_body); }; // static_assert(sizeof(t)<=24,"privateTask too big"); privateTask(t); // left side here loop_decomposition_private<Threshold,F>(start, (iterations+1)/2, loop_body); } } /// Does recursive loop decomposition, subdividing iterations by 2 until reaching /// the threshold and serializing the remaining iterations at each leaf. /// Note: this is an internal primitive for spawning tasks and does not synchronize on spawned tasks. /// /// This version spawns *public* tasks all the way down. /// /// Optionally enrolls/completes spawned tasks with a GlobalCompletionEvent if specified /// (need to do this in decomposition because we want to enroll/complete with GCE where /// each task is spawned so work spawned by stolen tasks can complete locally. /// /// Note: this will add 16 bytes to the loop_body functor for loop decomposition (start /// niters) and synchronization, allowing the `loop_body` to have 8 bytes of /// user-defined storage. /// /// warning: truncates int64_t's to 48 bits--should be enough for most problem sizes. template< GlobalCompletionEvent * GCE = nullptr, int64_t Threshold = USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void loop_decomposition_public(int64_t start, int64_t iterations, F loop_body) { DVLOG(4) << "< " << start << " : " << iterations << ">"; if (iterations == 0) { return; } else if ((Threshold == USE_LOOP_THRESHOLD_FLAG && iterations <= FLAGS_loop_threshold) || iterations <= Threshold) { loop_body(start, iterations); return; } else { // spawn right half int64_t rstart = start+(iterations+1)/2, riters = iterations/2; Core origin = mycore(); // pack these 3 into 14 bytes so we still have room for a full 8-byte word from user // (also need to count 2 bytes from lambda overhead or something) struct { long rstart:48, riters:48, origin:16; } packed = { rstart, riters, origin }; if (GCE) GCE->enroll(); publicTask([packed, loop_body] { loop_decomposition_public<GCE,Threshold,F>(packed.rstart, packed.riters, loop_body); if (GCE) complete(make_global(GCE,packed.origin)); }); // left side here loop_decomposition_public<GCE,Threshold,F>(start, (iterations+1)/2, loop_body); } } extern CompletionEvent local_ce; extern GlobalCompletionEvent local_gce; } /// Blocking parallel for loop, spawns only private tasks. Synchronizes itself with /// either a given static CompletionEvent (template param) or the local builtin one. /// /// Intended to be used for a loop of local tasks, often used as a primitive (along /// with `on_all_cores`) in global loops. /// /// Subject to "may-parallelism", @see `loop_threshold`. /// /// @warning { All calls to forall_here will share the same CompletionEvent by default, /// so only one should be called at once per core. } /// /// Also note: a single copy of `loop_body` is passed by reference to all of the child /// tasks, so be sure not to modify anything in the functor /// (TODO: figure out how to enforce this for all kinds of functors) template<CompletionEvent * CE = &impl::local_ce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void forall_here(int64_t start, int64_t iters, F loop_body) { CE->enroll(iters); impl::loop_decomposition_private<Threshold>(start, iters, // passing loop_body by ref to avoid copying potentially large functors many times in decomposition // also keeps task args < 24 bytes, preventing it from needing to be heap-allocated [&loop_body](int64_t s, int64_t n) { loop_body(s, n); CE->complete(n); }); CE->wait(); } /// Non-blocking parallel loop with privateTasks. Takes pointer to a functor which /// is shared by all child tasks. Enrolls tasks with specified GlobalCompletionEvent. /// /// Intended for spawning local tasks from within another GCE synchronization scheme /// (another parallel loop or otherwise). /// /// Note: this now takes a pointer to a functor so we can pass a pointer to the one /// functor to all child tasks rather than making lots of copies. Therefore, it /// should be alright to make the functor as large as desired. /// /// Subject to "may-parallelism", @see `loop_threshold`. template<GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void forall_here_async(int64_t start, int64_t iters, const F * loop_ptr) { GCE->enroll(iters); impl::loop_decomposition_private<Threshold>(start, iters, // passing loop_body by ref to avoid copying potentially large functors many times in decomposition // also keeps task args < 24 bytes, preventing it from needing to be heap-allocated [loop_ptr](int64_t s, int64_t n) { (*loop_ptr)(s, n); GCE->complete(n); }); } /// Non-blocking version of `forall_here`, does recursive decomposition of loop locally, /// but synchronization is up to you. /// /// Subject to "may-parallelism", @see `loop_threshold`. /// /// Note: this also cannot guarantee that `loop_body` will be in scope, so it passes it /// by copy to spawned tasks. /// Also uses impl::loop_decomposition_public, which adds 16 bytes to functor, so `loop_body` /// should be kept to 8 bytes for performance. template< GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > void forall_here_async_public(int64_t start, int64_t iters, F loop_body) { if (GCE) GCE->enroll(); impl::loop_decomposition_public<GCE,Threshold>(start, iters, [loop_body](int64_t start, int64_t iters) { loop_body(start, iters); }); if (GCE) GCE->complete(); } /// Spread iterations evenly (block-distributed) across all the cores, using recursive /// decomposition with private tasks (so will not be load-balanced). Blocks until all /// iterations on all cores complete. /// /// Subject to "may-parallelism", @see `loop_threshold`. template<CompletionEvent * CE = &impl::local_ce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr)> void forall_global_private(int64_t start, int64_t iters, F loop_body) { on_all_cores([start,iters,loop_body]{ range_t r = blockDist(start, start+iters, mycore(), cores()); forall_here<CE,Threshold>(r.start, r.end-r.start, loop_body); }); } /// Spread iterations evenly (block-distributed) across all the cores, using recursive /// decomposition with public tasks (that may moved to a different core for load-balancing). /// Blocks until all iterations on all cores complete. /// /// Note: `loop_body` will be copied to each core and that single copied is shared by all /// public tasks under this GlobalCompletionEvent. /// /// Subject to "may-parallelism", @see `loop_threshold`. template<GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr)> void forall_global_public(int64_t start, int64_t iters, F loop_body) { // note: loop_decomp uses 2*8-byte values to specify range. We additionally track originating // core. So to avoid exceeding 3*8-byte task size, we save the loop body once on each core // (on `on_all_cores` task's stack) and embed the pointer to it in GCE, so each public task // can look it up when run, wherever it is. on_all_cores([start,iters,loop_body]{ // GCE->reset(); GCE->set_shared_ptr(&loop_body); // need to initialize this on all nodes before any tasks start // may as well do this before the barrier too, but it shouldn't matter range_t r = blockDist(start, start+iters, mycore(), cores()); barrier(); forall_here_async_public<GCE,Threshold>(r.start, r.end-r.start, [](int64_t s, int64_t n) { auto& loop_body = *GCE->get_shared_ptr<F>(); loop_body(s,n); } ); GCE->wait(); // keeps captured `loop_body` around for child tasks from any core to use GCE->set_shared_ptr(nullptr); }); } /// Parallel loop over a global array. Spawned from a single core, fans out and runs /// tasks on elements that are local to each core. /// /// Subject to "may-parallelism", @see `loop_threshold`. /// /// Takes an optional pointer to a global static `GlobalCompletionEvent` as a template /// parameter to allow for programmer-specified task joining (to potentially allow /// more than one in flight simultaneously, though this call is itself blocking. /// /// takes a lambda/functor that operates on a range of iterations: /// void(int64_t first_index, int64_t niters, T * first_element) /// /// Warning: you cannot simply increment `first_index` `niters` times and get the /// correct global index because a single task may span more than one block. template< typename T, GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename F = decltype(nullptr) > // type_traits magic to make this verison work for 3-arg functors typename std::enable_if< function_traits<F>::arity == 3, void >::type forall_localized(GlobalAddress<T> base, int64_t nelems, F loop_body) { static_assert(block_size % sizeof(T) == 0, "forall_localized requires size of objects to evenly divide into block_size"); GCE->enroll(cores()); // make sure everyone has to check in, even if they don't have any work Core origin = mycore(); on_all_cores([base, nelems, loop_body, origin]{ // GCE->reset(); // barrier(); T* local_base = base.localize(); T* local_end = (base+nelems).localize(); auto n = local_end - local_base; auto f = [loop_body, local_base, base](int64_t start, int64_t iters) { auto laddr = make_linear(local_base+start); loop_body(laddr-base, iters, local_base+start); }; forall_here_async<GCE,Threshold>(0, n, &f); complete(make_global(GCE,origin)); GCE->wait(); }); } /// Alternate version of forall_localized that takes a lambda/functor with signature: /// void(int64_t index, T& element) /// (internally wraps this call in a loop and passes to the other version of forall_localized) /// /// This is meant to make it easy to make a loop where you don't care about amortizing /// anything for a single task. If you would like to do something that will be used by /// multiple iterations, use the other version of Grappa::forall_localized that takes a /// lambda that operates on a range. template< GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename T = decltype(nullptr), typename F = decltype(nullptr) > // type_traits magic to make this verison work for 2-arg functors typename std::enable_if< function_traits<F>::arity == 2, void >::type forall_localized(GlobalAddress<T> base, int64_t nelems, F loop_body) { forall_localized(base, nelems, [loop_body,base](int64_t start, int64_t niters, T * first) { auto block_elems = block_size / sizeof(T); auto a = make_linear(first); auto n_to_boundary = a.block_max() - a; auto index = start; for (int64_t i=0; i<niters; i++,index++,n_to_boundary--) { if (n_to_boundary == 0) { index += block_elems * (cores()-1); n_to_boundary = block_elems; } loop_body(index, first[i]); } }); } /// Asynchronous version of Grappa::forall_localized (enrolls with GCE, does not block). /// /// Spawns tasks to on cores that *may contain elements* of the part of a linear array /// from base[0]-base[nelems]. /// /// loop_body functor should be of the form: /// void(int64_t index, T& element) template< GlobalCompletionEvent * GCE = &impl::local_gce, int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG, typename T = decltype(nullptr), typename F = decltype(nullptr) > void forall_localized_async(GlobalAddress<T> base, int64_t nelems, F loop_body) { Core nc = cores(); Core fc; int64_t nbytes = nelems*sizeof(T); GlobalAddress<int64_t> end = base+nelems; if (nelems > 0) { fc = 1; } size_t block_elems = block_size / sizeof(T); int64_t nfirstcore = base.block_max() - base; int64_t n = nelems - nfirstcore; if (n > 0) { int64_t nrest = n / block_elems; if (nrest >= nc-1) { fc = nc; } else { fc += nrest; if ((end - end.block_min()) && end.node() != base.node()) { fc += 1; } } } Core origin = mycore(); Core start_core = base.node(); MessagePool pool(cores() * sizeof(Message<std::function<void(GlobalAddress<T>,int64_t,F)>>)); GCE->enroll(fc); for (Core i=0; i<fc; i++) { pool.send_message((start_core+i)%nc, [base,nelems,loop_body,origin] { // TODO: make this not heap-allocate the task. privateTask([base,nelems,loop_body,origin] { T* local_base = base.localize(); T* local_end = (base+nelems).localize(); size_t n = local_end - local_base; CompletionEvent ce(n); auto f = [base,loop_body, &ce](int64_t start, int64_t iters) { T* local_base = base.localize(); auto laddr = make_linear(local_base+start); for (int64_t i=start; i<start+iters; i++) { // TODO: check if this is inlined and if this loop is unrollable loop_body(laddr-base, local_base[i]); } ce.complete(iters); }; forall_here_async<GCE,Threshold>(0, n, &f); ce.wait(); complete(make_global(GCE,origin)); }); }); } } } // namespace Grappa #endif
#if !defined(__CINT__) || defined(__MAKECINT__) #include <TF1.h> #include <TFile.h> #include <TH1F.h> #include <TGraph.h> #include <TStyle.h> #include <TSystem.h> #include <TString.h> #include <TGrid.h> #include <TCanvas.h> #include <TLatex.h> #include <TObjArray.h> #include "AliCDBEntry.h" #include "AliITSDriftSpeedArraySDD.h" #include "AliITSDriftSpeedSDD.h" #endif // Macro to plot the calibration parameters from the OCDB file // created from an INJECTOR run (OCDB/ITS/Calib/DriftSpeedSDD) // Two methods ShowDriftSpeedSDD: // - the first takes the name of the file to be displayed // - the second builds the alien path+name from run number and file version // // Origin: F. Prino (prino@to.infn.it) Bool_t kNoDraw = kFALSE; // set to kTRUE to eliminate module dependent plots void ShowDriftSpeedSDD(Char_t filnam[150]="$ALICE_ROOT/ITS/Calib/DriftSpeedSDD/Run0_9999999_v0_s0.root", Int_t firstmod=0, Int_t lastmod=260,Int_t nrun=0){ TFile *f= TFile::Open(filnam); AliCDBEntry *ent=(AliCDBEntry*)f->Get("AliCDBEntry"); TObjArray *drspSDD = (TObjArray *)ent->GetObject(); AliITSDriftSpeedArraySDD *vdriftarr0; AliITSDriftSpeedArraySDD *vdriftarr1; TGraph **gvdr0=new TGraph*[260]; TGraph **gvdr1=new TGraph*[260]; TCanvas *c0=NULL; if(!kNoDraw)c0=new TCanvas("c0","Module Drift Speed",1100,500); TGraph *vvsmod0=new TGraph(0); TGraph *vvsmod1=new TGraph(0); TGraph *poldegvsmod0=new TGraph(0); TGraph *poldegvsmod1=new TGraph(0); TGraph *anmaxvsmod0=new TGraph(0); TGraph *anmaxvsmod1=new TGraph(0); TGraph *dvcevsmod0=new TGraph(0); TGraph *dvcevsmod1=new TGraph(0); TGraph *dveevsmod0=new TGraph(0); TGraph *dveevsmod1=new TGraph(0); char tit0[100]; sprintf(tit0,"Drift Speed vs. mod. number"); if(nrun!=0)sprintf(tit0,"Drift Speed vs. mod. number - Run %d",nrun); vvsmod0->SetTitle(tit0); vvsmod1->SetTitle(tit0); sprintf(tit0,"Degree of poly fit vs. mod. number"); if(nrun!=0)sprintf(tit0,"Degree of poly fit vs. mod. number - Run %d",nrun); poldegvsmod0->SetTitle(tit0); poldegvsmod1->SetTitle(tit0); sprintf(tit0,"Anode with max. vdrift vs. mod. number"); if(nrun!=0)sprintf(tit0,"Anode with max. vdrift vs. mod. number - Run %d",nrun); anmaxvsmod0->SetTitle(tit0); anmaxvsmod1->SetTitle(tit0); sprintf(tit0,"Delta Vdrift 128-0 vs. mod. number"); if(nrun!=0)sprintf(tit0,"Delta Vdrift 128-0 vs. mod. number - Run %d",nrun); dvcevsmod0->SetTitle(tit0); dvcevsmod1->SetTitle(tit0); sprintf(tit0,"Delta Vdrift 256-0 vs. mod. number"); if(nrun!=0)sprintf(tit0,"Delta Vdrift 256-0 vs. mod. number - Run %d",nrun); dveevsmod0->SetTitle(tit0); dveevsmod1->SetTitle(tit0); TF1* fPoly=new TF1("fPoly","[0]+[1]*x+[2]*x*x+[3]*x*x*x",0.,256.); Char_t tit[100]; Int_t iGoodInj=0; Int_t iAverSpeed=0; for(Int_t i=firstmod; i<lastmod; i++){ Int_t iMod=i+240; if(!kNoDraw){ c0->Clear(); c0->Divide(2,1); } Int_t i0=2*i; Int_t i1=1+2*i; vdriftarr0=(AliITSDriftSpeedArraySDD*)drspSDD->At(i0); vdriftarr1=(AliITSDriftSpeedArraySDD*)drspSDD->At(i1); AliITSDriftSpeedSDD* vdrift0=0x0; if(vdriftarr0) vdrift0=vdriftarr0->GetDriftSpeedObject(0); AliITSDriftSpeedSDD* vdrift1=0x0; if(vdriftarr1) vdrift1=vdriftarr1->GetDriftSpeedObject(0); gvdr0[i]=new TGraph(0); gvdr1[i]=new TGraph(0); gvdr0[i]->SetMarkerStyle(7); gvdr1[i]->SetMarkerStyle(7); gvdr0[i]->SetMinimum(5.); gvdr1[i]->SetMinimum(5.); gvdr0[i]->SetMaximum(9.); gvdr1[i]->SetMaximum(9.); sprintf(tit,"Mod %d\n",iMod); gvdr0[i]->SetTitle(tit); gvdr1[i]->SetTitle(tit); for(Int_t iAn=0; iAn<256; iAn++){ Float_t vel0=0; if(vdrift0) vel0=vdrift0->GetDriftSpeedAtAnode(iAn); Float_t vel1=0; if(vdrift1) vel1=vdrift1->GetDriftSpeedAtAnode(iAn); gvdr0[i]->SetPoint(iAn,(Float_t)iAn,vel0); gvdr1[i]->SetPoint(iAn,(Float_t)iAn,vel1); } if(vdriftarr0->GetInjectorStatus()>0) iGoodInj++; else iAverSpeed++; if(vdriftarr1->GetInjectorStatus()>0) iGoodInj++; else iAverSpeed++; printf(" Mod. %d \tStatusLR=%X %X \t v(an 128l)= %f",iMod,vdriftarr0->GetInjectorStatus(),vdriftarr1->GetInjectorStatus(),vdriftarr0->GetDriftSpeed(0,128)); printf(" \t v(an 128r)= %f Degree=%d %d\n",vdriftarr1->GetDriftSpeed(0,128),vdrift0->GetDegreeofPoly(),vdrift1->GetDegreeofPoly()); if(!kNoDraw){ c0->cd(1); gvdr0[i]->Draw("AP"); gvdr0[i]->GetXaxis()->SetTitle("Anode"); gvdr0[i]->GetYaxis()->SetTitle("Vdrift (#mum/ns)"); c0->cd(2); gvdr1[i]->Draw("AP"); gvdr1[i]->GetXaxis()->SetTitle("Anode"); gvdr1[i]->GetYaxis()->SetTitle("Vdrift (#mum/ns)"); c0->Update(); } Float_t vel0=0; Float_t pd0=0; if(vdrift0){ vel0=vdrift0->GetDriftSpeedAtAnode(128); pd0=vdrift0->GetDegreeofPoly(); } Float_t vel1=0; Float_t pd1=0; if(vdrift1){ vel1=vdrift1->GetDriftSpeedAtAnode(128); pd1=vdrift1->GetDegreeofPoly(); } vvsmod0->SetPoint(vvsmod0->GetN(),(Float_t)iMod,vel0); vvsmod1->SetPoint(vvsmod1->GetN(),(Float_t)iMod,vel1); poldegvsmod0->SetPoint(poldegvsmod0->GetN(),(Float_t)iMod,pd0); poldegvsmod1->SetPoint(poldegvsmod1->GetN(),(Float_t)iMod,pd1); for(Int_t ipar=0; ipar<=vdrift0->GetDegreeofPoly(); ipar++){ fPoly->SetParameter(ipar,vdrift0->GetDriftSpeedParameter(ipar)); } if(vdrift0->GetDegreeofPoly()<3){ for(Int_t ipar=vdrift0->GetDegreeofPoly()+1; ipar<=3; ipar++) fPoly->SetParameter(ipar,0.); } anmaxvsmod0->SetPoint(anmaxvsmod0->GetN(),(Float_t)iMod,fPoly->GetMaximumX(0.,256.)); dvcevsmod0->SetPoint(dvcevsmod0->GetN(),(Float_t)iMod,fPoly->Eval(128)-fPoly->Eval(0)); dveevsmod0->SetPoint(dveevsmod0->GetN(),(Float_t)iMod,fPoly->Eval(256)-fPoly->Eval(0)); for(Int_t ipar=0; ipar<=vdrift1->GetDegreeofPoly(); ipar++){ fPoly->SetParameter(ipar,vdrift1->GetDriftSpeedParameter(ipar)); } if(vdrift1->GetDegreeofPoly()<3){ for(Int_t ipar=vdrift1->GetDegreeofPoly()+1; ipar<=3; ipar++) fPoly->SetParameter(ipar,0.); } anmaxvsmod1->SetPoint(anmaxvsmod1->GetN(),(Float_t)iMod,fPoly->GetMaximumX(0.,256.)); dvcevsmod1->SetPoint(dvcevsmod1->GetN(),(Float_t)iMod,fPoly->Eval(128)-fPoly->Eval(0)); dveevsmod1->SetPoint(dveevsmod1->GetN(),(Float_t)iMod,fPoly->Eval(256)-fPoly->Eval(0)); // getchar(); } printf("Number of half-modules with drift speed from injectors = %d\n",iGoodInj); printf("Number of half-modules with average drift speed = %d\n",iAverSpeed); TCanvas* c2; c2=new TCanvas("c2","",1000,700); vvsmod0->SetMarkerStyle(20); vvsmod0->Draw("AP"); vvsmod0->GetXaxis()->SetTitle("Module Number"); vvsmod0->GetYaxis()->SetTitle("Vdrift (#mum/ns)"); vvsmod1->SetMarkerStyle(21); vvsmod1->SetMarkerColor(2); vvsmod1->Draw("SAMEP"); TLatex* tleft=new TLatex(0.2,0.82,"Side 0"); tleft->SetNDC(); tleft->SetTextColor(1); tleft->Draw(); TLatex* tright=new TLatex(0.2,0.75,"Side 1"); tright->SetNDC(); tright->SetTextColor(2); tright->Draw(); TCanvas* c3; c3=new TCanvas("c3","",900,900); c3->Divide(2,2); c3->cd(1); gPad->SetLeftMargin(0.14); poldegvsmod0->SetMarkerStyle(20); poldegvsmod0->Draw("AP"); poldegvsmod0->GetXaxis()->SetTitle("Module Number"); poldegvsmod0->GetYaxis()->SetTitle("Degree of Polynomial fit"); poldegvsmod0->GetYaxis()->SetTitleOffset(1.4); poldegvsmod1->SetMarkerStyle(21); poldegvsmod1->SetMarkerColor(2); poldegvsmod1->Draw("SAMEP"); tleft->Draw(); tright->Draw(); c3->cd(2); gPad->SetLeftMargin(0.14); anmaxvsmod0->SetMarkerStyle(20); anmaxvsmod0->Draw("AP"); anmaxvsmod0->GetXaxis()->SetTitle("Module Number"); anmaxvsmod0->GetYaxis()->SetTitle("Anode with max. drift speed"); anmaxvsmod0->GetYaxis()->SetTitleOffset(1.4); anmaxvsmod1->SetMarkerStyle(21); anmaxvsmod1->SetMarkerColor(2); anmaxvsmod1->Draw("SAMEP"); tleft->Draw(); tright->Draw(); c3->cd(3); gPad->SetLeftMargin(0.14); dvcevsmod0->SetMarkerStyle(20); dvcevsmod0->Draw("AP"); dvcevsmod0->GetXaxis()->SetTitle("Module Number"); dvcevsmod0->GetYaxis()->SetTitle("vdrift(anode128)-vdrift(anode0)"); dvcevsmod0->GetYaxis()->SetTitleOffset(1.4); dvcevsmod1->SetMarkerStyle(21); dvcevsmod1->SetMarkerColor(2); dvcevsmod1->Draw("SAMEP"); tleft->Draw(); tright->Draw(); c3->cd(4); gPad->SetLeftMargin(0.14); dveevsmod0->SetMarkerStyle(20); dveevsmod0->Draw("AP"); dveevsmod0->GetYaxis()->SetTitleOffset(1.4); dveevsmod0->GetXaxis()->SetTitle("Module Number"); dveevsmod0->GetYaxis()->SetTitle("vdrift(anode256)-vdrift(anode0)"); dveevsmod1->SetMarkerStyle(21); dveevsmod1->SetMarkerColor(2); dveevsmod1->Draw("SAMEP"); tleft->Draw(); tright->Draw(); } void ShowDriftSpeedSDD(Int_t nrun, Int_t year=2010){ TGrid::Connect("alien:",0,0,"t"); TString cmd=Form("gbbox find \"/alice/data/%d/OCDB/ITS/Calib/DriftSpeedSDD\" \"Run%d*.root\" > run.txt",year,nrun); gSystem->Exec(cmd.Data()); Char_t filnam[200],filnamalien[200]; FILE* runtxt=fopen("run.txt","r"); fscanf(runtxt,"%s\n",filnam); if(!strstr(filnam,"/alice/data/")){ printf("Bad run number\n"); gSystem->Exec("rm run.txt"); return; } sprintf(filnamalien,"alien://%s",filnam); printf("Open file: %s\n",filnamalien); ShowDriftSpeedSDD(filnamalien,0,260,nrun); fclose(runtxt); gSystem->Exec("rm run.txt"); } Updates in macro to monitor SDD drift speed values #if !defined(__CINT__) || defined(__MAKECINT__) #include <TF1.h> #include <TFile.h> #include <TH1F.h> #include <TGraph.h> #include <TStyle.h> #include <TSystem.h> #include <TString.h> #include <TGrid.h> #include <TCanvas.h> #include <TLatex.h> #include <TObjArray.h> #include "AliCDBEntry.h" #include "AliITSDriftSpeedArraySDD.h" #include "AliITSDriftSpeedSDD.h" #endif // Macro to plot the calibration parameters from the OCDB file // created from an INJECTOR run (OCDB/ITS/Calib/DriftSpeedSDD) // Two methods ShowDriftSpeedSDD: // - the first takes the name of the file to be displayed // - the second builds the alien path+name from run number and file version // // Origin: F. Prino (prino@to.infn.it) Bool_t kNoDraw = kFALSE; // set to kTRUE to eliminate module dependent plots void ShowDriftSpeedSDD(Char_t filnam[150]="$ALICE_ROOT/ITS/Calib/DriftSpeedSDD/Run0_9999999_v0_s0.root", Int_t firstmod=0, Int_t lastmod=260,Int_t nrun=0){ TFile *f= TFile::Open(filnam); AliCDBEntry *ent=(AliCDBEntry*)f->Get("AliCDBEntry"); TObjArray *drspSDD = (TObjArray *)ent->GetObject(); AliITSDriftSpeedArraySDD *vdriftarr0; AliITSDriftSpeedArraySDD *vdriftarr1; TGraph **gvdr0=new TGraph*[260]; TGraph **gvdr1=new TGraph*[260]; TCanvas *c0=0x0; if(!kNoDraw)c0=new TCanvas("c0","Module Drift Speed",700,1000); TGraph *vvsmod0=new TGraph(0); TGraph *vvsmod1=new TGraph(0); TGraph *poldegvsmod0=new TGraph(0); TGraph *poldegvsmod1=new TGraph(0); TGraph *anmaxvsmod0=new TGraph(0); TGraph *anmaxvsmod1=new TGraph(0); TGraph *dvcevsmod0=new TGraph(0); TGraph *dvcevsmod1=new TGraph(0); TGraph *dveevsmod0=new TGraph(0); TGraph *dveevsmod1=new TGraph(0); char tit0[100]; sprintf(tit0,"Drift Speed vs. mod. number"); if(nrun!=0)sprintf(tit0,"Drift Speed vs. mod. number - Run %d",nrun); vvsmod0->SetTitle(tit0); vvsmod1->SetTitle(tit0); sprintf(tit0,"Degree of poly fit vs. mod. number"); if(nrun!=0)sprintf(tit0,"Degree of poly fit vs. mod. number - Run %d",nrun); poldegvsmod0->SetTitle(tit0); poldegvsmod1->SetTitle(tit0); sprintf(tit0,"Anode with max. vdrift vs. mod. number"); if(nrun!=0)sprintf(tit0,"Anode with max. vdrift vs. mod. number - Run %d",nrun); anmaxvsmod0->SetTitle(tit0); anmaxvsmod1->SetTitle(tit0); sprintf(tit0,"Delta Vdrift 128-0 vs. mod. number"); if(nrun!=0)sprintf(tit0,"Delta Vdrift 128-0 vs. mod. number - Run %d",nrun); dvcevsmod0->SetTitle(tit0); dvcevsmod1->SetTitle(tit0); sprintf(tit0,"Delta Vdrift 256-0 vs. mod. number"); if(nrun!=0)sprintf(tit0,"Delta Vdrift 256-0 vs. mod. number - Run %d",nrun); dveevsmod0->SetTitle(tit0); dveevsmod1->SetTitle(tit0); TF1* fPoly=new TF1("fPoly","[0]+[1]*x+[2]*x*x+[3]*x*x*x",0.,256.); Char_t tit[100]; TString psnm0 = "vdriftSDD.ps["; TString psnm1 = "vdriftSDD.ps"; TString psnm2 = "vdriftSDD.ps]"; if(!kNoDraw) c0->Print(psnm0.Data()); Int_t cntpad = 0; Int_t iGoodInj=0; Int_t iAverSpeed=0; TLatex* tleft=new TLatex(0.2,0.82,"Side 0"); tleft->SetNDC(); tleft->SetTextColor(1); TLatex* tright=new TLatex(0.2,0.75,"Side 1"); tright->SetNDC(); tright->SetTextColor(2); for(Int_t i=firstmod; i<lastmod; i++){ Int_t iMod=i+240; Int_t i0=2*i; Int_t i1=1+2*i; vdriftarr0=(AliITSDriftSpeedArraySDD*)drspSDD->At(i0); vdriftarr1=(AliITSDriftSpeedArraySDD*)drspSDD->At(i1); AliITSDriftSpeedSDD* vdrift0=0x0; if(vdriftarr0) vdrift0=vdriftarr0->GetDriftSpeedObject(0); AliITSDriftSpeedSDD* vdrift1=0x0; if(vdriftarr1) vdrift1=vdriftarr1->GetDriftSpeedObject(0); gvdr0[i]=new TGraph(0); gvdr1[i]=new TGraph(0); gvdr0[i]->SetMarkerStyle(7); gvdr1[i]->SetMarkerStyle(7); gvdr0[i]->SetMarkerColor(kBlack); gvdr0[i]->SetLineColor(kBlack); gvdr0[i]->SetMinimum(5.); gvdr1[i]->SetMinimum(5.); gvdr0[i]->SetMaximum(7.5); gvdr1[i]->SetMaximum(7.5); sprintf(tit,"Mod %d\n",iMod); gvdr0[i]->SetTitle(tit); gvdr1[i]->SetTitle(tit); gvdr1[i]->SetMarkerColor(kRed); gvdr1[i]->SetLineColor(kRed); for(Int_t iAn=0; iAn<256; iAn++){ Float_t vel0=0; if(vdrift0) vel0=vdrift0->GetDriftSpeedAtAnode(iAn); Float_t vel1=0; if(vdrift1) vel1=vdrift1->GetDriftSpeedAtAnode(iAn); gvdr0[i]->SetPoint(iAn,(Float_t)iAn,vel0); gvdr1[i]->SetPoint(iAn,(Float_t)iAn,vel1); } if(vdriftarr0->GetInjectorStatus()>0) iGoodInj++; else iAverSpeed++; if(vdriftarr1->GetInjectorStatus()>0) iGoodInj++; else iAverSpeed++; printf(" Mod. %d \tStatusLR=%X %X \t v(an 128l)= %f",iMod,vdriftarr0->GetInjectorStatus(),vdriftarr1->GetInjectorStatus(),vdriftarr0->GetDriftSpeed(0,128)); printf(" \t v(an 128r)= %f Degree=%d %d\n",vdriftarr1->GetDriftSpeed(0,128),vdrift0->GetDegreeofPoly(),vdrift1->GetDegreeofPoly()); if(!kNoDraw){ if (i%12==0 ) { c0->cd(); c0->Modified(); c0->Update(); if (i) c0->Print(psnm1.Data()); c0->Clear(); c0->Divide(3,4); cntpad = 0; } c0->cd(++cntpad); gvdr0[i]->Draw("AP"); gvdr0[i]->GetXaxis()->SetTitle("Anode"); gvdr0[i]->GetYaxis()->SetTitle("Vdrift (#mum/ns)"); gvdr1[i]->Draw("P same"); gvdr1[i]->GetXaxis()->SetTitle("Anode"); gvdr1[i]->GetYaxis()->SetTitle("Vdrift (#mum/ns)"); tleft->Draw(); tright->Draw(); } Float_t vel0=0; Float_t pd0=0; if(vdrift0){ vel0=vdrift0->GetDriftSpeedAtAnode(128); pd0=vdrift0->GetDegreeofPoly(); } Float_t vel1=0; Float_t pd1=0; if(vdrift1){ vel1=vdrift1->GetDriftSpeedAtAnode(128); pd1=vdrift1->GetDegreeofPoly(); } vvsmod0->SetPoint(vvsmod0->GetN(),(Float_t)iMod,vel0); vvsmod1->SetPoint(vvsmod1->GetN(),(Float_t)iMod,vel1); poldegvsmod0->SetPoint(poldegvsmod0->GetN(),(Float_t)iMod,pd0); poldegvsmod1->SetPoint(poldegvsmod1->GetN(),(Float_t)iMod,pd1); for(Int_t ipar=0; ipar<=vdrift0->GetDegreeofPoly(); ipar++){ fPoly->SetParameter(ipar,vdrift0->GetDriftSpeedParameter(ipar)); } if(vdrift0->GetDegreeofPoly()<3){ for(Int_t ipar=vdrift0->GetDegreeofPoly()+1; ipar<=3; ipar++) fPoly->SetParameter(ipar,0.); } anmaxvsmod0->SetPoint(anmaxvsmod0->GetN(),(Float_t)iMod,fPoly->GetMaximumX(0.,256.)); dvcevsmod0->SetPoint(dvcevsmod0->GetN(),(Float_t)iMod,fPoly->Eval(128)-fPoly->Eval(0)); dveevsmod0->SetPoint(dveevsmod0->GetN(),(Float_t)iMod,fPoly->Eval(256)-fPoly->Eval(0)); for(Int_t ipar=0; ipar<=vdrift1->GetDegreeofPoly(); ipar++){ fPoly->SetParameter(ipar,vdrift1->GetDriftSpeedParameter(ipar)); } if(vdrift1->GetDegreeofPoly()<3){ for(Int_t ipar=vdrift1->GetDegreeofPoly()+1; ipar<=3; ipar++) fPoly->SetParameter(ipar,0.); } anmaxvsmod1->SetPoint(anmaxvsmod1->GetN(),(Float_t)iMod,fPoly->GetMaximumX(0.,256.)); dvcevsmod1->SetPoint(dvcevsmod1->GetN(),(Float_t)iMod,fPoly->Eval(128)-fPoly->Eval(0)); dveevsmod1->SetPoint(dveevsmod1->GetN(),(Float_t)iMod,fPoly->Eval(256)-fPoly->Eval(0)); // getchar(); } if(!kNoDraw){ c0->cd(); c0->Modified(); c0->Update(); c0->Print(psnm2.Data()); } printf("Number of half-modules with drift speed from injectors = %d\n",iGoodInj); printf("Number of half-modules with average drift speed = %d\n",iAverSpeed); TCanvas* c2; c2=new TCanvas("c2","",1000,700); vvsmod0->SetMarkerStyle(20); vvsmod0->Draw("AP"); vvsmod0->GetXaxis()->SetTitle("Module Number"); vvsmod0->GetYaxis()->SetTitle("Vdrift (#mum/ns)"); vvsmod1->SetMarkerStyle(21); vvsmod1->SetMarkerColor(2); vvsmod1->Draw("SAMEP"); tleft->Draw(); tright->Draw(); TCanvas* c3; c3=new TCanvas("c3","",900,900); c3->Divide(2,2); c3->cd(1); gPad->SetLeftMargin(0.14); poldegvsmod0->SetMarkerStyle(20); poldegvsmod0->Draw("AP"); poldegvsmod0->GetXaxis()->SetTitle("Module Number"); poldegvsmod0->GetYaxis()->SetTitle("Degree of Polynomial fit"); poldegvsmod0->GetYaxis()->SetTitleOffset(1.4); poldegvsmod1->SetMarkerStyle(21); poldegvsmod1->SetMarkerColor(2); poldegvsmod1->Draw("SAMEP"); tleft->Draw(); tright->Draw(); c3->cd(2); gPad->SetLeftMargin(0.14); anmaxvsmod0->SetMarkerStyle(20); anmaxvsmod0->Draw("AP"); anmaxvsmod0->GetXaxis()->SetTitle("Module Number"); anmaxvsmod0->GetYaxis()->SetTitle("Anode with max. drift speed"); anmaxvsmod0->GetYaxis()->SetTitleOffset(1.4); anmaxvsmod1->SetMarkerStyle(21); anmaxvsmod1->SetMarkerColor(2); anmaxvsmod1->Draw("SAMEP"); tleft->Draw(); tright->Draw(); c3->cd(3); gPad->SetLeftMargin(0.14); dvcevsmod0->SetMarkerStyle(20); dvcevsmod0->Draw("AP"); dvcevsmod0->GetXaxis()->SetTitle("Module Number"); dvcevsmod0->GetYaxis()->SetTitle("vdrift(anode128)-vdrift(anode0)"); dvcevsmod0->GetYaxis()->SetTitleOffset(1.4); dvcevsmod1->SetMarkerStyle(21); dvcevsmod1->SetMarkerColor(2); dvcevsmod1->Draw("SAMEP"); tleft->Draw(); tright->Draw(); c3->cd(4); gPad->SetLeftMargin(0.14); dveevsmod0->SetMarkerStyle(20); dveevsmod0->Draw("AP"); dveevsmod0->GetYaxis()->SetTitleOffset(1.4); dveevsmod0->GetXaxis()->SetTitle("Module Number"); dveevsmod0->GetYaxis()->SetTitle("vdrift(anode256)-vdrift(anode0)"); dveevsmod1->SetMarkerStyle(21); dveevsmod1->SetMarkerColor(2); dveevsmod1->Draw("SAMEP"); tleft->Draw(); tright->Draw(); } void ShowDriftSpeedSDD(Int_t nrun, Int_t year=2010, Int_t nv=-1){ TGrid::Connect("alien:",0,0,"t"); TString cmd=Form("gbbox find \"/alice/data/%d/OCDB/ITS/Calib/DriftSpeedSDD\" \"Run%d*.root\" > run.txt",year,nrun); if(nv>0){ cmd.Form("gbbox find \"/alice/data/%d/OCDB/ITS/Calib/DriftSpeedSDD\" \"Run%d_999999999_v%d_s0.root\" > run.txt",year,nrun,nv); } gSystem->Exec(cmd.Data()); Char_t filnam[200],filnamalien[200]; FILE* runtxt=fopen("run.txt","r"); fscanf(runtxt,"%s\n",filnam); if(!strstr(filnam,"/alice/data/")){ printf("Bad run number\n"); gSystem->Exec("rm run.txt"); return; } sprintf(filnamalien,"alien://%s",filnam); printf("Open file: %s\n",filnamalien); ShowDriftSpeedSDD(filnamalien,0,260,nrun); fclose(runtxt); gSystem->Exec("rm run.txt"); }
// rbOOmit: An implementation of the Certified Reduced Basis method. // Copyright (C) 2009, 2010 David J. Knezevic // This file is part of rbOOmit. // rbOOmit is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // rbOOmit is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // rbOOmit includes #include "rb_construction.h" #include "rb_assembly_expansion.h" // LibMesh includes #include "numeric_vector.h" #include "sparse_matrix.h" #include "dof_map.h" #include "libmesh_logging.h" #include "equation_systems.h" #include "exodusII_io.h" #include "linear_solver.h" #include "getpot.h" #include "mesh_base.h" #include "parallel.h" #include "xdr_cxx.h" #include "timestamp.h" #include "petsc_linear_solver.h" #include "fem_context.h" #include "dirichlet_boundaries.h" #include "zero_function.h" // For creating a directory #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fstream> #include <sstream> namespace libMesh { RBConstruction::RBConstruction (EquationSystems& es, const std::string& name, const unsigned int number) : Parent(es, name, number), inner_product_matrix(SparseMatrix<Number>::build()), non_dirichlet_inner_product_matrix(SparseMatrix<Number>::build()), constraint_matrix(SparseMatrix<Number>::build()), constrained_problem(false), single_matrix_mode(false), reuse_preconditioner(true), use_relative_bound_in_greedy(false), exit_on_repeated_greedy_parameters(true), write_data_during_training(false), impose_internal_dirichlet_BCs(false), impose_internal_fluxes(false), compute_RB_inner_product(false), store_non_dirichlet_operators(false), enforce_constraints_exactly(false), use_empty_rb_solve_in_greedy(true), Nmax(0), delta_N(1), quiet_mode(true), output_dual_innerprods_computed(false), Fq_representor_innerprods_computed(false), rb_eval(NULL), inner_product_assembly(NULL), constraint_assembly(NULL), training_tolerance(-1.) { // set assemble_before_solve flag to false // so that we control matrix assembly. assemble_before_solve = false; } RBConstruction::~RBConstruction () { this->clear(); } void RBConstruction::clear() { START_LOG("clear()", "RBConstruction"); Parent::clear(); for(unsigned int q=0; q<Aq_vector.size(); q++) { if(Aq_vector[q]) { delete Aq_vector[q]; Aq_vector[q] = NULL; } } for(unsigned int q=0; q<Fq_vector.size(); q++) { if(Fq_vector[q]) { delete Fq_vector[q]; Fq_vector[q] = NULL; } } if(store_non_dirichlet_operators) { for(unsigned int q=0; q<non_dirichlet_Aq_vector.size(); q++) { if(non_dirichlet_Aq_vector[q]) { delete non_dirichlet_Aq_vector[q]; non_dirichlet_Aq_vector[q] = NULL; } } for(unsigned int q=0; q<non_dirichlet_Fq_vector.size(); q++) { if(non_dirichlet_Fq_vector[q]) { delete non_dirichlet_Fq_vector[q]; non_dirichlet_Fq_vector[q] = NULL; } } } for(unsigned int i=0; i<outputs_vector.size(); i++) for(unsigned int q_l=0; q_l<outputs_vector[i].size(); q_l++) if(outputs_vector[i][q_l]) { delete outputs_vector[i][q_l]; outputs_vector[i][q_l] = NULL; } // Also delete the Fq representors for(unsigned int q_f=0; q_f<Fq_representor.size(); q_f++) { if(Fq_representor[q_f]) { delete Fq_representor[q_f]; Fq_representor[q_f] = NULL; } } // Set Fq_representor_innerprods_computed flag to false now // that we've cleared the Fq representors Fq_representor_innerprods_computed = false; STOP_LOG("clear()", "RBConstruction"); } std::string RBConstruction::system_type () const { return "RBConstruction"; } void RBConstruction::set_rb_evaluation(RBEvaluation& rb_eval_in) { rb_eval = &rb_eval_in; } RBEvaluation& RBConstruction::get_rb_evaluation() { if(!rb_eval) { libMesh::out << "Error: RBEvaluation object hasn't been initialized yet" << std::endl; libmesh_error(); } return *rb_eval; } bool RBConstruction::is_rb_eval_initialized() const { return (rb_eval != NULL); } RBThetaExpansion& RBConstruction::get_rb_theta_expansion() { return get_rb_evaluation().get_rb_theta_expansion(); } void RBConstruction::process_parameters_file (const std::string& parameters_filename) { // First read in data from input_filename GetPot infile(parameters_filename); const unsigned int n_training_samples = infile("n_training_samples",0); const bool deterministic_training = infile("deterministic_training",false); // String which selects an alternate pc/solver combo for the update_residual_terms solves. // Possible values are: // "unchanged" -- use whatever we were using for truth solves // "amg" -- Use Boomeramg from Hypre. DO NOT use on indefinite (Stokes) problems // "mumps" -- Use the sparse //update_residual_terms_solver = infile("update_residual_terms_solver",update_residual_terms_solver); alternative_solver = infile("rb_alternative_solver",alternative_solver); // Tell the system that it is constrained (i.e. we want to use // the Stokes inner product matrix to compute Riesz representors) constrained_problem = (constraint_assembly != NULL); // Tell the system if we're in single-matrix mode single_matrix_mode = infile("single_matrix_mode", single_matrix_mode); // Tell the system to reuse the preconditioner on consecutive // Offline solves to update residual data reuse_preconditioner = infile("reuse_preconditioner", reuse_preconditioner); // Tell the system whether or not to use a relative error bound // in the Greedy algorithm use_relative_bound_in_greedy = infile("use_relative_bound_in_greedy", use_relative_bound_in_greedy); // Tell the system whether or not to write out offline data during // train_reduced_basis. This allows us to continue from where the // training left off in case the computation stops for some reason. write_data_during_training = infile("write_data_during_training", write_data_during_training); // Read in training_parameters_random_seed value. This is used to // seed the RNG when picking the training parameters. By default the // value is -1, which means use std::time to seed the RNG. unsigned int training_parameters_random_seed_in = -1; training_parameters_random_seed_in = infile("training_parameters_random_seed", training_parameters_random_seed_in); set_training_random_seed(training_parameters_random_seed_in); // Set quiet mode const bool quiet_mode_in = infile("quiet_mode", quiet_mode); set_quiet_mode(quiet_mode_in); // Initialize RB parameters const unsigned int Nmax_in = infile("Nmax", Nmax); set_Nmax(Nmax_in); const Real training_tolerance_in = infile("training_tolerance", training_tolerance); set_training_tolerance(training_tolerance_in); // Initialize the parameter ranges and the parameters themselves initialize_parameters(parameters_filename); std::map<std::string,bool> log_scaling; const RBParameters& mu = get_parameters(); RBParameters::const_iterator it = mu.begin(); RBParameters::const_iterator it_end = mu.end(); unsigned int i=0; for( ; it != it_end; ++it) { // Read vector-based log scaling values. Note the intermediate conversion to // int... this implies log_scaling = '1 1 1...' in the input file. // log_scaling[i] = static_cast<bool>(infile("log_scaling", static_cast<int>(log_scaling[i]), i)); std::string param_name = it->first; log_scaling[param_name] = static_cast<bool>(infile("log_scaling", 0, i)); i++; } initialize_training_parameters(this->get_parameters_min(), this->get_parameters_max(), n_training_samples, log_scaling, deterministic_training); // use deterministic parameters } void RBConstruction::print_info() { // Print out info that describes the current setup libMesh::out << std::endl << "RBConstruction parameters:" << std::endl; libMesh::out << "system name: " << this->name() << std::endl; libMesh::out << "constrained_problem: " << constrained_problem << std::endl; libMesh::out << "Nmax: " << Nmax << std::endl; if(training_tolerance > 0.) libMesh::out << "Basis training error tolerance: " << get_training_tolerance() << std::endl; if( is_rb_eval_initialized() ) { libMesh::out << "Aq operators attached: " << get_rb_theta_expansion().get_n_A_terms() << std::endl; libMesh::out << "Fq functions attached: " << get_rb_theta_expansion().get_n_F_terms() << std::endl; libMesh::out << "n_outputs: " << get_rb_theta_expansion().get_n_outputs() << std::endl; for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) libMesh::out << "output " << n << ", Q_l = " << get_rb_theta_expansion().get_n_output_terms(n) << std::endl; libMesh::out << "Number of parameters: " << get_n_params() << std::endl; } else { libMesh::out << "RBThetaExpansion member is not set yet" << std::endl; } RBParameters::const_iterator it = get_parameters().begin(); RBParameters::const_iterator it_end = get_parameters().end(); for( ; it != it_end; ++it) { std::string param_name = it->first; libMesh::out << "Parameter " << param_name << ": Min = " << get_parameter_min(param_name) << ", Max = " << get_parameter_max(param_name) << ", value = " << get_parameters().get_value(param_name) << std::endl; } libMesh::out << "n_training_samples: " << get_n_training_samples() << std::endl; libMesh::out << "single-matrix mode? " << single_matrix_mode << std::endl; libMesh::out << "reuse preconditioner? " << reuse_preconditioner << std::endl; libMesh::out << "use a relative error bound in greedy? " << use_relative_bound_in_greedy << std::endl; libMesh::out << "write out data during basis training? " << write_data_during_training << std::endl; libMesh::out << "quiet mode? " << is_quiet() << std::endl; } void RBConstruction::set_rb_assembly_expansion(RBAssemblyExpansion& rb_assembly_expansion_in) { rb_assembly_expansion = &rb_assembly_expansion_in; } RBAssemblyExpansion& RBConstruction::get_rb_assembly_expansion() { if(!rb_assembly_expansion) { libMesh::out << "Error: RBAssemblyExpansion object hasn't been initialized yet" << std::endl; libmesh_error(); } return *rb_assembly_expansion; } void RBConstruction::set_inner_product_assembly(ElemAssembly& inner_product_assembly_in) { inner_product_assembly = &inner_product_assembly_in; } ElemAssembly& RBConstruction::get_inner_product_assembly() { if(!inner_product_assembly) { libMesh::out << "Error: inner_product_assembly hasn't been initialized yet" << std::endl; libmesh_error(); } return *inner_product_assembly; } void RBConstruction::set_constraint_assembly(ElemAssembly& constraint_assembly_in) { constraint_assembly = &constraint_assembly_in; } ElemAssembly& RBConstruction::get_constraint_assembly() { if(!constraint_assembly) { libMesh::out << "Error: constraint_assembly hasn't been initialized yet" << std::endl; libmesh_error(); } return *constraint_assembly; } void RBConstruction::zero_constrained_dofs_on_vector(NumericVector<Number>& vector) { const DofMap& dof_map = get_dof_map(); for(unsigned int i=dof_map.first_dof(); i<dof_map.end_dof(); i++) { if(get_dof_map().is_constrained_dof(i)) { vector.set(i, 0.); } } vector.close(); } void RBConstruction::initialize_rb_construction() { // Check that the theta and assembly objects are consistently sized libmesh_assert(get_rb_theta_expansion().get_n_A_terms() == get_rb_assembly_expansion().get_n_A_terms()); libmesh_assert(get_rb_theta_expansion().get_n_F_terms() == get_rb_assembly_expansion().get_n_F_terms()); libmesh_assert(get_rb_theta_expansion().get_n_outputs() == get_rb_assembly_expansion().get_n_outputs()); for(unsigned int i=0; i<get_rb_theta_expansion().get_n_outputs(); i++) { libmesh_assert(get_rb_theta_expansion().get_n_output_terms(i) == get_rb_assembly_expansion().get_n_output_terms(i)); } // Perform the initialization allocate_data_structures(); assemble_affine_expansion(); } void RBConstruction::assemble_affine_expansion() { // Assemble and store all of the matrices if we're // not in single-matrix mode if(!single_matrix_mode) { this->assemble_misc_matrices(); this->assemble_all_affine_operators(); } this->assemble_all_affine_vectors(); this->assemble_all_output_vectors(); } void RBConstruction::allocate_data_structures() { // Resize vectors for storing mesh-dependent data Aq_vector.resize(get_rb_theta_expansion().get_n_A_terms()); Fq_vector.resize(get_rb_theta_expansion().get_n_F_terms()); // Resize the Fq_representors and initialize each to NULL // These are basis independent and hence stored here, whereas // the Aq_representors are stored in RBEvaluation Fq_representor.resize(get_rb_theta_expansion().get_n_F_terms()); // Initialize vectors for the inner products of the Fq representors // These are basis independent and therefore stored here. unsigned int Q_f_hat = get_rb_theta_expansion().get_n_F_terms()*(get_rb_theta_expansion().get_n_F_terms()+1)/2; Fq_representor_innerprods.resize(Q_f_hat); // Resize the output vectors outputs_vector.resize(get_rb_theta_expansion().get_n_outputs()); for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) outputs_vector[n].resize( get_rb_theta_expansion().get_n_output_terms(n) ); // Resize the output dual norm vectors output_dual_innerprods.resize(get_rb_theta_expansion().get_n_outputs()); for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) { unsigned int Q_l_hat = get_rb_theta_expansion().get_n_output_terms(n)*(get_rb_theta_expansion().get_n_output_terms(n)+1)/2; output_dual_innerprods[n].resize(Q_l_hat); } // Only initialize matrices if we're not in single-matrix mode if(!single_matrix_mode) { DofMap& dof_map = this->get_dof_map(); dof_map.attach_matrix(*inner_product_matrix); inner_product_matrix->init(); inner_product_matrix->zero(); if(this->constrained_problem) { dof_map.attach_matrix(*constraint_matrix); constraint_matrix->init(); constraint_matrix->zero(); } for(unsigned int q=0; q<get_rb_theta_expansion().get_n_A_terms(); q++) { // Initialize the memory for the matrices Aq_vector[q] = SparseMatrix<Number>::build().release(); dof_map.attach_matrix(*Aq_vector[q]); Aq_vector[q]->init(); Aq_vector[q]->zero(); } // We also need to initialize a second set of non-Dirichlet operators if(store_non_dirichlet_operators) { dof_map.attach_matrix(*non_dirichlet_inner_product_matrix); non_dirichlet_inner_product_matrix->init(); non_dirichlet_inner_product_matrix->zero(); non_dirichlet_Aq_vector.resize(get_rb_theta_expansion().get_n_A_terms()); for(unsigned int q=0; q<get_rb_theta_expansion().get_n_A_terms(); q++) { // Initialize the memory for the matrices non_dirichlet_Aq_vector[q] = SparseMatrix<Number>::build().release(); dof_map.attach_matrix(*non_dirichlet_Aq_vector[q]); non_dirichlet_Aq_vector[q]->init(); non_dirichlet_Aq_vector[q]->zero(); } } } // Initialize the vectors for(unsigned int q=0; q<get_rb_theta_expansion().get_n_F_terms(); q++) { // Initialize the memory for the vectors Fq_vector[q] = NumericVector<Number>::build().release(); Fq_vector[q]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } // We also need to initialize a second set of non-Dirichlet operators if(store_non_dirichlet_operators) { non_dirichlet_Fq_vector.resize(get_rb_theta_expansion().get_n_F_terms()); for(unsigned int q=0; q<get_rb_theta_expansion().get_n_F_terms(); q++) { // Initialize the memory for the vectors non_dirichlet_Fq_vector[q] = NumericVector<Number>::build().release(); non_dirichlet_Fq_vector[q]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } } for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) for(unsigned int q_l=0; q_l<get_rb_theta_expansion().get_n_output_terms(n); q_l++) { // Initialize the memory for the truth output vectors outputs_vector[n][q_l] = (NumericVector<Number>::build().release()); outputs_vector[n][q_l]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } // Resize truth_outputs vector truth_outputs.resize(this->get_rb_theta_expansion().get_n_outputs()); } AutoPtr<FEMContext> RBConstruction::build_context () { return AutoPtr<FEMContext>(new FEMContext(*this)); } void RBConstruction::add_scaled_matrix_and_vector(Number scalar, ElemAssembly* elem_assembly, SparseMatrix<Number>* input_matrix, NumericVector<Number>* input_vector, bool symmetrize, bool apply_dof_constraints) { START_LOG("add_scaled_matrix_and_vector()", "RBConstruction"); bool assemble_matrix = (input_matrix != NULL); bool assemble_vector = (input_vector != NULL); if(!assemble_matrix && !assemble_vector) return; const MeshBase& mesh = this->get_mesh(); AutoPtr<FEMContext> c = this->build_context(); FEMContext &context = libmesh_cast_ref<FEMContext&>(*c); this->init_context(context); MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { context.pre_fe_reinit(*this, *el); context.elem_fe_reinit(); elem_assembly->interior_assembly(context); for (context.side = 0; context.side != context.elem->n_sides(); ++context.side) { // May not need to apply fluxes on non-boundary elements if( (context.elem->neighbor(context.side) != NULL) && !impose_internal_fluxes ) continue; // Impose boundary (e.g. Neumann) term context.side_fe_reinit(); elem_assembly->boundary_assembly(context); } // Need to symmetrize before imposing // periodic constraints if(assemble_matrix && symmetrize) { DenseMatrix<Number> Ke_transpose; context.elem_jacobian.get_transpose(Ke_transpose); context.elem_jacobian += Ke_transpose; context.elem_jacobian *= 0.5; } if(apply_dof_constraints) { // Apply constraints, e.g. Dirichlet and periodic constraints this->get_dof_map().constrain_element_matrix_and_vector (context.elem_jacobian, context.elem_residual, context.dof_indices); } // Scale and add to global matrix and/or vector context.elem_jacobian *= scalar; context.elem_residual *= scalar; if(assemble_matrix) input_matrix->add_matrix (context.elem_jacobian, context.dof_indices); if(assemble_vector) input_vector->add_vector (context.elem_residual, context.dof_indices); } if(assemble_matrix) input_matrix->close(); if(assemble_vector) input_vector->close(); STOP_LOG("add_scaled_matrix_and_vector()", "RBConstruction"); } void RBConstruction::set_context_solution_vec(NumericVector<Number>& vec) { // Set current_local_solution = vec so that we can access // vec from FEMContext during assembly vec.localize (*current_local_solution, this->get_dof_map().get_send_list()); } void RBConstruction::assemble_scaled_matvec(Number scalar, ElemAssembly* elem_assembly, NumericVector<Number>& dest, NumericVector<Number>& arg) { START_LOG("assemble_scaled_matvec()", "RBConstruction"); dest.zero(); // Set current_local_solution to be arg so that we // can access it from the FEMContext. Do this in a // function call so that it can be overloaded as // necessary in subclasses this->set_context_solution_vec(arg); const MeshBase& mesh = this->get_mesh(); AutoPtr<FEMContext> c = this->build_context(); FEMContext &context = libmesh_cast_ref<FEMContext&>(*c); this->init_context(context); MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { context.pre_fe_reinit(*this, *el); context.elem_fe_reinit(); elem_assembly->interior_assembly(context); for (context.side = 0; context.side != context.elem->n_sides(); ++context.side) { // May not need to apply fluxes on non-boundary elements if( (context.elem->neighbor(context.side) != NULL) && !impose_internal_fluxes ) continue; context.side_fe_reinit(); elem_assembly->boundary_assembly(context); } // Now perform the local matrix multiplcation context.elem_jacobian.vector_mult(context.elem_residual, context.elem_solution); context.elem_residual *= scalar; // Apply dof constraints, e.g. Dirichlet or periodic constraints this->get_dof_map().constrain_element_matrix_and_vector (context.elem_jacobian, context.elem_residual, context.dof_indices); dest.add_vector (context.elem_residual, context.dof_indices); } dest.close(); STOP_LOG("assemble_scaled_matvec()", "RBConstruction"); } void RBConstruction::truth_assembly() { START_LOG("truth_assembly()", "RBConstruction"); const RBParameters& mu = get_parameters(); this->matrix->zero(); this->rhs->zero(); this->matrix->close(); this->rhs->close(); if(!single_matrix_mode) { // We should have already assembled the matrices // and vectors in the affine expansion, so // just use them for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { matrix->add(get_rb_theta_expansion().eval_A_theta(q_a, mu), *get_Aq(q_a)); } AutoPtr< NumericVector<Number> > temp_vec = NumericVector<Number>::build(); temp_vec->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { *temp_vec = *get_Fq(q_f); temp_vec->scale( get_rb_theta_expansion().eval_F_theta(q_f, mu) ); rhs->add(*temp_vec); } if(constrained_problem) matrix->add(1., *constraint_matrix); } else { // In low memory mode we do not store the matrices // from the affine expansion, so need to assemble // For efficiency (i.e. to avoid doing Q_a+Q_f loops // over the mesh) we do not use add_scaled_matrix_and_vector // here const MeshBase& mesh = this->get_mesh(); std::vector<FEMContext*> Aq_context(get_rb_theta_expansion().get_n_A_terms()); for(unsigned int q_a=0; q_a<Aq_context.size(); q_a++) { Aq_context[q_a] = this->build_context().release(); this->init_context(*Aq_context[q_a]); } std::vector<FEMContext*> Fq_context(get_rb_theta_expansion().get_n_F_terms()); for(unsigned int q_f=0; q_f<Fq_context.size(); q_f++) { Fq_context[q_f] = this->build_context().release(); this->init_context(*Fq_context[q_f]); } MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { Aq_context[q_a]->pre_fe_reinit(*this, *el); Aq_context[q_a]->elem_fe_reinit(); rb_assembly_expansion->perform_A_interior_assembly(q_a, *Aq_context[q_a]); } for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { Fq_context[q_f]->pre_fe_reinit(*this, *el); Fq_context[q_f]->elem_fe_reinit(); rb_assembly_expansion->perform_F_interior_assembly(q_f, *Fq_context[q_f]); } for (Aq_context[0]->side = 0; Aq_context[0]->side != Aq_context[0]->elem->n_sides(); ++Aq_context[0]->side) { // May not need to apply fluxes on non-boundary elements if( (Aq_context[0]->elem->neighbor(Aq_context[0]->side) != NULL) && !impose_internal_fluxes ) continue; // Update the side information for all contexts for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { // Update the side information for all contexts Aq_context[q_a]->side = Aq_context[0]->side; Aq_context[q_a]->side_fe_reinit(); rb_assembly_expansion->perform_A_boundary_assembly(q_a, *Aq_context[q_a]); } // Impose boundary terms, e.g. Neuman BCs for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { // Update the side information for all contexts Fq_context[q_f]->side = Aq_context[0]->side; Fq_context[q_f]->side_fe_reinit(); rb_assembly_expansion->perform_F_boundary_assembly(q_f, *Fq_context[q_f]); } } // Constrain the dofs to impose Dirichlet BCs, hanging node or periodic constraints for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { this->get_dof_map().constrain_element_matrix (Aq_context[q_a]->elem_jacobian, Aq_context[q_a]->dof_indices); } for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { this->get_dof_map().constrain_element_vector (Fq_context[q_f]->elem_residual, Fq_context[q_f]->dof_indices); } // Finally add local matrices/vectors to global system for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { // Scale by theta_q_a Aq_context[q_a]->elem_jacobian *= get_rb_theta_expansion().eval_A_theta(q_a, mu); this->matrix->add_matrix (Aq_context[q_a]->elem_jacobian, Aq_context[q_a]->dof_indices); } for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { // Scale by theta_q_f Fq_context[q_f]->elem_residual *= get_rb_theta_expansion().eval_F_theta(q_f, mu); this->rhs->add_vector (Fq_context[q_f]->elem_residual, Fq_context[q_f]->dof_indices); } } if(constrained_problem) add_scaled_matrix_and_vector(1., constraint_assembly, matrix, NULL); // Delete all the ptrs to FEMContexts! for(unsigned int q_a=0; q_a<Aq_context.size(); q_a++) { delete Aq_context[q_a]; Aq_context[q_a] = NULL; } Aq_context.clear(); for(unsigned int q_f=0; q_f<Fq_context.size(); q_f++) { delete Fq_context[q_f]; Fq_context[q_f]; } Fq_context.clear(); } this->matrix->close(); this->rhs->close(); STOP_LOG("truth_assembly()", "RBConstruction"); } void RBConstruction::assemble_inner_product_matrix(SparseMatrix<Number>* input_matrix, bool apply_dof_constraints) { input_matrix->zero(); add_scaled_matrix_and_vector(1., inner_product_assembly, input_matrix, NULL, false, /* symmetrize */ apply_dof_constraints); } void RBConstruction::assemble_constraint_matrix(SparseMatrix<Number>* input_matrix) { input_matrix->zero(); add_scaled_matrix_and_vector(1., constraint_assembly, input_matrix, NULL); } void RBConstruction::assemble_and_add_constraint_matrix(SparseMatrix<Number>* input_matrix) { add_scaled_matrix_and_vector(1., constraint_assembly, input_matrix, NULL); } void RBConstruction::assemble_Aq_matrix(unsigned int q, SparseMatrix<Number>* input_matrix, bool apply_dof_constraints) { if(q >= get_rb_theta_expansion().get_n_A_terms()) { libMesh::err << "Error: We must have q < Q_a in assemble_Aq_matrix." << std::endl; libmesh_error(); } input_matrix->zero(); add_scaled_matrix_and_vector(1., &rb_assembly_expansion->get_A_assembly(q), input_matrix, NULL, false, /* symmetrize */ apply_dof_constraints); } void RBConstruction::add_scaled_Aq(Number scalar, unsigned int q_a, SparseMatrix<Number>* input_matrix, bool symmetrize) { START_LOG("add_scaled_Aq()", "RBConstruction"); if(q_a >= get_rb_theta_expansion().get_n_A_terms()) { libMesh::err << "Error: We must have q < Q_a in add_scaled_Aq." << std::endl; libmesh_error(); } if(!single_matrix_mode && !symmetrize) { input_matrix->add(scalar, *get_Aq(q_a)); input_matrix->close(); } else { add_scaled_matrix_and_vector(scalar, &rb_assembly_expansion->get_A_assembly(q_a), input_matrix, NULL, symmetrize); } STOP_LOG("add_scaled_Aq()", "RBConstruction"); } void RBConstruction::assemble_misc_matrices() { if(single_matrix_mode) { libMesh::out << "Error: Cannot store misc matrices in single-matrix mode." << std::endl; libmesh_error(); } assemble_inner_product_matrix(inner_product_matrix.get()); if(store_non_dirichlet_operators) { assemble_inner_product_matrix(non_dirichlet_inner_product_matrix.get(), /* apply_dof_constraints = */ false); } if( constrained_problem ) { assemble_constraint_matrix(constraint_matrix.get()); } } void RBConstruction::assemble_all_affine_operators() { if(single_matrix_mode) { libMesh::out << "Error: Cannot store affine matrices in single-matrix mode." << std::endl; libmesh_error(); } for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) assemble_Aq_matrix(q_a, get_Aq(q_a)); if(store_non_dirichlet_operators) { for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) assemble_Aq_matrix(q_a, get_non_dirichlet_Aq(q_a), false); } } void RBConstruction::assemble_all_affine_vectors() { for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) assemble_Fq_vector(q_f, get_Fq(q_f)); if(store_non_dirichlet_operators) { for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) assemble_Fq_vector(q_f, get_non_dirichlet_Fq(q_f), false); } } void RBConstruction::assemble_Fq_vector(unsigned int q, NumericVector<Number>* input_vector, bool apply_dof_constraints) { if(q >= get_rb_theta_expansion().get_n_F_terms()) { libMesh::err << "Error: We must have q < Q_f in assemble_Fq_vector." << std::endl; libmesh_error(); } input_vector->zero(); add_scaled_matrix_and_vector(1., &rb_assembly_expansion->get_F_assembly(q), NULL, input_vector, false, /* symmetrize */ apply_dof_constraints /* apply_dof_constraints */); } void RBConstruction::assemble_all_output_vectors() { for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) for(unsigned int q_l=0; q_l<get_rb_theta_expansion().get_n_output_terms(n); q_l++) { get_output_vector(n, q_l)->zero(); add_scaled_matrix_and_vector(1., &rb_assembly_expansion->get_output_assembly(n,q_l), NULL, get_output_vector(n,q_l)); } } Real RBConstruction::train_reduced_basis(const std::string& directory_name, const bool resize_rb_eval_data) { START_LOG("train_reduced_basis()", "RBConstruction"); int count = 0; // initialize rb_eval's parameters get_rb_evaluation().initialize_parameters(*this); // possibly resize data structures according to Nmax if(resize_rb_eval_data) { get_rb_evaluation().resize_data_structures(get_Nmax()); } // Clear the Greedy param list for(unsigned int i=0; i<get_rb_evaluation().greedy_param_list.size(); i++) { get_rb_evaluation().greedy_param_list[i].clear(); } get_rb_evaluation().greedy_param_list.clear(); Real training_greedy_error; // If we are continuing from a previous training run, // we might already be at the max number of basis functions. // If so, we can just return. if(get_rb_evaluation().get_n_basis_functions() >= get_Nmax()) { libMesh::out << "Maximum number of basis functions reached: Nmax = " << get_Nmax() << std::endl; return 0.; } // Compute the dual norms of the outputs if we haven't already done so compute_output_dual_innerprods(); // Compute the Fq Riesz representor dual norms if we haven't already done so compute_Fq_representor_innerprods(); libMesh::out << std::endl << "---- Performing Greedy basis enrichment ----" << std::endl; while(true) { libMesh::out << std::endl << "---- Basis dimension: " << get_rb_evaluation().get_n_basis_functions() << " ----" << std::endl; if( count > 0 || (count==0 && use_empty_rb_solve_in_greedy) ) { libMesh::out << "Performing RB solves on training set" << std::endl; training_greedy_error = compute_max_error_bound(); libMesh::out << "Maximum " << (use_relative_bound_in_greedy ? "(relative)" : "(absolute)") << " error bound is " << training_greedy_error << std::endl << std::endl; if(write_data_during_training) { std::stringstream new_dir_name; new_dir_name << directory_name << "_" << get_rb_evaluation().get_n_basis_functions(); libMesh::out << "Writing out RB data to " << new_dir_name.str() << std::endl; get_rb_evaluation().write_offline_data_to_files(new_dir_name.str()); } // Break out of training phase if we have reached Nmax // or if the training_tolerance is satisfied. if( greedy_termination_test(training_greedy_error, count) ) { break; } } libMesh::out << "Performing truth solve at parameter:" << std::endl; print_parameters(); // Update the list of Greedily selected parameters this->update_greedy_param_list(); // Perform an Offline truth solve for the current parameter truth_solve(-1); // Add orthogonal part of the snapshot to the RB space libMesh::out << "Enriching the RB space" << std::endl; enrich_RB_space(); update_system(); // Increment counter count++; } this->update_greedy_param_list(); STOP_LOG("train_reduced_basis()", "RBConstruction"); return training_greedy_error; } bool RBConstruction::greedy_termination_test(Real training_greedy_error, int) { if(training_greedy_error < this->training_tolerance) { libMesh::out << "Specified error tolerance reached." << std::endl; return true; } if(get_rb_evaluation().get_n_basis_functions() >= this->get_Nmax()) { libMesh::out << "Maximum number of basis functions reached: Nmax = " << get_Nmax() << std::endl; return true; } if(exit_on_repeated_greedy_parameters) { for(unsigned int i=0; i<get_rb_evaluation().greedy_param_list.size(); i++) { RBParameters& previous_parameters = get_rb_evaluation().greedy_param_list[i]; if(previous_parameters == get_parameters()) { libMesh::out << "Exiting greedy because the same parameters were selected twice" << std::endl; return true; } } } return false; } void RBConstruction::update_greedy_param_list() { get_rb_evaluation().greedy_param_list.push_back( get_parameters() ); } const RBParameters& RBConstruction::get_greedy_parameter(unsigned int i) { if( i >= get_rb_evaluation().greedy_param_list.size() ) { libMesh::out << "Error: Argument in RBConstruction::get_greedy_parameter is too large." << std::endl; libmesh_error(); } return get_rb_evaluation().greedy_param_list[i]; } Real RBConstruction::truth_solve(int plot_solution) { START_LOG("truth_solve()", "RBConstruction"); truth_assembly(); // Safer to zero the solution first, especially when using iterative solvers solution->zero(); solve(); const RBParameters& mu = get_parameters(); // Make sure we didn't max out the number of iterations if( (this->n_linear_iterations() >= this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) && (this->final_linear_residual() > this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) ) { libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = " << this->final_linear_residual() << ", number of iterations = " << this->n_linear_iterations() << std::endl << std::endl; // libmesh_error(); } for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) { truth_outputs[n] = 0.; for(unsigned int q_l=0; q_l<get_rb_theta_expansion().get_n_output_terms(n); q_l++) truth_outputs[n] += libmesh_conj(get_rb_theta_expansion().eval_output_theta(n, q_l, mu))* get_output_vector(n,q_l)->dot(*solution); } if(plot_solution > 0) { #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(get_mesh()).write_equation_systems ("truth.e", this->get_equation_systems()); #endif } // Get the X norm of the truth solution // Useful for normalizing our true error data if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector, *solution); } else { assemble_inner_product_matrix(matrix); matrix->vector_mult(*inner_product_storage_vector, *solution); } Number truth_X_norm = std::sqrt(inner_product_storage_vector->dot(*solution)); STOP_LOG("truth_solve()", "RBConstruction"); return libmesh_real(truth_X_norm); } void RBConstruction::set_Nmax(unsigned int Nmax_in) { this->Nmax = Nmax_in; } void RBConstruction::load_basis_function(unsigned int i) { START_LOG("load_basis_function()", "RBConstruction"); libmesh_assert(i < get_rb_evaluation().get_n_basis_functions()); *solution = get_rb_evaluation().get_basis_function(i); this->update(); STOP_LOG("load_basis_function()", "RBConstruction"); } void RBConstruction::enrich_RB_space() { START_LOG("enrich_RB_space()", "RBConstruction"); NumericVector<Number>* new_bf = NumericVector<Number>::build().release(); new_bf->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); *new_bf = *solution; // compute orthogonalization AutoPtr< NumericVector<Number> > proj_index = NumericVector<Number>::build(); proj_index->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); if(single_matrix_mode) assemble_inner_product_matrix(matrix); for(unsigned int index=0; index<get_rb_evaluation().get_n_basis_functions(); index++) { // invoke copy constructor for NumericVector *proj_index = get_rb_evaluation().get_basis_function(index); if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector,*proj_index); } else { matrix->vector_mult(*inner_product_storage_vector,*proj_index); } Number scalar = inner_product_storage_vector->dot(*new_bf); new_bf->add(-scalar,*proj_index); } // Normalize new_bf if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector,*new_bf); } else { matrix->vector_mult(*inner_product_storage_vector,*new_bf); } Number new_bf_norm = std::sqrt( inner_product_storage_vector->dot(*new_bf) ); if(new_bf_norm == 0.) { new_bf->zero(); // avoid potential nan's } else { new_bf->scale(1./new_bf_norm); } // load the new basis function into the basis_functions vector. get_rb_evaluation().basis_functions.push_back( new_bf ); STOP_LOG("enrich_RB_space()", "RBConstruction"); } void RBConstruction::update_system() { libMesh::out << "Updating RB matrices" << std::endl; update_RB_system_matrices(); libMesh::out << "Updating RB residual terms" << std::endl; // Note: the solves in this function employ a single system matrix and multiple // right-hand sides, so we may get better performance using a different // preconditioner, or even a direct solver. std::pair<std::string,std::string> orig_solver = this->set_alternative_solver(this->linear_solver); update_residual_terms(); // Change the preconditioner, Krylov solver back to their original // value. Note: does nothing if RBBase::alternative_solver == // "unchanged". this->reset_alternative_solver(this->linear_solver, orig_solver); } Real RBConstruction::get_RB_error_bound() { get_rb_evaluation().set_parameters( get_parameters() ); Real error_bound = get_rb_evaluation().rb_solve(get_rb_evaluation().get_n_basis_functions()); // Should we normalize the error bound to return a relative bound? if(use_relative_bound_in_greedy) { error_bound /= get_rb_evaluation().get_rb_solution_norm(); } return error_bound; } void RBConstruction::recompute_all_residual_terms(bool compute_inner_products) { // Use alternative solver for residual terms solves std::pair<std::string,std::string> orig_solver = this->set_alternative_solver(this->linear_solver); // Compute the basis independent terms Fq_representor_innerprods_computed = false; compute_Fq_representor_innerprods(compute_inner_products); // and all the basis dependent terms unsigned int saved_delta_N = delta_N; delta_N = get_rb_evaluation().get_n_basis_functions(); update_residual_terms(compute_inner_products); delta_N = saved_delta_N; // Return to original solver this->reset_alternative_solver(this->linear_solver, orig_solver); } Real RBConstruction::compute_max_error_bound() { START_LOG("compute_max_error_bound()", "RBConstruction"); training_error_bounds.resize(this->get_local_n_training_samples()); // keep track of the maximum error unsigned int max_err_index = 0; Real max_err = 0.; unsigned int first_index = get_first_local_training_index(); for(unsigned int i=0; i<get_local_n_training_samples(); i++) { // Load training parameter i, this is only loaded // locally since the RB solves are local. set_params_from_training_set( first_index+i ); training_error_bounds[i] = get_RB_error_bound(); if(training_error_bounds[i] > max_err) { max_err_index = i; max_err = training_error_bounds[i]; } } std::pair<unsigned int,Real> error_pair(first_index+max_err_index, max_err); get_global_max_error_pair(error_pair); // Now broadcast the parameter that produced the maximum error unsigned int root_id=0; if( (get_first_local_training_index() <= error_pair.first) && (error_pair.first < get_last_local_training_index()) ) { set_params_from_training_set( error_pair.first ); root_id = libMesh::processor_id(); } Parallel::sum(root_id); // root_id is only non-zero on one processor broadcast_parameters(root_id); STOP_LOG("compute_max_error_bound()", "RBConstruction"); return error_pair.second; } void RBConstruction::update_RB_system_matrices() { START_LOG("update_RB_system_matrices()", "RBConstruction"); unsigned int RB_size = get_rb_evaluation().get_n_basis_functions(); AutoPtr< NumericVector<Number> > temp = NumericVector<Number>::build(); temp->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { for(unsigned int i=(RB_size-delta_N); i<RB_size; i++) { get_rb_evaluation().RB_Fq_vector[q_f](i) = get_Fq(q_f)->dot(get_rb_evaluation().get_basis_function(i)); } } for(unsigned int i=(RB_size-delta_N); i<RB_size; i++) { for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) for(unsigned int q_l=0; q_l<get_rb_theta_expansion().get_n_output_terms(n); q_l++) { get_rb_evaluation().RB_output_vectors[n][q_l](i) = get_output_vector(n,q_l)->dot(get_rb_evaluation().get_basis_function(i)); } for(unsigned int j=0; j<RB_size; j++) { Number value = 0.; if(compute_RB_inner_product) { // Compute reduced inner_product_matrix temp->zero(); if(!single_matrix_mode) { inner_product_matrix->vector_mult(*temp, get_rb_evaluation().get_basis_function(j)); } else { assemble_inner_product_matrix(matrix); matrix->vector_mult(*temp, get_rb_evaluation().get_basis_function(j)); } value = get_rb_evaluation().get_basis_function(i).dot(*temp); get_rb_evaluation().RB_inner_product_matrix(i,j) = value; if(i!=j) { // The inner product matrix is assumed // to be symmetric get_rb_evaluation().RB_inner_product_matrix(j,i) = value; } } for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { // Compute reduced Aq matrix temp->zero(); if(!single_matrix_mode) { get_Aq(q_a)->vector_mult(*temp, get_rb_evaluation().get_basis_function(j)); } else { assemble_Aq_matrix(q_a,matrix); matrix->vector_mult(*temp, get_rb_evaluation().get_basis_function(j)); } value = (*temp).dot(get_rb_evaluation().get_basis_function(i)); get_rb_evaluation().RB_Aq_vector[q_a](i,j) = value; if(i!=j) { temp->zero(); if(!single_matrix_mode) { get_Aq(q_a)->vector_mult(*temp, get_rb_evaluation().get_basis_function(i)); } else { // matrix should still hold affine matrix q_a matrix->vector_mult(*temp, get_rb_evaluation().get_basis_function(i)); } value = (*temp).dot(get_rb_evaluation().get_basis_function(j)); get_rb_evaluation().RB_Aq_vector[q_a](j,i) = value; } } } } STOP_LOG("update_RB_system_matrices()", "RBConstruction"); } void RBConstruction::update_residual_terms(bool compute_inner_products) { START_LOG("update_residual_terms()", "RBConstruction"); unsigned int RB_size = get_rb_evaluation().get_n_basis_functions(); if(!single_matrix_mode) { matrix->zero(); matrix->add(1., *inner_product_matrix); if(constrained_problem) matrix->add(1., *constraint_matrix); } if(single_matrix_mode) { assemble_inner_product_matrix(matrix); if(constrained_problem) add_scaled_matrix_and_vector(1., constraint_assembly, matrix, NULL); } if(reuse_preconditioner) { // For the first solve, make sure we generate a new preconditioner linear_solver->reuse_preconditioner(false); } for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { for(unsigned int i=(RB_size-delta_N); i<RB_size; i++) { // Initialize the vector in which we'll store the representor if(!get_rb_evaluation().Aq_representor[q_a][i]) { get_rb_evaluation().Aq_representor[q_a][i] = (NumericVector<Number>::build().release()); get_rb_evaluation().Aq_representor[q_a][i]->init(this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } libmesh_assert(get_rb_evaluation().Aq_representor[q_a][i]->size() == this->n_dofs() && get_rb_evaluation().Aq_representor[q_a][i]->local_size() == this->n_local_dofs() ); rhs->zero(); if(!single_matrix_mode) { get_Aq(q_a)->vector_mult(*rhs, get_rb_evaluation().get_basis_function(i)); } else { assemble_scaled_matvec(1., &rb_assembly_expansion->get_A_assembly(q_a), *rhs, get_rb_evaluation().get_basis_function(i)); } rhs->scale(-1.); // zero_dirichlet_dofs_on_rhs(); solution->zero(); if (!is_quiet()) { libMesh::out << "Starting solve [q_a][i]=[" << q_a <<"]["<< i << "] in RBConstruction::update_residual_terms() at " << Utility::get_timestamp() << std::endl; } solve(); if (!is_quiet()) { libMesh::out << "Finished solve [q_a][i]=[" << q_a <<"]["<< i << "] in RBConstruction::update_residual_terms() at " << Utility::get_timestamp() << std::endl; libMesh::out << this->n_linear_iterations() << " iterations, final residual " << this->final_linear_residual() << std::endl; } // Make sure we didn't max out the number of iterations if( (this->n_linear_iterations() >= this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) && (this->final_linear_residual() > this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) ) { libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = " << this->final_linear_residual() << ", number of iterations = " << this->n_linear_iterations() << std::endl << std::endl; // libmesh_error(); } // Store the representor *get_rb_evaluation().Aq_representor[q_a][i] = *solution; if(reuse_preconditioner) { // set this flag again in case we didn't do any F solves linear_solver->reuse_preconditioner(true); } } } if(reuse_preconditioner) { linear_solver->reuse_preconditioner(false); } // Now compute and store the inner products (if requested) if (compute_inner_products) { if(single_matrix_mode && constrained_problem) assemble_inner_product_matrix(matrix); for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector,*Fq_representor[q_f]); } else { matrix->vector_mult(*inner_product_storage_vector,*Fq_representor[q_f]); } for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { for(unsigned int i=(RB_size-delta_N); i<RB_size; i++) { get_rb_evaluation().Fq_Aq_representor_innerprods[q_f][q_a][i] = inner_product_storage_vector->dot(*get_rb_evaluation().Aq_representor[q_a][i]); } } } unsigned int q=0; for(unsigned int q_a1=0; q_a1<get_rb_theta_expansion().get_n_A_terms(); q_a1++) { for(unsigned int q_a2=q_a1; q_a2<get_rb_theta_expansion().get_n_A_terms(); q_a2++) { for(unsigned int i=(RB_size-delta_N); i<RB_size; i++) { for(unsigned int j=0; j<RB_size; j++) { if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector, *get_rb_evaluation().Aq_representor[q_a2][j]); } else { matrix->vector_mult(*inner_product_storage_vector, *get_rb_evaluation().Aq_representor[q_a2][j]); } get_rb_evaluation().Aq_Aq_representor_innerprods[q][i][j] = inner_product_storage_vector->dot(*get_rb_evaluation().Aq_representor[q_a1][i]); if(i != j) { if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector, *get_rb_evaluation().Aq_representor[q_a2][i]); } else { matrix->vector_mult(*inner_product_storage_vector, *get_rb_evaluation().Aq_representor[q_a2][i]); } get_rb_evaluation().Aq_Aq_representor_innerprods[q][j][i] = inner_product_storage_vector->dot(*get_rb_evaluation().Aq_representor[q_a1][j]); } } } q++; } } } // end if (compute_inner_products) STOP_LOG("update_residual_terms()", "RBConstruction"); } void RBConstruction::assemble_matrix_for_output_dual_solves() { // By default we use the inner product matrix for steady problems if(!single_matrix_mode) { matrix->zero(); matrix->close(); matrix->add(1., *inner_product_matrix); } else { assemble_inner_product_matrix(matrix); } } void RBConstruction::compute_output_dual_innerprods() { // Skip calculations if we've already computed the output dual norms if(!output_dual_innerprods_computed) { // Short circuit if we don't have any outputs if( get_rb_theta_expansion().get_n_outputs() == 0 ) { output_dual_innerprods_computed = true; return; } // Only log if we get to here START_LOG("compute_output_dual_innerprods()", "RBConstruction"); libMesh::out << "Compute output dual norms" << std::endl; // Note: the solves in this function employ a single system matrix and multiple // right-hand sides, so we may get better performance using a different // preconditioner, or even a direct solver. std::pair<std::string,std::string> orig_solver = this->set_alternative_solver(this->linear_solver); // Find out the largest value of Q_l unsigned int max_Q_l = 0; for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) max_Q_l = (get_rb_theta_expansion().get_n_output_terms(n) > max_Q_l) ? get_rb_theta_expansion().get_n_output_terms(n) : max_Q_l; std::vector< NumericVector<Number>* > L_q_representor(max_Q_l); for(unsigned int q=0; q<max_Q_l; q++) { L_q_representor[q] = (NumericVector<Number>::build().release()); L_q_representor[q]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } if(reuse_preconditioner) { // For the first solve, make sure we generate a new preconditioner linear_solver->reuse_preconditioner(false); } for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) { // If constrained_problem, we need to reassemble to add the constraint part back in if( (n==0) || constrained_problem) { assemble_matrix_for_output_dual_solves(); if(constrained_problem) { if(!single_matrix_mode) { matrix->add(1., *constraint_matrix); } else { add_scaled_matrix_and_vector(1., constraint_assembly, matrix, NULL); } } } for(unsigned int q_l=0; q_l<get_rb_theta_expansion().get_n_output_terms(n); q_l++) { rhs->zero(); rhs->add(1., *get_output_vector(n,q_l)); // zero_dirichlet_dofs_on_rhs(); solution->zero(); if (!is_quiet()) libMesh::out << "Starting solve n=" << n << ", q_l=" << q_l << " in RBConstruction::compute_output_dual_innerprods() at " << Utility::get_timestamp() << std::endl; solve(); if (!is_quiet()) { libMesh::out << "Finished solve n=" << n << ", q_l=" << q_l << " in RBConstruction::compute_output_dual_innerprods() at " << Utility::get_timestamp() << std::endl; libMesh::out << this->n_linear_iterations() << " iterations, final residual " << this->final_linear_residual() << std::endl; } // Make sure we didn't max out the number of iterations if( (this->n_linear_iterations() >= this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) && (this->final_linear_residual() > this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) ) { libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = " << this->final_linear_residual() << ", number of iterations = " << this->n_linear_iterations() << std::endl << std::endl; // libmesh_error(); } *L_q_representor[q_l] = *solution; if(reuse_preconditioner) { // After we do a solve, tell PETSc we want to reuse the preconditioner // since the system matrix is not changing. linear_solver->reuse_preconditioner(true); } } // Get rid of the constraint part of the matrix before computing inner products if(constrained_problem) assemble_matrix_for_output_dual_solves(); unsigned int q=0; for(unsigned int q_l1=0; q_l1<get_rb_theta_expansion().get_n_output_terms(n); q_l1++) { matrix->vector_mult(*inner_product_storage_vector, *L_q_representor[q_l1]); for(unsigned int q_l2=q_l1; q_l2<get_rb_theta_expansion().get_n_output_terms(n); q_l2++) { output_dual_innerprods[n][q] = L_q_representor[q_l2]->dot(*inner_product_storage_vector); libMesh::out << "output_dual_innerprods[" << n << "][" << q << "] = " << output_dual_innerprods[n][q] << std::endl; q++; } } } // reset same_preconditioner to false once all solves are finished if(reuse_preconditioner) { linear_solver->reuse_preconditioner(false); } // Finally clear the L_q_representor vectors for(unsigned int q=0; q<max_Q_l; q++) { if(L_q_representor[q]) { delete L_q_representor[q]; L_q_representor[q] = NULL; } } output_dual_innerprods_computed = true; // Change the preconditioner, Krylov solver back to their original // value. Note: does nothing if RBBase::alternative_solver == // "unchanged". this->reset_alternative_solver(this->linear_solver, orig_solver); STOP_LOG("compute_output_dual_innerprods()", "RBConstruction"); } get_rb_evaluation().output_dual_innerprods = output_dual_innerprods; } void RBConstruction::compute_Fq_representor_innerprods(bool compute_inner_products) { // Skip calculations if we've already computed the Fq_representors if(!Fq_representor_innerprods_computed) { // Only log if we get to here START_LOG("compute_Fq_representor_innerprods()", "RBConstruction"); if(!single_matrix_mode) { matrix->zero(); matrix->close(); matrix->add(1., *inner_product_matrix); if(constrained_problem) matrix->add(1., *constraint_matrix); } if(single_matrix_mode) { assemble_inner_product_matrix(matrix); if(constrained_problem) add_scaled_matrix_and_vector(1., constraint_assembly, matrix, NULL); } if(reuse_preconditioner) { // For the first solve, make sure we generate a new preconditioner linear_solver->reuse_preconditioner(false); } for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { if(!Fq_representor[q_f]) { Fq_representor[q_f] = (NumericVector<Number>::build().release()); Fq_representor[q_f]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } libmesh_assert(Fq_representor[q_f]->size() == this->n_dofs() && Fq_representor[q_f]->local_size() == this->n_local_dofs() ); rhs->zero(); rhs->add(1., *get_Fq(q_f)); // zero_dirichlet_dofs_on_rhs(); solution->zero(); if (!is_quiet()) libMesh::out << "Starting solve q_f=" << q_f << " in RBConstruction::update_residual_terms() at " << Utility::get_timestamp() << std::endl; solve(); if (!is_quiet()) { libMesh::out << "Finished solve q_f=" << q_f << " in RBConstruction::update_residual_terms() at " << Utility::get_timestamp() << std::endl; libMesh::out << this->n_linear_iterations() << " iterations, final residual " << this->final_linear_residual() << std::endl; } // Make sure we didn't max out the number of iterations if( (this->n_linear_iterations() >= this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) && (this->final_linear_residual() > this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) ) { libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = " << this->final_linear_residual() << ", number of iterations = " << this->n_linear_iterations() << std::endl << std::endl; // libmesh_error(); } *Fq_representor[q_f] = *solution; if(reuse_preconditioner) { // After we do a solve, tell PETSc we want to reuse the preconditioner // since the system matrix is not changing. linear_solver->reuse_preconditioner(true); } } // Reset the same_preconditioner flag if(reuse_preconditioner) { linear_solver->reuse_preconditioner(false); } if (compute_inner_products) { unsigned int q=0; if(single_matrix_mode && constrained_problem) assemble_inner_product_matrix(matrix); for(unsigned int q_f1=0; q_f1<get_rb_theta_expansion().get_n_F_terms(); q_f1++) { if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector, *Fq_representor[q_f1]); } else { matrix->vector_mult(*inner_product_storage_vector, *Fq_representor[q_f1]); } for(unsigned int q_f2=q_f1; q_f2<get_rb_theta_expansion().get_n_F_terms(); q_f2++) { Fq_representor_innerprods[q] = inner_product_storage_vector->dot(*Fq_representor[q_f2]); q++; } } } // end if (compute_inner_products) Fq_representor_innerprods_computed = true; STOP_LOG("compute_Fq_representor_innerprods()", "RBConstruction"); } get_rb_evaluation().Fq_representor_innerprods = Fq_representor_innerprods; } void RBConstruction::load_rb_solution() { START_LOG("load_rb_solution()", "RBConstruction"); solution->zero(); if(get_rb_evaluation().RB_solution.size() > get_rb_evaluation().get_n_basis_functions()) { libMesh::err << "ERROR: System contains " << get_rb_evaluation().get_n_basis_functions() << " basis functions." << " RB_solution vector constains " << get_rb_evaluation().RB_solution.size() << " entries." << " RB_solution in RBConstruction::load_rb_solution is too long!" << std::endl; libmesh_error(); } for(unsigned int i=0; i<get_rb_evaluation().RB_solution.size(); i++) { solution->add(get_rb_evaluation().RB_solution(i), get_rb_evaluation().get_basis_function(i)); } update(); STOP_LOG("load_rb_solution()", "RBConstruction"); } // The slow (but simple, non-error prone) way to compute the residual dual norm // Useful for error checking //Real RBConstruction::compute_residual_dual_norm(const unsigned int N) //{ // START_LOG("compute_residual_dual_norm()", "RBConstruction"); // // // Put the residual in rhs in order to compute the norm of the Riesz representor // // Note that this only works in serial since otherwise each processor will // // have a different parameter value during the Greedy training. // // AutoPtr< NumericVector<Number> > RB_sol = NumericVector<Number>::build(); // RB_sol->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); // // AutoPtr< NumericVector<Number> > temp = NumericVector<Number>::build(); // temp->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); // // for(unsigned int i=0; i<N; i++) // { // RB_sol->add(RB_solution(i), get_rb_evaluation().get_basis_function(i)); // } // // this->truth_assembly(); // matrix->vector_mult(*temp, *RB_sol); // rhs->add(-1., *temp); // // // Then solve to get the Reisz representor // matrix->zero(); // matrix->add(1., *inner_product_matrix); // if(constrained_problem) // matrix->add(1., *constraint_matrix); // // solution->zero(); // solve(); // // Make sure we didn't max out the number of iterations // if( (this->n_linear_iterations() >= // this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) && // (this->final_linear_residual() > // this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) ) // { // libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = " // << this->final_linear_residual() << ", number of iterations = " // << this->n_linear_iterations() << std::endl << std::endl; // // libmesh_error(); // } // // if(!single_matrix_mode) // { // inner_product_matrix->vector_mult(*inner_product_storage_vector, *solution); // } // else // { // assemble_inner_product_matrix(matrix); // matrix->vector_mult(*inner_product_storage_vector, *solution); // } // // Real slow_residual_norm_sq = solution->dot(*inner_product_storage_vector); // // STOP_LOG("compute_residual_dual_norm()", "RBConstruction"); // // return std::sqrt( libmesh_real(slow_residual_norm_sq) ); //} SparseMatrix<Number>* RBConstruction::get_inner_product_matrix() { if(single_matrix_mode) { libMesh::err << "Error: The inner-product matrix is not stored in single-matrix mode." << std::endl; libmesh_error(); } return inner_product_matrix.get(); } SparseMatrix<Number>* RBConstruction::get_non_dirichlet_inner_product_matrix() { if(!store_non_dirichlet_operators) { libMesh::err << "Error: Must have store_non_dirichlet_operators==true " << "to access non_dirichlet_inner_product_matrix." << std::endl; libmesh_error(); } if(single_matrix_mode) { libMesh::err << "Error: The non-Dirichlet inner-product matrix is not stored in single-matrix mode." << std::endl; libmesh_error(); } return non_dirichlet_inner_product_matrix.get(); } SparseMatrix<Number>* RBConstruction::get_Aq(unsigned int q) { if(single_matrix_mode) { libMesh::err << "Error: The affine matrices are not stored in single-matrix mode." << std::endl; libmesh_error(); } if(q >= get_rb_theta_expansion().get_n_A_terms()) { libMesh::err << "Error: We must have q < Q_a in get_Aq." << std::endl; libmesh_error(); } return Aq_vector[q]; } SparseMatrix<Number>* RBConstruction::get_non_dirichlet_Aq(unsigned int q) { if(!store_non_dirichlet_operators) { libMesh::err << "Error: Must have store_non_dirichlet_operators==true to access non_dirichlet_Aq." << std::endl; libmesh_error(); } if(single_matrix_mode) { libMesh::err << "Error: The affine matrices are not stored in single-matrix mode." << std::endl; libmesh_error(); } if(q >= get_rb_theta_expansion().get_n_A_terms()) { libMesh::err << "Error: We must have q < Q_a in get_Aq." << std::endl; libmesh_error(); } return non_dirichlet_Aq_vector[q]; } NumericVector<Number>* RBConstruction::get_Fq(unsigned int q) { if(q >= get_rb_theta_expansion().get_n_F_terms()) { libMesh::err << "Error: We must have q < Q_f in get_Fq." << std::endl; libmesh_error(); } return Fq_vector[q]; } NumericVector<Number>* RBConstruction::get_non_dirichlet_Fq(unsigned int q) { if(!store_non_dirichlet_operators) { libMesh::err << "Error: Must have store_non_dirichlet_operators==true to access non_dirichlet_Fq." << std::endl; libmesh_error(); } if(q >= get_rb_theta_expansion().get_n_F_terms()) { libMesh::err << "Error: We must have q < Q_f in get_Fq." << std::endl; libmesh_error(); } return non_dirichlet_Fq_vector[q]; } NumericVector<Number>* RBConstruction::get_output_vector(unsigned int n, unsigned int q_l) { if( (n >= get_rb_theta_expansion().get_n_outputs()) || (q_l >= get_rb_theta_expansion().get_n_output_terms(n)) ) { libMesh::err << "Error: We must have n < n_outputs and " << "q_l < get_rb_theta_expansion().get_n_output_terms(n) in get_output_vector." << std::endl; libmesh_error(); } return outputs_vector[n][q_l]; } AutoPtr<DirichletBoundary> RBConstruction::build_zero_dirichlet_boundary_object() { ZeroFunction<> zf; std::set<boundary_id_type> dirichlet_ids; std::vector<unsigned int> variables; // The DirichletBoundary constructor clones zf, so it's OK that zf is only in local scope return AutoPtr<DirichletBoundary> (new DirichletBoundary(dirichlet_ids, variables, &zf)); } void RBConstruction::write_riesz_representors_to_files(const std::string& riesz_representors_dir, const bool write_binary_residual_representors) { START_LOG("write_riesz_representors_to_files()", "RBConstruction"); // Write out Riesz representors. These are useful to have when restarting, // so you don't have to recompute them all over again. // First we write out the Fq representors, these are independent of an RBEvaluation object. libMesh::out << "Writing out the Fq_representors..." << std::endl; std::ostringstream file_name; const std::string riesz_representor_suffix = (write_binary_residual_representors ? ".xdr" : ".dat"); struct stat stat_info; // Residual representors written out to their own separate directory if ( libMesh::processor_id() == 0) if ( mkdir(riesz_representors_dir.c_str(), 0755) != 0) libMesh::out << "Skipping creating residual_representors directory: " << strerror(errno) << std::endl; for (unsigned int i=0; i<Fq_representor.size(); ++i) { if (Fq_representor[i] != NULL) { file_name.str(""); // reset filename file_name << riesz_representors_dir << "/Fq_representor" << i << riesz_representor_suffix; // Check to see if file exists, if so, don't overwrite it, we assume it was // there from a previous call to this function. Note: if stat returns zero // it means it successfully got the file attributes (and therefore the file // exists). Because of the following factors: // 1.) write_serialized_data takes longer for proc 0 than it does for others, // so processors can get out of sync. // 2.) The constructor for Xdr opens a (0 length) file on *all* processors, // there are typically hundreds of 0-length files created during this loop, // and that screws up checking for the existence of files. One way to stay // in sync is to but a barrier at each iteration of the loop -- not sure how // bad this will affect performance, but it can't be much worse than serialized // I/O already is :) int stat_result = stat(file_name.str().c_str(), &stat_info); if ( (stat_result != 0) || // file definitely doesn't already exist (stat_info.st_size == 0)) // file exists, but has zero length (can happen if another proc already opened it!) { // No need to copy! // *solution = *(Fq_representor[i]); // std::swap doesn't work on pointers //std::swap(solution.get(), Fq_representor[i]); Fq_representor[i]->swap(*solution); Xdr fqr_data(file_name.str(), write_binary_residual_representors ? ENCODE : WRITE); write_serialized_data(fqr_data, false); // Synchronize before moving on Parallel::barrier(); // Swap back. Fq_representor[i]->swap(*solution); // TODO: bzip the resulting file? See $LIBMESH_DIR/src/mesh/unstructured_mesh.C // for the system call, be sure to do it only on one processor, etc. } } } // Next, write out the Aq representors associated with rb_eval. libMesh::out << "Writing out the Aq_representors..." << std::endl; const unsigned int jstop = get_rb_evaluation().get_n_basis_functions(); const unsigned int jstart = jstop-get_delta_N(); for (unsigned int i=0; i<get_rb_evaluation().Aq_representor.size(); ++i) for (unsigned int j=jstart; j<jstop; ++j) { libMesh::out << "Writing out Aq_representor[" << i << "][" << j << "]..." << std::endl; libmesh_assert(get_rb_evaluation().Aq_representor[i][j] != NULL); file_name.str(""); // reset filename file_name << riesz_representors_dir << "/Aq_representor" << i << "_" << j << riesz_representor_suffix; { // No need to copy! Use swap instead. // *solution = *(Aq_representor[i][j]); get_rb_evaluation().Aq_representor[i][j]->swap(*solution); Xdr aqr_data(file_name.str(), write_binary_residual_representors ? ENCODE : WRITE); write_serialized_data(aqr_data, false); // Synchronize before moving on Parallel::barrier(); // Swap back. get_rb_evaluation().Aq_representor[i][j]->swap(*solution); // TODO: bzip the resulting file? See $LIBMESH_DIR/src/mesh/unstructured_mesh.C // for the system call, be sure to do it only on one processor, etc. } } STOP_LOG("write_riesz_representors_to_files()", "RBConstruction"); } void RBConstruction::read_riesz_representors_from_files(const std::string& riesz_representors_dir, const bool read_binary_residual_representors) { START_LOG("read_riesz_representors_from_files()", "RBConstruction"); libMesh::out << "Reading in the Fq_representors..." << std::endl; const std::string riesz_representor_suffix = (read_binary_residual_representors ? ".xdr" : ".dat"); std::ostringstream file_name; struct stat stat_info; // Read in the Fq_representors. There should be Q_f of these. FIXME: // should we be worried about leaks here? for (unsigned int i=0; i<Fq_representor.size(); ++i) { if (Fq_representor[i] != NULL) { libMesh::out << "Error, must delete existing Fq_representor before reading in from file." << std::endl; libmesh_error(); } } for (unsigned int i=0; i<Fq_representor.size(); i++) { file_name.str(""); // reset filename file_name << riesz_representors_dir << "/Fq_representor" << i << riesz_representor_suffix; // On processor zero check to be sure the file exists if (libMesh::processor_id() == 0) { int stat_result = stat(file_name.str().c_str(), &stat_info); if (stat_result != 0) { libMesh::out << "File does not exist: " << file_name.str() << std::endl; libmesh_error(); } } Xdr fqr_data(file_name.str(), read_binary_residual_representors ? DECODE : READ); read_serialized_data(fqr_data, false); Fq_representor[i] = NumericVector<Number>::build().release(); Fq_representor[i]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); // No need to copy, just swap // *Fq_representor[i] = *solution; Fq_representor[i]->swap(*solution); } // Alert the update_residual_terms() function that we don't need to recompute // the Fq_representors as we have already read them in from file! Fq_representor_innerprods_computed = true; libMesh::out << "Reading in the Aq_representors..." << std::endl; // Read in the Aq representors. The class makes room for [Q_a][Nmax] of these. We are going to // read in [Q_a][get_rb_evaluation().get_n_basis_functions()]. FIXME: // should we be worried about leaks in the locations where we're about to fill entries? for (unsigned int i=0; i<get_rb_evaluation().Aq_representor.size(); ++i) for (unsigned int j=0; j<get_rb_evaluation().Aq_representor[i].size(); ++j) { if (get_rb_evaluation().Aq_representor[i][j] != NULL) { libMesh::out << "Error, must delete existing Aq_representor before reading in from file." << std::endl; libmesh_error(); } } // Now ready to read them in from file! for (unsigned int i=0; i<get_rb_evaluation().Aq_representor.size(); ++i) for (unsigned int j=0; j<get_rb_evaluation().get_n_basis_functions(); ++j) { file_name.str(""); // reset filename file_name << riesz_representors_dir << "/Aq_representor" << i << "_" << j << riesz_representor_suffix; // On processor zero check to be sure the file exists if (libMesh::processor_id() == 0) { int stat_result = stat(file_name.str().c_str(), &stat_info); if (stat_result != 0) { libMesh::out << "File does not exist: " << file_name.str() << std::endl; libmesh_error(); } } Xdr aqr_data(file_name.str(), read_binary_residual_representors ? DECODE : READ); read_serialized_data(aqr_data, false); get_rb_evaluation().Aq_representor[i][j] = NumericVector<Number>::build().release(); get_rb_evaluation().Aq_representor[i][j]->init (n_dofs(), n_local_dofs(), false, libMeshEnums::PARALLEL); // No need to copy, just swap //*Aq_representor[i][j] = *solution; get_rb_evaluation().Aq_representor[i][j]->swap(*solution); } STOP_LOG("read_riesz_representors_from_files()", "RBConstruction"); } } // namespace libMesh rbOOmit change: added an endl to improve formatting git-svn-id: ffc1bc5b3feaf8644044862cc38c386ade156493@5831 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf // rbOOmit: An implementation of the Certified Reduced Basis method. // Copyright (C) 2009, 2010 David J. Knezevic // This file is part of rbOOmit. // rbOOmit is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // rbOOmit is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // rbOOmit includes #include "rb_construction.h" #include "rb_assembly_expansion.h" // LibMesh includes #include "numeric_vector.h" #include "sparse_matrix.h" #include "dof_map.h" #include "libmesh_logging.h" #include "equation_systems.h" #include "exodusII_io.h" #include "linear_solver.h" #include "getpot.h" #include "mesh_base.h" #include "parallel.h" #include "xdr_cxx.h" #include "timestamp.h" #include "petsc_linear_solver.h" #include "fem_context.h" #include "dirichlet_boundaries.h" #include "zero_function.h" // For creating a directory #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fstream> #include <sstream> namespace libMesh { RBConstruction::RBConstruction (EquationSystems& es, const std::string& name, const unsigned int number) : Parent(es, name, number), inner_product_matrix(SparseMatrix<Number>::build()), non_dirichlet_inner_product_matrix(SparseMatrix<Number>::build()), constraint_matrix(SparseMatrix<Number>::build()), constrained_problem(false), single_matrix_mode(false), reuse_preconditioner(true), use_relative_bound_in_greedy(false), exit_on_repeated_greedy_parameters(true), write_data_during_training(false), impose_internal_dirichlet_BCs(false), impose_internal_fluxes(false), compute_RB_inner_product(false), store_non_dirichlet_operators(false), enforce_constraints_exactly(false), use_empty_rb_solve_in_greedy(true), Nmax(0), delta_N(1), quiet_mode(true), output_dual_innerprods_computed(false), Fq_representor_innerprods_computed(false), rb_eval(NULL), inner_product_assembly(NULL), constraint_assembly(NULL), training_tolerance(-1.) { // set assemble_before_solve flag to false // so that we control matrix assembly. assemble_before_solve = false; } RBConstruction::~RBConstruction () { this->clear(); } void RBConstruction::clear() { START_LOG("clear()", "RBConstruction"); Parent::clear(); for(unsigned int q=0; q<Aq_vector.size(); q++) { if(Aq_vector[q]) { delete Aq_vector[q]; Aq_vector[q] = NULL; } } for(unsigned int q=0; q<Fq_vector.size(); q++) { if(Fq_vector[q]) { delete Fq_vector[q]; Fq_vector[q] = NULL; } } if(store_non_dirichlet_operators) { for(unsigned int q=0; q<non_dirichlet_Aq_vector.size(); q++) { if(non_dirichlet_Aq_vector[q]) { delete non_dirichlet_Aq_vector[q]; non_dirichlet_Aq_vector[q] = NULL; } } for(unsigned int q=0; q<non_dirichlet_Fq_vector.size(); q++) { if(non_dirichlet_Fq_vector[q]) { delete non_dirichlet_Fq_vector[q]; non_dirichlet_Fq_vector[q] = NULL; } } } for(unsigned int i=0; i<outputs_vector.size(); i++) for(unsigned int q_l=0; q_l<outputs_vector[i].size(); q_l++) if(outputs_vector[i][q_l]) { delete outputs_vector[i][q_l]; outputs_vector[i][q_l] = NULL; } // Also delete the Fq representors for(unsigned int q_f=0; q_f<Fq_representor.size(); q_f++) { if(Fq_representor[q_f]) { delete Fq_representor[q_f]; Fq_representor[q_f] = NULL; } } // Set Fq_representor_innerprods_computed flag to false now // that we've cleared the Fq representors Fq_representor_innerprods_computed = false; STOP_LOG("clear()", "RBConstruction"); } std::string RBConstruction::system_type () const { return "RBConstruction"; } void RBConstruction::set_rb_evaluation(RBEvaluation& rb_eval_in) { rb_eval = &rb_eval_in; } RBEvaluation& RBConstruction::get_rb_evaluation() { if(!rb_eval) { libMesh::out << "Error: RBEvaluation object hasn't been initialized yet" << std::endl; libmesh_error(); } return *rb_eval; } bool RBConstruction::is_rb_eval_initialized() const { return (rb_eval != NULL); } RBThetaExpansion& RBConstruction::get_rb_theta_expansion() { return get_rb_evaluation().get_rb_theta_expansion(); } void RBConstruction::process_parameters_file (const std::string& parameters_filename) { // First read in data from input_filename GetPot infile(parameters_filename); const unsigned int n_training_samples = infile("n_training_samples",0); const bool deterministic_training = infile("deterministic_training",false); // String which selects an alternate pc/solver combo for the update_residual_terms solves. // Possible values are: // "unchanged" -- use whatever we were using for truth solves // "amg" -- Use Boomeramg from Hypre. DO NOT use on indefinite (Stokes) problems // "mumps" -- Use the sparse //update_residual_terms_solver = infile("update_residual_terms_solver",update_residual_terms_solver); alternative_solver = infile("rb_alternative_solver",alternative_solver); // Tell the system that it is constrained (i.e. we want to use // the Stokes inner product matrix to compute Riesz representors) constrained_problem = (constraint_assembly != NULL); // Tell the system if we're in single-matrix mode single_matrix_mode = infile("single_matrix_mode", single_matrix_mode); // Tell the system to reuse the preconditioner on consecutive // Offline solves to update residual data reuse_preconditioner = infile("reuse_preconditioner", reuse_preconditioner); // Tell the system whether or not to use a relative error bound // in the Greedy algorithm use_relative_bound_in_greedy = infile("use_relative_bound_in_greedy", use_relative_bound_in_greedy); // Tell the system whether or not to write out offline data during // train_reduced_basis. This allows us to continue from where the // training left off in case the computation stops for some reason. write_data_during_training = infile("write_data_during_training", write_data_during_training); // Read in training_parameters_random_seed value. This is used to // seed the RNG when picking the training parameters. By default the // value is -1, which means use std::time to seed the RNG. unsigned int training_parameters_random_seed_in = -1; training_parameters_random_seed_in = infile("training_parameters_random_seed", training_parameters_random_seed_in); set_training_random_seed(training_parameters_random_seed_in); // Set quiet mode const bool quiet_mode_in = infile("quiet_mode", quiet_mode); set_quiet_mode(quiet_mode_in); // Initialize RB parameters const unsigned int Nmax_in = infile("Nmax", Nmax); set_Nmax(Nmax_in); const Real training_tolerance_in = infile("training_tolerance", training_tolerance); set_training_tolerance(training_tolerance_in); // Initialize the parameter ranges and the parameters themselves initialize_parameters(parameters_filename); std::map<std::string,bool> log_scaling; const RBParameters& mu = get_parameters(); RBParameters::const_iterator it = mu.begin(); RBParameters::const_iterator it_end = mu.end(); unsigned int i=0; for( ; it != it_end; ++it) { // Read vector-based log scaling values. Note the intermediate conversion to // int... this implies log_scaling = '1 1 1...' in the input file. // log_scaling[i] = static_cast<bool>(infile("log_scaling", static_cast<int>(log_scaling[i]), i)); std::string param_name = it->first; log_scaling[param_name] = static_cast<bool>(infile("log_scaling", 0, i)); i++; } initialize_training_parameters(this->get_parameters_min(), this->get_parameters_max(), n_training_samples, log_scaling, deterministic_training); // use deterministic parameters } void RBConstruction::print_info() { // Print out info that describes the current setup libMesh::out << std::endl << "RBConstruction parameters:" << std::endl; libMesh::out << "system name: " << this->name() << std::endl; libMesh::out << "constrained_problem: " << constrained_problem << std::endl; libMesh::out << "Nmax: " << Nmax << std::endl; if(training_tolerance > 0.) libMesh::out << "Basis training error tolerance: " << get_training_tolerance() << std::endl; if( is_rb_eval_initialized() ) { libMesh::out << "Aq operators attached: " << get_rb_theta_expansion().get_n_A_terms() << std::endl; libMesh::out << "Fq functions attached: " << get_rb_theta_expansion().get_n_F_terms() << std::endl; libMesh::out << "n_outputs: " << get_rb_theta_expansion().get_n_outputs() << std::endl; for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) libMesh::out << "output " << n << ", Q_l = " << get_rb_theta_expansion().get_n_output_terms(n) << std::endl; libMesh::out << "Number of parameters: " << get_n_params() << std::endl; } else { libMesh::out << "RBThetaExpansion member is not set yet" << std::endl; } RBParameters::const_iterator it = get_parameters().begin(); RBParameters::const_iterator it_end = get_parameters().end(); for( ; it != it_end; ++it) { std::string param_name = it->first; libMesh::out << "Parameter " << param_name << ": Min = " << get_parameter_min(param_name) << ", Max = " << get_parameter_max(param_name) << ", value = " << get_parameters().get_value(param_name) << std::endl; } libMesh::out << "n_training_samples: " << get_n_training_samples() << std::endl; libMesh::out << "single-matrix mode? " << single_matrix_mode << std::endl; libMesh::out << "reuse preconditioner? " << reuse_preconditioner << std::endl; libMesh::out << "use a relative error bound in greedy? " << use_relative_bound_in_greedy << std::endl; libMesh::out << "write out data during basis training? " << write_data_during_training << std::endl; libMesh::out << "quiet mode? " << is_quiet() << std::endl; libMesh::out << std::endl; } void RBConstruction::set_rb_assembly_expansion(RBAssemblyExpansion& rb_assembly_expansion_in) { rb_assembly_expansion = &rb_assembly_expansion_in; } RBAssemblyExpansion& RBConstruction::get_rb_assembly_expansion() { if(!rb_assembly_expansion) { libMesh::out << "Error: RBAssemblyExpansion object hasn't been initialized yet" << std::endl; libmesh_error(); } return *rb_assembly_expansion; } void RBConstruction::set_inner_product_assembly(ElemAssembly& inner_product_assembly_in) { inner_product_assembly = &inner_product_assembly_in; } ElemAssembly& RBConstruction::get_inner_product_assembly() { if(!inner_product_assembly) { libMesh::out << "Error: inner_product_assembly hasn't been initialized yet" << std::endl; libmesh_error(); } return *inner_product_assembly; } void RBConstruction::set_constraint_assembly(ElemAssembly& constraint_assembly_in) { constraint_assembly = &constraint_assembly_in; } ElemAssembly& RBConstruction::get_constraint_assembly() { if(!constraint_assembly) { libMesh::out << "Error: constraint_assembly hasn't been initialized yet" << std::endl; libmesh_error(); } return *constraint_assembly; } void RBConstruction::zero_constrained_dofs_on_vector(NumericVector<Number>& vector) { const DofMap& dof_map = get_dof_map(); for(unsigned int i=dof_map.first_dof(); i<dof_map.end_dof(); i++) { if(get_dof_map().is_constrained_dof(i)) { vector.set(i, 0.); } } vector.close(); } void RBConstruction::initialize_rb_construction() { // Check that the theta and assembly objects are consistently sized libmesh_assert(get_rb_theta_expansion().get_n_A_terms() == get_rb_assembly_expansion().get_n_A_terms()); libmesh_assert(get_rb_theta_expansion().get_n_F_terms() == get_rb_assembly_expansion().get_n_F_terms()); libmesh_assert(get_rb_theta_expansion().get_n_outputs() == get_rb_assembly_expansion().get_n_outputs()); for(unsigned int i=0; i<get_rb_theta_expansion().get_n_outputs(); i++) { libmesh_assert(get_rb_theta_expansion().get_n_output_terms(i) == get_rb_assembly_expansion().get_n_output_terms(i)); } // Perform the initialization allocate_data_structures(); assemble_affine_expansion(); } void RBConstruction::assemble_affine_expansion() { // Assemble and store all of the matrices if we're // not in single-matrix mode if(!single_matrix_mode) { this->assemble_misc_matrices(); this->assemble_all_affine_operators(); } this->assemble_all_affine_vectors(); this->assemble_all_output_vectors(); } void RBConstruction::allocate_data_structures() { // Resize vectors for storing mesh-dependent data Aq_vector.resize(get_rb_theta_expansion().get_n_A_terms()); Fq_vector.resize(get_rb_theta_expansion().get_n_F_terms()); // Resize the Fq_representors and initialize each to NULL // These are basis independent and hence stored here, whereas // the Aq_representors are stored in RBEvaluation Fq_representor.resize(get_rb_theta_expansion().get_n_F_terms()); // Initialize vectors for the inner products of the Fq representors // These are basis independent and therefore stored here. unsigned int Q_f_hat = get_rb_theta_expansion().get_n_F_terms()*(get_rb_theta_expansion().get_n_F_terms()+1)/2; Fq_representor_innerprods.resize(Q_f_hat); // Resize the output vectors outputs_vector.resize(get_rb_theta_expansion().get_n_outputs()); for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) outputs_vector[n].resize( get_rb_theta_expansion().get_n_output_terms(n) ); // Resize the output dual norm vectors output_dual_innerprods.resize(get_rb_theta_expansion().get_n_outputs()); for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) { unsigned int Q_l_hat = get_rb_theta_expansion().get_n_output_terms(n)*(get_rb_theta_expansion().get_n_output_terms(n)+1)/2; output_dual_innerprods[n].resize(Q_l_hat); } // Only initialize matrices if we're not in single-matrix mode if(!single_matrix_mode) { DofMap& dof_map = this->get_dof_map(); dof_map.attach_matrix(*inner_product_matrix); inner_product_matrix->init(); inner_product_matrix->zero(); if(this->constrained_problem) { dof_map.attach_matrix(*constraint_matrix); constraint_matrix->init(); constraint_matrix->zero(); } for(unsigned int q=0; q<get_rb_theta_expansion().get_n_A_terms(); q++) { // Initialize the memory for the matrices Aq_vector[q] = SparseMatrix<Number>::build().release(); dof_map.attach_matrix(*Aq_vector[q]); Aq_vector[q]->init(); Aq_vector[q]->zero(); } // We also need to initialize a second set of non-Dirichlet operators if(store_non_dirichlet_operators) { dof_map.attach_matrix(*non_dirichlet_inner_product_matrix); non_dirichlet_inner_product_matrix->init(); non_dirichlet_inner_product_matrix->zero(); non_dirichlet_Aq_vector.resize(get_rb_theta_expansion().get_n_A_terms()); for(unsigned int q=0; q<get_rb_theta_expansion().get_n_A_terms(); q++) { // Initialize the memory for the matrices non_dirichlet_Aq_vector[q] = SparseMatrix<Number>::build().release(); dof_map.attach_matrix(*non_dirichlet_Aq_vector[q]); non_dirichlet_Aq_vector[q]->init(); non_dirichlet_Aq_vector[q]->zero(); } } } // Initialize the vectors for(unsigned int q=0; q<get_rb_theta_expansion().get_n_F_terms(); q++) { // Initialize the memory for the vectors Fq_vector[q] = NumericVector<Number>::build().release(); Fq_vector[q]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } // We also need to initialize a second set of non-Dirichlet operators if(store_non_dirichlet_operators) { non_dirichlet_Fq_vector.resize(get_rb_theta_expansion().get_n_F_terms()); for(unsigned int q=0; q<get_rb_theta_expansion().get_n_F_terms(); q++) { // Initialize the memory for the vectors non_dirichlet_Fq_vector[q] = NumericVector<Number>::build().release(); non_dirichlet_Fq_vector[q]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } } for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) for(unsigned int q_l=0; q_l<get_rb_theta_expansion().get_n_output_terms(n); q_l++) { // Initialize the memory for the truth output vectors outputs_vector[n][q_l] = (NumericVector<Number>::build().release()); outputs_vector[n][q_l]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } // Resize truth_outputs vector truth_outputs.resize(this->get_rb_theta_expansion().get_n_outputs()); } AutoPtr<FEMContext> RBConstruction::build_context () { return AutoPtr<FEMContext>(new FEMContext(*this)); } void RBConstruction::add_scaled_matrix_and_vector(Number scalar, ElemAssembly* elem_assembly, SparseMatrix<Number>* input_matrix, NumericVector<Number>* input_vector, bool symmetrize, bool apply_dof_constraints) { START_LOG("add_scaled_matrix_and_vector()", "RBConstruction"); bool assemble_matrix = (input_matrix != NULL); bool assemble_vector = (input_vector != NULL); if(!assemble_matrix && !assemble_vector) return; const MeshBase& mesh = this->get_mesh(); AutoPtr<FEMContext> c = this->build_context(); FEMContext &context = libmesh_cast_ref<FEMContext&>(*c); this->init_context(context); MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { context.pre_fe_reinit(*this, *el); context.elem_fe_reinit(); elem_assembly->interior_assembly(context); for (context.side = 0; context.side != context.elem->n_sides(); ++context.side) { // May not need to apply fluxes on non-boundary elements if( (context.elem->neighbor(context.side) != NULL) && !impose_internal_fluxes ) continue; // Impose boundary (e.g. Neumann) term context.side_fe_reinit(); elem_assembly->boundary_assembly(context); } // Need to symmetrize before imposing // periodic constraints if(assemble_matrix && symmetrize) { DenseMatrix<Number> Ke_transpose; context.elem_jacobian.get_transpose(Ke_transpose); context.elem_jacobian += Ke_transpose; context.elem_jacobian *= 0.5; } if(apply_dof_constraints) { // Apply constraints, e.g. Dirichlet and periodic constraints this->get_dof_map().constrain_element_matrix_and_vector (context.elem_jacobian, context.elem_residual, context.dof_indices); } // Scale and add to global matrix and/or vector context.elem_jacobian *= scalar; context.elem_residual *= scalar; if(assemble_matrix) input_matrix->add_matrix (context.elem_jacobian, context.dof_indices); if(assemble_vector) input_vector->add_vector (context.elem_residual, context.dof_indices); } if(assemble_matrix) input_matrix->close(); if(assemble_vector) input_vector->close(); STOP_LOG("add_scaled_matrix_and_vector()", "RBConstruction"); } void RBConstruction::set_context_solution_vec(NumericVector<Number>& vec) { // Set current_local_solution = vec so that we can access // vec from FEMContext during assembly vec.localize (*current_local_solution, this->get_dof_map().get_send_list()); } void RBConstruction::assemble_scaled_matvec(Number scalar, ElemAssembly* elem_assembly, NumericVector<Number>& dest, NumericVector<Number>& arg) { START_LOG("assemble_scaled_matvec()", "RBConstruction"); dest.zero(); // Set current_local_solution to be arg so that we // can access it from the FEMContext. Do this in a // function call so that it can be overloaded as // necessary in subclasses this->set_context_solution_vec(arg); const MeshBase& mesh = this->get_mesh(); AutoPtr<FEMContext> c = this->build_context(); FEMContext &context = libmesh_cast_ref<FEMContext&>(*c); this->init_context(context); MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { context.pre_fe_reinit(*this, *el); context.elem_fe_reinit(); elem_assembly->interior_assembly(context); for (context.side = 0; context.side != context.elem->n_sides(); ++context.side) { // May not need to apply fluxes on non-boundary elements if( (context.elem->neighbor(context.side) != NULL) && !impose_internal_fluxes ) continue; context.side_fe_reinit(); elem_assembly->boundary_assembly(context); } // Now perform the local matrix multiplcation context.elem_jacobian.vector_mult(context.elem_residual, context.elem_solution); context.elem_residual *= scalar; // Apply dof constraints, e.g. Dirichlet or periodic constraints this->get_dof_map().constrain_element_matrix_and_vector (context.elem_jacobian, context.elem_residual, context.dof_indices); dest.add_vector (context.elem_residual, context.dof_indices); } dest.close(); STOP_LOG("assemble_scaled_matvec()", "RBConstruction"); } void RBConstruction::truth_assembly() { START_LOG("truth_assembly()", "RBConstruction"); const RBParameters& mu = get_parameters(); this->matrix->zero(); this->rhs->zero(); this->matrix->close(); this->rhs->close(); if(!single_matrix_mode) { // We should have already assembled the matrices // and vectors in the affine expansion, so // just use them for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { matrix->add(get_rb_theta_expansion().eval_A_theta(q_a, mu), *get_Aq(q_a)); } AutoPtr< NumericVector<Number> > temp_vec = NumericVector<Number>::build(); temp_vec->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { *temp_vec = *get_Fq(q_f); temp_vec->scale( get_rb_theta_expansion().eval_F_theta(q_f, mu) ); rhs->add(*temp_vec); } if(constrained_problem) matrix->add(1., *constraint_matrix); } else { // In low memory mode we do not store the matrices // from the affine expansion, so need to assemble // For efficiency (i.e. to avoid doing Q_a+Q_f loops // over the mesh) we do not use add_scaled_matrix_and_vector // here const MeshBase& mesh = this->get_mesh(); std::vector<FEMContext*> Aq_context(get_rb_theta_expansion().get_n_A_terms()); for(unsigned int q_a=0; q_a<Aq_context.size(); q_a++) { Aq_context[q_a] = this->build_context().release(); this->init_context(*Aq_context[q_a]); } std::vector<FEMContext*> Fq_context(get_rb_theta_expansion().get_n_F_terms()); for(unsigned int q_f=0; q_f<Fq_context.size(); q_f++) { Fq_context[q_f] = this->build_context().release(); this->init_context(*Fq_context[q_f]); } MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { Aq_context[q_a]->pre_fe_reinit(*this, *el); Aq_context[q_a]->elem_fe_reinit(); rb_assembly_expansion->perform_A_interior_assembly(q_a, *Aq_context[q_a]); } for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { Fq_context[q_f]->pre_fe_reinit(*this, *el); Fq_context[q_f]->elem_fe_reinit(); rb_assembly_expansion->perform_F_interior_assembly(q_f, *Fq_context[q_f]); } for (Aq_context[0]->side = 0; Aq_context[0]->side != Aq_context[0]->elem->n_sides(); ++Aq_context[0]->side) { // May not need to apply fluxes on non-boundary elements if( (Aq_context[0]->elem->neighbor(Aq_context[0]->side) != NULL) && !impose_internal_fluxes ) continue; // Update the side information for all contexts for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { // Update the side information for all contexts Aq_context[q_a]->side = Aq_context[0]->side; Aq_context[q_a]->side_fe_reinit(); rb_assembly_expansion->perform_A_boundary_assembly(q_a, *Aq_context[q_a]); } // Impose boundary terms, e.g. Neuman BCs for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { // Update the side information for all contexts Fq_context[q_f]->side = Aq_context[0]->side; Fq_context[q_f]->side_fe_reinit(); rb_assembly_expansion->perform_F_boundary_assembly(q_f, *Fq_context[q_f]); } } // Constrain the dofs to impose Dirichlet BCs, hanging node or periodic constraints for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { this->get_dof_map().constrain_element_matrix (Aq_context[q_a]->elem_jacobian, Aq_context[q_a]->dof_indices); } for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { this->get_dof_map().constrain_element_vector (Fq_context[q_f]->elem_residual, Fq_context[q_f]->dof_indices); } // Finally add local matrices/vectors to global system for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { // Scale by theta_q_a Aq_context[q_a]->elem_jacobian *= get_rb_theta_expansion().eval_A_theta(q_a, mu); this->matrix->add_matrix (Aq_context[q_a]->elem_jacobian, Aq_context[q_a]->dof_indices); } for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { // Scale by theta_q_f Fq_context[q_f]->elem_residual *= get_rb_theta_expansion().eval_F_theta(q_f, mu); this->rhs->add_vector (Fq_context[q_f]->elem_residual, Fq_context[q_f]->dof_indices); } } if(constrained_problem) add_scaled_matrix_and_vector(1., constraint_assembly, matrix, NULL); // Delete all the ptrs to FEMContexts! for(unsigned int q_a=0; q_a<Aq_context.size(); q_a++) { delete Aq_context[q_a]; Aq_context[q_a] = NULL; } Aq_context.clear(); for(unsigned int q_f=0; q_f<Fq_context.size(); q_f++) { delete Fq_context[q_f]; Fq_context[q_f]; } Fq_context.clear(); } this->matrix->close(); this->rhs->close(); STOP_LOG("truth_assembly()", "RBConstruction"); } void RBConstruction::assemble_inner_product_matrix(SparseMatrix<Number>* input_matrix, bool apply_dof_constraints) { input_matrix->zero(); add_scaled_matrix_and_vector(1., inner_product_assembly, input_matrix, NULL, false, /* symmetrize */ apply_dof_constraints); } void RBConstruction::assemble_constraint_matrix(SparseMatrix<Number>* input_matrix) { input_matrix->zero(); add_scaled_matrix_and_vector(1., constraint_assembly, input_matrix, NULL); } void RBConstruction::assemble_and_add_constraint_matrix(SparseMatrix<Number>* input_matrix) { add_scaled_matrix_and_vector(1., constraint_assembly, input_matrix, NULL); } void RBConstruction::assemble_Aq_matrix(unsigned int q, SparseMatrix<Number>* input_matrix, bool apply_dof_constraints) { if(q >= get_rb_theta_expansion().get_n_A_terms()) { libMesh::err << "Error: We must have q < Q_a in assemble_Aq_matrix." << std::endl; libmesh_error(); } input_matrix->zero(); add_scaled_matrix_and_vector(1., &rb_assembly_expansion->get_A_assembly(q), input_matrix, NULL, false, /* symmetrize */ apply_dof_constraints); } void RBConstruction::add_scaled_Aq(Number scalar, unsigned int q_a, SparseMatrix<Number>* input_matrix, bool symmetrize) { START_LOG("add_scaled_Aq()", "RBConstruction"); if(q_a >= get_rb_theta_expansion().get_n_A_terms()) { libMesh::err << "Error: We must have q < Q_a in add_scaled_Aq." << std::endl; libmesh_error(); } if(!single_matrix_mode && !symmetrize) { input_matrix->add(scalar, *get_Aq(q_a)); input_matrix->close(); } else { add_scaled_matrix_and_vector(scalar, &rb_assembly_expansion->get_A_assembly(q_a), input_matrix, NULL, symmetrize); } STOP_LOG("add_scaled_Aq()", "RBConstruction"); } void RBConstruction::assemble_misc_matrices() { if(single_matrix_mode) { libMesh::out << "Error: Cannot store misc matrices in single-matrix mode." << std::endl; libmesh_error(); } assemble_inner_product_matrix(inner_product_matrix.get()); if(store_non_dirichlet_operators) { assemble_inner_product_matrix(non_dirichlet_inner_product_matrix.get(), /* apply_dof_constraints = */ false); } if( constrained_problem ) { assemble_constraint_matrix(constraint_matrix.get()); } } void RBConstruction::assemble_all_affine_operators() { if(single_matrix_mode) { libMesh::out << "Error: Cannot store affine matrices in single-matrix mode." << std::endl; libmesh_error(); } for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) assemble_Aq_matrix(q_a, get_Aq(q_a)); if(store_non_dirichlet_operators) { for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) assemble_Aq_matrix(q_a, get_non_dirichlet_Aq(q_a), false); } } void RBConstruction::assemble_all_affine_vectors() { for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) assemble_Fq_vector(q_f, get_Fq(q_f)); if(store_non_dirichlet_operators) { for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) assemble_Fq_vector(q_f, get_non_dirichlet_Fq(q_f), false); } } void RBConstruction::assemble_Fq_vector(unsigned int q, NumericVector<Number>* input_vector, bool apply_dof_constraints) { if(q >= get_rb_theta_expansion().get_n_F_terms()) { libMesh::err << "Error: We must have q < Q_f in assemble_Fq_vector." << std::endl; libmesh_error(); } input_vector->zero(); add_scaled_matrix_and_vector(1., &rb_assembly_expansion->get_F_assembly(q), NULL, input_vector, false, /* symmetrize */ apply_dof_constraints /* apply_dof_constraints */); } void RBConstruction::assemble_all_output_vectors() { for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) for(unsigned int q_l=0; q_l<get_rb_theta_expansion().get_n_output_terms(n); q_l++) { get_output_vector(n, q_l)->zero(); add_scaled_matrix_and_vector(1., &rb_assembly_expansion->get_output_assembly(n,q_l), NULL, get_output_vector(n,q_l)); } } Real RBConstruction::train_reduced_basis(const std::string& directory_name, const bool resize_rb_eval_data) { START_LOG("train_reduced_basis()", "RBConstruction"); int count = 0; // initialize rb_eval's parameters get_rb_evaluation().initialize_parameters(*this); // possibly resize data structures according to Nmax if(resize_rb_eval_data) { get_rb_evaluation().resize_data_structures(get_Nmax()); } // Clear the Greedy param list for(unsigned int i=0; i<get_rb_evaluation().greedy_param_list.size(); i++) { get_rb_evaluation().greedy_param_list[i].clear(); } get_rb_evaluation().greedy_param_list.clear(); Real training_greedy_error; // If we are continuing from a previous training run, // we might already be at the max number of basis functions. // If so, we can just return. if(get_rb_evaluation().get_n_basis_functions() >= get_Nmax()) { libMesh::out << "Maximum number of basis functions reached: Nmax = " << get_Nmax() << std::endl; return 0.; } // Compute the dual norms of the outputs if we haven't already done so compute_output_dual_innerprods(); // Compute the Fq Riesz representor dual norms if we haven't already done so compute_Fq_representor_innerprods(); libMesh::out << std::endl << "---- Performing Greedy basis enrichment ----" << std::endl; while(true) { libMesh::out << std::endl << "---- Basis dimension: " << get_rb_evaluation().get_n_basis_functions() << " ----" << std::endl; if( count > 0 || (count==0 && use_empty_rb_solve_in_greedy) ) { libMesh::out << "Performing RB solves on training set" << std::endl; training_greedy_error = compute_max_error_bound(); libMesh::out << "Maximum " << (use_relative_bound_in_greedy ? "(relative)" : "(absolute)") << " error bound is " << training_greedy_error << std::endl << std::endl; if(write_data_during_training) { std::stringstream new_dir_name; new_dir_name << directory_name << "_" << get_rb_evaluation().get_n_basis_functions(); libMesh::out << "Writing out RB data to " << new_dir_name.str() << std::endl; get_rb_evaluation().write_offline_data_to_files(new_dir_name.str()); } // Break out of training phase if we have reached Nmax // or if the training_tolerance is satisfied. if( greedy_termination_test(training_greedy_error, count) ) { break; } } libMesh::out << "Performing truth solve at parameter:" << std::endl; print_parameters(); // Update the list of Greedily selected parameters this->update_greedy_param_list(); // Perform an Offline truth solve for the current parameter truth_solve(-1); // Add orthogonal part of the snapshot to the RB space libMesh::out << "Enriching the RB space" << std::endl; enrich_RB_space(); update_system(); // Increment counter count++; } this->update_greedy_param_list(); STOP_LOG("train_reduced_basis()", "RBConstruction"); return training_greedy_error; } bool RBConstruction::greedy_termination_test(Real training_greedy_error, int) { if(training_greedy_error < this->training_tolerance) { libMesh::out << "Specified error tolerance reached." << std::endl; return true; } if(get_rb_evaluation().get_n_basis_functions() >= this->get_Nmax()) { libMesh::out << "Maximum number of basis functions reached: Nmax = " << get_Nmax() << std::endl; return true; } if(exit_on_repeated_greedy_parameters) { for(unsigned int i=0; i<get_rb_evaluation().greedy_param_list.size(); i++) { RBParameters& previous_parameters = get_rb_evaluation().greedy_param_list[i]; if(previous_parameters == get_parameters()) { libMesh::out << "Exiting greedy because the same parameters were selected twice" << std::endl; return true; } } } return false; } void RBConstruction::update_greedy_param_list() { get_rb_evaluation().greedy_param_list.push_back( get_parameters() ); } const RBParameters& RBConstruction::get_greedy_parameter(unsigned int i) { if( i >= get_rb_evaluation().greedy_param_list.size() ) { libMesh::out << "Error: Argument in RBConstruction::get_greedy_parameter is too large." << std::endl; libmesh_error(); } return get_rb_evaluation().greedy_param_list[i]; } Real RBConstruction::truth_solve(int plot_solution) { START_LOG("truth_solve()", "RBConstruction"); truth_assembly(); // Safer to zero the solution first, especially when using iterative solvers solution->zero(); solve(); const RBParameters& mu = get_parameters(); // Make sure we didn't max out the number of iterations if( (this->n_linear_iterations() >= this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) && (this->final_linear_residual() > this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) ) { libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = " << this->final_linear_residual() << ", number of iterations = " << this->n_linear_iterations() << std::endl << std::endl; // libmesh_error(); } for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) { truth_outputs[n] = 0.; for(unsigned int q_l=0; q_l<get_rb_theta_expansion().get_n_output_terms(n); q_l++) truth_outputs[n] += libmesh_conj(get_rb_theta_expansion().eval_output_theta(n, q_l, mu))* get_output_vector(n,q_l)->dot(*solution); } if(plot_solution > 0) { #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(get_mesh()).write_equation_systems ("truth.e", this->get_equation_systems()); #endif } // Get the X norm of the truth solution // Useful for normalizing our true error data if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector, *solution); } else { assemble_inner_product_matrix(matrix); matrix->vector_mult(*inner_product_storage_vector, *solution); } Number truth_X_norm = std::sqrt(inner_product_storage_vector->dot(*solution)); STOP_LOG("truth_solve()", "RBConstruction"); return libmesh_real(truth_X_norm); } void RBConstruction::set_Nmax(unsigned int Nmax_in) { this->Nmax = Nmax_in; } void RBConstruction::load_basis_function(unsigned int i) { START_LOG("load_basis_function()", "RBConstruction"); libmesh_assert(i < get_rb_evaluation().get_n_basis_functions()); *solution = get_rb_evaluation().get_basis_function(i); this->update(); STOP_LOG("load_basis_function()", "RBConstruction"); } void RBConstruction::enrich_RB_space() { START_LOG("enrich_RB_space()", "RBConstruction"); NumericVector<Number>* new_bf = NumericVector<Number>::build().release(); new_bf->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); *new_bf = *solution; // compute orthogonalization AutoPtr< NumericVector<Number> > proj_index = NumericVector<Number>::build(); proj_index->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); if(single_matrix_mode) assemble_inner_product_matrix(matrix); for(unsigned int index=0; index<get_rb_evaluation().get_n_basis_functions(); index++) { // invoke copy constructor for NumericVector *proj_index = get_rb_evaluation().get_basis_function(index); if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector,*proj_index); } else { matrix->vector_mult(*inner_product_storage_vector,*proj_index); } Number scalar = inner_product_storage_vector->dot(*new_bf); new_bf->add(-scalar,*proj_index); } // Normalize new_bf if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector,*new_bf); } else { matrix->vector_mult(*inner_product_storage_vector,*new_bf); } Number new_bf_norm = std::sqrt( inner_product_storage_vector->dot(*new_bf) ); if(new_bf_norm == 0.) { new_bf->zero(); // avoid potential nan's } else { new_bf->scale(1./new_bf_norm); } // load the new basis function into the basis_functions vector. get_rb_evaluation().basis_functions.push_back( new_bf ); STOP_LOG("enrich_RB_space()", "RBConstruction"); } void RBConstruction::update_system() { libMesh::out << "Updating RB matrices" << std::endl; update_RB_system_matrices(); libMesh::out << "Updating RB residual terms" << std::endl; // Note: the solves in this function employ a single system matrix and multiple // right-hand sides, so we may get better performance using a different // preconditioner, or even a direct solver. std::pair<std::string,std::string> orig_solver = this->set_alternative_solver(this->linear_solver); update_residual_terms(); // Change the preconditioner, Krylov solver back to their original // value. Note: does nothing if RBBase::alternative_solver == // "unchanged". this->reset_alternative_solver(this->linear_solver, orig_solver); } Real RBConstruction::get_RB_error_bound() { get_rb_evaluation().set_parameters( get_parameters() ); Real error_bound = get_rb_evaluation().rb_solve(get_rb_evaluation().get_n_basis_functions()); // Should we normalize the error bound to return a relative bound? if(use_relative_bound_in_greedy) { error_bound /= get_rb_evaluation().get_rb_solution_norm(); } return error_bound; } void RBConstruction::recompute_all_residual_terms(bool compute_inner_products) { // Use alternative solver for residual terms solves std::pair<std::string,std::string> orig_solver = this->set_alternative_solver(this->linear_solver); // Compute the basis independent terms Fq_representor_innerprods_computed = false; compute_Fq_representor_innerprods(compute_inner_products); // and all the basis dependent terms unsigned int saved_delta_N = delta_N; delta_N = get_rb_evaluation().get_n_basis_functions(); update_residual_terms(compute_inner_products); delta_N = saved_delta_N; // Return to original solver this->reset_alternative_solver(this->linear_solver, orig_solver); } Real RBConstruction::compute_max_error_bound() { START_LOG("compute_max_error_bound()", "RBConstruction"); training_error_bounds.resize(this->get_local_n_training_samples()); // keep track of the maximum error unsigned int max_err_index = 0; Real max_err = 0.; unsigned int first_index = get_first_local_training_index(); for(unsigned int i=0; i<get_local_n_training_samples(); i++) { // Load training parameter i, this is only loaded // locally since the RB solves are local. set_params_from_training_set( first_index+i ); training_error_bounds[i] = get_RB_error_bound(); if(training_error_bounds[i] > max_err) { max_err_index = i; max_err = training_error_bounds[i]; } } std::pair<unsigned int,Real> error_pair(first_index+max_err_index, max_err); get_global_max_error_pair(error_pair); // Now broadcast the parameter that produced the maximum error unsigned int root_id=0; if( (get_first_local_training_index() <= error_pair.first) && (error_pair.first < get_last_local_training_index()) ) { set_params_from_training_set( error_pair.first ); root_id = libMesh::processor_id(); } Parallel::sum(root_id); // root_id is only non-zero on one processor broadcast_parameters(root_id); STOP_LOG("compute_max_error_bound()", "RBConstruction"); return error_pair.second; } void RBConstruction::update_RB_system_matrices() { START_LOG("update_RB_system_matrices()", "RBConstruction"); unsigned int RB_size = get_rb_evaluation().get_n_basis_functions(); AutoPtr< NumericVector<Number> > temp = NumericVector<Number>::build(); temp->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { for(unsigned int i=(RB_size-delta_N); i<RB_size; i++) { get_rb_evaluation().RB_Fq_vector[q_f](i) = get_Fq(q_f)->dot(get_rb_evaluation().get_basis_function(i)); } } for(unsigned int i=(RB_size-delta_N); i<RB_size; i++) { for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) for(unsigned int q_l=0; q_l<get_rb_theta_expansion().get_n_output_terms(n); q_l++) { get_rb_evaluation().RB_output_vectors[n][q_l](i) = get_output_vector(n,q_l)->dot(get_rb_evaluation().get_basis_function(i)); } for(unsigned int j=0; j<RB_size; j++) { Number value = 0.; if(compute_RB_inner_product) { // Compute reduced inner_product_matrix temp->zero(); if(!single_matrix_mode) { inner_product_matrix->vector_mult(*temp, get_rb_evaluation().get_basis_function(j)); } else { assemble_inner_product_matrix(matrix); matrix->vector_mult(*temp, get_rb_evaluation().get_basis_function(j)); } value = get_rb_evaluation().get_basis_function(i).dot(*temp); get_rb_evaluation().RB_inner_product_matrix(i,j) = value; if(i!=j) { // The inner product matrix is assumed // to be symmetric get_rb_evaluation().RB_inner_product_matrix(j,i) = value; } } for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { // Compute reduced Aq matrix temp->zero(); if(!single_matrix_mode) { get_Aq(q_a)->vector_mult(*temp, get_rb_evaluation().get_basis_function(j)); } else { assemble_Aq_matrix(q_a,matrix); matrix->vector_mult(*temp, get_rb_evaluation().get_basis_function(j)); } value = (*temp).dot(get_rb_evaluation().get_basis_function(i)); get_rb_evaluation().RB_Aq_vector[q_a](i,j) = value; if(i!=j) { temp->zero(); if(!single_matrix_mode) { get_Aq(q_a)->vector_mult(*temp, get_rb_evaluation().get_basis_function(i)); } else { // matrix should still hold affine matrix q_a matrix->vector_mult(*temp, get_rb_evaluation().get_basis_function(i)); } value = (*temp).dot(get_rb_evaluation().get_basis_function(j)); get_rb_evaluation().RB_Aq_vector[q_a](j,i) = value; } } } } STOP_LOG("update_RB_system_matrices()", "RBConstruction"); } void RBConstruction::update_residual_terms(bool compute_inner_products) { START_LOG("update_residual_terms()", "RBConstruction"); unsigned int RB_size = get_rb_evaluation().get_n_basis_functions(); if(!single_matrix_mode) { matrix->zero(); matrix->add(1., *inner_product_matrix); if(constrained_problem) matrix->add(1., *constraint_matrix); } if(single_matrix_mode) { assemble_inner_product_matrix(matrix); if(constrained_problem) add_scaled_matrix_and_vector(1., constraint_assembly, matrix, NULL); } if(reuse_preconditioner) { // For the first solve, make sure we generate a new preconditioner linear_solver->reuse_preconditioner(false); } for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { for(unsigned int i=(RB_size-delta_N); i<RB_size; i++) { // Initialize the vector in which we'll store the representor if(!get_rb_evaluation().Aq_representor[q_a][i]) { get_rb_evaluation().Aq_representor[q_a][i] = (NumericVector<Number>::build().release()); get_rb_evaluation().Aq_representor[q_a][i]->init(this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } libmesh_assert(get_rb_evaluation().Aq_representor[q_a][i]->size() == this->n_dofs() && get_rb_evaluation().Aq_representor[q_a][i]->local_size() == this->n_local_dofs() ); rhs->zero(); if(!single_matrix_mode) { get_Aq(q_a)->vector_mult(*rhs, get_rb_evaluation().get_basis_function(i)); } else { assemble_scaled_matvec(1., &rb_assembly_expansion->get_A_assembly(q_a), *rhs, get_rb_evaluation().get_basis_function(i)); } rhs->scale(-1.); // zero_dirichlet_dofs_on_rhs(); solution->zero(); if (!is_quiet()) { libMesh::out << "Starting solve [q_a][i]=[" << q_a <<"]["<< i << "] in RBConstruction::update_residual_terms() at " << Utility::get_timestamp() << std::endl; } solve(); if (!is_quiet()) { libMesh::out << "Finished solve [q_a][i]=[" << q_a <<"]["<< i << "] in RBConstruction::update_residual_terms() at " << Utility::get_timestamp() << std::endl; libMesh::out << this->n_linear_iterations() << " iterations, final residual " << this->final_linear_residual() << std::endl; } // Make sure we didn't max out the number of iterations if( (this->n_linear_iterations() >= this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) && (this->final_linear_residual() > this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) ) { libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = " << this->final_linear_residual() << ", number of iterations = " << this->n_linear_iterations() << std::endl << std::endl; // libmesh_error(); } // Store the representor *get_rb_evaluation().Aq_representor[q_a][i] = *solution; if(reuse_preconditioner) { // set this flag again in case we didn't do any F solves linear_solver->reuse_preconditioner(true); } } } if(reuse_preconditioner) { linear_solver->reuse_preconditioner(false); } // Now compute and store the inner products (if requested) if (compute_inner_products) { if(single_matrix_mode && constrained_problem) assemble_inner_product_matrix(matrix); for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector,*Fq_representor[q_f]); } else { matrix->vector_mult(*inner_product_storage_vector,*Fq_representor[q_f]); } for(unsigned int q_a=0; q_a<get_rb_theta_expansion().get_n_A_terms(); q_a++) { for(unsigned int i=(RB_size-delta_N); i<RB_size; i++) { get_rb_evaluation().Fq_Aq_representor_innerprods[q_f][q_a][i] = inner_product_storage_vector->dot(*get_rb_evaluation().Aq_representor[q_a][i]); } } } unsigned int q=0; for(unsigned int q_a1=0; q_a1<get_rb_theta_expansion().get_n_A_terms(); q_a1++) { for(unsigned int q_a2=q_a1; q_a2<get_rb_theta_expansion().get_n_A_terms(); q_a2++) { for(unsigned int i=(RB_size-delta_N); i<RB_size; i++) { for(unsigned int j=0; j<RB_size; j++) { if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector, *get_rb_evaluation().Aq_representor[q_a2][j]); } else { matrix->vector_mult(*inner_product_storage_vector, *get_rb_evaluation().Aq_representor[q_a2][j]); } get_rb_evaluation().Aq_Aq_representor_innerprods[q][i][j] = inner_product_storage_vector->dot(*get_rb_evaluation().Aq_representor[q_a1][i]); if(i != j) { if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector, *get_rb_evaluation().Aq_representor[q_a2][i]); } else { matrix->vector_mult(*inner_product_storage_vector, *get_rb_evaluation().Aq_representor[q_a2][i]); } get_rb_evaluation().Aq_Aq_representor_innerprods[q][j][i] = inner_product_storage_vector->dot(*get_rb_evaluation().Aq_representor[q_a1][j]); } } } q++; } } } // end if (compute_inner_products) STOP_LOG("update_residual_terms()", "RBConstruction"); } void RBConstruction::assemble_matrix_for_output_dual_solves() { // By default we use the inner product matrix for steady problems if(!single_matrix_mode) { matrix->zero(); matrix->close(); matrix->add(1., *inner_product_matrix); } else { assemble_inner_product_matrix(matrix); } } void RBConstruction::compute_output_dual_innerprods() { // Skip calculations if we've already computed the output dual norms if(!output_dual_innerprods_computed) { // Short circuit if we don't have any outputs if( get_rb_theta_expansion().get_n_outputs() == 0 ) { output_dual_innerprods_computed = true; return; } // Only log if we get to here START_LOG("compute_output_dual_innerprods()", "RBConstruction"); libMesh::out << "Compute output dual norms" << std::endl; // Note: the solves in this function employ a single system matrix and multiple // right-hand sides, so we may get better performance using a different // preconditioner, or even a direct solver. std::pair<std::string,std::string> orig_solver = this->set_alternative_solver(this->linear_solver); // Find out the largest value of Q_l unsigned int max_Q_l = 0; for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) max_Q_l = (get_rb_theta_expansion().get_n_output_terms(n) > max_Q_l) ? get_rb_theta_expansion().get_n_output_terms(n) : max_Q_l; std::vector< NumericVector<Number>* > L_q_representor(max_Q_l); for(unsigned int q=0; q<max_Q_l; q++) { L_q_representor[q] = (NumericVector<Number>::build().release()); L_q_representor[q]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } if(reuse_preconditioner) { // For the first solve, make sure we generate a new preconditioner linear_solver->reuse_preconditioner(false); } for(unsigned int n=0; n<get_rb_theta_expansion().get_n_outputs(); n++) { // If constrained_problem, we need to reassemble to add the constraint part back in if( (n==0) || constrained_problem) { assemble_matrix_for_output_dual_solves(); if(constrained_problem) { if(!single_matrix_mode) { matrix->add(1., *constraint_matrix); } else { add_scaled_matrix_and_vector(1., constraint_assembly, matrix, NULL); } } } for(unsigned int q_l=0; q_l<get_rb_theta_expansion().get_n_output_terms(n); q_l++) { rhs->zero(); rhs->add(1., *get_output_vector(n,q_l)); // zero_dirichlet_dofs_on_rhs(); solution->zero(); if (!is_quiet()) libMesh::out << "Starting solve n=" << n << ", q_l=" << q_l << " in RBConstruction::compute_output_dual_innerprods() at " << Utility::get_timestamp() << std::endl; solve(); if (!is_quiet()) { libMesh::out << "Finished solve n=" << n << ", q_l=" << q_l << " in RBConstruction::compute_output_dual_innerprods() at " << Utility::get_timestamp() << std::endl; libMesh::out << this->n_linear_iterations() << " iterations, final residual " << this->final_linear_residual() << std::endl; } // Make sure we didn't max out the number of iterations if( (this->n_linear_iterations() >= this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) && (this->final_linear_residual() > this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) ) { libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = " << this->final_linear_residual() << ", number of iterations = " << this->n_linear_iterations() << std::endl << std::endl; // libmesh_error(); } *L_q_representor[q_l] = *solution; if(reuse_preconditioner) { // After we do a solve, tell PETSc we want to reuse the preconditioner // since the system matrix is not changing. linear_solver->reuse_preconditioner(true); } } // Get rid of the constraint part of the matrix before computing inner products if(constrained_problem) assemble_matrix_for_output_dual_solves(); unsigned int q=0; for(unsigned int q_l1=0; q_l1<get_rb_theta_expansion().get_n_output_terms(n); q_l1++) { matrix->vector_mult(*inner_product_storage_vector, *L_q_representor[q_l1]); for(unsigned int q_l2=q_l1; q_l2<get_rb_theta_expansion().get_n_output_terms(n); q_l2++) { output_dual_innerprods[n][q] = L_q_representor[q_l2]->dot(*inner_product_storage_vector); libMesh::out << "output_dual_innerprods[" << n << "][" << q << "] = " << output_dual_innerprods[n][q] << std::endl; q++; } } } // reset same_preconditioner to false once all solves are finished if(reuse_preconditioner) { linear_solver->reuse_preconditioner(false); } // Finally clear the L_q_representor vectors for(unsigned int q=0; q<max_Q_l; q++) { if(L_q_representor[q]) { delete L_q_representor[q]; L_q_representor[q] = NULL; } } output_dual_innerprods_computed = true; // Change the preconditioner, Krylov solver back to their original // value. Note: does nothing if RBBase::alternative_solver == // "unchanged". this->reset_alternative_solver(this->linear_solver, orig_solver); STOP_LOG("compute_output_dual_innerprods()", "RBConstruction"); } get_rb_evaluation().output_dual_innerprods = output_dual_innerprods; } void RBConstruction::compute_Fq_representor_innerprods(bool compute_inner_products) { // Skip calculations if we've already computed the Fq_representors if(!Fq_representor_innerprods_computed) { // Only log if we get to here START_LOG("compute_Fq_representor_innerprods()", "RBConstruction"); if(!single_matrix_mode) { matrix->zero(); matrix->close(); matrix->add(1., *inner_product_matrix); if(constrained_problem) matrix->add(1., *constraint_matrix); } if(single_matrix_mode) { assemble_inner_product_matrix(matrix); if(constrained_problem) add_scaled_matrix_and_vector(1., constraint_assembly, matrix, NULL); } if(reuse_preconditioner) { // For the first solve, make sure we generate a new preconditioner linear_solver->reuse_preconditioner(false); } for(unsigned int q_f=0; q_f<get_rb_theta_expansion().get_n_F_terms(); q_f++) { if(!Fq_representor[q_f]) { Fq_representor[q_f] = (NumericVector<Number>::build().release()); Fq_representor[q_f]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); } libmesh_assert(Fq_representor[q_f]->size() == this->n_dofs() && Fq_representor[q_f]->local_size() == this->n_local_dofs() ); rhs->zero(); rhs->add(1., *get_Fq(q_f)); // zero_dirichlet_dofs_on_rhs(); solution->zero(); if (!is_quiet()) libMesh::out << "Starting solve q_f=" << q_f << " in RBConstruction::update_residual_terms() at " << Utility::get_timestamp() << std::endl; solve(); if (!is_quiet()) { libMesh::out << "Finished solve q_f=" << q_f << " in RBConstruction::update_residual_terms() at " << Utility::get_timestamp() << std::endl; libMesh::out << this->n_linear_iterations() << " iterations, final residual " << this->final_linear_residual() << std::endl; } // Make sure we didn't max out the number of iterations if( (this->n_linear_iterations() >= this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) && (this->final_linear_residual() > this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) ) { libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = " << this->final_linear_residual() << ", number of iterations = " << this->n_linear_iterations() << std::endl << std::endl; // libmesh_error(); } *Fq_representor[q_f] = *solution; if(reuse_preconditioner) { // After we do a solve, tell PETSc we want to reuse the preconditioner // since the system matrix is not changing. linear_solver->reuse_preconditioner(true); } } // Reset the same_preconditioner flag if(reuse_preconditioner) { linear_solver->reuse_preconditioner(false); } if (compute_inner_products) { unsigned int q=0; if(single_matrix_mode && constrained_problem) assemble_inner_product_matrix(matrix); for(unsigned int q_f1=0; q_f1<get_rb_theta_expansion().get_n_F_terms(); q_f1++) { if(!single_matrix_mode) { inner_product_matrix->vector_mult(*inner_product_storage_vector, *Fq_representor[q_f1]); } else { matrix->vector_mult(*inner_product_storage_vector, *Fq_representor[q_f1]); } for(unsigned int q_f2=q_f1; q_f2<get_rb_theta_expansion().get_n_F_terms(); q_f2++) { Fq_representor_innerprods[q] = inner_product_storage_vector->dot(*Fq_representor[q_f2]); q++; } } } // end if (compute_inner_products) Fq_representor_innerprods_computed = true; STOP_LOG("compute_Fq_representor_innerprods()", "RBConstruction"); } get_rb_evaluation().Fq_representor_innerprods = Fq_representor_innerprods; } void RBConstruction::load_rb_solution() { START_LOG("load_rb_solution()", "RBConstruction"); solution->zero(); if(get_rb_evaluation().RB_solution.size() > get_rb_evaluation().get_n_basis_functions()) { libMesh::err << "ERROR: System contains " << get_rb_evaluation().get_n_basis_functions() << " basis functions." << " RB_solution vector constains " << get_rb_evaluation().RB_solution.size() << " entries." << " RB_solution in RBConstruction::load_rb_solution is too long!" << std::endl; libmesh_error(); } for(unsigned int i=0; i<get_rb_evaluation().RB_solution.size(); i++) { solution->add(get_rb_evaluation().RB_solution(i), get_rb_evaluation().get_basis_function(i)); } update(); STOP_LOG("load_rb_solution()", "RBConstruction"); } // The slow (but simple, non-error prone) way to compute the residual dual norm // Useful for error checking //Real RBConstruction::compute_residual_dual_norm(const unsigned int N) //{ // START_LOG("compute_residual_dual_norm()", "RBConstruction"); // // // Put the residual in rhs in order to compute the norm of the Riesz representor // // Note that this only works in serial since otherwise each processor will // // have a different parameter value during the Greedy training. // // AutoPtr< NumericVector<Number> > RB_sol = NumericVector<Number>::build(); // RB_sol->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); // // AutoPtr< NumericVector<Number> > temp = NumericVector<Number>::build(); // temp->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); // // for(unsigned int i=0; i<N; i++) // { // RB_sol->add(RB_solution(i), get_rb_evaluation().get_basis_function(i)); // } // // this->truth_assembly(); // matrix->vector_mult(*temp, *RB_sol); // rhs->add(-1., *temp); // // // Then solve to get the Reisz representor // matrix->zero(); // matrix->add(1., *inner_product_matrix); // if(constrained_problem) // matrix->add(1., *constraint_matrix); // // solution->zero(); // solve(); // // Make sure we didn't max out the number of iterations // if( (this->n_linear_iterations() >= // this->get_equation_systems().parameters.get<unsigned int>("linear solver maximum iterations")) && // (this->final_linear_residual() > // this->get_equation_systems().parameters.get<Real>("linear solver tolerance")) ) // { // libMesh::out << "Warning: Linear solver may not have converged! Final linear residual = " // << this->final_linear_residual() << ", number of iterations = " // << this->n_linear_iterations() << std::endl << std::endl; // // libmesh_error(); // } // // if(!single_matrix_mode) // { // inner_product_matrix->vector_mult(*inner_product_storage_vector, *solution); // } // else // { // assemble_inner_product_matrix(matrix); // matrix->vector_mult(*inner_product_storage_vector, *solution); // } // // Real slow_residual_norm_sq = solution->dot(*inner_product_storage_vector); // // STOP_LOG("compute_residual_dual_norm()", "RBConstruction"); // // return std::sqrt( libmesh_real(slow_residual_norm_sq) ); //} SparseMatrix<Number>* RBConstruction::get_inner_product_matrix() { if(single_matrix_mode) { libMesh::err << "Error: The inner-product matrix is not stored in single-matrix mode." << std::endl; libmesh_error(); } return inner_product_matrix.get(); } SparseMatrix<Number>* RBConstruction::get_non_dirichlet_inner_product_matrix() { if(!store_non_dirichlet_operators) { libMesh::err << "Error: Must have store_non_dirichlet_operators==true " << "to access non_dirichlet_inner_product_matrix." << std::endl; libmesh_error(); } if(single_matrix_mode) { libMesh::err << "Error: The non-Dirichlet inner-product matrix is not stored in single-matrix mode." << std::endl; libmesh_error(); } return non_dirichlet_inner_product_matrix.get(); } SparseMatrix<Number>* RBConstruction::get_Aq(unsigned int q) { if(single_matrix_mode) { libMesh::err << "Error: The affine matrices are not stored in single-matrix mode." << std::endl; libmesh_error(); } if(q >= get_rb_theta_expansion().get_n_A_terms()) { libMesh::err << "Error: We must have q < Q_a in get_Aq." << std::endl; libmesh_error(); } return Aq_vector[q]; } SparseMatrix<Number>* RBConstruction::get_non_dirichlet_Aq(unsigned int q) { if(!store_non_dirichlet_operators) { libMesh::err << "Error: Must have store_non_dirichlet_operators==true to access non_dirichlet_Aq." << std::endl; libmesh_error(); } if(single_matrix_mode) { libMesh::err << "Error: The affine matrices are not stored in single-matrix mode." << std::endl; libmesh_error(); } if(q >= get_rb_theta_expansion().get_n_A_terms()) { libMesh::err << "Error: We must have q < Q_a in get_Aq." << std::endl; libmesh_error(); } return non_dirichlet_Aq_vector[q]; } NumericVector<Number>* RBConstruction::get_Fq(unsigned int q) { if(q >= get_rb_theta_expansion().get_n_F_terms()) { libMesh::err << "Error: We must have q < Q_f in get_Fq." << std::endl; libmesh_error(); } return Fq_vector[q]; } NumericVector<Number>* RBConstruction::get_non_dirichlet_Fq(unsigned int q) { if(!store_non_dirichlet_operators) { libMesh::err << "Error: Must have store_non_dirichlet_operators==true to access non_dirichlet_Fq." << std::endl; libmesh_error(); } if(q >= get_rb_theta_expansion().get_n_F_terms()) { libMesh::err << "Error: We must have q < Q_f in get_Fq." << std::endl; libmesh_error(); } return non_dirichlet_Fq_vector[q]; } NumericVector<Number>* RBConstruction::get_output_vector(unsigned int n, unsigned int q_l) { if( (n >= get_rb_theta_expansion().get_n_outputs()) || (q_l >= get_rb_theta_expansion().get_n_output_terms(n)) ) { libMesh::err << "Error: We must have n < n_outputs and " << "q_l < get_rb_theta_expansion().get_n_output_terms(n) in get_output_vector." << std::endl; libmesh_error(); } return outputs_vector[n][q_l]; } AutoPtr<DirichletBoundary> RBConstruction::build_zero_dirichlet_boundary_object() { ZeroFunction<> zf; std::set<boundary_id_type> dirichlet_ids; std::vector<unsigned int> variables; // The DirichletBoundary constructor clones zf, so it's OK that zf is only in local scope return AutoPtr<DirichletBoundary> (new DirichletBoundary(dirichlet_ids, variables, &zf)); } void RBConstruction::write_riesz_representors_to_files(const std::string& riesz_representors_dir, const bool write_binary_residual_representors) { START_LOG("write_riesz_representors_to_files()", "RBConstruction"); // Write out Riesz representors. These are useful to have when restarting, // so you don't have to recompute them all over again. // First we write out the Fq representors, these are independent of an RBEvaluation object. libMesh::out << "Writing out the Fq_representors..." << std::endl; std::ostringstream file_name; const std::string riesz_representor_suffix = (write_binary_residual_representors ? ".xdr" : ".dat"); struct stat stat_info; // Residual representors written out to their own separate directory if ( libMesh::processor_id() == 0) if ( mkdir(riesz_representors_dir.c_str(), 0755) != 0) libMesh::out << "Skipping creating residual_representors directory: " << strerror(errno) << std::endl; for (unsigned int i=0; i<Fq_representor.size(); ++i) { if (Fq_representor[i] != NULL) { file_name.str(""); // reset filename file_name << riesz_representors_dir << "/Fq_representor" << i << riesz_representor_suffix; // Check to see if file exists, if so, don't overwrite it, we assume it was // there from a previous call to this function. Note: if stat returns zero // it means it successfully got the file attributes (and therefore the file // exists). Because of the following factors: // 1.) write_serialized_data takes longer for proc 0 than it does for others, // so processors can get out of sync. // 2.) The constructor for Xdr opens a (0 length) file on *all* processors, // there are typically hundreds of 0-length files created during this loop, // and that screws up checking for the existence of files. One way to stay // in sync is to but a barrier at each iteration of the loop -- not sure how // bad this will affect performance, but it can't be much worse than serialized // I/O already is :) int stat_result = stat(file_name.str().c_str(), &stat_info); if ( (stat_result != 0) || // file definitely doesn't already exist (stat_info.st_size == 0)) // file exists, but has zero length (can happen if another proc already opened it!) { // No need to copy! // *solution = *(Fq_representor[i]); // std::swap doesn't work on pointers //std::swap(solution.get(), Fq_representor[i]); Fq_representor[i]->swap(*solution); Xdr fqr_data(file_name.str(), write_binary_residual_representors ? ENCODE : WRITE); write_serialized_data(fqr_data, false); // Synchronize before moving on Parallel::barrier(); // Swap back. Fq_representor[i]->swap(*solution); // TODO: bzip the resulting file? See $LIBMESH_DIR/src/mesh/unstructured_mesh.C // for the system call, be sure to do it only on one processor, etc. } } } // Next, write out the Aq representors associated with rb_eval. libMesh::out << "Writing out the Aq_representors..." << std::endl; const unsigned int jstop = get_rb_evaluation().get_n_basis_functions(); const unsigned int jstart = jstop-get_delta_N(); for (unsigned int i=0; i<get_rb_evaluation().Aq_representor.size(); ++i) for (unsigned int j=jstart; j<jstop; ++j) { libMesh::out << "Writing out Aq_representor[" << i << "][" << j << "]..." << std::endl; libmesh_assert(get_rb_evaluation().Aq_representor[i][j] != NULL); file_name.str(""); // reset filename file_name << riesz_representors_dir << "/Aq_representor" << i << "_" << j << riesz_representor_suffix; { // No need to copy! Use swap instead. // *solution = *(Aq_representor[i][j]); get_rb_evaluation().Aq_representor[i][j]->swap(*solution); Xdr aqr_data(file_name.str(), write_binary_residual_representors ? ENCODE : WRITE); write_serialized_data(aqr_data, false); // Synchronize before moving on Parallel::barrier(); // Swap back. get_rb_evaluation().Aq_representor[i][j]->swap(*solution); // TODO: bzip the resulting file? See $LIBMESH_DIR/src/mesh/unstructured_mesh.C // for the system call, be sure to do it only on one processor, etc. } } STOP_LOG("write_riesz_representors_to_files()", "RBConstruction"); } void RBConstruction::read_riesz_representors_from_files(const std::string& riesz_representors_dir, const bool read_binary_residual_representors) { START_LOG("read_riesz_representors_from_files()", "RBConstruction"); libMesh::out << "Reading in the Fq_representors..." << std::endl; const std::string riesz_representor_suffix = (read_binary_residual_representors ? ".xdr" : ".dat"); std::ostringstream file_name; struct stat stat_info; // Read in the Fq_representors. There should be Q_f of these. FIXME: // should we be worried about leaks here? for (unsigned int i=0; i<Fq_representor.size(); ++i) { if (Fq_representor[i] != NULL) { libMesh::out << "Error, must delete existing Fq_representor before reading in from file." << std::endl; libmesh_error(); } } for (unsigned int i=0; i<Fq_representor.size(); i++) { file_name.str(""); // reset filename file_name << riesz_representors_dir << "/Fq_representor" << i << riesz_representor_suffix; // On processor zero check to be sure the file exists if (libMesh::processor_id() == 0) { int stat_result = stat(file_name.str().c_str(), &stat_info); if (stat_result != 0) { libMesh::out << "File does not exist: " << file_name.str() << std::endl; libmesh_error(); } } Xdr fqr_data(file_name.str(), read_binary_residual_representors ? DECODE : READ); read_serialized_data(fqr_data, false); Fq_representor[i] = NumericVector<Number>::build().release(); Fq_representor[i]->init (this->n_dofs(), this->n_local_dofs(), false, libMeshEnums::PARALLEL); // No need to copy, just swap // *Fq_representor[i] = *solution; Fq_representor[i]->swap(*solution); } // Alert the update_residual_terms() function that we don't need to recompute // the Fq_representors as we have already read them in from file! Fq_representor_innerprods_computed = true; libMesh::out << "Reading in the Aq_representors..." << std::endl; // Read in the Aq representors. The class makes room for [Q_a][Nmax] of these. We are going to // read in [Q_a][get_rb_evaluation().get_n_basis_functions()]. FIXME: // should we be worried about leaks in the locations where we're about to fill entries? for (unsigned int i=0; i<get_rb_evaluation().Aq_representor.size(); ++i) for (unsigned int j=0; j<get_rb_evaluation().Aq_representor[i].size(); ++j) { if (get_rb_evaluation().Aq_representor[i][j] != NULL) { libMesh::out << "Error, must delete existing Aq_representor before reading in from file." << std::endl; libmesh_error(); } } // Now ready to read them in from file! for (unsigned int i=0; i<get_rb_evaluation().Aq_representor.size(); ++i) for (unsigned int j=0; j<get_rb_evaluation().get_n_basis_functions(); ++j) { file_name.str(""); // reset filename file_name << riesz_representors_dir << "/Aq_representor" << i << "_" << j << riesz_representor_suffix; // On processor zero check to be sure the file exists if (libMesh::processor_id() == 0) { int stat_result = stat(file_name.str().c_str(), &stat_info); if (stat_result != 0) { libMesh::out << "File does not exist: " << file_name.str() << std::endl; libmesh_error(); } } Xdr aqr_data(file_name.str(), read_binary_residual_representors ? DECODE : READ); read_serialized_data(aqr_data, false); get_rb_evaluation().Aq_representor[i][j] = NumericVector<Number>::build().release(); get_rb_evaluation().Aq_representor[i][j]->init (n_dofs(), n_local_dofs(), false, libMeshEnums::PARALLEL); // No need to copy, just swap //*Aq_representor[i][j] = *solution; get_rb_evaluation().Aq_representor[i][j]->swap(*solution); } STOP_LOG("read_riesz_representors_from_files()", "RBConstruction"); } } // namespace libMesh
#include "omp.h" inline kth_cv_omp::kth_cv_omp(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length, const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim) { actions.load( actionNames ); } // Log-Euclidean Distance inline void kth_cv_omp::logEucl() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; float acc; acc = 0; int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 vec real_labels; vec est_labels; field<std::string> test_video_list(n_test); real_labels.zeros(n_test); est_labels.zeros(n_test); int k=0; for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { if( !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3 { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); vec count = zeros<vec>( n_actions ); for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; //debe devolver el est_labe de ese segmento est_lab_segm(s) = logEucl_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); count( est_lab_segm(s) )++; //getchar(); } uword index_video; double max_val = count.max(index_video); //est_lab_segm.t().print("est_lab_segm"); cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl; real_labels(k) = act; est_labels(k) = index_video; test_video_list(k) = load_sub_path.str(); real_labels.save("Log_Eucl_real_labels.dat", raw_ascii); est_labels.save("Log_Eucl_est_labels.dat", raw_ascii); test_video_list.save("Log_Eucl_test_video_list.dat", raw_ascii); k++; if (index_video == act) { acc++; } //getchar(); } } } } cout << "Performance: " << acc*100/n_test << " %" << endl; } inline uword kth_cv_omp::logEucl_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { //wall_clock timer; //timer.tic(); mat logMtest_cov; logMtest_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist, tmp_dist; tmp_dist = datum::inf; double est_lab; //cout << "Comparing with person "; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); vec dist_segm_s<zeros> (num_s); #pragma omp for for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; mat logMtrain_cov; logMtrain_cov.load( load_cov_seg_tr.str() ); //logMtest_cov.print("logMtest_cov"); //train_cov.print("train_cov"); dist_segm_s(s_tr) = norm( logMtest_cov - logMtrain_cov, "fro"); //cout << "dist " << dis //cout << "Press a key" << endl; //getchar(); } #pragma omp barrier dist_segm_s.t().print("dist_segm_s"); getchar(); } } } } //double n = timer.toc(); //cout << "number of seconds: " << n << endl; //cout << " est_lab "<< est_lab << endl << endl; //getchar(); return est_lab; } //DO IT // Stein Divergence inline void kth_cv_omp::SteinDiv() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; float acc; acc = 0; int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 vec real_labels; vec est_labels; field<std::string> test_video_list(n_test); real_labels.zeros(n_test); est_labels.zeros(n_test); int k=0; for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { if( !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3 { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); vec count = zeros<vec>( n_actions ); for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; est_lab_segm(s) = SteinDiv_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); count( est_lab_segm(s) )++; //getchar(); } uword index_video; double max_val = count.max(index_video); //est_lab_segm.t().print("est_lab_segm"); cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl; real_labels(k) = act; est_labels(k) = index_video; test_video_list(k) = load_sub_path.str(); real_labels.save("Stein_div_real_labels.dat", raw_ascii); est_labels.save("Stein_div__est_labels.dat", raw_ascii); test_video_list.save("Stein_div_test_video_list.dat", raw_ascii); k++; if (index_video == act) { acc++; } //getchar(); } } } } cout << "Performance: " << acc*100/n_test << " %" << endl; } //DO IT!!!!!!!!! inline uword kth_cv_omp::SteinDiv_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { //wall_clock timer; //timer.tic(); mat test_cov; test_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist_stein, tmp_dist; tmp_dist = datum::inf; double est_lab; //cout << "Comparing with person "; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; mat train_cov; train_cov.load( load_cov_seg_tr.str() ); //Esto vienen de PartI4. No recuerdo mas :( double det_op1 = det( diagmat( (test_cov + train_cov)/2 ) ); double det_op2 = det( diagmat( ( test_cov%train_cov ) ) ); dist_stein = log( det_op1 ) - 0.5*log( det_op2 ) ; //dist_stein = norm( logMtest_cov - logMtrain_cov, "fro"); //cout << "dist " << dist << endl; if (dist_stein < tmp_dist) { //cout << "Es menor" << endl; tmp_dist = dist_stein; est_lab = act; } //cout << "Press a key" << endl; //getchar(); } } } } } //double n = timer.toc(); //cout << "number of seconds: " << n << endl; //cout << " est_lab "<< est_lab << endl << endl; //getchar(); return est_lab; } try oPenMP #include "omp.h" inline kth_cv_omp::kth_cv_omp(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length, const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim) { actions.load( actionNames ); } // Log-Euclidean Distance inline void kth_cv_omp::logEucl() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; float acc; acc = 0; int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 vec real_labels; vec est_labels; field<std::string> test_video_list(n_test); real_labels.zeros(n_test); est_labels.zeros(n_test); int k=0; for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { if( !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3 { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); vec count = zeros<vec>( n_actions ); for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; //debe devolver el est_labe de ese segmento est_lab_segm(s) = logEucl_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); count( est_lab_segm(s) )++; //getchar(); } uword index_video; double max_val = count.max(index_video); //est_lab_segm.t().print("est_lab_segm"); cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl; real_labels(k) = act; est_labels(k) = index_video; test_video_list(k) = load_sub_path.str(); real_labels.save("Log_Eucl_real_labels.dat", raw_ascii); est_labels.save("Log_Eucl_est_labels.dat", raw_ascii); test_video_list.save("Log_Eucl_test_video_list.dat", raw_ascii); k++; if (index_video == act) { acc++; } //getchar(); } } } } cout << "Performance: " << acc*100/n_test << " %" << endl; } inline uword kth_cv_omp::logEucl_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { //wall_clock timer; //timer.tic(); mat logMtest_cov; logMtest_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist, tmp_dist; tmp_dist = datum::inf; double est_lab; //cout << "Comparing with person "; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); vec dist_segm_s<zeros> (num_s); #pragma omp for for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; mat logMtrain_cov; logMtrain_cov.load( load_cov_seg_tr.str() ); //logMtest_cov.print("logMtest_cov"); //train_cov.print("train_cov"); dist_segm_s(s_tr) = norm( logMtest_cov - logMtrain_cov, "fro"); //cout << "dist " << dis //cout << "Press a key" << endl; //getchar(); } #pragma omp barrier dist_segm_s.t().print("dist_segm_s"); getchar(); } } } } //double n = timer.toc(); //cout << "number of seconds: " << n << endl; //cout << " est_lab "<< est_lab << endl << endl; //getchar(); return est_lab; } //DO IT // Stein Divergence inline void kth_cv_omp::SteinDiv() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; float acc; acc = 0; int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 vec real_labels; vec est_labels; field<std::string> test_video_list(n_test); real_labels.zeros(n_test); est_labels.zeros(n_test); int k=0; for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { if( !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3 { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); vec count = zeros<vec>( n_actions ); for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; est_lab_segm(s) = SteinDiv_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); count( est_lab_segm(s) )++; //getchar(); } uword index_video; double max_val = count.max(index_video); //est_lab_segm.t().print("est_lab_segm"); cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl; real_labels(k) = act; est_labels(k) = index_video; test_video_list(k) = load_sub_path.str(); real_labels.save("Stein_div_real_labels.dat", raw_ascii); est_labels.save("Stein_div__est_labels.dat", raw_ascii); test_video_list.save("Stein_div_test_video_list.dat", raw_ascii); k++; if (index_video == act) { acc++; } //getchar(); } } } } cout << "Performance: " << acc*100/n_test << " %" << endl; } //DO IT!!!!!!!!! inline uword kth_cv_omp::SteinDiv_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { //wall_clock timer; //timer.tic(); mat test_cov; test_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist_stein, tmp_dist; tmp_dist = datum::inf; double est_lab; //cout << "Comparing with person "; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; mat train_cov; train_cov.load( load_cov_seg_tr.str() ); //Esto vienen de PartI4. No recuerdo mas :( double det_op1 = det( diagmat( (test_cov + train_cov)/2 ) ); double det_op2 = det( diagmat( ( test_cov%train_cov ) ) ); dist_stein = log( det_op1 ) - 0.5*log( det_op2 ) ; //dist_stein = norm( logMtest_cov - logMtrain_cov, "fro"); //cout << "dist " << dist << endl; if (dist_stein < tmp_dist) { //cout << "Es menor" << endl; tmp_dist = dist_stein; est_lab = act; } //cout << "Press a key" << endl; //getchar(); } } } } } //double n = timer.toc(); //cout << "number of seconds: " << n << endl; //cout << " est_lab "<< est_lab << endl << endl; //getchar(); return est_lab; }
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Browser test for basic Chrome OS file manager functionality: // - The file list is updated when a file is added externally to the Downloads // folder. // - Selecting a file and copy-pasting it with the keyboard copies the file. // - Selecting a file and pressing delete deletes it. #include <algorithm> #include <string> #include "base/callback.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/files/file_path_watcher.h" #include "base/platform_file.h" #include "base/threading/platform_thread.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/chromeos/drive/drive_integration_service.h" #include "chrome/browser/chromeos/drive/file_system.h" #include "chrome/browser/chromeos/drive/file_system_observer.h" #include "chrome/browser/chromeos/extensions/file_manager/drive_test_util.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/google_apis/fake_drive_service.h" #include "chrome/browser/google_apis/gdata_wapi_parser.h" #include "chrome/browser/google_apis/test_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/test/base/ui_test_utils.h" #include "chromeos/chromeos_switches.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_view_host.h" #include "net/base/escape.h" #include "webkit/fileapi/external_mount_points.h" namespace { const char kKeyboardTestFileName[] = "world.ogv"; const char kKeyboardTestFileCopyName[] = "world (1).ogv"; // Test suffixes appended to the Javascript tests' names. const char kDownloadsVolume[] = "Downloads"; const char kDriveVolume[] = "Drive"; enum EntryType { FILE, DIRECTORY, }; enum SharedOption { NONE, SHARED, }; struct TestEntryInfo { EntryType type; const char* source_file_name; // Source file name to be used as a prototype. const char* target_name; // Target file or directory name. const char* mime_type; SharedOption shared_option; const char* last_modified_time_as_string; }; TestEntryInfo kTestEntrySetCommon[] = { { FILE, "text.txt", "hello.txt", "text/plain", NONE, "4 Sep 1998 12:34:56" }, { FILE, "image.png", "My Desktop Background.png", "text/plain", NONE, "18 Jan 2038 01:02:03" }, { FILE, "video.ogv", kKeyboardTestFileName, "text/plain", NONE, "4 July 2012 10:35:00" }, { DIRECTORY, "", "photos", NULL, NONE, "1 Jan 1980 23:59:59" }, { DIRECTORY, "", ".warez", NULL, NONE, "26 Oct 1985 13:39" } }; TestEntryInfo kTestEntrySetDriveOnly[] = { { FILE, "", "Test Document", "application/vnd.google-apps.document", NONE, "10 Apr 2013 16:20:00" }, { FILE, "", "Test Shared Document", "application/vnd.google-apps.document", SHARED, "20 Mar 2013 22:40:00" } }; // Monitors changes to a single file until the supplied condition callback // returns true. Usage: // TestFilePathWatcher watcher(path_to_file, MyConditionCallback); // watcher.StartAndWaitUntilReady(); // ... trigger filesystem modification ... // watcher.RunMessageLoopUntilConditionSatisfied(); class TestFilePathWatcher { public: typedef base::Callback<bool(const base::FilePath& file_path)> ConditionCallback; // Stores the supplied |path| and |condition| for later use (no side effects). TestFilePathWatcher(const base::FilePath& path, const ConditionCallback& condition); // Waits (running a message pump) until the callback returns true or // FilePathWatcher reports an error. Return true on success. bool RunMessageLoopUntilConditionSatisfied(); private: // Starts the FilePathWatcher to watch the target file. Also check if the // condition is already met. void StartWatching(); // FilePathWatcher callback (on the FILE thread). Posts Done() to the UI // thread when the condition is satisfied or there is an error. void FilePathWatcherCallback(const base::FilePath& path, bool error); const base::FilePath path_; ConditionCallback condition_; scoped_ptr<base::FilePathWatcher> watcher_; base::RunLoop run_loop_; base::Closure quit_closure_; bool failed_; }; TestFilePathWatcher::TestFilePathWatcher(const base::FilePath& path, const ConditionCallback& condition) : path_(path), condition_(condition), quit_closure_(run_loop_.QuitClosure()), failed_(false) { } void TestFilePathWatcher::StartWatching() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); watcher_.reset(new base::FilePathWatcher); bool ok = watcher_->Watch( path_, false /*recursive*/, base::Bind(&TestFilePathWatcher::FilePathWatcherCallback, base::Unretained(this))); ASSERT_TRUE(ok); // If the condition was already met before FilePathWatcher was launched, // FilePathWatcher won't be able to detect a change, so check the condition // here. if (condition_.Run(path_)) { watcher_.reset(); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, quit_closure_); return; } } void TestFilePathWatcher::FilePathWatcherCallback(const base::FilePath& path, bool failed) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); DCHECK_EQ(path_.value(), path.value()); if (failed || condition_.Run(path)) { failed_ = failed; watcher_.reset(); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, quit_closure_); } } bool TestFilePathWatcher::RunMessageLoopUntilConditionSatisfied() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&TestFilePathWatcher::StartWatching, base::Unretained(this))); // Wait until the condition is met. run_loop_.Run(); return !failed_; } // Returns true if a file with the given size is present at |path|. bool FilePresentWithSize(const int64 file_size, const base::FilePath& path) { int64 copy_size = 0; // If the file doesn't exist yet this will fail and we'll keep waiting. if (!file_util::GetFileSize(path, &copy_size)) return false; return (copy_size == file_size); } // Returns true if a file is not present at |path|. bool FileNotPresent(const base::FilePath& path) { return !file_util::PathExists(path); }; // The base class of volumes for test. // Sub-classes of this class are used by test cases and provide operations such // as creating files for each type of test volume. class TestVolume { public: virtual ~TestVolume() {} // Creates an entry with given information. virtual void CreateEntry(const TestEntryInfo& entry) = 0; // Returns the path of the root directory. virtual base::FilePath GetRootPath() const = 0; // Returns true if |file_path| exists. virtual bool PathExists(const base::FilePath& file_path) const = 0; // Returns the name of volume such as "Downloads" or "Drive". virtual std::string GetName() const = 0; // Waits until a file with the given size is present at |path|. Returns // true on success. virtual bool WaitUntilFilePresentWithSize(const base::FilePath& file_path, int64 file_size) = 0; // Waits until a file is not present at |path|. Returns true on success. virtual bool WaitUntilFileNotPresent(const base::FilePath& file_path) = 0; }; // The local volume class for test. // This class provides the operations for a test volume that simulates local // drive. class LocalTestVolume : public TestVolume { public: explicit LocalTestVolume(const std::string& mount_name) : mount_name_(mount_name) { } LocalTestVolume(const std::string& mount_name, const base::FilePath& local_path) : mount_name_(mount_name), local_path_(local_path) { } // Adds this volume to the file system as a local volume. Returns true on // success. bool Mount(Profile* profile) { if (local_path_.empty()) { if (!tmp_dir_.CreateUniqueTempDir()) return false; local_path_ = tmp_dir_.path().Append(mount_name_); } fileapi::ExternalMountPoints* const mount_points = content::BrowserContext::GetMountPoints(profile); mount_points->RevokeFileSystem(mount_name_); if (!mount_points->RegisterFileSystem( mount_name_, fileapi::kFileSystemTypeNativeLocal, local_path_)) { return false; } if (!file_util::CreateDirectory(local_path_)) return false; return true; } virtual void CreateEntry(const TestEntryInfo& entry) OVERRIDE { if (entry.type == DIRECTORY) { CreateDirectory(entry.target_name , entry.last_modified_time_as_string); } else if (entry.type == FILE) { CreateFile(entry.source_file_name, entry.target_name, entry.last_modified_time_as_string); } else { NOTREACHED(); } } void CreateFile(const std::string& source_file_name, const std::string& target_name, const std::string& modification_time) { std::string content_data; base::FilePath test_file_path = google_apis::test_util::GetTestFilePath("chromeos/file_manager"). AppendASCII(source_file_name); base::FilePath path = local_path_.AppendASCII(target_name); ASSERT_TRUE(file_util::PathExists(test_file_path)) << "Test file doesn't exist: " << test_file_path.value(); ASSERT_TRUE(file_util::CopyFile(test_file_path, path)); ASSERT_TRUE(file_util::PathExists(path)) << "Copying to: " << path.value() << " failed."; base::Time time; ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time)); ASSERT_TRUE(file_util::SetLastModifiedTime(path, time)); } void CreateDirectory(const std::string& target_name, const std::string& modification_time) { base::FilePath path = local_path_.AppendASCII(target_name); ASSERT_TRUE(file_util::CreateDirectory(path)) << "Failed to create a directory: " << target_name; base::Time time; ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time)); ASSERT_TRUE(file_util::SetLastModifiedTime(path, time)); } virtual std::string GetName() const OVERRIDE { return mount_name_; } virtual base::FilePath GetRootPath() const OVERRIDE { return local_path_; } virtual bool PathExists(const base::FilePath& file_path) const OVERRIDE { return file_util::PathExists(file_path); } virtual bool WaitUntilFilePresentWithSize( const base::FilePath& file_path, int64 file_size) OVERRIDE { TestFilePathWatcher watcher(file_path, base::Bind(FilePresentWithSize, file_size)); return watcher.RunMessageLoopUntilConditionSatisfied(); } virtual bool WaitUntilFileNotPresent( const base::FilePath& file_path) OVERRIDE { TestFilePathWatcher watcher(file_path, base::Bind(FileNotPresent)); return watcher.RunMessageLoopUntilConditionSatisfied(); } private: std::string mount_name_; base::FilePath local_path_; base::ScopedTempDir tmp_dir_; }; // The drive volume class for test. // This class provides the operations for a test volume that simulates Google // drive. class DriveTestVolume : public TestVolume, public drive::FileSystemObserver { public: DriveTestVolume() : fake_drive_service_(NULL), integration_service_(NULL), waiting_for_directory_change_(false) { } // Send request to add this volume to the file system as Google drive. // This method must be calld at SetUp method of FileManagerBrowserTestBase. // Returns true on success. bool SetUp() { if (!test_cache_root_.CreateUniqueTempDir()) return false; drive::DriveIntegrationServiceFactory::SetFactoryForTest( base::Bind(&DriveTestVolume::CreateDriveIntegrationService, base::Unretained(this))); return true; } virtual void CreateEntry(const TestEntryInfo& entry) OVERRIDE { if (entry.type == DIRECTORY) { CreateDirectory(entry.target_name, entry.last_modified_time_as_string); } else if (entry.type == FILE) { CreateFile(entry.source_file_name, entry.target_name, entry.mime_type, entry.shared_option == SHARED, entry.last_modified_time_as_string); } else { NOTREACHED(); } } // Creates an empty directory with the given |name| and |modification_time|. void CreateDirectory(const std::string& name, const std::string& modification_time) { google_apis::GDataErrorCode error = google_apis::GDATA_OTHER_ERROR; scoped_ptr<google_apis::ResourceEntry> resource_entry; fake_drive_service_->AddNewDirectory( fake_drive_service_->GetRootResourceId(), name, google_apis::test_util::CreateCopyResultCallback(&error, &resource_entry)); MessageLoop::current()->RunUntilIdle(); ASSERT_TRUE(error == google_apis::HTTP_CREATED); ASSERT_TRUE(resource_entry); base::Time time; ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time)); fake_drive_service_->SetLastModifiedTime( resource_entry->resource_id(), time, google_apis::test_util::CreateCopyResultCallback(&error, &resource_entry)); MessageLoop::current()->RunUntilIdle(); ASSERT_TRUE(error == google_apis::HTTP_SUCCESS); ASSERT_TRUE(resource_entry); CheckForUpdates(); } virtual std::string GetName() const OVERRIDE { return "Drive"; } // Creates a test file with the given spec. // Serves |test_file_name| file. Pass an empty string for an empty file. void CreateFile(const std::string& source_file_name, const std::string& target_file_name, const std::string& mime_type, bool shared_with_me, const std::string& modification_time) { google_apis::GDataErrorCode error = google_apis::GDATA_OTHER_ERROR; std::string content_data; if (!source_file_name.empty()) { base::FilePath source_file_path = google_apis::test_util::GetTestFilePath("chromeos/file_manager"). AppendASCII(source_file_name); ASSERT_TRUE(file_util::ReadFileToString(source_file_path, &content_data)); } scoped_ptr<google_apis::ResourceEntry> resource_entry; fake_drive_service_->AddNewFile( mime_type, content_data, fake_drive_service_->GetRootResourceId(), target_file_name, shared_with_me, google_apis::test_util::CreateCopyResultCallback(&error, &resource_entry)); MessageLoop::current()->RunUntilIdle(); ASSERT_EQ(google_apis::HTTP_CREATED, error); ASSERT_TRUE(resource_entry); base::Time time; ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time)); fake_drive_service_->SetLastModifiedTime( resource_entry->resource_id(), time, google_apis::test_util::CreateCopyResultCallback(&error, &resource_entry)); MessageLoop::current()->RunUntilIdle(); ASSERT_EQ(google_apis::HTTP_SUCCESS, error); ASSERT_TRUE(resource_entry); CheckForUpdates(); } virtual base::FilePath GetRootPath() const OVERRIDE { return base::FilePath(drive::util::kDriveMyDriveRootPath); } virtual bool PathExists(const base::FilePath& file_path) const OVERRIDE { DCHECK(integration_service_); DCHECK(integration_service_->file_system()); drive::FileError error = drive::FILE_ERROR_FAILED; scoped_ptr<drive::ResourceEntry> entry_proto; integration_service_->file_system()->GetResourceEntryByPath( file_path, google_apis::test_util::CreateCopyResultCallback(&error, &entry_proto)); google_apis::test_util::RunBlockingPoolTask(); return error == drive::FILE_ERROR_OK; } virtual bool WaitUntilFilePresentWithSize( const base::FilePath& file_path, int64 file_size) OVERRIDE { while (true) { if (FileIsPresentWithSize(file_path, file_size)) return true; WaitUntilDirectoryChanged(); } NOTREACHED(); return false; } virtual bool WaitUntilFileNotPresent( const base::FilePath& file_path) OVERRIDE { while (true) { if (FileIsNotPresent(file_path)) return true; WaitUntilDirectoryChanged(); } NOTREACHED(); return false; } virtual void OnDirectoryChanged( const base::FilePath& directory_path) OVERRIDE { if (waiting_for_directory_change_) MessageLoop::current()->Quit(); } // Notifies FileSystem that the contents in FakeDriveService are // changed, hence the new contents should be fetched. void CheckForUpdates() { if (integration_service_ && integration_service_->file_system()) { integration_service_->file_system()->CheckForUpdates(); } } // Waits until a notification for a directory change is received. void WaitUntilDirectoryChanged() { waiting_for_directory_change_ = true; MessageLoop::current()->Run(); waiting_for_directory_change_ = false; } // Returns true if a file of the size |file_size| is present at |file_path|. bool FileIsPresentWithSize( const base::FilePath& file_path, int64 file_size) { DCHECK(integration_service_); DCHECK(integration_service_->file_system()); drive::FileError error = drive::FILE_ERROR_FAILED; scoped_ptr<drive::ResourceEntry> entry_proto; integration_service_->file_system()->GetResourceEntryByPath( file_path, google_apis::test_util::CreateCopyResultCallback(&error, &entry_proto)); google_apis::test_util::RunBlockingPoolTask(); return (error == drive::FILE_ERROR_OK && entry_proto->file_info().size() == file_size); } // Returns true if a file is not present at |file_path|. bool FileIsNotPresent( const base::FilePath& file_path) { DCHECK(integration_service_); DCHECK(integration_service_->file_system()); drive::FileError error = drive::FILE_ERROR_FAILED; scoped_ptr<drive::ResourceEntry> entry_proto; integration_service_->file_system()->GetResourceEntryByPath( file_path, google_apis::test_util::CreateCopyResultCallback(&error, &entry_proto)); google_apis::test_util::RunBlockingPoolTask(); return error == drive::FILE_ERROR_NOT_FOUND; } drive::DriveIntegrationService* CreateDriveIntegrationService( Profile* profile) { fake_drive_service_ = new google_apis::FakeDriveService; fake_drive_service_->LoadResourceListForWapi( "chromeos/gdata/empty_feed.json"); fake_drive_service_->LoadAccountMetadataForWapi( "chromeos/gdata/account_metadata.json"); fake_drive_service_->LoadAppListForDriveApi("chromeos/drive/applist.json"); integration_service_ = new drive::DriveIntegrationService( profile, fake_drive_service_, test_cache_root_.path(), NULL); integration_service_->file_system()->AddObserver(this); return integration_service_; } private: base::ScopedTempDir test_cache_root_; google_apis::FakeDriveService* fake_drive_service_; drive::DriveIntegrationService* integration_service_; bool waiting_for_directory_change_; }; // The base test class. Used by FileManagerBrowserLocalTest, // FileManagerBrowserDriveTest, and FileManagerBrowserTransferTest. // The boolean parameter, retrieved by GetParam(), is true if testing in the // guest mode. See SetUpCommandLine() below for details. class FileManagerBrowserTestBase : public ExtensionApiTest, public ::testing::WithParamInterface<bool> { protected: // Adds an incognito and guest-mode flags for tests in the guest mode. virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE; // Loads our testing extension and sends it a string identifying the current // test. void StartTest(const std::string& test_name); // Creates test files and directories. void CreateTestEntries(TestVolume* volume, const TestEntryInfo* entries, size_t num_entries); // After starting the test, set up volumes. virtual void PrepareVolume() = 0; // Runs the file display test on the passed |volume|, shared by subclasses. void DoTestFileDisplay(TestVolume* volume); // Runs the gallery open test on the passed |volume|, shared by subclasses. void DoTestGalleryOpen(TestVolume* volume); // Runs the keyboard copy test on the passed |volume|, shared by subclasses. void DoTestKeyboardCopy(TestVolume* volume); // Runs the keyboard delete test on the passed |volume|, shared by subclasses. void DoTestKeyboardDelete(TestVolume* volume); }; void FileManagerBrowserTestBase::SetUpCommandLine(CommandLine* command_line) { bool in_guest_mode = GetParam(); if (in_guest_mode) { command_line->AppendSwitch(chromeos::switches::kGuestSession); command_line->AppendSwitchNative(chromeos::switches::kLoginUser, ""); command_line->AppendSwitch(switches::kIncognito); } ExtensionApiTest::SetUpCommandLine(command_line); } void FileManagerBrowserTestBase::StartTest(const std::string& test_name) { base::FilePath path = test_data_dir_.AppendASCII("file_manager_browsertest"); const extensions::Extension* extension = LoadExtensionAsComponent(path); ASSERT_TRUE(extension); bool in_guest_mode = GetParam(); ExtensionTestMessageListener listener( in_guest_mode ? "which test guest" : "which test non-guest", true); ASSERT_TRUE(listener.WaitUntilSatisfied()); listener.Reply(test_name); } void FileManagerBrowserTestBase::CreateTestEntries( TestVolume* volume, const TestEntryInfo* entries, size_t num_entries) { for (size_t i = 0; i < num_entries; ++i) { volume->CreateEntry(entries[i]); } } void FileManagerBrowserTestBase::DoTestFileDisplay(TestVolume* volume) { ResultCatcher catcher; StartTest("fileDisplay" + volume->GetName()); ExtensionTestMessageListener listener("initial check done", true); ASSERT_TRUE(listener.WaitUntilSatisfied()); const TestEntryInfo entry = { FILE, "music.ogg", // Prototype file name. "newly added file.ogg", // Target file name. "audio/ogg", NONE, "4 Sep 1998 00:00:00" }; volume->CreateEntry(entry); listener.Reply("file added"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } void FileManagerBrowserTestBase::DoTestGalleryOpen(TestVolume* volume) { ResultCatcher catcher; StartTest("galleryOpen" + volume->GetName()); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } void FileManagerBrowserTestBase::DoTestKeyboardCopy(TestVolume* volume) { base::FilePath copy_path = volume->GetRootPath().AppendASCII(kKeyboardTestFileCopyName); ASSERT_FALSE(volume->PathExists(copy_path)); ResultCatcher catcher; StartTest("keyboardCopy" + volume->GetName()); const int64 kKeyboardTestFileSize = 59943; ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(volume->WaitUntilFilePresentWithSize( copy_path, kKeyboardTestFileSize)); // Check that it was a copy, not a move. base::FilePath source_path = volume->GetRootPath().AppendASCII(kKeyboardTestFileName); ASSERT_TRUE(volume->PathExists(source_path)); } void FileManagerBrowserTestBase::DoTestKeyboardDelete(TestVolume* volume) { base::FilePath delete_path = volume->GetRootPath().AppendASCII(kKeyboardTestFileName); ASSERT_TRUE(volume->PathExists(delete_path)); ResultCatcher catcher; StartTest("keyboardDelete" + volume->GetName()); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(volume->WaitUntilFileNotPresent(delete_path)); } // A class to test local volumes. class FileManagerBrowserLocalTest : public FileManagerBrowserTestBase { public: FileManagerBrowserLocalTest() : volume_("Downloads") {} virtual void SetUp() OVERRIDE { extensions::ComponentLoader::EnableBackgroundExtensionsForTesting(); ExtensionApiTest::SetUp(); } protected: virtual void PrepareVolume() OVERRIDE { ASSERT_TRUE(volume_.Mount(browser()->profile())); CreateTestEntries(&volume_, kTestEntrySetCommon, arraysize(kTestEntrySetCommon)); } LocalTestVolume volume_; }; INSTANTIATE_TEST_CASE_P(InGuestMode, FileManagerBrowserLocalTest, ::testing::Values(true)); INSTANTIATE_TEST_CASE_P(InNonGuestMode, FileManagerBrowserLocalTest, ::testing::Values(false)); // A class to test Drive's volumes class FileManagerBrowserDriveTest : public FileManagerBrowserTestBase { public: virtual void SetUp() OVERRIDE { extensions::ComponentLoader::EnableBackgroundExtensionsForTesting(); ASSERT_TRUE(volume_.SetUp()); ExtensionApiTest::SetUp(); } virtual void TearDown() OVERRIDE { // The system service should be deleted by the time this function is // called hence no need to call RemoveObserver(). } protected: virtual void PrepareVolume() OVERRIDE { CreateTestEntries(&volume_, kTestEntrySetCommon, arraysize(kTestEntrySetCommon)); // For testing Drive, create more entries with Drive specific attributes. // TODO(haruki): Add a case for an entry cached by DriveCache. CreateTestEntries(&volume_, kTestEntrySetDriveOnly, arraysize(kTestEntrySetDriveOnly)); drive_test_util::WaitUntilDriveMountPointIsAdded(browser()->profile()); } DriveTestVolume volume_; }; // Don't test Drive in the guest mode as it's not supported. INSTANTIATE_TEST_CASE_P(InNonGuestMode, FileManagerBrowserDriveTest, ::testing::Values(false)); // A class to test both local and Drive's volumes. class FileManagerBrowserTransferTest : public FileManagerBrowserTestBase { public: FileManagerBrowserTransferTest() : local_volume_("Downloads") {} virtual void SetUp() OVERRIDE { extensions::ComponentLoader::EnableBackgroundExtensionsForTesting(); ASSERT_TRUE(drive_volume_.SetUp()); ExtensionApiTest::SetUp(); } protected: virtual void PrepareVolume() OVERRIDE { ASSERT_TRUE(local_volume_.Mount(browser()->profile())); CreateTestEntries(&local_volume_, kTestEntrySetCommon, arraysize(kTestEntrySetCommon)); CreateTestEntries(&drive_volume_, kTestEntrySetCommon, arraysize(kTestEntrySetCommon)); CreateTestEntries(&drive_volume_, kTestEntrySetDriveOnly, arraysize(kTestEntrySetDriveOnly)); drive_test_util::WaitUntilDriveMountPointIsAdded(browser()->profile()); } LocalTestVolume local_volume_; DriveTestVolume drive_volume_; }; // FileManagerBrowserTransferTest depends on Drive and Drive is not supported in // the guest mode. INSTANTIATE_TEST_CASE_P(InNonGuestMode, FileManagerBrowserTransferTest, ::testing::Values(false)); IN_PROC_BROWSER_TEST_P(FileManagerBrowserLocalTest, TestFileDisplay) { PrepareVolume(); DoTestFileDisplay(&volume_); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserLocalTest, TestGalleryOpen) { PrepareVolume(); DoTestGalleryOpen(&volume_); } // Disabled temporarily since fails on Linux Chromium OS ASAN Tests (2). // TODO(mtomasz): crbug.com/243611. IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, DISABLED_TestGalleryOpen) { PrepareVolume(); DoTestGalleryOpen(&volume_); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, TestKeyboardCopy) { PrepareVolume(); DoTestKeyboardCopy(&volume_); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, TestKeyboardDelete) { PrepareVolume(); DoTestKeyboardDelete(&volume_); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, TestOpenRecent) { PrepareVolume(); ResultCatcher catcher; StartTest("openSidebarRecent"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } // TODO(hirono): Bring back the offline feature. http://crbug.com/238545 IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, DISABLED_TestOpenOffline) { PrepareVolume(); ResultCatcher catcher; StartTest("openSidebarOffline"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, TestOpenSharedWithMe) { PrepareVolume(); ResultCatcher catcher; StartTest("openSidebarSharedWithMe"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, TestAutocomplete) { PrepareVolume(); ResultCatcher catcher; StartTest("autocomplete"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromDriveToDownloads) { PrepareVolume(); ResultCatcher catcher; StartTest("transferFromDriveToDownloads"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromDownloadsToDrive) { PrepareVolume(); ResultCatcher catcher; StartTest("transferFromDownloadsToDrive"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromSharedToDownloads) { PrepareVolume(); ResultCatcher catcher; StartTest("transferFromSharedToDownloads"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromSharedToDrive) { PrepareVolume(); ResultCatcher catcher; StartTest("transferFromSharedToDrive"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromRecentToDownloads) { PrepareVolume(); ResultCatcher catcher; StartTest("transferFromRecentToDownloads"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromRecentToDrive) { PrepareVolume(); ResultCatcher catcher; StartTest("transferFromRecentToDrive"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } // TODO(hirono): Bring back the offline feature. http://crbug.com/238545 IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, DISABLED_TransferFromOfflineToDownloads) { PrepareVolume(); ResultCatcher catcher; StartTest("transferFromOfflineToDownloads"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } // TODO(hirono): Bring back the offline feature. http://crbug.com/238545 IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, DISABLED_TransferFromOfflineToDrive) { PrepareVolume(); ResultCatcher catcher; StartTest("transferFromOfflineToDrive"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } } // namespace Break test cases on inner asserts. We were calling asserts withing a subroutines. In that case, asserts breaks the current subroutine but not the test case. This patch wraps calls to subroutines with ASSERT_NO_FATAL_FAILURE, which checks if it failed on any asserts, and if so, then terminates the test case. TEST=browser_tests BUG=235334 Review URL: https://chromiumcodereview.appspot.com/15771005 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@202010 0039d316-1c4b-4281-b951-d872f2087c98 // Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Browser test for basic Chrome OS file manager functionality: // - The file list is updated when a file is added externally to the Downloads // folder. // - Selecting a file and copy-pasting it with the keyboard copies the file. // - Selecting a file and pressing delete deletes it. #include <algorithm> #include <string> #include "base/callback.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/files/file_path_watcher.h" #include "base/platform_file.h" #include "base/threading/platform_thread.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/chromeos/drive/drive_integration_service.h" #include "chrome/browser/chromeos/drive/file_system.h" #include "chrome/browser/chromeos/drive/file_system_observer.h" #include "chrome/browser/chromeos/extensions/file_manager/drive_test_util.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/google_apis/fake_drive_service.h" #include "chrome/browser/google_apis/gdata_wapi_parser.h" #include "chrome/browser/google_apis/test_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/test/base/ui_test_utils.h" #include "chromeos/chromeos_switches.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_view_host.h" #include "net/base/escape.h" #include "webkit/fileapi/external_mount_points.h" namespace { const char kKeyboardTestFileName[] = "world.ogv"; const char kKeyboardTestFileCopyName[] = "world (1).ogv"; // Test suffixes appended to the Javascript tests' names. const char kDownloadsVolume[] = "Downloads"; const char kDriveVolume[] = "Drive"; enum EntryType { FILE, DIRECTORY, }; enum SharedOption { NONE, SHARED, }; struct TestEntryInfo { EntryType type; const char* source_file_name; // Source file name to be used as a prototype. const char* target_name; // Target file or directory name. const char* mime_type; SharedOption shared_option; const char* last_modified_time_as_string; }; TestEntryInfo kTestEntrySetCommon[] = { { FILE, "text.txt", "hello.txt", "text/plain", NONE, "4 Sep 1998 12:34:56" }, { FILE, "image.png", "My Desktop Background.png", "text/plain", NONE, "18 Jan 2038 01:02:03" }, { FILE, "video.ogv", kKeyboardTestFileName, "text/plain", NONE, "4 July 2012 10:35:00" }, { DIRECTORY, "", "photos", NULL, NONE, "1 Jan 1980 23:59:59" }, { DIRECTORY, "", ".warez", NULL, NONE, "26 Oct 1985 13:39" } }; TestEntryInfo kTestEntrySetDriveOnly[] = { { FILE, "", "Test Document", "application/vnd.google-apps.document", NONE, "10 Apr 2013 16:20:00" }, { FILE, "", "Test Shared Document", "application/vnd.google-apps.document", SHARED, "20 Mar 2013 22:40:00" } }; // Monitors changes to a single file until the supplied condition callback // returns true. Usage: // TestFilePathWatcher watcher(path_to_file, MyConditionCallback); // watcher.StartAndWaitUntilReady(); // ... trigger filesystem modification ... // watcher.RunMessageLoopUntilConditionSatisfied(); class TestFilePathWatcher { public: typedef base::Callback<bool(const base::FilePath& file_path)> ConditionCallback; // Stores the supplied |path| and |condition| for later use (no side effects). TestFilePathWatcher(const base::FilePath& path, const ConditionCallback& condition); // Waits (running a message pump) until the callback returns true or // FilePathWatcher reports an error. Return true on success. bool RunMessageLoopUntilConditionSatisfied(); private: // Starts the FilePathWatcher to watch the target file. Also check if the // condition is already met. void StartWatching(); // FilePathWatcher callback (on the FILE thread). Posts Done() to the UI // thread when the condition is satisfied or there is an error. void FilePathWatcherCallback(const base::FilePath& path, bool error); const base::FilePath path_; ConditionCallback condition_; scoped_ptr<base::FilePathWatcher> watcher_; base::RunLoop run_loop_; base::Closure quit_closure_; bool failed_; }; TestFilePathWatcher::TestFilePathWatcher(const base::FilePath& path, const ConditionCallback& condition) : path_(path), condition_(condition), quit_closure_(run_loop_.QuitClosure()), failed_(false) { } void TestFilePathWatcher::StartWatching() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); watcher_.reset(new base::FilePathWatcher); failed_ = !watcher_->Watch( path_, false /*recursive*/, base::Bind(&TestFilePathWatcher::FilePathWatcherCallback, base::Unretained(this))); // If failed to start the watcher, then quit the message loop immediately. // Also, if the condition was already met before FilePathWatcher was launched, // FilePathWatcher won't be able to detect a change, so check the condition // here. if (failed_ || condition_.Run(path_)) { watcher_.reset(); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, quit_closure_); return; } } void TestFilePathWatcher::FilePathWatcherCallback(const base::FilePath& path, bool failed) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); DCHECK_EQ(path_.value(), path.value()); if (failed || condition_.Run(path)) { failed_ = failed; watcher_.reset(); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, quit_closure_); } } bool TestFilePathWatcher::RunMessageLoopUntilConditionSatisfied() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&TestFilePathWatcher::StartWatching, base::Unretained(this))); // Wait until the condition is met. run_loop_.Run(); return !failed_; } // Returns true if a file with the given size is present at |path|. bool FilePresentWithSize(const int64 file_size, const base::FilePath& path) { int64 copy_size = 0; // If the file doesn't exist yet this will fail and we'll keep waiting. if (!file_util::GetFileSize(path, &copy_size)) return false; return (copy_size == file_size); } // Returns true if a file is not present at |path|. bool FileNotPresent(const base::FilePath& path) { return !file_util::PathExists(path); }; // The base class of volumes for test. // Sub-classes of this class are used by test cases and provide operations such // as creating files for each type of test volume. class TestVolume { public: virtual ~TestVolume() {} // Creates an entry with given information. virtual void CreateEntry(const TestEntryInfo& entry) = 0; // Returns the path of the root directory. virtual base::FilePath GetRootPath() const = 0; // Returns true if |file_path| exists. virtual bool PathExists(const base::FilePath& file_path) const = 0; // Returns the name of volume such as "Downloads" or "Drive". virtual std::string GetName() const = 0; // Waits until a file with the given size is present at |path|. Returns // true on success. virtual bool WaitUntilFilePresentWithSize(const base::FilePath& file_path, int64 file_size) = 0; // Waits until a file is not present at |path|. Returns true on success. virtual bool WaitUntilFileNotPresent(const base::FilePath& file_path) = 0; }; // The local volume class for test. // This class provides the operations for a test volume that simulates local // drive. class LocalTestVolume : public TestVolume { public: explicit LocalTestVolume(const std::string& mount_name) : mount_name_(mount_name) { } LocalTestVolume(const std::string& mount_name, const base::FilePath& local_path) : mount_name_(mount_name), local_path_(local_path) { } // Adds this volume to the file system as a local volume. Returns true on // success. bool Mount(Profile* profile) { if (local_path_.empty()) { if (!tmp_dir_.CreateUniqueTempDir()) return false; local_path_ = tmp_dir_.path().Append(mount_name_); } fileapi::ExternalMountPoints* const mount_points = content::BrowserContext::GetMountPoints(profile); mount_points->RevokeFileSystem(mount_name_); if (!mount_points->RegisterFileSystem( mount_name_, fileapi::kFileSystemTypeNativeLocal, local_path_)) { return false; } if (!file_util::CreateDirectory(local_path_)) return false; return true; } virtual void CreateEntry(const TestEntryInfo& entry) OVERRIDE { if (entry.type == DIRECTORY) { CreateDirectory(entry.target_name , entry.last_modified_time_as_string); } else if (entry.type == FILE) { CreateFile(entry.source_file_name, entry.target_name, entry.last_modified_time_as_string); } else { NOTREACHED(); } } void CreateFile(const std::string& source_file_name, const std::string& target_name, const std::string& modification_time) { std::string content_data; base::FilePath test_file_path = google_apis::test_util::GetTestFilePath("chromeos/file_manager"). AppendASCII(source_file_name); base::FilePath path = local_path_.AppendASCII(target_name); ASSERT_TRUE(file_util::PathExists(test_file_path)) << "Test file doesn't exist: " << test_file_path.value(); ASSERT_TRUE(file_util::CopyFile(test_file_path, path)); ASSERT_TRUE(file_util::PathExists(path)) << "Copying to: " << path.value() << " failed."; base::Time time; ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time)); ASSERT_TRUE(file_util::SetLastModifiedTime(path, time)); } void CreateDirectory(const std::string& target_name, const std::string& modification_time) { base::FilePath path = local_path_.AppendASCII(target_name); ASSERT_TRUE(file_util::CreateDirectory(path)) << "Failed to create a directory: " << target_name; base::Time time; ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time)); ASSERT_TRUE(file_util::SetLastModifiedTime(path, time)); } virtual std::string GetName() const OVERRIDE { return mount_name_; } virtual base::FilePath GetRootPath() const OVERRIDE { return local_path_; } virtual bool PathExists(const base::FilePath& file_path) const OVERRIDE { return file_util::PathExists(file_path); } virtual bool WaitUntilFilePresentWithSize( const base::FilePath& file_path, int64 file_size) OVERRIDE { TestFilePathWatcher watcher(file_path, base::Bind(FilePresentWithSize, file_size)); return watcher.RunMessageLoopUntilConditionSatisfied(); } virtual bool WaitUntilFileNotPresent( const base::FilePath& file_path) OVERRIDE { TestFilePathWatcher watcher(file_path, base::Bind(FileNotPresent)); return watcher.RunMessageLoopUntilConditionSatisfied(); } private: std::string mount_name_; base::FilePath local_path_; base::ScopedTempDir tmp_dir_; }; // The drive volume class for test. // This class provides the operations for a test volume that simulates Google // drive. class DriveTestVolume : public TestVolume, public drive::FileSystemObserver { public: DriveTestVolume() : fake_drive_service_(NULL), integration_service_(NULL), waiting_for_directory_change_(false) { } // Send request to add this volume to the file system as Google drive. // This method must be calld at SetUp method of FileManagerBrowserTestBase. // Returns true on success. bool SetUp() { if (!test_cache_root_.CreateUniqueTempDir()) return false; drive::DriveIntegrationServiceFactory::SetFactoryForTest( base::Bind(&DriveTestVolume::CreateDriveIntegrationService, base::Unretained(this))); return true; } virtual void CreateEntry(const TestEntryInfo& entry) OVERRIDE { if (entry.type == DIRECTORY) { CreateDirectory(entry.target_name, entry.last_modified_time_as_string); } else if (entry.type == FILE) { CreateFile(entry.source_file_name, entry.target_name, entry.mime_type, entry.shared_option == SHARED, entry.last_modified_time_as_string); } else { NOTREACHED(); } } // Creates an empty directory with the given |name| and |modification_time|. void CreateDirectory(const std::string& name, const std::string& modification_time) { google_apis::GDataErrorCode error = google_apis::GDATA_OTHER_ERROR; scoped_ptr<google_apis::ResourceEntry> resource_entry; fake_drive_service_->AddNewDirectory( fake_drive_service_->GetRootResourceId(), name, google_apis::test_util::CreateCopyResultCallback(&error, &resource_entry)); MessageLoop::current()->RunUntilIdle(); ASSERT_TRUE(error == google_apis::HTTP_CREATED); ASSERT_TRUE(resource_entry); base::Time time; ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time)); fake_drive_service_->SetLastModifiedTime( resource_entry->resource_id(), time, google_apis::test_util::CreateCopyResultCallback(&error, &resource_entry)); MessageLoop::current()->RunUntilIdle(); ASSERT_TRUE(error == google_apis::HTTP_SUCCESS); ASSERT_TRUE(resource_entry); CheckForUpdates(); } virtual std::string GetName() const OVERRIDE { return "Drive"; } // Creates a test file with the given spec. // Serves |test_file_name| file. Pass an empty string for an empty file. void CreateFile(const std::string& source_file_name, const std::string& target_file_name, const std::string& mime_type, bool shared_with_me, const std::string& modification_time) { google_apis::GDataErrorCode error = google_apis::GDATA_OTHER_ERROR; std::string content_data; if (!source_file_name.empty()) { base::FilePath source_file_path = google_apis::test_util::GetTestFilePath("chromeos/file_manager"). AppendASCII(source_file_name); ASSERT_TRUE(file_util::ReadFileToString(source_file_path, &content_data)); } scoped_ptr<google_apis::ResourceEntry> resource_entry; fake_drive_service_->AddNewFile( mime_type, content_data, fake_drive_service_->GetRootResourceId(), target_file_name, shared_with_me, google_apis::test_util::CreateCopyResultCallback(&error, &resource_entry)); MessageLoop::current()->RunUntilIdle(); ASSERT_EQ(google_apis::HTTP_CREATED, error); ASSERT_TRUE(resource_entry); base::Time time; ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time)); fake_drive_service_->SetLastModifiedTime( resource_entry->resource_id(), time, google_apis::test_util::CreateCopyResultCallback(&error, &resource_entry)); MessageLoop::current()->RunUntilIdle(); ASSERT_EQ(google_apis::HTTP_SUCCESS, error); ASSERT_TRUE(resource_entry); CheckForUpdates(); } virtual base::FilePath GetRootPath() const OVERRIDE { return base::FilePath(drive::util::kDriveMyDriveRootPath); } virtual bool PathExists(const base::FilePath& file_path) const OVERRIDE { DCHECK(integration_service_); DCHECK(integration_service_->file_system()); drive::FileError error = drive::FILE_ERROR_FAILED; scoped_ptr<drive::ResourceEntry> entry_proto; integration_service_->file_system()->GetResourceEntryByPath( file_path, google_apis::test_util::CreateCopyResultCallback(&error, &entry_proto)); google_apis::test_util::RunBlockingPoolTask(); return error == drive::FILE_ERROR_OK; } virtual bool WaitUntilFilePresentWithSize( const base::FilePath& file_path, int64 file_size) OVERRIDE { while (true) { if (FileIsPresentWithSize(file_path, file_size)) return true; WaitUntilDirectoryChanged(); } NOTREACHED(); return false; } virtual bool WaitUntilFileNotPresent( const base::FilePath& file_path) OVERRIDE { while (true) { if (FileIsNotPresent(file_path)) return true; WaitUntilDirectoryChanged(); } NOTREACHED(); return false; } virtual void OnDirectoryChanged( const base::FilePath& directory_path) OVERRIDE { if (waiting_for_directory_change_) MessageLoop::current()->Quit(); } // Notifies FileSystem that the contents in FakeDriveService are // changed, hence the new contents should be fetched. void CheckForUpdates() { if (integration_service_ && integration_service_->file_system()) { integration_service_->file_system()->CheckForUpdates(); } } // Waits until a notification for a directory change is received. void WaitUntilDirectoryChanged() { waiting_for_directory_change_ = true; MessageLoop::current()->Run(); waiting_for_directory_change_ = false; } // Returns true if a file of the size |file_size| is present at |file_path|. bool FileIsPresentWithSize( const base::FilePath& file_path, int64 file_size) { DCHECK(integration_service_); DCHECK(integration_service_->file_system()); drive::FileError error = drive::FILE_ERROR_FAILED; scoped_ptr<drive::ResourceEntry> entry_proto; integration_service_->file_system()->GetResourceEntryByPath( file_path, google_apis::test_util::CreateCopyResultCallback(&error, &entry_proto)); google_apis::test_util::RunBlockingPoolTask(); return (error == drive::FILE_ERROR_OK && entry_proto->file_info().size() == file_size); } // Returns true if a file is not present at |file_path|. bool FileIsNotPresent( const base::FilePath& file_path) { DCHECK(integration_service_); DCHECK(integration_service_->file_system()); drive::FileError error = drive::FILE_ERROR_FAILED; scoped_ptr<drive::ResourceEntry> entry_proto; integration_service_->file_system()->GetResourceEntryByPath( file_path, google_apis::test_util::CreateCopyResultCallback(&error, &entry_proto)); google_apis::test_util::RunBlockingPoolTask(); return error == drive::FILE_ERROR_NOT_FOUND; } drive::DriveIntegrationService* CreateDriveIntegrationService( Profile* profile) { fake_drive_service_ = new google_apis::FakeDriveService; fake_drive_service_->LoadResourceListForWapi( "chromeos/gdata/empty_feed.json"); fake_drive_service_->LoadAccountMetadataForWapi( "chromeos/gdata/account_metadata.json"); fake_drive_service_->LoadAppListForDriveApi("chromeos/drive/applist.json"); integration_service_ = new drive::DriveIntegrationService( profile, fake_drive_service_, test_cache_root_.path(), NULL); integration_service_->file_system()->AddObserver(this); return integration_service_; } private: base::ScopedTempDir test_cache_root_; google_apis::FakeDriveService* fake_drive_service_; drive::DriveIntegrationService* integration_service_; bool waiting_for_directory_change_; }; // The base test class. Used by FileManagerBrowserLocalTest, // FileManagerBrowserDriveTest, and FileManagerBrowserTransferTest. // The boolean parameter, retrieved by GetParam(), is true if testing in the // guest mode. See SetUpCommandLine() below for details. class FileManagerBrowserTestBase : public ExtensionApiTest, public ::testing::WithParamInterface<bool> { protected: // Adds an incognito and guest-mode flags for tests in the guest mode. virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE; // Loads our testing extension and sends it a string identifying the current // test. void StartTest(const std::string& test_name); // Creates test files and directories. void CreateTestEntries(TestVolume* volume, const TestEntryInfo* entries, size_t num_entries); // After starting the test, set up volumes. virtual void PrepareVolume() = 0; // Runs the file display test on the passed |volume|, shared by subclasses. void DoTestFileDisplay(TestVolume* volume); // Runs the gallery open test on the passed |volume|, shared by subclasses. void DoTestGalleryOpen(TestVolume* volume); // Runs the keyboard copy test on the passed |volume|, shared by subclasses. void DoTestKeyboardCopy(TestVolume* volume); // Runs the keyboard delete test on the passed |volume|, shared by subclasses. void DoTestKeyboardDelete(TestVolume* volume); }; void FileManagerBrowserTestBase::SetUpCommandLine(CommandLine* command_line) { bool in_guest_mode = GetParam(); if (in_guest_mode) { command_line->AppendSwitch(chromeos::switches::kGuestSession); command_line->AppendSwitchNative(chromeos::switches::kLoginUser, ""); command_line->AppendSwitch(switches::kIncognito); } ExtensionApiTest::SetUpCommandLine(command_line); } void FileManagerBrowserTestBase::StartTest(const std::string& test_name) { base::FilePath path = test_data_dir_.AppendASCII("file_manager_browsertest"); const extensions::Extension* extension = LoadExtensionAsComponent(path); ASSERT_TRUE(extension); bool in_guest_mode = GetParam(); ExtensionTestMessageListener listener( in_guest_mode ? "which test guest" : "which test non-guest", true); ASSERT_TRUE(listener.WaitUntilSatisfied()); listener.Reply(test_name); } void FileManagerBrowserTestBase::CreateTestEntries( TestVolume* volume, const TestEntryInfo* entries, size_t num_entries) { for (size_t i = 0; i < num_entries; ++i) { volume->CreateEntry(entries[i]); } } void FileManagerBrowserTestBase::DoTestFileDisplay(TestVolume* volume) { ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("fileDisplay" + volume->GetName())); ExtensionTestMessageListener listener("initial check done", true); ASSERT_TRUE(listener.WaitUntilSatisfied()); const TestEntryInfo entry = { FILE, "music.ogg", // Prototype file name. "newly added file.ogg", // Target file name. "audio/ogg", NONE, "4 Sep 1998 00:00:00" }; volume->CreateEntry(entry); listener.Reply("file added"); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } void FileManagerBrowserTestBase::DoTestGalleryOpen(TestVolume* volume) { ResultCatcher catcher; StartTest("galleryOpen" + volume->GetName()); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } void FileManagerBrowserTestBase::DoTestKeyboardCopy(TestVolume* volume) { base::FilePath copy_path = volume->GetRootPath().AppendASCII(kKeyboardTestFileCopyName); ASSERT_FALSE(volume->PathExists(copy_path)); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("keyboardCopy" + volume->GetName())); const int64 kKeyboardTestFileSize = 59943; ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(volume->WaitUntilFilePresentWithSize( copy_path, kKeyboardTestFileSize)); // Check that it was a copy, not a move. base::FilePath source_path = volume->GetRootPath().AppendASCII(kKeyboardTestFileName); ASSERT_TRUE(volume->PathExists(source_path)); } void FileManagerBrowserTestBase::DoTestKeyboardDelete(TestVolume* volume) { base::FilePath delete_path = volume->GetRootPath().AppendASCII(kKeyboardTestFileName); ASSERT_TRUE(volume->PathExists(delete_path)); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("keyboardDelete" + volume->GetName())); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); ASSERT_TRUE(volume->WaitUntilFileNotPresent(delete_path)); } // A class to test local volumes. class FileManagerBrowserLocalTest : public FileManagerBrowserTestBase { public: FileManagerBrowserLocalTest() : volume_("Downloads") {} virtual void SetUp() OVERRIDE { extensions::ComponentLoader::EnableBackgroundExtensionsForTesting(); ExtensionApiTest::SetUp(); } protected: virtual void PrepareVolume() OVERRIDE { ASSERT_TRUE(volume_.Mount(browser()->profile())); CreateTestEntries(&volume_, kTestEntrySetCommon, arraysize(kTestEntrySetCommon)); } LocalTestVolume volume_; }; INSTANTIATE_TEST_CASE_P(InGuestMode, FileManagerBrowserLocalTest, ::testing::Values(true)); INSTANTIATE_TEST_CASE_P(InNonGuestMode, FileManagerBrowserLocalTest, ::testing::Values(false)); // A class to test Drive's volumes class FileManagerBrowserDriveTest : public FileManagerBrowserTestBase { public: virtual void SetUp() OVERRIDE { extensions::ComponentLoader::EnableBackgroundExtensionsForTesting(); ASSERT_TRUE(volume_.SetUp()); ExtensionApiTest::SetUp(); } virtual void TearDown() OVERRIDE { // The system service should be deleted by the time this function is // called hence no need to call RemoveObserver(). } protected: virtual void PrepareVolume() OVERRIDE { CreateTestEntries(&volume_, kTestEntrySetCommon, arraysize(kTestEntrySetCommon)); // For testing Drive, create more entries with Drive specific attributes. // TODO(haruki): Add a case for an entry cached by DriveCache. CreateTestEntries(&volume_, kTestEntrySetDriveOnly, arraysize(kTestEntrySetDriveOnly)); drive_test_util::WaitUntilDriveMountPointIsAdded(browser()->profile()); } DriveTestVolume volume_; }; // Don't test Drive in the guest mode as it's not supported. INSTANTIATE_TEST_CASE_P(InNonGuestMode, FileManagerBrowserDriveTest, ::testing::Values(false)); // A class to test both local and Drive's volumes. class FileManagerBrowserTransferTest : public FileManagerBrowserTestBase { public: FileManagerBrowserTransferTest() : local_volume_("Downloads") {} virtual void SetUp() OVERRIDE { extensions::ComponentLoader::EnableBackgroundExtensionsForTesting(); ASSERT_TRUE(drive_volume_.SetUp()); ExtensionApiTest::SetUp(); } protected: virtual void PrepareVolume() OVERRIDE { ASSERT_TRUE(local_volume_.Mount(browser()->profile())); CreateTestEntries(&local_volume_, kTestEntrySetCommon, arraysize(kTestEntrySetCommon)); CreateTestEntries(&drive_volume_, kTestEntrySetCommon, arraysize(kTestEntrySetCommon)); CreateTestEntries(&drive_volume_, kTestEntrySetDriveOnly, arraysize(kTestEntrySetDriveOnly)); drive_test_util::WaitUntilDriveMountPointIsAdded(browser()->profile()); } LocalTestVolume local_volume_; DriveTestVolume drive_volume_; }; // FileManagerBrowserTransferTest depends on Drive and Drive is not supported in // the guest mode. INSTANTIATE_TEST_CASE_P(InNonGuestMode, FileManagerBrowserTransferTest, ::testing::Values(false)); IN_PROC_BROWSER_TEST_P(FileManagerBrowserLocalTest, TestFileDisplay) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); DoTestFileDisplay(&volume_); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserLocalTest, TestGalleryOpen) { PrepareVolume(); DoTestGalleryOpen(&volume_); } // Disabled temporarily since fails on Linux Chromium OS ASAN Tests (2). // TODO(mtomasz): crbug.com/243611. IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, DISABLED_TestGalleryOpen) { PrepareVolume(); DoTestGalleryOpen(&volume_); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, TestKeyboardCopy) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); DoTestKeyboardCopy(&volume_); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, TestKeyboardDelete) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); DoTestKeyboardDelete(&volume_); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, TestOpenRecent) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("openSidebarRecent")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } // TODO(hirono): Bring back the offline feature. http://crbug.com/238545 IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, DISABLED_TestOpenOffline) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("openSidebarOffline")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, TestOpenSharedWithMe) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("openSidebarSharedWithMe")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserDriveTest, TestAutocomplete) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("autocomplete")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromDriveToDownloads) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE( StartTest("transferFromDriveToDownloads")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromDownloadsToDrive) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE( StartTest("transferFromDownloadsToDrive")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromSharedToDownloads) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("transferFromSharedToDownloads")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromSharedToDrive) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("transferFromSharedToDrive")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromRecentToDownloads) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("transferFromRecentToDownloads")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, TransferFromRecentToDrive) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("transferFromRecentToDrive")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } // TODO(hirono): Bring back the offline feature. http://crbug.com/238545 IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, DISABLED_TransferFromOfflineToDownloads) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("transferFromOfflineToDownloads")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } // TODO(hirono): Bring back the offline feature. http://crbug.com/238545 IN_PROC_BROWSER_TEST_P(FileManagerBrowserTransferTest, DISABLED_TransferFromOfflineToDrive) { ASSERT_NO_FATAL_FAILURE(PrepareVolume()); ResultCatcher catcher; ASSERT_NO_FATAL_FAILURE(StartTest("transferFromOfflineToDrive")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } } // namespace
// ========================================================================== // Barebones OpenGL Core Profile Boilerplate // using the GLFW windowing system (http://www.glfw.org) // // Loosely based on // - Chris Wellons' example (https://github.com/skeeto/opengl-demo) and // - Camilla Berglund's example (http://www.glfw.org/docs/latest/quick.html) // // Author: Sonny Chan, University of Calgary // Date: December 2015 // ========================================================================== #include <iostream> #include <fstream> #include <string> #include <iterator> #include <algorithm> // specify that we want the OpenGL core profile before including GLFW headers #define GLFW_INCLUDE_GLCOREARB #define GL_GLEXT_PROTOTYPES #include <GLFW/glfw3.h> #include <Magick++.h> using namespace std; // -------------------------------------------------------------------------- // OpenGL utility and support function prototypes void QueryGLVersion(); bool CheckGLErrors(); string LoadSource(const string &filename); GLuint CompileShader(GLenum shaderType, const string &source); GLuint LinkProgram(GLuint vertexShader, GLuint fragmentShader); // ========================================================================== // ========================================================================== // Image File Reading Support Functions // - requires the Magick++ development libraries: http://www.imagemagick.org // // Note: This file will not compile by itself! The snippets below are meant // to be added to the template application distributed for Assignment #1. // You may use this code (or not) however you see fit for your work. // // Author: Sonny Chan, University of Calgary // Date: January 2016 // ========================================================================== // -------------------------------------------------------------------------- // Functions to set up OpenGL objects for storing image data struct MyTexture { // OpenGL names for array buffer objects, vertex array object GLuint textureName; // dimensions of the image stored in this texture GLuint width, height; // initialize object names to zero (OpenGL reserved value) MyTexture() : textureName(0), width(0), height(0) {} }; // use the Magick++ library to load an image with a given file name into // an OpenGL rectangle texture bool InitializeTexture(MyTexture *texture, const string &imageFileName) { Magick::Image myImage; // try to read the provided image file try { myImage.read(imageFileName); } catch (Magick::Error &error) { cout << "Magick++ failed to read image " << imageFileName << endl; cout << "ERROR: " << error.what() << endl; return false; } // store the image width and height into the texture structure texture->width = myImage.columns(); texture->height = myImage.rows(); // create a Magick++ pixel cache from the image for direct access to data Magick::Pixels pixelCache(myImage); Magick::PixelPacket *pixels; pixels = pixelCache.get(0, 0, texture->width, texture->height); // determine the number of stored bytes per pixel channel in the cache GLenum channelDataType; switch (sizeof(Magick::Quantum)) { case 4: channelDataType = GL_UNSIGNED_INT; break; case 2: channelDataType = GL_UNSIGNED_SHORT; break; default: channelDataType = GL_UNSIGNED_BYTE; } // create a texture name to associate our image data with if (!texture->textureName) glGenTextures(1, &texture->textureName); // bind the texture as a "rectangle" to access using image pixel coordinates glBindTexture(GL_TEXTURE_RECTANGLE, texture->textureName); // send image pixel data to OpenGL texture memory glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGB, texture->width, texture->height, 0, GL_BGRA, channelDataType, pixels); // unbind this texture glBindTexture(GL_TEXTURE_RECTANGLE, 0); return !CheckGLErrors(); } // -------------------------------------------------------------------------- // Functions to set up OpenGL shader programs for rendering struct MyShader { // OpenGL names for vertex and fragment shaders, shader program GLuint vertex; GLuint fragment; GLuint program; // initialize shader and program names to zero (OpenGL reserved value) MyShader() : vertex(0), fragment(0), program(0) {} }; // load, compile, and link shaders, returning true if successful bool InitializeShaders(MyShader *shader) { // load shader source from files string vertexSource = LoadSource("vertex.glsl"); string fragmentSource = LoadSource("fragment.glsl"); if (vertexSource.empty() || fragmentSource.empty()) return false; // compile shader source into shader objects shader->vertex = CompileShader(GL_VERTEX_SHADER, vertexSource); shader->fragment = CompileShader(GL_FRAGMENT_SHADER, fragmentSource); // link shader program shader->program = LinkProgram(shader->vertex, shader->fragment); // check for OpenGL errors and return false if error occurred return !CheckGLErrors(); } // deallocate shader-related objects void DestroyShaders(MyShader *shader) { // unbind any shader programs and destroy shader objects glUseProgram(0); glDeleteProgram(shader->program); glDeleteShader(shader->vertex); glDeleteShader(shader->fragment); } // -------------------------------------------------------------------------- // Functions to set up OpenGL buffers for storing geometry data struct MyGeometry { // OpenGL names for array buffer objects, vertex array object GLuint vertexBuffer; GLuint colourBuffer; GLuint textureCoordBuffer; GLuint vertexArray; GLsizei elementCount; // initialize object names to zero (OpenGL reserved value) MyGeometry() : vertexBuffer(0), colourBuffer(0), vertexArray(0), elementCount(0) {} }; // create buffers and fill with geometry data, returning true if successful bool InitializeGeometry(MyGeometry *geometry, MyTexture *texture) { // three vertex positions and assocated colours of a triangle const GLfloat vertices[][2] = { { -0.6, -0.4 }, { 0.6, -0.4 }, { 0.0, 0.6 } }; const GLfloat colours[][3] = { { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 } }; //------------------- // Add array of texture coordinates //------------------- const GLuint textureCoords[][2] = { {0, texture->height}, {texture->width, texture->height}, {texture->width / 2.0, 0} }; geometry->elementCount = 3; // these vertex attribute indices correspond to those specified for the // input variables in the vertex shader const GLuint VERTEX_INDEX = 0; const GLuint COLOUR_INDEX = 1; const GLuint TEXTURE_INDEX = 2; //----------- // add texture index //----------- // create an array buffer object for storing our vertices glGenBuffers(1, &geometry->vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, geometry->vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // create another one for storing our colours glGenBuffers(1, &geometry->colourBuffer); glBindBuffer(GL_ARRAY_BUFFER, geometry->colourBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(colours), colours, GL_STATIC_DRAW); //------------------------- // generate bind and buffer texture coordinate data //------------------------- glGenBuffers(1, &geometry->textureCoordBuffer); glBindBuffer(GL_ARRAY_BUFFER, geometry->textureCoordBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(textureCoords), textureCoords, GL_STATIC_DRAW); // create a vertex array object encapsulating all our vertex attributes glGenVertexArrays(1, &geometry->vertexArray); glBindVertexArray(geometry->vertexArray); // associate the position array with the vertex array object glBindBuffer(GL_ARRAY_BUFFER, geometry->vertexBuffer); glVertexAttribPointer(VERTEX_INDEX, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(VERTEX_INDEX); // assocaite the colour array with the vertex array object glBindBuffer(GL_ARRAY_BUFFER, geometry->colourBuffer); glVertexAttribPointer(COLOUR_INDEX, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(COLOUR_INDEX); //----------------- // Set up vertex attribute info for textures //----------------- glBindBuffer(GL_ARRAY_BUFFER, geometry->textureCoordBuffer); glVertexAttribPointer(TEXTURE_INDEX, 2, GL_UNSIGNED_INT, GL_FALSE, 0, 0); glEnableVertexAttribArray(TEXTURE_INDEX); // unbind our buffers, resetting to default state glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // check for OpenGL errors and return false if error occurred return !CheckGLErrors(); } // deallocate geometry-related objects void DestroyGeometry(MyGeometry *geometry) { // unbind and destroy our vertex array object and associated buffers glBindVertexArray(0); glDeleteVertexArrays(1, &geometry->vertexArray); glDeleteBuffers(1, &geometry->vertexBuffer); glDeleteBuffers(1, &geometry->colourBuffer); } // -------------------------------------------------------------------------- // Rendering function that draws our scene to the frame buffer void RenderScene(MyGeometry *geometry, MyTexture* texture, MyShader *shader) { // clear screen to a dark grey colour glClearColor(0.2, 0.2, 0.2, 1.0); glClear(GL_COLOR_BUFFER_BIT); // bind our shader program and the vertex array object containing our // scene geometry, then tell OpenGL to draw our geometry glUseProgram(shader->program); glBindVertexArray(geometry->vertexArray); glBindTexture(GL_TEXTURE_RECTANGLE, texture->textureName); glDrawArrays(GL_TRIANGLES, 0, geometry->elementCount); // reset state to default (no shader or geometry bound) glBindTexture(GL_TEXTURE_RECTANGLE, 0); glBindVertexArray(0); glUseProgram(0); // check for an report any OpenGL errors CheckGLErrors(); } // -------------------------------------------------------------------------- // GLFW callback functions // reports GLFW errors void ErrorCallback(int error, const char* description) { cout << "GLFW ERROR " << error << ":" << endl; cout << description << endl; } // handles keyboard input events void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); } void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { if(button == GLFW_MOUSE_BUTTON_1) { cout << "left "; if(action == GLFW_PRESS) { cout << "pressed" << endl; } else if(action == GLFW_RELEASE) { cout << "released" << endl; } } } void mouseMoveCallback(GLFWwindow* window, double x, double y) { cout << "x " << x << " y " << y << endl; } // ========================================================================== // PROGRAM ENTRY POINT int main(int argc, char *argv[]) { Magick::InitializeMagick(NULL); // initialize the GLFW windowing system if (!glfwInit()) { cout << "ERROR: GLFW failed to initilize, TERMINATING" << endl; return -1; } glfwSetErrorCallback(ErrorCallback); // attempt to create a window with an OpenGL 4.1 core profile context GLFWwindow *window = 0; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(512, 512, "CPSC 453 OpenGL Boilerplate", 0, 0); if (!window) { cout << "Program failed to create GLFW window, TERMINATING" << endl; glfwTerminate(); return -1; } // set keyboard callback function and make our context current (active) glfwSetKeyCallback(window, KeyCallback); glfwSetMouseButtonCallback(window, mouseButtonCallback); glfwSetCursorPosCallback(window, mouseMoveCallback); glfwMakeContextCurrent(window); // set mouse call back functions // query and print out information about our OpenGL environment QueryGLVersion(); // call function to load and compile shader programs MyShader shader; if (!InitializeShaders(&shader)) { cout << "Program could not initialize shaders, TERMINATING" << endl; return -1; } // load and initialize the texture MyTexture texture; if(!InitializeTexture(&texture, "test.jpg")) cout << "Failed to load texture!" << endl; // call function to create and fill buffers with geometry data MyGeometry geometry; if (!InitializeGeometry(&geometry, &texture)) cout << "Program failed to intialize geometry!" << endl; // run an event-triggered main loop while (!glfwWindowShouldClose(window)) { // call function to draw our scene RenderScene(&geometry, &texture, &shader); // scene is rendered to the back buffer, so swap to front for display glfwSwapBuffers(window); // sleep until next event before drawing again glfwWaitEvents(); } // clean up allocated resources before exit DestroyGeometry(&geometry); DestroyShaders(&shader); glfwDestroyWindow(window); glfwTerminate(); cout << "Goodbye!" << endl; return 0; } // ========================================================================== // SUPPORT FUNCTION DEFINITIONS // -------------------------------------------------------------------------- // OpenGL utility functions void QueryGLVersion() { // query opengl version and renderer information string version = reinterpret_cast<const char *>(glGetString(GL_VERSION)); string glslver = reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION)); string renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER)); cout << "OpenGL [ " << version << " ] " << "with GLSL [ " << glslver << " ] " << "on renderer [ " << renderer << " ]" << endl; } bool CheckGLErrors() { bool error = false; for (GLenum flag = glGetError(); flag != GL_NO_ERROR; flag = glGetError()) { cout << "OpenGL ERROR: "; switch (flag) { case GL_INVALID_ENUM: cout << "GL_INVALID_ENUM" << endl; break; case GL_INVALID_VALUE: cout << "GL_INVALID_VALUE" << endl; break; case GL_INVALID_OPERATION: cout << "GL_INVALID_OPERATION" << endl; break; case GL_INVALID_FRAMEBUFFER_OPERATION: cout << "GL_INVALID_FRAMEBUFFER_OPERATION" << endl; break; case GL_OUT_OF_MEMORY: cout << "GL_OUT_OF_MEMORY" << endl; break; default: cout << "[unknown error code]" << endl; } error = true; } return error; } // -------------------------------------------------------------------------- // OpenGL shader support functions // reads a text file with the given name into a string string LoadSource(const string &filename) { string source; ifstream input(filename.c_str()); if (input) { copy(istreambuf_iterator<char>(input), istreambuf_iterator<char>(), back_inserter(source)); input.close(); } else { cout << "ERROR: Could not load shader source from file " << filename << endl; } return source; } // creates and returns a shader object compiled from the given source GLuint CompileShader(GLenum shaderType, const string &source) { // allocate shader object name GLuint shaderObject = glCreateShader(shaderType); // try compiling the source as a shader of the given type const GLchar *source_ptr = source.c_str(); glShaderSource(shaderObject, 1, &source_ptr, 0); glCompileShader(shaderObject); // retrieve compile status GLint status; glGetShaderiv(shaderObject, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { GLint length; glGetShaderiv(shaderObject, GL_INFO_LOG_LENGTH, &length); string info(length, ' '); glGetShaderInfoLog(shaderObject, info.length(), &length, &info[0]); cout << "ERROR compiling shader:" << endl << endl; cout << source << endl; cout << info << endl; } return shaderObject; } // creates and returns a program object linked from vertex and fragment shaders GLuint LinkProgram(GLuint vertexShader, GLuint fragmentShader) { // allocate program object name GLuint programObject = glCreateProgram(); // attach provided shader objects to this program if (vertexShader) glAttachShader(programObject, vertexShader); if (fragmentShader) glAttachShader(programObject, fragmentShader); // try linking the program with given attachments glLinkProgram(programObject); // retrieve link status GLint status; glGetProgramiv(programObject, GL_LINK_STATUS, &status); if (status == GL_FALSE) { GLint length; glGetProgramiv(programObject, GL_INFO_LOG_LENGTH, &length); string info(length, ' '); glGetProgramInfoLog(programObject, info.length(), &length, &info[0]); cout << "ERROR linking shader program:" << endl; cout << info << endl; } return programObject; } Added ability to switch through correctly size images // ========================================================================== // Barebones OpenGL Core Profile Boilerplate // using the GLFW windowing system (http://www.glfw.org) // // Loosely based on // - Chris Wellons' example (https://github.com/skeeto/opengl-demo) and // - Camilla Berglund's example (http://www.glfw.org/docs/latest/quick.html) // // Author: Sonny Chan, University of Calgary // Date: December 2015 // ========================================================================== #include <iostream> #include <fstream> #include <string> #include <iterator> #include <algorithm> // specify that we want the OpenGL core profile before including GLFW headers #define GLFW_INCLUDE_GLCOREARB #define GL_GLEXT_PROTOTYPES #include <GLFW/glfw3.h> #include <Magick++.h> using namespace std; // -------------------------------------------------------------------------- // OpenGL utility and support function prototypes void QueryGLVersion(); bool CheckGLErrors(); string LoadSource(const string &filename); GLuint CompileShader(GLenum shaderType, const string &source); GLuint LinkProgram(GLuint vertexShader, GLuint fragmentShader); // ========================================================================== // ========================================================================== // Image File Reading Support Functions // - requires the Magick++ development libraries: http://www.imagemagick.org // // Note: This file will not compile by itself! The snippets below are meant // to be added to the template application distributed for Assignment #1. // You may use this code (or not) however you see fit for your work. // // Author: Sonny Chan, University of Calgary // Date: January 2016 // ========================================================================== // Enum to keep track of current image enum ImageType { MANDRILL, UCLOGO, AERIAL, THIRSK, PATTERN, IMAGETYPE_MAX }; ImageType image_type = MANDRILL; // -------------------------------------------------------------------------- // Functions to set up OpenGL objects for storing image data struct MyTexture { // OpenGL names for array buffer objects, vertex array object GLuint textureName; // dimensions of the image stored in this texture GLuint width, height; // initialize object names to zero (OpenGL reserved value) MyTexture() : textureName(0), width(0), height(0) {} }; // use the Magick++ library to load an image with a given file name into // an OpenGL rectangle texture bool InitializeTexture(MyTexture *texture, const string &imageFileName) { Magick::Image myImage; // try to read the provided image file try { myImage.read(imageFileName); } catch (Magick::Error &error) { cout << "Magick++ failed to read image " << imageFileName << endl; cout << "ERROR: " << error.what() << endl; return false; } // store the image width and height into the texture structure texture->width = myImage.columns(); texture->height = myImage.rows(); // create a Magick++ pixel cache from the image for direct access to data Magick::Pixels pixelCache(myImage); Magick::PixelPacket *pixels; pixels = pixelCache.get(0, 0, texture->width, texture->height); // determine the number of stored bytes per pixel channel in the cache GLenum channelDataType; switch (sizeof(Magick::Quantum)) { case 4: channelDataType = GL_UNSIGNED_INT; break; case 2: channelDataType = GL_UNSIGNED_SHORT; break; default: channelDataType = GL_UNSIGNED_BYTE; } // create a texture name to associate our image data with if (!texture->textureName) glGenTextures(1, &texture->textureName); // bind the texture as a "rectangle" to access using image pixel coordinates glBindTexture(GL_TEXTURE_RECTANGLE, texture->textureName); // send image pixel data to OpenGL texture memory glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGB, texture->width, texture->height, 0, GL_BGRA, channelDataType, pixels); // unbind this texture glBindTexture(GL_TEXTURE_RECTANGLE, 0); return !CheckGLErrors(); } // -------------------------------------------------------------------------- // Functions to set up OpenGL shader programs for rendering struct MyShader { // OpenGL names for vertex and fragment shaders, shader program GLuint vertex; GLuint fragment; GLuint program; // initialize shader and program names to zero (OpenGL reserved value) MyShader() : vertex(0), fragment(0), program(0) {} }; // load, compile, and link shaders, returning true if successful bool InitializeShaders(MyShader *shader) { // load shader source from files string vertexSource = LoadSource("vertex.glsl"); string fragmentSource = LoadSource("fragment.glsl"); if (vertexSource.empty() || fragmentSource.empty()) return false; // compile shader source into shader objects shader->vertex = CompileShader(GL_VERTEX_SHADER, vertexSource); shader->fragment = CompileShader(GL_FRAGMENT_SHADER, fragmentSource); // link shader program shader->program = LinkProgram(shader->vertex, shader->fragment); // check for OpenGL errors and return false if error occurred return !CheckGLErrors(); } // deallocate shader-related objects void DestroyShaders(MyShader *shader) { // unbind any shader programs and destroy shader objects glUseProgram(0); glDeleteProgram(shader->program); glDeleteShader(shader->vertex); glDeleteShader(shader->fragment); } // -------------------------------------------------------------------------- // Functions to set up OpenGL buffers for storing geometry data struct MyGeometry { // OpenGL names for array buffer objects, vertex array object GLuint vertexBuffer; GLuint colourBuffer; GLuint textureCoordBuffer; GLuint vertexArray; GLsizei elementCount; // initialize object names to zero (OpenGL reserved value) MyGeometry() : vertexBuffer(0), colourBuffer(0), textureCoordBuffer(0), vertexArray(0), elementCount(0) {} }; // create buffers and fill with geometry data, returning true if successful bool InitializeGeometry(MyGeometry *geometry, MyTexture *texture) { GLfloat x_max = 0; GLfloat y_max = 0; GLfloat x_min = 0; GLfloat y_min = 0; if(texture->width > texture->height) { y_max = (texture->height/float(texture->width)); y_min = -(texture->height/float(texture->width)); x_max = 1.0; x_min = -1.0; } else if(texture->width < texture->height) { x_max = (texture->width/float(texture->height)); x_min = -(texture->width/float(texture->height)); y_max = 1.0; y_min = -1.0; } else { y_max = 1.0; y_min = -1.0; x_max = 1.0; x_min = -1.0; } // associated vertices based on image aspect ratio const GLfloat vertices[][2] = { { x_min, y_min }, { x_max, y_min }, { x_min, y_max }, { x_min, y_max }, { x_max, y_max }, { x_max, y_min } }; const GLfloat colours[][3] = { { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 }, { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 } }; const GLuint textureCoords[][2] = { {0, texture->height}, {texture->width, texture->height}, {0, 0}, {0, 0}, {texture->width, 0}, {texture->width, texture->height} }; geometry->elementCount = 6; // these vertex attribute indices correspond to those specified for the // input variables in the vertex shader const GLuint VERTEX_INDEX = 0; const GLuint COLOUR_INDEX = 1; const GLuint TEXTURE_INDEX = 2; // create an array buffer object for storing our vertices glGenBuffers(1, &geometry->vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, geometry->vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // create another one for storing our colours glGenBuffers(1, &geometry->colourBuffer); glBindBuffer(GL_ARRAY_BUFFER, geometry->colourBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(colours), colours, GL_STATIC_DRAW); // Buffer for storing texture glGenBuffers(1, &geometry->textureCoordBuffer); glBindBuffer(GL_ARRAY_BUFFER, geometry->textureCoordBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(textureCoords), textureCoords, GL_STATIC_DRAW); // create a vertex array object encapsulating all our vertex attributes glGenVertexArrays(1, &geometry->vertexArray); glBindVertexArray(geometry->vertexArray); // associate the position array with the vertex array object glBindBuffer(GL_ARRAY_BUFFER, geometry->vertexBuffer); glVertexAttribPointer(VERTEX_INDEX, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(VERTEX_INDEX); // assocaite the colour array with the vertex array object glBindBuffer(GL_ARRAY_BUFFER, geometry->colourBuffer); glVertexAttribPointer(COLOUR_INDEX, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(COLOUR_INDEX); // Set up vertex attribute info for textures glBindBuffer(GL_ARRAY_BUFFER, geometry->textureCoordBuffer); glVertexAttribPointer(TEXTURE_INDEX, 2, GL_UNSIGNED_INT, GL_FALSE, 0, 0); glEnableVertexAttribArray(TEXTURE_INDEX); // unbind our buffers, resetting to default state glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // check for OpenGL errors and return false if error occurred return !CheckGLErrors(); } // deallocate geometry-related objects void DestroyGeometry(MyGeometry *geometry) { // unbind and destroy our vertex array object and associated buffers glBindVertexArray(0); glDeleteVertexArrays(1, &geometry->vertexArray); glDeleteBuffers(1, &geometry->vertexBuffer); glDeleteBuffers(1, &geometry->colourBuffer); } // -------------------------------------------------------------------------- // Rendering function that draws our scene to the frame buffer void RenderScene(MyGeometry *geometry, MyTexture* texture, MyShader *shader) { // clear screen to a dark grey colour glClearColor(0.2, 0.2, 0.2, 1.0); glClear(GL_COLOR_BUFFER_BIT); // bind our shader program and the vertex array object containing our // scene geometry, then tell OpenGL to draw our geometry glUseProgram(shader->program); glBindVertexArray(geometry->vertexArray); glBindTexture(GL_TEXTURE_RECTANGLE, texture->textureName); glDrawArrays(GL_TRIANGLES, 0, geometry->elementCount); // reset state to default (no shader or geometry bound) glBindTexture(GL_TEXTURE_RECTANGLE, 0); glBindVertexArray(0); glUseProgram(0); // check for an report any OpenGL errors CheckGLErrors(); } // -------------------------------------------------------------------------- // GLFW callback functions // reports GLFW errors void ErrorCallback(int error, const char* description) { cout << "GLFW ERROR " << error << ":" << endl; cout << description << endl; } // handles keyboard input events void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); if (action == GLFW_PRESS) { switch(key) { case GLFW_KEY_1: image_type = MANDRILL; break; case GLFW_KEY_2: image_type = UCLOGO; break; case GLFW_KEY_3: image_type = AERIAL; break; case GLFW_KEY_4: image_type = THIRSK; break; case GLFW_KEY_5: image_type = PATTERN; break; } } } void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { if(button == GLFW_MOUSE_BUTTON_1) { cout << "left "; if(action == GLFW_PRESS) { cout << "pressed" << endl; } else if(action == GLFW_RELEASE) { cout << "released" << endl; } } } void mouseMoveCallback(GLFWwindow* window, double x, double y) { cout << "x " << x << " y " << y << endl; } // ========================================================================== // PROGRAM ENTRY POINT int main(int argc, char *argv[]) { Magick::InitializeMagick(NULL); // initialize the GLFW windowing system if (!glfwInit()) { cout << "ERROR: GLFW failed to initilize, TERMINATING" << endl; return -1; } glfwSetErrorCallback(ErrorCallback); // attempt to create a window with an OpenGL 4.1 core profile context GLFWwindow *window = 0; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(512, 512, "CPSC 453 OpenGL Assignment 2", 0, 0); if (!window) { cout << "Program failed to create GLFW window, TERMINATING" << endl; glfwTerminate(); return -1; } // set keyboard callback function and make our context current (active) glfwSetKeyCallback(window, KeyCallback); glfwSetMouseButtonCallback(window, mouseButtonCallback); glfwSetCursorPosCallback(window, mouseMoveCallback); glfwMakeContextCurrent(window); // set mouse call back functions // query and print out information about our OpenGL environment QueryGLVersion(); // call function to load and compile shader programs MyShader shader; if (!InitializeShaders(&shader)) { cout << "Program could not initialize shaders, TERMINATING" << endl; return -1; } // load and initialize the texture MyTexture textures[IMAGETYPE_MAX]; if(!InitializeTexture(&textures[MANDRILL], "image1-mandrill.png")) cout << "Failed to load texture!" << endl; if(!InitializeTexture(&textures[UCLOGO], "image2-uclogo.png")) cout << "Failed to load texture!" << endl; if(!InitializeTexture(&textures[AERIAL], "image3-aerial.jpg")) cout << "Failed to load texture!" << endl; if(!InitializeTexture(&textures[THIRSK], "image4-thirsk.jpg")) cout << "Failed to load texture!" << endl; if(!InitializeTexture(&textures[PATTERN], "image5-pattern.png")) cout << "Failed to load texture!" << endl; // call function to create and fill buffers with geometry data MyGeometry geometries[IMAGETYPE_MAX]; if (!InitializeGeometry(&geometries[MANDRILL], &textures[MANDRILL])) cout << "Program failed to intialize geometry!" << endl; if (!InitializeGeometry(&geometries[UCLOGO], &textures[UCLOGO])) cout << "Program failed to intialize geometry!" << endl; if (!InitializeGeometry(&geometries[AERIAL], &textures[AERIAL])) cout << "Program failed to intialize geometry!" << endl; if (!InitializeGeometry(&geometries[THIRSK], &textures[THIRSK])) cout << "Program failed to intialize geometry!" << endl; if (!InitializeGeometry(&geometries[PATTERN], &textures[PATTERN])) cout << "Program failed to intialize geometry!" << endl; // run an event-triggered main loop while (!glfwWindowShouldClose(window)) { // call function to draw our scene RenderScene(&geometries[image_type], &textures[image_type], &shader); // scene is rendered to the back buffer, so swap to front for display glfwSwapBuffers(window); // sleep until next event before drawing again glfwWaitEvents(); } // clean up allocated resources before exit for(GLuint i = 0; i < IMAGETYPE_MAX; i++) { DestroyGeometry(&geometries[i]); } DestroyShaders(&shader); glfwDestroyWindow(window); glfwTerminate(); cout << "Goodbye!" << endl; return 0; } // ========================================================================== // SUPPORT FUNCTION DEFINITIONS // -------------------------------------------------------------------------- // OpenGL utility functions void QueryGLVersion() { // query opengl version and renderer information string version = reinterpret_cast<const char *>(glGetString(GL_VERSION)); string glslver = reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION)); string renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER)); cout << "OpenGL [ " << version << " ] " << "with GLSL [ " << glslver << " ] " << "on renderer [ " << renderer << " ]" << endl; } bool CheckGLErrors() { bool error = false; for (GLenum flag = glGetError(); flag != GL_NO_ERROR; flag = glGetError()) { cout << "OpenGL ERROR: "; switch (flag) { case GL_INVALID_ENUM: cout << "GL_INVALID_ENUM" << endl; break; case GL_INVALID_VALUE: cout << "GL_INVALID_VALUE" << endl; break; case GL_INVALID_OPERATION: cout << "GL_INVALID_OPERATION" << endl; break; case GL_INVALID_FRAMEBUFFER_OPERATION: cout << "GL_INVALID_FRAMEBUFFER_OPERATION" << endl; break; case GL_OUT_OF_MEMORY: cout << "GL_OUT_OF_MEMORY" << endl; break; default: cout << "[unknown error code]" << endl; } error = true; } return error; } // -------------------------------------------------------------------------- // OpenGL shader support functions // reads a text file with the given name into a string string LoadSource(const string &filename) { string source; ifstream input(filename.c_str()); if (input) { copy(istreambuf_iterator<char>(input), istreambuf_iterator<char>(), back_inserter(source)); input.close(); } else { cout << "ERROR: Could not load shader source from file " << filename << endl; } return source; } // creates and returns a shader object compiled from the given source GLuint CompileShader(GLenum shaderType, const string &source) { // allocate shader object name GLuint shaderObject = glCreateShader(shaderType); // try compiling the source as a shader of the given type const GLchar *source_ptr = source.c_str(); glShaderSource(shaderObject, 1, &source_ptr, 0); glCompileShader(shaderObject); // retrieve compile status GLint status; glGetShaderiv(shaderObject, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { GLint length; glGetShaderiv(shaderObject, GL_INFO_LOG_LENGTH, &length); string info(length, ' '); glGetShaderInfoLog(shaderObject, info.length(), &length, &info[0]); cout << "ERROR compiling shader:" << endl << endl; cout << source << endl; cout << info << endl; } return shaderObject; } // creates and returns a program object linked from vertex and fragment shaders GLuint LinkProgram(GLuint vertexShader, GLuint fragmentShader) { // allocate program object name GLuint programObject = glCreateProgram(); // attach provided shader objects to this program if (vertexShader) glAttachShader(programObject, vertexShader); if (fragmentShader) glAttachShader(programObject, fragmentShader); // try linking the program with given attachments glLinkProgram(programObject); // retrieve link status GLint status; glGetProgramiv(programObject, GL_LINK_STATUS, &status); if (status == GL_FALSE) { GLint length; glGetProgramiv(programObject, GL_INFO_LOG_LENGTH, &length); string info(length, ' '); glGetProgramInfoLog(programObject, info.length(), &length, &info[0]); cout << "ERROR linking shader program:" << endl; cout << info << endl; } return programObject; }
/* Jim Viebke Jeb 16 2015 */ #include "constants.h" #include "character.h" #include "world.h" Recipes Character::recipes; // Character constructor Character::Character(const string & name, const string & set_faction_ID) : name(name) { // if the faction is valid if (set_faction_ID == C::PC_FACTION_ID || set_faction_ID == C::NPC_NEUTRAL_FACTION_ID || set_faction_ID == C::NPC_HOSTILE_FACTION_ID) { // set the actor's faction this->faction_ID = set_faction_ID; } else // the faction is not valid { // Raise an error in the console cout << "ERROR: attempted to create character with invalid faction: [" << set_faction_ID << "]\n"; } } string Character::login(World & world) { // create a document to load the player's data xml_document user_data_xml; // load the player's data to user_data_xml user_data_xml.load_file((C::user_data_directory + "/" + this->name + ".xml").c_str()); // create holder values to save the coordinates from the file int loaded_x = -1, loaded_y = -1, loaded_z = -1; // load the three values from the node const xml_node location_node = user_data_xml.child(C::XML_USER_LOCATION.c_str()); // extract the attributes as well as the values for the attributes const xml_attribute x_attribute = location_node.attribute(string("x").c_str()); const xml_attribute y_attribute = location_node.attribute(string("y").c_str()); const xml_attribute z_attribute = location_node.attribute(string("z").c_str()); loaded_x = x_attribute.as_int(); loaded_y = y_attribute.as_int(); loaded_z = z_attribute.as_int(); // if any of the attributes are empty or the extracted values fail bounds-checking if (x_attribute.empty() || y_attribute.empty() || z_attribute.empty() || !U::bounds_check(loaded_x, loaded_y, loaded_z)) { // set the player to the default spawn this->x = C::DEFAULT_SPAWN_X; this->y = C::DEFAULT_SPAWN_Y; this->z = C::DEFAULT_SPAWN_Z; } else { // set the player to the valid loaded coordinates this->x = loaded_x; this->y = loaded_y; this->z = loaded_z; } // load the rooms around the player's spawn world.load_view_radius_around(x, y, name); // spawn in the player world.room_at(x, y, z)->add_actor(this->name); // select the level node const xml_node level_node = user_data_xml.child(C::XML_USER_LEVELS.c_str()); // select each level attribute const xml_attribute swordsmanship_level_attribute = level_node.attribute(C::XML_LEVEL_SWORDSMANSHIP.c_str()); const xml_attribute archery_level_attribute = level_node.attribute(C::XML_LEVEL_ARCHERY.c_str()); const xml_attribute forest_visibility_level_attribute = level_node.attribute(C::XML_LEVEL_FOREST_VISIBILITY.c_str()); const xml_attribute full_health_level_attribute = level_node.attribute(C::XML_LEVEL_HEALTH_MAX.c_str()); // if an attribute is non-empty, load its level value if (!swordsmanship_level_attribute.empty()) { this->set_swordsmanship_level(swordsmanship_level_attribute.as_int()); } if (!archery_level_attribute.empty()) { this->set_archery_level(archery_level_attribute.as_int()); } if (!forest_visibility_level_attribute.empty()) { this->set_forest_visibilty_level(forest_visibility_level_attribute.as_int()); } if (!full_health_level_attribute.empty()) { this->set_health_max(full_health_level_attribute.as_int()); } // select status node (just holds current_health at this time) const xml_node status_node = user_data_xml.child(C::XML_USER_STATUS.c_str()); // if current_health is non-empty, set current health const xml_attribute current_health_attribute = status_node.attribute(C::XML_USER_STATUS_CURRENT_HEALTH.c_str()); if (!current_health_attribute.empty()) { this->set_current_health(current_health_attribute.as_int()); } else // if current_health is empty, explicitly set current health to base maximum { this->set_current_health(C::FULL_HEALTH_MIN); } // for each item node of the equipment node for (const xml_node & equipment_node : user_data_xml.child(C::XML_USER_EQUIPMENT.c_str()).children()) { // create the item shared_ptr<Equipment> equipment = U::convert_to<Equipment>(Craft::make(equipment_node.name())); // extract the value of the health attribute and use it to set the item's health equipment->set_health(equipment_node.attribute(C::XML_ITEM_HEALTH.c_str()).as_int()); // add the item to the player's inventory equipment_inventory.insert(pair<string, shared_ptr<Equipment>>(equipment->name, equipment)); } // for each item in the material node for (const xml_node & material : user_data_xml.child(C::XML_USER_MATERIALS.c_str()).children()) { // use the name of the material node to create a new materail object shared_ptr<Material> item = U::convert_to<Material>(Craft::make(material.name())); // extract the amount from the item's attribute item->amount = material.attribute(C::XML_USER_MATERIAL_COUNT.c_str()).as_uint(); // add the item to the material inventory material_inventory.insert(pair<string, shared_ptr<Material>>(item->name, item)); } // notify success return "You have logged in to IslandMUD!"; } string Character::save() { // if an item is equipped, move it back to the player's inventory this->unequip(); // create a document to save the user's info xml_document user_data_xml; // create nodes to store user equipment and materials xml_node status_node = user_data_xml.append_child(C::XML_USER_STATUS.c_str()); xml_node location_node = user_data_xml.append_child(C::XML_USER_LOCATION.c_str()); xml_node level_node = user_data_xml.append_child(C::XML_USER_LEVELS.c_str()); xml_node equipment_node = user_data_xml.append_child(C::XML_USER_EQUIPMENT.c_str()); xml_node material_node = user_data_xml.append_child(C::XML_USER_MATERIALS.c_str()); /// add health attribute to status node status_node.append_attribute(C::XML_USER_STATUS_CURRENT_HEALTH.c_str()).set_value(this->current_health); // add x, y, and z attributes to the location node location_node.append_attribute(string("x").c_str()).set_value(this->x); location_node.append_attribute(string("y").c_str()).set_value(this->y); location_node.append_attribute(string("z").c_str()).set_value(this->z); // add each level to the location node level_node.append_attribute(C::XML_LEVEL_SWORDSMANSHIP.c_str()).set_value(this->swordsmanship_level); level_node.append_attribute(C::XML_LEVEL_ARCHERY.c_str()).set_value(this->archery_level); level_node.append_attribute(C::XML_LEVEL_FOREST_VISIBILITY.c_str()).set_value(this->forest_visibility_level); level_node.append_attribute(C::XML_LEVEL_HEALTH_MAX.c_str()).set_value(this->max_health); // for each piece of equipment in the user's inventory for (multimap<string, shared_ptr<Equipment>>::const_iterator it = equipment_inventory.cbegin(); it != equipment_inventory.cend(); ++it) { // save the equipment to a new node under the equipment node xml_node equipment = equipment_node.append_child(it->first.c_str()); // append a health attribute to the equipment node and set its value to the health of the equipment equipment.append_attribute(C::XML_ITEM_HEALTH.c_str()).set_value(it->second->get_health()); } // for each material in the user's inventory for (map<string, shared_ptr<Material>>::const_iterator it = material_inventory.cbegin(); it != material_inventory.cend(); ++it) { // save the material to a new node under the material node xml_node material = material_node.append_child(it->first.c_str()); // add an attribute called "count" with a value of material->count xml_attribute material_attribute = material.append_attribute(C::XML_USER_MATERIAL_COUNT.c_str()); material_attribute.set_value(it->second->amount); } // save the user_data to disk user_data_xml.save_file((C::user_data_directory + "/" + this->name + ".xml").c_str()); // returns an unused boolean return "Player info saved."; } // levels void Character::set_swordsmanship_level(const int & level_value) { if (level_value > C::SWORDSMANSHIP_LEVEL_MAX) { swordsmanship_level = C::SWORDSMANSHIP_LEVEL_MAX; } else if (level_value < C::SWORDSMANSHIP_LEVEL_MIN) { swordsmanship_level = C::SWORDSMANSHIP_LEVEL_MIN; } else { swordsmanship_level = level_value; } } void Character::set_archery_level(const int & level_value) { if (level_value > C::ARCHERY_LEVEL_MAX) { archery_level = C::ARCHERY_LEVEL_MAX; } else if (level_value < C::ARCHERY_LEVEL_MIN) { archery_level = C::ARCHERY_LEVEL_MIN; } else { archery_level = level_value; } } void Character::set_forest_visibilty_level(const int & level_value) { if (level_value > C::FOREST_VISIBILITY_LEVEL_MAX) { forest_visibility_level = C::FOREST_VISIBILITY_LEVEL_MAX; } else if (level_value < C::FOREST_VISIBILITY_LEVEL_MIN) { forest_visibility_level = C::FOREST_VISIBILITY_LEVEL_MIN; } else { forest_visibility_level = level_value; } } void Character::set_health_max(const int & level_value) { if (level_value > C::FULL_HEALTH_MAX) { max_health = C::FULL_HEALTH_MAX; } else if (level_value < C::FULL_HEALTH_MIN) { max_health = C::FULL_HEALTH_MIN; } else { max_health = level_value; } } // setters void Character::set_current_health(const int & health_value) { // don't call this until after the player's max_health has been set // otherwise the max_health field will still be at the default game constant if (health_value > max_health) { current_health = max_health; } else if (health_value <= C::HEALTH_MIN) // we can't set the user's health level to "die", so just use max { current_health = max_health; } else { current_health = health_value; } } // inventory information bool Character::has(const string & item_name, const unsigned & item_count) const { if (item_count == 1) // only one instance is required { return ((equipped_item != nullptr) ? equipped_item->name : "") == item_name || equipment_inventory.find(item_name) != equipment_inventory.cend() || material_inventory.find(item_name) != material_inventory.cend(); } else // more than one item is required { return (equipment_inventory.count(item_name) >= item_count) // the equipment inventory contains item_count of the required item || (material_inventory.find(item_name) != material_inventory.cend() && // the material invenory contains the required item material_inventory.find(item_name)->second->amount >= item_count); // AND the material exists in sufficient quantity } } bool Character::does_not_have(const string & item_name, const unsigned & item_count) const { return !this->has(item_name, item_count); } string Character::get_inventory() const // debugging { stringstream contents; for (multimap<string, shared_ptr<Equipment>>::const_iterator it = equipment_inventory.begin(); it != equipment_inventory.end(); ++it) { contents << it->second->name << " "; } for (map<string, shared_ptr<Material>>::const_iterator it = material_inventory.begin(); it != material_inventory.end(); ++it) { contents << it->second->name << ":" << it->second->amount << " "; } return contents.str(); } // inventory manipulation void Character::add(const shared_ptr<Item> & item) { // if the item is a material and is therefore stackable if (U::is<Material>(item)) { // check if the player already has an instance of the item in their material inventory if (this->material_inventory.find(item->name) != this->material_inventory.cend()) { // if so, increment the count this->material_inventory[item->name]->amount++; } else { // if not, give the player a new instance of the item this->material_inventory.insert(pair<string, shared_ptr<Material>>(item->name, U::convert_to<Material>(Craft::make(item->name)))); } } else // the item is not a material and is therefore an Equipment type { // insert the new item this->equipment_inventory.insert(pair<string, shared_ptr<Equipment>>(item->name, U::convert_to<Equipment>(item))); } } void Character::remove(const string & item_id, const unsigned & count) { // WARNING - for materials this assumes the player has [count] instances // if the player is holding the item if (this->equipped_item != nullptr && this->equipped_item->name == item_id) { this->equipped_item = nullptr; // erase the item } // remove or reduce the item in the player's inventory else if (equipment_inventory.find(item_id) != equipment_inventory.cend()) { for (unsigned i = 0; i < count; ++i) { equipment_inventory.erase(equipment_inventory.find(item_id)); } } else if (material_inventory.find(item_id) != material_inventory.cend()) // the item is present in the material inventory { material_inventory.find(item_id)->second->amount -= count; // decrement the material count in the player's inventory if (material_inventory.find(item_id)->second->amount < 1) { material_inventory.erase(material_inventory.find(item_id)); } } else { // the player does not have the item } } // actions Update_Messages Character::move(const string & direction_ID, World & world) { // movement deltas int dx = 0, dy = 0, dz = 0; U::assign_movement_deltas(direction_ID, dx, dy, dz); // validate movement deltas if (!U::bounds_check(x + dx, y + dy, z + dz)) { return Update_Messages("You can't go there."); } // copy the destination from disk to memory // world.load_room_to_world(x + dx, y + dy, z + dz); // test if the environment (structures) allow the player to move in a given direction const string validate_movement = this->validate_movement(x, y, z, direction_ID, dx, dy, dz, world); // if the validation failed for any reason if (validate_movement != C::GOOD_SIGNAL) { // return that reason movement validation failed return Update_Messages(validate_movement); } // the movement validated, load the radius for the destination world.load_view_radius_around(x + dx, y + dy, this->name); // maintain a list of users that are falling out of view that will also need a map update vector<string> additional_users_to_notify; // remove viewing ID from rooms leaving view if (direction_ID == C::NORTH || direction_ID == C::SOUTH) { // if the character is moving north, add the view distance to x to get the x of the row being removed // otherwise (moving south) remove the distance from x int rx = (direction_ID == C::NORTH) ? x + C::VIEW_DISTANCE : x - C::VIEW_DISTANCE; // each room to try unload from from x,(y-view) to (x,y+view) for (int ry = y - C::VIEW_DISTANCE; ry <= y + C::VIEW_DISTANCE; ++ry) { // Skip this room if it is not loaded. This occurs when a player moves diagonally, and both room unload passes overlap at the corner of the map. if (world.room_at(rx, ry, C::GROUND_INDEX) != nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); // save any users in the room // remove the character from the room's viewer list, trying to unload the room in the process world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); // bounds checking takes place in here } } else if (direction_ID == C::WEST || direction_ID == C::EAST) { // logic is the same as above, but in rotated axes (axes is plural of axis) const int ry = (direction_ID == C::WEST) ? y + C::VIEW_DISTANCE : y - C::VIEW_DISTANCE; for (int rx = x - C::VIEW_DISTANCE; rx <= x + C::VIEW_DISTANCE; ++rx) { if (world.room_at(rx, ry, C::GROUND_INDEX) != nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); } } else if (direction_ID == C::UP) { return Update_Messages("[moving up not available yet]"); } else if (direction_ID == C::DOWN) { return Update_Messages("[moving down not available yet]"); } else { /* The direction is a secondary compass direction. This means execution will alwways enter two of the four below blocks. Functionality here is the same as above. For documentation, scroll up. */ if (direction_ID == C::NORTH_WEST || direction_ID == C::NORTH_EAST) // moving north, parse south row { const int rx = x + C::VIEW_DISTANCE; for (int ry = y - C::VIEW_DISTANCE; ry <= y + C::VIEW_DISTANCE; ++ry) { if (world.room_at(rx, ry, C::GROUND_INDEX) != nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); } } if (direction_ID == C::NORTH_EAST || direction_ID == C::SOUTH_EAST) // moving east, parse west row { const int ry = y - C::VIEW_DISTANCE; for (int rx = x - C::VIEW_DISTANCE; rx <= x + C::VIEW_DISTANCE; ++rx) { if (world.room_at(rx, ry, C::GROUND_INDEX) != nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); } } if (direction_ID == C::SOUTH_EAST || direction_ID == C::SOUTH_WEST) // moving south, parse north row { const int rx = x - C::VIEW_DISTANCE; for (int ry = y - C::VIEW_DISTANCE; ry <= y + C::VIEW_DISTANCE; ++ry) { if (world.room_at(rx, ry, C::GROUND_INDEX) != nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); } } if (direction_ID == C::SOUTH_WEST || direction_ID == C::NORTH_WEST) // moving west, parse east row { const int ry = y + C::VIEW_DISTANCE; for (int rx = x - C::VIEW_DISTANCE; rx <= x + C::VIEW_DISTANCE; ++rx) { if (world.room_at(rx, ry, C::GROUND_INDEX) != nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); } } } // the movement validated, remove character id from area world.room_at(x, y, z)->remove_actor(this->name); // test if the room can be unloaded if (world.is_unloadable(x, y, z)) // Why are we trying to unload the room we're moving out of? The player will still be able to see this. { world.unload_room(x, y, z); } // consider moving the above block to world.remove_character(x, y, z, id) // the check to unload could be in one place // update character internal coordinates x += dx; y += dy; z += dz; // add character id to new area using the new x and y coordinates world.room_at(x, y, z)->add_actor(this->name); // prepare responses Update_Messages updates("You move " + direction_ID + ".", // "Jeb arrives from the south [wielding an axe]." this->name + " arrives from the " + C::opposite_direction_id.find(direction_ID)->second + ((this->equipped_item == nullptr) ? "." : (" wielding " + U::get_article_for(equipped_item->name) + " " + equipped_item->name + ".")), true); // update required for all users in sight range // users that have fallen out of view won't recieve a map update unless we send one to them explicitly updates.additional_map_update_users = make_shared<vector<string>>(std::move(additional_users_to_notify)); return updates; } Update_Messages Character::craft(const string & craft_item_id, World & world) { // check for special case if (craft_item_id == C::CHEST_ID) { if (world.room_at(x, y, z)->has_chest()) { return Update_Messages("There is already a chest here."); } } // return if the recipe does not exist if (!Character::recipes.has_recipe_for(craft_item_id)) { return Update_Messages("There is no way to craft " + U::get_article_for(craft_item_id) + " " + craft_item_id + "."); } // get the recipe const Recipe recipe = Character::recipes.get_recipe(craft_item_id); // verify the conditions for the recipe are present for (map<string, int>::const_iterator it = recipe.inventory_need.cbegin(); it != recipe.inventory_need.cend(); ++it) { if (it->first != "" && !this->has(it->first, it->second)) { return Update_Messages(U::get_article_for(craft_item_id) + " " + craft_item_id + " requires " + ((it->second == 1) ? U::get_article_for(it->first) : U::to_string(it->second)) + " " + it->first); } } for (map<string, int>::const_iterator it = recipe.inventory_remove.cbegin(); it != recipe.inventory_remove.cend(); ++it) { if (it->first != "" && !this->has(it->first, it->second)) { return Update_Messages(U::get_article_for(craft_item_id) + " " + craft_item_id + " uses " + ((it->second == 1) ? U::get_article_for(it->first) : U::to_string(it->second)) + " " + it->first); } } for (map<string, int>::const_iterator it = recipe.local_need.cbegin(); it != recipe.local_need.cend(); ++it) { if (it->first != "" && !world.room_at(x, y, z)->contains_item(it->first)) { return Update_Messages(U::get_article_for(craft_item_id) + " " + craft_item_id + " requires " + ((it->second == 1) ? "a" : U::to_string(it->second)) + " nearby " + it->first); } } for (map<string, int>::const_iterator it = recipe.local_remove.cbegin(); it != recipe.local_remove.cend(); ++it) { if (it->first != "" && !world.room_at(x, y, z)->contains_item(it->first)) { return Update_Messages(U::get_article_for(craft_item_id) + " " + craft_item_id + " uses " + ((it->second == 1) ? "a" : U::to_string(it->second)) + " nearby " + it->first); } } // remove ingredients from inventory for (map<string, int>::const_iterator it = recipe.inventory_remove.cbegin(); it != recipe.inventory_remove.cend(); ++it) { this->remove(it->first, it->second); // ID, count } // remove ingredients from area for (map<string, int>::const_iterator it = recipe.local_remove.cbegin(); it != recipe.local_remove.cend(); ++it) { this->remove(it->first, it->second); // ID, count } stringstream player_update, room_update; // for each item to be given to the player for (map<string, int>::const_iterator it = recipe.yields.cbegin(); it != recipe.yields.cend(); ++it) { // for as many times as the item is to be given to the player for (int i = 0; i < it->second; ++i) { // special test cast for chests if (craft_item_id == C::CHEST_ID) { // add a chest to the room world.room_at(x, y, z)->add_chest(this->faction_ID); continue; } // craft the item shared_ptr<Item> item = Craft::make(it->first); // if the item can be carried if (item->is_takable()) { // add the item to the player's inventory this->add(item); } else // the item can not be taken { // add the item to the room world.room_at(x, y, z)->add_item(item); } } player_update << "You craft "; room_update << this->name << " crafts "; if (it->second > 1) // ... 3 arrowheads. { player_update << it->second << " " << U::get_plural_for(it->first) << "."; room_update << it->second << " " << U::get_plural_for(it->first) << "."; } else // ... an arrowhead. { player_update << U::get_article_for(it->first) << " " << it->first << "."; room_update << U::get_article_for(it->first) << " " << it->first << "."; } } return Update_Messages(player_update.str(), room_update.str()); } Update_Messages Character::take(const string & take_item_id, World & world) { // check if the item is not in the player's vicinity if (!world.room_at(x, y, z)->contains_item(take_item_id)) { return Update_Messages("There is no " + take_item_id + " here."); } // check if the item is not takable if (!world.room_at(x, y, z)->get_contents().find(take_item_id)->second->is_takable()) { // return failure return Update_Messages("You can't take the " + take_item_id + "."); } // the item is takable this->add(world.room_at(x, y, z)->get_contents().find(take_item_id)->second); // copy the item to the player world.room_at(x, y, z)->remove_item(take_item_id); // remove the item from the world return Update_Messages("You take " + U::get_article_for(take_item_id) + " " + take_item_id + ".", this->name + " takes " + U::get_article_for(take_item_id) + " " + take_item_id + "."); } string Character::drop(const string & drop_item_id, World & world) { // if the player is holding the item specified if (this->equipped_item != nullptr && this->equipped_item->name == drop_item_id) { // add the item to the world world.room_at(x, y, z)->add_item(this->equipped_item); } else { if (!this->has(drop_item_id)) // if the player does not have the item specified { // the item does not exist in the player's inventory return "You don't have " + U::get_article_for(drop_item_id) + " " + drop_item_id + " to drop."; } // add the item to the world world.room_at(x, y, z)->add_item( (equipment_inventory.find(drop_item_id) != equipment_inventory.end()) ? U::convert_to<Item>( // determine where to get the item from equipment_inventory.find(drop_item_id)->second) : // upcast one of the items to an <Item> type material_inventory.find(drop_item_id)->second ); } /// remove item this->remove(drop_item_id); // success reply return "You drop " + U::get_article_for(drop_item_id) + " " + drop_item_id + "."; } Update_Messages Character::equip(const string & item_ID) { /* You ready your [item_id]. You replace your [item_id] with a(n) [item_id]; */ // if the player does not have the item specified if (!this->has(item_ID)) { return Update_Messages("You do not have " + U::get_article_for(item_ID) + " " + item_ID + " to equip."); } // the player has at least one instance of the item, check if the player does not have another one to equip if (equipment_inventory.find(item_ID) == equipment_inventory.cend() && material_inventory.find(item_ID) == material_inventory.cend()) { return Update_Messages("You are holding " + U::get_article_for(item_ID) + " " + item_ID + " and don't have another one to equip."); } // create a stringstream to accumulate feedback stringstream user_update; stringstream room_update; // the player does have the item to equip, test if an item is already equipped if (this->equipped_item != nullptr) { user_update << "You replace your " << equipped_item->name << " with "; room_update << this->name << " replaces " << U::get_article_for(equipped_item->name) << " " << equipped_item->name << " with "; // save the existing the item to the player's inventory this->add(equipped_item); // erase the existing item this->equipped_item = nullptr; } // set the equipped item to the specified item from whichever inventory we find it in if (this->equipment_inventory.find(item_ID) != equipment_inventory.cend()) { equipped_item = equipment_inventory.find(item_ID)->second; } else { equipped_item = material_inventory.find(item_ID)->second; } // remove or reduce the item in the player's inventory if (equipment_inventory.find(item_ID) != equipment_inventory.cend()) { equipment_inventory.erase(equipment_inventory.find(item_ID)); } else if (material_inventory.find(item_ID) != material_inventory.cend()) // the item is present in the material inventory { material_inventory.find(item_ID)->second->amount--; // decrement the material count in the player's inventory if (material_inventory.find(item_ID)->second->amount < 1) { material_inventory.erase(material_inventory.find(item_ID)); } } // if the stringstream is empty (no item was previously equipped) if (user_update.str().length() == 0) { return Update_Messages( "You equip your " + item_ID + ".", this->name + " equips " + U::get_article_for(item_ID) + " " + item_ID + "."); } else { // complete and return the response message user_update << U::get_article_for(equipped_item->name) << " " << equipped_item->name << "."; room_update << U::get_article_for(equipped_item->name) << " " << equipped_item->name << "."; return Update_Messages(user_update.str(), room_update.str()); } } Update_Messages Character::unequip() { // test if no item is equipped if (this->equipped_item == nullptr) { return Update_Messages("You aren't holding anything."); } // save the ID of the currently equipped item const string item_ID = equipped_item->name; // save the existing the item to the player's inventory this->add(equipped_item); // reset the currently equipped item equipped_item = nullptr; return Update_Messages("You put your " + item_ID + " away.", this->name + " lowers the " + item_ID + "."); } string Character::add_to_chest(const string & insert_item_id, World & world) { // if this room does not have a chest if (!world.room_at(x, y, z)->has_chest()) { return "There is no chest here."; } // if the chest was crafted by another faction if (world.room_at(x, y, z)->get_chest_faction_id() != this->faction_ID) { return "This chest has an unfamiliar lock."; } // if the player doesn't have the item if (!this->has(insert_item_id)) { return "You don't have " + U::get_article_for(insert_item_id) + " " + insert_item_id + "."; } // if the item is equipped if (equipped_item != nullptr && equipped_item->name == insert_item_id) { world.room_at(x, y, z)->add_item_to_chest(equipped_item); } // if the item is a piece of equipment else if (equipment_inventory.find(insert_item_id) != equipment_inventory.cend()) { // add the item world.room_at(x, y, z)->add_item_to_chest(equipment_inventory.find(insert_item_id)->second); } else // the item is a material that the user may have 1 or more { // create a new instance to add the the chest world.room_at(x, y, z)->add_item_to_chest(Craft::make(insert_item_id)); } // remove it from the player's inventory (this works for materials too) this->remove(insert_item_id); // You place the sword into the chest. return "You place the " + insert_item_id + " into the chest."; } string Character::take_from_chest(const string & take_item_id, World & world) { // if this room does not have a chest if (!world.room_at(x, y, z)->has_chest()) { return "There is no chest here."; } // if the chest was crafted by another faction if (world.room_at(x, y, z)->get_chest_faction_id() != this->faction_ID) { return "This chest has an unfamiliar lock."; } // if the player doesn't have the item if (!world.room_at(x, y, z)->chest_has(take_item_id)) { return "The chest does not contain " + U::get_article_for(take_item_id) + " " + take_item_id + "."; } this->add(world.room_at(x, y, z)->remove_from_chest(take_item_id)); // You place the sword into the chest. return "You take the " + take_item_id + " from the chest."; } string Character::look_inside_chest(const World & world) const { // validation within return world.room_at(x, y, z)->chest_contents(faction_ID); } string Character::construct_surface(const string & material_id, const string & surface_id, World & world) { if (world.room_at(x, y, z)->is_forest()) { return "You are in a forest and cannot build a structure here."; } // make sure the material can be used to construct a surface if (C::SURFACE_REQUIREMENTS.find(material_id) == C::SURFACE_REQUIREMENTS.end()) { return "You can't build a structure's surface out of " + material_id + "."; } // check if the surface already exists if (world.room_at(x, y, z)->has_surface(surface_id)) // bounds checking not necissary because the player is standing here { // test if construction is prevented by an intact wall or a pile of rubble if (world.room_at(x, y, z)->get_room_sides().find(surface_id)->second.is_rubble()) { return "A pile of rubble prevents construction."; } else // the surface is intact { return ((surface_id == C::CEILING || surface_id == C::FLOOR) ? "A " + surface_id + " already exists here." : // ceiling or floor U::capitalize(U::get_article_for(surface_id)) + " " + surface_id + " wall already exists here."); // any wall } } // check that the surface to construct is a wall, ceiling, or floor if (!U::contains(C::surface_ids, surface_id)) { return "Construct a wall, ceiling or floor."; } // if the surface is a ceiling, check that any intact wall exists if (surface_id == C::CEILING && // the user is constructing a ceiling !world.room_at(x, y, z)->has_standing_wall()) // the room does not have a wall { return "You need at least one standing wall to support a ceiling."; } // check that the player has the item if (this->material_inventory.find(material_id) == material_inventory.end()) { return "You don't have " + material_id + "."; } // check that the player has enough of the item to construct if (this->material_inventory.find(material_id)->second->amount < C::SURFACE_REQUIREMENTS.find(material_id)->second) { // "You need 5 wood to continue construction." return "You need " + U::to_string(C::SURFACE_REQUIREMENTS.find(material_id)->second) + " " + material_id + " to continue construction."; } // remove the number of materials from the player's inventory this->remove(material_id, C::SURFACE_REQUIREMENTS.find(material_id)->second); // create a Room_Side and add it to Room::room_side using the surface ID world.room_at(x, y, z)->add_surface(surface_id, material_id); // "You construct a stone floor/ceiling." OR "You construct a stone wall to your north." return "You construct a " + material_id + // you construct a [material] ((surface_id != C::CEILING && surface_id != C::FLOOR) ? " wall to your " + surface_id : // wall to your [direction] " " + surface_id); // ceiling/floor } string Character::construct_surface_with_door(const string & surface_material_id, const string & surface_id, const string & door_material_id, World & world) { // Part 1: validate that a surface can be constructed if (world.room_at(x, y, z)->is_forest()) { return "You are in a forest and cannot build a structure here."; } // make sure the material can be used to construct a surface if (C::SURFACE_REQUIREMENTS.find(surface_material_id) == C::SURFACE_REQUIREMENTS.end()) { return "You can't build a structure's surface out of " + surface_material_id + "."; } // check if the surface already exists if (world.room_at(x, y, z)->has_surface(surface_id)) // bounds checking not necissary because the player is standing here { // test if construction is prevented by an intact wall or a pile of rubble if (world.room_at(x, y, z)->get_room_sides().find(surface_id)->second.is_rubble()) { return "A pile of rubble prevents construction."; } else // the surface is intact { return ((surface_id == C::CEILING || surface_id == C::FLOOR) ? "A " + surface_id + " already exists here." : // ceiling or floor U::capitalize(U::get_article_for(surface_id)) + " " + surface_id + " wall already exists here."); // any wall } } // check that the surface to construct is a wall, ceiling, or floor if (!U::contains(C::surface_ids, surface_id)) { return "Construct a wall, ceiling or floor."; } // if the surface is a ceiling, check that any intact wall exists if (surface_id == C::CEILING && // the user is construction a ceiling !world.room_at(x, y, z)->has_standing_wall()) // the room does not have a wall { return "You need at least one standing wall to support a ceiling."; } // check that the player has the item if (this->material_inventory.find(surface_material_id) == material_inventory.end()) { return "You don't have " + surface_material_id + "."; } // check that the player has enough of the item to construct if (this->material_inventory.find(surface_material_id)->second->amount < C::SURFACE_REQUIREMENTS.find(surface_material_id)->second) { // "You need 5 wood to continue construction of the wall." return "You need " + U::to_string(C::SURFACE_REQUIREMENTS.find(surface_material_id)->second) + " " + surface_material_id + " to continue construction of the wall."; } // Part 2: Validate that a door can be constructed // check that there exist requirements for making a door of the specified type if (C::DOOR_REQUIREMENTS.find(door_material_id) == C::DOOR_REQUIREMENTS.cend()) { return "You cannot construct a door using " + door_material_id + "."; } // extract the amount of materials required to make a door of the specified type const unsigned DOOR_MATERIAL_COUNT_REQUIRED = C::DOOR_REQUIREMENTS.find(door_material_id)->second; // check that the player has the required materials if (!this->has(door_material_id, DOOR_MATERIAL_COUNT_REQUIRED)) { // "A stone door requires 5 stone." return "A " + door_material_id + " door requires " + U::to_string(DOOR_MATERIAL_COUNT_REQUIRED) + " " + door_material_id + "."; } // Part 3: Build the surface // remove the materials to construct the surface this->remove(surface_material_id, C::SURFACE_REQUIREMENTS.find(surface_material_id)->second); // add the surface to the room world.room_at(x, y, z)->add_surface(surface_id, surface_material_id); // Part 4: Add the door to the surface // remove the materials to construct the door this->remove(door_material_id, C::DOOR_REQUIREMENTS.find(door_material_id)->second); // add a door to the surface in the room world.room_at(x, y, z)->add_door(surface_id, C::MAX_SURFACE_HEALTH, door_material_id, this->faction_ID); // Part 5: the response // "You construct a stone floor with a stone hatch." OR "You construct a stone wall to your north with a branch door." return "You construct a " + surface_material_id + // you construct a [material] ((surface_id != C::CEILING && surface_id != C::FLOOR) ? " wall to your " + surface_id + " with a " + door_material_id + " door." : // wall to your [direction] " " + surface_id + " with a " + door_material_id + " hatch."); // ceiling/floor } string Character::attack_surface(const string & surface_ID, World & world) { // get this check out of the way if (surface_ID == C::CEILING || surface_ID == C::FLOOR) { return "Damaging a surface in a room above or below you is not supported yet."; } // verify we are working with a primary compass point if (surface_ID != C::NORTH && surface_ID != C::EAST && surface_ID != C::SOUTH && surface_ID != C::WEST) { return "Only n/s/e/w surfaces can be damaged at this time."; } // if the current room has an intact surface if (world.room_at(x, y, z)->is_standing_wall(surface_ID)) { // apply damage to the surface return world.room_at(x, y, z)->damage_surface(surface_ID, this->equipped_item); } // this room does not have an intact surface, the neighboring room might // find coordinates of neighboring room int new_x = x, new_y = y; { int new_z = 0; U::assign_movement_deltas(surface_ID, new_x, new_y, new_z); } // dz falls out of scope to prevent accidental use - we're only working in two dimensions right now // if the neighboring room has the opposite surface intact (our west wall borders next room's east wall) if (world.room_at(new_x, new_y, z)->is_standing_wall(C::opposite_surface_id.find(surface_ID)->second)) // deliberately using just "z" throughout this block { // inflict damage upon the surface return world.room_at(new_x, new_y, z)->damage_surface(C::opposite_surface_id.find(surface_ID)->second, this->equipped_item); } // neither room has an intact surface // test if both walls do not exist if (!world.room_at(x, y, z)->has_surface(surface_ID) && !world.room_at(new_x, new_y, z)->has_surface(C::opposite_surface_id.find(surface_ID)->second)) { return "There is no " + surface_ID + " wall here."; } else { // any surface that does exist is rubble, and at least one surface exists return "There is only rubble where a wall once was."; } } string Character::attack_door(const string & surface_ID, World & world) { // get this check out of the way if (surface_ID == C::CEILING || surface_ID == C::FLOOR) { return "Damaging above or below you is not supported yet."; } // verify we are working with a primary compass point if (surface_ID != C::NORTH && surface_ID != C::EAST && surface_ID != C::SOUTH && surface_ID != C::WEST) { return "Only doors in n/s/e/w surfaces can be damaged at this time."; } // if the current room has an intact surface with an intact door in it if (world.room_at(x, y, z)->has_surface(surface_ID) && world.room_at(x, y, z)->get_room_sides().find(surface_ID)->second.has_intact_door()) { // applied damage to the door return world.room_at(x, y, z)->damage_door(surface_ID, this->equipped_item); } // the current room does not have an intact door in the specified direction, // test if the next room has an intact door facing us. // find coordinates of target room int new_x = x, new_y = y; { int new_z = 0; U::assign_movement_deltas(surface_ID, new_x, new_y, new_z); } // new_z falls out of scope to prevent accidental use - we're only working in two dimensions right now // if the neighboring room has the opposite surface intact if (world.room_at(new_x, new_y, z)->is_standing_wall(C::opposite_surface_id.find(surface_ID)->second)) // deliberately using just "z" throughout this block { // inflict damaage upon the surface or door return world.room_at(new_x, new_y, z)->damage_door(C::opposite_surface_id.find(surface_ID)->second, this->equipped_item); } // this feedback might not be correct for all cases return "There is no door to your " + surface_ID; } string Character::attack_item(const string & target_ID, World & world) { // if the target isn't here if (!world.room_at(x, y, z)->contains_item(target_ID)) { return "There is no " + target_ID + " here."; } // if the user has an item equipped if (equipped_item != nullptr) { // if the attacking implement is not in the damage tables if (C::damage_tables.find(equipped_item->name) == C::damage_tables.cend()) { return "You can't do that with " + U::get_article_for(equipped_item->name) + " " + equipped_item->name + "."; } // extract the damage table for the attacking implement const map<string, int> damage_table = C::damage_tables.find(equipped_item->name)->second; // if the damage table does not have an entry for the target item ID if (damage_table.find(target_ID) == damage_table.cend()) { return "You can't do that to a " + target_ID + "."; } // damage the item, return a different message depending of if the item was destroyed or damaged if (world.room_at(x, y, z)->damage_item(target_ID, damage_table.find(target_ID)->second)) { return "You destroy the " + target_ID + " using your " + equipped_item->name + "."; } else { return "You damage the " + target_ID + " using your " + equipped_item->name + "."; } } else // the user does not have an item equipped, do a barehanded attack { // extract the damage table for a bare-handed attack const map<string, int> damage_table = C::damage_tables.find(C::ATTACK_COMMAND)->second; // if the damage table does not contain an entry for the target if (damage_table.find(target_ID) == damage_table.cend()) { return "You can't do that to a " + target_ID + "."; } // the damage table does contain an entry for the target if (world.room_at(x, y, z)->damage_item(target_ID, damage_table.find(target_ID)->second)) { return "You destroy the " + target_ID + " using your bare hands."; } else { return "You damage the " + target_ID + " using your bare hands."; } } } // movement info string Character::validate_movement(const int & cx, const int & cy, const int & cz, const string & direction_ID, const int & dx, const int & dy, const int & dz, const World & world) const { // determine if a character can move in a given direction (8 compass points, up, or down) // validate direction if (!U::contains(C::direction_ids, direction_ID)) { return direction_ID + " is not a direction."; } // if the player wants to move in a primary direction (n/e/s/w) if (direction_ID == C::NORTH || direction_ID == C::EAST || direction_ID == C::SOUTH || direction_ID == C::WEST) { // save the value of an attempt to move out of the current room string move_attempt = world.room_at(cx, cy, cz)->can_move_in_direction(direction_ID, faction_ID); if (move_attempt != C::GOOD_SIGNAL) { // the player can't move out of the current room return move_attempt; } // save the value of an attempt to move into the destination room move_attempt = world.room_at(cx + dx, cy + dy, cz)->can_move_in_direction(C::opposite_surface_id.find(direction_ID)->second, faction_ID); if (move_attempt != C::GOOD_SIGNAL) { // the player can't move into the destination return move_attempt; } } // if the player wants to move in a secondary direction (nw/ne/se/sw), condition is // none of four possible walls obstruct path AND an obstructing corner is not formed by adjacent rooms else if ( direction_ID == C::NORTH_WEST || direction_ID == C::NORTH_EAST || direction_ID == C::SOUTH_EAST || direction_ID == C::SOUTH_WEST) { const unique_ptr<Room>::pointer current_room = world.room_at(cx, cy, cz); const unique_ptr<Room>::pointer destination_room = world.room_at(cx + dx, cy + dy, cz); if (direction_ID == C::NORTH_WEST) { if (current_room->has_surface(C::NORTH) || current_room->has_surface(C::WEST) || destination_room->has_surface(C::SOUTH) || destination_room->has_surface(C::EAST) || (world.room_has_surface(cx - 1, cy, cz, C::WEST) && world.room_has_surface(cx, cy - 1, cz, C::NORTH)) || (world.room_has_surface(cx - 1, cy, cz, C::SOUTH) && world.room_has_surface(cx, cy - 1, cz, C::EAST))) { return "There are walls in your way to the " + direction_ID + "."; } } else if (direction_ID == C::NORTH_EAST) { if (current_room->has_surface(C::NORTH) || current_room->has_surface(C::EAST) || destination_room->has_surface(C::SOUTH) || destination_room->has_surface(C::WEST) || (world.room_has_surface(cx - 1, cy, cz, C::EAST) && world.room_has_surface(cx, cy + 1, cz, C::NORTH)) || (world.room_has_surface(cx - 1, cy, cz, C::SOUTH) && world.room_has_surface(cx, cy + 1, cz, C::WEST))) { return "There are walls in your way to the " + direction_ID + "."; } } else if (direction_ID == C::SOUTH_EAST) { if (current_room->has_surface(C::SOUTH) || current_room->has_surface(C::EAST) || destination_room->has_surface(C::NORTH) || destination_room->has_surface(C::WEST) || (world.room_has_surface(cx + 1, cy, cz, C::EAST) && world.room_has_surface(cx, cy + 1, cz, C::SOUTH)) || (world.room_has_surface(cx + 1, cy, cz, C::NORTH) && world.room_has_surface(cx, cy + 1, cz, C::WEST))) { return "There are walls in your way to the " + direction_ID + "."; } } else if (direction_ID == C::SOUTH_WEST) { if (current_room->has_surface(C::SOUTH) || current_room->has_surface(C::WEST) || destination_room->has_surface(C::NORTH) || destination_room->has_surface(C::EAST) || (world.room_has_surface(cx + 1, cy, cz, C::WEST) && world.room_has_surface(cx, cy - 1, cz, C::SOUTH)) || (world.room_has_surface(cx + 1, cy, cz, C::NORTH) && world.room_has_surface(cx, cy - 1, cz, C::EAST))) { return "There are walls in your way to the " + direction_ID + "."; } } } // condition for up is (opening AND ladder/stair/ramp) /*else if (direction_ID == C::UP || ) { if () { return "You [walk]/[climb] up to the [...]." //... ground level, second level, ... } } // condition for down is (ceiling) AND (ceiling has opening) else if (direction_ID == C::DOWN) { if () { return "You drop down."; // ... to [ground level]/[the second level] } }*/ // no issues were detected return C::GOOD_SIGNAL; } fix map update bug /* Jim Viebke Jeb 16 2015 */ #include "constants.h" #include "character.h" #include "world.h" Recipes Character::recipes; // Character constructor Character::Character(const string & name, const string & set_faction_ID) : name(name) { // if the faction is valid if (set_faction_ID == C::PC_FACTION_ID || set_faction_ID == C::NPC_NEUTRAL_FACTION_ID || set_faction_ID == C::NPC_HOSTILE_FACTION_ID) { // set the actor's faction this->faction_ID = set_faction_ID; } else // the faction is not valid { // Raise an error in the console cout << "ERROR: attempted to create character with invalid faction: [" << set_faction_ID << "]\n"; } } string Character::login(World & world) { // create a document to load the player's data xml_document user_data_xml; // load the player's data to user_data_xml user_data_xml.load_file((C::user_data_directory + "/" + this->name + ".xml").c_str()); // create holder values to save the coordinates from the file int loaded_x = -1, loaded_y = -1, loaded_z = -1; // load the three values from the node const xml_node location_node = user_data_xml.child(C::XML_USER_LOCATION.c_str()); // extract the attributes as well as the values for the attributes const xml_attribute x_attribute = location_node.attribute(string("x").c_str()); const xml_attribute y_attribute = location_node.attribute(string("y").c_str()); const xml_attribute z_attribute = location_node.attribute(string("z").c_str()); loaded_x = x_attribute.as_int(); loaded_y = y_attribute.as_int(); loaded_z = z_attribute.as_int(); // if any of the attributes are empty or the extracted values fail bounds-checking if (x_attribute.empty() || y_attribute.empty() || z_attribute.empty() || !U::bounds_check(loaded_x, loaded_y, loaded_z)) { // set the player to the default spawn this->x = C::DEFAULT_SPAWN_X; this->y = C::DEFAULT_SPAWN_Y; this->z = C::DEFAULT_SPAWN_Z; } else { // set the player to the valid loaded coordinates this->x = loaded_x; this->y = loaded_y; this->z = loaded_z; } // load the rooms around the player's spawn world.load_view_radius_around(x, y, name); // spawn in the player world.room_at(x, y, z)->add_actor(this->name); // select the level node const xml_node level_node = user_data_xml.child(C::XML_USER_LEVELS.c_str()); // select each level attribute const xml_attribute swordsmanship_level_attribute = level_node.attribute(C::XML_LEVEL_SWORDSMANSHIP.c_str()); const xml_attribute archery_level_attribute = level_node.attribute(C::XML_LEVEL_ARCHERY.c_str()); const xml_attribute forest_visibility_level_attribute = level_node.attribute(C::XML_LEVEL_FOREST_VISIBILITY.c_str()); const xml_attribute full_health_level_attribute = level_node.attribute(C::XML_LEVEL_HEALTH_MAX.c_str()); // if an attribute is non-empty, load its level value if (!swordsmanship_level_attribute.empty()) { this->set_swordsmanship_level(swordsmanship_level_attribute.as_int()); } if (!archery_level_attribute.empty()) { this->set_archery_level(archery_level_attribute.as_int()); } if (!forest_visibility_level_attribute.empty()) { this->set_forest_visibilty_level(forest_visibility_level_attribute.as_int()); } if (!full_health_level_attribute.empty()) { this->set_health_max(full_health_level_attribute.as_int()); } // select status node (just holds current_health at this time) const xml_node status_node = user_data_xml.child(C::XML_USER_STATUS.c_str()); // if current_health is non-empty, set current health const xml_attribute current_health_attribute = status_node.attribute(C::XML_USER_STATUS_CURRENT_HEALTH.c_str()); if (!current_health_attribute.empty()) { this->set_current_health(current_health_attribute.as_int()); } else // if current_health is empty, explicitly set current health to base maximum { this->set_current_health(C::FULL_HEALTH_MIN); } // for each item node of the equipment node for (const xml_node & equipment_node : user_data_xml.child(C::XML_USER_EQUIPMENT.c_str()).children()) { // create the item shared_ptr<Equipment> equipment = U::convert_to<Equipment>(Craft::make(equipment_node.name())); // extract the value of the health attribute and use it to set the item's health equipment->set_health(equipment_node.attribute(C::XML_ITEM_HEALTH.c_str()).as_int()); // add the item to the player's inventory equipment_inventory.insert(pair<string, shared_ptr<Equipment>>(equipment->name, equipment)); } // for each item in the material node for (const xml_node & material : user_data_xml.child(C::XML_USER_MATERIALS.c_str()).children()) { // use the name of the material node to create a new materail object shared_ptr<Material> item = U::convert_to<Material>(Craft::make(material.name())); // extract the amount from the item's attribute item->amount = material.attribute(C::XML_USER_MATERIAL_COUNT.c_str()).as_uint(); // add the item to the material inventory material_inventory.insert(pair<string, shared_ptr<Material>>(item->name, item)); } // notify success return "You have logged in to IslandMUD!"; } string Character::save() { // if an item is equipped, move it back to the player's inventory this->unequip(); // create a document to save the user's info xml_document user_data_xml; // create nodes to store user equipment and materials xml_node status_node = user_data_xml.append_child(C::XML_USER_STATUS.c_str()); xml_node location_node = user_data_xml.append_child(C::XML_USER_LOCATION.c_str()); xml_node level_node = user_data_xml.append_child(C::XML_USER_LEVELS.c_str()); xml_node equipment_node = user_data_xml.append_child(C::XML_USER_EQUIPMENT.c_str()); xml_node material_node = user_data_xml.append_child(C::XML_USER_MATERIALS.c_str()); /// add health attribute to status node status_node.append_attribute(C::XML_USER_STATUS_CURRENT_HEALTH.c_str()).set_value(this->current_health); // add x, y, and z attributes to the location node location_node.append_attribute(string("x").c_str()).set_value(this->x); location_node.append_attribute(string("y").c_str()).set_value(this->y); location_node.append_attribute(string("z").c_str()).set_value(this->z); // add each level to the location node level_node.append_attribute(C::XML_LEVEL_SWORDSMANSHIP.c_str()).set_value(this->swordsmanship_level); level_node.append_attribute(C::XML_LEVEL_ARCHERY.c_str()).set_value(this->archery_level); level_node.append_attribute(C::XML_LEVEL_FOREST_VISIBILITY.c_str()).set_value(this->forest_visibility_level); level_node.append_attribute(C::XML_LEVEL_HEALTH_MAX.c_str()).set_value(this->max_health); // for each piece of equipment in the user's inventory for (multimap<string, shared_ptr<Equipment>>::const_iterator it = equipment_inventory.cbegin(); it != equipment_inventory.cend(); ++it) { // save the equipment to a new node under the equipment node xml_node equipment = equipment_node.append_child(it->first.c_str()); // append a health attribute to the equipment node and set its value to the health of the equipment equipment.append_attribute(C::XML_ITEM_HEALTH.c_str()).set_value(it->second->get_health()); } // for each material in the user's inventory for (map<string, shared_ptr<Material>>::const_iterator it = material_inventory.cbegin(); it != material_inventory.cend(); ++it) { // save the material to a new node under the material node xml_node material = material_node.append_child(it->first.c_str()); // add an attribute called "count" with a value of material->count xml_attribute material_attribute = material.append_attribute(C::XML_USER_MATERIAL_COUNT.c_str()); material_attribute.set_value(it->second->amount); } // save the user_data to disk user_data_xml.save_file((C::user_data_directory + "/" + this->name + ".xml").c_str()); // returns an unused boolean return "Player info saved."; } // levels void Character::set_swordsmanship_level(const int & level_value) { if (level_value > C::SWORDSMANSHIP_LEVEL_MAX) { swordsmanship_level = C::SWORDSMANSHIP_LEVEL_MAX; } else if (level_value < C::SWORDSMANSHIP_LEVEL_MIN) { swordsmanship_level = C::SWORDSMANSHIP_LEVEL_MIN; } else { swordsmanship_level = level_value; } } void Character::set_archery_level(const int & level_value) { if (level_value > C::ARCHERY_LEVEL_MAX) { archery_level = C::ARCHERY_LEVEL_MAX; } else if (level_value < C::ARCHERY_LEVEL_MIN) { archery_level = C::ARCHERY_LEVEL_MIN; } else { archery_level = level_value; } } void Character::set_forest_visibilty_level(const int & level_value) { if (level_value > C::FOREST_VISIBILITY_LEVEL_MAX) { forest_visibility_level = C::FOREST_VISIBILITY_LEVEL_MAX; } else if (level_value < C::FOREST_VISIBILITY_LEVEL_MIN) { forest_visibility_level = C::FOREST_VISIBILITY_LEVEL_MIN; } else { forest_visibility_level = level_value; } } void Character::set_health_max(const int & level_value) { if (level_value > C::FULL_HEALTH_MAX) { max_health = C::FULL_HEALTH_MAX; } else if (level_value < C::FULL_HEALTH_MIN) { max_health = C::FULL_HEALTH_MIN; } else { max_health = level_value; } } // setters void Character::set_current_health(const int & health_value) { // don't call this until after the player's max_health has been set // otherwise the max_health field will still be at the default game constant if (health_value > max_health) { current_health = max_health; } else if (health_value <= C::HEALTH_MIN) // we can't set the user's health level to "die", so just use max { current_health = max_health; } else { current_health = health_value; } } // inventory information bool Character::has(const string & item_name, const unsigned & item_count) const { if (item_count == 1) // only one instance is required { return ((equipped_item != nullptr) ? equipped_item->name : "") == item_name || equipment_inventory.find(item_name) != equipment_inventory.cend() || material_inventory.find(item_name) != material_inventory.cend(); } else // more than one item is required { return (equipment_inventory.count(item_name) >= item_count) // the equipment inventory contains item_count of the required item || (material_inventory.find(item_name) != material_inventory.cend() && // the material invenory contains the required item material_inventory.find(item_name)->second->amount >= item_count); // AND the material exists in sufficient quantity } } bool Character::does_not_have(const string & item_name, const unsigned & item_count) const { return !this->has(item_name, item_count); } string Character::get_inventory() const // debugging { stringstream contents; for (multimap<string, shared_ptr<Equipment>>::const_iterator it = equipment_inventory.begin(); it != equipment_inventory.end(); ++it) { contents << it->second->name << " "; } for (map<string, shared_ptr<Material>>::const_iterator it = material_inventory.begin(); it != material_inventory.end(); ++it) { contents << it->second->name << ":" << it->second->amount << " "; } return contents.str(); } // inventory manipulation void Character::add(const shared_ptr<Item> & item) { // if the item is a material and is therefore stackable if (U::is<Material>(item)) { // check if the player already has an instance of the item in their material inventory if (this->material_inventory.find(item->name) != this->material_inventory.cend()) { // if so, increment the count this->material_inventory[item->name]->amount++; } else { // if not, give the player a new instance of the item this->material_inventory.insert(pair<string, shared_ptr<Material>>(item->name, U::convert_to<Material>(Craft::make(item->name)))); } } else // the item is not a material and is therefore an Equipment type { // insert the new item this->equipment_inventory.insert(pair<string, shared_ptr<Equipment>>(item->name, U::convert_to<Equipment>(item))); } } void Character::remove(const string & item_id, const unsigned & count) { // WARNING - for materials this assumes the player has [count] instances // if the player is holding the item if (this->equipped_item != nullptr && this->equipped_item->name == item_id) { this->equipped_item = nullptr; // erase the item } // remove or reduce the item in the player's inventory else if (equipment_inventory.find(item_id) != equipment_inventory.cend()) { for (unsigned i = 0; i < count; ++i) { equipment_inventory.erase(equipment_inventory.find(item_id)); } } else if (material_inventory.find(item_id) != material_inventory.cend()) // the item is present in the material inventory { material_inventory.find(item_id)->second->amount -= count; // decrement the material count in the player's inventory if (material_inventory.find(item_id)->second->amount < 1) { material_inventory.erase(material_inventory.find(item_id)); } } else { // the player does not have the item } } // actions Update_Messages Character::move(const string & direction_ID, World & world) { // movement deltas int dx = 0, dy = 0, dz = 0; U::assign_movement_deltas(direction_ID, dx, dy, dz); // validate movement deltas if (!U::bounds_check(x + dx, y + dy, z + dz)) { return Update_Messages("You can't go there."); } // copy the destination from disk to memory // world.load_room_to_world(x + dx, y + dy, z + dz); // test if the environment (structures) allow the player to move in a given direction const string validate_movement = this->validate_movement(x, y, z, direction_ID, dx, dy, dz, world); // if the validation failed for any reason if (validate_movement != C::GOOD_SIGNAL) { // return that reason movement validation failed return Update_Messages(validate_movement); } // the movement validated, load the radius for the destination world.load_view_radius_around(x + dx, y + dy, this->name); // maintain a list of users that are falling out of view that will also need a map update vector<string> additional_users_to_notify; // remove viewing ID from rooms leaving view if (direction_ID == C::NORTH || direction_ID == C::SOUTH) { // if the character is moving north, add the view distance to x to get the x of the row being removed // otherwise (moving south) remove the distance from x int rx = (direction_ID == C::NORTH) ? x + C::VIEW_DISTANCE : x - C::VIEW_DISTANCE; // each room to try unload from from x,(y-view) to (x,y+view) for (int ry = y - C::VIEW_DISTANCE; ry <= y + C::VIEW_DISTANCE; ++ry) { // Skip this room if it is not loaded. This occurs when a player moves diagonally, and both room unload passes overlap at the corner of the map. if (world.room_at(rx, ry, C::GROUND_INDEX) == nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); // save any users in the room // remove the character from the room's viewer list, trying to unload the room in the process world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); // bounds checking takes place in here } } else if (direction_ID == C::WEST || direction_ID == C::EAST) { // logic is the same as above, but in rotated axes (axes is plural of axis) const int ry = (direction_ID == C::WEST) ? y + C::VIEW_DISTANCE : y - C::VIEW_DISTANCE; for (int rx = x - C::VIEW_DISTANCE; rx <= x + C::VIEW_DISTANCE; ++rx) { if (world.room_at(rx, ry, C::GROUND_INDEX) == nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); } } else if (direction_ID == C::UP) { return Update_Messages("[moving up not available yet]"); } else if (direction_ID == C::DOWN) { return Update_Messages("[moving down not available yet]"); } else { /* The direction is a secondary compass direction. This means execution will alwways enter two of the four below blocks. Functionality here is the same as above. For documentation, scroll up. */ if (direction_ID == C::NORTH_WEST || direction_ID == C::NORTH_EAST) // moving north, parse south row { const int rx = x + C::VIEW_DISTANCE; for (int ry = y - C::VIEW_DISTANCE; ry <= y + C::VIEW_DISTANCE; ++ry) { if (world.room_at(rx, ry, C::GROUND_INDEX) == nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); } } if (direction_ID == C::NORTH_EAST || direction_ID == C::SOUTH_EAST) // moving east, parse west row { const int ry = y - C::VIEW_DISTANCE; for (int rx = x - C::VIEW_DISTANCE; rx <= x + C::VIEW_DISTANCE; ++rx) { if (world.room_at(rx, ry, C::GROUND_INDEX) == nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); } } if (direction_ID == C::SOUTH_EAST || direction_ID == C::SOUTH_WEST) // moving south, parse north row { const int rx = x - C::VIEW_DISTANCE; for (int ry = y - C::VIEW_DISTANCE; ry <= y + C::VIEW_DISTANCE; ++ry) { if (world.room_at(rx, ry, C::GROUND_INDEX) == nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); } } if (direction_ID == C::SOUTH_WEST || direction_ID == C::NORTH_WEST) // moving west, parse east row { const int ry = y + C::VIEW_DISTANCE; for (int rx = x - C::VIEW_DISTANCE; rx <= x + C::VIEW_DISTANCE; ++rx) { if (world.room_at(rx, ry, C::GROUND_INDEX) == nullptr) continue; U::append_b_to_a(additional_users_to_notify, world.room_at(rx, ry, C::GROUND_INDEX)->get_actor_ids()); world.remove_viewer_and_attempt_unload(rx, ry, C::GROUND_INDEX, this->name); } } } // the movement validated, remove character id from area world.room_at(x, y, z)->remove_actor(this->name); // test if the room can be unloaded if (world.is_unloadable(x, y, z)) // Why are we trying to unload the room we're moving out of? The player will still be able to see this. { world.unload_room(x, y, z); } // consider moving the above block to world.remove_character(x, y, z, id) // the check to unload could be in one place // update character internal coordinates x += dx; y += dy; z += dz; // add character id to new area using the new x and y coordinates world.room_at(x, y, z)->add_actor(this->name); // prepare responses Update_Messages updates("You move " + direction_ID + ".", // "Jeb arrives from the south [wielding an axe]." this->name + " arrives from the " + C::opposite_direction_id.find(direction_ID)->second + ((this->equipped_item == nullptr) ? "." : (" wielding " + U::get_article_for(equipped_item->name) + " " + equipped_item->name + ".")), true); // update required for all users in sight range // users that have fallen out of view won't recieve a map update unless we send one to them explicitly updates.additional_map_update_users = make_shared<vector<string>>(std::move(additional_users_to_notify)); return updates; } Update_Messages Character::craft(const string & craft_item_id, World & world) { // check for special case if (craft_item_id == C::CHEST_ID) { if (world.room_at(x, y, z)->has_chest()) { return Update_Messages("There is already a chest here."); } } // return if the recipe does not exist if (!Character::recipes.has_recipe_for(craft_item_id)) { return Update_Messages("There is no way to craft " + U::get_article_for(craft_item_id) + " " + craft_item_id + "."); } // get the recipe const Recipe recipe = Character::recipes.get_recipe(craft_item_id); // verify the conditions for the recipe are present for (map<string, int>::const_iterator it = recipe.inventory_need.cbegin(); it != recipe.inventory_need.cend(); ++it) { if (it->first != "" && !this->has(it->first, it->second)) { return Update_Messages(U::get_article_for(craft_item_id) + " " + craft_item_id + " requires " + ((it->second == 1) ? U::get_article_for(it->first) : U::to_string(it->second)) + " " + it->first); } } for (map<string, int>::const_iterator it = recipe.inventory_remove.cbegin(); it != recipe.inventory_remove.cend(); ++it) { if (it->first != "" && !this->has(it->first, it->second)) { return Update_Messages(U::get_article_for(craft_item_id) + " " + craft_item_id + " uses " + ((it->second == 1) ? U::get_article_for(it->first) : U::to_string(it->second)) + " " + it->first); } } for (map<string, int>::const_iterator it = recipe.local_need.cbegin(); it != recipe.local_need.cend(); ++it) { if (it->first != "" && !world.room_at(x, y, z)->contains_item(it->first)) { return Update_Messages(U::get_article_for(craft_item_id) + " " + craft_item_id + " requires " + ((it->second == 1) ? "a" : U::to_string(it->second)) + " nearby " + it->first); } } for (map<string, int>::const_iterator it = recipe.local_remove.cbegin(); it != recipe.local_remove.cend(); ++it) { if (it->first != "" && !world.room_at(x, y, z)->contains_item(it->first)) { return Update_Messages(U::get_article_for(craft_item_id) + " " + craft_item_id + " uses " + ((it->second == 1) ? "a" : U::to_string(it->second)) + " nearby " + it->first); } } // remove ingredients from inventory for (map<string, int>::const_iterator it = recipe.inventory_remove.cbegin(); it != recipe.inventory_remove.cend(); ++it) { this->remove(it->first, it->second); // ID, count } // remove ingredients from area for (map<string, int>::const_iterator it = recipe.local_remove.cbegin(); it != recipe.local_remove.cend(); ++it) { this->remove(it->first, it->second); // ID, count } stringstream player_update, room_update; // for each item to be given to the player for (map<string, int>::const_iterator it = recipe.yields.cbegin(); it != recipe.yields.cend(); ++it) { // for as many times as the item is to be given to the player for (int i = 0; i < it->second; ++i) { // special test cast for chests if (craft_item_id == C::CHEST_ID) { // add a chest to the room world.room_at(x, y, z)->add_chest(this->faction_ID); continue; } // craft the item shared_ptr<Item> item = Craft::make(it->first); // if the item can be carried if (item->is_takable()) { // add the item to the player's inventory this->add(item); } else // the item can not be taken { // add the item to the room world.room_at(x, y, z)->add_item(item); } } player_update << "You craft "; room_update << this->name << " crafts "; if (it->second > 1) // ... 3 arrowheads. { player_update << it->second << " " << U::get_plural_for(it->first) << "."; room_update << it->second << " " << U::get_plural_for(it->first) << "."; } else // ... an arrowhead. { player_update << U::get_article_for(it->first) << " " << it->first << "."; room_update << U::get_article_for(it->first) << " " << it->first << "."; } } return Update_Messages(player_update.str(), room_update.str()); } Update_Messages Character::take(const string & take_item_id, World & world) { // check if the item is not in the player's vicinity if (!world.room_at(x, y, z)->contains_item(take_item_id)) { return Update_Messages("There is no " + take_item_id + " here."); } // check if the item is not takable if (!world.room_at(x, y, z)->get_contents().find(take_item_id)->second->is_takable()) { // return failure return Update_Messages("You can't take the " + take_item_id + "."); } // the item is takable this->add(world.room_at(x, y, z)->get_contents().find(take_item_id)->second); // copy the item to the player world.room_at(x, y, z)->remove_item(take_item_id); // remove the item from the world return Update_Messages("You take " + U::get_article_for(take_item_id) + " " + take_item_id + ".", this->name + " takes " + U::get_article_for(take_item_id) + " " + take_item_id + "."); } string Character::drop(const string & drop_item_id, World & world) { // if the player is holding the item specified if (this->equipped_item != nullptr && this->equipped_item->name == drop_item_id) { // add the item to the world world.room_at(x, y, z)->add_item(this->equipped_item); } else { if (!this->has(drop_item_id)) // if the player does not have the item specified { // the item does not exist in the player's inventory return "You don't have " + U::get_article_for(drop_item_id) + " " + drop_item_id + " to drop."; } // add the item to the world world.room_at(x, y, z)->add_item( (equipment_inventory.find(drop_item_id) != equipment_inventory.end()) ? U::convert_to<Item>( // determine where to get the item from equipment_inventory.find(drop_item_id)->second) : // upcast one of the items to an <Item> type material_inventory.find(drop_item_id)->second ); } // remove item this->remove(drop_item_id); // success reply return "You drop " + U::get_article_for(drop_item_id) + " " + drop_item_id + "."; } Update_Messages Character::equip(const string & item_ID) { /* You ready your [item_id]. You replace your [item_id] with a(n) [item_id]; */ // if the player does not have the item specified if (!this->has(item_ID)) { return Update_Messages("You do not have " + U::get_article_for(item_ID) + " " + item_ID + " to equip."); } // the player has at least one instance of the item, check if the player does not have another one to equip if (equipment_inventory.find(item_ID) == equipment_inventory.cend() && material_inventory.find(item_ID) == material_inventory.cend()) { return Update_Messages("You are holding " + U::get_article_for(item_ID) + " " + item_ID + " and don't have another one to equip."); } // create a stringstream to accumulate feedback stringstream user_update; stringstream room_update; // the player does have the item to equip, test if an item is already equipped if (this->equipped_item != nullptr) { user_update << "You replace your " << equipped_item->name << " with "; room_update << this->name << " replaces " << U::get_article_for(equipped_item->name) << " " << equipped_item->name << " with "; // save the existing the item to the player's inventory this->add(equipped_item); // erase the existing item this->equipped_item = nullptr; } // set the equipped item to the specified item from whichever inventory we find it in if (this->equipment_inventory.find(item_ID) != equipment_inventory.cend()) { equipped_item = equipment_inventory.find(item_ID)->second; } else { equipped_item = material_inventory.find(item_ID)->second; } // remove or reduce the item in the player's inventory if (equipment_inventory.find(item_ID) != equipment_inventory.cend()) { equipment_inventory.erase(equipment_inventory.find(item_ID)); } else if (material_inventory.find(item_ID) != material_inventory.cend()) // the item is present in the material inventory { material_inventory.find(item_ID)->second->amount--; // decrement the material count in the player's inventory if (material_inventory.find(item_ID)->second->amount < 1) { material_inventory.erase(material_inventory.find(item_ID)); } } // if the stringstream is empty (no item was previously equipped) if (user_update.str().length() == 0) { return Update_Messages( "You equip your " + item_ID + ".", this->name + " equips " + U::get_article_for(item_ID) + " " + item_ID + "."); } else { // complete and return the response message user_update << U::get_article_for(equipped_item->name) << " " << equipped_item->name << "."; room_update << U::get_article_for(equipped_item->name) << " " << equipped_item->name << "."; return Update_Messages(user_update.str(), room_update.str()); } } Update_Messages Character::unequip() { // test if no item is equipped if (this->equipped_item == nullptr) { return Update_Messages("You aren't holding anything."); } // save the ID of the currently equipped item const string item_ID = equipped_item->name; // save the existing the item to the player's inventory this->add(equipped_item); // reset the currently equipped item equipped_item = nullptr; return Update_Messages("You put your " + item_ID + " away.", this->name + " lowers the " + item_ID + "."); } string Character::add_to_chest(const string & insert_item_id, World & world) { // if this room does not have a chest if (!world.room_at(x, y, z)->has_chest()) { return "There is no chest here."; } // if the chest was crafted by another faction if (world.room_at(x, y, z)->get_chest_faction_id() != this->faction_ID) { return "This chest has an unfamiliar lock."; } // if the player doesn't have the item if (!this->has(insert_item_id)) { return "You don't have " + U::get_article_for(insert_item_id) + " " + insert_item_id + "."; } // if the item is equipped if (equipped_item != nullptr && equipped_item->name == insert_item_id) { world.room_at(x, y, z)->add_item_to_chest(equipped_item); } // if the item is a piece of equipment else if (equipment_inventory.find(insert_item_id) != equipment_inventory.cend()) { // add the item world.room_at(x, y, z)->add_item_to_chest(equipment_inventory.find(insert_item_id)->second); } else // the item is a material that the user may have 1 or more { // create a new instance to add the the chest world.room_at(x, y, z)->add_item_to_chest(Craft::make(insert_item_id)); } // remove it from the player's inventory (this works for materials too) this->remove(insert_item_id); // You place the sword into the chest. return "You place the " + insert_item_id + " into the chest."; } string Character::take_from_chest(const string & take_item_id, World & world) { // if this room does not have a chest if (!world.room_at(x, y, z)->has_chest()) { return "There is no chest here."; } // if the chest was crafted by another faction if (world.room_at(x, y, z)->get_chest_faction_id() != this->faction_ID) { return "This chest has an unfamiliar lock."; } // if the player doesn't have the item if (!world.room_at(x, y, z)->chest_has(take_item_id)) { return "The chest does not contain " + U::get_article_for(take_item_id) + " " + take_item_id + "."; } this->add(world.room_at(x, y, z)->remove_from_chest(take_item_id)); // You place the sword into the chest. return "You take the " + take_item_id + " from the chest."; } string Character::look_inside_chest(const World & world) const { // validation within return world.room_at(x, y, z)->chest_contents(faction_ID); } string Character::construct_surface(const string & material_id, const string & surface_id, World & world) { if (world.room_at(x, y, z)->is_forest()) { return "You are in a forest and cannot build a structure here."; } // make sure the material can be used to construct a surface if (C::SURFACE_REQUIREMENTS.find(material_id) == C::SURFACE_REQUIREMENTS.end()) { return "You can't build a structure's surface out of " + material_id + "."; } // check if the surface already exists if (world.room_at(x, y, z)->has_surface(surface_id)) // bounds checking not necissary because the player is standing here { // test if construction is prevented by an intact wall or a pile of rubble if (world.room_at(x, y, z)->get_room_sides().find(surface_id)->second.is_rubble()) { return "A pile of rubble prevents construction."; } else // the surface is intact { return ((surface_id == C::CEILING || surface_id == C::FLOOR) ? "A " + surface_id + " already exists here." : // ceiling or floor U::capitalize(U::get_article_for(surface_id)) + " " + surface_id + " wall already exists here."); // any wall } } // check that the surface to construct is a wall, ceiling, or floor if (!U::contains(C::surface_ids, surface_id)) { return "Construct a wall, ceiling or floor."; } // if the surface is a ceiling, check that any intact wall exists if (surface_id == C::CEILING && // the user is constructing a ceiling !world.room_at(x, y, z)->has_standing_wall()) // the room does not have a wall { return "You need at least one standing wall to support a ceiling."; } // check that the player has the item if (this->material_inventory.find(material_id) == material_inventory.end()) { return "You don't have " + material_id + "."; } // check that the player has enough of the item to construct if (this->material_inventory.find(material_id)->second->amount < C::SURFACE_REQUIREMENTS.find(material_id)->second) { // "You need 5 wood to continue construction." return "You need " + U::to_string(C::SURFACE_REQUIREMENTS.find(material_id)->second) + " " + material_id + " to continue construction."; } // remove the number of materials from the player's inventory this->remove(material_id, C::SURFACE_REQUIREMENTS.find(material_id)->second); // create a Room_Side and add it to Room::room_side using the surface ID world.room_at(x, y, z)->add_surface(surface_id, material_id); // "You construct a stone floor/ceiling." OR "You construct a stone wall to your north." return "You construct a " + material_id + // you construct a [material] ((surface_id != C::CEILING && surface_id != C::FLOOR) ? " wall to your " + surface_id : // wall to your [direction] " " + surface_id); // ceiling/floor } string Character::construct_surface_with_door(const string & surface_material_id, const string & surface_id, const string & door_material_id, World & world) { // Part 1: validate that a surface can be constructed if (world.room_at(x, y, z)->is_forest()) { return "You are in a forest and cannot build a structure here."; } // make sure the material can be used to construct a surface if (C::SURFACE_REQUIREMENTS.find(surface_material_id) == C::SURFACE_REQUIREMENTS.end()) { return "You can't build a structure's surface out of " + surface_material_id + "."; } // check if the surface already exists if (world.room_at(x, y, z)->has_surface(surface_id)) // bounds checking not necissary because the player is standing here { // test if construction is prevented by an intact wall or a pile of rubble if (world.room_at(x, y, z)->get_room_sides().find(surface_id)->second.is_rubble()) { return "A pile of rubble prevents construction."; } else // the surface is intact { return ((surface_id == C::CEILING || surface_id == C::FLOOR) ? "A " + surface_id + " already exists here." : // ceiling or floor U::capitalize(U::get_article_for(surface_id)) + " " + surface_id + " wall already exists here."); // any wall } } // check that the surface to construct is a wall, ceiling, or floor if (!U::contains(C::surface_ids, surface_id)) { return "Construct a wall, ceiling or floor."; } // if the surface is a ceiling, check that any intact wall exists if (surface_id == C::CEILING && // the user is construction a ceiling !world.room_at(x, y, z)->has_standing_wall()) // the room does not have a wall { return "You need at least one standing wall to support a ceiling."; } // check that the player has the item if (this->material_inventory.find(surface_material_id) == material_inventory.end()) { return "You don't have " + surface_material_id + "."; } // check that the player has enough of the item to construct if (this->material_inventory.find(surface_material_id)->second->amount < C::SURFACE_REQUIREMENTS.find(surface_material_id)->second) { // "You need 5 wood to continue construction of the wall." return "You need " + U::to_string(C::SURFACE_REQUIREMENTS.find(surface_material_id)->second) + " " + surface_material_id + " to continue construction of the wall."; } // Part 2: Validate that a door can be constructed // check that there exist requirements for making a door of the specified type if (C::DOOR_REQUIREMENTS.find(door_material_id) == C::DOOR_REQUIREMENTS.cend()) { return "You cannot construct a door using " + door_material_id + "."; } // extract the amount of materials required to make a door of the specified type const unsigned DOOR_MATERIAL_COUNT_REQUIRED = C::DOOR_REQUIREMENTS.find(door_material_id)->second; // check that the player has the required materials if (!this->has(door_material_id, DOOR_MATERIAL_COUNT_REQUIRED)) { // "A stone door requires 5 stone." return "A " + door_material_id + " door requires " + U::to_string(DOOR_MATERIAL_COUNT_REQUIRED) + " " + door_material_id + "."; } // Part 3: Build the surface // remove the materials to construct the surface this->remove(surface_material_id, C::SURFACE_REQUIREMENTS.find(surface_material_id)->second); // add the surface to the room world.room_at(x, y, z)->add_surface(surface_id, surface_material_id); // Part 4: Add the door to the surface // remove the materials to construct the door this->remove(door_material_id, C::DOOR_REQUIREMENTS.find(door_material_id)->second); // add a door to the surface in the room world.room_at(x, y, z)->add_door(surface_id, C::MAX_SURFACE_HEALTH, door_material_id, this->faction_ID); // Part 5: the response // "You construct a stone floor with a stone hatch." OR "You construct a stone wall to your north with a branch door." return "You construct a " + surface_material_id + // you construct a [material] ((surface_id != C::CEILING && surface_id != C::FLOOR) ? " wall to your " + surface_id + " with a " + door_material_id + " door." : // wall to your [direction] " " + surface_id + " with a " + door_material_id + " hatch."); // ceiling/floor } string Character::attack_surface(const string & surface_ID, World & world) { // get this check out of the way if (surface_ID == C::CEILING || surface_ID == C::FLOOR) { return "Damaging a surface in a room above or below you is not supported yet."; } // verify we are working with a primary compass point if (surface_ID != C::NORTH && surface_ID != C::EAST && surface_ID != C::SOUTH && surface_ID != C::WEST) { return "Only n/s/e/w surfaces can be damaged at this time."; } // if the current room has an intact surface if (world.room_at(x, y, z)->is_standing_wall(surface_ID)) { // apply damage to the surface return world.room_at(x, y, z)->damage_surface(surface_ID, this->equipped_item); } // this room does not have an intact surface, the neighboring room might // find coordinates of neighboring room int new_x = x, new_y = y; { int new_z = 0; U::assign_movement_deltas(surface_ID, new_x, new_y, new_z); } // dz falls out of scope to prevent accidental use - we're only working in two dimensions right now // if the neighboring room has the opposite surface intact (our west wall borders next room's east wall) if (world.room_at(new_x, new_y, z)->is_standing_wall(C::opposite_surface_id.find(surface_ID)->second)) // deliberately using just "z" throughout this block { // inflict damage upon the surface return world.room_at(new_x, new_y, z)->damage_surface(C::opposite_surface_id.find(surface_ID)->second, this->equipped_item); } // neither room has an intact surface // test if both walls do not exist if (!world.room_at(x, y, z)->has_surface(surface_ID) && !world.room_at(new_x, new_y, z)->has_surface(C::opposite_surface_id.find(surface_ID)->second)) { return "There is no " + surface_ID + " wall here."; } else { // any surface that does exist is rubble, and at least one surface exists return "There is only rubble where a wall once was."; } } string Character::attack_door(const string & surface_ID, World & world) { // get this check out of the way if (surface_ID == C::CEILING || surface_ID == C::FLOOR) { return "Damaging above or below you is not supported yet."; } // verify we are working with a primary compass point if (surface_ID != C::NORTH && surface_ID != C::EAST && surface_ID != C::SOUTH && surface_ID != C::WEST) { return "Only doors in n/s/e/w surfaces can be damaged at this time."; } // if the current room has an intact surface with an intact door in it if (world.room_at(x, y, z)->has_surface(surface_ID) && world.room_at(x, y, z)->get_room_sides().find(surface_ID)->second.has_intact_door()) { // applied damage to the door return world.room_at(x, y, z)->damage_door(surface_ID, this->equipped_item); } // the current room does not have an intact door in the specified direction, // test if the next room has an intact door facing us. // find coordinates of target room int new_x = x, new_y = y; { int new_z = 0; U::assign_movement_deltas(surface_ID, new_x, new_y, new_z); } // new_z falls out of scope to prevent accidental use - we're only working in two dimensions right now // if the neighboring room has the opposite surface intact if (world.room_at(new_x, new_y, z)->is_standing_wall(C::opposite_surface_id.find(surface_ID)->second)) // deliberately using just "z" throughout this block { // inflict damaage upon the surface or door return world.room_at(new_x, new_y, z)->damage_door(C::opposite_surface_id.find(surface_ID)->second, this->equipped_item); } // this feedback might not be correct for all cases return "There is no door to your " + surface_ID; } string Character::attack_item(const string & target_ID, World & world) { // if the target isn't here if (!world.room_at(x, y, z)->contains_item(target_ID)) { return "There is no " + target_ID + " here."; } // if the user has an item equipped if (equipped_item != nullptr) { // if the attacking implement is not in the damage tables if (C::damage_tables.find(equipped_item->name) == C::damage_tables.cend()) { return "You can't do that with " + U::get_article_for(equipped_item->name) + " " + equipped_item->name + "."; } // extract the damage table for the attacking implement const map<string, int> damage_table = C::damage_tables.find(equipped_item->name)->second; // if the damage table does not have an entry for the target item ID if (damage_table.find(target_ID) == damage_table.cend()) { return "You can't do that to a " + target_ID + "."; } // damage the item, return a different message depending of if the item was destroyed or damaged if (world.room_at(x, y, z)->damage_item(target_ID, damage_table.find(target_ID)->second)) { return "You destroy the " + target_ID + " using your " + equipped_item->name + "."; } else { return "You damage the " + target_ID + " using your " + equipped_item->name + "."; } } else // the user does not have an item equipped, do a barehanded attack { // extract the damage table for a bare-handed attack const map<string, int> damage_table = C::damage_tables.find(C::ATTACK_COMMAND)->second; // if the damage table does not contain an entry for the target if (damage_table.find(target_ID) == damage_table.cend()) { return "You can't do that to a " + target_ID + "."; } // the damage table does contain an entry for the target if (world.room_at(x, y, z)->damage_item(target_ID, damage_table.find(target_ID)->second)) { return "You destroy the " + target_ID + " using your bare hands."; } else { return "You damage the " + target_ID + " using your bare hands."; } } } // movement info string Character::validate_movement(const int & cx, const int & cy, const int & cz, const string & direction_ID, const int & dx, const int & dy, const int & dz, const World & world) const { // determine if a character can move in a given direction (8 compass points, up, or down) // validate direction if (!U::contains(C::direction_ids, direction_ID)) { return direction_ID + " is not a direction."; } // if the player wants to move in a primary direction (n/e/s/w) if (direction_ID == C::NORTH || direction_ID == C::EAST || direction_ID == C::SOUTH || direction_ID == C::WEST) { // save the value of an attempt to move out of the current room string move_attempt = world.room_at(cx, cy, cz)->can_move_in_direction(direction_ID, faction_ID); if (move_attempt != C::GOOD_SIGNAL) { // the player can't move out of the current room return move_attempt; } // save the value of an attempt to move into the destination room move_attempt = world.room_at(cx + dx, cy + dy, cz)->can_move_in_direction(C::opposite_surface_id.find(direction_ID)->second, faction_ID); if (move_attempt != C::GOOD_SIGNAL) { // the player can't move into the destination return move_attempt; } } // if the player wants to move in a secondary direction (nw/ne/se/sw), condition is // none of four possible walls obstruct path AND an obstructing corner is not formed by adjacent rooms else if ( direction_ID == C::NORTH_WEST || direction_ID == C::NORTH_EAST || direction_ID == C::SOUTH_EAST || direction_ID == C::SOUTH_WEST) { const unique_ptr<Room>::pointer current_room = world.room_at(cx, cy, cz); const unique_ptr<Room>::pointer destination_room = world.room_at(cx + dx, cy + dy, cz); if (direction_ID == C::NORTH_WEST) { if (current_room->has_surface(C::NORTH) || current_room->has_surface(C::WEST) || destination_room->has_surface(C::SOUTH) || destination_room->has_surface(C::EAST) || (world.room_has_surface(cx - 1, cy, cz, C::WEST) && world.room_has_surface(cx, cy - 1, cz, C::NORTH)) || (world.room_has_surface(cx - 1, cy, cz, C::SOUTH) && world.room_has_surface(cx, cy - 1, cz, C::EAST))) { return "There are walls in your way to the " + direction_ID + "."; } } else if (direction_ID == C::NORTH_EAST) { if (current_room->has_surface(C::NORTH) || current_room->has_surface(C::EAST) || destination_room->has_surface(C::SOUTH) || destination_room->has_surface(C::WEST) || (world.room_has_surface(cx - 1, cy, cz, C::EAST) && world.room_has_surface(cx, cy + 1, cz, C::NORTH)) || (world.room_has_surface(cx - 1, cy, cz, C::SOUTH) && world.room_has_surface(cx, cy + 1, cz, C::WEST))) { return "There are walls in your way to the " + direction_ID + "."; } } else if (direction_ID == C::SOUTH_EAST) { if (current_room->has_surface(C::SOUTH) || current_room->has_surface(C::EAST) || destination_room->has_surface(C::NORTH) || destination_room->has_surface(C::WEST) || (world.room_has_surface(cx + 1, cy, cz, C::EAST) && world.room_has_surface(cx, cy + 1, cz, C::SOUTH)) || (world.room_has_surface(cx + 1, cy, cz, C::NORTH) && world.room_has_surface(cx, cy + 1, cz, C::WEST))) { return "There are walls in your way to the " + direction_ID + "."; } } else if (direction_ID == C::SOUTH_WEST) { if (current_room->has_surface(C::SOUTH) || current_room->has_surface(C::WEST) || destination_room->has_surface(C::NORTH) || destination_room->has_surface(C::EAST) || (world.room_has_surface(cx + 1, cy, cz, C::WEST) && world.room_has_surface(cx, cy - 1, cz, C::SOUTH)) || (world.room_has_surface(cx + 1, cy, cz, C::NORTH) && world.room_has_surface(cx, cy - 1, cz, C::EAST))) { return "There are walls in your way to the " + direction_ID + "."; } } } // condition for up is (opening AND ladder/stair/ramp) /*else if (direction_ID == C::UP || ) { if () { return "You [walk]/[climb] up to the [...]." //... ground level, second level, ... } } // condition for down is (ceiling) AND (ceiling has opening) else if (direction_ID == C::DOWN) { if () { return "You drop down."; // ... to [ground level]/[the second level] } }*/ // no issues were detected return C::GOOD_SIGNAL; }
#include "rbridge.h" #include <boost/foreach.hpp> #include "../JASP-Common/base64.h" #include "../JASP-Common/lib_json/json.h" #include "../JASP-Common/sharedmemory.h" RInside *rbridge_rinside; DataSet *rbridge_dataSet; using namespace std; RCallback rbridge_runCallback; boost::function<std::string(const std::string &)> rbridge_fileNameSource; boost::function<std::string()> rbridge_stateFileSource; Rcpp::DataFrame rbridge_readDataSetSEXP(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns); Rcpp::DataFrame rbridge_readDataSetHeaderSEXP(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns); std::map<std::string, Column::ColumnType> rbridge_marshallSEXPs(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns); SEXP rbridge_callbackSEXP(SEXP results); SEXP rbridge_requestTempFileNameSEXP(SEXP extension); SEXP rbridge_requestStateFileNameSEXP(); int rbridge_callback(SEXP results); Rcpp::DataFrame rbridge_readDataSet(const std::map<std::string, Column::ColumnType> &columns); Rcpp::DataFrame rbridge_readDataSetHeader(const std::map<std::string, Column::ColumnType> &columns); void rbridge_makeFactor(Rcpp::IntegerVector &v, const std::vector<std::string> &levels, bool ordinal = false); void rbridge_makeFactor(Rcpp::IntegerVector &v, const Labels &levels, bool ordinal = false); void rbridge_init() { rbridge_dataSet = NULL; rbridge_runCallback = NULL; rbridge_fileNameSource = NULL; rbridge_stateFileSource = NULL; rbridge_rinside = new RInside(); RInside &rInside = rbridge_rinside->instance(); rInside[".readDatasetToEndNative"] = Rcpp::InternalFunction(&rbridge_readDataSetSEXP); rInside[".readDataSetHeaderNative"] = Rcpp::InternalFunction(&rbridge_readDataSetHeaderSEXP); rInside[".callbackNative"] = Rcpp::InternalFunction(&rbridge_callbackSEXP); rInside[".requestTempFileNameNative"] = Rcpp::InternalFunction(&rbridge_requestTempFileNameSEXP); rInside[".requestStateFileNameNative"] = Rcpp::InternalFunction(&rbridge_requestStateFileNameSEXP); rInside[".baseCitation"] = "Love, J., Selker, R., Verhagen, J., Smira, M., Wild, A., Marsman, M., Gronau, Q., Morey, R., Rouder, J. & Wagenmakers, E. J. (2014). JASP (Version 0.5)[Computer software]."; rInside["jasp.analyses"] = Rcpp::List(); rInside.parseEvalQNT("suppressPackageStartupMessages(library(\"RJSONIO\"))"); rInside.parseEvalQNT("suppressPackageStartupMessages(library(\"JASP\"))"); rInside.parseEvalQNT("suppressPackageStartupMessages(library(\"methods\"))"); } void rbridge_setDataSet(DataSet *dataSet) { rbridge_dataSet = dataSet; } void rbridge_setFileNameSource(boost::function<string (const string &)> source) { rbridge_fileNameSource = source; } void rbridge_setStateFileSource(boost::function<string ()> source) { rbridge_stateFileSource = source; } SEXP rbridge_requestTempFileNameSEXP(SEXP extension) { if (rbridge_fileNameSource == NULL) return R_NilValue; string extensionAsString = Rcpp::as<string>(extension); return Rcpp::CharacterVector(rbridge_fileNameSource(extensionAsString)); } SEXP rbridge_requestStateFileNameSEXP() { if (rbridge_stateFileSource == NULL) return R_NilValue; return Rcpp::CharacterVector(rbridge_stateFileSource()); } string rbridge_run(const string &name, const string &options, const string &perform, int ppi, RCallback callback) { SEXP results; rbridge_runCallback = callback; RInside &rInside = rbridge_rinside->instance(); rInside["name"] = name; rInside["options.as.json.string"] = options; rInside["perform"] = perform; rInside[".ppi"] = ppi; rInside.parseEval("run(name=name, options.as.json.string=options.as.json.string, perform)", results); rbridge_runCallback = NULL; return Rcpp::as<string>(results); } Rcpp::DataFrame rbridge_readDataSet(const std::map<std::string, Column::ColumnType> &columns) { if (rbridge_dataSet == NULL) { std::cout << "rbridge dataset not set!\n"; std::cout.flush(); } Rcpp::List list(columns.size()); Rcpp::CharacterVector columnNames; int colNo = 0; typedef pair<const string, Column::ColumnType> ColumnInfo; BOOST_FOREACH(const ColumnInfo &columnInfo, columns) { (void)columns; string columnName = columnInfo.first; string base64 = Base64::encode("X", columnName, Base64::RVarEncoding); columnNames.push_back(base64); Column &column = rbridge_dataSet->columns().get(columnName); Column::ColumnType columnType = column.columnType(); Column::ColumnType requestedType = columnInfo.second; if (requestedType == Column::ColumnTypeUnknown) requestedType = columnType; int rowCount = column.rowCount(); int rowNo = 0; if (requestedType == Column::ColumnTypeScale) { if (columnType == Column::ColumnTypeScale) { Rcpp::NumericVector v(rowCount); BOOST_FOREACH(double value, column.AsDoubles) { (void)column; v[rowNo++] = value; } list[colNo++] = v; } else if (columnType == Column::ColumnTypeOrdinal || columnType == Column::ColumnTypeNominal) { Rcpp::IntegerVector v(rowCount); BOOST_FOREACH(int value, column.AsInts) { (void)column; v[rowNo++] = column.actualFromRaw(value); } list[colNo++] = v; } else // columnType == Column::ColumnTypeNominalText { Rcpp::IntegerVector v(rowCount); BOOST_FOREACH(int value, column.AsInts) { (void)column; if (value == INT_MIN) v[rowNo++] = INT_MIN; else v[rowNo++] = value + 1; } rbridge_makeFactor(v, column.labels()); list[colNo++] = v; } } else // if (requestedType != Column::ColumnTypeScale) { bool ordinal = (requestedType == Column::ColumnTypeOrdinal); Rcpp::IntegerVector v(rowCount); if (columnType != Column::ColumnTypeScale) { BOOST_FOREACH(int value, column.AsInts) { (void)column; if (value == INT_MIN) v[rowNo++] = INT_MIN; else v[rowNo++] = value + 1; } rbridge_makeFactor(v, column.labels(), ordinal); } else { // scale to nominal or ordinal (doesn't really make sense, but we have to do something) set<int> uniqueValues; BOOST_FOREACH(double value, column.AsDoubles) { (void)column; int intValue = (int)(value * 1000); uniqueValues.insert(intValue); } int index = 0; map<int, int> valueToIndex; vector<string> labels; BOOST_FOREACH(int value, uniqueValues) { (void)uniqueValues; valueToIndex[value] = index; stringstream ss; ss << ((double)value / 1000); labels.push_back(ss.str()); index++; } BOOST_FOREACH(double value, column.AsDoubles) { (void)column; if (isnan(value)) v[rowNo++] = INT_MIN; else { v[rowNo++] = valueToIndex[(int)(value * 1000)] + 1; } } rbridge_makeFactor(v, labels, ordinal); } list[colNo++] = v; } } list.attr("names") = columnNames; Rcpp::DataFrame dataFrame = Rcpp::DataFrame(list); return dataFrame; } Rcpp::DataFrame rbridge_readDataSetHeader(const std::map<string, Column::ColumnType> &columns) { if (rbridge_dataSet == NULL) { std::cout << "rbridge dataset not set!\n"; std::cout.flush(); } Rcpp::List list(columns.size()); Rcpp::CharacterVector columnNames; int colNo = 0; typedef pair<const string, Column::ColumnType> ColumnInfo; BOOST_FOREACH(const ColumnInfo &columnInfo, columns) { (void)columns; string columnName = columnInfo.first; string base64 = Base64::encode("X", columnName, Base64::RVarEncoding); columnNames.push_back(base64); Columns &columns = rbridge_dataSet->columns(); Column &column = columns.get(columnName); Column::ColumnType columnType = column.columnType(); Column::ColumnType requestedType = columnInfo.second; if (requestedType == Column::ColumnTypeUnknown) requestedType = columnType; if (requestedType == Column::ColumnTypeScale) { if (columnType == Column::ColumnTypeScale) { list[colNo++] = Rcpp::NumericVector(0); } else if (columnType == Column::ColumnTypeOrdinal || columnType == Column::ColumnTypeNominal) { list[colNo++] = Rcpp::IntegerVector(0); } else { Rcpp::IntegerVector v(0); rbridge_makeFactor(v, column.labels()); list[colNo++] = v; } } else { bool ordinal = (requestedType == Column::ColumnTypeOrdinal); Rcpp::IntegerVector v(0); rbridge_makeFactor(v, column.labels(), ordinal); list[colNo++] = v; } } list.attr("names") = columnNames; Rcpp::DataFrame dataFrame = Rcpp::DataFrame(list); return dataFrame; } void rbridge_makeFactor(Rcpp::IntegerVector &v, const Labels &levels, bool ordinal) { Rcpp::CharacterVector labels; if (levels.size() == 0) { labels.push_back("."); } else { for (int i = 0; i < levels.size(); i++) labels.push_back(levels.at(i).text()); } v.attr("levels") = labels; vector<string> cla55; if (ordinal) cla55.push_back("ordered"); cla55.push_back("factor"); v.attr("class") = cla55; } void rbridge_makeFactor(Rcpp::IntegerVector &v, const std::vector<string> &levels, bool ordinal) { v.attr("levels") = levels; vector<string> cla55; if (ordinal) cla55.push_back("ordered"); cla55.push_back("factor"); v.attr("class") = cla55; } int rbridge_callback(SEXP results) { if (rbridge_runCallback != NULL) { if (Rf_isNull(results)) { return rbridge_runCallback("null"); } else { return rbridge_runCallback(Rcpp::as<string>(results)); } } else { return 0; } } std::map<string, Column::ColumnType> rbridge_marshallSEXPs(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns) { map<string, Column::ColumnType> columnsRequested; if (Rf_isLogical(allColumns) && Rcpp::as<bool>(allColumns)) { BOOST_FOREACH(const Column &column, rbridge_dataSet->columns()) columnsRequested[column.name()] = Column::ColumnTypeUnknown; } if (Rf_isString(columns)) { vector<string> temp = Rcpp::as<vector<string> >(columns); for (int i = 0; i < temp.size(); i++) columnsRequested[temp.at(i)] = Column::ColumnTypeUnknown; } if (Rf_isString(columnsAsNumeric)) { vector<string> temp = Rcpp::as<vector<string> >(columnsAsNumeric); for (int i = 0; i < temp.size(); i++) columnsRequested[temp.at(i)] = Column::ColumnTypeScale; } if (Rf_isString(columnsAsOrdinal)) { vector<string> temp = Rcpp::as<vector<string> >(columnsAsOrdinal); for (int i = 0; i < temp.size(); i++) columnsRequested[temp.at(i)] = Column::ColumnTypeOrdinal; } if (Rf_isString(columnsAsNominal)) { vector<string> temp = Rcpp::as<vector<string> >(columnsAsNominal); for (int i = 0; i < temp.size(); i++) columnsRequested[temp.at(i)] = Column::ColumnTypeNominal; } return columnsRequested; } SEXP rbridge_callbackSEXP(SEXP results) { Rcpp::NumericVector control(1); control[0] = rbridge_callback(results); return control; } Rcpp::DataFrame rbridge_readDataSetSEXP(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns) { map<string, Column::ColumnType> columnsRequested = rbridge_marshallSEXPs(columns, columnsAsNumeric, columnsAsOrdinal, columnsAsNominal, allColumns); return rbridge_readDataSet(columnsRequested); } Rcpp::DataFrame rbridge_readDataSetHeaderSEXP(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns) { map<string, Column::ColumnType> columnsRequested = rbridge_marshallSEXPs(columns, columnsAsNumeric, columnsAsOrdinal, columnsAsNominal, allColumns); return rbridge_readDataSetHeader(columnsRequested); } Fix to scale to nominal marshalling #include "rbridge.h" #include <boost/foreach.hpp> #include "../JASP-Common/base64.h" #include "../JASP-Common/lib_json/json.h" #include "../JASP-Common/sharedmemory.h" RInside *rbridge_rinside; DataSet *rbridge_dataSet; using namespace std; RCallback rbridge_runCallback; boost::function<std::string(const std::string &)> rbridge_fileNameSource; boost::function<std::string()> rbridge_stateFileSource; Rcpp::DataFrame rbridge_readDataSetSEXP(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns); Rcpp::DataFrame rbridge_readDataSetHeaderSEXP(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns); std::map<std::string, Column::ColumnType> rbridge_marshallSEXPs(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns); SEXP rbridge_callbackSEXP(SEXP results); SEXP rbridge_requestTempFileNameSEXP(SEXP extension); SEXP rbridge_requestStateFileNameSEXP(); int rbridge_callback(SEXP results); Rcpp::DataFrame rbridge_readDataSet(const std::map<std::string, Column::ColumnType> &columns); Rcpp::DataFrame rbridge_readDataSetHeader(const std::map<std::string, Column::ColumnType> &columns); void rbridge_makeFactor(Rcpp::IntegerVector &v, const std::vector<std::string> &levels, bool ordinal = false); void rbridge_makeFactor(Rcpp::IntegerVector &v, const Labels &levels, bool ordinal = false); void rbridge_init() { rbridge_dataSet = NULL; rbridge_runCallback = NULL; rbridge_fileNameSource = NULL; rbridge_stateFileSource = NULL; rbridge_rinside = new RInside(); RInside &rInside = rbridge_rinside->instance(); rInside[".readDatasetToEndNative"] = Rcpp::InternalFunction(&rbridge_readDataSetSEXP); rInside[".readDataSetHeaderNative"] = Rcpp::InternalFunction(&rbridge_readDataSetHeaderSEXP); rInside[".callbackNative"] = Rcpp::InternalFunction(&rbridge_callbackSEXP); rInside[".requestTempFileNameNative"] = Rcpp::InternalFunction(&rbridge_requestTempFileNameSEXP); rInside[".requestStateFileNameNative"] = Rcpp::InternalFunction(&rbridge_requestStateFileNameSEXP); rInside[".baseCitation"] = "Love, J., Selker, R., Verhagen, J., Smira, M., Wild, A., Marsman, M., Gronau, Q., Morey, R., Rouder, J. & Wagenmakers, E. J. (2014). JASP (Version 0.5)[Computer software]."; rInside["jasp.analyses"] = Rcpp::List(); rInside.parseEvalQNT("suppressPackageStartupMessages(library(\"RJSONIO\"))"); rInside.parseEvalQNT("suppressPackageStartupMessages(library(\"JASP\"))"); rInside.parseEvalQNT("suppressPackageStartupMessages(library(\"methods\"))"); } void rbridge_setDataSet(DataSet *dataSet) { rbridge_dataSet = dataSet; } void rbridge_setFileNameSource(boost::function<string (const string &)> source) { rbridge_fileNameSource = source; } void rbridge_setStateFileSource(boost::function<string ()> source) { rbridge_stateFileSource = source; } SEXP rbridge_requestTempFileNameSEXP(SEXP extension) { if (rbridge_fileNameSource == NULL) return R_NilValue; string extensionAsString = Rcpp::as<string>(extension); return Rcpp::CharacterVector(rbridge_fileNameSource(extensionAsString)); } SEXP rbridge_requestStateFileNameSEXP() { if (rbridge_stateFileSource == NULL) return R_NilValue; return Rcpp::CharacterVector(rbridge_stateFileSource()); } string rbridge_run(const string &name, const string &options, const string &perform, int ppi, RCallback callback) { SEXP results; rbridge_runCallback = callback; RInside &rInside = rbridge_rinside->instance(); rInside["name"] = name; rInside["options.as.json.string"] = options; rInside["perform"] = perform; rInside[".ppi"] = ppi; rInside.parseEval("run(name=name, options.as.json.string=options.as.json.string, perform)", results); rbridge_runCallback = NULL; return Rcpp::as<string>(results); } Rcpp::DataFrame rbridge_readDataSet(const std::map<std::string, Column::ColumnType> &columns) { if (rbridge_dataSet == NULL) { std::cout << "rbridge dataset not set!\n"; std::cout.flush(); } Rcpp::List list(columns.size()); Rcpp::CharacterVector columnNames; int colNo = 0; typedef pair<const string, Column::ColumnType> ColumnInfo; BOOST_FOREACH(const ColumnInfo &columnInfo, columns) { (void)columns; string columnName = columnInfo.first; string base64 = Base64::encode("X", columnName, Base64::RVarEncoding); columnNames.push_back(base64); Column &column = rbridge_dataSet->columns().get(columnName); Column::ColumnType columnType = column.columnType(); Column::ColumnType requestedType = columnInfo.second; if (requestedType == Column::ColumnTypeUnknown) requestedType = columnType; int rowCount = column.rowCount(); int rowNo = 0; if (requestedType == Column::ColumnTypeScale) { if (columnType == Column::ColumnTypeScale) { Rcpp::NumericVector v(rowCount); BOOST_FOREACH(double value, column.AsDoubles) { (void)column; v[rowNo++] = value; } list[colNo++] = v; } else if (columnType == Column::ColumnTypeOrdinal || columnType == Column::ColumnTypeNominal) { Rcpp::IntegerVector v(rowCount); BOOST_FOREACH(int value, column.AsInts) { (void)column; v[rowNo++] = column.actualFromRaw(value); } list[colNo++] = v; } else // columnType == Column::ColumnTypeNominalText { Rcpp::IntegerVector v(rowCount); BOOST_FOREACH(int value, column.AsInts) { (void)column; if (value == INT_MIN) v[rowNo++] = INT_MIN; else v[rowNo++] = value + 1; } rbridge_makeFactor(v, column.labels()); list[colNo++] = v; } } else // if (requestedType != Column::ColumnTypeScale) { bool ordinal = (requestedType == Column::ColumnTypeOrdinal); Rcpp::IntegerVector v(rowCount); if (columnType != Column::ColumnTypeScale) { BOOST_FOREACH(int value, column.AsInts) { (void)column; if (value == INT_MIN) v[rowNo++] = INT_MIN; else v[rowNo++] = value + 1; } rbridge_makeFactor(v, column.labels(), ordinal); } else { // scale to nominal or ordinal (doesn't really make sense, but we have to do something) set<int> uniqueValues; BOOST_FOREACH(double value, column.AsDoubles) { (void)column; if (isnan(value)) continue; int intValue = (int)(value * 1000); uniqueValues.insert(intValue); } int index = 0; map<int, int> valueToIndex; vector<string> labels; BOOST_FOREACH(int value, uniqueValues) { (void)value; (void)uniqueValues; valueToIndex[value] = index; stringstream ss; ss << ((double)value / 1000); labels.push_back(ss.str()); index++; } BOOST_FOREACH(double value, column.AsDoubles) { (void)column; if (isnan(value)) v[rowNo++] = INT_MIN; else { v[rowNo++] = valueToIndex[(int)(value * 1000)] + 1; } } rbridge_makeFactor(v, labels, ordinal); } list[colNo++] = v; } } list.attr("names") = columnNames; Rcpp::DataFrame dataFrame = Rcpp::DataFrame(list); return dataFrame; } Rcpp::DataFrame rbridge_readDataSetHeader(const std::map<string, Column::ColumnType> &columns) { if (rbridge_dataSet == NULL) { std::cout << "rbridge dataset not set!\n"; std::cout.flush(); } Rcpp::List list(columns.size()); Rcpp::CharacterVector columnNames; int colNo = 0; typedef pair<const string, Column::ColumnType> ColumnInfo; BOOST_FOREACH(const ColumnInfo &columnInfo, columns) { (void)columns; string columnName = columnInfo.first; string base64 = Base64::encode("X", columnName, Base64::RVarEncoding); columnNames.push_back(base64); Columns &columns = rbridge_dataSet->columns(); Column &column = columns.get(columnName); Column::ColumnType columnType = column.columnType(); Column::ColumnType requestedType = columnInfo.second; if (requestedType == Column::ColumnTypeUnknown) requestedType = columnType; if (requestedType == Column::ColumnTypeScale) { if (columnType == Column::ColumnTypeScale) { list[colNo++] = Rcpp::NumericVector(0); } else if (columnType == Column::ColumnTypeOrdinal || columnType == Column::ColumnTypeNominal) { list[colNo++] = Rcpp::IntegerVector(0); } else { Rcpp::IntegerVector v(0); rbridge_makeFactor(v, column.labels()); list[colNo++] = v; } } else { bool ordinal = (requestedType == Column::ColumnTypeOrdinal); Rcpp::IntegerVector v(0); rbridge_makeFactor(v, column.labels(), ordinal); list[colNo++] = v; } } list.attr("names") = columnNames; Rcpp::DataFrame dataFrame = Rcpp::DataFrame(list); return dataFrame; } void rbridge_makeFactor(Rcpp::IntegerVector &v, const Labels &levels, bool ordinal) { Rcpp::CharacterVector labels; if (levels.size() == 0) { labels.push_back("."); } else { for (int i = 0; i < levels.size(); i++) labels.push_back(levels.at(i).text()); } v.attr("levels") = labels; vector<string> cla55; if (ordinal) cla55.push_back("ordered"); cla55.push_back("factor"); v.attr("class") = cla55; } void rbridge_makeFactor(Rcpp::IntegerVector &v, const std::vector<string> &levels, bool ordinal) { v.attr("levels") = levels; vector<string> cla55; if (ordinal) cla55.push_back("ordered"); cla55.push_back("factor"); v.attr("class") = cla55; } int rbridge_callback(SEXP results) { if (rbridge_runCallback != NULL) { if (Rf_isNull(results)) { return rbridge_runCallback("null"); } else { return rbridge_runCallback(Rcpp::as<string>(results)); } } else { return 0; } } std::map<string, Column::ColumnType> rbridge_marshallSEXPs(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns) { map<string, Column::ColumnType> columnsRequested; if (Rf_isLogical(allColumns) && Rcpp::as<bool>(allColumns)) { BOOST_FOREACH(const Column &column, rbridge_dataSet->columns()) columnsRequested[column.name()] = Column::ColumnTypeUnknown; } if (Rf_isString(columns)) { vector<string> temp = Rcpp::as<vector<string> >(columns); for (int i = 0; i < temp.size(); i++) columnsRequested[temp.at(i)] = Column::ColumnTypeUnknown; } if (Rf_isString(columnsAsNumeric)) { vector<string> temp = Rcpp::as<vector<string> >(columnsAsNumeric); for (int i = 0; i < temp.size(); i++) columnsRequested[temp.at(i)] = Column::ColumnTypeScale; } if (Rf_isString(columnsAsOrdinal)) { vector<string> temp = Rcpp::as<vector<string> >(columnsAsOrdinal); for (int i = 0; i < temp.size(); i++) columnsRequested[temp.at(i)] = Column::ColumnTypeOrdinal; } if (Rf_isString(columnsAsNominal)) { vector<string> temp = Rcpp::as<vector<string> >(columnsAsNominal); for (int i = 0; i < temp.size(); i++) columnsRequested[temp.at(i)] = Column::ColumnTypeNominal; } return columnsRequested; } SEXP rbridge_callbackSEXP(SEXP results) { Rcpp::NumericVector control(1); control[0] = rbridge_callback(results); return control; } Rcpp::DataFrame rbridge_readDataSetSEXP(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns) { map<string, Column::ColumnType> columnsRequested = rbridge_marshallSEXPs(columns, columnsAsNumeric, columnsAsOrdinal, columnsAsNominal, allColumns); return rbridge_readDataSet(columnsRequested); } Rcpp::DataFrame rbridge_readDataSetHeaderSEXP(SEXP columns, SEXP columnsAsNumeric, SEXP columnsAsOrdinal, SEXP columnsAsNominal, SEXP allColumns) { map<string, Column::ColumnType> columnsRequested = rbridge_marshallSEXPs(columns, columnsAsNumeric, columnsAsOrdinal, columnsAsNominal, allColumns); return rbridge_readDataSetHeader(columnsRequested); }
#include "fast++.hpp" std::string remove_first_last(std::string val, std::string charlist) { if (val.empty()) return val; uint_t p0 = 0, n = val.size(); if (charlist.find_first_of(val[0]) != charlist.npos) { ++p0; --n; } if (n > 0 && charlist.find_first_of(val[val.size()-1]) != charlist.npos) { --n; } return val.substr(p0, n); } template <typename T> bool parse_value_impl(const std::string& val, T& out) { return from_string(val, out); } bool parse_value_impl(const std::string& val, std::string& out) { out = remove_first_last(val, "\'\""); return true; } bool parse_value_impl(std::string val, parallel_choice& out) { val = trim(tolower(remove_first_last(val, "\'\""))); if (val == "none" || val.empty()) { out = parallel_choice::none; } else if (val == "sources") { out = parallel_choice::sources; } else if (val == "models") { out = parallel_choice::models; } else { error("unknown parallelization choice '", val, "'"); error("must be one of 'none', sources' or 'models'"); return false; } return true; } template <typename T> bool parse_value_impl(std::string val, vec<1,T>& out) { if (val.empty()) return true; val = remove_first_last(val, "[]"); vec1s spl = split(val, ","); out.resize(spl.size()); for (uint_t i : range(spl)) { if (!parse_value_impl(spl[i], out[i])) { return false; } } return true; } template <typename T> bool parse_value(const std::string& key, const std::string& val, T& out) { if (!parse_value_impl(val, out)) { error("could not parse value of parameter ", key); note("could not convert '", val, "' into ", pretty_type_t(T)); return false; } return true; } bool read_params(options_t& opts, input_state_t& state, const std::string& filename) { std::ifstream in(filename); if (!in.is_open()) { error("could not open parameter file '", filename, "'"); return false; } opts.cosmo = astro::get_cosmo("std"); vec1s unparsed_key, unparsed_val; auto do_parse = [&](const std::string& key, const std::string& val) { #define PARSE_OPTION(name) if (key == #name) { return parse_value(key, val, opts.name); } #define PARSE_OPTION_RENAME(opt, name) if (key == name) { return parse_value(key, val, opts.opt); } PARSE_OPTION(catalog) PARSE_OPTION(ab_zeropoint) PARSE_OPTION(filters_res) PARSE_OPTION_RENAME(filters_format, "filter_format") PARSE_OPTION(temp_err_file) PARSE_OPTION(name_zphot) PARSE_OPTION(spectrum) PARSE_OPTION(auto_scale) PARSE_OPTION(output_dir) PARSE_OPTION(output_file) PARSE_OPTION(n_sim) PARSE_OPTION(c_interval) PARSE_OPTION(best_fit) PARSE_OPTION(library_dir) PARSE_OPTION(library) PARSE_OPTION(resolution) PARSE_OPTION_RENAME(name_imf, "imf") PARSE_OPTION_RENAME(name_sfh, "sfh") PARSE_OPTION(dust_law) PARSE_OPTION_RENAME(dust_noll_eb, "e_b") PARSE_OPTION_RENAME(dust_noll_delta, "delta") PARSE_OPTION(my_sfh) PARSE_OPTION(log_tau_min) PARSE_OPTION(log_tau_max) PARSE_OPTION(log_tau_step) PARSE_OPTION(log_age_min) PARSE_OPTION(log_age_max) PARSE_OPTION(log_age_step) PARSE_OPTION(no_max_age) PARSE_OPTION(z_min) PARSE_OPTION(z_max) PARSE_OPTION(z_step) PARSE_OPTION(z_step_type) PARSE_OPTION(a_v_min) PARSE_OPTION(a_v_max) PARSE_OPTION(a_v_step) PARSE_OPTION(metal) PARSE_OPTION_RENAME(cosmo.H0, "h0") PARSE_OPTION_RENAME(cosmo.wm, "omega_m") PARSE_OPTION_RENAME(cosmo.wL, "omega_l") PARSE_OPTION(save_chi_grid) // Not in original FAST PARSE_OPTION(force_zphot) PARSE_OPTION(best_at_zphot) PARSE_OPTION(zphot_conf) PARSE_OPTION(save_sim) PARSE_OPTION(best_from_sim) PARSE_OPTION(no_cache) PARSE_OPTION(parallel) PARSE_OPTION(n_thread) PARSE_OPTION(max_queued_fits) PARSE_OPTION(verbose) PARSE_OPTION(sfr_avg) PARSE_OPTION(intrinsic_best_fit) PARSE_OPTION(best_sfhs) PARSE_OPTION(sfh_output_step) PARSE_OPTION(sfh_output) PARSE_OPTION(use_lir) PARSE_OPTION(output_columns) PARSE_OPTION(custom_sfh) PARSE_OPTION(custom_sfh_step) PARSE_OPTION(custom_params) #undef PARSE_OPTION #undef PARSE_OPTION_RENAME // warning("unknown parameter '", key, "'"); unparsed_key.push_back(key); unparsed_val.push_back(val); return true; }; // Read the parameter file line by line std::string line; while (std::getline(in, line)) { line = trim(line); if (line.empty() || line[0] == '#') continue; // Remove inline comments auto cp = line.find_first_of('#'); if (cp != line.npos) { line = line.substr(0, cp); } // Split on '=' and parse key and values auto eqp = line.find_first_of('='); if (eqp == line.npos) { error("ill formed line in configuration file"); note(line); return false; } std::string key = tolower(trim(line.substr(0, eqp))); std::string val = trim(line.substr(eqp+1)); if (!do_parse(key, val)) { return false; } } // Initialize custom parameter grid opts.custom_params_min = opts.custom_params_max = opts.custom_params_step = replicate(fnan, opts.custom_params.size()); // Check unparsed key/value pairs for additional options we couldn't parse before for (uint_t p : range(unparsed_key)) { std::string key = unparsed_key[p]; std::string val = unparsed_val[p]; bool read = false; // Read custom grid parameters for (uint_t c : range(opts.custom_params)) { if (key == tolower(opts.custom_params[c])+"_min") { read = true; if (!parse_value(key, val, opts.custom_params_min[c])) { return false; } } else if (key == tolower(opts.custom_params[c])+"_max") { read = true; if (!parse_value(key, val, opts.custom_params_max[c])) { return false; } } else if (key == tolower(opts.custom_params[c])+"_step") { read = true; if (!parse_value(key, val, opts.custom_params_step[c])) { return false; } } } if (!read) { warning("unknown parameter '", toupper(key), "'"); } } // Create output directory, if it doesn't exist if (!opts.output_dir.empty()) { opts.output_dir = file::directorize(opts.output_dir); if (!file::mkdir(opts.output_dir)) { error("could not create output directory '", opts.output_dir, "'"); error("make sure you have the proper rights"); return false; } } if (opts.output_file.empty()) opts.output_file = opts.catalog; // Now check for the consistency of the output and make corrections when necessary if (opts.sfr_avg < 0 || !is_finite(opts.sfr_avg)) { opts.sfr_avg = 0; } auto check_sfh_step = [&](float& step, std::string which) { if (step < 0) { error("step of ", which, " SFH cannot be negative"); return false; } else if (step > 1e4) { error("step of ", which, " SFH must be given in Myr"); error("(you gave ", step, " which is larger than the age of the Universe)"); return false; } step *= 1e6; // convert to yr return true; }; check_sfh_step(opts.sfh_output_step, "output"); check_sfh_step(opts.custom_sfh_step, "custom"); if (opts.verbose) { if (opts.sfr_avg == 0) { note("using instantaneous SFRs"); } else { note("averaging SFRs over ", opts.sfr_avg, " Myr"); } } opts.sfh_output = tolower(opts.sfh_output); if (!(opts.sfh_output == "sfr" || opts.sfh_output == "mass")) { error("'SFH_OUTPUT' must be either 'sfr' or 'mass'"); return false; } opts.sfr_avg *= 1e6; if (opts.intrinsic_best_fit && !opts.best_fit) { warning("'INTRINSIC_BEST_FIT' has no effect if 'BEST_SIM' is not set to 1"); } if (opts.best_sfhs && !opts.my_sfh.empty()) { warning("cannot output best fit SFH when using custom SFH"); opts.best_sfhs = false; } if (opts.best_from_sim && opts.n_sim == 0) { error("cannot use the option 'BEST_FROM_SIM' if simulations are not enabled (set N_SIM > 0)"); return false; } if (!opts.my_sfh.empty()) { opts.sfh = sfh_type::single; } else if (!opts.custom_sfh.empty()) { opts.sfh = sfh_type::custom; } else { opts.sfh = sfh_type::gridded; } if (opts.spectrum.empty()) { opts.auto_scale = false; } if (opts.parallel != parallel_choice::none && opts.n_thread <= 1) { warning("parallelization is enabled but the number of thread is set to zero"); warning("parallelization will be disabled unless you set N_THREAD > 1"); opts.parallel = parallel_choice::none; } if (opts.best_at_zphot && opts.force_zphot) { note("BEST_AT_ZPHOT=1 is automatically true if FORCE_ZPHOT=1, " "so you do not have to specify both"); } for (double c : opts.c_interval) { if (abs(c - 68.0) > 0.01 && abs(c - 95.0) > 0.01 && abs(c - 99.0) > 0.01) { error("confidence interval must be one of 68, 95 or 99% (got ", c, ")"); return false; } } if (opts.n_sim != 0) { state.conf_interval = 0.5*(1.0 - opts.c_interval/100.0); inplace_sort(opts.c_interval); vec1f cint = state.conf_interval; state.conf_interval.clear(); for (float c : cint) { state.conf_interval.push_back(c); state.conf_interval.push_back(1.0 - c); } } else { opts.c_interval.clear(); } if (opts.force_zphot || abs(opts.zphot_conf) < 0.1) { opts.zphot_conf = fnan; } else { opts.zphot_conf /= 100.0; } if (opts.metal.empty()) { if (opts.library == "bc03" || opts.library == "ma05") { opts.metal = {0.02}; } else if (opts.library == "co11") { opts.metal = {0.019}; } else { // Unknown stellar library, simply guess what could be a good default value... opts.metal = {0.02}; } } if (opts.output_columns.empty()) { // Default columns to display switch (opts.sfh) { case sfh_type::gridded: opts.output_columns = { "id", "z", "ltau", "metal", "lage", "Av", "lmass", "lsfr", "lssfr", "la2t", "chi2" }; break; case sfh_type::single: opts.output_columns = { "id", "z", "metal", "lage", "Av", "lmass", "lsfr", "lssfr", "chi2" }; break; case sfh_type::custom: opts.output_columns = { "id", "z", "metal", "lage", "Av", "lmass", "lsfr", "lssfr" }; append(opts.output_columns, opts.custom_params); opts.output_columns.push_back("chi2"); break; } } if (!opts.custom_params.empty()) { // Add tau to the custom parameter grid if the user used it uint_t idp = where_first(tolower(opts.custom_params) == "log_tau"); if (idp != npos) { opts.custom_params_min[idp] = opts.log_tau_min; opts.custom_params_max[idp] = opts.log_tau_max; opts.custom_params_step[idp] = opts.log_tau_step; } } if (!opts.custom_sfh.empty()) { // Check that all parameters in the grid have been properly defined bool bad = false; for (uint_t c : range(opts.custom_params)) { if (!is_finite(opts.custom_params_min[c])) { error("missing ", toupper(opts.custom_params[c])+"_MIN value"); bad = true; } if (!is_finite(opts.custom_params_max[c])) { error("missing ", toupper(opts.custom_params[c])+"_MAX value"); bad = true; } if (!is_finite(opts.custom_params_step[c])) { error("missing ", toupper(opts.custom_params[c])+"_STEP value"); bad = true; } } if (bad) return false; } // Use the default 'share' directory if nothing is provided if (opts.filters_res.empty()) { opts.filters_res = std::string(FASTPP_SHARE_DIR)+"/FILTER.RES.latest"; } if (opts.temp_err_file.empty()) { opts.temp_err_file = std::string(FASTPP_SHARE_DIR)+"/TEMPLATE_ERROR.fast.v0.2"; } if (opts.library_dir.empty()) { opts.library_dir = std::string(FASTPP_SHARE_DIR)+"/libraries/"; } else { opts.library_dir = file::directorize(opts.library_dir); } return true; } bool read_header(const std::string& filename, vec1s& header) { std::ifstream in(filename); std::string line; while (std::getline(in, line)) { line = trim(line); // Find the first non-empty comment line if (line.empty() || line[0] != '#') continue; line = trim(line.substr(1)); if (line.empty()) continue; // Split column names by spaces header = split_any_of(line, " \t\n\r"); return true; } error("missing header in '", filename, "'"); note("the header line must start with # and list the column names"); return false; } bool read_filters(const options_t& opts, input_state_t& state) { if (opts.filters_res.empty()) { // No filter, maybe just trying to fit a spectrum? return true; } if (opts.verbose) { note("reading filters from '", opts.filters_res, "'"); } std::ifstream in(opts.filters_res); if (!in.is_open()) { error("could not open filter file '", opts.filters_res, "'"); return false; } // Read the required filters from the database std::string line; uint_t l = 0; fast_filter_t filt; vec1u idcat, idfil; bool doread = false; uint_t ntotfilt = 0; while (std::getline(in, line)) { ++l; line = trim(line); if (line.empty()) continue; vec1s spl = split_any_of(line, " \t\n\r"); if (spl.size() > 3) { // Start of a new filter // Save the previous one, if any if (!filt.wl.empty()) { state.filters.push_back(filt); // Cleanup for next filter filt.wl.clear(); filt.tr.clear(); filt.id = npos; } ++ntotfilt; filt.id = ntotfilt; // Determine if this filter is used in the catalog vec1u idused = where(state.no_filt == filt.id); if (!idused.empty()) { // It is there, keep the ID aside for later sorting append(idcat, idused); append(idfil, replicate(state.filters.size(), idused.size())); doread = true; } else { // If not, discard its values doread = false; } } else if (doread && spl.size() == 3) { // Reading the filter response float wl, tr; if (!from_string(spl[1], wl) || !from_string(spl[2], tr)) { error("could not parse values from line ", l); note("reading '", opts.filters_res, "'"); return false; } filt.wl.push_back(wl); filt.tr.push_back(tr); } } // Save the last filter, if any if (!filt.wl.empty()) { state.filters.push_back(filt); } if (opts.verbose) { note("found ", ntotfilt, " filters in the database, will use ", state.filters.size(), " of them"); } // Sort the filter list as in the catalog state.filters = state.filters[idfil[sort(idcat)]]; // Make sure we are not missing any if (state.filters.size() != state.no_filt.size()) { vec1u notfound; for (uint_t b : state.no_filt) { bool found = false; for (auto& f : state.filters) { if (f.id == b) { found = true; break; } } if (!found) { notfound.push_back(b); } } error("filters ", notfound, " are missing from the filter library"); return false; } // Normalize filter and compute the central wavelength for (auto& f : state.filters) { if (opts.filters_format == 1) { f.tr *= f.wl; } else { f.tr *= sqr(f.wl); } double ttot = integrate(f.wl, f.tr); if (!is_finite(ttot) || ttot == 0) { error("filter ", f.id, " has zero or invalid througput"); return false; } f.tr /= ttot; state.lambda.push_back(integrate(f.wl, f.wl*f.tr)); } return true; } bool read_fluxes(const options_t& opts, input_state_t& state) { std::string catalog_file = opts.catalog+".cat"; if (opts.verbose) { note("reading fluxes from '", catalog_file, "'"); } if (!file::exists(catalog_file)) { error("could not open photometric catalog '", catalog_file, "'"); return false; } // Read the header of the photometric catalog vec1s header; if (!read_header(catalog_file, header)) { return false; } // Read and apply the column translation file, if it exists vec1s header_trans = header; std::string translate_file = opts.catalog+".translate"; if (file::exists(translate_file)) { if (opts.verbose) { note("using column translation file '", catalog_file, "'"); } vec1s tr_from, tr_to; ascii::read_table(translate_file, ascii::find_skip(translate_file), tr_from, tr_to); vec1u idh, idt; match(header, tr_from, idh, idt); header_trans[idh] = tr_to[idt]; } header_trans = toupper(header_trans); // Parse the filter IDs from the (translated) header vec1u col_flux, col_eflux; for (uint_t ih : range(header)) { vec2s ext = regex_extract(header_trans[ih], "^F([0-9]+)$"); if (ext.empty()) continue; uint_t ihe = where_first(header_trans == "E"+ext[0]); if (ihe == npos) { warning("flux column ", header[ih], " has no uncertainty (E"+ext[0]+") " "and will be ignored"); continue; } uint_t tid; from_string(ext[0], tid); state.no_filt.push_back(tid); col_flux.push_back(ih); col_eflux.push_back(ihe); } // Check that we have all the columns we need uint_t col_id = where_first(header_trans == "ID"); uint_t col_zspec = where_first(header_trans == "Z_SPEC"); uint_t col_tot = where_first(is_any_of(header_trans, "TOT"+strna(state.no_filt))); if (col_id == npos) { error("missing ID column in photometric catalog"); return false; } // Read filters from the database if (!read_filters(opts, state)) { return false; } // Now read the catalog itself, only keeping the columns we are interested in uint_t l = 0; std::ifstream in(catalog_file); std::string line; while (std::getline(in, line)) { ++l; line = trim(line); if (line.empty() || line[0] == '#') continue; vec1s spl = split_any_of(line, " \t\n\r"); // Read the ID state.id.push_back(spl[col_id]); // Read the zspec if any if (col_zspec != npos) { float tz; if (!from_string(spl[col_zspec], tz)) { error("could not read z_spec from line ", l); note("must be a floating point number, got: '", spl[col_zspec], "'"); return false; } // Negative means "no zspec" if (tz < 0) { tz = fnan; } state.zspec.push_back(tz); } // Read the fluxes and uncertainties vec1f flx, err; vec1b good = from_string(spl[col_flux], flx); if (count(!good) != 0) { for (uint_t b : where(!good)) { error("could not read flux (", header[col_flux[b]], ") from line ", l); note("must be a floating point number, got: '", spl[col_flux[b]], "'"); } return false; } good = from_string(spl[col_eflux], err); if (count(!good) != 0) { for (uint_t b : where(!good)) { error("could not read uncertainty (", header[col_eflux[b]], ") from line ", l); note("must be a floating point number, got: '", spl[col_eflux[b]], "'"); } return false; } // Apply scaling to total fluxes if requested if (col_tot != npos) { float totcor; if (!from_string(spl[col_tot], totcor)) { error("could not read total flux scaling (", header[col_tot], ") from line ", l); note("must be a floating point number, got: '", spl[col_tot], "'"); return false; } flx *= totcor; err *= totcor; } // Flag bad values vec1u idb = where(err < 0 || !is_finite(flx) || !is_finite(err)); err[idb] = finf; flx[idb] = 0; // Save flux and uncertainties in the input state append<0>(state.flux, reform(flx, 1, flx.size())); append<0>(state.eflux, reform(err, 1, err.size())); } if (col_zspec == npos) { // If no zspec column, give no zspec to all galaxies state.zspec = replicate(fnan, state.id.size()); } // Convert photometry from [catalog unit] to [uJy] float abzp = e10(0.4*(23.9 - opts.ab_zeropoint)); // Convert photometry from fnu [uJy] to flambda [1e-19 x erg/s/cm2/A] vec1u idbb = uindgen(state.no_filt.size()); for (uint_t i : range(state.id)) { state.flux(i,idbb) = 1e19*abzp*astro::uJy2cgs(state.lambda*1e-4, state.flux(i,idbb)); state.eflux(i,idbb) = 1e19*abzp*astro::uJy2cgs(state.lambda*1e-4, state.eflux(i,idbb)); } if (opts.verbose) { note("fitting ", state.flux.dims[0], " source", (state.flux.dims[0] > 1 ? "s" : ""), " with ", state.flux.dims[1], " fluxes", (state.flux.dims[0] > 1 ? " each" : "")); } return true; } bool read_spectra(const options_t& opts, input_state_t& state) { if (opts.spectrum.empty()) { return true; } if (opts.verbose) { note("reading spectra from '", opts.spectrum, "'"); } if (!file::exists(opts.spectrum+".spec")) { error("could not open spectral catalog '", opts.spectrum, ".spec'"); return false; } // Read the header vec1s spec_header; if (!read_header(opts.spectrum+".spec", spec_header)) { return false; } spec_header = toupper(spec_header); // Check we have the right columns there uint_t col_wl0 = where_first(spec_header == "WL_LOW"); uint_t col_wl1 = where_first(spec_header == "WL_UP"); uint_t col_wl = where_first(spec_header == "WL"); uint_t col_tr = where_first(spec_header == "TR"); uint_t col_bin = where_first(spec_header == "BIN"); // First check if the user is using the FAST-IDL format if ((col_wl0 == npos || col_wl1 == npos) && col_wl != npos) { col_wl0 = npos; col_wl1 = npos; } else { col_wl = npos; // Then check for missing wavelength columns if (col_wl0 == npos) { error("missing lower wavelength column (WL_LOW) in spectral catalog"); return false; } if (col_wl1 == npos) { error("missing upper wavelength column (WL_UP) in spectral catalog"); return false; } } vec1u sid; vec1u col_flux, col_eflux; for (uint_t b : range(spec_header)) { vec2s ext = regex_extract(spec_header[b], "F([0-9]+)"); if (ext.empty()) continue; std::string id = ext[0]; uint_t cid = where_first(state.id == id); if (cid == npos) { warning("spectrum for source ", id, " has no corresponding photometry " "and will be ignored"); continue; } uint_t ce = where_first(spec_header == "E"+ext[0]); if (ce == npos) { warning("spectral flux column ", spec_header[b], " has no uncertainty (E"+ext[0]+") " "and will be ignored"); continue; } sid.push_back(cid); col_flux.push_back(b); col_eflux.push_back(ce); } // Read the catalog vec1u bin; vec2f sflx, serr; vec1f slam0, slam1; uint_t l = 0; std::ifstream in(opts.spectrum+".spec"); std::string line; while (std::getline(in, line)) { ++l; line = trim(line); if (line.empty() || line[0] == '#') continue; vec1s spl = split_any_of(line, " \t\n\r"); if (col_tr != npos) { bool tr; if (!from_string(spl[col_tr], tr)) { error("could not read spectral transmission from line ", l); note("must be a boolean (0 or 1), got: '", spl[col_tr], "'"); return false; } // Transmission is binary: 0 = ignore, 1 = use if (!tr) continue; } if (col_bin != npos) { uint_t tbin; if (!from_string(spl[col_bin], tbin)) { error("could not read spectral binning from line ", l); note("must be a positive integer (>= 0), got: '", spl[col_bin], "'"); return false; } bin.push_back(tbin); } if (col_wl0 != npos) { double wl0; if (!from_string(spl[col_wl0], wl0)) { error("could not read spectral lower wavelength from line ", l); note("must be a floating point number, got: '", spl[col_wl0], "'"); return false; } slam0.push_back(wl0); } if (col_wl1 != npos) { double wl1; if (!from_string(spl[col_wl1], wl1)) { error("could not read spectral upper wavelength from line ", l); note("must be a floating point number, got: '", spl[col_wl1], "'"); return false; } slam1.push_back(wl1); } if (col_wl != npos) { double wl; if (!from_string(spl[col_wl], wl)) { error("could not read spectral wavelength from line ", l); note("must be a floating point number, got: '", spl[col_wl], "'"); return false; } slam0.push_back(wl); } // Read the fluxes and uncertainties vec1f flx, err; vec1b good = from_string(spl[col_flux], flx); if (count(!good) != 0) { for (uint_t b : where(!good)) { error("could not read spectral flux (", spec_header[col_flux[b]], ") from line ", l); note("must be a floating point number, got: '", spl[col_flux[b]], "'"); } return false; } good = from_string(spl[col_eflux], err); if (count(!good) != 0) { for (uint_t b : where(!good)) { error("could not read spectral uncertainty (", spec_header[col_eflux[b]], ") from line ", l); note("must be a floating point number, got: '", spl[col_eflux[b]], "'"); } return false; } // Flag bad values vec1u idb = where(err < 0 || !is_finite(flx) || !is_finite(err)); err[idb] = finf; flx[idb] = 0; // Add fluxes to the list append<1>(sflx, reform(flx, flx.size(), 1)); append<1>(serr, reform(err, err.size(), 1)); } if (opts.verbose) { note("found ", sflx.dims[0], " spectr", (sflx.dims[0] > 1 ? "a" : "um"), " with ", sflx.dims[1], " spectral elements", (sflx.dims[0] > 1 ? " each" : "")); } // Compute upper/lower wavelength if only WL was provided, assuming contiguous coverage and // mostly uniform binning as advised in the FAST documentation if (col_wl != npos) { double lam0 = slam0.front(); double lam1 = slam0.back(); double dlam_whole = (slam0.back()-slam0.front())/(slam0.size()-1); for (uint_t il : range(1, slam0.size())) { if (abs((slam0[il]-slam0[il-1])/dlam_whole - 1.0) > 0.05) { error("the wavelength grid of the input spectrum is not uniform"); error("if this was intended, please use the new WL_LOW/WL_UP synthax to " "specify each spectral element unambiguously"); return false; } } slam0 = rgen(lam0, lam1, slam0.size()) - dlam_whole*0.5; slam1 = slam0 + dlam_whole; } // Apply binning if required if (!bin.empty()) { // First sort by bin ID vec1u sortid = sort(bin); sflx = sflx(_,sortid); serr = serr(_,sortid); bin = bin[sortid]; slam0 = slam0[sortid]; slam1 = slam1[sortid]; // Now combine photometry by inverse variance weighting vec2f oflx = sflx, oerr = serr; sflx.clear(); serr.clear(); vec1f oslam0 = slam0, oslam1 = slam1; slam0.clear(); slam1.clear(); vec1f tw(oflx.dims[0]), tf(oflx.dims[0]); uint_t lastb = npos; uint_t nb = 0; double min_lam = finf, max_lam = -finf; for (uint_t b : range(oslam0)) { if (bin[b] != lastb) { if (nb > 0) { // Save the previous bin append<1>(sflx, reform(tf/tw, tf.size(), 1)); append<1>(serr, reform(1/sqrt(tw), tw.size(), 1)); slam0.push_back(min_lam); slam1.push_back(max_lam); } // Cleanup for the next one tw[_] = 0; tf[_] = 0; nb = 0; lastb = bin[b]; min_lam = finf; max_lam = -finf; } // Accumulate the flux with weighting vec1f w = 1/sqr(oerr(_,b)); w[where(!is_finite(w))] = 0; tf += oflx(_,b)*w; tw += w; ++nb; // The width of the effective spectral bin is taken // from the extrema of the binned elements, even if // they are not contiguous... be warned min_lam = min(min_lam, oslam0[b]); max_lam = max(max_lam, oslam1[b]); } if (nb > 0) { // Save the last bin, if any append<1>(sflx, reform(tf/tw, tf.size(), 1)); append<1>(serr, reform(1/sqrt(tw), tw.size(), 1)); slam0.push_back(min_lam); slam1.push_back(max_lam); } vec1u idb = where(!is_finite(serr) || !is_finite(sflx)); serr[idb] = finf; sflx[idb] = 0; if (opts.verbose) { if (oflx.dims[1] == sflx.dims[1]) { note("binned and original spectra resolution are the same (", sflx.dims[1], " spectral elements)"); } else { note("rebinned spectra from ", oflx.dims[1], " to ", sflx.dims[1], " spectral elements"); } } } else { if (opts.verbose) { note("fitting spectra at original resolution (", sflx.dims[1], " spectral elements)"); } } // Create synthetic filters for (uint_t b : range(sflx)) { fast_filter_t f; f.spectral = true; f.id = max(state.no_filt)+1 + b; f.wl = {slam0[b], slam1[b]}; f.tr = {1.0f, 1.0f}; double ttot = integrate(f.wl, f.tr); if (!is_finite(ttot) || ttot == 0) { error("synthetic filter ", b, " for spectral data (wavelength ", slam0[b], " to ", slam1[b], " A) has zero or invalid througput"); return false; } f.tr /= ttot; state.filters.push_back(f); state.lambda.push_back(0.5f*(slam0[b] + slam1[b])); } // Merge the spectra into the flux catalog vec2f pflx = std::move(state.flux); vec2f perr = std::move(state.eflux); uint_t nplam = pflx.dims[1]; uint_t nslam = sflx.dims[1]; uint_t ngal = pflx.dims[0]; state.flux = replicate(fnan, ngal, nplam+nslam); state.eflux = replicate(fnan, ngal, nplam+nslam); for (uint_t i : range(ngal)) { state.flux(i,_-(nplam-1)) = pflx(i,_); state.eflux(i,_-(nplam-1)) = perr(i,_); } for (uint_t i : range(sid)) { state.flux(sid[i],nplam-_) = sflx(i,_); state.eflux(sid[i],nplam-_) = serr(i,_); } return true; } bool read_photoz(const options_t& opts, input_state_t& state) { std::string catalog_file = opts.catalog+".zout"; if (!file::exists(catalog_file)) { return true; } if (opts.verbose) { note("reading photometric redshifts from '", catalog_file, "'"); } // Read the header vec1s header; if (!read_header(catalog_file, header)) { return false; } header = toupper(header); // Check we have all the columns we need uint_t col_zphot = where_first(header == toupper(opts.name_zphot)); uint_t col_zspec = where_first(header == "Z_SPEC"); uint_t col_id = where_first(header == "ID"); vec1u col_up, col_low; if (is_finite(opts.zphot_conf)) { for (float c : {0.68, 0.95, 0.99}) { uint_t cl = where_first(header == "L"+strn(round(100.0*c))); uint_t cu = where_first(header == "U"+strn(round(100.0*c))); if (cl == npos) { error("could not find redshift confidence interval column L"+strn(round(100.0*c))); continue; } else if (cu == npos) { error("could not find redshift confidence interval column U"+strn(round(100.0*c))); continue; } col_up.push_back(cu); col_low.push_back(cl); state.zphot_conf.push_back(c); } { vec1u ids = sort(state.zphot_conf); state.zphot_conf = state.zphot_conf[ids]; col_up = col_up[ids]; col_low = col_low[ids]; } if (!is_any_of(round(100*opts.zphot_conf), round(100*state.zphot_conf))) { error("missing zphot confidence intervals (", round(100*opts.zphot_conf), "th " "percentiles)"); return false; } } if (col_zphot == npos) { error("missing zphot (", toupper(opts.name_zphot), ") column in photometric redshift file"); return false; } if (col_id == npos) { error("missing ID column in photometric redshift file"); return false; } // Initialize the zphot columns state.zphot = replicate(fnan, state.id.size(), 1 + 2*state.zphot_conf.size()); // Read the catalog uint_t l = 0; uint_t i = 0; std::ifstream in(catalog_file); std::string line; while (std::getline(in, line)) { ++l; line = trim(line); if (line.empty() || line[0] == '#') continue; vec1s spl = split_any_of(line, " \t\n\r"); std::string id = spl[col_id]; float zp; if (!from_string(spl[col_zphot], zp)) { error("could not read photometric redshift from line ", l); note("must be a floating point number, got: '", spl[col_zphot], "'"); return false; } if (id != state.id[i]) { error("photometric redshift and photometry catalogs do not match"); return false; } state.zphot(i,0) = (zp > 0 ? zp : fnan); if (col_zspec != npos && !is_finite(state.zspec[i])) { if (!from_string(spl[col_zspec], zp)) { error("could not read spectroscopic redshift from line ", l); note("must be a floating point number, got: '", spl[col_zspec], "'"); return false; } state.zspec[i] = (zp > 0 ? zp : fnan); } for (uint_t c : range(col_low)) { if (!from_string(spl[col_low[c]], zp)) { error("could not read photometric redshift lower ", round(100.0*state.zphot_conf[c]), "th confidence boundary from line ", l); note("must be a floating point number, got: '", spl[col_low[c]], "'"); return false; } state.zphot(i,1+2*c+0) = (zp > 0 ? zp : fnan); } for (uint_t c : range(col_up)) { if (!from_string(spl[col_up[c]], zp)) { error("could not read photometric redshift upper ", round(100.0*state.zphot_conf[c]), "th confidence boundary from line ", l); note("must be a floating point number, got: '", spl[col_up[c]], "'"); return false; } state.zphot(i,1+2*c+1) = (zp > 0 ? zp : fnan); } ++i; } if (i != state.id.size()) { error("photometric redshift and photometry catalogs do not match (", i, " vs. ", state.id.size(), ")"); return false; } return true; } bool read_lir(const options_t& opts, input_state_t& state) { if (!opts.use_lir) return true; std::string catalog_file = opts.catalog+".lir"; if (!file::exists(catalog_file)) { return true; } if (opts.verbose) { note("reading infrared luminosities from '", catalog_file, "'"); } // Read the header vec1s header; if (!read_header(catalog_file, header)) { return false; } header = toupper(header); // Check we have all the columns we need uint_t col_lir = where_first(header == "LIR"); uint_t col_err = where_first(header == "ELIR"); uint_t col_id = where_first(header == "ID"); if (col_lir == npos) { error("missing LIR column in infrared luminosity file"); return false; } if (col_err == npos) { error("missing ELIR column in infrared luminosity file"); return false; } if (col_id == npos) { error("missing ID column in infrared luminosity file"); return false; } // Initialize the lir columns state.lir = replicate(fnan, state.id.size()); state.lir_err = replicate(fnan, state.id.size()); // Read the catalog uint_t l = 0; uint_t i = 0; std::ifstream in(catalog_file); std::string line; while (std::getline(in, line)) { ++l; line = trim(line); if (line.empty() || line[0] == '#') continue; vec1s spl = split_any_of(line, " \t\n\r"); std::string id = spl[col_id]; float lir; if (!from_string(spl[col_lir], lir)) { error("could not read infrared luminosity from line ", l); note("must be a floating point number, got: '", spl[col_lir], "'"); return false; } float err; if (!from_string(spl[col_err], err)) { error("could not read infrared luminosity uncertainty from line ", l); note("must be a floating point number, got: '", spl[col_err], "'"); return false; } if (id != state.id[i]) { error("infrared luminosity and photometry catalogs do not match"); return false; } if (err > 0) { state.lir[i] = lir; state.lir_err[i] = err; } ++i; } if (i != state.id.size()) { error("infrared luminosity and photometry catalogs do not match (", i, " vs. ", state.id.size(), ")"); return false; } return true; } bool read_template_error(const options_t& opts, input_state_t& state) { if (opts.temp_err_file.empty()) { return true; } if (opts.verbose) { note("apply template library error function to photometry"); } if (!file::exists(opts.temp_err_file)) { error("could not open template error function file '", opts.temp_err_file, "'"); return false; } ascii::read_table(opts.temp_err_file, ascii::find_skip(opts.temp_err_file), state.tplerr_lam, state.tplerr_err ); if (state.tplerr_lam.empty()) { error("template error function is empty, something must be wrong in the file"); return false; } return true; } bool read_input(options_t& opts, input_state_t& state, const std::string& filename) { // First read options from the parameter file if (!read_params(opts, state, filename)) { return false; } // Read the photometry + filters if (!read_fluxes(opts, state)) { return false; } // Read the spectra, if any if (!read_spectra(opts, state)) { return false; } // Read the photometric redshift catalog from EAzY, if any if (!read_photoz(opts, state)) { return false; } // Read infrared luminosities, if any if (!read_lir(opts, state)) { return false; } // Read the template error function, if any if (!read_template_error(opts, state)) { return false; } return true; } Fixed error message when OUTPUT_COLUMNS = '' #include "fast++.hpp" std::string remove_first_last(std::string val, std::string charlist) { if (val.empty()) return val; uint_t p0 = 0, n = val.size(); if (charlist.find_first_of(val[0]) != charlist.npos) { ++p0; --n; } if (n > 0 && charlist.find_first_of(val[val.size()-1]) != charlist.npos) { --n; } return val.substr(p0, n); } template <typename T> bool parse_value_impl(const std::string& val, T& out) { return from_string(val, out); } bool parse_value_impl(const std::string& val, std::string& out) { out = remove_first_last(val, "\'\""); return true; } bool parse_value_impl(std::string val, parallel_choice& out) { val = trim(tolower(remove_first_last(val, "\'\""))); if (val == "none" || val.empty()) { out = parallel_choice::none; } else if (val == "sources") { out = parallel_choice::sources; } else if (val == "models") { out = parallel_choice::models; } else { error("unknown parallelization choice '", val, "'"); error("must be one of 'none', sources' or 'models'"); return false; } return true; } template <typename T> bool parse_value_impl(std::string val, vec<1,T>& out) { if (val.empty()) return true; val = remove_first_last(val, "[]"); vec1s spl = split(val, ","); out.resize(spl.size()); for (uint_t i : range(spl)) { if (!parse_value_impl(spl[i], out[i])) { return false; } } return true; } template <typename T> bool parse_value(const std::string& key, const std::string& val, T& out) { if (!parse_value_impl(val, out)) { error("could not parse value of parameter ", key); note("could not convert '", val, "' into ", pretty_type_t(T)); return false; } return true; } bool read_params(options_t& opts, input_state_t& state, const std::string& filename) { std::ifstream in(filename); if (!in.is_open()) { error("could not open parameter file '", filename, "'"); return false; } opts.cosmo = astro::get_cosmo("std"); vec1s unparsed_key, unparsed_val; auto do_parse = [&](const std::string& key, const std::string& val) { #define PARSE_OPTION(name) if (key == #name) { return parse_value(key, val, opts.name); } #define PARSE_OPTION_RENAME(opt, name) if (key == name) { return parse_value(key, val, opts.opt); } PARSE_OPTION(catalog) PARSE_OPTION(ab_zeropoint) PARSE_OPTION(filters_res) PARSE_OPTION_RENAME(filters_format, "filter_format") PARSE_OPTION(temp_err_file) PARSE_OPTION(name_zphot) PARSE_OPTION(spectrum) PARSE_OPTION(auto_scale) PARSE_OPTION(output_dir) PARSE_OPTION(output_file) PARSE_OPTION(n_sim) PARSE_OPTION(c_interval) PARSE_OPTION(best_fit) PARSE_OPTION(library_dir) PARSE_OPTION(library) PARSE_OPTION(resolution) PARSE_OPTION_RENAME(name_imf, "imf") PARSE_OPTION_RENAME(name_sfh, "sfh") PARSE_OPTION(dust_law) PARSE_OPTION_RENAME(dust_noll_eb, "e_b") PARSE_OPTION_RENAME(dust_noll_delta, "delta") PARSE_OPTION(my_sfh) PARSE_OPTION(log_tau_min) PARSE_OPTION(log_tau_max) PARSE_OPTION(log_tau_step) PARSE_OPTION(log_age_min) PARSE_OPTION(log_age_max) PARSE_OPTION(log_age_step) PARSE_OPTION(no_max_age) PARSE_OPTION(z_min) PARSE_OPTION(z_max) PARSE_OPTION(z_step) PARSE_OPTION(z_step_type) PARSE_OPTION(a_v_min) PARSE_OPTION(a_v_max) PARSE_OPTION(a_v_step) PARSE_OPTION(metal) PARSE_OPTION_RENAME(cosmo.H0, "h0") PARSE_OPTION_RENAME(cosmo.wm, "omega_m") PARSE_OPTION_RENAME(cosmo.wL, "omega_l") PARSE_OPTION(save_chi_grid) // Not in original FAST PARSE_OPTION(force_zphot) PARSE_OPTION(best_at_zphot) PARSE_OPTION(zphot_conf) PARSE_OPTION(save_sim) PARSE_OPTION(best_from_sim) PARSE_OPTION(no_cache) PARSE_OPTION(parallel) PARSE_OPTION(n_thread) PARSE_OPTION(max_queued_fits) PARSE_OPTION(verbose) PARSE_OPTION(sfr_avg) PARSE_OPTION(intrinsic_best_fit) PARSE_OPTION(best_sfhs) PARSE_OPTION(sfh_output_step) PARSE_OPTION(sfh_output) PARSE_OPTION(use_lir) PARSE_OPTION(output_columns) PARSE_OPTION(custom_sfh) PARSE_OPTION(custom_sfh_step) PARSE_OPTION(custom_params) #undef PARSE_OPTION #undef PARSE_OPTION_RENAME // warning("unknown parameter '", key, "'"); unparsed_key.push_back(key); unparsed_val.push_back(val); return true; }; // Read the parameter file line by line std::string line; while (std::getline(in, line)) { line = trim(line); if (line.empty() || line[0] == '#') continue; // Remove inline comments auto cp = line.find_first_of('#'); if (cp != line.npos) { line = line.substr(0, cp); } // Split on '=' and parse key and values auto eqp = line.find_first_of('='); if (eqp == line.npos) { error("ill formed line in configuration file"); note(line); return false; } std::string key = tolower(trim(line.substr(0, eqp))); std::string val = trim(line.substr(eqp+1)); if (!do_parse(key, val)) { return false; } } // Initialize custom parameter grid opts.custom_params_min = opts.custom_params_max = opts.custom_params_step = replicate(fnan, opts.custom_params.size()); // Check unparsed key/value pairs for additional options we couldn't parse before for (uint_t p : range(unparsed_key)) { std::string key = unparsed_key[p]; std::string val = unparsed_val[p]; bool read = false; // Read custom grid parameters for (uint_t c : range(opts.custom_params)) { if (key == tolower(opts.custom_params[c])+"_min") { read = true; if (!parse_value(key, val, opts.custom_params_min[c])) { return false; } } else if (key == tolower(opts.custom_params[c])+"_max") { read = true; if (!parse_value(key, val, opts.custom_params_max[c])) { return false; } } else if (key == tolower(opts.custom_params[c])+"_step") { read = true; if (!parse_value(key, val, opts.custom_params_step[c])) { return false; } } } if (!read) { warning("unknown parameter '", toupper(key), "'"); } } // Create output directory, if it doesn't exist if (!opts.output_dir.empty()) { opts.output_dir = file::directorize(opts.output_dir); if (!file::mkdir(opts.output_dir)) { error("could not create output directory '", opts.output_dir, "'"); error("make sure you have the proper rights"); return false; } } if (opts.output_file.empty()) opts.output_file = opts.catalog; // Now check for the consistency of the output and make corrections when necessary if (opts.sfr_avg < 0 || !is_finite(opts.sfr_avg)) { opts.sfr_avg = 0; } auto check_sfh_step = [&](float& step, std::string which) { if (step < 0) { error("step of ", which, " SFH cannot be negative"); return false; } else if (step > 1e4) { error("step of ", which, " SFH must be given in Myr"); error("(you gave ", step, " which is larger than the age of the Universe)"); return false; } step *= 1e6; // convert to yr return true; }; check_sfh_step(opts.sfh_output_step, "output"); check_sfh_step(opts.custom_sfh_step, "custom"); if (opts.verbose) { if (opts.sfr_avg == 0) { note("using instantaneous SFRs"); } else { note("averaging SFRs over ", opts.sfr_avg, " Myr"); } } opts.sfh_output = tolower(opts.sfh_output); if (!(opts.sfh_output == "sfr" || opts.sfh_output == "mass")) { error("'SFH_OUTPUT' must be either 'sfr' or 'mass'"); return false; } opts.sfr_avg *= 1e6; if (opts.intrinsic_best_fit && !opts.best_fit) { warning("'INTRINSIC_BEST_FIT' has no effect if 'BEST_SIM' is not set to 1"); } if (opts.best_sfhs && !opts.my_sfh.empty()) { warning("cannot output best fit SFH when using custom SFH"); opts.best_sfhs = false; } if (opts.best_from_sim && opts.n_sim == 0) { error("cannot use the option 'BEST_FROM_SIM' if simulations are not enabled (set N_SIM > 0)"); return false; } if (!opts.my_sfh.empty()) { opts.sfh = sfh_type::single; } else if (!opts.custom_sfh.empty()) { opts.sfh = sfh_type::custom; } else { opts.sfh = sfh_type::gridded; } if (opts.spectrum.empty()) { opts.auto_scale = false; } if (opts.parallel != parallel_choice::none && opts.n_thread <= 1) { warning("parallelization is enabled but the number of thread is set to zero"); warning("parallelization will be disabled unless you set N_THREAD > 1"); opts.parallel = parallel_choice::none; } if (opts.best_at_zphot && opts.force_zphot) { note("BEST_AT_ZPHOT=1 is automatically true if FORCE_ZPHOT=1, " "so you do not have to specify both"); } for (double c : opts.c_interval) { if (abs(c - 68.0) > 0.01 && abs(c - 95.0) > 0.01 && abs(c - 99.0) > 0.01) { error("confidence interval must be one of 68, 95 or 99% (got ", c, ")"); return false; } } if (opts.n_sim != 0) { state.conf_interval = 0.5*(1.0 - opts.c_interval/100.0); inplace_sort(opts.c_interval); vec1f cint = state.conf_interval; state.conf_interval.clear(); for (float c : cint) { state.conf_interval.push_back(c); state.conf_interval.push_back(1.0 - c); } } else { opts.c_interval.clear(); } if (opts.force_zphot || abs(opts.zphot_conf) < 0.1) { opts.zphot_conf = fnan; } else { opts.zphot_conf /= 100.0; } if (opts.metal.empty()) { if (opts.library == "bc03" || opts.library == "ma05") { opts.metal = {0.02}; } else if (opts.library == "co11") { opts.metal = {0.019}; } else { // Unknown stellar library, simply guess what could be a good default value... opts.metal = {0.02}; } } if (opts.output_columns.empty() || (opts.output_columns.size() == 1 && opts.output_columns[0].empty())) { // Default columns to display switch (opts.sfh) { case sfh_type::gridded: opts.output_columns = { "id", "z", "ltau", "metal", "lage", "Av", "lmass", "lsfr", "lssfr", "la2t", "chi2" }; break; case sfh_type::single: opts.output_columns = { "id", "z", "metal", "lage", "Av", "lmass", "lsfr", "lssfr", "chi2" }; break; case sfh_type::custom: opts.output_columns = { "id", "z", "metal", "lage", "Av", "lmass", "lsfr", "lssfr" }; append(opts.output_columns, opts.custom_params); opts.output_columns.push_back("chi2"); break; } } if (!opts.custom_params.empty()) { // Add tau to the custom parameter grid if the user used it uint_t idp = where_first(tolower(opts.custom_params) == "log_tau"); if (idp != npos) { opts.custom_params_min[idp] = opts.log_tau_min; opts.custom_params_max[idp] = opts.log_tau_max; opts.custom_params_step[idp] = opts.log_tau_step; } } if (!opts.custom_sfh.empty()) { // Check that all parameters in the grid have been properly defined bool bad = false; for (uint_t c : range(opts.custom_params)) { if (!is_finite(opts.custom_params_min[c])) { error("missing ", toupper(opts.custom_params[c])+"_MIN value"); bad = true; } if (!is_finite(opts.custom_params_max[c])) { error("missing ", toupper(opts.custom_params[c])+"_MAX value"); bad = true; } if (!is_finite(opts.custom_params_step[c])) { error("missing ", toupper(opts.custom_params[c])+"_STEP value"); bad = true; } } if (bad) return false; } // Use the default 'share' directory if nothing is provided if (opts.filters_res.empty()) { opts.filters_res = std::string(FASTPP_SHARE_DIR)+"/FILTER.RES.latest"; } if (opts.temp_err_file.empty()) { opts.temp_err_file = std::string(FASTPP_SHARE_DIR)+"/TEMPLATE_ERROR.fast.v0.2"; } if (opts.library_dir.empty()) { opts.library_dir = std::string(FASTPP_SHARE_DIR)+"/libraries/"; } else { opts.library_dir = file::directorize(opts.library_dir); } return true; } bool read_header(const std::string& filename, vec1s& header) { std::ifstream in(filename); std::string line; while (std::getline(in, line)) { line = trim(line); // Find the first non-empty comment line if (line.empty() || line[0] != '#') continue; line = trim(line.substr(1)); if (line.empty()) continue; // Split column names by spaces header = split_any_of(line, " \t\n\r"); return true; } error("missing header in '", filename, "'"); note("the header line must start with # and list the column names"); return false; } bool read_filters(const options_t& opts, input_state_t& state) { if (opts.filters_res.empty()) { // No filter, maybe just trying to fit a spectrum? return true; } if (opts.verbose) { note("reading filters from '", opts.filters_res, "'"); } std::ifstream in(opts.filters_res); if (!in.is_open()) { error("could not open filter file '", opts.filters_res, "'"); return false; } // Read the required filters from the database std::string line; uint_t l = 0; fast_filter_t filt; vec1u idcat, idfil; bool doread = false; uint_t ntotfilt = 0; while (std::getline(in, line)) { ++l; line = trim(line); if (line.empty()) continue; vec1s spl = split_any_of(line, " \t\n\r"); if (spl.size() > 3) { // Start of a new filter // Save the previous one, if any if (!filt.wl.empty()) { state.filters.push_back(filt); // Cleanup for next filter filt.wl.clear(); filt.tr.clear(); filt.id = npos; } ++ntotfilt; filt.id = ntotfilt; // Determine if this filter is used in the catalog vec1u idused = where(state.no_filt == filt.id); if (!idused.empty()) { // It is there, keep the ID aside for later sorting append(idcat, idused); append(idfil, replicate(state.filters.size(), idused.size())); doread = true; } else { // If not, discard its values doread = false; } } else if (doread && spl.size() == 3) { // Reading the filter response float wl, tr; if (!from_string(spl[1], wl) || !from_string(spl[2], tr)) { error("could not parse values from line ", l); note("reading '", opts.filters_res, "'"); return false; } filt.wl.push_back(wl); filt.tr.push_back(tr); } } // Save the last filter, if any if (!filt.wl.empty()) { state.filters.push_back(filt); } if (opts.verbose) { note("found ", ntotfilt, " filters in the database, will use ", state.filters.size(), " of them"); } // Sort the filter list as in the catalog state.filters = state.filters[idfil[sort(idcat)]]; // Make sure we are not missing any if (state.filters.size() != state.no_filt.size()) { vec1u notfound; for (uint_t b : state.no_filt) { bool found = false; for (auto& f : state.filters) { if (f.id == b) { found = true; break; } } if (!found) { notfound.push_back(b); } } error("filters ", notfound, " are missing from the filter library"); return false; } // Normalize filter and compute the central wavelength for (auto& f : state.filters) { if (opts.filters_format == 1) { f.tr *= f.wl; } else { f.tr *= sqr(f.wl); } double ttot = integrate(f.wl, f.tr); if (!is_finite(ttot) || ttot == 0) { error("filter ", f.id, " has zero or invalid througput"); return false; } f.tr /= ttot; state.lambda.push_back(integrate(f.wl, f.wl*f.tr)); } return true; } bool read_fluxes(const options_t& opts, input_state_t& state) { std::string catalog_file = opts.catalog+".cat"; if (opts.verbose) { note("reading fluxes from '", catalog_file, "'"); } if (!file::exists(catalog_file)) { error("could not open photometric catalog '", catalog_file, "'"); return false; } // Read the header of the photometric catalog vec1s header; if (!read_header(catalog_file, header)) { return false; } // Read and apply the column translation file, if it exists vec1s header_trans = header; std::string translate_file = opts.catalog+".translate"; if (file::exists(translate_file)) { if (opts.verbose) { note("using column translation file '", catalog_file, "'"); } vec1s tr_from, tr_to; ascii::read_table(translate_file, ascii::find_skip(translate_file), tr_from, tr_to); vec1u idh, idt; match(header, tr_from, idh, idt); header_trans[idh] = tr_to[idt]; } header_trans = toupper(header_trans); // Parse the filter IDs from the (translated) header vec1u col_flux, col_eflux; for (uint_t ih : range(header)) { vec2s ext = regex_extract(header_trans[ih], "^F([0-9]+)$"); if (ext.empty()) continue; uint_t ihe = where_first(header_trans == "E"+ext[0]); if (ihe == npos) { warning("flux column ", header[ih], " has no uncertainty (E"+ext[0]+") " "and will be ignored"); continue; } uint_t tid; from_string(ext[0], tid); state.no_filt.push_back(tid); col_flux.push_back(ih); col_eflux.push_back(ihe); } // Check that we have all the columns we need uint_t col_id = where_first(header_trans == "ID"); uint_t col_zspec = where_first(header_trans == "Z_SPEC"); uint_t col_tot = where_first(is_any_of(header_trans, "TOT"+strna(state.no_filt))); if (col_id == npos) { error("missing ID column in photometric catalog"); return false; } // Read filters from the database if (!read_filters(opts, state)) { return false; } // Now read the catalog itself, only keeping the columns we are interested in uint_t l = 0; std::ifstream in(catalog_file); std::string line; while (std::getline(in, line)) { ++l; line = trim(line); if (line.empty() || line[0] == '#') continue; vec1s spl = split_any_of(line, " \t\n\r"); // Read the ID state.id.push_back(spl[col_id]); // Read the zspec if any if (col_zspec != npos) { float tz; if (!from_string(spl[col_zspec], tz)) { error("could not read z_spec from line ", l); note("must be a floating point number, got: '", spl[col_zspec], "'"); return false; } // Negative means "no zspec" if (tz < 0) { tz = fnan; } state.zspec.push_back(tz); } // Read the fluxes and uncertainties vec1f flx, err; vec1b good = from_string(spl[col_flux], flx); if (count(!good) != 0) { for (uint_t b : where(!good)) { error("could not read flux (", header[col_flux[b]], ") from line ", l); note("must be a floating point number, got: '", spl[col_flux[b]], "'"); } return false; } good = from_string(spl[col_eflux], err); if (count(!good) != 0) { for (uint_t b : where(!good)) { error("could not read uncertainty (", header[col_eflux[b]], ") from line ", l); note("must be a floating point number, got: '", spl[col_eflux[b]], "'"); } return false; } // Apply scaling to total fluxes if requested if (col_tot != npos) { float totcor; if (!from_string(spl[col_tot], totcor)) { error("could not read total flux scaling (", header[col_tot], ") from line ", l); note("must be a floating point number, got: '", spl[col_tot], "'"); return false; } flx *= totcor; err *= totcor; } // Flag bad values vec1u idb = where(err < 0 || !is_finite(flx) || !is_finite(err)); err[idb] = finf; flx[idb] = 0; // Save flux and uncertainties in the input state append<0>(state.flux, reform(flx, 1, flx.size())); append<0>(state.eflux, reform(err, 1, err.size())); } if (col_zspec == npos) { // If no zspec column, give no zspec to all galaxies state.zspec = replicate(fnan, state.id.size()); } // Convert photometry from [catalog unit] to [uJy] float abzp = e10(0.4*(23.9 - opts.ab_zeropoint)); // Convert photometry from fnu [uJy] to flambda [1e-19 x erg/s/cm2/A] vec1u idbb = uindgen(state.no_filt.size()); for (uint_t i : range(state.id)) { state.flux(i,idbb) = 1e19*abzp*astro::uJy2cgs(state.lambda*1e-4, state.flux(i,idbb)); state.eflux(i,idbb) = 1e19*abzp*astro::uJy2cgs(state.lambda*1e-4, state.eflux(i,idbb)); } if (opts.verbose) { note("fitting ", state.flux.dims[0], " source", (state.flux.dims[0] > 1 ? "s" : ""), " with ", state.flux.dims[1], " fluxes", (state.flux.dims[0] > 1 ? " each" : "")); } return true; } bool read_spectra(const options_t& opts, input_state_t& state) { if (opts.spectrum.empty()) { return true; } if (opts.verbose) { note("reading spectra from '", opts.spectrum, "'"); } if (!file::exists(opts.spectrum+".spec")) { error("could not open spectral catalog '", opts.spectrum, ".spec'"); return false; } // Read the header vec1s spec_header; if (!read_header(opts.spectrum+".spec", spec_header)) { return false; } spec_header = toupper(spec_header); // Check we have the right columns there uint_t col_wl0 = where_first(spec_header == "WL_LOW"); uint_t col_wl1 = where_first(spec_header == "WL_UP"); uint_t col_wl = where_first(spec_header == "WL"); uint_t col_tr = where_first(spec_header == "TR"); uint_t col_bin = where_first(spec_header == "BIN"); // First check if the user is using the FAST-IDL format if ((col_wl0 == npos || col_wl1 == npos) && col_wl != npos) { col_wl0 = npos; col_wl1 = npos; } else { col_wl = npos; // Then check for missing wavelength columns if (col_wl0 == npos) { error("missing lower wavelength column (WL_LOW) in spectral catalog"); return false; } if (col_wl1 == npos) { error("missing upper wavelength column (WL_UP) in spectral catalog"); return false; } } vec1u sid; vec1u col_flux, col_eflux; for (uint_t b : range(spec_header)) { vec2s ext = regex_extract(spec_header[b], "F([0-9]+)"); if (ext.empty()) continue; std::string id = ext[0]; uint_t cid = where_first(state.id == id); if (cid == npos) { warning("spectrum for source ", id, " has no corresponding photometry " "and will be ignored"); continue; } uint_t ce = where_first(spec_header == "E"+ext[0]); if (ce == npos) { warning("spectral flux column ", spec_header[b], " has no uncertainty (E"+ext[0]+") " "and will be ignored"); continue; } sid.push_back(cid); col_flux.push_back(b); col_eflux.push_back(ce); } // Read the catalog vec1u bin; vec2f sflx, serr; vec1f slam0, slam1; uint_t l = 0; std::ifstream in(opts.spectrum+".spec"); std::string line; while (std::getline(in, line)) { ++l; line = trim(line); if (line.empty() || line[0] == '#') continue; vec1s spl = split_any_of(line, " \t\n\r"); if (col_tr != npos) { bool tr; if (!from_string(spl[col_tr], tr)) { error("could not read spectral transmission from line ", l); note("must be a boolean (0 or 1), got: '", spl[col_tr], "'"); return false; } // Transmission is binary: 0 = ignore, 1 = use if (!tr) continue; } if (col_bin != npos) { uint_t tbin; if (!from_string(spl[col_bin], tbin)) { error("could not read spectral binning from line ", l); note("must be a positive integer (>= 0), got: '", spl[col_bin], "'"); return false; } bin.push_back(tbin); } if (col_wl0 != npos) { double wl0; if (!from_string(spl[col_wl0], wl0)) { error("could not read spectral lower wavelength from line ", l); note("must be a floating point number, got: '", spl[col_wl0], "'"); return false; } slam0.push_back(wl0); } if (col_wl1 != npos) { double wl1; if (!from_string(spl[col_wl1], wl1)) { error("could not read spectral upper wavelength from line ", l); note("must be a floating point number, got: '", spl[col_wl1], "'"); return false; } slam1.push_back(wl1); } if (col_wl != npos) { double wl; if (!from_string(spl[col_wl], wl)) { error("could not read spectral wavelength from line ", l); note("must be a floating point number, got: '", spl[col_wl], "'"); return false; } slam0.push_back(wl); } // Read the fluxes and uncertainties vec1f flx, err; vec1b good = from_string(spl[col_flux], flx); if (count(!good) != 0) { for (uint_t b : where(!good)) { error("could not read spectral flux (", spec_header[col_flux[b]], ") from line ", l); note("must be a floating point number, got: '", spl[col_flux[b]], "'"); } return false; } good = from_string(spl[col_eflux], err); if (count(!good) != 0) { for (uint_t b : where(!good)) { error("could not read spectral uncertainty (", spec_header[col_eflux[b]], ") from line ", l); note("must be a floating point number, got: '", spl[col_eflux[b]], "'"); } return false; } // Flag bad values vec1u idb = where(err < 0 || !is_finite(flx) || !is_finite(err)); err[idb] = finf; flx[idb] = 0; // Add fluxes to the list append<1>(sflx, reform(flx, flx.size(), 1)); append<1>(serr, reform(err, err.size(), 1)); } if (opts.verbose) { note("found ", sflx.dims[0], " spectr", (sflx.dims[0] > 1 ? "a" : "um"), " with ", sflx.dims[1], " spectral elements", (sflx.dims[0] > 1 ? " each" : "")); } // Compute upper/lower wavelength if only WL was provided, assuming contiguous coverage and // mostly uniform binning as advised in the FAST documentation if (col_wl != npos) { double lam0 = slam0.front(); double lam1 = slam0.back(); double dlam_whole = (slam0.back()-slam0.front())/(slam0.size()-1); for (uint_t il : range(1, slam0.size())) { if (abs((slam0[il]-slam0[il-1])/dlam_whole - 1.0) > 0.05) { error("the wavelength grid of the input spectrum is not uniform"); error("if this was intended, please use the new WL_LOW/WL_UP synthax to " "specify each spectral element unambiguously"); return false; } } slam0 = rgen(lam0, lam1, slam0.size()) - dlam_whole*0.5; slam1 = slam0 + dlam_whole; } // Apply binning if required if (!bin.empty()) { // First sort by bin ID vec1u sortid = sort(bin); sflx = sflx(_,sortid); serr = serr(_,sortid); bin = bin[sortid]; slam0 = slam0[sortid]; slam1 = slam1[sortid]; // Now combine photometry by inverse variance weighting vec2f oflx = sflx, oerr = serr; sflx.clear(); serr.clear(); vec1f oslam0 = slam0, oslam1 = slam1; slam0.clear(); slam1.clear(); vec1f tw(oflx.dims[0]), tf(oflx.dims[0]); uint_t lastb = npos; uint_t nb = 0; double min_lam = finf, max_lam = -finf; for (uint_t b : range(oslam0)) { if (bin[b] != lastb) { if (nb > 0) { // Save the previous bin append<1>(sflx, reform(tf/tw, tf.size(), 1)); append<1>(serr, reform(1/sqrt(tw), tw.size(), 1)); slam0.push_back(min_lam); slam1.push_back(max_lam); } // Cleanup for the next one tw[_] = 0; tf[_] = 0; nb = 0; lastb = bin[b]; min_lam = finf; max_lam = -finf; } // Accumulate the flux with weighting vec1f w = 1/sqr(oerr(_,b)); w[where(!is_finite(w))] = 0; tf += oflx(_,b)*w; tw += w; ++nb; // The width of the effective spectral bin is taken // from the extrema of the binned elements, even if // they are not contiguous... be warned min_lam = min(min_lam, oslam0[b]); max_lam = max(max_lam, oslam1[b]); } if (nb > 0) { // Save the last bin, if any append<1>(sflx, reform(tf/tw, tf.size(), 1)); append<1>(serr, reform(1/sqrt(tw), tw.size(), 1)); slam0.push_back(min_lam); slam1.push_back(max_lam); } vec1u idb = where(!is_finite(serr) || !is_finite(sflx)); serr[idb] = finf; sflx[idb] = 0; if (opts.verbose) { if (oflx.dims[1] == sflx.dims[1]) { note("binned and original spectra resolution are the same (", sflx.dims[1], " spectral elements)"); } else { note("rebinned spectra from ", oflx.dims[1], " to ", sflx.dims[1], " spectral elements"); } } } else { if (opts.verbose) { note("fitting spectra at original resolution (", sflx.dims[1], " spectral elements)"); } } // Create synthetic filters for (uint_t b : range(sflx)) { fast_filter_t f; f.spectral = true; f.id = max(state.no_filt)+1 + b; f.wl = {slam0[b], slam1[b]}; f.tr = {1.0f, 1.0f}; double ttot = integrate(f.wl, f.tr); if (!is_finite(ttot) || ttot == 0) { error("synthetic filter ", b, " for spectral data (wavelength ", slam0[b], " to ", slam1[b], " A) has zero or invalid througput"); return false; } f.tr /= ttot; state.filters.push_back(f); state.lambda.push_back(0.5f*(slam0[b] + slam1[b])); } // Merge the spectra into the flux catalog vec2f pflx = std::move(state.flux); vec2f perr = std::move(state.eflux); uint_t nplam = pflx.dims[1]; uint_t nslam = sflx.dims[1]; uint_t ngal = pflx.dims[0]; state.flux = replicate(fnan, ngal, nplam+nslam); state.eflux = replicate(fnan, ngal, nplam+nslam); for (uint_t i : range(ngal)) { state.flux(i,_-(nplam-1)) = pflx(i,_); state.eflux(i,_-(nplam-1)) = perr(i,_); } for (uint_t i : range(sid)) { state.flux(sid[i],nplam-_) = sflx(i,_); state.eflux(sid[i],nplam-_) = serr(i,_); } return true; } bool read_photoz(const options_t& opts, input_state_t& state) { std::string catalog_file = opts.catalog+".zout"; if (!file::exists(catalog_file)) { return true; } if (opts.verbose) { note("reading photometric redshifts from '", catalog_file, "'"); } // Read the header vec1s header; if (!read_header(catalog_file, header)) { return false; } header = toupper(header); // Check we have all the columns we need uint_t col_zphot = where_first(header == toupper(opts.name_zphot)); uint_t col_zspec = where_first(header == "Z_SPEC"); uint_t col_id = where_first(header == "ID"); vec1u col_up, col_low; if (is_finite(opts.zphot_conf)) { for (float c : {0.68, 0.95, 0.99}) { uint_t cl = where_first(header == "L"+strn(round(100.0*c))); uint_t cu = where_first(header == "U"+strn(round(100.0*c))); if (cl == npos) { error("could not find redshift confidence interval column L"+strn(round(100.0*c))); continue; } else if (cu == npos) { error("could not find redshift confidence interval column U"+strn(round(100.0*c))); continue; } col_up.push_back(cu); col_low.push_back(cl); state.zphot_conf.push_back(c); } { vec1u ids = sort(state.zphot_conf); state.zphot_conf = state.zphot_conf[ids]; col_up = col_up[ids]; col_low = col_low[ids]; } if (!is_any_of(round(100*opts.zphot_conf), round(100*state.zphot_conf))) { error("missing zphot confidence intervals (", round(100*opts.zphot_conf), "th " "percentiles)"); return false; } } if (col_zphot == npos) { error("missing zphot (", toupper(opts.name_zphot), ") column in photometric redshift file"); return false; } if (col_id == npos) { error("missing ID column in photometric redshift file"); return false; } // Initialize the zphot columns state.zphot = replicate(fnan, state.id.size(), 1 + 2*state.zphot_conf.size()); // Read the catalog uint_t l = 0; uint_t i = 0; std::ifstream in(catalog_file); std::string line; while (std::getline(in, line)) { ++l; line = trim(line); if (line.empty() || line[0] == '#') continue; vec1s spl = split_any_of(line, " \t\n\r"); std::string id = spl[col_id]; float zp; if (!from_string(spl[col_zphot], zp)) { error("could not read photometric redshift from line ", l); note("must be a floating point number, got: '", spl[col_zphot], "'"); return false; } if (id != state.id[i]) { error("photometric redshift and photometry catalogs do not match"); return false; } state.zphot(i,0) = (zp > 0 ? zp : fnan); if (col_zspec != npos && !is_finite(state.zspec[i])) { if (!from_string(spl[col_zspec], zp)) { error("could not read spectroscopic redshift from line ", l); note("must be a floating point number, got: '", spl[col_zspec], "'"); return false; } state.zspec[i] = (zp > 0 ? zp : fnan); } for (uint_t c : range(col_low)) { if (!from_string(spl[col_low[c]], zp)) { error("could not read photometric redshift lower ", round(100.0*state.zphot_conf[c]), "th confidence boundary from line ", l); note("must be a floating point number, got: '", spl[col_low[c]], "'"); return false; } state.zphot(i,1+2*c+0) = (zp > 0 ? zp : fnan); } for (uint_t c : range(col_up)) { if (!from_string(spl[col_up[c]], zp)) { error("could not read photometric redshift upper ", round(100.0*state.zphot_conf[c]), "th confidence boundary from line ", l); note("must be a floating point number, got: '", spl[col_up[c]], "'"); return false; } state.zphot(i,1+2*c+1) = (zp > 0 ? zp : fnan); } ++i; } if (i != state.id.size()) { error("photometric redshift and photometry catalogs do not match (", i, " vs. ", state.id.size(), ")"); return false; } return true; } bool read_lir(const options_t& opts, input_state_t& state) { if (!opts.use_lir) return true; std::string catalog_file = opts.catalog+".lir"; if (!file::exists(catalog_file)) { return true; } if (opts.verbose) { note("reading infrared luminosities from '", catalog_file, "'"); } // Read the header vec1s header; if (!read_header(catalog_file, header)) { return false; } header = toupper(header); // Check we have all the columns we need uint_t col_lir = where_first(header == "LIR"); uint_t col_err = where_first(header == "ELIR"); uint_t col_id = where_first(header == "ID"); if (col_lir == npos) { error("missing LIR column in infrared luminosity file"); return false; } if (col_err == npos) { error("missing ELIR column in infrared luminosity file"); return false; } if (col_id == npos) { error("missing ID column in infrared luminosity file"); return false; } // Initialize the lir columns state.lir = replicate(fnan, state.id.size()); state.lir_err = replicate(fnan, state.id.size()); // Read the catalog uint_t l = 0; uint_t i = 0; std::ifstream in(catalog_file); std::string line; while (std::getline(in, line)) { ++l; line = trim(line); if (line.empty() || line[0] == '#') continue; vec1s spl = split_any_of(line, " \t\n\r"); std::string id = spl[col_id]; float lir; if (!from_string(spl[col_lir], lir)) { error("could not read infrared luminosity from line ", l); note("must be a floating point number, got: '", spl[col_lir], "'"); return false; } float err; if (!from_string(spl[col_err], err)) { error("could not read infrared luminosity uncertainty from line ", l); note("must be a floating point number, got: '", spl[col_err], "'"); return false; } if (id != state.id[i]) { error("infrared luminosity and photometry catalogs do not match"); return false; } if (err > 0) { state.lir[i] = lir; state.lir_err[i] = err; } ++i; } if (i != state.id.size()) { error("infrared luminosity and photometry catalogs do not match (", i, " vs. ", state.id.size(), ")"); return false; } return true; } bool read_template_error(const options_t& opts, input_state_t& state) { if (opts.temp_err_file.empty()) { return true; } if (opts.verbose) { note("apply template library error function to photometry"); } if (!file::exists(opts.temp_err_file)) { error("could not open template error function file '", opts.temp_err_file, "'"); return false; } ascii::read_table(opts.temp_err_file, ascii::find_skip(opts.temp_err_file), state.tplerr_lam, state.tplerr_err ); if (state.tplerr_lam.empty()) { error("template error function is empty, something must be wrong in the file"); return false; } return true; } bool read_input(options_t& opts, input_state_t& state, const std::string& filename) { // First read options from the parameter file if (!read_params(opts, state, filename)) { return false; } // Read the photometry + filters if (!read_fluxes(opts, state)) { return false; } // Read the spectra, if any if (!read_spectra(opts, state)) { return false; } // Read the photometric redshift catalog from EAzY, if any if (!read_photoz(opts, state)) { return false; } // Read infrared luminosities, if any if (!read_lir(opts, state)) { return false; } // Read the template error function, if any if (!read_template_error(opts, state)) { return false; } return true; }
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <deque> #include <vector> #include "tensorflow/cc/framework/grad_op_registry.h" #include "tensorflow/cc/framework/gradients.h" #include "tensorflow/cc/framework/while_gradients.h" #include "tensorflow/cc/ops/standard_ops.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/graph/algorithm.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/graph/while_context.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/platform/macros.h" namespace tensorflow { namespace { struct OutputHash { uint64 operator()(const Output& x) const { return x.hash(); } }; struct OutputEq { bool operator()(const Output& x, const Output& y) const { return (x.node() == y.node()) && (x.index() == y.index()); } }; class SymbolicGradientBuilder { public: SymbolicGradientBuilder(const Scope& scope, const ops::GradOpRegistry* registry, const std::vector<Output>& outputs, const std::vector<Output>& inputs, const std::vector<Output>& grad_inputs, std::vector<Output>* grad_outputs); Status AddGradients(); static Output NoGradient() { return Output(nullptr, -1); } private: Status Initialize(); // For each forward edge from `src` to `dst` in the initial/forward graph: // propagates gradients `dst_grad` backwards along the edge from `src` // to `dst` in the graph. This will add `dst_grad` to the list of pending // gradients for the node associated with `src`. Status BackpropAlongEdge(const Output& dst_grad, const Output& src); // Adds a node to the graph (returned in `grad`) that sums the in-bound // gradients to `src` (if there are more than one). Status SumGradients(const Output& src, Output* grad); // Returns true if `opname` is registered in `registry_` with no gradient // function, false otherwise. bool IsPrimitiveOpWithNoGrad(const string& opname); // Call the gradient function for `op`, storing the result in `grad_outputs`. Status CallGradFunction(const Operation& op, const std::vector<Output>& grad_inputs, std::vector<Output>* grad_outputs); // Returns a list mapping whether each node in the graph is reachable // from outputs_. Keyed by node id. std::vector<bool> GetReachableNodes(); // Creates the gradient subgraph for a while loop (or just stores // `summed_grads` if not all incoming gradients are available yet). All exit // nodes (which are the first nodes of a loop encountered in the backwards // pass) are passed to this function rather than processed normally. // `summed_grads` is the sum of `exit_node`s gradients. Status ProcessWhileLoop(Node* exit_node, const Output& summed_grads); // Gets the set of node ids at which to stop backprop. These are all elements // of `outputs_` that do not get transitively consumed by other `outputs_`. // Used to identify nodes at which to stop backprop. std::unordered_set<int> GetStopBackpropNodes( const std::vector<bool>& reachable_nodes, const std::unordered_set<int>& output_nodes); const Scope& scope_; const ops::GradOpRegistry* registry_; const std::vector<Output>& outputs_; const std::vector<Output>& inputs_; const std::vector<Output>& grad_inputs_; std::vector<Output>* grad_outputs_; // A vector of output endpoints which represents backpropagated gradients. typedef std::vector<Output> BackproppedGradients; // backprops_ is a map from a node output to its accumulated // gradients. When a node output has accumulated all its // gradients, we add a node which sums them up. std::unordered_map<Output, BackproppedGradients, OutputHash, OutputEq> backprops_; // pending[i] is count-down counter for i-th node's expected // backprops. When pending[i] becomes zero, we collected all // backprop gradients for all outputs of the ith-node. std::vector<int> pending_; // `ready` keeps track of nodes that have been completely // backpropped. Initially, for every output in `outputs_`, we add initial // gradients from `grad_inputs_`. std::deque<Node*> ready_; // The set of node ids in `inputs_`. Used to identify nodes at backprop // frontier. Maps from Output -> index into `grad_outputs_`. std::unordered_map<Output, int, OutputHash, OutputEq> input_nodes_; // For each while loop in the graph, collects the summed gradients for each of // the loop's exit nodes. Note that unlike backprops_, this map contains the // output of SumGradients(), not the input (i.e. each exit node may have // multiple incoming gradients, but we only store the combined Output here). std::map<WhileContext*, std::map<Node*, Output>> while_backprops_; TF_DISALLOW_COPY_AND_ASSIGN(SymbolicGradientBuilder); }; SymbolicGradientBuilder::SymbolicGradientBuilder( const Scope& scope, const ops::GradOpRegistry* registry, const std::vector<Output>& outputs, const std::vector<Output>& inputs, const std::vector<Output>& grad_inputs, std::vector<Output>* grad_outputs) : scope_(scope), registry_(registry), outputs_(outputs), inputs_(inputs), grad_inputs_(grad_inputs), grad_outputs_(grad_outputs) {} Status SymbolicGradientBuilder::BackpropAlongEdge(const Output& dst_grad, const Output& src) { if (src.node() == nullptr) { return errors::Internal("Attempted to backprop along an invalid edge."); } auto iter = backprops_.find(src); if (iter != backprops_.end()) { auto* grads = &iter->second; grads->push_back(dst_grad); if (--pending_[src.node()->id()] == 0) { ready_.push_back(src.node()); } } return Status::OK(); } std::vector<bool> SymbolicGradientBuilder::GetReachableNodes() { std::vector<bool> reachable_nodes(scope_.graph()->num_node_ids(), false); std::deque<Node*> queue; for (const Output& out : outputs_) { const Node* const out_node = out.node(); const int out_node_id = out_node->id(); if (!reachable_nodes[out_node_id]) { queue.push_back(out_node); reachable_nodes[out_node_id] = true; } } while (!queue.empty()) { Node* n = queue.front(); queue.pop_front(); for (const Edge* e : n->in_edges()) { if (e->IsControlEdge()) continue; const Node* const src_node = e->src(); const int src_node_id = src_node->id(); if (!reachable_nodes[src_node_id]) { queue.push_back(src_node); reachable_nodes[src_node_id] = true; } } } return reachable_nodes; } std::unordered_set<int> SymbolicGradientBuilder::GetStopBackpropNodes( const std::vector<bool>& reachable_nodes, const std::unordered_set<int>& output_nodes) { // Output nodes that get transitively consumed by other `outputs_` are stored // in `internal_outputs`. std::unordered_set<int> internal_outputs; std::unordered_set<Node*> visited; // Initialize `queue` for BFS traversal. Nodes in `queue` hold upcoming nodes // along with the last Node in `output_` encountered along that path. If no // `output_` node was encountered, pair.second will be nullptr. std::deque<std::pair<Node*, Node*>> queue; for (const Output& nout : inputs_) { if (visited.find(nout.node()) == visited.end()) { queue.push_back(std::make_pair(nout.node(), static_cast<Node*>(nullptr))); visited.insert(nout.node()); } } // BFS from nodes in 'inputs_' along out edges for the entire graph. Internal // output nodes are recorded during the traversal. All nodes that are output // nodes but not internal output nodes are considered the frontier of the // output nodes, and thus our stop backprop nodes. while (!queue.empty()) { std::pair<Node*, Node*> p = queue.front(); Node* n = p.first; queue.pop_front(); for (const Edge* e : n->out_edges()) { // If a node is not reachable from outputs_, we can stop. if (e->IsControlEdge() || !reachable_nodes[e->dst()->id()]) continue; if (visited.find(e->dst()) != visited.end()) continue; int node_id = e->dst()->id(); Node* last_output_node = p.second; if (output_nodes.find(node_id) != output_nodes.end()) { // We reached an output node. if (last_output_node != nullptr) { // If we had already found an output node on this path so we mark // it as an internal output. internal_outputs.insert(last_output_node->id()); } // Mark this newly found output node to insert in the queue. last_output_node = e->dst(); } queue.push_back(std::make_pair(e->dst(), last_output_node)); visited.insert(e->dst()); } } // Finally, we set stop_backprop_nodes to all output_nodes that aren't also // internal_outputs. std::unordered_set<int> stop_backprop_nodes; for (int output_node : output_nodes) { if (internal_outputs.find(output_node) == internal_outputs.end()) { stop_backprop_nodes.insert(output_node); } } return stop_backprop_nodes; } Status SymbolicGradientBuilder::Initialize() { if (outputs_.size() != grad_inputs_.size()) { return errors::InvalidArgument( "Must specify a gradient input for each output."); } std::vector<bool> reachable_nodes = GetReachableNodes(); for (const Output& input : inputs_) { if (!reachable_nodes[input.node()->id()]) { return errors::InvalidArgument( "Cannot compute the partial derivative for node '", input.node()->name(), "' as it's unreachable from the output node(s)."); } } grad_outputs_->clear(); grad_outputs_->resize(inputs_.size()); std::unordered_set<int> output_nodes; output_nodes.reserve(outputs_.size()); for (size_t i = 0; i < outputs_.size(); ++i) { output_nodes.insert(outputs_[i].node()->id()); } std::unordered_set<int> stop_backprop_nodes = GetStopBackpropNodes(reachable_nodes, output_nodes); // Populate `input_nodes_` from Outputs in `inputs_`. input_nodes_.reserve(inputs_.size()); for (size_t i = 0; i < inputs_.size(); ++i) { input_nodes_.insert({inputs_[i], i}); } // TODO(andydavis) Consider a more efficient data structure for `pending_` to // handle computing gradients over small subgraphs from a very large graph. pending_.resize(scope_.graph()->num_node_ids(), 0); { backprops_.clear(); std::unordered_set<Node*> visited; std::deque<Node*> queue; for (const Output& nout : inputs_) { if (visited.find(nout.node()) == visited.end()) { queue.push_back(nout.node()); visited.insert(nout.node()); } } // Going forward to figure out which endpoints need backprop-ed. // A node's endpoints need to be backprop-ed only if one of the // arg node can reach the node via data edges. while (!queue.empty()) { Node* n = queue.front(); queue.pop_front(); for (int i = 0; i < n->num_outputs(); ++i) { backprops_[{n, i}].clear(); } int num_expected_backprops = 0; if (stop_backprop_nodes.find(n->id()) == stop_backprop_nodes.end()) { // Internal node: continue BFS along connected outputs. for (const Edge* e : n->out_edges()) { // If a node is not reachable from outputs_, // we don't expect it to receive a backpropagated gradient. // It will not be counted in num_expected_backprops. if (e->IsControlEdge() || !reachable_nodes[e->dst()->id()]) continue; if (visited.find(e->dst()) == visited.end()) { queue.push_back(e->dst()); visited.insert(e->dst()); } ++num_expected_backprops; } } if (output_nodes.find(n->id()) != output_nodes.end()) { // Output node: update `num_expected_backprops` for each Output in // `outputs_` that references `n`. for (const Output& output : outputs_) { if (output.node() == n) { ++num_expected_backprops; } } } pending_[n->id()] = num_expected_backprops; } } { // Initialize backprop with `grad_inputs_`. const size_t num_dy = grad_inputs_.size(); for (size_t i = 0; i < num_dy; ++i) { TF_RETURN_IF_ERROR(BackpropAlongEdge(grad_inputs_[i], outputs_[i])); } } return Status::OK(); } Status SymbolicGradientBuilder::SumGradients(const Output& src, Output* grad) { auto iter = backprops_.find(src); if (iter == backprops_.end()) { return errors::Internal( "Unable to find backprop list for node.id ", src.node()->name()); } const auto& grads = iter->second; // Filter any backproped 'NoGradient' Outputs from 'grads' (if needed). // Return any valid backproped gradients that remain after filtering, // or 'NoGradient' otherwise. std::vector<Output> grads_to_keep; for (const Output& o : grads) { if (o == NoGradient()) continue; grads_to_keep.push_back(o); } if (grads_to_keep.empty()) { // Nothing propagated back. Return 'NoGradient'. *grad = NoGradient(); } else if (grads_to_keep.size() == 1) { // Just one backprop edge. *grad = grads_to_keep[0]; } else { // Otherwise, adds backprop-ed gradients. // TODO(andydavis) Use a better accumulator here. *grad = ops::AddN(scope_, grads_to_keep); } return Status::OK(); } bool SymbolicGradientBuilder::IsPrimitiveOpWithNoGrad(const string& opname) { ops::GradFunc grad_fn; Status s = registry_->Lookup(opname, &grad_fn); return s.ok() && (grad_fn == nullptr); } Status SymbolicGradientBuilder::CallGradFunction( const Operation& op, const std::vector<Output>& grad_inputs, std::vector<Output>* grad_outputs) { ops::GradFunc grad_fn; TF_RETURN_IF_ERROR(registry_->Lookup(op.node()->type_string(), &grad_fn)); TF_RETURN_IF_ERROR(grad_fn(scope_, op, grad_inputs, grad_outputs)); TF_RETURN_IF_ERROR(scope_.status()); return Status::OK(); } Status SymbolicGradientBuilder::ProcessWhileLoop(Node* exit_node, const Output& summed_grads) { // TODO(skyewm): detect second-order gradient and return bad status // TODO(skyewm): handle (or at least detect) nested while loops // TODO(skyewm): handle NoGradient in while loop if (summed_grads == NoGradient()) { return errors::Unimplemented( "Missing gradient into while loop not yet implemented"); } DCHECK(exit_node->IsExit()); WhileContext* while_ctx = exit_node->while_ctx(); DCHECK(while_ctx != nullptr); // Record 'summed_grads' as the backprop input associated with 'exit_node' std::map<Node*, Output>& backprops = while_backprops_[while_ctx]; DCHECK(backprops.find(exit_node) == backprops.end()); backprops[exit_node] = summed_grads; // Wait until we have all exit nodes' backprops collected before processing // the while loop. // TODO(skyewm): what if not all the exit nodes are reachable? if (backprops.size() < while_ctx->exit_nodes().size()) return Status::OK(); // We've seen all the exit nodes for this loop and have collected all the // backprops. Create the gradient graph for the while loop. Scope while_scope = scope_.NewSubScope(strings::StrCat(while_ctx->frame_name(), "_grad")); std::vector<Output> dy; for (Node* n : while_ctx->exit_nodes()) dy.push_back(backprops[n]); std::vector<Output> dx; TF_RETURN_IF_ERROR(AddWhileLoopGradient(while_ctx, while_scope, dy, &dx)); // Backprop along the in edges to the while loop (i.e. the inputs to the enter // nodes) DCHECK_EQ(dx.size(), while_ctx->enter_nodes().size()); for (int i = 0; i < dx.size(); ++i) { Node* enter_node = while_ctx->enter_nodes()[i]; for (const Edge* e : enter_node->in_edges()) { if (e->IsControlEdge()) continue; TF_RETURN_IF_ERROR(BackpropAlongEdge(dx[i], {e->src(), e->src_output()})); } } return Status::OK(); } Status SymbolicGradientBuilder::AddGradients() { // Initialize backprops. TF_RETURN_IF_ERROR(Initialize()); // Backward propagation. std::vector<Output> dy; while (!ready_.empty()) { // n has collected all gradients. Node* n = ready_.front(); ready_.pop_front(); // dy[i] is the sum of i-th output's backpropped gradients. const int num_y = n->num_outputs(); dy.clear(); dy.resize(num_y, {nullptr, 0}); std::vector<int> no_grad_dy_indices; for (int i = 0; i < num_y; ++i) { TF_RETURN_IF_ERROR(SumGradients({n, i}, &dy[i])); if (dy[i] == NoGradient()) { no_grad_dy_indices.push_back(i); } auto iter = input_nodes_.find({n, i}); if (iter != input_nodes_.end()) { // Return gradients for Output in 'grad_outputs_'. (*grad_outputs_)[iter->second] = dy[i]; } } // Stop backprop if none of the inputs to `n` are in `backprops_'. bool stop_node = true; for (const Edge* e : n->in_edges()) { if (e->IsControlEdge()) continue; if (backprops_.find({e->src(), e->src_output()}) != backprops_.end()) { stop_node = false; break; } } if (stop_node) { continue; } // Special case: if we find an exit node, process the associated while loop. // Note that ProcessWhileLoop() calls BackpropAlongEdge() if necessary // (which updates ready_), and we skip all the regular processing below // after calling it. if (n->IsExit()) { DCHECK_EQ(dy.size(), 1); TF_RETURN_IF_ERROR(ProcessWhileLoop(n, dy[0])); continue; } // All loop-specific control flow ops should have been handled above DCHECK(!n->IsEnter() && !n->IsNextIteration()) << n->DebugString(); const size_t num_no_grad = no_grad_dy_indices.size(); if (IsPrimitiveOpWithNoGrad(n->type_string()) || num_no_grad == num_y) { // No grad defined for this op, or all outputs returned 'NoGradient': // Backprop 'NoGradient' along the in edges. for (const Edge* e : n->in_edges()) { if (e->IsControlEdge()) continue; TF_RETURN_IF_ERROR( BackpropAlongEdge(NoGradient(), {e->src(), e->src_output()})); } continue; } if (num_no_grad > 0 && num_no_grad < num_y) { // The outputs of 'n' returned a mixture of valid gradients and // 'NoGradient'. Therefore, we need to add 'ZerosLike' nodes for each // 'NoGradient' output before we call the gradient function for 'n'. // TODO(andydavis) If static shapes are known, replace 'ZerosLike' with // zero-filled Constant node of appropriate shape. for (const int dy_index : no_grad_dy_indices) { dy[dy_index] = ops::ZerosLike(scope_, Output(n, dy_index)); } } // TODO(andydavis) Add option to encapsulate grad function in // SymbolicGradientOp (as opposed to inlining into the graph). std::vector<Output> dx; TF_RETURN_IF_ERROR(CallGradFunction(Operation(n), dy, &dx)); // Backprop along the in edges. // TODO(andydavis) Find cleaner way to map each grad output returned by // gradient function to the src node/output to which it should be // backproped. Maybe grad functions can return a vector of Output pairs to // make this association explicit. size_t dx_index = 0; for (const Edge* e : n->in_edges()) { if (e->IsControlEdge()) continue; if (dx_index == dx.size()) { return errors::Internal( "Invalid gradient output index: ", dx_index, " size: ", dx.size()); } TF_RETURN_IF_ERROR( BackpropAlongEdge(dx[dx_index++], {e->src(), e->src_output()})); } } // Check if any input nodes still have pending gradients and have not been // processed yet. This happens if not all outputs of a node are in 'inputs_'. std::unordered_map<Node*, int> requested_grads; for (const Output& nout : inputs_) { if (pending_[nout.node()->id()] > 0) { DCHECK_GT(nout.node()->num_outputs(), 1); int idx = input_nodes_[nout]; DCHECK(((*grad_outputs_)[idx].node() == nullptr)); TF_RETURN_IF_ERROR(SumGradients(nout, &(*grad_outputs_)[idx])); ++requested_grads[nout.node()]; } } for (const auto& p : requested_grads) { int num_requested_inputs = p.first->num_outputs() - pending_[p.first->id()]; CHECK_EQ(num_requested_inputs, p.second); } return Status::OK(); } } // namespace Status AddSymbolicGradients(const Scope& scope, const std::vector<Output>& outputs, const std::vector<Output>& inputs, const std::vector<Output>& grad_inputs, std::vector<Output>* grad_outputs) { SymbolicGradientBuilder builder(scope, ops::GradOpRegistry::Global(), outputs, inputs, grad_inputs, grad_outputs); return builder.AddGradients(); } Status AddSymbolicGradients(const Scope& scope, const std::vector<Output>& outputs, const std::vector<Output>& inputs, std::vector<Output>* grad_outputs) { std::vector<Output> grad_inputs; grad_inputs.reserve(outputs.size()); for (const Output& output : outputs) { grad_inputs.emplace_back(ops::OnesLike(scope, output)); } return AddSymbolicGradients(scope, outputs, inputs, grad_inputs, grad_outputs); } Output NoGradient() { return SymbolicGradientBuilder::NoGradient(); } } // end namespace tensorflow const removed /* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <deque> #include <vector> #include "tensorflow/cc/framework/grad_op_registry.h" #include "tensorflow/cc/framework/gradients.h" #include "tensorflow/cc/framework/while_gradients.h" #include "tensorflow/cc/ops/standard_ops.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/graph/algorithm.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/graph/while_context.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/platform/macros.h" namespace tensorflow { namespace { struct OutputHash { uint64 operator()(const Output& x) const { return x.hash(); } }; struct OutputEq { bool operator()(const Output& x, const Output& y) const { return (x.node() == y.node()) && (x.index() == y.index()); } }; class SymbolicGradientBuilder { public: SymbolicGradientBuilder(const Scope& scope, const ops::GradOpRegistry* registry, const std::vector<Output>& outputs, const std::vector<Output>& inputs, const std::vector<Output>& grad_inputs, std::vector<Output>* grad_outputs); Status AddGradients(); static Output NoGradient() { return Output(nullptr, -1); } private: Status Initialize(); // For each forward edge from `src` to `dst` in the initial/forward graph: // propagates gradients `dst_grad` backwards along the edge from `src` // to `dst` in the graph. This will add `dst_grad` to the list of pending // gradients for the node associated with `src`. Status BackpropAlongEdge(const Output& dst_grad, const Output& src); // Adds a node to the graph (returned in `grad`) that sums the in-bound // gradients to `src` (if there are more than one). Status SumGradients(const Output& src, Output* grad); // Returns true if `opname` is registered in `registry_` with no gradient // function, false otherwise. bool IsPrimitiveOpWithNoGrad(const string& opname); // Call the gradient function for `op`, storing the result in `grad_outputs`. Status CallGradFunction(const Operation& op, const std::vector<Output>& grad_inputs, std::vector<Output>* grad_outputs); // Returns a list mapping whether each node in the graph is reachable // from outputs_. Keyed by node id. std::vector<bool> GetReachableNodes(); // Creates the gradient subgraph for a while loop (or just stores // `summed_grads` if not all incoming gradients are available yet). All exit // nodes (which are the first nodes of a loop encountered in the backwards // pass) are passed to this function rather than processed normally. // `summed_grads` is the sum of `exit_node`s gradients. Status ProcessWhileLoop(Node* exit_node, const Output& summed_grads); // Gets the set of node ids at which to stop backprop. These are all elements // of `outputs_` that do not get transitively consumed by other `outputs_`. // Used to identify nodes at which to stop backprop. std::unordered_set<int> GetStopBackpropNodes( const std::vector<bool>& reachable_nodes, const std::unordered_set<int>& output_nodes); const Scope& scope_; const ops::GradOpRegistry* registry_; const std::vector<Output>& outputs_; const std::vector<Output>& inputs_; const std::vector<Output>& grad_inputs_; std::vector<Output>* grad_outputs_; // A vector of output endpoints which represents backpropagated gradients. typedef std::vector<Output> BackproppedGradients; // backprops_ is a map from a node output to its accumulated // gradients. When a node output has accumulated all its // gradients, we add a node which sums them up. std::unordered_map<Output, BackproppedGradients, OutputHash, OutputEq> backprops_; // pending[i] is count-down counter for i-th node's expected // backprops. When pending[i] becomes zero, we collected all // backprop gradients for all outputs of the ith-node. std::vector<int> pending_; // `ready` keeps track of nodes that have been completely // backpropped. Initially, for every output in `outputs_`, we add initial // gradients from `grad_inputs_`. std::deque<Node*> ready_; // The set of node ids in `inputs_`. Used to identify nodes at backprop // frontier. Maps from Output -> index into `grad_outputs_`. std::unordered_map<Output, int, OutputHash, OutputEq> input_nodes_; // For each while loop in the graph, collects the summed gradients for each of // the loop's exit nodes. Note that unlike backprops_, this map contains the // output of SumGradients(), not the input (i.e. each exit node may have // multiple incoming gradients, but we only store the combined Output here). std::map<WhileContext*, std::map<Node*, Output>> while_backprops_; TF_DISALLOW_COPY_AND_ASSIGN(SymbolicGradientBuilder); }; SymbolicGradientBuilder::SymbolicGradientBuilder( const Scope& scope, const ops::GradOpRegistry* registry, const std::vector<Output>& outputs, const std::vector<Output>& inputs, const std::vector<Output>& grad_inputs, std::vector<Output>* grad_outputs) : scope_(scope), registry_(registry), outputs_(outputs), inputs_(inputs), grad_inputs_(grad_inputs), grad_outputs_(grad_outputs) {} Status SymbolicGradientBuilder::BackpropAlongEdge(const Output& dst_grad, const Output& src) { if (src.node() == nullptr) { return errors::Internal("Attempted to backprop along an invalid edge."); } auto iter = backprops_.find(src); if (iter != backprops_.end()) { auto* grads = &iter->second; grads->push_back(dst_grad); if (--pending_[src.node()->id()] == 0) { ready_.push_back(src.node()); } } return Status::OK(); } std::vector<bool> SymbolicGradientBuilder::GetReachableNodes() { std::vector<bool> reachable_nodes(scope_.graph()->num_node_ids(), false); std::deque<Node*> queue; for (const Output& out : outputs_) { Node* const out_node = out.node(); const int out_node_id = out_node->id(); if (!reachable_nodes[out_node_id]) { queue.push_back(out_node); reachable_nodes[out_node_id] = true; } } while (!queue.empty()) { Node* n = queue.front(); queue.pop_front(); for (const Edge* e : n->in_edges()) { if (e->IsControlEdge()) continue; Node* const src_node = e->src(); const int src_node_id = src_node->id(); if (!reachable_nodes[src_node_id]) { queue.push_back(src_node); reachable_nodes[src_node_id] = true; } } } return reachable_nodes; } std::unordered_set<int> SymbolicGradientBuilder::GetStopBackpropNodes( const std::vector<bool>& reachable_nodes, const std::unordered_set<int>& output_nodes) { // Output nodes that get transitively consumed by other `outputs_` are stored // in `internal_outputs`. std::unordered_set<int> internal_outputs; std::unordered_set<Node*> visited; // Initialize `queue` for BFS traversal. Nodes in `queue` hold upcoming nodes // along with the last Node in `output_` encountered along that path. If no // `output_` node was encountered, pair.second will be nullptr. std::deque<std::pair<Node*, Node*>> queue; for (const Output& nout : inputs_) { if (visited.find(nout.node()) == visited.end()) { queue.push_back(std::make_pair(nout.node(), static_cast<Node*>(nullptr))); visited.insert(nout.node()); } } // BFS from nodes in 'inputs_' along out edges for the entire graph. Internal // output nodes are recorded during the traversal. All nodes that are output // nodes but not internal output nodes are considered the frontier of the // output nodes, and thus our stop backprop nodes. while (!queue.empty()) { std::pair<Node*, Node*> p = queue.front(); Node* n = p.first; queue.pop_front(); for (const Edge* e : n->out_edges()) { // If a node is not reachable from outputs_, we can stop. if (e->IsControlEdge() || !reachable_nodes[e->dst()->id()]) continue; if (visited.find(e->dst()) != visited.end()) continue; int node_id = e->dst()->id(); Node* last_output_node = p.second; if (output_nodes.find(node_id) != output_nodes.end()) { // We reached an output node. if (last_output_node != nullptr) { // If we had already found an output node on this path so we mark // it as an internal output. internal_outputs.insert(last_output_node->id()); } // Mark this newly found output node to insert in the queue. last_output_node = e->dst(); } queue.push_back(std::make_pair(e->dst(), last_output_node)); visited.insert(e->dst()); } } // Finally, we set stop_backprop_nodes to all output_nodes that aren't also // internal_outputs. std::unordered_set<int> stop_backprop_nodes; for (int output_node : output_nodes) { if (internal_outputs.find(output_node) == internal_outputs.end()) { stop_backprop_nodes.insert(output_node); } } return stop_backprop_nodes; } Status SymbolicGradientBuilder::Initialize() { if (outputs_.size() != grad_inputs_.size()) { return errors::InvalidArgument( "Must specify a gradient input for each output."); } std::vector<bool> reachable_nodes = GetReachableNodes(); for (const Output& input : inputs_) { if (!reachable_nodes[input.node()->id()]) { return errors::InvalidArgument( "Cannot compute the partial derivative for node '", input.node()->name(), "' as it's unreachable from the output node(s)."); } } grad_outputs_->clear(); grad_outputs_->resize(inputs_.size()); std::unordered_set<int> output_nodes; output_nodes.reserve(outputs_.size()); for (size_t i = 0; i < outputs_.size(); ++i) { output_nodes.insert(outputs_[i].node()->id()); } std::unordered_set<int> stop_backprop_nodes = GetStopBackpropNodes(reachable_nodes, output_nodes); // Populate `input_nodes_` from Outputs in `inputs_`. input_nodes_.reserve(inputs_.size()); for (size_t i = 0; i < inputs_.size(); ++i) { input_nodes_.insert({inputs_[i], i}); } // TODO(andydavis) Consider a more efficient data structure for `pending_` to // handle computing gradients over small subgraphs from a very large graph. pending_.resize(scope_.graph()->num_node_ids(), 0); { backprops_.clear(); std::unordered_set<Node*> visited; std::deque<Node*> queue; for (const Output& nout : inputs_) { if (visited.find(nout.node()) == visited.end()) { queue.push_back(nout.node()); visited.insert(nout.node()); } } // Going forward to figure out which endpoints need backprop-ed. // A node's endpoints need to be backprop-ed only if one of the // arg node can reach the node via data edges. while (!queue.empty()) { Node* n = queue.front(); queue.pop_front(); for (int i = 0; i < n->num_outputs(); ++i) { backprops_[{n, i}].clear(); } int num_expected_backprops = 0; if (stop_backprop_nodes.find(n->id()) == stop_backprop_nodes.end()) { // Internal node: continue BFS along connected outputs. for (const Edge* e : n->out_edges()) { // If a node is not reachable from outputs_, // we don't expect it to receive a backpropagated gradient. // It will not be counted in num_expected_backprops. if (e->IsControlEdge() || !reachable_nodes[e->dst()->id()]) continue; if (visited.find(e->dst()) == visited.end()) { queue.push_back(e->dst()); visited.insert(e->dst()); } ++num_expected_backprops; } } if (output_nodes.find(n->id()) != output_nodes.end()) { // Output node: update `num_expected_backprops` for each Output in // `outputs_` that references `n`. for (const Output& output : outputs_) { if (output.node() == n) { ++num_expected_backprops; } } } pending_[n->id()] = num_expected_backprops; } } { // Initialize backprop with `grad_inputs_`. const size_t num_dy = grad_inputs_.size(); for (size_t i = 0; i < num_dy; ++i) { TF_RETURN_IF_ERROR(BackpropAlongEdge(grad_inputs_[i], outputs_[i])); } } return Status::OK(); } Status SymbolicGradientBuilder::SumGradients(const Output& src, Output* grad) { auto iter = backprops_.find(src); if (iter == backprops_.end()) { return errors::Internal( "Unable to find backprop list for node.id ", src.node()->name()); } const auto& grads = iter->second; // Filter any backproped 'NoGradient' Outputs from 'grads' (if needed). // Return any valid backproped gradients that remain after filtering, // or 'NoGradient' otherwise. std::vector<Output> grads_to_keep; for (const Output& o : grads) { if (o == NoGradient()) continue; grads_to_keep.push_back(o); } if (grads_to_keep.empty()) { // Nothing propagated back. Return 'NoGradient'. *grad = NoGradient(); } else if (grads_to_keep.size() == 1) { // Just one backprop edge. *grad = grads_to_keep[0]; } else { // Otherwise, adds backprop-ed gradients. // TODO(andydavis) Use a better accumulator here. *grad = ops::AddN(scope_, grads_to_keep); } return Status::OK(); } bool SymbolicGradientBuilder::IsPrimitiveOpWithNoGrad(const string& opname) { ops::GradFunc grad_fn; Status s = registry_->Lookup(opname, &grad_fn); return s.ok() && (grad_fn == nullptr); } Status SymbolicGradientBuilder::CallGradFunction( const Operation& op, const std::vector<Output>& grad_inputs, std::vector<Output>* grad_outputs) { ops::GradFunc grad_fn; TF_RETURN_IF_ERROR(registry_->Lookup(op.node()->type_string(), &grad_fn)); TF_RETURN_IF_ERROR(grad_fn(scope_, op, grad_inputs, grad_outputs)); TF_RETURN_IF_ERROR(scope_.status()); return Status::OK(); } Status SymbolicGradientBuilder::ProcessWhileLoop(Node* exit_node, const Output& summed_grads) { // TODO(skyewm): detect second-order gradient and return bad status // TODO(skyewm): handle (or at least detect) nested while loops // TODO(skyewm): handle NoGradient in while loop if (summed_grads == NoGradient()) { return errors::Unimplemented( "Missing gradient into while loop not yet implemented"); } DCHECK(exit_node->IsExit()); WhileContext* while_ctx = exit_node->while_ctx(); DCHECK(while_ctx != nullptr); // Record 'summed_grads' as the backprop input associated with 'exit_node' std::map<Node*, Output>& backprops = while_backprops_[while_ctx]; DCHECK(backprops.find(exit_node) == backprops.end()); backprops[exit_node] = summed_grads; // Wait until we have all exit nodes' backprops collected before processing // the while loop. // TODO(skyewm): what if not all the exit nodes are reachable? if (backprops.size() < while_ctx->exit_nodes().size()) return Status::OK(); // We've seen all the exit nodes for this loop and have collected all the // backprops. Create the gradient graph for the while loop. Scope while_scope = scope_.NewSubScope(strings::StrCat(while_ctx->frame_name(), "_grad")); std::vector<Output> dy; for (Node* n : while_ctx->exit_nodes()) dy.push_back(backprops[n]); std::vector<Output> dx; TF_RETURN_IF_ERROR(AddWhileLoopGradient(while_ctx, while_scope, dy, &dx)); // Backprop along the in edges to the while loop (i.e. the inputs to the enter // nodes) DCHECK_EQ(dx.size(), while_ctx->enter_nodes().size()); for (int i = 0; i < dx.size(); ++i) { Node* enter_node = while_ctx->enter_nodes()[i]; for (const Edge* e : enter_node->in_edges()) { if (e->IsControlEdge()) continue; TF_RETURN_IF_ERROR(BackpropAlongEdge(dx[i], {e->src(), e->src_output()})); } } return Status::OK(); } Status SymbolicGradientBuilder::AddGradients() { // Initialize backprops. TF_RETURN_IF_ERROR(Initialize()); // Backward propagation. std::vector<Output> dy; while (!ready_.empty()) { // n has collected all gradients. Node* n = ready_.front(); ready_.pop_front(); // dy[i] is the sum of i-th output's backpropped gradients. const int num_y = n->num_outputs(); dy.clear(); dy.resize(num_y, {nullptr, 0}); std::vector<int> no_grad_dy_indices; for (int i = 0; i < num_y; ++i) { TF_RETURN_IF_ERROR(SumGradients({n, i}, &dy[i])); if (dy[i] == NoGradient()) { no_grad_dy_indices.push_back(i); } auto iter = input_nodes_.find({n, i}); if (iter != input_nodes_.end()) { // Return gradients for Output in 'grad_outputs_'. (*grad_outputs_)[iter->second] = dy[i]; } } // Stop backprop if none of the inputs to `n` are in `backprops_'. bool stop_node = true; for (const Edge* e : n->in_edges()) { if (e->IsControlEdge()) continue; if (backprops_.find({e->src(), e->src_output()}) != backprops_.end()) { stop_node = false; break; } } if (stop_node) { continue; } // Special case: if we find an exit node, process the associated while loop. // Note that ProcessWhileLoop() calls BackpropAlongEdge() if necessary // (which updates ready_), and we skip all the regular processing below // after calling it. if (n->IsExit()) { DCHECK_EQ(dy.size(), 1); TF_RETURN_IF_ERROR(ProcessWhileLoop(n, dy[0])); continue; } // All loop-specific control flow ops should have been handled above DCHECK(!n->IsEnter() && !n->IsNextIteration()) << n->DebugString(); const size_t num_no_grad = no_grad_dy_indices.size(); if (IsPrimitiveOpWithNoGrad(n->type_string()) || num_no_grad == num_y) { // No grad defined for this op, or all outputs returned 'NoGradient': // Backprop 'NoGradient' along the in edges. for (const Edge* e : n->in_edges()) { if (e->IsControlEdge()) continue; TF_RETURN_IF_ERROR( BackpropAlongEdge(NoGradient(), {e->src(), e->src_output()})); } continue; } if (num_no_grad > 0 && num_no_grad < num_y) { // The outputs of 'n' returned a mixture of valid gradients and // 'NoGradient'. Therefore, we need to add 'ZerosLike' nodes for each // 'NoGradient' output before we call the gradient function for 'n'. // TODO(andydavis) If static shapes are known, replace 'ZerosLike' with // zero-filled Constant node of appropriate shape. for (const int dy_index : no_grad_dy_indices) { dy[dy_index] = ops::ZerosLike(scope_, Output(n, dy_index)); } } // TODO(andydavis) Add option to encapsulate grad function in // SymbolicGradientOp (as opposed to inlining into the graph). std::vector<Output> dx; TF_RETURN_IF_ERROR(CallGradFunction(Operation(n), dy, &dx)); // Backprop along the in edges. // TODO(andydavis) Find cleaner way to map each grad output returned by // gradient function to the src node/output to which it should be // backproped. Maybe grad functions can return a vector of Output pairs to // make this association explicit. size_t dx_index = 0; for (const Edge* e : n->in_edges()) { if (e->IsControlEdge()) continue; if (dx_index == dx.size()) { return errors::Internal( "Invalid gradient output index: ", dx_index, " size: ", dx.size()); } TF_RETURN_IF_ERROR( BackpropAlongEdge(dx[dx_index++], {e->src(), e->src_output()})); } } // Check if any input nodes still have pending gradients and have not been // processed yet. This happens if not all outputs of a node are in 'inputs_'. std::unordered_map<Node*, int> requested_grads; for (const Output& nout : inputs_) { if (pending_[nout.node()->id()] > 0) { DCHECK_GT(nout.node()->num_outputs(), 1); int idx = input_nodes_[nout]; DCHECK(((*grad_outputs_)[idx].node() == nullptr)); TF_RETURN_IF_ERROR(SumGradients(nout, &(*grad_outputs_)[idx])); ++requested_grads[nout.node()]; } } for (const auto& p : requested_grads) { int num_requested_inputs = p.first->num_outputs() - pending_[p.first->id()]; CHECK_EQ(num_requested_inputs, p.second); } return Status::OK(); } } // namespace Status AddSymbolicGradients(const Scope& scope, const std::vector<Output>& outputs, const std::vector<Output>& inputs, const std::vector<Output>& grad_inputs, std::vector<Output>* grad_outputs) { SymbolicGradientBuilder builder(scope, ops::GradOpRegistry::Global(), outputs, inputs, grad_inputs, grad_outputs); return builder.AddGradients(); } Status AddSymbolicGradients(const Scope& scope, const std::vector<Output>& outputs, const std::vector<Output>& inputs, std::vector<Output>* grad_outputs) { std::vector<Output> grad_inputs; grad_inputs.reserve(outputs.size()); for (const Output& output : outputs) { grad_inputs.emplace_back(ops::OnesLike(scope, output)); } return AddSymbolicGradients(scope, outputs, inputs, grad_inputs, grad_outputs); } Output NoGradient() { return SymbolicGradientBuilder::NoGradient(); } } // end namespace tensorflow
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/grappler/op_types.h" namespace tensorflow { namespace grappler { bool IsConcat(const NodeDef& node) { const auto op = node.op(); return op == "Concat" || op == "ConcatV2"; } bool IsConstant(const NodeDef& node) { const auto op = node.op(); return op == "Const"; } bool IsDequeueOp(const NodeDef& node) { static const std::set<std::string> dequeue_ops = { "QueueDequeueManyV2", "QueueDequeueMany", "QueueDequeueV2", "QueueDequeue"}; return dequeue_ops.count(node.op()) > 0; } bool IsMerge(const NodeDef& node) { const auto op = node.op(); return op == "Merge"; } bool IsPlaceholder(const NodeDef& node) { const auto op = node.op(); return op == "Placeholder" || op == "PlaceholderV2" || op == "PlaceholderWithDefault"; } bool IsTranspose(const NodeDef& node) { const auto op = node.op(); return op == "Transpose"; } bool IsVariable(const NodeDef& node) { const auto op = node.op(); return op == "Variable" || op == "VariableV2" || op == "AutoReloadVariable" || op == "VarHandleOp" || op == "TemporaryVariable"; } } // end namespace grappler } // end namespace tensorflow Add QueueDequeueUpTo to the list of dequeue ops PiperOrigin-RevId: 157760201 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/grappler/op_types.h" namespace tensorflow { namespace grappler { bool IsConcat(const NodeDef& node) { const auto op = node.op(); return op == "Concat" || op == "ConcatV2"; } bool IsConstant(const NodeDef& node) { const auto op = node.op(); return op == "Const"; } bool IsDequeueOp(const NodeDef& node) { static const std::set<std::string> dequeue_ops = { "QueueDequeueManyV2", "QueueDequeueMany", "QueueDequeueV2", "QueueDequeue", "QueueDequeueUpToV2", "QueueDequeueUpTo"}; return dequeue_ops.count(node.op()) > 0; } bool IsMerge(const NodeDef& node) { const auto op = node.op(); return op == "Merge"; } bool IsPlaceholder(const NodeDef& node) { const auto op = node.op(); return op == "Placeholder" || op == "PlaceholderV2" || op == "PlaceholderWithDefault"; } bool IsTranspose(const NodeDef& node) { const auto op = node.op(); return op == "Transpose"; } bool IsVariable(const NodeDef& node) { const auto op = node.op(); return op == "Variable" || op == "VariableV2" || op == "AutoReloadVariable" || op == "VarHandleOp" || op == "TemporaryVariable"; } } // end namespace grappler } // end namespace tensorflow
#include "../src/ForceFields/LennardJonesFF.h" #include "../src/ForceFields/ForceFieldManager.h" #include "../src/Simulation/StandardSimulation.h" #include "../src/Moves/MoveManager.h" #include "../src/Moves/TranslateMove.h" #include "../src/Moves/InsertParticleMove.h" #include "../src/Moves/DeleteParticleMove.h" #include "../src/Particles/Site.h" #include "../src/Particles/Molecule.h" #include "../src/Worlds/World.h" #include "../src/Worlds/WorldManager.h" #include "TestAccumulator.h" #include "json/json.h" #include "gtest/gtest.h" #include "../src/Observers/DLMFileObserver.h" #include <fstream> using namespace SAPHRON; // Grand canonical simulation tests. TEST(GrandCanonicalEnsembleTests, Default) { auto N = 500; auto sigma = 1.; auto eps = 1.; auto T = 1.50; auto V = 250.047; auto rcut = 3.*sigma; // Prototype particle. Site lj({0, 0, 0}, {0, 0, 0}, "LJ"); // Initialze world, set chemical potential and pack with lj. World world(1, 1, 1, rcut); world.SetNeighborRadius(rcut + 1.0); world.PackWorld({&lj}, {1.0}, N, 0.6); world.SetChemicalPotential("LJ", 2.0); world.SetTemperature(T); world.SetVolume(V, true); // Override volume. This will be fixed. // Initialize world manager. WorldManager wm; wm.AddWorld(&world); ASSERT_EQ(N, world.GetParticleCount()); ASSERT_DOUBLE_EQ(V, world.GetVolume()); // Initialize LJ forcefield. LennardJonesFF ff(eps, sigma); ForceFieldManager ffm; ffm.AddNonBondedForceField("LJ", "LJ", ff); // Initialize moves. MoveManager mm; TranslateMove move1(0.22); mm.AddMove(&move1, 75); InsertParticleMove move2({"LJ"}, wm, 500); mm.AddMove(&move2, 12); DeleteParticleMove move3({"LJ"}); mm.AddMove(&move3, 12); // Initialize observer. SimFlags flags; flags.world_on(); flags.simulation_on(); DLMFileObserver dlm("gcmc.test", flags); // Initialize ensemble. StandardSimulation ensemble(&wm, &ffm, &mm); ensemble.AddObserver(&dlm); ASSERT_EQ(N, world.GetParticleCount()); // Run ensemble.Run(10000); } Updated GCMC test. #include "../src/ForceFields/LennardJonesFF.h" #include "../src/ForceFields/ForceFieldManager.h" #include "../src/Simulation/StandardSimulation.h" #include "../src/Moves/MoveManager.h" #include "../src/Moves/TranslateMove.h" #include "../src/Moves/InsertParticleMove.h" #include "../src/Moves/DeleteParticleMove.h" #include "../src/Particles/Site.h" #include "../src/Particles/Molecule.h" #include "../src/Worlds/World.h" #include "../src/Worlds/WorldManager.h" #include "TestAccumulator.h" #include "json/json.h" #include "gtest/gtest.h" #include "../src/Observers/DLMFileObserver.h" #include <fstream> using namespace SAPHRON; // Grand canonical simulation tests. TEST(GrandCanonicalEnsembleTests, Default) { auto N = 500; auto sigma = 1.; auto eps = 1.; auto T = 1.50; auto V = 512.0; auto rcut = 3.*sigma; // Prototype particle. Site lj({0, 0, 0}, {0, 0, 0}, "LJ"); // Initialze world, set chemical potential and pack with lj. World world(1, 1, 1, rcut); world.SetNeighborRadius(rcut + 1.0); world.PackWorld({&lj}, {1.0}, N, 0.6); world.SetChemicalPotential("LJ", -2.0); world.SetTemperature(T); world.SetVolume(V, true); // Override volume. This will be fixed. // Initialize world manager. WorldManager wm; wm.AddWorld(&world); ASSERT_EQ(N, world.GetParticleCount()); ASSERT_DOUBLE_EQ(V, world.GetVolume()); // Initialize LJ forcefield. LennardJonesFF ff(eps, sigma); ForceFieldManager ffm; ffm.AddNonBondedForceField("LJ", "LJ", ff); // Initialize moves. MoveManager mm; TranslateMove move1(0.22); mm.AddMove(&move1, 75); InsertParticleMove move2({"LJ"}, wm, 500); mm.AddMove(&move2, 12); DeleteParticleMove move3({"LJ"}); mm.AddMove(&move3, 12); // Initialize observer. SimFlags flags; flags.world_on(); flags.simulation_on(); TestAccumulator observer(flags, 1, 6000); // Initialize ensemble. StandardSimulation ensemble(&wm, &ffm, &mm); ensemble.AddObserver(&observer); ASSERT_EQ(N, world.GetParticleCount()); // Run ensemble.Run(20000); auto rhos = observer.GetAverageDensities(); ASSERT_NEAR(rhos[&world], 0.64, 1e-2); auto Ps = observer.GetAveragePressures(); ASSERT_NEAR(Ps[&world].isotropic(), 1.04, 1e-2); }
#include "Server.h" #include "Logger.h" #include "common.h" #include "fmitcp.pb.h" using namespace fmitcp; void serverOnConnect(lw_server s, lw_client c) { Server * server = (Server*)lw_server_tag(s); server->clientConnected(c); lw_fdstream_nagle(c,lw_false); } void serverOnData(lw_server s, lw_client client, const char* data, size_t size) { Server * server = (Server*)lw_server_tag(s); server->clientData(client,data,size); } void serverOnDisconnect(lw_server s, lw_client c) { Server * server = (Server*)lw_server_tag(s); server->clientDisconnected(c); } void serverOnError(lw_server s, lw_error error) { Server * server = (Server*)lw_server_tag(s); server->error(s,error); } /*! * Callback function for FMILibrary. Logs the FMILibrary operations. */ void jmCallbacksLogger(jm_callbacks* c, jm_string module, jm_log_level_enu_t log_level, jm_string message) { printf("[module = %s][log level = %s] %s\n", module, jm_log_level_to_string(log_level), message);fflush(NULL); } void Server::error(lw_server s, lw_error error) { string err = lw_error_tostring(error); onError(err); } Server::Server(string fmuPath, bool debugLogging, jm_log_level_enu_t logLevel, EventPump *pump) { m_fmuParsed = true; m_fmuPath = fmuPath; m_debugLogging = debugLogging; m_logLevel = logLevel; init(pump); } Server::Server(string fmuPath, bool debugLogging, jm_log_level_enu_t logLevel, EventPump *pump, const Logger &logger) { m_fmuParsed = true; m_fmuPath = fmuPath; m_debugLogging = debugLogging; m_logLevel = logLevel; m_logger = logger; init(pump); } Server::~Server() { lw_server_delete(m_server); } void Server::init(EventPump * pump) { m_pump = pump; m_server = lw_server_new(pump->getPump()); m_sendDummyResponses = false; if(m_fmuPath == "dummy"){ m_sendDummyResponses = true; m_fmuParsed = true; return; } // Parse FMU // JM callbacks m_jmCallbacks.malloc = malloc; m_jmCallbacks.calloc = calloc; m_jmCallbacks.realloc = realloc; m_jmCallbacks.free = free; m_jmCallbacks.logger = jmCallbacksLogger; m_jmCallbacks.log_level = m_logLevel; m_jmCallbacks.context = 0; // working directory char* dir = fmi_import_mk_temp_dir(&m_jmCallbacks, NULL, "fmitcp_"); m_workingDir = dir; // convert to std::string free(dir); // import allocate context m_context = fmi_import_allocate_context(&m_jmCallbacks); // get FMU version m_version = fmi_import_get_fmi_version(m_context, m_fmuPath.c_str(), m_workingDir.c_str()); // Check version OK if ((m_version <= fmi_version_unknown_enu) || (m_version >= fmi_version_unsupported_enu)) { fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); m_logger.log(Logger::LOG_ERROR, "Unsupported/unknown FMU version: '%s'.\n", fmi_version_to_string(m_version)); m_fmuParsed = false; return; } if (m_version == fmi_version_2_0_enu) { // FMI 2.0 // parse the xml file m_fmi2Instance = fmi2_import_parse_xml(m_context, m_workingDir.c_str(), 0); if(!m_fmi2Instance) { fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); m_logger.log(Logger::LOG_ERROR, "Error parsing the modelDescription.xml file contained in %s\n", m_workingDir.c_str()); m_fmuParsed = false; return; } // check FMU kind fmi2_fmu_kind_enu_t fmuType = fmi2_import_get_fmu_kind(m_fmi2Instance); if(fmuType != fmi2_fmu_kind_cs && fmuType != fmi2_fmu_kind_me_and_cs) { fmi2_import_free(m_fmi2Instance); fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); m_logger.log(Logger::LOG_ERROR, "Only FMI Co-Simulation 2.0 is supported.\n"); m_fmuParsed = false; return; } // FMI callback functions m_fmi2CallbackFunctions.logger = fmi2_log_forwarding; m_fmi2CallbackFunctions.allocateMemory = calloc; m_fmi2CallbackFunctions.freeMemory = free; m_fmi2CallbackFunctions.stepFinished = 0; m_fmi2CallbackFunctions.componentEnvironment = 0; // Load the binary (dll/so) jm_status_enu_t status = fmi2_import_create_dllfmu(m_fmi2Instance, fmuType, &m_fmi2CallbackFunctions); if (status == jm_status_error) { fmi2_import_free(m_fmi2Instance); fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); m_logger.log(Logger::LOG_ERROR, "There was an error loading the FMU binary. Turn on logging (-l) for more info.\n"); m_fmuParsed = false; return; } m_instanceName = fmi2_import_get_model_name(m_fmi2Instance); m_fmuLocation = fmi_import_create_URL_from_abs_path(&m_jmCallbacks, m_fmuPath.c_str()); /* 0 - original order as found in the XML file; * 1 - sorted alphabetically by variable name; * 2 sorted by types/value references. */ int sortOrder = 0; m_fmi2Variables = fmi2_import_get_variable_list(m_fmi2Instance, sortOrder); } else { // todo add FMI 1.0 later on. fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); m_logger.log(Logger::LOG_ERROR, "Only FMI Co-Simulation 2.0 is supported.\n"); m_fmuParsed = false; return; } } void Server::onClientConnect() {} void Server::onClientDisconnect() {} void Server::onError(string message) {} void Server::clientConnected(lw_client c) { m_logger.log(Logger::LOG_NETWORK,"+ Client connected.\n"); onClientConnect(); } void Server::clientDisconnected(lw_client c) { m_logger.log(Logger::LOG_NETWORK,"- Client disconnected.\n"); onClientDisconnect(); } void Server::clientData(lw_client c, const char *data, size_t size) { string data2(data, size); if(data2 == "\n") return; // Construct message fmitcp_proto::fmitcp_message req; //string data2 = fmitcp::dataToString(data,size); bool parseStatus = req.ParseFromString(data2); fmitcp_proto::fmitcp_message_Type type = req.type(); m_logger.log(Logger::LOG_DEBUG,"Parse status: %d\n", parseStatus); fmitcp_proto::fmitcp_message res; bool sendResponse = true; if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_instantiate_req) { // Unpack message fmitcp_proto::fmi2_import_instantiate_req * r = req.mutable_fmi2_import_instantiate_req(); int messageId = r->message_id(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_instantiate_req(mid=%d)\n",messageId); jm_status_enu_t status = jm_status_success; if (!m_sendDummyResponses) { // instantiate FMU fmi2_boolean_t visible = fmi2_false; status = fmi2_import_instantiate(m_fmi2Instance, m_instanceName, fmi2_cosimulation, m_fmuLocation, visible); // set the debug logging for FMU if (status != jm_status_error) { // fetch the logging categories from the FMU size_t nCategories = fmi2_import_get_log_categories_num(m_fmi2Instance); fmi2_string_t categories[nCategories]; int i; for (i = 0 ; i < nCategories ; i++) { categories[i] = fmi2_import_get_log_category(m_fmi2Instance, i); } // set debug logging. We don't care about its result. fmi2_import_set_debug_logging(m_fmi2Instance, m_debugLogging, nCategories, categories); } } // Create response message res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_instantiate_res); fmitcp_proto::fmi2_import_instantiate_res * instantiateRes = res.mutable_fmi2_import_instantiate_res(); instantiateRes->set_message_id(messageId); instantiateRes->set_status(fmiJMStatusToProtoJMStatus(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_instantiate_slave_res(mid=%d,status=%d)\n",messageId,instantiateRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_initialize_slave_req) { // Unpack message fmitcp_proto::fmi2_import_initialize_slave_req * r = req.mutable_fmi2_import_initialize_slave_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); bool toleranceDefined = r->has_tolerancedefined(); double tolerance = r->tolerance(); double starttime = r->starttime(); bool stopTimeDefined = r->has_stoptimedefined(); double stoptime = r->stoptime(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_initialize_slave_req(mid=%d)\n",messageId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // initialize FMU /*! * \todo * We should set all variable start values (of "ScalarVariable / <type> / start"). * fmiSetReal/Integer/Boolean/String(s1, ...); */ /*! * \todo * What about FMUs internal experiment values e.g tolerance ???? */ // fmi2_boolean_t toleranceControlled = fmi2_false; // fmi2_real_t relativeTolerance = fmi2_import_get_default_experiment_tolerance(m_fmi2Instance); /*! * \todo * We need to set the input values at time = startTime after fmiEnterInitializationMode and before fmiExitInitializationMode. * fmiSetReal/Integer/Boolean/String(s1, ...); */ if (fmi2StatusOkOrWarning(status = fmi2_import_setup_experiment(m_fmi2Instance, toleranceDefined, tolerance, starttime, stopTimeDefined, stoptime)) && fmi2StatusOkOrWarning(status = fmi2_import_enter_initialization_mode(m_fmi2Instance)) && fmi2StatusOkOrWarning(fmi2_import_exit_initialization_mode(m_fmi2Instance))) { // do nothing } } // Create response message res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_initialize_slave_res); fmitcp_proto::fmi2_import_initialize_slave_res * initializeRes = res.mutable_fmi2_import_initialize_slave_res(); initializeRes->set_message_id(messageId); initializeRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_initialize_slave_res(mid=%d,status=%d)\n",messageId,initializeRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_terminate_slave_req) { // Unpack message fmitcp_proto::fmi2_import_terminate_slave_req * r = req.mutable_fmi2_import_terminate_slave_req(); int fmuId = r->fmuid(); int messageId = r->message_id(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_terminate_slave_req(mid=%d,fmuId=%d)\n",messageId,fmuId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // terminate FMU status = fmi2_import_terminate(m_fmi2Instance); } // Create response message res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_terminate_slave_res); fmitcp_proto::fmi2_import_terminate_slave_res * terminateRes = res.mutable_fmi2_import_terminate_slave_res(); terminateRes->set_message_id(messageId); terminateRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_terminate_slave_res(mid=%d,status=%d)\n",messageId,terminateRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_reset_slave_req) { // Unpack message fmitcp_proto::fmi2_import_reset_slave_req * r = req.mutable_fmi2_import_reset_slave_req(); int fmuId = r->fmuid(); int messageId = r->message_id(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_reset_slave_req(fmuId=%d)\n",fmuId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // reset FMU status = fmi2_import_reset(m_fmi2Instance); } // Create response message res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_reset_slave_res); fmitcp_proto::fmi2_import_reset_slave_res * resetRes = res.mutable_fmi2_import_reset_slave_res(); resetRes->set_message_id(messageId); resetRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_reset_slave_res(mid=%d,status=%d)\n",messageId,resetRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_free_slave_instance_req) { // Unpack message fmitcp_proto::fmi2_import_free_slave_instance_req * r = req.mutable_fmi2_import_free_slave_instance_req(); int fmuId = r->fmuid(), messageId = r->message_id(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_free_slave_instance_req(fmuId=%d)\n",fmuId); // Create response message res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_free_slave_instance_res); fmitcp_proto::fmi2_import_free_slave_instance_res * resetRes = res.mutable_fmi2_import_free_slave_instance_res(); resetRes->set_message_id(messageId); if (!m_sendDummyResponses) { // Interact with FMU fmi2_import_free(m_fmi2Instance); fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_free_slave_instance_res(mid=%d)\n",messageId); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_real_input_derivatives_req) { // Unpack message fmitcp_proto::fmi2_import_set_real_input_derivatives_req * r = req.mutable_fmi2_import_set_real_input_derivatives_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_integer_t order[r->orders_size()]; fmi2_real_t value[r->values_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); order[i] = r->orders(i); value[i] = r->values(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_real_input_derivatives_req(mid=%d,fmuId=%d)\n",messageId,fmuId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_set_real_input_derivatives(m_fmi2Instance, vr, r->valuereferences_size(), order, value); } // Create response fmitcp_proto::fmi2_import_set_real_input_derivatives_res * setRealInputDerivativesRes = res.mutable_fmi2_import_set_real_input_derivatives_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_real_input_derivatives_res); setRealInputDerivativesRes->set_message_id(messageId); setRealInputDerivativesRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_real_input_derivatives_res(mid=%d,status=%d)\n",messageId, setRealInputDerivativesRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_output_derivatives_req) { // Unpack message fmitcp_proto::fmi2_import_get_real_output_derivatives_req * r = req.mutable_fmi2_import_get_real_output_derivatives_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_integer_t order[r->orders_size()]; fmi2_real_t value[r->valuereferences_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); order[i] = r->orders(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_real_output_derivatives_req(mid=%d,fmuId=%d)\n",messageId,fmuId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_real_output_derivatives(m_fmi2Instance, vr, r->valuereferences_size(), order, value); } // Create response fmitcp_proto::fmi2_import_get_real_output_derivatives_res * getRealOutputDerivativesRes = res.mutable_fmi2_import_get_real_output_derivatives_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_output_derivatives_res); getRealOutputDerivativesRes->set_message_id(messageId); getRealOutputDerivativesRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->valuereferences_size() ; i++) { getRealOutputDerivativesRes->add_values(value[i]); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_real_output_derivatives_res(mid=%d,status=%d,values=...)\n",getRealOutputDerivativesRes->message_id(),getRealOutputDerivativesRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_cancel_step_req) { // Unpack message fmitcp_proto::fmi2_import_cancel_step_req * r = req.mutable_fmi2_import_cancel_step_req(); int fmuId = r->fmuid(), messageId = r->message_id(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_cancel_step_req(mid=%d,fmuId=%d)\n",messageId,fmuId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // Interact with FMU status = fmi2_import_cancel_step(m_fmi2Instance); } // Create response res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_cancel_step_res); fmitcp_proto::fmi2_import_cancel_step_res * cancelStepRes = res.mutable_fmi2_import_cancel_step_res(); cancelStepRes->set_message_id(messageId); cancelStepRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_cancel_step_res(mid=%d,status=%d)\n",messageId,cancelStepRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_do_step_req) { // Unpack message fmitcp_proto::fmi2_import_do_step_req * r = req.mutable_fmi2_import_do_step_req(); int fmuId = r->fmuid(); double currentCommunicationPoint = r->currentcommunicationpoint(), communicationStepSize = r->communicationstepsize(); bool newStep = r->newstep(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_do_step_req(fmuId=%d,commPoint=%g,stepSize=%g,newStep=%d)\n",fmuId,currentCommunicationPoint,communicationStepSize,newStep?1:0); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // Step the FMU status = fmi2_import_do_step(m_fmi2Instance, currentCommunicationPoint, communicationStepSize, newStep); } // Create response fmitcp_proto::fmi2_import_do_step_res * doStepRes = res.mutable_fmi2_import_do_step_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_do_step_res); doStepRes->set_message_id(r->message_id()); doStepRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_do_step_res(status=%d)\n",doStepRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_status_req){ // Unpack message fmitcp_proto::fmi2_import_get_status_req * r = req.mutable_fmi2_import_get_status_req(); int fmuId = r->fmuid(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_status_req(fmuId=%d)\n",fmuId); // Defaults fmitcp_proto::fmi2_import_get_status_res * getStatusRes = res.mutable_fmi2_import_get_status_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_status_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_value(fmitcp_proto::fmi2_status_ok); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_status_res(value=%d)\n",getStatusRes->value()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_status_req){ // Unpack message fmitcp_proto::fmi2_import_get_real_status_req * r = req.mutable_fmi2_import_get_real_status_req(); int fmuId = r->fmuid(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_real_status_req(fmuId=%d)\n",fmuId); // Defaults fmitcp_proto::fmi2_import_get_real_status_res * getStatusRes = res.mutable_fmi2_import_get_real_status_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_status_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_value(0.0); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_real_status_res(value=%g)\n",getStatusRes->value()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_integer_status_req){ // Unpack message fmitcp_proto::fmi2_import_get_integer_status_req * r = req.mutable_fmi2_import_get_integer_status_req(); int fmuId = r->fmuid(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_integer_status_req(fmuId=%d)\n",fmuId); // Defaults fmitcp_proto::fmi2_import_get_integer_status_res * getStatusRes = res.mutable_fmi2_import_get_integer_status_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_integer_status_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_value(0); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_integer_status_res(value=%d)\n",getStatusRes->value()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_boolean_status_req){ // Unpack message fmitcp_proto::fmi2_import_get_boolean_status_req * r = req.mutable_fmi2_import_get_boolean_status_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_boolean_status_req(mid=%d,fmuId=%d)\n",r->message_id(),r->fmuid()); // Defaults fmitcp_proto::fmi2_import_get_boolean_status_res * getStatusRes = res.mutable_fmi2_import_get_boolean_status_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_boolean_status_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_value(true); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_boolean_status_res(mid=%d,value=%d)\n",getStatusRes->message_id(),getStatusRes->value()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_string_status_req){ // Unpack message fmitcp_proto::fmi2_import_get_string_status_req * r = req.mutable_fmi2_import_get_string_status_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_string_status_req(mid=%d,fmuId=%d)\n",r->message_id(),r->fmuid()); // Defaults fmitcp_proto::fmi2_import_get_string_status_res * getStatusRes = res.mutable_fmi2_import_get_string_status_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_string_status_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_value("hey there!"); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_string_status_res(mid=%d,value=%s)\n",getStatusRes->message_id(),getStatusRes->value().c_str()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_instantiate_model_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_free_model_instance_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_time_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_continuous_states_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_completed_integrator_step_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_initialize_model_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_derivatives_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_event_indicators_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_eventUpdate_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_completed_event_iteration_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_continuous_states_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_nominal_continuous_states_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_terminate_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_version_req){ // Unpack message fmitcp_proto::fmi2_import_get_version_req * r = req.mutable_fmi2_import_get_version_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_version_req(mid=%d,fmuId=%d)\n",r->message_id(),r->fmuid()); // Defaults fmitcp_proto::fmi2_import_get_version_res * getStatusRes = res.mutable_fmi2_import_get_version_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_version_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_version("VeRsIoN"); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_version_res(mid=%d,version=%s)\n",getStatusRes->message_id(),getStatusRes->version().c_str()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_debug_logging_req){ // Unpack message fmitcp_proto::fmi2_import_set_debug_logging_req * r = req.mutable_fmi2_import_set_debug_logging_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_debug_logging_req(mid=%d,fmuId=%d,loggingOn=%d,categories=...)\n",r->message_id(),r->fmuid(),r->loggingon()); // Defaults fmitcp_proto::fmi2_import_set_debug_logging_res * getStatusRes = res.mutable_fmi2_import_set_debug_logging_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_debug_logging_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_status(fmitcp_proto::fmi2_status_ok); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_debug_logging_res(mid=%d,status=%d)\n",getStatusRes->message_id(),getStatusRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_real_req) { // Unpack message fmitcp_proto::fmi2_import_set_real_req * r = req.mutable_fmi2_import_set_real_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_real_t value[r->values_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); value[i] = r->values(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_real_req(mid=%d,fmuId=%d,vrs=...,values=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_set_real(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_set_real_res * setRealRes = res.mutable_fmi2_import_set_real_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_real_res); setRealRes->set_message_id(r->message_id()); setRealRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_real_res(mid=%d,status=%d)\n",setRealRes->message_id(),setRealRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_integer_req) { // Unpack message fmitcp_proto::fmi2_import_set_integer_req * r = req.mutable_fmi2_import_set_integer_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_integer_t value[r->values_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); value[i] = r->values(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_integer_req(mid=%d,fmuId=%d,vrs=...,values=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_set_integer(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_set_integer_res * setIntegerRes = res.mutable_fmi2_import_set_integer_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_integer_res); setIntegerRes->set_message_id(r->message_id()); setIntegerRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_integer_res(mid=%d,status=%d)\n",setIntegerRes->message_id(),setIntegerRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_boolean_req) { // Unpack message fmitcp_proto::fmi2_import_set_boolean_req * r = req.mutable_fmi2_import_set_boolean_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_boolean_t value[r->values_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); value[i] = r->values(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_boolean_req(mid=%d,fmuId=%d,vrs=...,values=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_set_boolean(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_set_boolean_res * setBooleanRes = res.mutable_fmi2_import_set_boolean_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_boolean_res); setBooleanRes->set_message_id(r->message_id()); setBooleanRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_boolean_res(mid=%d,status=%d)\n",setBooleanRes->message_id(),setBooleanRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_string_req) { // Unpack message fmitcp_proto::fmi2_import_set_string_req * r = req.mutable_fmi2_import_set_string_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_string_t value[r->values_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); value[i] = r->values(i).c_str(); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_string_req(mid=%d,fmuId=%d,vrs=...,values=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_set_string(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_set_string_res * getStatusRes = res.mutable_fmi2_import_set_string_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_string_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_string_res(mid=%d,status=%d)\n",getStatusRes->message_id(),getStatusRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_req) { // Unpack message fmitcp_proto::fmi2_import_get_real_req * r = req.mutable_fmi2_import_get_real_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_real_t value[r->valuereferences_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_real_req(mid=%d,fmuId=%d,vrs=...)\n",r->message_id(),r->fmuid()); // Create response fmitcp_proto::fmi2_import_get_real_res * getRealRes = res.mutable_fmi2_import_get_real_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_res); getRealRes->set_message_id(r->message_id()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_real(m_fmi2Instance, vr, r->valuereferences_size(), value); getRealRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->valuereferences_size() ; i++) { getRealRes->add_values(value[i]); } } else { // Set dummy values for (int i = 0 ; i < r->valuereferences_size() ; i++) { getRealRes->add_values(0.0); } getRealRes->set_status(fmi2StatusToProtofmi2Status(fmi2_status_ok)); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_real_res(mid=%d,status=%d,values=...)\n",getRealRes->message_id(),getRealRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_integer_req) { // Unpack message fmitcp_proto::fmi2_import_get_integer_req * r = req.mutable_fmi2_import_get_integer_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_integer_t value[r->valuereferences_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_integer_req(mid=%d,fmuId=%d,vrs=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_integer(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_get_integer_res * getIntegerRes = res.mutable_fmi2_import_get_integer_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_integer_res); getIntegerRes->set_message_id(r->message_id()); getIntegerRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->valuereferences_size() ; i++) { getIntegerRes->add_values(value[i]); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_integer_res(mid=%d,status=%d,values=...)\n",getIntegerRes->message_id(),getIntegerRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_boolean_req) { // Unpack message fmitcp_proto::fmi2_import_get_boolean_req * r = req.mutable_fmi2_import_get_boolean_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_boolean_t value[r->valuereferences_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_boolean_req(mid=%d,fmuId=%d,vrs=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_boolean(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_get_boolean_res * getBooleanRes = res.mutable_fmi2_import_get_boolean_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_boolean_res); getBooleanRes->set_message_id(r->message_id()); getBooleanRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->valuereferences_size() ; i++) { getBooleanRes->add_values(value[i]); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_boolean_res(mid=%d,status=%d,values=...)\n",getBooleanRes->message_id(),getBooleanRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_string_req) { // Unpack message fmitcp_proto::fmi2_import_get_string_req * r = req.mutable_fmi2_import_get_string_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_string_t value[r->valuereferences_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_string_req(mid=%d,fmuId=%d,vrs=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_string(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_get_string_res * getStringRes = res.mutable_fmi2_import_get_string_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_string_res); getStringRes->set_message_id(r->message_id()); getStringRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->valuereferences_size() ; i++) { getStringRes->add_values(value[i]); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_string_res(mid=%d,status=%d,values=...)\n",getStringRes->message_id(),getStringRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_fmu_state_req){ // Unpack message fmitcp_proto::fmi2_import_get_fmu_state_req * r = req.mutable_fmi2_import_get_fmu_state_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_fmu_state_req(mid=%d,fmuId=%d)\n",r->message_id(),r->fmuid()); fmitcp_proto::fmi2_import_get_fmu_state_res * getStatusRes = res.mutable_fmi2_import_get_fmu_state_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_fmu_state_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_status(fmitcp_proto::fmi2_status_ok); getStatusRes->set_stateid(0); // TODO if(!m_sendDummyResponses){ // TODO: interact with FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_fmu_state_res(mid=%d,stateId=%d,status=%d)\n",getStatusRes->message_id(),getStatusRes->stateid(),getStatusRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_fmu_state_req){ // Unpack message fmitcp_proto::fmi2_import_set_fmu_state_req * r = req.mutable_fmi2_import_set_fmu_state_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_fmu_state_req(mid=%d,fmuId=%d,stateId=%d)\n",r->message_id(),r->fmuid(),r->stateid()); fmitcp_proto::fmi2_import_set_fmu_state_res * getStatusRes = res.mutable_fmi2_import_set_fmu_state_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_fmu_state_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_status(fmitcp_proto::fmi2_status_ok); if(!m_sendDummyResponses){ // TODO: interact with FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_fmu_state_res(mid=%d,status=%d)\n",getStatusRes->message_id(),getStatusRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_free_fmu_state_req){ // Unpack message fmitcp_proto::fmi2_import_free_fmu_state_req * r = req.mutable_fmi2_import_free_fmu_state_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_free_fmu_state_req(mid=%d,stateId=%d)\n",r->message_id(),r->stateid()); fmitcp_proto::fmi2_import_free_fmu_state_res * getStatusRes = res.mutable_fmi2_import_free_fmu_state_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_free_fmu_state_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_status(fmitcp_proto::fmi2_status_ok); if(!m_sendDummyResponses){ // TODO: interact with FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_free_fmu_state_res(mid=%d,status=%d)\n",getStatusRes->message_id(),getStatusRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_serialized_fmu_state_size_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_serialize_fmu_state_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_de_serialize_fmu_state_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_directional_derivative_req){ // Unpack message fmitcp_proto::fmi2_import_get_directional_derivative_req * r = req.mutable_fmi2_import_get_directional_derivative_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t v_ref[r->v_ref_size()]; fmi2_value_reference_t z_ref[r->z_ref_size()]; fmi2_real_t dv[r->dv_size()], dz[r->z_ref_size()]; for (int i = 0 ; i < r->v_ref_size() ; i++) { v_ref[i] = r->v_ref(i); } for (int i = 0 ; i < r->z_ref_size() ; i++) { z_ref[i] = r->z_ref(i); } for (int i = 0 ; i < r->dv_size()() ; i++) { dv[i] = r->dv(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_directional_derivative_req(mid=%d,fmuId=%d,vref=...,zref=...,dv=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_directional_derivative(m_fmi2Instance, v_ref, r->v_ref_size(), z_ref, r->z_ref_size(), dv, dz); } // Create response fmitcp_proto::fmi2_import_get_directional_derivative_res * getDirectionalDerivativesRes = res.mutable_fmi2_import_get_directional_derivative_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_directional_derivative_res); getDirectionalDerivativesRes->set_message_id(r->message_id()); getDirectionalDerivativesRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->z_ref_size() ; i++) { getDirectionalDerivativesRes->add_dz(dz[i]); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_directional_derivative_res(mid=%d,status=%d,dz=...)\n",getDirectionalDerivativesRes->message_id(),getDirectionalDerivativesRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_get_xml_req){ // Unpack message fmitcp_proto::get_xml_req * r = req.mutable_get_xml_req(); m_logger.log(Logger::LOG_NETWORK,"< get_xml_req(mid=%d,fmuId=%d)\n",r->message_id(),r->fmuid()); fmitcp_proto::get_xml_res * getStatusRes = res.mutable_get_xml_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_get_xml_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_xml(""); if(!m_sendDummyResponses){ // TODO: interact with FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> get_xml_res(mid=%d,xml=...)\n",getStatusRes->message_id()); } else { // Something is wrong. sendResponse = false; m_logger.log(Logger::LOG_ERROR,"Message type not recognized: %d.\n",type); } if (sendResponse) { sendMessage(c, &res); } } void Server::host(string hostName, long port) { // save this object in the server tag so we can use it later on. lw_server_set_tag(m_server, (void*)this); // connect the hooks lw_server_on_connect( m_server, serverOnConnect); lw_server_on_data( m_server, serverOnData); lw_server_on_disconnect(m_server, serverOnDisconnect); lw_server_on_error( m_server, serverOnError); // setup the server host name and port lw_addr host = lw_addr_new_port(hostName.c_str(), port); lw_filter filter = lw_filter_new(); lw_filter_set_ipv6(filter, lw_false); lw_filter_set_local(filter, host); // host/start the server lw_server_host_filter(m_server, filter); lw_filter_delete(filter); m_logger.log(Logger::LOG_NETWORK,"Listening to %s:%ld\n",hostName.c_str(),port); } void Server::sendDummyResponses(bool sendDummyResponses){ m_sendDummyResponses = sendDummyResponses; } void Server::sendMessage(lw_client c, fmitcp_proto::fmitcp_message* message) { fmitcp::sendProtoBuffer(c,message); } void Server::setLogger(const Logger &logger) { m_logger = logger; } Fixed typo error #include "Server.h" #include "Logger.h" #include "common.h" #include "fmitcp.pb.h" using namespace fmitcp; void serverOnConnect(lw_server s, lw_client c) { Server * server = (Server*)lw_server_tag(s); server->clientConnected(c); lw_fdstream_nagle(c,lw_false); } void serverOnData(lw_server s, lw_client client, const char* data, size_t size) { Server * server = (Server*)lw_server_tag(s); server->clientData(client,data,size); } void serverOnDisconnect(lw_server s, lw_client c) { Server * server = (Server*)lw_server_tag(s); server->clientDisconnected(c); } void serverOnError(lw_server s, lw_error error) { Server * server = (Server*)lw_server_tag(s); server->error(s,error); } /*! * Callback function for FMILibrary. Logs the FMILibrary operations. */ void jmCallbacksLogger(jm_callbacks* c, jm_string module, jm_log_level_enu_t log_level, jm_string message) { printf("[module = %s][log level = %s] %s\n", module, jm_log_level_to_string(log_level), message);fflush(NULL); } void Server::error(lw_server s, lw_error error) { string err = lw_error_tostring(error); onError(err); } Server::Server(string fmuPath, bool debugLogging, jm_log_level_enu_t logLevel, EventPump *pump) { m_fmuParsed = true; m_fmuPath = fmuPath; m_debugLogging = debugLogging; m_logLevel = logLevel; init(pump); } Server::Server(string fmuPath, bool debugLogging, jm_log_level_enu_t logLevel, EventPump *pump, const Logger &logger) { m_fmuParsed = true; m_fmuPath = fmuPath; m_debugLogging = debugLogging; m_logLevel = logLevel; m_logger = logger; init(pump); } Server::~Server() { lw_server_delete(m_server); } void Server::init(EventPump * pump) { m_pump = pump; m_server = lw_server_new(pump->getPump()); m_sendDummyResponses = false; if(m_fmuPath == "dummy"){ m_sendDummyResponses = true; m_fmuParsed = true; return; } // Parse FMU // JM callbacks m_jmCallbacks.malloc = malloc; m_jmCallbacks.calloc = calloc; m_jmCallbacks.realloc = realloc; m_jmCallbacks.free = free; m_jmCallbacks.logger = jmCallbacksLogger; m_jmCallbacks.log_level = m_logLevel; m_jmCallbacks.context = 0; // working directory char* dir = fmi_import_mk_temp_dir(&m_jmCallbacks, NULL, "fmitcp_"); m_workingDir = dir; // convert to std::string free(dir); // import allocate context m_context = fmi_import_allocate_context(&m_jmCallbacks); // get FMU version m_version = fmi_import_get_fmi_version(m_context, m_fmuPath.c_str(), m_workingDir.c_str()); // Check version OK if ((m_version <= fmi_version_unknown_enu) || (m_version >= fmi_version_unsupported_enu)) { fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); m_logger.log(Logger::LOG_ERROR, "Unsupported/unknown FMU version: '%s'.\n", fmi_version_to_string(m_version)); m_fmuParsed = false; return; } if (m_version == fmi_version_2_0_enu) { // FMI 2.0 // parse the xml file m_fmi2Instance = fmi2_import_parse_xml(m_context, m_workingDir.c_str(), 0); if(!m_fmi2Instance) { fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); m_logger.log(Logger::LOG_ERROR, "Error parsing the modelDescription.xml file contained in %s\n", m_workingDir.c_str()); m_fmuParsed = false; return; } // check FMU kind fmi2_fmu_kind_enu_t fmuType = fmi2_import_get_fmu_kind(m_fmi2Instance); if(fmuType != fmi2_fmu_kind_cs && fmuType != fmi2_fmu_kind_me_and_cs) { fmi2_import_free(m_fmi2Instance); fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); m_logger.log(Logger::LOG_ERROR, "Only FMI Co-Simulation 2.0 is supported.\n"); m_fmuParsed = false; return; } // FMI callback functions m_fmi2CallbackFunctions.logger = fmi2_log_forwarding; m_fmi2CallbackFunctions.allocateMemory = calloc; m_fmi2CallbackFunctions.freeMemory = free; m_fmi2CallbackFunctions.stepFinished = 0; m_fmi2CallbackFunctions.componentEnvironment = 0; // Load the binary (dll/so) jm_status_enu_t status = fmi2_import_create_dllfmu(m_fmi2Instance, fmuType, &m_fmi2CallbackFunctions); if (status == jm_status_error) { fmi2_import_free(m_fmi2Instance); fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); m_logger.log(Logger::LOG_ERROR, "There was an error loading the FMU binary. Turn on logging (-l) for more info.\n"); m_fmuParsed = false; return; } m_instanceName = fmi2_import_get_model_name(m_fmi2Instance); m_fmuLocation = fmi_import_create_URL_from_abs_path(&m_jmCallbacks, m_fmuPath.c_str()); /* 0 - original order as found in the XML file; * 1 - sorted alphabetically by variable name; * 2 sorted by types/value references. */ int sortOrder = 0; m_fmi2Variables = fmi2_import_get_variable_list(m_fmi2Instance, sortOrder); } else { // todo add FMI 1.0 later on. fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); m_logger.log(Logger::LOG_ERROR, "Only FMI Co-Simulation 2.0 is supported.\n"); m_fmuParsed = false; return; } } void Server::onClientConnect() {} void Server::onClientDisconnect() {} void Server::onError(string message) {} void Server::clientConnected(lw_client c) { m_logger.log(Logger::LOG_NETWORK,"+ Client connected.\n"); onClientConnect(); } void Server::clientDisconnected(lw_client c) { m_logger.log(Logger::LOG_NETWORK,"- Client disconnected.\n"); onClientDisconnect(); } void Server::clientData(lw_client c, const char *data, size_t size) { string data2(data, size); if(data2 == "\n") return; // Construct message fmitcp_proto::fmitcp_message req; //string data2 = fmitcp::dataToString(data,size); bool parseStatus = req.ParseFromString(data2); fmitcp_proto::fmitcp_message_Type type = req.type(); m_logger.log(Logger::LOG_DEBUG,"Parse status: %d\n", parseStatus); fmitcp_proto::fmitcp_message res; bool sendResponse = true; if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_instantiate_req) { // Unpack message fmitcp_proto::fmi2_import_instantiate_req * r = req.mutable_fmi2_import_instantiate_req(); int messageId = r->message_id(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_instantiate_req(mid=%d)\n",messageId); jm_status_enu_t status = jm_status_success; if (!m_sendDummyResponses) { // instantiate FMU fmi2_boolean_t visible = fmi2_false; status = fmi2_import_instantiate(m_fmi2Instance, m_instanceName, fmi2_cosimulation, m_fmuLocation, visible); // set the debug logging for FMU if (status != jm_status_error) { // fetch the logging categories from the FMU size_t nCategories = fmi2_import_get_log_categories_num(m_fmi2Instance); fmi2_string_t categories[nCategories]; int i; for (i = 0 ; i < nCategories ; i++) { categories[i] = fmi2_import_get_log_category(m_fmi2Instance, i); } // set debug logging. We don't care about its result. fmi2_import_set_debug_logging(m_fmi2Instance, m_debugLogging, nCategories, categories); } } // Create response message res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_instantiate_res); fmitcp_proto::fmi2_import_instantiate_res * instantiateRes = res.mutable_fmi2_import_instantiate_res(); instantiateRes->set_message_id(messageId); instantiateRes->set_status(fmiJMStatusToProtoJMStatus(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_instantiate_slave_res(mid=%d,status=%d)\n",messageId,instantiateRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_initialize_slave_req) { // Unpack message fmitcp_proto::fmi2_import_initialize_slave_req * r = req.mutable_fmi2_import_initialize_slave_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); bool toleranceDefined = r->has_tolerancedefined(); double tolerance = r->tolerance(); double starttime = r->starttime(); bool stopTimeDefined = r->has_stoptimedefined(); double stoptime = r->stoptime(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_initialize_slave_req(mid=%d)\n",messageId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // initialize FMU /*! * \todo * We should set all variable start values (of "ScalarVariable / <type> / start"). * fmiSetReal/Integer/Boolean/String(s1, ...); */ /*! * \todo * What about FMUs internal experiment values e.g tolerance ???? */ // fmi2_boolean_t toleranceControlled = fmi2_false; // fmi2_real_t relativeTolerance = fmi2_import_get_default_experiment_tolerance(m_fmi2Instance); /*! * \todo * We need to set the input values at time = startTime after fmiEnterInitializationMode and before fmiExitInitializationMode. * fmiSetReal/Integer/Boolean/String(s1, ...); */ if (fmi2StatusOkOrWarning(status = fmi2_import_setup_experiment(m_fmi2Instance, toleranceDefined, tolerance, starttime, stopTimeDefined, stoptime)) && fmi2StatusOkOrWarning(status = fmi2_import_enter_initialization_mode(m_fmi2Instance)) && fmi2StatusOkOrWarning(fmi2_import_exit_initialization_mode(m_fmi2Instance))) { // do nothing } } // Create response message res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_initialize_slave_res); fmitcp_proto::fmi2_import_initialize_slave_res * initializeRes = res.mutable_fmi2_import_initialize_slave_res(); initializeRes->set_message_id(messageId); initializeRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_initialize_slave_res(mid=%d,status=%d)\n",messageId,initializeRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_terminate_slave_req) { // Unpack message fmitcp_proto::fmi2_import_terminate_slave_req * r = req.mutable_fmi2_import_terminate_slave_req(); int fmuId = r->fmuid(); int messageId = r->message_id(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_terminate_slave_req(mid=%d,fmuId=%d)\n",messageId,fmuId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // terminate FMU status = fmi2_import_terminate(m_fmi2Instance); } // Create response message res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_terminate_slave_res); fmitcp_proto::fmi2_import_terminate_slave_res * terminateRes = res.mutable_fmi2_import_terminate_slave_res(); terminateRes->set_message_id(messageId); terminateRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_terminate_slave_res(mid=%d,status=%d)\n",messageId,terminateRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_reset_slave_req) { // Unpack message fmitcp_proto::fmi2_import_reset_slave_req * r = req.mutable_fmi2_import_reset_slave_req(); int fmuId = r->fmuid(); int messageId = r->message_id(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_reset_slave_req(fmuId=%d)\n",fmuId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // reset FMU status = fmi2_import_reset(m_fmi2Instance); } // Create response message res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_reset_slave_res); fmitcp_proto::fmi2_import_reset_slave_res * resetRes = res.mutable_fmi2_import_reset_slave_res(); resetRes->set_message_id(messageId); resetRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_reset_slave_res(mid=%d,status=%d)\n",messageId,resetRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_free_slave_instance_req) { // Unpack message fmitcp_proto::fmi2_import_free_slave_instance_req * r = req.mutable_fmi2_import_free_slave_instance_req(); int fmuId = r->fmuid(), messageId = r->message_id(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_free_slave_instance_req(fmuId=%d)\n",fmuId); // Create response message res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_free_slave_instance_res); fmitcp_proto::fmi2_import_free_slave_instance_res * resetRes = res.mutable_fmi2_import_free_slave_instance_res(); resetRes->set_message_id(messageId); if (!m_sendDummyResponses) { // Interact with FMU fmi2_import_free(m_fmi2Instance); fmi_import_free_context(m_context); fmi_import_rmdir(&m_jmCallbacks, m_workingDir.c_str()); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_free_slave_instance_res(mid=%d)\n",messageId); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_real_input_derivatives_req) { // Unpack message fmitcp_proto::fmi2_import_set_real_input_derivatives_req * r = req.mutable_fmi2_import_set_real_input_derivatives_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_integer_t order[r->orders_size()]; fmi2_real_t value[r->values_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); order[i] = r->orders(i); value[i] = r->values(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_real_input_derivatives_req(mid=%d,fmuId=%d)\n",messageId,fmuId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_set_real_input_derivatives(m_fmi2Instance, vr, r->valuereferences_size(), order, value); } // Create response fmitcp_proto::fmi2_import_set_real_input_derivatives_res * setRealInputDerivativesRes = res.mutable_fmi2_import_set_real_input_derivatives_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_real_input_derivatives_res); setRealInputDerivativesRes->set_message_id(messageId); setRealInputDerivativesRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_real_input_derivatives_res(mid=%d,status=%d)\n",messageId, setRealInputDerivativesRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_output_derivatives_req) { // Unpack message fmitcp_proto::fmi2_import_get_real_output_derivatives_req * r = req.mutable_fmi2_import_get_real_output_derivatives_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_integer_t order[r->orders_size()]; fmi2_real_t value[r->valuereferences_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); order[i] = r->orders(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_real_output_derivatives_req(mid=%d,fmuId=%d)\n",messageId,fmuId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_real_output_derivatives(m_fmi2Instance, vr, r->valuereferences_size(), order, value); } // Create response fmitcp_proto::fmi2_import_get_real_output_derivatives_res * getRealOutputDerivativesRes = res.mutable_fmi2_import_get_real_output_derivatives_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_output_derivatives_res); getRealOutputDerivativesRes->set_message_id(messageId); getRealOutputDerivativesRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->valuereferences_size() ; i++) { getRealOutputDerivativesRes->add_values(value[i]); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_real_output_derivatives_res(mid=%d,status=%d,values=...)\n",getRealOutputDerivativesRes->message_id(),getRealOutputDerivativesRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_cancel_step_req) { // Unpack message fmitcp_proto::fmi2_import_cancel_step_req * r = req.mutable_fmi2_import_cancel_step_req(); int fmuId = r->fmuid(), messageId = r->message_id(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_cancel_step_req(mid=%d,fmuId=%d)\n",messageId,fmuId); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // Interact with FMU status = fmi2_import_cancel_step(m_fmi2Instance); } // Create response res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_cancel_step_res); fmitcp_proto::fmi2_import_cancel_step_res * cancelStepRes = res.mutable_fmi2_import_cancel_step_res(); cancelStepRes->set_message_id(messageId); cancelStepRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_cancel_step_res(mid=%d,status=%d)\n",messageId,cancelStepRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_do_step_req) { // Unpack message fmitcp_proto::fmi2_import_do_step_req * r = req.mutable_fmi2_import_do_step_req(); int fmuId = r->fmuid(); double currentCommunicationPoint = r->currentcommunicationpoint(), communicationStepSize = r->communicationstepsize(); bool newStep = r->newstep(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_do_step_req(fmuId=%d,commPoint=%g,stepSize=%g,newStep=%d)\n",fmuId,currentCommunicationPoint,communicationStepSize,newStep?1:0); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // Step the FMU status = fmi2_import_do_step(m_fmi2Instance, currentCommunicationPoint, communicationStepSize, newStep); } // Create response fmitcp_proto::fmi2_import_do_step_res * doStepRes = res.mutable_fmi2_import_do_step_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_do_step_res); doStepRes->set_message_id(r->message_id()); doStepRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_do_step_res(status=%d)\n",doStepRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_status_req){ // Unpack message fmitcp_proto::fmi2_import_get_status_req * r = req.mutable_fmi2_import_get_status_req(); int fmuId = r->fmuid(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_status_req(fmuId=%d)\n",fmuId); // Defaults fmitcp_proto::fmi2_import_get_status_res * getStatusRes = res.mutable_fmi2_import_get_status_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_status_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_value(fmitcp_proto::fmi2_status_ok); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_status_res(value=%d)\n",getStatusRes->value()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_status_req){ // Unpack message fmitcp_proto::fmi2_import_get_real_status_req * r = req.mutable_fmi2_import_get_real_status_req(); int fmuId = r->fmuid(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_real_status_req(fmuId=%d)\n",fmuId); // Defaults fmitcp_proto::fmi2_import_get_real_status_res * getStatusRes = res.mutable_fmi2_import_get_real_status_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_status_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_value(0.0); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_real_status_res(value=%g)\n",getStatusRes->value()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_integer_status_req){ // Unpack message fmitcp_proto::fmi2_import_get_integer_status_req * r = req.mutable_fmi2_import_get_integer_status_req(); int fmuId = r->fmuid(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_integer_status_req(fmuId=%d)\n",fmuId); // Defaults fmitcp_proto::fmi2_import_get_integer_status_res * getStatusRes = res.mutable_fmi2_import_get_integer_status_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_integer_status_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_value(0); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_integer_status_res(value=%d)\n",getStatusRes->value()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_boolean_status_req){ // Unpack message fmitcp_proto::fmi2_import_get_boolean_status_req * r = req.mutable_fmi2_import_get_boolean_status_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_boolean_status_req(mid=%d,fmuId=%d)\n",r->message_id(),r->fmuid()); // Defaults fmitcp_proto::fmi2_import_get_boolean_status_res * getStatusRes = res.mutable_fmi2_import_get_boolean_status_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_boolean_status_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_value(true); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_boolean_status_res(mid=%d,value=%d)\n",getStatusRes->message_id(),getStatusRes->value()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_string_status_req){ // Unpack message fmitcp_proto::fmi2_import_get_string_status_req * r = req.mutable_fmi2_import_get_string_status_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_string_status_req(mid=%d,fmuId=%d)\n",r->message_id(),r->fmuid()); // Defaults fmitcp_proto::fmi2_import_get_string_status_res * getStatusRes = res.mutable_fmi2_import_get_string_status_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_string_status_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_value("hey there!"); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_string_status_res(mid=%d,value=%s)\n",getStatusRes->message_id(),getStatusRes->value().c_str()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_instantiate_model_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_free_model_instance_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_time_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_continuous_states_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_completed_integrator_step_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_initialize_model_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_derivatives_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_event_indicators_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_eventUpdate_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_completed_event_iteration_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_continuous_states_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_nominal_continuous_states_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_terminate_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_version_req){ // Unpack message fmitcp_proto::fmi2_import_get_version_req * r = req.mutable_fmi2_import_get_version_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_version_req(mid=%d,fmuId=%d)\n",r->message_id(),r->fmuid()); // Defaults fmitcp_proto::fmi2_import_get_version_res * getStatusRes = res.mutable_fmi2_import_get_version_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_version_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_version("VeRsIoN"); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_version_res(mid=%d,version=%s)\n",getStatusRes->message_id(),getStatusRes->version().c_str()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_debug_logging_req){ // Unpack message fmitcp_proto::fmi2_import_set_debug_logging_req * r = req.mutable_fmi2_import_set_debug_logging_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_debug_logging_req(mid=%d,fmuId=%d,loggingOn=%d,categories=...)\n",r->message_id(),r->fmuid(),r->loggingon()); // Defaults fmitcp_proto::fmi2_import_set_debug_logging_res * getStatusRes = res.mutable_fmi2_import_set_debug_logging_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_debug_logging_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_status(fmitcp_proto::fmi2_status_ok); if(!m_sendDummyResponses){ // TODO: Step the FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_debug_logging_res(mid=%d,status=%d)\n",getStatusRes->message_id(),getStatusRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_real_req) { // Unpack message fmitcp_proto::fmi2_import_set_real_req * r = req.mutable_fmi2_import_set_real_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_real_t value[r->values_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); value[i] = r->values(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_real_req(mid=%d,fmuId=%d,vrs=...,values=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_set_real(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_set_real_res * setRealRes = res.mutable_fmi2_import_set_real_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_real_res); setRealRes->set_message_id(r->message_id()); setRealRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_real_res(mid=%d,status=%d)\n",setRealRes->message_id(),setRealRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_integer_req) { // Unpack message fmitcp_proto::fmi2_import_set_integer_req * r = req.mutable_fmi2_import_set_integer_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_integer_t value[r->values_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); value[i] = r->values(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_integer_req(mid=%d,fmuId=%d,vrs=...,values=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_set_integer(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_set_integer_res * setIntegerRes = res.mutable_fmi2_import_set_integer_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_integer_res); setIntegerRes->set_message_id(r->message_id()); setIntegerRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_integer_res(mid=%d,status=%d)\n",setIntegerRes->message_id(),setIntegerRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_boolean_req) { // Unpack message fmitcp_proto::fmi2_import_set_boolean_req * r = req.mutable_fmi2_import_set_boolean_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_boolean_t value[r->values_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); value[i] = r->values(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_boolean_req(mid=%d,fmuId=%d,vrs=...,values=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_set_boolean(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_set_boolean_res * setBooleanRes = res.mutable_fmi2_import_set_boolean_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_boolean_res); setBooleanRes->set_message_id(r->message_id()); setBooleanRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_boolean_res(mid=%d,status=%d)\n",setBooleanRes->message_id(),setBooleanRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_string_req) { // Unpack message fmitcp_proto::fmi2_import_set_string_req * r = req.mutable_fmi2_import_set_string_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_string_t value[r->values_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); value[i] = r->values(i).c_str(); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_string_req(mid=%d,fmuId=%d,vrs=...,values=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_set_string(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_set_string_res * getStatusRes = res.mutable_fmi2_import_set_string_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_string_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_status(fmi2StatusToProtofmi2Status(status)); m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_string_res(mid=%d,status=%d)\n",getStatusRes->message_id(),getStatusRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_req) { // Unpack message fmitcp_proto::fmi2_import_get_real_req * r = req.mutable_fmi2_import_get_real_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_real_t value[r->valuereferences_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_real_req(mid=%d,fmuId=%d,vrs=...)\n",r->message_id(),r->fmuid()); // Create response fmitcp_proto::fmi2_import_get_real_res * getRealRes = res.mutable_fmi2_import_get_real_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_real_res); getRealRes->set_message_id(r->message_id()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_real(m_fmi2Instance, vr, r->valuereferences_size(), value); getRealRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->valuereferences_size() ; i++) { getRealRes->add_values(value[i]); } } else { // Set dummy values for (int i = 0 ; i < r->valuereferences_size() ; i++) { getRealRes->add_values(0.0); } getRealRes->set_status(fmi2StatusToProtofmi2Status(fmi2_status_ok)); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_real_res(mid=%d,status=%d,values=...)\n",getRealRes->message_id(),getRealRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_integer_req) { // Unpack message fmitcp_proto::fmi2_import_get_integer_req * r = req.mutable_fmi2_import_get_integer_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_integer_t value[r->valuereferences_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_integer_req(mid=%d,fmuId=%d,vrs=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_integer(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_get_integer_res * getIntegerRes = res.mutable_fmi2_import_get_integer_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_integer_res); getIntegerRes->set_message_id(r->message_id()); getIntegerRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->valuereferences_size() ; i++) { getIntegerRes->add_values(value[i]); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_integer_res(mid=%d,status=%d,values=...)\n",getIntegerRes->message_id(),getIntegerRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_boolean_req) { // Unpack message fmitcp_proto::fmi2_import_get_boolean_req * r = req.mutable_fmi2_import_get_boolean_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_boolean_t value[r->valuereferences_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_boolean_req(mid=%d,fmuId=%d,vrs=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_boolean(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_get_boolean_res * getBooleanRes = res.mutable_fmi2_import_get_boolean_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_boolean_res); getBooleanRes->set_message_id(r->message_id()); getBooleanRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->valuereferences_size() ; i++) { getBooleanRes->add_values(value[i]); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_boolean_res(mid=%d,status=%d,values=...)\n",getBooleanRes->message_id(),getBooleanRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_string_req) { // Unpack message fmitcp_proto::fmi2_import_get_string_req * r = req.mutable_fmi2_import_get_string_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t vr[r->valuereferences_size()]; fmi2_string_t value[r->valuereferences_size()]; for (int i = 0 ; i < r->valuereferences_size() ; i++) { vr[i] = r->valuereferences(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_string_req(mid=%d,fmuId=%d,vrs=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_string(m_fmi2Instance, vr, r->valuereferences_size(), value); } // Create response fmitcp_proto::fmi2_import_get_string_res * getStringRes = res.mutable_fmi2_import_get_string_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_string_res); getStringRes->set_message_id(r->message_id()); getStringRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->valuereferences_size() ; i++) { getStringRes->add_values(value[i]); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_string_res(mid=%d,status=%d,values=...)\n",getStringRes->message_id(),getStringRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_fmu_state_req){ // Unpack message fmitcp_proto::fmi2_import_get_fmu_state_req * r = req.mutable_fmi2_import_get_fmu_state_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_fmu_state_req(mid=%d,fmuId=%d)\n",r->message_id(),r->fmuid()); fmitcp_proto::fmi2_import_get_fmu_state_res * getStatusRes = res.mutable_fmi2_import_get_fmu_state_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_fmu_state_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_status(fmitcp_proto::fmi2_status_ok); getStatusRes->set_stateid(0); // TODO if(!m_sendDummyResponses){ // TODO: interact with FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_fmu_state_res(mid=%d,stateId=%d,status=%d)\n",getStatusRes->message_id(),getStatusRes->stateid(),getStatusRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_fmu_state_req){ // Unpack message fmitcp_proto::fmi2_import_set_fmu_state_req * r = req.mutable_fmi2_import_set_fmu_state_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_set_fmu_state_req(mid=%d,fmuId=%d,stateId=%d)\n",r->message_id(),r->fmuid(),r->stateid()); fmitcp_proto::fmi2_import_set_fmu_state_res * getStatusRes = res.mutable_fmi2_import_set_fmu_state_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_set_fmu_state_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_status(fmitcp_proto::fmi2_status_ok); if(!m_sendDummyResponses){ // TODO: interact with FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_set_fmu_state_res(mid=%d,status=%d)\n",getStatusRes->message_id(),getStatusRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_free_fmu_state_req){ // Unpack message fmitcp_proto::fmi2_import_free_fmu_state_req * r = req.mutable_fmi2_import_free_fmu_state_req(); m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_free_fmu_state_req(mid=%d,stateId=%d)\n",r->message_id(),r->stateid()); fmitcp_proto::fmi2_import_free_fmu_state_res * getStatusRes = res.mutable_fmi2_import_free_fmu_state_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_free_fmu_state_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_status(fmitcp_proto::fmi2_status_ok); if(!m_sendDummyResponses){ // TODO: interact with FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_free_fmu_state_res(mid=%d,status=%d)\n",getStatusRes->message_id(),getStatusRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_serialized_fmu_state_size_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_serialize_fmu_state_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_de_serialize_fmu_state_req){ // TODO sendResponse = false; } else if(type == fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_directional_derivative_req){ // Unpack message fmitcp_proto::fmi2_import_get_directional_derivative_req * r = req.mutable_fmi2_import_get_directional_derivative_req(); int messageId = r->message_id(); int fmuId = r->fmuid(); fmi2_value_reference_t v_ref[r->v_ref_size()]; fmi2_value_reference_t z_ref[r->z_ref_size()]; fmi2_real_t dv[r->dv_size()], dz[r->z_ref_size()]; for (int i = 0 ; i < r->v_ref_size() ; i++) { v_ref[i] = r->v_ref(i); } for (int i = 0 ; i < r->z_ref_size() ; i++) { z_ref[i] = r->z_ref(i); } for (int i = 0 ; i < r->dv_size() ; i++) { dv[i] = r->dv(i); } m_logger.log(Logger::LOG_NETWORK,"< fmi2_import_get_directional_derivative_req(mid=%d,fmuId=%d,vref=...,zref=...,dv=...)\n",r->message_id(),r->fmuid()); fmi2_status_t status = fmi2_status_ok; if (!m_sendDummyResponses) { // interact with FMU status = fmi2_import_get_directional_derivative(m_fmi2Instance, v_ref, r->v_ref_size(), z_ref, r->z_ref_size(), dv, dz); } // Create response fmitcp_proto::fmi2_import_get_directional_derivative_res * getDirectionalDerivativesRes = res.mutable_fmi2_import_get_directional_derivative_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_fmi2_import_get_directional_derivative_res); getDirectionalDerivativesRes->set_message_id(r->message_id()); getDirectionalDerivativesRes->set_status(fmi2StatusToProtofmi2Status(status)); for (int i = 0 ; i < r->z_ref_size() ; i++) { getDirectionalDerivativesRes->add_dz(dz[i]); } m_logger.log(Logger::LOG_NETWORK,"> fmi2_import_get_directional_derivative_res(mid=%d,status=%d,dz=...)\n",getDirectionalDerivativesRes->message_id(),getDirectionalDerivativesRes->status()); } else if(type == fmitcp_proto::fmitcp_message_Type_type_get_xml_req){ // Unpack message fmitcp_proto::get_xml_req * r = req.mutable_get_xml_req(); m_logger.log(Logger::LOG_NETWORK,"< get_xml_req(mid=%d,fmuId=%d)\n",r->message_id(),r->fmuid()); fmitcp_proto::get_xml_res * getStatusRes = res.mutable_get_xml_res(); res.set_type(fmitcp_proto::fmitcp_message_Type_type_get_xml_res); getStatusRes->set_message_id(r->message_id()); getStatusRes->set_xml(""); if(!m_sendDummyResponses){ // TODO: interact with FMU } // Create response m_logger.log(Logger::LOG_NETWORK,"> get_xml_res(mid=%d,xml=...)\n",getStatusRes->message_id()); } else { // Something is wrong. sendResponse = false; m_logger.log(Logger::LOG_ERROR,"Message type not recognized: %d.\n",type); } if (sendResponse) { sendMessage(c, &res); } } void Server::host(string hostName, long port) { // save this object in the server tag so we can use it later on. lw_server_set_tag(m_server, (void*)this); // connect the hooks lw_server_on_connect( m_server, serverOnConnect); lw_server_on_data( m_server, serverOnData); lw_server_on_disconnect(m_server, serverOnDisconnect); lw_server_on_error( m_server, serverOnError); // setup the server host name and port lw_addr host = lw_addr_new_port(hostName.c_str(), port); lw_filter filter = lw_filter_new(); lw_filter_set_ipv6(filter, lw_false); lw_filter_set_local(filter, host); // host/start the server lw_server_host_filter(m_server, filter); lw_filter_delete(filter); m_logger.log(Logger::LOG_NETWORK,"Listening to %s:%ld\n",hostName.c_str(),port); } void Server::sendDummyResponses(bool sendDummyResponses){ m_sendDummyResponses = sendDummyResponses; } void Server::sendMessage(lw_client c, fmitcp_proto::fmitcp_message* message) { fmitcp::sendProtoBuffer(c,message); } void Server::setLogger(const Logger &logger) { m_logger = logger; }
#ifndef ENTT_SIGNAL_SIGH_HPP #define ENTT_SIGNAL_SIGH_HPP #include <algorithm> #include <utility> #include <vector> #include <functional> #include <type_traits> #include "../config/config.h" #include "delegate.hpp" #include "fwd.hpp" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename, typename> struct invoker; template<typename Ret, typename... Args, typename Collector> struct invoker<Ret(Args...), Collector> { virtual ~invoker() = default; bool invoke(Collector &collector, const delegate<Ret(Args...)> &delegate, Args... args) const { return collector(delegate(args...)); } }; template<typename... Args, typename Collector> struct invoker<void(Args...), Collector> { virtual ~invoker() = default; bool invoke(Collector &, const delegate<void(Args...)> &delegate, Args... args) const { return (delegate(args...), true); } }; template<typename Ret> struct null_collector { using result_type = Ret; bool operator()(result_type) const ENTT_NOEXCEPT { return true; } }; template<> struct null_collector<void> { using result_type = void; bool operator()() const ENTT_NOEXCEPT { return true; } }; template<typename> struct default_collector; template<typename Ret, typename... Args> struct default_collector<Ret(Args...)> { using collector_type = null_collector<Ret>; }; template<typename Function> using default_collector_type = typename default_collector<Function>::collector_type; } /** * Internal details not to be documented. * @endcond TURN_OFF_DOXYGEN */ /** * @brief Sink implementation. * * Primary template isn't defined on purpose. All the specializations give a * compile-time error unless the template parameter is a function type. * * @tparam Function A valid function type. */ template<typename Function> class sink; /** * @brief Unmanaged signal handler declaration. * * Primary template isn't defined on purpose. All the specializations give a * compile-time error unless the template parameter is a function type. * * @tparam Function A valid function type. * @tparam Collector Type of collector to use, if any. */ template<typename Function, typename Collector = internal::default_collector_type<Function>> struct sigh; /** * @brief Sink implementation. * * A sink is an opaque object used to connect listeners to signals.<br/> * The function type for a listener is the one of the signal to which it * belongs. * * The clear separation between a signal and a sink permits to store the former * as private data member without exposing the publish functionality to the * users of a class. * * @tparam Ret Return type of a function type. * @tparam Args Types of arguments of a function type. */ template<typename Ret, typename... Args> class sink<Ret(Args...)> { /*! @brief A signal is allowed to create sinks. */ template<typename, typename> friend struct sigh; template<typename Type> Type * payload_type(Ret(*)(Type *, Args...)); sink(std::vector<delegate<Ret(Args...)>> *ref) ENTT_NOEXCEPT : calls{ref} {} public: /** * @brief Returns false if at least a listener is connected to the sink. * @return True if the sink has no listeners connected, false otherwise. */ bool empty() const ENTT_NOEXCEPT { return calls->empty(); } /** * @brief Connects a free function to a signal. * * The signal handler performs checks to avoid multiple connections for free * functions. * * @tparam Function A valid free function pointer. */ template<auto Function> void connect() { disconnect<Function>(); delegate<Ret(Args...)> delegate{}; delegate.template connect<Function>(); calls->emplace_back(std::move(delegate)); } /** * @brief Connects a member function or a free function with payload to a * signal. * * The signal isn't responsible for the connected object or the payload. * Users must always guarantee that the lifetime of the instance overcomes * the one of the delegate. On the other side, the signal handler performs * checks to avoid multiple connections for the same function.<br/> * When used to connect a free function with payload, its signature must be * such that the instance is the first argument before the ones used to * define the delegate itself. * * @tparam Candidate Member or free function to connect to the signal. * @tparam Type Type of class or type of payload. * @param value_or_instance A valid pointer that fits the purpose. */ template<auto Candidate, typename Type> void connect(Type *value_or_instance) { disconnect<Candidate>(value_or_instance); delegate<Ret(Args...)> delegate{}; delegate.template connect<Candidate>(value_or_instance); calls->emplace_back(std::move(delegate)); } /** * @brief Disconnects a free function from a signal. * @tparam Function A valid free function pointer. */ template<auto Function> void disconnect() { delegate<Ret(Args...)> delegate{}; delegate.template connect<Function>(); calls->erase(std::remove(calls->begin(), calls->end(), std::move(delegate)), calls->end()); } /** * @brief Disconnects a member function or a free function with payload from * a signal. * @tparam Candidate Member or free function to disconnect from the signal. * @tparam Type Type of class or type of payload. * @param value_or_instance A valid pointer that fits the purpose. */ template<auto Candidate, typename Type> void disconnect(Type *value_or_instance) { delegate<Ret(Args...)> delegate{}; delegate.template connect<Candidate>(value_or_instance); calls->erase(std::remove_if(calls->begin(), calls->end(), [delegate](const auto &other) { return other == delegate && other.instance() == delegate.instance(); }), calls->end()); } /** * @brief Disconnects member functions or free functions based on an * instance or specific payload. * @param value_or_instance A valid pointer that fits the purpose. */ void disconnect(const void *value_or_instance) { calls->erase(std::remove_if(calls->begin(), calls->end(), [value_or_instance](const auto &delegate) { return value_or_instance == delegate.instance(); }), calls->end()); } /*! @brief Disconnects all the listeners from a signal. */ void disconnect() { calls->clear(); } private: std::vector<delegate<Ret(Args...)>> *calls; }; /** * @brief Unmanaged signal handler definition. * * Unmanaged signal handler. It works directly with naked pointers to classes * and pointers to member functions as well as pointers to free functions. Users * of this class are in charge of disconnecting instances before deleting them. * * This class serves mainly two purposes: * * * Creating signals used later to notify a bunch of listeners. * * Collecting results from a set of functions like in a voting system. * * The default collector does nothing. To properly collect data, define and use * a class that has a call operator the signature of which is `bool(Param)` and: * * * `Param` is a type to which `Ret` can be converted. * * The return type is true if the handler must stop collecting data, false * otherwise. * * @tparam Ret Return type of a function type. * @tparam Args Types of arguments of a function type. * @tparam Collector Type of collector to use, if any. */ template<typename Ret, typename... Args, typename Collector> struct sigh<Ret(Args...), Collector>: private internal::invoker<Ret(Args...), Collector> { /*! @brief Unsigned integer type. */ using size_type = typename std::vector<delegate<Ret(Args...)>>::size_type; /*! @brief Collector type. */ using collector_type = Collector; /*! @brief Sink type. */ using sink_type = entt::sink<Ret(Args...)>; /** * @brief Instance type when it comes to connecting member functions. * @tparam Class Type of class to which the member function belongs. */ template<typename Class> using instance_type = Class *; /** * @brief Number of listeners connected to the signal. * @return Number of listeners currently connected. */ size_type size() const ENTT_NOEXCEPT { return calls.size(); } /** * @brief Returns false if at least a listener is connected to the signal. * @return True if the signal has no listeners connected, false otherwise. */ bool empty() const ENTT_NOEXCEPT { return calls.empty(); } /** * @brief Returns a sink object for the given signal. * * A sink is an opaque object used to connect listeners to signals.<br/> * The function type for a listener is the one of the signal to which it * belongs. The order of invocation of the listeners isn't guaranteed. * * @return A temporary sink object. */ sink_type sink() ENTT_NOEXCEPT { return { &calls }; } /** * @brief Triggers a signal. * * All the listeners are notified. Order isn't guaranteed. * * @param args Arguments to use to invoke listeners. */ void publish(Args... args) const { for(auto pos = calls.size(); pos; --pos) { auto &call = calls[pos-1]; call(args...); } } /** * @brief Collects return values from the listeners. * @param args Arguments to use to invoke listeners. * @return An instance of the collector filled with collected data. */ collector_type collect(Args... args) const { collector_type collector; for(auto &&call: calls) { if(!this->invoke(collector, call, args...)) { break; } } return collector; } /** * @brief Swaps listeners between the two signals. * @param lhs A valid signal object. * @param rhs A valid signal object. */ friend void swap(sigh &lhs, sigh &rhs) { using std::swap; swap(lhs.calls, rhs.calls); } private: std::vector<delegate<Ret(Args...)>> calls; }; } #endif // ENTT_SIGNAL_SIGH_HPP cleanup - thanks to @Kerndog73 (see #267) #ifndef ENTT_SIGNAL_SIGH_HPP #define ENTT_SIGNAL_SIGH_HPP #include <algorithm> #include <utility> #include <vector> #include <functional> #include <type_traits> #include "../config/config.h" #include "delegate.hpp" #include "fwd.hpp" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename, typename> struct invoker; template<typename Ret, typename... Args, typename Collector> struct invoker<Ret(Args...), Collector> { bool invoke(Collector &collector, const delegate<Ret(Args...)> &delegate, Args... args) const { return collector(delegate(args...)); } }; template<typename... Args, typename Collector> struct invoker<void(Args...), Collector> { bool invoke(Collector &, const delegate<void(Args...)> &delegate, Args... args) const { return (delegate(args...), true); } }; template<typename Ret> struct null_collector { using result_type = Ret; bool operator()(result_type) const ENTT_NOEXCEPT { return true; } }; template<> struct null_collector<void> { using result_type = void; bool operator()() const ENTT_NOEXCEPT { return true; } }; template<typename> struct default_collector; template<typename Ret, typename... Args> struct default_collector<Ret(Args...)> { using collector_type = null_collector<Ret>; }; template<typename Function> using default_collector_type = typename default_collector<Function>::collector_type; } /** * Internal details not to be documented. * @endcond TURN_OFF_DOXYGEN */ /** * @brief Sink implementation. * * Primary template isn't defined on purpose. All the specializations give a * compile-time error unless the template parameter is a function type. * * @tparam Function A valid function type. */ template<typename Function> class sink; /** * @brief Unmanaged signal handler declaration. * * Primary template isn't defined on purpose. All the specializations give a * compile-time error unless the template parameter is a function type. * * @tparam Function A valid function type. * @tparam Collector Type of collector to use, if any. */ template<typename Function, typename Collector = internal::default_collector_type<Function>> struct sigh; /** * @brief Sink implementation. * * A sink is an opaque object used to connect listeners to signals.<br/> * The function type for a listener is the one of the signal to which it * belongs. * * The clear separation between a signal and a sink permits to store the former * as private data member without exposing the publish functionality to the * users of a class. * * @tparam Ret Return type of a function type. * @tparam Args Types of arguments of a function type. */ template<typename Ret, typename... Args> class sink<Ret(Args...)> { /*! @brief A signal is allowed to create sinks. */ template<typename, typename> friend struct sigh; sink(std::vector<delegate<Ret(Args...)>> *ref) ENTT_NOEXCEPT : calls{ref} {} public: /** * @brief Returns false if at least a listener is connected to the sink. * @return True if the sink has no listeners connected, false otherwise. */ bool empty() const ENTT_NOEXCEPT { return calls->empty(); } /** * @brief Connects a free function to a signal. * * The signal handler performs checks to avoid multiple connections for free * functions. * * @tparam Function A valid free function pointer. */ template<auto Function> void connect() { disconnect<Function>(); delegate<Ret(Args...)> delegate{}; delegate.template connect<Function>(); calls->emplace_back(std::move(delegate)); } /** * @brief Connects a member function or a free function with payload to a * signal. * * The signal isn't responsible for the connected object or the payload. * Users must always guarantee that the lifetime of the instance overcomes * the one of the delegate. On the other side, the signal handler performs * checks to avoid multiple connections for the same function.<br/> * When used to connect a free function with payload, its signature must be * such that the instance is the first argument before the ones used to * define the delegate itself. * * @tparam Candidate Member or free function to connect to the signal. * @tparam Type Type of class or type of payload. * @param value_or_instance A valid pointer that fits the purpose. */ template<auto Candidate, typename Type> void connect(Type *value_or_instance) { disconnect<Candidate>(value_or_instance); delegate<Ret(Args...)> delegate{}; delegate.template connect<Candidate>(value_or_instance); calls->emplace_back(std::move(delegate)); } /** * @brief Disconnects a free function from a signal. * @tparam Function A valid free function pointer. */ template<auto Function> void disconnect() { delegate<Ret(Args...)> delegate{}; delegate.template connect<Function>(); calls->erase(std::remove(calls->begin(), calls->end(), std::move(delegate)), calls->end()); } /** * @brief Disconnects a member function or a free function with payload from * a signal. * @tparam Candidate Member or free function to disconnect from the signal. * @tparam Type Type of class or type of payload. * @param value_or_instance A valid pointer that fits the purpose. */ template<auto Candidate, typename Type> void disconnect(Type *value_or_instance) { delegate<Ret(Args...)> delegate{}; delegate.template connect<Candidate>(value_or_instance); calls->erase(std::remove_if(calls->begin(), calls->end(), [delegate](const auto &other) { return other == delegate && other.instance() == delegate.instance(); }), calls->end()); } /** * @brief Disconnects member functions or free functions based on an * instance or specific payload. * @param value_or_instance A valid pointer that fits the purpose. */ void disconnect(const void *value_or_instance) { calls->erase(std::remove_if(calls->begin(), calls->end(), [value_or_instance](const auto &delegate) { return value_or_instance == delegate.instance(); }), calls->end()); } /*! @brief Disconnects all the listeners from a signal. */ void disconnect() { calls->clear(); } private: std::vector<delegate<Ret(Args...)>> *calls; }; /** * @brief Unmanaged signal handler definition. * * Unmanaged signal handler. It works directly with naked pointers to classes * and pointers to member functions as well as pointers to free functions. Users * of this class are in charge of disconnecting instances before deleting them. * * This class serves mainly two purposes: * * * Creating signals used later to notify a bunch of listeners. * * Collecting results from a set of functions like in a voting system. * * The default collector does nothing. To properly collect data, define and use * a class that has a call operator the signature of which is `bool(Param)` and: * * * `Param` is a type to which `Ret` can be converted. * * The return type is true if the handler must stop collecting data, false * otherwise. * * @tparam Ret Return type of a function type. * @tparam Args Types of arguments of a function type. * @tparam Collector Type of collector to use, if any. */ template<typename Ret, typename... Args, typename Collector> struct sigh<Ret(Args...), Collector>: private internal::invoker<Ret(Args...), Collector> { /*! @brief Unsigned integer type. */ using size_type = typename std::vector<delegate<Ret(Args...)>>::size_type; /*! @brief Collector type. */ using collector_type = Collector; /*! @brief Sink type. */ using sink_type = entt::sink<Ret(Args...)>; /** * @brief Instance type when it comes to connecting member functions. * @tparam Class Type of class to which the member function belongs. */ template<typename Class> using instance_type = Class *; /** * @brief Number of listeners connected to the signal. * @return Number of listeners currently connected. */ size_type size() const ENTT_NOEXCEPT { return calls.size(); } /** * @brief Returns false if at least a listener is connected to the signal. * @return True if the signal has no listeners connected, false otherwise. */ bool empty() const ENTT_NOEXCEPT { return calls.empty(); } /** * @brief Returns a sink object for the given signal. * * A sink is an opaque object used to connect listeners to signals.<br/> * The function type for a listener is the one of the signal to which it * belongs. The order of invocation of the listeners isn't guaranteed. * * @return A temporary sink object. */ sink_type sink() ENTT_NOEXCEPT { return { &calls }; } /** * @brief Triggers a signal. * * All the listeners are notified. Order isn't guaranteed. * * @param args Arguments to use to invoke listeners. */ void publish(Args... args) const { for(auto pos = calls.size(); pos; --pos) { auto &call = calls[pos-1]; call(args...); } } /** * @brief Collects return values from the listeners. * @param args Arguments to use to invoke listeners. * @return An instance of the collector filled with collected data. */ collector_type collect(Args... args) const { collector_type collector; for(auto &&call: calls) { if(!this->invoke(collector, call, args...)) { break; } } return collector; } /** * @brief Swaps listeners between the two signals. * @param lhs A valid signal object. * @param rhs A valid signal object. */ friend void swap(sigh &lhs, sigh &rhs) { using std::swap; swap(lhs.calls, rhs.calls); } private: std::vector<delegate<Ret(Args...)>> calls; }; } #endif // ENTT_SIGNAL_SIGH_HPP
/* * cfibentry.cc * * Created on: 15.07.2013 * Author: andreas */ #include <cfibentry.h> using namespace ethercore; cfibentry::cfibentry( cfibentry_owner *fib, uint8_t src_stage_table_id, uint8_t dst_stage_table_id, rofl::cmacaddr lladdr, uint64_t dpid, uint16_t vid, uint32_t out_port_no, bool tagged) : fib(fib), dpid(dpid), vid(vid), portno(out_port_no), tagged(tagged), lladdr(lladdr), src_stage_table_id(src_stage_table_id), dst_stage_table_id(dst_stage_table_id), entry_timeout(CFIBENTRY_DEFAULT_TIMEOUT), expiration_timer_id(0) { flow_mod_configure(FLOW_MOD_ADD); //expiration_timer_id = register_timer(CFIBENTRY_ENTRY_EXPIRED, entry_timeout); } cfibentry::~cfibentry() { flow_mod_configure(FLOW_MOD_DELETE); #if 0 rofl::crofbase *rofbase = fib->get_rofbase(); rofl::crofdpt *dpt = rofbase->dpt_find(dpid); rofbase->send_barrier_request(dpt); #endif } void cfibentry::handle_timeout(int opaque, void *data) { switch (opaque) { // intentionally disabled #if 0 case CFIBENTRY_ENTRY_EXPIRED: { flow_mod_configure(FLOW_MOD_DELETE); fib->fib_timer_expired(this); } break; #endif } } void cfibentry::set_portno(uint32_t portno) { flow_mod_configure(FLOW_MOD_DELETE); this->portno = portno; #if 0 // intentionally disabled reset_timer(expiration_timer_id, entry_timeout); #endif flow_mod_configure(FLOW_MOD_ADD); } void cfibentry::flow_mod_configure(enum flow_mod_cmd_t flow_mod_cmd) { try { rofl::crofbase *rofbase = fib->get_rofbase(); rofl::crofdpt *dpt = rofbase->dpt_find(dpid); if ((NULL == dpt) || (rofl::openflow::OFP_VERSION_UNKNOWN == dpt->get_version())) { return; } rofl::cofflowmod fe(dpt->get_version()); /* table 'src_stage_table_id': * * if src mac address is already known, move on to next table, otherwise, send packet to controller * * this allows the controller to learn yet unknown src macs when being received on a port */ if (true) { fe.reset(); switch (flow_mod_cmd) { case FLOW_MOD_ADD: fe.set_command(OFPFC_ADD); break; case FLOW_MOD_MODIFY: fe.set_command(OFPFC_MODIFY_STRICT); break; case FLOW_MOD_DELETE: fe.set_command(OFPFC_DELETE_STRICT); break; } fe.set_table_id(src_stage_table_id); fe.set_priority(0x8000); fe.set_idle_timeout(entry_timeout); fe.set_flags(rofl::openflow12::OFPFF_SEND_FLOW_REM); fe.match.set_in_port(portno); fe.match.set_vlan_vid(vid); fe.match.set_eth_src(lladdr); // yes, indeed: set_eth_src for dst fe.instructions.add_inst_goto_table().set_table_id(dst_stage_table_id); dpt->send_flow_mod_message(fe); } dpt->send_barrier_request(); /* table 'dst_stage_table_id': * * add a second rule to dst-stage: checks for destination */ if (true) { fe.reset(); switch (flow_mod_cmd) { case FLOW_MOD_ADD: fe.set_command(OFPFC_ADD); break; case FLOW_MOD_MODIFY: fe.set_command(OFPFC_MODIFY_STRICT); break; case FLOW_MOD_DELETE: fe.set_command(OFPFC_DELETE_STRICT); break; } fe.set_table_id(dst_stage_table_id); fe.set_priority(0x8000); fe.set_idle_timeout(entry_timeout); fe.match.set_vlan_vid(vid); fe.match.set_eth_dst(lladdr); fe.instructions.add_inst_apply_actions(); if (not tagged) fe.instructions.set_inst_apply_actions().get_actions().append_action_pop_vlan(); fe.instructions.set_inst_apply_actions().get_actions().append_action_output(portno); dpt->send_flow_mod_message(fe); } dpt->send_barrier_request(); } catch (rofl::eRofBaseNotFound& e) { } catch (rofl::eBadVersion& e) { logging::error << "[ethcore][cfibentry] data path already disconnected, unable to remove our entries" << std::endl; } } ethcore => cfibentry => removing sending of Barrier Request messages /* * cfibentry.cc * * Created on: 15.07.2013 * Author: andreas */ #include <cfibentry.h> using namespace ethercore; cfibentry::cfibentry( cfibentry_owner *fib, uint8_t src_stage_table_id, uint8_t dst_stage_table_id, rofl::cmacaddr lladdr, uint64_t dpid, uint16_t vid, uint32_t out_port_no, bool tagged) : fib(fib), dpid(dpid), vid(vid), portno(out_port_no), tagged(tagged), lladdr(lladdr), src_stage_table_id(src_stage_table_id), dst_stage_table_id(dst_stage_table_id), entry_timeout(CFIBENTRY_DEFAULT_TIMEOUT), expiration_timer_id(0) { flow_mod_configure(FLOW_MOD_ADD); //expiration_timer_id = register_timer(CFIBENTRY_ENTRY_EXPIRED, entry_timeout); } cfibentry::~cfibentry() { flow_mod_configure(FLOW_MOD_DELETE); #if 0 rofl::crofbase *rofbase = fib->get_rofbase(); rofl::crofdpt *dpt = rofbase->dpt_find(dpid); //rofbase->send_barrier_request(dpt); #endif } void cfibentry::handle_timeout(int opaque, void *data) { switch (opaque) { // intentionally disabled #if 0 case CFIBENTRY_ENTRY_EXPIRED: { flow_mod_configure(FLOW_MOD_DELETE); fib->fib_timer_expired(this); } break; #endif } } void cfibentry::set_portno(uint32_t portno) { flow_mod_configure(FLOW_MOD_DELETE); this->portno = portno; #if 0 // intentionally disabled reset_timer(expiration_timer_id, entry_timeout); #endif flow_mod_configure(FLOW_MOD_ADD); } void cfibentry::flow_mod_configure(enum flow_mod_cmd_t flow_mod_cmd) { try { rofl::crofbase *rofbase = fib->get_rofbase(); rofl::crofdpt *dpt = rofbase->dpt_find(dpid); if ((NULL == dpt) || (rofl::openflow::OFP_VERSION_UNKNOWN == dpt->get_version())) { return; } rofl::cofflowmod fe(dpt->get_version()); /* table 'src_stage_table_id': * * if src mac address is already known, move on to next table, otherwise, send packet to controller * * this allows the controller to learn yet unknown src macs when being received on a port */ if (true) { fe.reset(); switch (flow_mod_cmd) { case FLOW_MOD_ADD: fe.set_command(OFPFC_ADD); break; case FLOW_MOD_MODIFY: fe.set_command(OFPFC_MODIFY_STRICT); break; case FLOW_MOD_DELETE: fe.set_command(OFPFC_DELETE_STRICT); break; } fe.set_table_id(src_stage_table_id); fe.set_priority(0x8000); fe.set_idle_timeout(entry_timeout); fe.set_flags(rofl::openflow12::OFPFF_SEND_FLOW_REM); fe.match.set_in_port(portno); fe.match.set_vlan_vid(vid); fe.match.set_eth_src(lladdr); // yes, indeed: set_eth_src for dst fe.instructions.add_inst_goto_table().set_table_id(dst_stage_table_id); dpt->send_flow_mod_message(fe); } //dpt->send_barrier_request(); /* table 'dst_stage_table_id': * * add a second rule to dst-stage: checks for destination */ if (true) { fe.reset(); switch (flow_mod_cmd) { case FLOW_MOD_ADD: fe.set_command(OFPFC_ADD); break; case FLOW_MOD_MODIFY: fe.set_command(OFPFC_MODIFY_STRICT); break; case FLOW_MOD_DELETE: fe.set_command(OFPFC_DELETE_STRICT); break; } fe.set_table_id(dst_stage_table_id); fe.set_priority(0x8000); fe.set_idle_timeout(entry_timeout); fe.match.set_vlan_vid(vid); fe.match.set_eth_dst(lladdr); fe.instructions.add_inst_apply_actions(); if (not tagged) fe.instructions.set_inst_apply_actions().get_actions().append_action_pop_vlan(); fe.instructions.set_inst_apply_actions().get_actions().append_action_output(portno); dpt->send_flow_mod_message(fe); } //dpt->send_barrier_request(); } catch (rofl::eRofBaseNotFound& e) { } catch (rofl::eBadVersion& e) { logging::error << "[ethcore][cfibentry] data path already disconnected, unable to remove our entries" << std::endl; } }
/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * synexts/lang_item.cpp * - Binds language items to #[lang_item] tagged items */ #include <synext.hpp> #include "../common.hpp" #include "../ast/ast.hpp" #include "../ast/crate.hpp" void handle_lang_item(const Span& sp, AST::Crate& crate, const AST::Path& path, const ::std::string& name, AST::eItemType type) { if(name == "phantom_fn") { // - Just save path } else if( name == "send" ) { // Don't care, Send is fully library in mrustc // - Needed for `static` } else if( name == "sync" ) { // Don't care, Sync is fully library in mrustc // - Needed for `static` } else if( name == "sized" ) { DEBUG("Bind 'sized' to " << path); } else if( name == "copy" ) { DEBUG("Bind 'copy' to " << path); } // ops traits else if( name == "drop" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "add" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "sub" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "mul" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "div" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "rem" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "neg" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "not" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitand" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitor" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitxor" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "shl" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "shr" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "add_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "sub_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "div_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "rem_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "mul_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitand_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitor_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitxor_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "shl_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "shr_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "index" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "deref" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "index_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "deref_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "fn" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "fn_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "fn_once" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "eq" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "ord" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "unsize" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "coerce_unsized" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "iterator" ) { /* mrustc just desugars? */ } else if( name == "debug_trait" ) { /* TODO: Poke derive() with this */ } // Structs else if( name == "non_zero" ) { } else if( name == "phantom_data" ) { } else if( name == "range_full" ) { } else if( name == "range" ) { } else if( name == "range_from" ) { } else if( name == "range_to" ) { } else if( name == "unsafe_cell" ) { } // Functions else if( name == "panic" ) { } else if( name == "panic_bounds_check" ) { } else if( name == "panic_fmt" ) { } else if( name == "str_eq" ) { } // - builtin `box` support else if( name == "exchange_malloc" ) { } else if( name == "exchange_free" ) { } else if( name == "box_free" ) { } else if( name == "owned_box" ) { } else { ERROR(sp, E0000, "Unknown language item '" << name << "'"); } auto rv = crate.m_lang_items.insert( ::std::make_pair( name, ::AST::Path(path) ) ); if( !rv.second ) { ERROR(sp, E0000, "Duplicate definition of language item '" << name << "'"); } } class Decorator_LangItem: public ExpandDecorator { public: AttrStage stage() const override { return AttrStage::EarlyPost; } void handle(const Span& sp, const AST::MetaItem& attr, AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item& i) const override { TU_MATCH_DEF(::AST::Item, (i), (e), ( TODO(sp, "Unknown item type with #[lang=\""<<attr<<"\"] attached at " << path); ), (Function, handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_FN); ), (Struct, handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_STRUCT); ), (Trait, handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_TRAIT); ) ) } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, const AST::Module& mod, AST::ImplDef& impl) const override { const ::std::string& name = mi.string(); if( name == "i8" ) {} else if( name == "u8" ) {} else if( name == "i16" ) {} else if( name == "u16" ) {} else if( name == "i32" ) {} else if( name == "u32" ) {} else if( name == "i64" ) {} else if( name == "u64" ) {} else if( name == "isize" ) {} else if( name == "usize" ) {} else if( name == "const_ptr" ) {} else if( name == "mut_ptr" ) {} // rustc_unicode else if( name == "char" ) {} // collections //else if( name == "str" ) {} //else if( name == "slice" ) {} else { ERROR(sp, E0000, "Unknown lang item '" << name << "' on impl"); } // TODO: Somehow annotate these impls to allow them to provide inherents? } }; STATIC_DECORATOR("lang", Decorator_LangItem) Expand/lang - libcollections impl lang items /* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * synexts/lang_item.cpp * - Binds language items to #[lang_item] tagged items */ #include <synext.hpp> #include "../common.hpp" #include "../ast/ast.hpp" #include "../ast/crate.hpp" void handle_lang_item(const Span& sp, AST::Crate& crate, const AST::Path& path, const ::std::string& name, AST::eItemType type) { if(name == "phantom_fn") { // - Just save path } else if( name == "send" ) { // Don't care, Send is fully library in mrustc // - Needed for `static` } else if( name == "sync" ) { // Don't care, Sync is fully library in mrustc // - Needed for `static` } else if( name == "sized" ) { DEBUG("Bind 'sized' to " << path); } else if( name == "copy" ) { DEBUG("Bind 'copy' to " << path); } // ops traits else if( name == "drop" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "add" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "sub" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "mul" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "div" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "rem" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "neg" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "not" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitand" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitor" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitxor" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "shl" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "shr" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "add_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "sub_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "div_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "rem_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "mul_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitand_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitor_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "bitxor_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "shl_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "shr_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "index" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "deref" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "index_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "deref_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "fn" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "fn_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "fn_once" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "eq" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "ord" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "unsize" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "coerce_unsized" ) { DEBUG("Bind '"<<name<<"' to " << path); } else if( name == "iterator" ) { /* mrustc just desugars? */ } else if( name == "debug_trait" ) { /* TODO: Poke derive() with this */ } // Structs else if( name == "non_zero" ) { } else if( name == "phantom_data" ) { } else if( name == "range_full" ) { } else if( name == "range" ) { } else if( name == "range_from" ) { } else if( name == "range_to" ) { } else if( name == "unsafe_cell" ) { } // Functions else if( name == "panic" ) { } else if( name == "panic_bounds_check" ) { } else if( name == "panic_fmt" ) { } else if( name == "str_eq" ) { } // - builtin `box` support else if( name == "exchange_malloc" ) { } else if( name == "exchange_free" ) { } else if( name == "box_free" ) { } else if( name == "owned_box" ) { } else { ERROR(sp, E0000, "Unknown language item '" << name << "'"); } auto rv = crate.m_lang_items.insert( ::std::make_pair( name, ::AST::Path(path) ) ); if( !rv.second ) { ERROR(sp, E0000, "Duplicate definition of language item '" << name << "'"); } } class Decorator_LangItem: public ExpandDecorator { public: AttrStage stage() const override { return AttrStage::EarlyPost; } void handle(const Span& sp, const AST::MetaItem& attr, AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item& i) const override { TU_MATCH_DEF(::AST::Item, (i), (e), ( TODO(sp, "Unknown item type with #[lang=\""<<attr<<"\"] attached at " << path); ), (Function, handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_FN); ), (Struct, handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_STRUCT); ), (Trait, handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_TRAIT); ) ) } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, const AST::Module& mod, AST::ImplDef& impl) const override { const ::std::string& name = mi.string(); if( name == "i8" ) {} else if( name == "u8" ) {} else if( name == "i16" ) {} else if( name == "u16" ) {} else if( name == "i32" ) {} else if( name == "u32" ) {} else if( name == "i64" ) {} else if( name == "u64" ) {} else if( name == "isize" ) {} else if( name == "usize" ) {} else if( name == "const_ptr" ) {} else if( name == "mut_ptr" ) {} // rustc_unicode else if( name == "char" ) {} // collections else if( name == "str" ) {} else if( name == "slice" ) {} else { ERROR(sp, E0000, "Unknown lang item '" << name << "' on impl"); } // TODO: Somehow annotate these impls to allow them to provide inherents? } }; STATIC_DECORATOR("lang", Decorator_LangItem)
/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" // implementation header #include "CacheManager.h" // system headers #include <string> #include <vector> #include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <string> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #ifndef _WIN32 # include <unistd.h> #endif // common headers #include "md5.h" #include "bzfio.h" #include "TextUtils.h" #include "FileManager.h" #include "StateDatabase.h" #include "DirectoryNames.h" // function prototypes static bool fileExists(const std::string& name); static void removeDirs(const std::string& path); static void removeNewlines(char* c); static std::string partialEncoding(const std::string& string); static bool compareUsedDate(const CacheManager::CacheRecord& a, const CacheManager::CacheRecord& b); CacheManager CACHEMGR; CacheManager::CacheManager() { indexName = getCacheDirName(); indexName += "CacheIndex.txt"; return; } CacheManager::~CacheManager() { return; } bool CacheManager::isCacheFileType(const std::string name) const { if (strncasecmp(name.c_str(), "http://", 7) == 0) { return true; } if (strncasecmp(name.c_str(), "ftp://", 6) == 0) { return true; } return false; } std::string CacheManager::getLocalName(const std::string name) const { std::string local = ""; if (strncasecmp(name.c_str(), "http://", 7) == 0) { local = getCacheDirName() + "http/"; local += partialEncoding(name.substr(7)); } else if (strncasecmp(name.c_str(), "ftp://", 6) == 0) { local = getCacheDirName() + "ftp/"; local += partialEncoding(name.substr(6)); } #ifdef _WIN32 std::replace(local.begin(), local.end(), '/', '\\'); #endif return local; } bool CacheManager::findURL(const std::string& url, CacheRecord& record) { int pos = findRecord(url); if (pos >= 0) { CacheRecord* rec = &records[pos]; rec->usedDate = time(NULL); // update the timestamp record = *rec; return true; } return false; } bool CacheManager::addFile(CacheRecord& record, const void* data) { if (((data == NULL) && (record.size != 0)) || (record.url.size() <= 0)) { return false; } record.name = getLocalName(record.url); std::ostream* out = FILEMGR.createDataOutStream(record.name); if (out == NULL) { return false; } bool replacement = false; CacheRecord* rec = &record; int pos = findRecord(record.url); if (pos >= 0) { records[pos] = record; rec = &records[pos]; replacement = true; } out->write((char*)data, rec->size); rec->usedDate = time(NULL); // update the timestamp MD5 md5; md5.update((unsigned char *)data, rec->size); md5.finalize(); rec->key = md5.hexdigest(); if (!replacement) { records.push_back(*rec); } delete out; return true; } int CacheManager::findRecord(const std::string& url) { for (unsigned int i = 0; i < records.size(); i++) { CacheRecord* rec = &(records[i]); if (url == rec->url) { return i; } } return -1; } bool CacheManager::loadIndex() { records.clear(); FILE* file = fopen(indexName.c_str(), "r"); if (file == NULL) { return false; } char buffer[1024]; while (fgets(buffer, 1024, file) != NULL) { removeNewlines(buffer); if ((buffer[0] == '\0') || (buffer[0] == '#')) { continue; } CacheRecord rec; rec.url = buffer; rec.name = getLocalName(rec.url); if (fgets(buffer, 1024, file) == NULL) { break; } else { removeNewlines(buffer); } std::string line = buffer; std::vector<std::string> tokens = TextUtils::tokenize(line, " "); if (tokens.size() != 4) { DEBUG1("loadCacheIndex (bad line): %s\n", buffer); continue; } rec.size = strtoul(tokens[0].c_str(), NULL, 10); rec.date = strtoul(tokens[1].c_str(), NULL, 10); rec.usedDate = strtoul(tokens[2].c_str(), NULL, 10); rec.key = tokens[3]; if (fileExists(rec.name)) { records.push_back(rec); } } fclose(file); return true; } bool CacheManager::saveIndex() { std::sort(records.begin(), records.end(), compareUsedDate); std::string tmpIndexName = indexName + ".tmp"; FILE* file = fopen(tmpIndexName.c_str(), "w"); if (file == NULL) { return false; } for (unsigned int i = 0; i < records.size(); i++) { const CacheRecord& rec = records[i]; fprintf(file, "%s\n%u %lu %lu %s\n\n", rec.url.c_str(), rec.size, rec.date, rec.usedDate, rec.key.c_str()); } fclose(file); return (rename(tmpIndexName.c_str(), indexName.c_str()) == 0); } void CacheManager::limitCacheSize() { int maxSize = BZDB.evalInt("maxCacheMB") * 1024 * 1024; if (maxSize < 0) { maxSize = 0; } int currentSize = 0; for (unsigned int i = 0; i < records.size(); i++) { currentSize += records[i].size; } std::sort(records.begin(), records.end(), compareUsedDate); while ((currentSize > maxSize) && (records.size() > 0)) { CacheManager::CacheRecord& rec = records.back(); currentSize -= rec.size; remove(rec.name.c_str()); removeDirs(rec.name); records.pop_back(); } return; } std::vector<CacheManager::CacheRecord> CacheManager::getCacheList() const { return records; } static bool fileExists (const std::string& name) { struct stat buf; #ifndef _WIN32 return (stat(name.c_str(), &buf) == 0); #else // Windows sucks yet again, if there is a trailing "\" // at the end of the filename, _stat will return -1. std::string dirname = name; while (dirname.find_last_of('\\') == (dirname.size() - 1)) { dirname.resize(dirname.size() - 1); } return (_stat(dirname.c_str(), (struct _stat *) &buf) == 0); #endif } static void removeDirs(const std::string& path) { unsigned int minLen = (unsigned int)getConfigDirName().size(); std::string tmp = path; while (tmp.size() > minLen) { #ifndef _WIN32 unsigned int i = (unsigned int)tmp.find_last_of('/'); #else unsigned int i = (unsigned int)tmp.find_last_of('\\'); #endif tmp = tmp.substr(0, i); if (remove(tmp.c_str()) != 0) { break; } } return; } static void removeNewlines(char* c) { while (*c != '\0') { if ((*c == '\n') || (*c == '\r')) { *c = '\0'; } c++; } return; } static std::string partialEncoding(const std::string& string) { // URL encoding removes the '/' and '.', which is // not acceptable. It is nice to have the directory // structure, and to be able to point and click your // way through it to view ".png"s. std::string tmp; char hex[5]; for (unsigned int i = 0; i < string.size(); i++) { const char c = string[i]; if (TextUtils::isWhitespace(c)) { tmp += "%20"; } else if ((c == '%') || (c == '*') || (c == '?') || (c == ':') || (c == '"') || (c == '\\')) { tmp += '%'; sprintf(hex, "%-2.2X", c); tmp += hex; } else { tmp += c; } } return tmp; } static bool compareUsedDate(const CacheManager::CacheRecord& a, const CacheManager::CacheRecord& b) { // oldest last return (a.usedDate > b.usedDate); } /* * Local Variables: *** * mode:C *** * tab-width: 8 *** * c-basic-offset: 2 *** * indent-tabs-mode: t *** * End: *** * ex: shiftwidth=2 tabstop=8 */ don't include <string> twice, use <string.h> git-svn-id: 67bf12f30ddf2081c31403e0b02b2123541f1680@10146 08b3d480-bf2c-0410-a26f-811ee3361c24 /* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" // implementation header #include "CacheManager.h" // system headers #include <string> #include <vector> #include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #ifndef _WIN32 # include <unistd.h> #endif // common headers #include "md5.h" #include "bzfio.h" #include "TextUtils.h" #include "FileManager.h" #include "StateDatabase.h" #include "DirectoryNames.h" // function prototypes static bool fileExists(const std::string& name); static void removeDirs(const std::string& path); static void removeNewlines(char* c); static std::string partialEncoding(const std::string& string); static bool compareUsedDate(const CacheManager::CacheRecord& a, const CacheManager::CacheRecord& b); CacheManager CACHEMGR; CacheManager::CacheManager() { indexName = getCacheDirName(); indexName += "CacheIndex.txt"; return; } CacheManager::~CacheManager() { return; } bool CacheManager::isCacheFileType(const std::string name) const { if (strncasecmp(name.c_str(), "http://", 7) == 0) { return true; } if (strncasecmp(name.c_str(), "ftp://", 6) == 0) { return true; } return false; } std::string CacheManager::getLocalName(const std::string name) const { std::string local = ""; if (strncasecmp(name.c_str(), "http://", 7) == 0) { local = getCacheDirName() + "http/"; local += partialEncoding(name.substr(7)); } else if (strncasecmp(name.c_str(), "ftp://", 6) == 0) { local = getCacheDirName() + "ftp/"; local += partialEncoding(name.substr(6)); } #ifdef _WIN32 std::replace(local.begin(), local.end(), '/', '\\'); #endif return local; } bool CacheManager::findURL(const std::string& url, CacheRecord& record) { int pos = findRecord(url); if (pos >= 0) { CacheRecord* rec = &records[pos]; rec->usedDate = time(NULL); // update the timestamp record = *rec; return true; } return false; } bool CacheManager::addFile(CacheRecord& record, const void* data) { if (((data == NULL) && (record.size != 0)) || (record.url.size() <= 0)) { return false; } record.name = getLocalName(record.url); std::ostream* out = FILEMGR.createDataOutStream(record.name); if (out == NULL) { return false; } bool replacement = false; CacheRecord* rec = &record; int pos = findRecord(record.url); if (pos >= 0) { records[pos] = record; rec = &records[pos]; replacement = true; } out->write((char*)data, rec->size); rec->usedDate = time(NULL); // update the timestamp MD5 md5; md5.update((unsigned char *)data, rec->size); md5.finalize(); rec->key = md5.hexdigest(); if (!replacement) { records.push_back(*rec); } delete out; return true; } int CacheManager::findRecord(const std::string& url) { for (unsigned int i = 0; i < records.size(); i++) { CacheRecord* rec = &(records[i]); if (url == rec->url) { return i; } } return -1; } bool CacheManager::loadIndex() { records.clear(); FILE* file = fopen(indexName.c_str(), "r"); if (file == NULL) { return false; } char buffer[1024]; while (fgets(buffer, 1024, file) != NULL) { removeNewlines(buffer); if ((buffer[0] == '\0') || (buffer[0] == '#')) { continue; } CacheRecord rec; rec.url = buffer; rec.name = getLocalName(rec.url); if (fgets(buffer, 1024, file) == NULL) { break; } else { removeNewlines(buffer); } std::string line = buffer; std::vector<std::string> tokens = TextUtils::tokenize(line, " "); if (tokens.size() != 4) { DEBUG1("loadCacheIndex (bad line): %s\n", buffer); continue; } rec.size = strtoul(tokens[0].c_str(), NULL, 10); rec.date = strtoul(tokens[1].c_str(), NULL, 10); rec.usedDate = strtoul(tokens[2].c_str(), NULL, 10); rec.key = tokens[3]; if (fileExists(rec.name)) { records.push_back(rec); } } fclose(file); return true; } bool CacheManager::saveIndex() { std::sort(records.begin(), records.end(), compareUsedDate); std::string tmpIndexName = indexName + ".tmp"; FILE* file = fopen(tmpIndexName.c_str(), "w"); if (file == NULL) { return false; } for (unsigned int i = 0; i < records.size(); i++) { const CacheRecord& rec = records[i]; fprintf(file, "%s\n%u %lu %lu %s\n\n", rec.url.c_str(), rec.size, rec.date, rec.usedDate, rec.key.c_str()); } fclose(file); return (rename(tmpIndexName.c_str(), indexName.c_str()) == 0); } void CacheManager::limitCacheSize() { int maxSize = BZDB.evalInt("maxCacheMB") * 1024 * 1024; if (maxSize < 0) { maxSize = 0; } int currentSize = 0; for (unsigned int i = 0; i < records.size(); i++) { currentSize += records[i].size; } std::sort(records.begin(), records.end(), compareUsedDate); while ((currentSize > maxSize) && (records.size() > 0)) { CacheManager::CacheRecord& rec = records.back(); currentSize -= rec.size; remove(rec.name.c_str()); removeDirs(rec.name); records.pop_back(); } return; } std::vector<CacheManager::CacheRecord> CacheManager::getCacheList() const { return records; } static bool fileExists (const std::string& name) { struct stat buf; #ifndef _WIN32 return (stat(name.c_str(), &buf) == 0); #else // Windows sucks yet again, if there is a trailing "\" // at the end of the filename, _stat will return -1. std::string dirname = name; while (dirname.find_last_of('\\') == (dirname.size() - 1)) { dirname.resize(dirname.size() - 1); } return (_stat(dirname.c_str(), (struct _stat *) &buf) == 0); #endif } static void removeDirs(const std::string& path) { unsigned int minLen = (unsigned int)getConfigDirName().size(); std::string tmp = path; while (tmp.size() > minLen) { #ifndef _WIN32 unsigned int i = (unsigned int)tmp.find_last_of('/'); #else unsigned int i = (unsigned int)tmp.find_last_of('\\'); #endif tmp = tmp.substr(0, i); if (remove(tmp.c_str()) != 0) { break; } } return; } static void removeNewlines(char* c) { while (*c != '\0') { if ((*c == '\n') || (*c == '\r')) { *c = '\0'; } c++; } return; } static std::string partialEncoding(const std::string& string) { // URL encoding removes the '/' and '.', which is // not acceptable. It is nice to have the directory // structure, and to be able to point and click your // way through it to view ".png"s. std::string tmp; char hex[5]; for (unsigned int i = 0; i < string.size(); i++) { const char c = string[i]; if (TextUtils::isWhitespace(c)) { tmp += "%20"; } else if ((c == '%') || (c == '*') || (c == '?') || (c == ':') || (c == '"') || (c == '\\')) { tmp += '%'; sprintf(hex, "%-2.2X", c); tmp += hex; } else { tmp += c; } } return tmp; } static bool compareUsedDate(const CacheManager::CacheRecord& a, const CacheManager::CacheRecord& b) { // oldest last return (a.usedDate > b.usedDate); } /* * Local Variables: *** * mode:C *** * tab-width: 8 *** * c-basic-offset: 2 *** * indent-tabs-mode: t *** * End: *** * ex: shiftwidth=2 tabstop=8 */
#include "ge/material_asset.hpp" #include "ge/shader_asset.hpp" #include "ge/texture_asset.hpp" namespace ge { struct reassign_from_json_visitor : boost::static_visitor<shader::parameter_type> { reassign_from_json_visitor(const nlohmann::json& js, asset_manager& asset_man_arg) : json_obj{js}, asset_man{asset_man_arg} { } const nlohmann::json& json_obj; asset_manager& asset_man; shader::parameter_type operator()(float) { return (float)json_obj; } shader::parameter_type operator()(glm::vec2) { return glm::vec2{json_obj[0], json_obj[1]}; } shader::parameter_type operator()(glm::vec3) { return glm::vec3{json_obj[0], json_obj[1], json_obj[2]}; } shader::parameter_type operator()(glm::vec4) { return glm::vec4{json_obj[0], json_obj[1], json_obj[2], json_obj[3]}; } shader::parameter_type operator()(std::shared_ptr<texture>&) { std::string asset_path = json_obj; return asset_man.get_asset<texture_asset>(asset_path.c_str()); } }; material material_asset::load_asset(asset_manager& manager, const char* asset_name, const char* filepath, const nlohmann::json& json_data) { std::string shader_asset_name = json_data["shader"]; auto shader_ass = manager.get_asset<shader_asset>(shader_asset_name.c_str()); auto ret = material(shader_ass); // load parameters auto parameter_iter = json_data.find("parameters"); if (parameter_iter != json_data.end() && parameter_iter->is_array()) { for (auto& parameter : *parameter_iter) { std::string parameter_name = parameter["name"]; // get the type from the shader auto paramater_iter = ret.m_shader->parameters.find(parameter_name); if (parameter_iter == ret.m_shader->parameters.end()) { throw std::runtime_error("Could not find property: " + parameter_name + " in shader while loading material asset: " + asset_name); } auto default_value = *parameter_iter; reassign_from_json_visitor vis{parameter["value"], manager}; try { ret.property_values[parameter_name] = default_value.apply_visitor(vis); } catch (std::exception& e) { std::cerr << "ERROR THROWN: " << e.what() << std::endl; } } } return ret; } } Fix material_asset issue #include "ge/material_asset.hpp" #include "ge/shader_asset.hpp" #include "ge/texture_asset.hpp" namespace ge { struct reassign_from_json_visitor : boost::static_visitor<shader::parameter_type> { reassign_from_json_visitor(const nlohmann::json& js, asset_manager& asset_man_arg) : json_obj{js}, asset_man{asset_man_arg} { } const nlohmann::json& json_obj; asset_manager& asset_man; shader::parameter_type operator()(float) { return (float)json_obj; } shader::parameter_type operator()(glm::vec2) { return glm::vec2{json_obj[0], json_obj[1]}; } shader::parameter_type operator()(glm::vec3) { return glm::vec3{json_obj[0], json_obj[1], json_obj[2]}; } shader::parameter_type operator()(glm::vec4) { return glm::vec4{json_obj[0], json_obj[1], json_obj[2], json_obj[3]}; } shader::parameter_type operator()(std::shared_ptr<texture>&) { std::string asset_path = json_obj; return asset_man.get_asset<texture_asset>(asset_path.c_str()); } }; material material_asset::load_asset(asset_manager& manager, const char* asset_name, const char* filepath, const nlohmann::json& json_data) { std::string shader_asset_name = json_data["shader"]; auto shader_ass = manager.get_asset<shader_asset>(shader_asset_name.c_str()); auto ret = material(shader_ass); // load parameters auto parameter_iter = json_data.find("parameters"); if (parameter_iter != json_data.end() && parameter_iter->is_array()) { for (auto& parameter : *parameter_iter) { std::string parameter_name = parameter["name"]; // get the type from the shader auto default_paramater_iter = ret.m_shader->parameters.find(parameter_name); if (default_paramater_iter == ret.m_shader->parameters.end()) { throw std::runtime_error("Could not find property: " + parameter_name + " in shader while loading material asset: " + asset_name); } auto default_value = default_paramater_iter->second.value; reassign_from_json_visitor vis{parameter["value"], manager}; try { ret.property_values[parameter_name] = default_value.apply_visitor(vis); } catch (std::exception& e) { std::cerr << "ERROR THROWN: " << e.what() << std::endl; } } } return ret; } }
#include "main.h" #include "User.h" #include "Nick.h" #include "Modules.h" #include "Chan.h" #include "znc.h" #include "HTTPSock.h" #include "Server.h" #include "Template.h" class CWebAdminMod; class CWebAdminSock : public CHTTPSock { public: CWebAdminSock(CWebAdminMod* pModule); CWebAdminSock(CWebAdminMod* pModule, const CString& sHostname, unsigned short uPort, int iTimeout = 60); virtual ~CWebAdminSock(); virtual bool OnPageRequest(const CString& sURI, CString& sPageRet); virtual bool OnLogin(const CString& sUser, const CString& sPass); void PrintPage(CString& sPageRet, const CString& sTmplName); void GetErrorPage(CString& sPageRet, const CString& sError) { m_Template["Title"] = "Error"; m_Template["Error"] = sError; PrintPage(sPageRet, "Error.tmpl"); } void ListUsersPage(CString& sPageRet); bool SettingsPage(CString& sPageRet); bool ChanPage(CString& sPageRet, CChan* = NULL); bool DelChan(CString& sPageRet); bool UserPage(CString& sPageRet, CUser* pUser = NULL); CUser* GetNewUser(CString& sPageRet, CUser* pUser); CString GetModArgs(const CString& sModName, bool bGlobal = false) { if (!bGlobal && !m_pUser) { return ""; } CModules& Modules = (bGlobal) ? CZNC::Get().GetModules() : m_pUser->GetModules(); for (unsigned int a = 0; a < Modules.size(); a++) { CModule* pModule = Modules[a]; if (pModule->GetModName() == sModName) { return pModule->GetArgs(); } } return ""; } virtual Csock* GetSockObj(const CString& sHost, unsigned short uPort); bool IsAdmin(bool bAllowUserAdmin = true) const { return m_bAdmin; } private: protected: CWebAdminMod* m_pModule; CUser* m_pUser; bool m_bAdmin; CTemplate m_Template; }; class CWebAdminMod : public CGlobalModule { public: CWebAdminMod(void *pDLL, const CString& sModName) : CGlobalModule(pDLL, sModName) { m_uPort = 8080; } virtual ~CWebAdminMod() { while (m_spSocks.size()) { // Loop through the sockets that we have created m_pManager->DelSockByAddr(*m_spSocks.begin()); // Delete each one which will call SockDestroyed() and erase it from the set } // This way we don't want to erase it ourselves, that's why we're using the funky while loop m_spSocks.clear(); } virtual bool OnBoot() { return true; } virtual bool OnLoad(const CString& sArgs) { bool bSSL = false; CString sPort = sArgs.Token(0); if (sPort.Left(1) == "+") { #ifdef HAVE_LIBSSL sPort.TrimLeft("+"); bSSL = true; #else return false; #endif } if (!sPort.empty()) { m_uPort = sPort.ToUInt(); } CWebAdminSock* pListenSock = new CWebAdminSock(this); #ifdef HAVE_LIBSSL if (bSSL) { pListenSock->SetPemLocation(CZNC::Get().GetPemLocation()); } #endif return m_pManager->ListenHost(m_uPort, "WebAdmin::Listener", CZNC::Get().GetListenHost(), bSSL, SOMAXCONN, pListenSock); } void AddSock(CWebAdminSock* pSock) { m_spSocks.insert(pSock); } void SockDestroyed(CWebAdminSock* pSock) { m_spSocks.erase(pSock); } private: unsigned int m_uPort; set<CWebAdminSock*> m_spSocks; }; void CWebAdminSock::PrintPage(CString& sPageRet, const CString& sTmplName) { sPageRet.clear(); CString sModPath = CZNC::Get().FindModPath(m_pModule->GetModName()); // @todo store the path to the module at load time and store it in a member var which can be used here while (!sModPath.empty() && sModPath.Right(1) != "/") { sModPath.RightChomp(); } // @todo possibly standardize the location of meta files such as these skins // @todo give an option for changing the current skin from 'default' if (!m_Template.SetFile(sModPath + "/" + m_pModule->GetModName() + "/skins/default/" + sTmplName)) { return; } stringstream oStr; m_Template.Print(oStr); sPageRet = oStr.str(); } bool CWebAdminSock::OnLogin(const CString& sUser, const CString& sPass) { CUser* pUser = CZNC::Get().FindUser(GetUser()); if (pUser) { CString sHost = GetRemoteIP(); if (pUser->IsHostAllowed(sHost) && pUser->CheckPass(GetPass())) { if (pUser->IsAdmin()) { m_bAdmin = true; } else { m_pUser = pUser; } return true; } } return false; } void CWebAdminSock::ListUsersPage(CString& sPageRet) { const map<CString,CUser*>& msUsers = CZNC::Get().GetUserMap(); m_Template["Title"] = "List Users"; unsigned int a = 0; for (map<CString,CUser*>::const_iterator it = msUsers.begin(); it != msUsers.end(); it++, a++) { CServer* pServer = it->second->GetCurrentServer(); CTemplate& l = m_Template.AddRow("UserLoop"); l["User"] = it->second->GetUserName(); if (pServer) { l["Server"] = pServer->GetName(); } } PrintPage(sPageRet, "ListUsers.tmpl"); } Csock* CWebAdminSock::GetSockObj(const CString& sHost, unsigned short uPort) { CWebAdminSock* pSock = new CWebAdminSock(m_pModule, sHost, uPort); pSock->SetSockName("WebAdmin::Client"); pSock->SetTimeout(120); m_pModule->AddSock(pSock); return pSock; } CWebAdminSock::CWebAdminSock(CWebAdminMod* pModule) : CHTTPSock() { m_pModule = pModule; m_pUser = NULL; m_bAdmin = false; m_pModule->AddSock(this); } CWebAdminSock::CWebAdminSock(CWebAdminMod* pModule, const CString& sHostname, unsigned short uPort, int iTimeout) : CHTTPSock(sHostname, uPort, iTimeout) { m_pModule = pModule; m_pUser = NULL; m_bAdmin = false; m_pModule->AddSock(this); } CWebAdminSock::~CWebAdminSock() { m_pModule->SockDestroyed(this); } bool CWebAdminSock::OnPageRequest(const CString& sURI, CString& sPageRet) { if (!ForceLogin()) { return false; } m_Template["User"] = GetUser(); m_Template["UserIP"] = GetRemoteIP(); if (IsAdmin()) { m_Template["IsAdmin"] = "true"; } if (sURI == "/") { if (!IsAdmin()) { Redirect("/edituser"); return false; } m_Template["Title"] = "Main Page"; PrintPage(sPageRet, "Main.tmpl"); } else if (sURI == "/settings") { if (!IsAdmin()) { return false; } if (!SettingsPage(sPageRet)) { return false; } } else if (sURI == "/adduser") { if (!IsAdmin()) { return false; } if (!UserPage(sPageRet)) { return false; } } else if (sURI == "/edituser") { if (!m_pUser) { m_pUser = CZNC::Get().FindUser(GetParam("user")); } if (m_pUser) { if (!UserPage(sPageRet, m_pUser)) { return false; } } else { GetErrorPage(sPageRet, "No such username"); } } else if (sURI == "/editchan") { if (!m_pUser) { m_pUser = CZNC::Get().FindUser(GetParam("user")); } if (!m_pUser) { GetErrorPage(sPageRet, "No such username"); return true; } CChan* pChan = m_pUser->FindChan(GetParam("chan")); if (!pChan) { GetErrorPage(sPageRet, "No such channel"); return true; } if (!ChanPage(sPageRet, pChan)) { return false; } } else if (sURI == "/addchan") { if (!m_pUser) { m_pUser = CZNC::Get().FindUser(GetParam("user")); } if (m_pUser) { if (!ChanPage(sPageRet)) { return false; } } else { GetErrorPage(sPageRet, "No such username"); } } else if (sURI == "/delchan") { if (!m_pUser) { m_pUser = CZNC::Get().FindUser(GetParam("user")); } if (m_pUser) { if (!DelChan(sPageRet)) { return false; } } else { GetErrorPage(sPageRet, "No such username"); } } else if (sURI == "/favicon.ico") { CString sIcon = "AAABAAIAICAAAAAAAACoCAAAJgAAABAQAAAAAAAAaAUAAM4IAAAoAAAAIAAAAEAAAAABAAgAAAAAAAAEAAAAAAAAAAAAAAABAAAAAQAAAAAAAAAAgAAAgAAAAICAAIAAAACAAIAAgIAAAMDA" "wADA3MAA8MqmAAQEBAAICAgADAwMABEREQAWFhYAHBwcACIiIgApKSkAVVVVAE1NTQBCQkIAOTk5AIB8/wBQUP8AkwDWAP/szADG1u8A1ufnAJCprQAAADMAAABmAAAAmQAAAMwAADMAAAAz" "MwAAM2YAADOZAAAzzAAAM/8AAGYAAABmMwAAZmYAAGaZAABmzAAAZv8AAJkAAACZMwAAmWYAAJmZAACZzAAAmf8AAMwAAADMMwAAzGYAAMyZAADMzAAAzP8AAP9mAAD/mQAA/8wAMwAAADMA" "MwAzAGYAMwCZADMAzAAzAP8AMzMAADMzMwAzM2YAMzOZADMzzAAzM/8AM2YAADNmMwAzZmYAM2aZADNmzAAzZv8AM5kAADOZMwAzmWYAM5mZADOZzAAzmf8AM8wAADPMMwAzzGYAM8yZADPM" "zAAzzP8AM/8zADP/ZgAz/5kAM//MADP//wBmAAAAZgAzAGYAZgBmAJkAZgDMAGYA/wBmMwAAZjMzAGYzZgBmM5kAZjPMAGYz/wBmZgAAZmYzAGZmZgBmZpkAZmbMAGaZAABmmTMAZplmAGaZ" "mQBmmcwAZpn/AGbMAABmzDMAZsyZAGbMzABmzP8AZv8AAGb/MwBm/5kAZv/MAMwA/wD/AMwAmZkAAJkzmQCZAJkAmQDMAJkAAACZMzMAmQBmAJkzzACZAP8AmWYAAJlmMwCZM2YAmWaZAJlm" "zACZM/8AmZkzAJmZZgCZmZkAmZnMAJmZ/wCZzAAAmcwzAGbMZgCZzJkAmczMAJnM/wCZ/wAAmf8zAJnMZgCZ/5kAmf/MAJn//wDMAAAAmQAzAMwAZgDMAJkAzADMAJkzAADMMzMAzDNmAMwz" "mQDMM8wAzDP/AMxmAADMZjMAmWZmAMxmmQDMZswAmWb/AMyZAADMmTMAzJlmAMyZmQDMmcwAzJn/AMzMAADMzDMAzMxmAMzMmQDMzMwAzMz/AMz/AADM/zMAmf9mAMz/mQDM/8wAzP//AMwA" "MwD/AGYA/wCZAMwzAAD/MzMA/zNmAP8zmQD/M8wA/zP/AP9mAAD/ZjMAzGZmAP9mmQD/ZswAzGb/AP+ZAAD/mTMA/5lmAP+ZmQD/mcwA/5n/AP/MAAD/zDMA/8xmAP/MmQD/zMwA/8z/AP//" "MwDM/2YA//+ZAP//zABmZv8AZv9mAGb//wD/ZmYA/2b/AP//ZgAhAKUAX19fAHd3dwCGhoYAlpaWAMvLywCysrIA19fXAN3d3QDj4+MA6urqAPHx8QD4+PgA8Pv/AKSgoACAgIAAAAD/AAD/" "AAAA//8A/wAAAP8A/wD//wAA////AP///////////////////////////////////////////////////////////////////////////////////////////wAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAD///////////8AeXl5eXl5eXl5eXl5eXl5eXl5eXl5eQD/////////AHkKCgoKCgoKCgoKCgoKCgoKCgoKCgoKeQD//////wB5CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKeQD/////" "AHkKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgp5AP////8AeQoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCnkA//////8AeQoKCgoKCgoKCgoKCgoKCgoKCgoKCgp5AP////////8AeQoKCgoKCgp5" "eXl5eXl5eXl5eXl5eQD///////////8AeQoKCgoKCgp5AAAAAAAAAAAAAAAA//////////////8AeQoKCgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP//////////" "//////////////////8AeQoKCgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP//////////////////////" "//////8AeQoKCgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP////////////////////////////8AeQoK" "CgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP//////////////AAAAAAAAAAAAAAAAeQoKCgoKCgp5AP///////////wB5eXl5eXl5eXl5eXl5eQoKCgoKCgp5AP//" "//////8AeQoKCgoKCgoKCgoKCgoKCgoKCgoKCgp5AP//////AHkKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgp5AP////8AeQoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCnkA/////wB5CgoKCgoK" "CgoKCgoKCgoKCgoKCgoKCgoKeQD//////wB5CgoKCgoKCgoKCgoKCgoKCgoKCgoKCnkA/////////wB5eXl5eXl5eXl5eXl5eXl5eXl5eXl5AP///////////wAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAD///////////////////////////////////////////////////////////////////////////////////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAQAAAAIAAAAAEA" "CAAAAAAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYWFgAcHBwAIiIiACkpKQBVVVUATU1NAEJC" "QgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAAMwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm/wAAmQAAAJkzAACZ" "ZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNm" "ZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM/wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYz" "AABmMzMAZjNmAGYzmQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbMMwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8A" "zACZmQAAmTOZAJkAmQCZAMwAmQAAAJkzMwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnMAACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/" "AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwAmQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZMwDMmWYAzJmZAMyZ" "zADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9m" "zADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaG" "hgCWlpYAy8vLALKysgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP//AAD///8ADw8PDw8PDw8PDw8PDw8PDw95eXl5eXl5eXl5eXl5" "eQ8PeQoKCgoKCgoKCgoKCnkPD3kKCgoKCgoKCgoKCgp5Dw95CgoKCgoKCgoKCgoKeQ8AD3kKCgoKCnl5eXl5eXkPAAAPeQoKCgoKeQ8PDw8PDwAAAA95CgoKCgp5DwAAAAAAAAAAD3kKCgoK" "CnkPAAAAAAAADw8PeQoKCgoKeQ8AAA95eXl5eXl5CgoKCgp5DwAPeQoKCgoKCgoKCgoKCnkPD3kKCgoKCgoKCgoKCgp5Dw95CgoKCgoKCgoKCgoKeQ8PeXl5eXl5eXl5eXl5eXkPDw8PDw8P" "Dw8PDw8PDw8PDwAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAMAAAADgDwAA8AcAAAADAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="; SetContentType("image/x-icon"); sIcon.Base64Decode(sPageRet); return true; } else if (sURI == "/listusers") { if (!IsAdmin()) { return false; } ListUsersPage(sPageRet); } else if (sURI == "/deluser") { if (!IsAdmin()) { return false; } if (CZNC::Get().DeleteUser(GetParam("user"))) { Redirect("/listusers"); return false; } else { GetErrorPage(sPageRet, "No such username"); } } else { return false; } return true; } bool CWebAdminSock::SettingsPage(CString& sPageRet) { if (!GetParam("submitted").ToUInt()) { CString sVHosts, sMotd; m_Template["Title"] = "Settings"; m_Template["StatusPrefix"] = CZNC::Get().GetStatusPrefix(); m_Template["ISpoofFile"] = CZNC::Get().GetISpoofFile(); m_Template["ISpoofFormat"] = CZNC::Get().GetISpoofFormat(); const VCString& vsVHosts = CZNC::Get().GetVHosts(); for (unsigned int a = 0; a < vsVHosts.size(); a++) { CTemplate& l = m_Template.AddRow("VHostLoop"); l["VHost"] = vsVHosts[a]; } const VCString& vsMotd = CZNC::Get().GetMotd(); for (unsigned int b = 0; b < vsMotd.size(); b++) { CTemplate& l = m_Template.AddRow("MOTDLoop"); l["Line"] = vsMotd[b]; } set<CModInfo> ssGlobalMods; CZNC::Get().GetModules().GetAvailableMods(ssGlobalMods, true); for (set<CModInfo>::iterator it = ssGlobalMods.begin(); it != ssGlobalMods.end(); it++) { const CModInfo& Info = *it; CTemplate& l = m_Template.AddRow("ModuleLoop"); if (CZNC::Get().GetModules().FindModule(Info.GetName())) { l["Checked"] = "true"; } if (Info.GetName() == m_pModule->GetModName()) { l["Disabled"] = "true"; } l["Name"] = Info.GetName(); l["Description"] = Info.GetDescription(); l["Args"] = GetModArgs(Info.GetName(), true); } PrintPage(sPageRet, "Settings.tmpl"); return true; } CString sArg; sArg = GetParam("statusprefix"); CZNC::Get().SetStatusPrefix(sArg); sArg = GetParam("ispooffile"); CZNC::Get().SetISpoofFile(sArg); sArg = GetParam("ispoofformat"); CZNC::Get().SetISpoofFormat(sArg); //sArg = GetParam(""); if (!sArg.empty()) { CZNC::Get().Set(sArg); } VCString vsArgs; GetParam("motd").Split("\n", vsArgs); CZNC::Get().ClearMotd(); unsigned int a = 0; for (a = 0; a < vsArgs.size(); a++) { CZNC::Get().AddMotd(vsArgs[a].TrimRight_n()); } GetParam("vhosts").Split("\n", vsArgs); CZNC::Get().ClearVHosts(); for (a = 0; a < vsArgs.size(); a++) { CZNC::Get().AddVHost(vsArgs[a].Trim_n()); } set<CString> ssArgs; GetParamValues("loadmod", ssArgs); for (set<CString>::iterator it = ssArgs.begin(); it != ssArgs.end(); it++) { CString sModRet; CString sModName = (*it).TrimRight_n("\r"); if (!sModName.empty()) { CString sArgs = GetParam("modargs_" + sModName); try { if (!CZNC::Get().GetModules().FindModule(sModName)) { if (!CZNC::Get().GetModules().LoadModule(sModName, sArgs, NULL, sModRet)) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] [" << sModRet << "]" << endl); } } else { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] because it is already loaded" << endl); } } catch(...) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] [" << sArgs << "]" << endl); } } } const CModules& vCurMods = CZNC::Get().GetModules(); set<CString> ssUnloadMods; for (a = 0; a < vCurMods.size(); a++) { CModule* pCurMod = vCurMods[a]; if (ssArgs.find(pCurMod->GetModName()) == ssArgs.end() && pCurMod->GetModName() != m_pModule->GetModName()) { ssUnloadMods.insert(pCurMod->GetModName()); } } for (set<CString>::iterator it2 = ssUnloadMods.begin(); it2 != ssUnloadMods.end(); it2++) { CZNC::Get().GetModules().UnloadModule(*it2); } if (!CZNC::Get().WriteConfig()) { GetErrorPage(sPageRet, "Settings changed, but config was not written"); return true; } Redirect("/"); return false; } bool CWebAdminSock::ChanPage(CString& sPageRet, CChan* pChan) { if (!m_pUser) { GetErrorPage(sPageRet, "That user doesn't exist"); } if (!GetParam("submitted").ToUInt()) { if (pChan) { m_Template["Edit"] = "true"; m_Template["Title"] = "Edit Channel" + CString(" [" + pChan->GetName() + "]"); m_Template["ChanName"] = pChan->GetName(); m_Template["BufferCount"] = CString::ToString(pChan->GetBufferCount()); m_Template["DefModes"] = pChan->GetDefaultModes(); if (pChan->InConfig()) { m_Template["InConfig"] = "true"; } } else { m_Template["Title"] = "Add Channel" + CString(" for User [" + m_pUser->GetUserName() + "]"); m_Template["BufferCount"] = "50"; m_Template["DefModes"] = "+stn"; m_Template["InConfig"] = "true"; } CTemplate& o1 = m_Template.AddRow("OptionLoop"); o1["Name"] = "autocycle"; o1["DisplayName"] = "Auto Cycle"; if (!pChan || pChan->AutoCycle()) { o1["Checked"] = "true"; } CTemplate& o2 = m_Template.AddRow("OptionLoop"); o2["Name"] = "keepbuffer"; o2["DisplayName"] = "Keep Buffer"; if (!pChan || pChan->KeepBuffer()) { o2["Checked"] = "true"; } CTemplate& o3 = m_Template.AddRow("OptionLoop"); o3["Name"] = "detached"; o3["DisplayName"] = "Detached"; if (pChan && pChan->IsDetached()) { o3["Checked"] = "true"; } PrintPage(sPageRet, "Channel.tmpl"); return true; } CString sChanName = GetParam("name").Trim_n(); if (!pChan) { if (sChanName.empty()) { GetErrorPage(sPageRet, "Channel name is a required argument"); return true; } if (m_pUser->FindChan(sChanName.Token(0))) { GetErrorPage(sPageRet, "Channel [" + sChanName.Token(0) + "] already exists"); return true; } pChan = new CChan(sChanName, m_pUser, true); m_pUser->AddChan(pChan); } pChan->SetDefaultModes(GetParam("defmodes")); pChan->SetBufferCount(GetParam("buffercount").ToUInt()); pChan->SetInConfig(GetParam("save").ToBool()); pChan->SetAutoCycle(GetParam("autocycle").ToBool()); pChan->SetKeepBuffer(GetParam("keepbuffer").ToBool()); bool bDetached = GetParam("detached").ToBool(); if (pChan->IsDetached() != bDetached) { if (bDetached) { pChan->DetachUser(); } else { pChan->AttachUser(); } } m_pUser->JoinChans(); if (!CZNC::Get().WriteConfig()) { GetErrorPage(sPageRet, "Channel added/modified, but config was not written"); return true; } Redirect("/edituser?user=" + m_pUser->GetUserName().Escape_n(CString::EURL)); return false; } bool CWebAdminSock::DelChan(CString& sPageRet) { CString sChan = GetParam("chan"); if (!m_pUser) { GetErrorPage(sPageRet, "That user doesn't exist"); return true; } if (sChan.empty()) { GetErrorPage(sPageRet, "That channel doesn't exist for this user"); return true; } m_pUser->DelChan(sChan); m_pUser->PutIRC("PART " + sChan); if (!CZNC::Get().WriteConfig()) { GetErrorPage(sPageRet, "Channel deleted, but config was not written"); return true; } Redirect("/edituser?user=" + m_pUser->GetUserName().Escape_n(CString::EURL)); return false; } bool CWebAdminSock::UserPage(CString& sPageRet, CUser* pUser) { if (!GetParam("submitted").ToUInt()) { CString sAllowedHosts, sServers, sChans, sCTCPReplies; if (pUser) { m_Template["Title"] = "Edit User [" + pUser->GetUserName() + "]"; m_Template["Edit"] = "true"; m_Template["Username"] = pUser->GetUserName(); m_Template["Nick"] = pUser->GetNick(); m_Template["AltNick"] = pUser->GetAltNick(); m_Template["AwaySuffix"] = pUser->GetAwaySuffix(); m_Template["StatusPrefix"] = pUser->GetStatusPrefix(); m_Template["Ident"] = pUser->GetIdent(); m_Template["RealName"] = pUser->GetRealName(); m_Template["QuitMsg"] = pUser->GetQuitMsg(); m_Template["DefaultChanModes"] = pUser->GetDefaultChanModes(); m_Template["BufferCount"] = CString::ToString(pUser->GetBufferCount()); const set<CString>& ssAllowedHosts = pUser->GetAllowedHosts(); for (set<CString>::const_iterator it = ssAllowedHosts.begin(); it != ssAllowedHosts.end(); it++) { CTemplate& l = m_Template.AddRow("AllowedHostLoop"); l["Host"] = *it; } const vector<CServer*>& vServers = pUser->GetServers(); for (unsigned int a = 0; a < vServers.size(); a++) { CTemplate& l = m_Template.AddRow("ServerLoop"); l["Server"] = vServers[a]->GetString(); } const MCString& msCTCPReplies = pUser->GetCTCPReplies(); for (MCString::const_iterator it2 = msCTCPReplies.begin(); it2 != msCTCPReplies.end(); it2++) { CTemplate& l = m_Template.AddRow("CTCPLoop"); l["CTCP"] = it2->first + " " + it2->second; } if (pUser == CZNC::Get().FindUser(GetUser())) { CString sIP = GetRemoteIP(); if (!sIP.empty()) { m_Template["OwnIP"] = sIP.Token(0, false, ".") + "." + sIP.Token(1, false, ".") + "." + sIP.Token(2, false, ".") + ".*"; } } const VCString& vsVHosts = CZNC::Get().GetVHosts(); for (unsigned int b = 0; b < vsVHosts.size(); b++) { const CString& sVHost = vsVHosts[b]; CTemplate& l = m_Template.AddRow("VHostLoop"); l["VHost"] = sVHost; if (pUser && pUser->GetVHost() == sVHost) { l["Checked"] = "true"; } } const vector<CChan*>& Channels = pUser->GetChans(); for (unsigned int c = 0; c < Channels.size(); c++) { CChan* pChan = Channels[c]; CTemplate& l = m_Template.AddRow("ChannelLoop"); l["Username"] = pUser->GetUserName(); l["Name"] = pChan->GetName(); l["Perms"] = pChan->GetPermStr(); l["CurModes"] = pChan->GetModeString(); l["DefModes"] = pChan->GetDefaultModes(); l["BufferCount"] = CString::ToString(pChan->GetBufferCount()); l["Options"] = pChan->GetOptions(); if (pChan->InConfig()) { l["InConfig"] = "true"; } } } else { m_Template["Title"] = "Add User"; m_Template["AwaySuffix"] = "*"; } set<CModInfo> ssUserMods; CZNC::Get().GetModules().GetAvailableMods(ssUserMods); for (set<CModInfo>::iterator it = ssUserMods.begin(); it != ssUserMods.end(); it++) { const CModInfo& Info = *it; CTemplate& l = m_Template.AddRow("ModuleLoop"); l["Name"] = Info.GetName(); l["Description"] = Info.GetDescription(); l["Args"] = GetModArgs(Info.GetName()); if (pUser && pUser->GetModules().FindModule(Info.GetName())) { l["Checked"] = "true"; } if (!IsAdmin() && pUser && pUser->DenyLoadMod()) { l["Disabled"] = "true"; } } CTemplate& o1 = m_Template.AddRow("OptionLoop"); o1["Name"] = "keepbuffer"; o1["DisplayName"] = "Keep Buffer"; if (!pUser || pUser->KeepBuffer()) { o1["Checked"] = "true"; } CTemplate& o2 = m_Template.AddRow("OptionLoop"); o2["Name"] = "autocycle"; o2["DisplayName"] = "Auto Cycle"; if (!pUser || pUser->AutoCycle()) { o2["Checked"] = "true"; } CTemplate& o3 = m_Template.AddRow("OptionLoop"); o3["Name"] = "keepnick"; o3["DisplayName"] = "Keep Nick"; if (!pUser || pUser->GetKeepNick()) { o3["Checked"] = "true"; } CTemplate& o4 = m_Template.AddRow("OptionLoop"); o4["Name"] = "multiclients"; o4["DisplayName"] = "Multi Clients"; if (!pUser || pUser->MultiClients()) { o4["Checked"] = "true"; } CTemplate& o5 = m_Template.AddRow("OptionLoop"); o5["Name"] = "bouncedccs"; o5["DisplayName"] = "Bounce DCCs"; if (!pUser || pUser->BounceDCCs()) { o5["Checked"] = "true"; } CTemplate& o6 = m_Template.AddRow("OptionLoop"); o6["Name"] = "useclientip"; o6["DisplayName"] = "Use Client IP"; if (pUser && pUser->UseClientIP()) { o6["Checked"] = "true"; } if (IsAdmin()) { CTemplate& o7 = m_Template.AddRow("OptionLoop"); o7["Name"] = "denyloadmod"; o7["DisplayName"] = "Deny LoadMod"; if (pUser && pUser->DenyLoadMod()) { o7["Checked"] = "true"; } CTemplate& o8 = m_Template.AddRow("OptionLoop"); o8["Name"] = "isadmin"; o8["DisplayName"] = "Admin"; if (pUser && pUser->IsAdmin()) { o8["Checked"] = "true"; } if (pUser && pUser == CZNC::Get().FindUser(GetUser())) { o8["Disabled"] = "true"; } } PrintPage(sPageRet, "UserPage.tmpl"); return true; } CString sUsername = GetParam("user"); if (!pUser && CZNC::Get().FindUser(sUsername)) { GetErrorPage(sPageRet, "Invalid Submission [User " + sUsername + " already exists]"); return true; } CUser* pNewUser = GetNewUser(sPageRet, pUser); if (!pNewUser) { return true; } CString sErr; if (!pUser) { // Add User Submission if (!pNewUser->IsValid(sErr)) { delete pNewUser; GetErrorPage(sPageRet, "Invalid submission [" + sErr + "]"); return true; } CZNC::Get().AddUser(pNewUser); if (!CZNC::Get().WriteConfig()) { GetErrorPage(sPageRet, "User added, but config was not written"); return true; } } else { // Edit User Submission if (!pUser->Clone(*pNewUser, sErr)) { delete pNewUser; GetErrorPage(sPageRet, "Invalid Submission [" + sErr + "]"); return true; } delete pNewUser; if (!CZNC::Get().WriteConfig()) { GetErrorPage(sPageRet, "User edited, but config was not written"); return true; } } if (!IsAdmin()) { Redirect("/edituser"); } else { Redirect("/listusers"); } return false; } CUser* CWebAdminSock::GetNewUser(CString& sPageRet, CUser* pUser) { CString sUsername = GetParam("newuser"); if (sUsername.empty()) { sUsername = GetParam("user"); } if (sUsername.empty()) { GetErrorPage(sPageRet, "Invalid Submission [Username is required]"); return NULL; } CString sArg = GetParam("password"); if (sArg != GetParam("password2")) { GetErrorPage(sPageRet, "Invalid Submission [Passwords do not match]"); return NULL; } CUser* pNewUser = new CUser(sUsername); if (!sArg.empty()) { pNewUser->SetPass(sArg.MD5(), true); } VCString vsArgs; GetParam("servers").Split("\n", vsArgs); unsigned int a = 0; for (a = 0; a < vsArgs.size(); a++) { pNewUser->AddServer(vsArgs[a].Trim_n()); } GetParam("allowedips").Split("\n", vsArgs); if (vsArgs.size()) { for (a = 0; a < vsArgs.size(); a++) { pNewUser->AddAllowedHost(vsArgs[a].Trim_n()); } } else { pNewUser->AddAllowedHost("*"); } if (HasParam("ownip")) { pNewUser->AddAllowedHost(GetParam("ownip")); } GetParam("ctcpreplies").Split("\n", vsArgs); for (a = 0; a < vsArgs.size(); a++) { CString sReply = vsArgs[a].TrimRight_n("\r"); pNewUser->AddCTCPReply(sReply.Token(0).Trim_n(), sReply.Token(1, true).Trim_n()); } if (IsAdmin() || (pUser && !pUser->DenyLoadMod())) { GetParamValues("loadmod", vsArgs); for (a = 0; a < vsArgs.size(); a++) { CString sModRet; CString sModName = vsArgs[a].TrimRight_n("\r"); if (!sModName.empty()) { CString sArgs = GetParam("modargs_" + sModName); try { if (!pNewUser->GetModules().LoadModule(sModName, sArgs, pNewUser, sModRet, (pUser != NULL))) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] [" << sModRet << "]" << endl); } } catch (...) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] [" << sArgs << "]" << endl); } } } } else if (pUser) { CModules& Modules = pUser->GetModules(); for (a = 0; a < Modules.size(); a++) { CString sModName = Modules[a]->GetModName(); CString sArgs = Modules[a]->GetArgs(); CString sModRet; try { if (!pNewUser->GetModules().LoadModule(sModName, sArgs, pNewUser, sModRet, (pUser != NULL))) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] [" << sModRet << "]" << endl); } } catch (...) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "]" << endl); } } } sArg = GetParam("nick"); if (!sArg.empty()) { pNewUser->SetNick(sArg); } sArg = GetParam("altnick"); if (!sArg.empty()) { pNewUser->SetAltNick(sArg); } sArg = GetParam("awaysuffix"); if (!sArg.empty()) { pNewUser->SetAwaySuffix(sArg); } sArg = GetParam("statusprefix"); if (!sArg.empty()) { pNewUser->SetStatusPrefix(sArg); } sArg = GetParam("ident"); if (!sArg.empty()) { pNewUser->SetIdent(sArg); } sArg = GetParam("realname"); if (!sArg.empty()) { pNewUser->SetRealName(sArg); } sArg = GetParam("vhost"); if (!sArg.empty()) { pNewUser->SetVHost(sArg); } sArg = GetParam("quitmsg"); if (!sArg.empty()) { pNewUser->SetQuitMsg(sArg); } sArg = GetParam("chanmodes"); if (!sArg.empty()) { pNewUser->SetDefaultChanModes(sArg); } pNewUser->SetBufferCount(GetParam("bufsize").ToUInt()); pNewUser->SetKeepBuffer(GetParam("keepbuffer").ToBool()); pNewUser->SetMultiClients(GetParam("multiclients").ToBool()); pNewUser->SetBounceDCCs(GetParam("bouncedccs").ToBool()); pNewUser->SetAutoCycle(GetParam("autocycle").ToBool()); pNewUser->SetKeepNick(GetParam("keepnick").ToBool()); pNewUser->SetUseClientIP(GetParam("useclientip").ToBool()); if (IsAdmin()) { pNewUser->SetDenyLoadMod(GetParam("denyloadmod").ToBool()); } else if (pUser) { pNewUser->SetDenyLoadMod(pUser->DenyLoadMod()); } if (pUser && pUser != CZNC::Get().FindUser(GetUser())) { pNewUser->SetAdmin(GetParam("isadmin").ToBool()); } else if (pUser) { pNewUser->SetAdmin(pUser->IsAdmin()); } GetParamValues("channel", vsArgs); for (a = 0; a < vsArgs.size(); a++) { const CString& sChan = vsArgs[a]; pNewUser->AddChan(sChan.TrimRight_n("\r"), GetParam("save_" + sChan).ToBool()); } return pNewUser; } GLOBALMODULEDEFS(CWebAdminMod, "Dynamic configuration of users/settings through a web browser") Added support for css files git-svn-id: 3ad904ec35b89a071badd9cb0113dfe58093e920@611 726aef4b-f618-498e-8847-2d620e286838 #include "main.h" #include "User.h" #include "Nick.h" #include "Modules.h" #include "Chan.h" #include "znc.h" #include "HTTPSock.h" #include "Server.h" #include "Template.h" class CWebAdminMod; class CWebAdminSock : public CHTTPSock { public: CWebAdminSock(CWebAdminMod* pModule); CWebAdminSock(CWebAdminMod* pModule, const CString& sHostname, unsigned short uPort, int iTimeout = 60); virtual ~CWebAdminSock(); virtual bool OnPageRequest(const CString& sURI, CString& sPageRet); virtual bool OnLogin(const CString& sUser, const CString& sPass); CString GetSkinDir(); void PrintPage(CString& sPageRet, const CString& sTmplName); void GetErrorPage(CString& sPageRet, const CString& sError) { m_Template["Title"] = "Error"; m_Template["Error"] = sError; PrintPage(sPageRet, "Error.tmpl"); } void ListUsersPage(CString& sPageRet); bool SettingsPage(CString& sPageRet); bool ChanPage(CString& sPageRet, CChan* = NULL); bool DelChan(CString& sPageRet); bool UserPage(CString& sPageRet, CUser* pUser = NULL); CUser* GetNewUser(CString& sPageRet, CUser* pUser); CString GetModArgs(const CString& sModName, bool bGlobal = false) { if (!bGlobal && !m_pUser) { return ""; } CModules& Modules = (bGlobal) ? CZNC::Get().GetModules() : m_pUser->GetModules(); for (unsigned int a = 0; a < Modules.size(); a++) { CModule* pModule = Modules[a]; if (pModule->GetModName() == sModName) { return pModule->GetArgs(); } } return ""; } virtual Csock* GetSockObj(const CString& sHost, unsigned short uPort); bool IsAdmin(bool bAllowUserAdmin = true) const { return m_bAdmin; } private: protected: CWebAdminMod* m_pModule; CUser* m_pUser; bool m_bAdmin; CTemplate m_Template; }; class CWebAdminMod : public CGlobalModule { public: CWebAdminMod(void *pDLL, const CString& sModName) : CGlobalModule(pDLL, sModName) { m_uPort = 8080; } virtual ~CWebAdminMod() { while (m_spSocks.size()) { // Loop through the sockets that we have created m_pManager->DelSockByAddr(*m_spSocks.begin()); // Delete each one which will call SockDestroyed() and erase it from the set } // This way we don't want to erase it ourselves, that's why we're using the funky while loop m_spSocks.clear(); } virtual bool OnBoot() { return true; } virtual bool OnLoad(const CString& sArgs) { bool bSSL = false; CString sPort = sArgs.Token(0); if (sPort.Left(1) == "+") { #ifdef HAVE_LIBSSL sPort.TrimLeft("+"); bSSL = true; #else return false; #endif } if (!sPort.empty()) { m_uPort = sPort.ToUInt(); } CWebAdminSock* pListenSock = new CWebAdminSock(this); #ifdef HAVE_LIBSSL if (bSSL) { pListenSock->SetPemLocation(CZNC::Get().GetPemLocation()); } #endif return m_pManager->ListenHost(m_uPort, "WebAdmin::Listener", CZNC::Get().GetListenHost(), bSSL, SOMAXCONN, pListenSock); } void AddSock(CWebAdminSock* pSock) { m_spSocks.insert(pSock); } void SockDestroyed(CWebAdminSock* pSock) { m_spSocks.erase(pSock); } private: unsigned int m_uPort; set<CWebAdminSock*> m_spSocks; }; CString CWebAdminSock::GetSkinDir() { CString sModPath = CZNC::Get().FindModPath(m_pModule->GetModName()); // @todo store the path to the module at load time and store it in a member var which can be used here while (!sModPath.empty() && sModPath.Right(1) != "/") { sModPath.RightChomp(); } return sModPath + "/" + m_pModule->GetModName() + "/skins/default/"; } void CWebAdminSock::PrintPage(CString& sPageRet, const CString& sTmplName) { sPageRet.clear(); // @todo possibly standardize the location of meta files such as these skins // @todo give an option for changing the current skin from 'default' if (!m_Template.SetFile(GetSkinDir() + sTmplName)) { return; } stringstream oStr; m_Template.Print(oStr); sPageRet = oStr.str(); } bool CWebAdminSock::OnLogin(const CString& sUser, const CString& sPass) { CUser* pUser = CZNC::Get().FindUser(GetUser()); if (pUser) { CString sHost = GetRemoteIP(); if (pUser->IsHostAllowed(sHost) && pUser->CheckPass(GetPass())) { if (pUser->IsAdmin()) { m_bAdmin = true; } else { m_pUser = pUser; } return true; } } return false; } void CWebAdminSock::ListUsersPage(CString& sPageRet) { const map<CString,CUser*>& msUsers = CZNC::Get().GetUserMap(); m_Template["Title"] = "List Users"; unsigned int a = 0; for (map<CString,CUser*>::const_iterator it = msUsers.begin(); it != msUsers.end(); it++, a++) { CServer* pServer = it->second->GetCurrentServer(); CTemplate& l = m_Template.AddRow("UserLoop"); l["Username"] = it->second->GetUserName(); if (pServer) { l["Server"] = pServer->GetName(); } } PrintPage(sPageRet, "ListUsers.tmpl"); } Csock* CWebAdminSock::GetSockObj(const CString& sHost, unsigned short uPort) { CWebAdminSock* pSock = new CWebAdminSock(m_pModule, sHost, uPort); pSock->SetSockName("WebAdmin::Client"); pSock->SetTimeout(120); m_pModule->AddSock(pSock); return pSock; } CWebAdminSock::CWebAdminSock(CWebAdminMod* pModule) : CHTTPSock() { m_pModule = pModule; m_pUser = NULL; m_bAdmin = false; m_pModule->AddSock(this); SetDocRoot(GetSkinDir()); } CWebAdminSock::CWebAdminSock(CWebAdminMod* pModule, const CString& sHostname, unsigned short uPort, int iTimeout) : CHTTPSock(sHostname, uPort, iTimeout) { m_pModule = pModule; m_pUser = NULL; m_bAdmin = false; m_pModule->AddSock(this); SetDocRoot(GetSkinDir()); } CWebAdminSock::~CWebAdminSock() { m_pModule->SockDestroyed(this); } bool CWebAdminSock::OnPageRequest(const CString& sURI, CString& sPageRet) { /*if (!ForceLogin()) { return false; }*/ m_Template["SessionUser"] = GetUser(); m_Template["SessionIP"] = GetRemoteIP(); m_Template["Tag"] = CZNC::GetTag(); if (IsAdmin()) { m_Template["IsAdmin"] = "true"; } if (sURI == "/") { if (!IsAdmin()) { Redirect("/edituser"); return false; } m_Template["Title"] = "Main Page"; PrintPage(sPageRet, "Main.tmpl"); } else if (sURI.Left(5).CaseCmp("/css/") == 0) { PrintFile(GetSkinDir() + sURI, "text/css"); return false; } else if (sURI == "/settings") { if (!IsAdmin()) { return false; } if (!SettingsPage(sPageRet)) { return false; } } else if (sURI == "/adduser") { if (!IsAdmin()) { return false; } if (!UserPage(sPageRet)) { return false; } } else if (sURI == "/edituser") { if (!m_pUser) { m_pUser = CZNC::Get().FindUser(GetParam("user")); } if (m_pUser) { if (!UserPage(sPageRet, m_pUser)) { return false; } } else { GetErrorPage(sPageRet, "No such username"); } } else if (sURI == "/editchan") { if (!m_pUser) { m_pUser = CZNC::Get().FindUser(GetParam("user")); } if (!m_pUser) { GetErrorPage(sPageRet, "No such username"); return true; } CChan* pChan = m_pUser->FindChan(GetParam("chan")); if (!pChan) { GetErrorPage(sPageRet, "No such channel"); return true; } if (!ChanPage(sPageRet, pChan)) { return false; } } else if (sURI == "/addchan") { if (!m_pUser) { m_pUser = CZNC::Get().FindUser(GetParam("user")); } if (m_pUser) { if (!ChanPage(sPageRet)) { return false; } } else { GetErrorPage(sPageRet, "No such username"); } } else if (sURI == "/delchan") { if (!m_pUser) { m_pUser = CZNC::Get().FindUser(GetParam("user")); } if (m_pUser) { if (!DelChan(sPageRet)) { return false; } } else { GetErrorPage(sPageRet, "No such username"); } } else if (sURI == "/favicon.ico") { CString sIcon = "AAABAAIAICAAAAAAAACoCAAAJgAAABAQAAAAAAAAaAUAAM4IAAAoAAAAIAAAAEAAAAABAAgAAAAAAAAEAAAAAAAAAAAAAAABAAAAAQAAAAAAAAAAgAAAgAAAAICAAIAAAACAAIAAgIAAAMDA" "wADA3MAA8MqmAAQEBAAICAgADAwMABEREQAWFhYAHBwcACIiIgApKSkAVVVVAE1NTQBCQkIAOTk5AIB8/wBQUP8AkwDWAP/szADG1u8A1ufnAJCprQAAADMAAABmAAAAmQAAAMwAADMAAAAz" "MwAAM2YAADOZAAAzzAAAM/8AAGYAAABmMwAAZmYAAGaZAABmzAAAZv8AAJkAAACZMwAAmWYAAJmZAACZzAAAmf8AAMwAAADMMwAAzGYAAMyZAADMzAAAzP8AAP9mAAD/mQAA/8wAMwAAADMA" "MwAzAGYAMwCZADMAzAAzAP8AMzMAADMzMwAzM2YAMzOZADMzzAAzM/8AM2YAADNmMwAzZmYAM2aZADNmzAAzZv8AM5kAADOZMwAzmWYAM5mZADOZzAAzmf8AM8wAADPMMwAzzGYAM8yZADPM" "zAAzzP8AM/8zADP/ZgAz/5kAM//MADP//wBmAAAAZgAzAGYAZgBmAJkAZgDMAGYA/wBmMwAAZjMzAGYzZgBmM5kAZjPMAGYz/wBmZgAAZmYzAGZmZgBmZpkAZmbMAGaZAABmmTMAZplmAGaZ" "mQBmmcwAZpn/AGbMAABmzDMAZsyZAGbMzABmzP8AZv8AAGb/MwBm/5kAZv/MAMwA/wD/AMwAmZkAAJkzmQCZAJkAmQDMAJkAAACZMzMAmQBmAJkzzACZAP8AmWYAAJlmMwCZM2YAmWaZAJlm" "zACZM/8AmZkzAJmZZgCZmZkAmZnMAJmZ/wCZzAAAmcwzAGbMZgCZzJkAmczMAJnM/wCZ/wAAmf8zAJnMZgCZ/5kAmf/MAJn//wDMAAAAmQAzAMwAZgDMAJkAzADMAJkzAADMMzMAzDNmAMwz" "mQDMM8wAzDP/AMxmAADMZjMAmWZmAMxmmQDMZswAmWb/AMyZAADMmTMAzJlmAMyZmQDMmcwAzJn/AMzMAADMzDMAzMxmAMzMmQDMzMwAzMz/AMz/AADM/zMAmf9mAMz/mQDM/8wAzP//AMwA" "MwD/AGYA/wCZAMwzAAD/MzMA/zNmAP8zmQD/M8wA/zP/AP9mAAD/ZjMAzGZmAP9mmQD/ZswAzGb/AP+ZAAD/mTMA/5lmAP+ZmQD/mcwA/5n/AP/MAAD/zDMA/8xmAP/MmQD/zMwA/8z/AP//" "MwDM/2YA//+ZAP//zABmZv8AZv9mAGb//wD/ZmYA/2b/AP//ZgAhAKUAX19fAHd3dwCGhoYAlpaWAMvLywCysrIA19fXAN3d3QDj4+MA6urqAPHx8QD4+PgA8Pv/AKSgoACAgIAAAAD/AAD/" "AAAA//8A/wAAAP8A/wD//wAA////AP///////////////////////////////////////////////////////////////////////////////////////////wAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAD///////////8AeXl5eXl5eXl5eXl5eXl5eXl5eXl5eQD/////////AHkKCgoKCgoKCgoKCgoKCgoKCgoKCgoKeQD//////wB5CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKeQD/////" "AHkKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgp5AP////8AeQoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCnkA//////8AeQoKCgoKCgoKCgoKCgoKCgoKCgoKCgp5AP////////8AeQoKCgoKCgp5" "eXl5eXl5eXl5eXl5eQD///////////8AeQoKCgoKCgp5AAAAAAAAAAAAAAAA//////////////8AeQoKCgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP//////////" "//////////////////8AeQoKCgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP//////////////////////" "//////8AeQoKCgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP////////////////////////////8AeQoK" "CgoKCgp5AP////////////////////////////8AeQoKCgoKCgp5AP//////////////AAAAAAAAAAAAAAAAeQoKCgoKCgp5AP///////////wB5eXl5eXl5eXl5eXl5eQoKCgoKCgp5AP//" "//////8AeQoKCgoKCgoKCgoKCgoKCgoKCgoKCgp5AP//////AHkKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgp5AP////8AeQoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCnkA/////wB5CgoKCgoK" "CgoKCgoKCgoKCgoKCgoKCgoKeQD//////wB5CgoKCgoKCgoKCgoKCgoKCgoKCgoKCnkA/////////wB5eXl5eXl5eXl5eXl5eXl5eXl5eXl5AP///////////wAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAD///////////////////////////////////////////////////////////////////////////////////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAQAAAAIAAAAAEA" "CAAAAAAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYWFgAcHBwAIiIiACkpKQBVVVUATU1NAEJC" "QgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAAMwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm/wAAmQAAAJkzAACZ" "ZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNm" "ZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM/wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYz" "AABmMzMAZjNmAGYzmQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbMMwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8A" "zACZmQAAmTOZAJkAmQCZAMwAmQAAAJkzMwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnMAACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/" "AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwAmQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZMwDMmWYAzJmZAMyZ" "zADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9m" "zADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaG" "hgCWlpYAy8vLALKysgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP//AAD///8ADw8PDw8PDw8PDw8PDw8PDw95eXl5eXl5eXl5eXl5" "eQ8PeQoKCgoKCgoKCgoKCnkPD3kKCgoKCgoKCgoKCgp5Dw95CgoKCgoKCgoKCgoKeQ8AD3kKCgoKCnl5eXl5eXkPAAAPeQoKCgoKeQ8PDw8PDwAAAA95CgoKCgp5DwAAAAAAAAAAD3kKCgoK" "CnkPAAAAAAAADw8PeQoKCgoKeQ8AAA95eXl5eXl5CgoKCgp5DwAPeQoKCgoKCgoKCgoKCnkPD3kKCgoKCgoKCgoKCgp5Dw95CgoKCgoKCgoKCgoKeQ8PeXl5eXl5eXl5eXl5eXkPDw8PDw8P" "Dw8PDw8PDw8PDwAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAMAAAADgDwAA8AcAAAADAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="; SetContentType("image/x-icon"); sIcon.Base64Decode(sPageRet); return true; } else if (sURI == "/listusers") { if (!IsAdmin()) { return false; } ListUsersPage(sPageRet); } else if (sURI == "/deluser") { if (!IsAdmin()) { return false; } if (CZNC::Get().DeleteUser(GetParam("user"))) { Redirect("/listusers"); return false; } else { GetErrorPage(sPageRet, "No such username"); } } else { return false; } return true; } bool CWebAdminSock::SettingsPage(CString& sPageRet) { if (!GetParam("submitted").ToUInt()) { CString sVHosts, sMotd; m_Template["Title"] = "Settings"; m_Template["StatusPrefix"] = CZNC::Get().GetStatusPrefix(); m_Template["ISpoofFile"] = CZNC::Get().GetISpoofFile(); m_Template["ISpoofFormat"] = CZNC::Get().GetISpoofFormat(); const VCString& vsVHosts = CZNC::Get().GetVHosts(); for (unsigned int a = 0; a < vsVHosts.size(); a++) { CTemplate& l = m_Template.AddRow("VHostLoop"); l["VHost"] = vsVHosts[a]; } const VCString& vsMotd = CZNC::Get().GetMotd(); for (unsigned int b = 0; b < vsMotd.size(); b++) { CTemplate& l = m_Template.AddRow("MOTDLoop"); l["Line"] = vsMotd[b]; } set<CModInfo> ssGlobalMods; CZNC::Get().GetModules().GetAvailableMods(ssGlobalMods, true); for (set<CModInfo>::iterator it = ssGlobalMods.begin(); it != ssGlobalMods.end(); it++) { const CModInfo& Info = *it; CTemplate& l = m_Template.AddRow("ModuleLoop"); if (CZNC::Get().GetModules().FindModule(Info.GetName())) { l["Checked"] = "true"; } if (Info.GetName() == m_pModule->GetModName()) { l["Disabled"] = "true"; } l["Name"] = Info.GetName(); l["Description"] = Info.GetDescription(); l["Args"] = GetModArgs(Info.GetName(), true); } PrintPage(sPageRet, "Settings.tmpl"); return true; } CString sArg; sArg = GetParam("statusprefix"); CZNC::Get().SetStatusPrefix(sArg); sArg = GetParam("ispooffile"); CZNC::Get().SetISpoofFile(sArg); sArg = GetParam("ispoofformat"); CZNC::Get().SetISpoofFormat(sArg); //sArg = GetParam(""); if (!sArg.empty()) { CZNC::Get().Set(sArg); } VCString vsArgs; GetParam("motd").Split("\n", vsArgs); CZNC::Get().ClearMotd(); unsigned int a = 0; for (a = 0; a < vsArgs.size(); a++) { CZNC::Get().AddMotd(vsArgs[a].TrimRight_n()); } GetParam("vhosts").Split("\n", vsArgs); CZNC::Get().ClearVHosts(); for (a = 0; a < vsArgs.size(); a++) { CZNC::Get().AddVHost(vsArgs[a].Trim_n()); } set<CString> ssArgs; GetParamValues("loadmod", ssArgs); for (set<CString>::iterator it = ssArgs.begin(); it != ssArgs.end(); it++) { CString sModRet; CString sModName = (*it).TrimRight_n("\r"); if (!sModName.empty()) { CString sArgs = GetParam("modargs_" + sModName); try { if (!CZNC::Get().GetModules().FindModule(sModName)) { if (!CZNC::Get().GetModules().LoadModule(sModName, sArgs, NULL, sModRet)) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] [" << sModRet << "]" << endl); } } else { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] because it is already loaded" << endl); } } catch(...) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] [" << sArgs << "]" << endl); } } } const CModules& vCurMods = CZNC::Get().GetModules(); set<CString> ssUnloadMods; for (a = 0; a < vCurMods.size(); a++) { CModule* pCurMod = vCurMods[a]; if (ssArgs.find(pCurMod->GetModName()) == ssArgs.end() && pCurMod->GetModName() != m_pModule->GetModName()) { ssUnloadMods.insert(pCurMod->GetModName()); } } for (set<CString>::iterator it2 = ssUnloadMods.begin(); it2 != ssUnloadMods.end(); it2++) { CZNC::Get().GetModules().UnloadModule(*it2); } if (!CZNC::Get().WriteConfig()) { GetErrorPage(sPageRet, "Settings changed, but config was not written"); return true; } Redirect("/"); return false; } bool CWebAdminSock::ChanPage(CString& sPageRet, CChan* pChan) { if (!m_pUser) { GetErrorPage(sPageRet, "That user doesn't exist"); return true; } if (!GetParam("submitted").ToUInt()) { m_Template["User"] = m_pUser->GetUserName(); if (pChan) { m_Template["Edit"] = "true"; m_Template["Title"] = "Edit Channel" + CString(" [" + pChan->GetName() + "]"); m_Template["ChanName"] = pChan->GetName(); m_Template["BufferCount"] = CString::ToString(pChan->GetBufferCount()); m_Template["DefModes"] = pChan->GetDefaultModes(); if (pChan->InConfig()) { m_Template["InConfig"] = "true"; } } else { m_Template["Title"] = "Add Channel" + CString(" for User [" + m_pUser->GetUserName() + "]"); m_Template["BufferCount"] = "50"; m_Template["DefModes"] = "+stn"; m_Template["InConfig"] = "true"; } CTemplate& o1 = m_Template.AddRow("OptionLoop"); o1["Name"] = "autocycle"; o1["DisplayName"] = "Auto Cycle"; if (!pChan || pChan->AutoCycle()) { o1["Checked"] = "true"; } CTemplate& o2 = m_Template.AddRow("OptionLoop"); o2["Name"] = "keepbuffer"; o2["DisplayName"] = "Keep Buffer"; if (!pChan || pChan->KeepBuffer()) { o2["Checked"] = "true"; } CTemplate& o3 = m_Template.AddRow("OptionLoop"); o3["Name"] = "detached"; o3["DisplayName"] = "Detached"; if (pChan && pChan->IsDetached()) { o3["Checked"] = "true"; } PrintPage(sPageRet, "Channel.tmpl"); return true; } CString sChanName = GetParam("name").Trim_n(); if (!pChan) { if (sChanName.empty()) { GetErrorPage(sPageRet, "Channel name is a required argument"); return true; } if (m_pUser->FindChan(sChanName.Token(0))) { GetErrorPage(sPageRet, "Channel [" + sChanName.Token(0) + "] already exists"); return true; } pChan = new CChan(sChanName, m_pUser, true); m_pUser->AddChan(pChan); } pChan->SetDefaultModes(GetParam("defmodes")); pChan->SetBufferCount(GetParam("buffercount").ToUInt()); pChan->SetInConfig(GetParam("save").ToBool()); pChan->SetAutoCycle(GetParam("autocycle").ToBool()); pChan->SetKeepBuffer(GetParam("keepbuffer").ToBool()); bool bDetached = GetParam("detached").ToBool(); if (pChan->IsDetached() != bDetached) { if (bDetached) { pChan->DetachUser(); } else { pChan->AttachUser(); } } m_pUser->JoinChans(); if (!CZNC::Get().WriteConfig()) { GetErrorPage(sPageRet, "Channel added/modified, but config was not written"); return true; } Redirect("/edituser?user=" + m_pUser->GetUserName().Escape_n(CString::EURL)); return false; } bool CWebAdminSock::DelChan(CString& sPageRet) { CString sChan = GetParam("chan"); if (!m_pUser) { GetErrorPage(sPageRet, "That user doesn't exist"); return true; } if (sChan.empty()) { GetErrorPage(sPageRet, "That channel doesn't exist for this user"); return true; } m_pUser->DelChan(sChan); m_pUser->PutIRC("PART " + sChan); if (!CZNC::Get().WriteConfig()) { GetErrorPage(sPageRet, "Channel deleted, but config was not written"); return true; } Redirect("/edituser?user=" + m_pUser->GetUserName().Escape_n(CString::EURL)); return false; } bool CWebAdminSock::UserPage(CString& sPageRet, CUser* pUser) { if (!GetParam("submitted").ToUInt()) { CString sAllowedHosts, sServers, sChans, sCTCPReplies; if (pUser) { m_Template["Title"] = "Edit User [" + pUser->GetUserName() + "]"; m_Template["Edit"] = "true"; m_Template["Username"] = pUser->GetUserName(); m_Template["Nick"] = pUser->GetNick(); m_Template["AltNick"] = pUser->GetAltNick(); m_Template["AwaySuffix"] = pUser->GetAwaySuffix(); m_Template["StatusPrefix"] = pUser->GetStatusPrefix(); m_Template["Ident"] = pUser->GetIdent(); m_Template["RealName"] = pUser->GetRealName(); m_Template["QuitMsg"] = pUser->GetQuitMsg(); m_Template["DefaultChanModes"] = pUser->GetDefaultChanModes(); m_Template["BufferCount"] = CString::ToString(pUser->GetBufferCount()); const set<CString>& ssAllowedHosts = pUser->GetAllowedHosts(); for (set<CString>::const_iterator it = ssAllowedHosts.begin(); it != ssAllowedHosts.end(); it++) { CTemplate& l = m_Template.AddRow("AllowedHostLoop"); l["Host"] = *it; } const vector<CServer*>& vServers = pUser->GetServers(); for (unsigned int a = 0; a < vServers.size(); a++) { CTemplate& l = m_Template.AddRow("ServerLoop"); l["Server"] = vServers[a]->GetString(); } const MCString& msCTCPReplies = pUser->GetCTCPReplies(); for (MCString::const_iterator it2 = msCTCPReplies.begin(); it2 != msCTCPReplies.end(); it2++) { CTemplate& l = m_Template.AddRow("CTCPLoop"); l["CTCP"] = it2->first + " " + it2->second; } if (pUser == CZNC::Get().FindUser(GetUser())) { CString sIP = GetRemoteIP(); if (!sIP.empty()) { m_Template["OwnIP"] = sIP.Token(0, false, ".") + "." + sIP.Token(1, false, ".") + "." + sIP.Token(2, false, ".") + ".*"; } } const VCString& vsVHosts = CZNC::Get().GetVHosts(); for (unsigned int b = 0; b < vsVHosts.size(); b++) { const CString& sVHost = vsVHosts[b]; CTemplate& l = m_Template.AddRow("VHostLoop"); l["VHost"] = sVHost; if (pUser && pUser->GetVHost() == sVHost) { l["Checked"] = "true"; } } const vector<CChan*>& Channels = pUser->GetChans(); for (unsigned int c = 0; c < Channels.size(); c++) { CChan* pChan = Channels[c]; CTemplate& l = m_Template.AddRow("ChannelLoop"); l["Username"] = pUser->GetUserName(); l["Name"] = pChan->GetName(); l["Perms"] = pChan->GetPermStr(); l["CurModes"] = pChan->GetModeString(); l["DefModes"] = pChan->GetDefaultModes(); l["BufferCount"] = CString::ToString(pChan->GetBufferCount()); l["Options"] = pChan->GetOptions(); if (pChan->InConfig()) { l["InConfig"] = "true"; } } } else { m_Template["Title"] = "Add User"; m_Template["StatusPrefix"] = "*"; } set<CModInfo> ssUserMods; CZNC::Get().GetModules().GetAvailableMods(ssUserMods); for (set<CModInfo>::iterator it = ssUserMods.begin(); it != ssUserMods.end(); it++) { const CModInfo& Info = *it; CTemplate& l = m_Template.AddRow("ModuleLoop"); l["Name"] = Info.GetName(); l["Description"] = Info.GetDescription(); l["Args"] = GetModArgs(Info.GetName()); if (pUser && pUser->GetModules().FindModule(Info.GetName())) { l["Checked"] = "true"; } if (!IsAdmin() && pUser && pUser->DenyLoadMod()) { l["Disabled"] = "true"; } } CTemplate& o1 = m_Template.AddRow("OptionLoop"); o1["Name"] = "keepbuffer"; o1["DisplayName"] = "Keep Buffer"; if (!pUser || pUser->KeepBuffer()) { o1["Checked"] = "true"; } CTemplate& o2 = m_Template.AddRow("OptionLoop"); o2["Name"] = "autocycle"; o2["DisplayName"] = "Auto Cycle"; if (!pUser || pUser->AutoCycle()) { o2["Checked"] = "true"; } CTemplate& o3 = m_Template.AddRow("OptionLoop"); o3["Name"] = "keepnick"; o3["DisplayName"] = "Keep Nick"; if (!pUser || pUser->GetKeepNick()) { o3["Checked"] = "true"; } CTemplate& o4 = m_Template.AddRow("OptionLoop"); o4["Name"] = "multiclients"; o4["DisplayName"] = "Multi Clients"; if (!pUser || pUser->MultiClients()) { o4["Checked"] = "true"; } CTemplate& o5 = m_Template.AddRow("OptionLoop"); o5["Name"] = "bouncedccs"; o5["DisplayName"] = "Bounce DCCs"; if (!pUser || pUser->BounceDCCs()) { o5["Checked"] = "true"; } CTemplate& o6 = m_Template.AddRow("OptionLoop"); o6["Name"] = "useclientip"; o6["DisplayName"] = "Use Client IP"; if (pUser && pUser->UseClientIP()) { o6["Checked"] = "true"; } if (IsAdmin()) { CTemplate& o7 = m_Template.AddRow("OptionLoop"); o7["Name"] = "denyloadmod"; o7["DisplayName"] = "Deny LoadMod"; if (pUser && pUser->DenyLoadMod()) { o7["Checked"] = "true"; } CTemplate& o8 = m_Template.AddRow("OptionLoop"); o8["Name"] = "isadmin"; o8["DisplayName"] = "Admin"; if (pUser && pUser->IsAdmin()) { o8["Checked"] = "true"; } if (pUser && pUser == CZNC::Get().FindUser(GetUser())) { o8["Disabled"] = "true"; } } PrintPage(sPageRet, "UserPage.tmpl"); return true; } CString sUsername = GetParam("user"); if (!pUser && CZNC::Get().FindUser(sUsername)) { GetErrorPage(sPageRet, "Invalid Submission [User " + sUsername + " already exists]"); return true; } CUser* pNewUser = GetNewUser(sPageRet, pUser); if (!pNewUser) { return true; } CString sErr; if (!pUser) { // Add User Submission if (!pNewUser->IsValid(sErr)) { delete pNewUser; GetErrorPage(sPageRet, "Invalid submission [" + sErr + "]"); return true; } CZNC::Get().AddUser(pNewUser); if (!CZNC::Get().WriteConfig()) { GetErrorPage(sPageRet, "User added, but config was not written"); return true; } } else { // Edit User Submission if (!pUser->Clone(*pNewUser, sErr)) { delete pNewUser; GetErrorPage(sPageRet, "Invalid Submission [" + sErr + "]"); return true; } delete pNewUser; if (!CZNC::Get().WriteConfig()) { GetErrorPage(sPageRet, "User edited, but config was not written"); return true; } } if (!IsAdmin()) { Redirect("/edituser"); } else { Redirect("/listusers"); } return false; } CUser* CWebAdminSock::GetNewUser(CString& sPageRet, CUser* pUser) { CString sUsername = GetParam("newuser"); if (sUsername.empty()) { sUsername = GetParam("user"); } if (sUsername.empty()) { GetErrorPage(sPageRet, "Invalid Submission [Username is required]"); return NULL; } CString sArg = GetParam("password"); if (sArg != GetParam("password2")) { GetErrorPage(sPageRet, "Invalid Submission [Passwords do not match]"); return NULL; } CUser* pNewUser = new CUser(sUsername); if (!sArg.empty()) { pNewUser->SetPass(sArg.MD5(), true); } VCString vsArgs; GetParam("servers").Split("\n", vsArgs); unsigned int a = 0; for (a = 0; a < vsArgs.size(); a++) { pNewUser->AddServer(vsArgs[a].Trim_n()); } GetParam("allowedips").Split("\n", vsArgs); if (vsArgs.size()) { for (a = 0; a < vsArgs.size(); a++) { pNewUser->AddAllowedHost(vsArgs[a].Trim_n()); } } else { pNewUser->AddAllowedHost("*"); } if (HasParam("ownip")) { pNewUser->AddAllowedHost(GetParam("ownip")); } GetParam("ctcpreplies").Split("\n", vsArgs); for (a = 0; a < vsArgs.size(); a++) { CString sReply = vsArgs[a].TrimRight_n("\r"); pNewUser->AddCTCPReply(sReply.Token(0).Trim_n(), sReply.Token(1, true).Trim_n()); } if (IsAdmin() || (pUser && !pUser->DenyLoadMod())) { GetParamValues("loadmod", vsArgs); for (a = 0; a < vsArgs.size(); a++) { CString sModRet; CString sModName = vsArgs[a].TrimRight_n("\r"); if (!sModName.empty()) { CString sArgs = GetParam("modargs_" + sModName); try { if (!pNewUser->GetModules().LoadModule(sModName, sArgs, pNewUser, sModRet, (pUser != NULL))) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] [" << sModRet << "]" << endl); } } catch (...) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] [" << sArgs << "]" << endl); } } } } else if (pUser) { CModules& Modules = pUser->GetModules(); for (a = 0; a < Modules.size(); a++) { CString sModName = Modules[a]->GetModName(); CString sArgs = Modules[a]->GetArgs(); CString sModRet; try { if (!pNewUser->GetModules().LoadModule(sModName, sArgs, pNewUser, sModRet, (pUser != NULL))) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "] [" << sModRet << "]" << endl); } } catch (...) { DEBUG_ONLY(cerr << "Unable to load module [" << sModName << "]" << endl); } } } sArg = GetParam("nick"); if (!sArg.empty()) { pNewUser->SetNick(sArg); } sArg = GetParam("altnick"); if (!sArg.empty()) { pNewUser->SetAltNick(sArg); } sArg = GetParam("awaysuffix"); if (!sArg.empty()) { pNewUser->SetAwaySuffix(sArg); } sArg = GetParam("statusprefix"); if (!sArg.empty()) { pNewUser->SetStatusPrefix(sArg); } sArg = GetParam("ident"); if (!sArg.empty()) { pNewUser->SetIdent(sArg); } sArg = GetParam("realname"); if (!sArg.empty()) { pNewUser->SetRealName(sArg); } sArg = GetParam("vhost"); if (!sArg.empty()) { pNewUser->SetVHost(sArg); } sArg = GetParam("quitmsg"); if (!sArg.empty()) { pNewUser->SetQuitMsg(sArg); } sArg = GetParam("chanmodes"); if (!sArg.empty()) { pNewUser->SetDefaultChanModes(sArg); } pNewUser->SetBufferCount(GetParam("bufsize").ToUInt()); pNewUser->SetKeepBuffer(GetParam("keepbuffer").ToBool()); pNewUser->SetMultiClients(GetParam("multiclients").ToBool()); pNewUser->SetBounceDCCs(GetParam("bouncedccs").ToBool()); pNewUser->SetAutoCycle(GetParam("autocycle").ToBool()); pNewUser->SetKeepNick(GetParam("keepnick").ToBool()); pNewUser->SetUseClientIP(GetParam("useclientip").ToBool()); if (IsAdmin()) { pNewUser->SetDenyLoadMod(GetParam("denyloadmod").ToBool()); } else if (pUser) { pNewUser->SetDenyLoadMod(pUser->DenyLoadMod()); } if (pUser && pUser != CZNC::Get().FindUser(GetUser())) { pNewUser->SetAdmin(GetParam("isadmin").ToBool()); } else if (pUser) { pNewUser->SetAdmin(pUser->IsAdmin()); } GetParamValues("channel", vsArgs); for (a = 0; a < vsArgs.size(); a++) { const CString& sChan = vsArgs[a]; pNewUser->AddChan(sChan.TrimRight_n("\r"), GetParam("save_" + sChan).ToBool()); } return pNewUser; } GLOBALMODULEDEFS(CWebAdminMod, "Dynamic configuration of users/settings through a web browser")
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Sergey Lisitsyn * Copyright (C) 2010-2012 Jun Liu, Jieping Ye */ #include <shogun/lib/slep/slep_solver.h> #include <shogun/mathematics/Math.h> #include <shogun/lib/slep/q1/eppMatrix.h> #include <shogun/lib/slep/q1/eppVector.h> #include <shogun/lib/slep/flsa/flsa.h> #include <shogun/lib/slep/tree/altra.h> #include <shogun/lib/slep/tree/general_altra.h> #include <shogun/lib/Signal.h> namespace shogun { double compute_regularizer(double* w, double lambda, double lambda2, int n_vecs, int n_feats, int n_blocks, const slep_options& options) { double regularizer = 0.0; switch (options.mode) { case MULTITASK_GROUP: { for (int i=0; i<n_feats; i++) { double w_row_norm = 0.0; for (int t=0; t<n_blocks; t++) w_row_norm += CMath::pow(w[i+t*n_feats],options.q); regularizer += CMath::pow(w_row_norm,1.0/options.q); } regularizer *= lambda; } break; case MULTITASK_TREE: { for (int i=0; i<n_feats; i++) { double tree_norm = 0.0; if (options.general) tree_norm = general_treeNorm(w+i, n_blocks, n_blocks, options.G, options.ind_t, options.n_nodes); else tree_norm = treeNorm(w+i, n_blocks, n_blocks, options.ind_t, options.n_nodes); regularizer += tree_norm; } regularizer *= lambda; } break; case FEATURE_GROUP: { for (int t=0; t<n_blocks; t++) { double group_qpow_sum = 0.0; int group_ind_start = options.ind[t]; int group_ind_end = options.ind[t+1]; for (int i=group_ind_start; i<group_ind_end; i++) group_qpow_sum += CMath::pow(w[i], options.q); regularizer += options.gWeight[t]*CMath::pow(group_qpow_sum, 1.0/options.q); } regularizer *= lambda; } break; case FEATURE_TREE: { if (options.general) regularizer = general_treeNorm(w, 1, n_feats, options.G, options.ind_t, options.n_nodes); else regularizer = treeNorm(w, 1, n_feats, options.ind_t, options.n_nodes); regularizer *= lambda; } break; case PLAIN: { for (int i=0; i<n_feats; i++) regularizer += CMath::abs(w[i]); regularizer *= lambda; } break; case FUSED: { double l1 = 0.0; for (int i=0; i<n_feats; i++) l1 += CMath::abs(w[i]); regularizer += lambda*l1; double fuse = 0.0; for (int i=1; i<n_feats; i++) fuse += CMath::abs(w[i]-w[i-1]); regularizer += lambda2*fuse; } break; default: SG_SERROR("WHOA?\n"); } return regularizer; }; double compute_lambda( double* ATx, double z, CDotFeatures* features, double* y, int n_vecs, int n_feats, int n_blocks, const slep_options& options) { double lambda_max = 0.0; if (z<0 || z>1) SG_SERROR("z is not in range [0,1]"); double q_bar = 0.0; if (options.q==1) q_bar = CMath::ALMOST_INFTY; else if (options.q>1e6) q_bar = 1; else q_bar = options.q/(options.q-1); SG_SDEBUG("q bar = %f \n",q_bar); switch (options.mode) { case MULTITASK_GROUP: case MULTITASK_TREE: { for (int t=0; t<n_blocks; t++) { SGVector<index_t> task_idx = options.tasks_indices[t]; int n_vecs_task = task_idx.vlen; switch (options.loss) { case LOGISTIC: { double b = 0.0; int m1 = 0, m2 = 0; for (int i=0; i<n_vecs_task; i++) { if (y[task_idx[i]]>0) m1++; else m2++; } for (int i=0; i<n_vecs_task; i++) { if (y[task_idx[i]]>0) b = double(m1)/(m1+m2); else b = -double(m2)/(m1+m2); features->add_to_dense_vec(b,task_idx[i],ATx+t*n_feats,n_feats); } } break; case LEAST_SQUARES: { for (int i=0; i<n_vecs_task; i++) features->add_to_dense_vec(y[task_idx[i]],task_idx[i],ATx+t*n_feats,n_feats); } } } } break; case FEATURE_GROUP: case FEATURE_TREE: case PLAIN: case FUSED: { switch (options.loss) { case LOGISTIC: { int m1 = 0, m2 = 0; double b = 0.0; for (int i=0; i<n_vecs; i++) y[i]>0 ? m1++ : m2++; SG_SDEBUG("# pos = %d , # neg = %d\n",m1,m2); for (int i=0; i<n_vecs; i++) { y[i]>0 ? b=double(m2) / CMath::sq(n_vecs) : b=-double(m1) / CMath::sq(n_vecs); features->add_to_dense_vec(b,i,ATx,n_feats); } } break; case LEAST_SQUARES: { for (int i=0; i<n_vecs; i++) features->add_to_dense_vec(y[i],i,ATx,n_feats); } break; } } break; } switch (options.mode) { case MULTITASK_GROUP: { for (int i=0; i<n_feats; i++) { double sum = 0.0; for (int t=0; t<n_blocks; t++) sum += CMath::pow(fabs(ATx[t*n_feats+i]),q_bar); lambda_max = CMath::max(lambda_max, CMath::pow(sum,1.0/q_bar)); } if (options.loss==LOGISTIC) lambda_max /= n_vecs; } break; case MULTITASK_TREE: { if (options.general) lambda_max = general_findLambdaMax_mt(ATx, n_feats, n_blocks, options.G, options.ind_t, options.n_nodes); else lambda_max = findLambdaMax_mt(ATx, n_feats, n_blocks, options.ind_t, options.n_nodes); lambda_max /= n_vecs*n_blocks; } break; case FEATURE_GROUP: { for (int t=0; t<n_blocks; t++) { int group_ind_start = options.ind[t]; int group_ind_end = options.ind[t+1]; double sum = 0.0; for (int i=group_ind_start; i<group_ind_end; i++) sum += CMath::pow(fabs(ATx[i]),q_bar); sum = CMath::pow(sum, 1.0/q_bar); sum /= options.gWeight[t]; if (sum>lambda_max) lambda_max = sum; } } break; case FEATURE_TREE: { if (options.general) lambda_max = general_findLambdaMax(ATx, n_feats, options.G, options.ind_t, options.n_nodes); else lambda_max = findLambdaMax(ATx, n_feats, options.ind_t, options.n_nodes); } break; case PLAIN: case FUSED: { double max = 0.0; for (int i=0; i<n_feats; i++) { if (CMath::abs(ATx[i]) > max) max = CMath::abs(ATx[i]); } lambda_max = max; } break; } SG_SINFO("Computed lambda = %f\n",z*lambda_max); return z*lambda_max; } void projection(double* w, double* v, int n_feats, int n_blocks, double lambda, double lambda2, double L, double* z, double* z0, const slep_options& options) { switch (options.mode) { case MULTITASK_GROUP: eppMatrix(w, v, n_feats, n_blocks, lambda/L, options.q); break; case MULTITASK_TREE: if (options.general) general_altra_mt(w, v, n_feats, n_blocks, options.G, options.ind_t, options.n_nodes, lambda/L); else altra_mt(w, v, n_feats, n_blocks, options.ind_t, options.n_nodes, lambda/L); break; case FEATURE_GROUP: eppVector(w, v, options.ind, n_blocks, n_feats, options.gWeight, lambda/L, CMath::max(options.q,1e6)); break; case FEATURE_TREE: if (options.general) general_altra(w, v, n_feats, options.G, options.ind_t, options.n_nodes, lambda/L); else altra(w, v, n_feats, options.ind_t, options.n_nodes, lambda/L); break; case PLAIN: for (int i=0; i<n_feats; i++) w[i] = CMath::sign(v[i])*CMath::max(0.0,CMath::abs(v[i])-lambda/L); break; case FUSED: flsa(w,z,NULL,v,z0,lambda/L,lambda2/L,n_feats,1000,1e-8,1,6); for (int i=0; i<n_feats; i++) z0[i] = z[i]; break; } } double search_point_gradient_and_objective(CDotFeatures* features, double* ATx, double* As, double* sc, double* y, int n_vecs, int n_feats, int n_tasks, double* g, double* gc, const slep_options& options) { double fun_s = 0.0; SG_SDEBUG("As=%f\n", SGVector<float64_t>::dot(As,As,n_vecs)); SG_SDEBUG("sc=%f\n", SGVector<float64_t>::dot(sc,sc,n_tasks)); switch (options.mode) { case MULTITASK_GROUP: case MULTITASK_TREE: for (int t=0; t<n_tasks; t++) { SGVector<index_t> task_idx = options.tasks_indices[t]; int n_vecs_task = task_idx.vlen; switch (options.loss) { case LOGISTIC: gc[t] = 0.0; for (int i=0; i<n_vecs_task; i++) { double aa = -y[task_idx[i]]*(As[task_idx[i]]+sc[t]); double bb = CMath::max(aa,0.0); fun_s += (CMath::log(CMath::exp(-bb) + CMath::exp(aa-bb)) + bb)/ n_vecs; double prob = 1.0/(1.0+CMath::exp(aa)); double b = -y[task_idx[i]]*(1.0-prob) / n_vecs; gc[t] += b; features->add_to_dense_vec(b,task_idx[i],g+t*n_feats,n_feats); } break; case LEAST_SQUARES: for (int i=0; i<n_feats*n_tasks; i++) g[i] = -ATx[i]; for (int i=0; i<n_vecs_task; i++) features->add_to_dense_vec(As[task_idx[i]],task_idx[i],g+t*n_feats,n_feats); break; } } break; case FEATURE_GROUP: case FEATURE_TREE: case PLAIN: case FUSED: switch (options.loss) { case LOGISTIC: gc[0] = 0.0; for (int i=0; i<n_vecs; i++) { double aa = -y[i]*(As[i]+sc[0]); double bb = CMath::max(aa,0.0); fun_s += (CMath::log(CMath::exp(-bb) + CMath::exp(aa-bb)) + bb); double prob = 1.0/(1.0+CMath::exp(aa)); double b = -y[i]*(1.0-prob) / n_vecs; gc[0] += b; features->add_to_dense_vec(b,i,g,n_feats); } fun_s /= n_vecs; break; case LEAST_SQUARES: for (int i=0; i<n_feats; i++) g[i] = -ATx[i]; for (int i=0; i<n_vecs; i++) features->add_to_dense_vec(As[i],i,g,n_feats); break; } break; } SG_SDEBUG("G=%f\n", SGVector<float64_t>::dot(g,g,n_feats*n_tasks)); return fun_s; } slep_result_t slep_solver( CDotFeatures* features, double* y, double z, const slep_options& options) { int i,t; int n_feats = features->get_dim_feature_space(); int n_vecs = features->get_num_vectors(); double lambda, beta; double funcp = 0.0, func = 0.0; int n_blocks = 0; int n_tasks = 0; switch (options.mode) { case MULTITASK_GROUP: case MULTITASK_TREE: n_tasks = options.n_tasks; n_blocks = options.n_tasks; break; case FEATURE_GROUP: case FEATURE_TREE: n_tasks = 1; n_blocks = options.n_feature_blocks; break; case PLAIN: case FUSED: n_tasks = 1; n_blocks = 1; break; } SG_SDEBUG("n_tasks = %d, n_blocks = %d\n",n_tasks,n_blocks); SG_SDEBUG("n_nodes = %d\n",options.n_nodes); int iter = 1; bool done = false; bool gradient_break = false; double rsL2 = options.rsL2; double* ATx = SG_CALLOC(double, n_feats*n_tasks); if (options.regularization!=0) { lambda = compute_lambda(ATx, z, features, y, n_vecs, n_feats, n_blocks, options); rsL2*= lambda; } else lambda = z; double lambda2 = 0.0; SGMatrix<double> w(n_feats,n_tasks); w.zero(); SGVector<double> c(n_blocks); c.zero(); if (options.last_result) { w = options.last_result->w; c = options.last_result->c; } double* s = SG_CALLOC(double, n_feats*n_tasks); double* sc = SG_CALLOC(double, n_tasks); double* g = SG_CALLOC(double, n_feats*n_tasks); double* v = SG_CALLOC(double, n_feats*n_tasks); double* z_flsa = SG_CALLOC(double, n_feats); double* z0_flsa = SG_CALLOC(double, n_feats); double* Aw = SG_CALLOC(double, n_vecs); switch (options.mode) { case MULTITASK_GROUP: case MULTITASK_TREE: { for (t=0; t<n_blocks; t++) { SGVector<index_t> task_idx = options.tasks_indices[t]; //task_idx.display_vector("task"); int n_vecs_task = task_idx.vlen; for (i=0; i<n_vecs_task; i++) Aw[task_idx[i]] = features->dense_dot(task_idx[i],w.matrix+t*n_feats,n_feats); } } break; case FEATURE_GROUP: case FEATURE_TREE: case PLAIN: case FUSED: { for (i=0; i<n_vecs; i++) Aw[i] = features->dense_dot(i,w.matrix,n_feats); } break; } double* Av = SG_MALLOC(double, n_vecs); double* As = SG_MALLOC(double, n_vecs); double L = 1.0/n_vecs; if (options.mode==FUSED) L += rsL2; double* wp = SG_CALLOC(double, n_feats*n_tasks); for (i=0; i<n_feats*n_tasks; i++) wp[i] = w[i]; double* Awp = SG_MALLOC(double, n_vecs); for (i=0; i<n_vecs; i++) Awp[i] = Aw[i]; double* wwp = SG_CALLOC(double, n_feats*n_tasks); double* cp = SG_MALLOC(double, n_tasks); for (t=0; t<n_tasks; t++) cp[t] = c[t]; double* ccp = SG_CALLOC(double, n_tasks); double* gc = SG_MALLOC(double, n_tasks); double alphap = 0.0, alpha = 1.0; double fun_x = 0.0; while (!done && iter <= options.max_iter && !CSignal::cancel_computations()) { beta = (alphap-1.0)/alpha; for (i=0; i<n_feats*n_tasks; i++) s[i] = w[i] + beta*wwp[i]; for (t=0; t<n_tasks; t++) sc[t] = c[t] + beta*ccp[t]; for (i=0; i<n_vecs; i++) As[i] = Aw[i] + beta*(Aw[i]-Awp[i]); for (i=0; i<n_tasks*n_feats; i++) g[i] = 0.0; double fun_s = search_point_gradient_and_objective(features, ATx, As, sc, y, n_vecs, n_feats, n_tasks, g, gc, options); if (options.mode==PLAIN || options.mode==FUSED) fun_s += rsL2/2 * SGVector<float64_t>::dot(w.matrix,w.matrix,n_feats); for (i=0; i<n_feats*n_tasks; i++) wp[i] = w[i]; for (t=0; t<n_tasks; t++) cp[t] = c[t]; for (i=0; i<n_vecs; i++) Awp[i] = Aw[i]; int inner_iter = 1; while (inner_iter <= 1000) { for (i=0; i<n_feats*n_tasks; i++) v[i] = s[i] - g[i]*(1.0/L); for (t=0; t<n_tasks; t++) c[t] = sc[t] - gc[t]*(1.0/L); projection(w.matrix,v,n_feats,n_blocks,lambda,lambda2,L,z_flsa,z0_flsa,options); for (i=0; i<n_feats*n_tasks; i++) v[i] = w[i] - s[i]; double l_sum = 0.0, r_sum = 0.0; switch (options.loss) { case LOGISTIC: r_sum = SGVector<float64_t>::dot(v,v,n_feats*n_tasks); l_sum = fun_x - fun_s - SGVector<float64_t>::dot(v,g,n_feats*n_tasks); for (t=0; t<n_tasks; t++) { r_sum += CMath::sq(c[t] - sc[t]); l_sum -= (c[t] - sc[t])*gc[t]; } r_sum /= 2.0; break; case LEAST_SQUARES: r_sum = SGVector<float64_t>::dot(v,v,n_feats*n_tasks); for (i=0; i<n_vecs; i++) l_sum += CMath::sq(Aw[i]-As[i]); break; } if (r_sum <= 1e-20) { gradient_break = true; break; } if (l_sum <= r_sum*L) break; else L = CMath::max(2*L, l_sum/r_sum); inner_iter++; } alphap = alpha; alpha = 0.5*(1+CMath::sqrt(4*alpha*alpha+1)); for (i=0; i<n_feats*n_tasks; i++) wwp[i] = w[i] - wp[i]; for (t=0; t<n_tasks; t++) ccp[t] = c[t] - cp[t]; double regularizer = compute_regularizer(w.matrix, lambda, lambda2, n_vecs, n_feats, n_blocks, options); funcp = func; if (options.loss==LOGISTIC) { func = fun_x + regularizer; } if (options.loss==LEAST_SQUARES) { func = regularizer; for (i=0; i<n_vecs; i++) func += CMath::sq(Aw[i] - y[i]); } //SG_SDEBUG("Obj = %f + %f * %f = %f \n",fun_x, lambda, regularizer, func); if (gradient_break) { SG_SINFO("Gradient norm is less than 1e-20\n"); break; } double norm_wp, norm_wwp; double step; switch (options.termination) { case 0: if (iter>=2) { step = CMath::abs(func-funcp); if (step <= options.tolerance) { SG_SINFO("Objective changes less than tolerance\n"); done = true; } } break; case 1: if (iter>=2) { step = CMath::abs(func-funcp); if (step <= step*options.tolerance) { SG_SINFO("Objective changes relatively less than tolerance\n"); done = true; } } break; case 2: if (func <= options.tolerance) { SG_SINFO("Objective is less than tolerance\n"); done = true; } break; case 3: norm_wwp = CMath::sqrt(SGVector<float64_t>::dot(wwp,wwp,n_feats*n_tasks)); if (norm_wwp <= options.tolerance) done = true; break; case 4: norm_wp = CMath::sqrt(SGVector<float64_t>::dot(wp,wp,n_feats*n_tasks)); norm_wwp = CMath::sqrt(SGVector<float64_t>::dot(wwp,wwp,n_feats*n_tasks)); if (norm_wwp <= options.tolerance*CMath::max(norm_wp,1.0)) done = true; break; case 5: if (iter > options.max_iter) done = true; break; default: done = true; } iter++; } SG_SINFO("Finished %d iterations, objective = %f\n", iter, func); cleanup: SG_FREE(ATx); SG_FREE(wp); SG_FREE(wwp); SG_FREE(s); SG_FREE(sc); SG_FREE(cp); SG_FREE(ccp); SG_FREE(g); SG_FREE(v); SG_FREE(Aw); SG_FREE(Awp); SG_FREE(Av); SG_FREE(As); SG_FREE(gc); SG_FREE(z_flsa); SG_FREE(z0_flsa); return slep_result_t(w,c); }; }; Restored mystery objective calculation code in slep /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Sergey Lisitsyn * Copyright (C) 2010-2012 Jun Liu, Jieping Ye */ #include <shogun/lib/slep/slep_solver.h> #include <shogun/mathematics/Math.h> #include <shogun/lib/slep/q1/eppMatrix.h> #include <shogun/lib/slep/q1/eppVector.h> #include <shogun/lib/slep/flsa/flsa.h> #include <shogun/lib/slep/tree/altra.h> #include <shogun/lib/slep/tree/general_altra.h> #include <shogun/lib/Signal.h> namespace shogun { double compute_regularizer(double* w, double lambda, double lambda2, int n_vecs, int n_feats, int n_blocks, const slep_options& options) { double regularizer = 0.0; switch (options.mode) { case MULTITASK_GROUP: { for (int i=0; i<n_feats; i++) { double w_row_norm = 0.0; for (int t=0; t<n_blocks; t++) w_row_norm += CMath::pow(w[i+t*n_feats],options.q); regularizer += CMath::pow(w_row_norm,1.0/options.q); } regularizer *= lambda; } break; case MULTITASK_TREE: { for (int i=0; i<n_feats; i++) { double tree_norm = 0.0; if (options.general) tree_norm = general_treeNorm(w+i, n_blocks, n_blocks, options.G, options.ind_t, options.n_nodes); else tree_norm = treeNorm(w+i, n_blocks, n_blocks, options.ind_t, options.n_nodes); regularizer += tree_norm; } regularizer *= lambda; } break; case FEATURE_GROUP: { for (int t=0; t<n_blocks; t++) { double group_qpow_sum = 0.0; int group_ind_start = options.ind[t]; int group_ind_end = options.ind[t+1]; for (int i=group_ind_start; i<group_ind_end; i++) group_qpow_sum += CMath::pow(w[i], options.q); regularizer += options.gWeight[t]*CMath::pow(group_qpow_sum, 1.0/options.q); } regularizer *= lambda; } break; case FEATURE_TREE: { if (options.general) regularizer = general_treeNorm(w, 1, n_feats, options.G, options.ind_t, options.n_nodes); else regularizer = treeNorm(w, 1, n_feats, options.ind_t, options.n_nodes); regularizer *= lambda; } break; case PLAIN: { for (int i=0; i<n_feats; i++) regularizer += CMath::abs(w[i]); regularizer *= lambda; } break; case FUSED: { double l1 = 0.0; for (int i=0; i<n_feats; i++) l1 += CMath::abs(w[i]); regularizer += lambda*l1; double fuse = 0.0; for (int i=1; i<n_feats; i++) fuse += CMath::abs(w[i]-w[i-1]); regularizer += lambda2*fuse; } break; default: SG_SERROR("WHOA?\n"); } return regularizer; }; double compute_lambda( double* ATx, double z, CDotFeatures* features, double* y, int n_vecs, int n_feats, int n_blocks, const slep_options& options) { double lambda_max = 0.0; if (z<0 || z>1) SG_SERROR("z is not in range [0,1]"); double q_bar = 0.0; if (options.q==1) q_bar = CMath::ALMOST_INFTY; else if (options.q>1e6) q_bar = 1; else q_bar = options.q/(options.q-1); SG_SDEBUG("q bar = %f \n",q_bar); switch (options.mode) { case MULTITASK_GROUP: case MULTITASK_TREE: { for (int t=0; t<n_blocks; t++) { SGVector<index_t> task_idx = options.tasks_indices[t]; int n_vecs_task = task_idx.vlen; switch (options.loss) { case LOGISTIC: { double b = 0.0; int m1 = 0, m2 = 0; for (int i=0; i<n_vecs_task; i++) { if (y[task_idx[i]]>0) m1++; else m2++; } for (int i=0; i<n_vecs_task; i++) { if (y[task_idx[i]]>0) b = double(m1)/(m1+m2); else b = -double(m2)/(m1+m2); features->add_to_dense_vec(b,task_idx[i],ATx+t*n_feats,n_feats); } } break; case LEAST_SQUARES: { for (int i=0; i<n_vecs_task; i++) features->add_to_dense_vec(y[task_idx[i]],task_idx[i],ATx+t*n_feats,n_feats); } } } } break; case FEATURE_GROUP: case FEATURE_TREE: case PLAIN: case FUSED: { switch (options.loss) { case LOGISTIC: { int m1 = 0, m2 = 0; double b = 0.0; for (int i=0; i<n_vecs; i++) y[i]>0 ? m1++ : m2++; SG_SDEBUG("# pos = %d , # neg = %d\n",m1,m2); for (int i=0; i<n_vecs; i++) { y[i]>0 ? b=double(m2) / CMath::sq(n_vecs) : b=-double(m1) / CMath::sq(n_vecs); features->add_to_dense_vec(b,i,ATx,n_feats); } } break; case LEAST_SQUARES: { for (int i=0; i<n_vecs; i++) features->add_to_dense_vec(y[i],i,ATx,n_feats); } break; } } break; } switch (options.mode) { case MULTITASK_GROUP: { for (int i=0; i<n_feats; i++) { double sum = 0.0; for (int t=0; t<n_blocks; t++) sum += CMath::pow(fabs(ATx[t*n_feats+i]),q_bar); lambda_max = CMath::max(lambda_max, CMath::pow(sum,1.0/q_bar)); } if (options.loss==LOGISTIC) lambda_max /= n_vecs; } break; case MULTITASK_TREE: { if (options.general) lambda_max = general_findLambdaMax_mt(ATx, n_feats, n_blocks, options.G, options.ind_t, options.n_nodes); else lambda_max = findLambdaMax_mt(ATx, n_feats, n_blocks, options.ind_t, options.n_nodes); lambda_max /= n_vecs*n_blocks; } break; case FEATURE_GROUP: { for (int t=0; t<n_blocks; t++) { int group_ind_start = options.ind[t]; int group_ind_end = options.ind[t+1]; double sum = 0.0; for (int i=group_ind_start; i<group_ind_end; i++) sum += CMath::pow(fabs(ATx[i]),q_bar); sum = CMath::pow(sum, 1.0/q_bar); sum /= options.gWeight[t]; if (sum>lambda_max) lambda_max = sum; } } break; case FEATURE_TREE: { if (options.general) lambda_max = general_findLambdaMax(ATx, n_feats, options.G, options.ind_t, options.n_nodes); else lambda_max = findLambdaMax(ATx, n_feats, options.ind_t, options.n_nodes); } break; case PLAIN: case FUSED: { double max = 0.0; for (int i=0; i<n_feats; i++) { if (CMath::abs(ATx[i]) > max) max = CMath::abs(ATx[i]); } lambda_max = max; } break; } SG_SINFO("Computed lambda = %f\n",z*lambda_max); return z*lambda_max; } void projection(double* w, double* v, int n_feats, int n_blocks, double lambda, double lambda2, double L, double* z, double* z0, const slep_options& options) { switch (options.mode) { case MULTITASK_GROUP: eppMatrix(w, v, n_feats, n_blocks, lambda/L, options.q); break; case MULTITASK_TREE: if (options.general) general_altra_mt(w, v, n_feats, n_blocks, options.G, options.ind_t, options.n_nodes, lambda/L); else altra_mt(w, v, n_feats, n_blocks, options.ind_t, options.n_nodes, lambda/L); break; case FEATURE_GROUP: eppVector(w, v, options.ind, n_blocks, n_feats, options.gWeight, lambda/L, CMath::max(options.q,1e6)); break; case FEATURE_TREE: if (options.general) general_altra(w, v, n_feats, options.G, options.ind_t, options.n_nodes, lambda/L); else altra(w, v, n_feats, options.ind_t, options.n_nodes, lambda/L); break; case PLAIN: for (int i=0; i<n_feats; i++) w[i] = CMath::sign(v[i])*CMath::max(0.0,CMath::abs(v[i])-lambda/L); break; case FUSED: flsa(w,z,NULL,v,z0,lambda/L,lambda2/L,n_feats,1000,1e-8,1,6); for (int i=0; i<n_feats; i++) z0[i] = z[i]; break; } } double search_point_gradient_and_objective(CDotFeatures* features, double* ATx, double* As, double* sc, double* y, int n_vecs, int n_feats, int n_tasks, double* g, double* gc, const slep_options& options) { double fun_s = 0.0; //SG_SDEBUG("As=%f\n", SGVector<float64_t>::dot(As,As,n_vecs)); //SG_SDEBUG("sc=%f\n", SGVector<float64_t>::dot(sc,sc,n_tasks)); switch (options.mode) { case MULTITASK_GROUP: case MULTITASK_TREE: for (int t=0; t<n_tasks; t++) { SGVector<index_t> task_idx = options.tasks_indices[t]; int n_vecs_task = task_idx.vlen; switch (options.loss) { case LOGISTIC: gc[t] = 0.0; for (int i=0; i<n_vecs_task; i++) { double aa = -y[task_idx[i]]*(As[task_idx[i]]+sc[t]); double bb = CMath::max(aa,0.0); fun_s += (CMath::log(CMath::exp(-bb) + CMath::exp(aa-bb)) + bb)/ n_vecs; double prob = 1.0/(1.0+CMath::exp(aa)); double b = -y[task_idx[i]]*(1.0-prob) / n_vecs; gc[t] += b; features->add_to_dense_vec(b,task_idx[i],g+t*n_feats,n_feats); } break; case LEAST_SQUARES: for (int i=0; i<n_feats*n_tasks; i++) g[i] = -ATx[i]; for (int i=0; i<n_vecs_task; i++) features->add_to_dense_vec(As[task_idx[i]],task_idx[i],g+t*n_feats,n_feats); break; } } break; case FEATURE_GROUP: case FEATURE_TREE: case PLAIN: case FUSED: switch (options.loss) { case LOGISTIC: gc[0] = 0.0; for (int i=0; i<n_vecs; i++) { double aa = -y[i]*(As[i]+sc[0]); double bb = CMath::max(aa,0.0); fun_s += (CMath::log(CMath::exp(-bb) + CMath::exp(aa-bb)) + bb); double prob = 1.0/(1.0+CMath::exp(aa)); double b = -y[i]*(1.0-prob) / n_vecs; gc[0] += b; features->add_to_dense_vec(b,i,g,n_feats); } fun_s /= n_vecs; break; case LEAST_SQUARES: for (int i=0; i<n_feats; i++) g[i] = -ATx[i]; for (int i=0; i<n_vecs; i++) features->add_to_dense_vec(As[i],i,g,n_feats); break; } break; } //SG_SDEBUG("G=%f\n", SGVector<float64_t>::dot(g,g,n_feats*n_tasks)); return fun_s; } slep_result_t slep_solver( CDotFeatures* features, double* y, double z, const slep_options& options) { int i,t; int n_feats = features->get_dim_feature_space(); int n_vecs = features->get_num_vectors(); double lambda, beta; double funcp = 0.0, func = 0.0; int n_blocks = 0; int n_tasks = 0; switch (options.mode) { case MULTITASK_GROUP: case MULTITASK_TREE: n_tasks = options.n_tasks; n_blocks = options.n_tasks; break; case FEATURE_GROUP: case FEATURE_TREE: n_tasks = 1; n_blocks = options.n_feature_blocks; break; case PLAIN: case FUSED: n_tasks = 1; n_blocks = 1; break; } SG_SDEBUG("n_tasks = %d, n_blocks = %d\n",n_tasks,n_blocks); SG_SDEBUG("n_nodes = %d\n",options.n_nodes); int iter = 1; bool done = false; bool gradient_break = false; double rsL2 = options.rsL2; double* ATx = SG_CALLOC(double, n_feats*n_tasks); if (options.regularization!=0) { lambda = compute_lambda(ATx, z, features, y, n_vecs, n_feats, n_blocks, options); rsL2*= lambda; } else lambda = z; double lambda2 = 0.0; SGMatrix<double> w(n_feats,n_tasks); w.zero(); SGVector<double> c(n_blocks); c.zero(); if (options.last_result) { w = options.last_result->w; c = options.last_result->c; } double* s = SG_CALLOC(double, n_feats*n_tasks); double* sc = SG_CALLOC(double, n_tasks); double* g = SG_CALLOC(double, n_feats*n_tasks); double* v = SG_CALLOC(double, n_feats*n_tasks); double* z_flsa = SG_CALLOC(double, n_feats); double* z0_flsa = SG_CALLOC(double, n_feats); double* Aw = SG_CALLOC(double, n_vecs); switch (options.mode) { case MULTITASK_GROUP: case MULTITASK_TREE: { for (t=0; t<n_blocks; t++) { SGVector<index_t> task_idx = options.tasks_indices[t]; //task_idx.display_vector("task"); int n_vecs_task = task_idx.vlen; for (i=0; i<n_vecs_task; i++) Aw[task_idx[i]] = features->dense_dot(task_idx[i],w.matrix+t*n_feats,n_feats); } } break; case FEATURE_GROUP: case FEATURE_TREE: case PLAIN: case FUSED: { for (i=0; i<n_vecs; i++) Aw[i] = features->dense_dot(i,w.matrix,n_feats); } break; } double* Av = SG_MALLOC(double, n_vecs); double* As = SG_MALLOC(double, n_vecs); double L = 1.0/n_vecs; if (options.mode==FUSED) L += rsL2; double* wp = SG_CALLOC(double, n_feats*n_tasks); for (i=0; i<n_feats*n_tasks; i++) wp[i] = w[i]; double* Awp = SG_MALLOC(double, n_vecs); for (i=0; i<n_vecs; i++) Awp[i] = Aw[i]; double* wwp = SG_CALLOC(double, n_feats*n_tasks); double* cp = SG_MALLOC(double, n_tasks); for (t=0; t<n_tasks; t++) cp[t] = c[t]; double* ccp = SG_CALLOC(double, n_tasks); double* gc = SG_MALLOC(double, n_tasks); double alphap = 0.0, alpha = 1.0; double fun_x = 0.0; while (!done && iter <= options.max_iter && !CSignal::cancel_computations()) { beta = (alphap-1.0)/alpha; for (i=0; i<n_feats*n_tasks; i++) s[i] = w[i] + beta*wwp[i]; for (t=0; t<n_tasks; t++) sc[t] = c[t] + beta*ccp[t]; for (i=0; i<n_vecs; i++) As[i] = Aw[i] + beta*(Aw[i]-Awp[i]); for (i=0; i<n_tasks*n_feats; i++) g[i] = 0.0; double fun_s = search_point_gradient_and_objective(features, ATx, As, sc, y, n_vecs, n_feats, n_tasks, g, gc, options); //SG_SDEBUG("fun_s = %f\n", fun_s); if (options.mode==PLAIN || options.mode==FUSED) fun_s += rsL2/2 * SGVector<float64_t>::dot(w.matrix,w.matrix,n_feats); for (i=0; i<n_feats*n_tasks; i++) wp[i] = w[i]; for (t=0; t<n_tasks; t++) cp[t] = c[t]; for (i=0; i<n_vecs; i++) Awp[i] = Aw[i]; int inner_iter = 1; while (inner_iter <= 1000) { for (i=0; i<n_feats*n_tasks; i++) v[i] = s[i] - g[i]*(1.0/L); for (t=0; t<n_tasks; t++) c[t] = sc[t] - gc[t]*(1.0/L); projection(w.matrix,v,n_feats,n_blocks,lambda,lambda2,L,z_flsa,z0_flsa,options); for (i=0; i<n_feats*n_tasks; i++) v[i] = w[i] - s[i]; fun_x = 0.0; switch (options.mode) { case MULTITASK_GROUP: case MULTITASK_TREE: for (t=0; t<n_blocks; t++) { SGVector<index_t> task_idx = options.tasks_indices[t]; int n_vecs_task = task_idx.vlen; for (i=0; i<n_vecs_task; i++) { Aw[task_idx[i]] = features->dense_dot(task_idx[i],w.matrix+t*n_feats,n_feats); if (options.loss==LOGISTIC) { double aa = -y[task_idx[i]]*(Aw[task_idx[i]]+c[t]); double bb = CMath::max(aa,0.0); fun_x += (CMath::log(CMath::exp(-bb) + CMath::exp(aa-bb)) + bb); } } } break; case FEATURE_GROUP: case FEATURE_TREE: case PLAIN: case FUSED: for (i=0; i<n_vecs; i++) { Aw[i] = features->dense_dot(i, w.matrix, n_feats); if (options.loss==LOGISTIC) { double aa = -y[i]*(Aw[i]+c[0]); double bb = CMath::max(aa,0.0); fun_x += (CMath::log(CMath::exp(-bb) + CMath::exp(aa-bb)) + bb); } } break; } if (options.loss==LOGISTIC) fun_x /= n_vecs; if (options.mode==PLAIN || options.mode==FUSED) fun_x += rsL2/2 * SGVector<float64_t>::dot(w.matrix,w.matrix,n_feats); double l_sum = 0.0, r_sum = 0.0; switch (options.loss) { case LOGISTIC: r_sum = SGVector<float64_t>::dot(v,v,n_feats*n_tasks); l_sum = fun_x - fun_s - SGVector<float64_t>::dot(v,g,n_feats*n_tasks); for (t=0; t<n_tasks; t++) { r_sum += CMath::sq(c[t] - sc[t]); l_sum -= (c[t] - sc[t])*gc[t]; } r_sum /= 2.0; break; case LEAST_SQUARES: r_sum = SGVector<float64_t>::dot(v,v,n_feats*n_tasks); for (i=0; i<n_vecs; i++) l_sum += CMath::sq(Aw[i]-As[i]); break; } if (r_sum <= 1e-20) { gradient_break = true; break; } if (l_sum <= r_sum*L) break; else L = CMath::max(2*L, l_sum/r_sum); inner_iter++; } alphap = alpha; alpha = 0.5*(1+CMath::sqrt(4*alpha*alpha+1)); for (i=0; i<n_feats*n_tasks; i++) wwp[i] = w[i] - wp[i]; for (t=0; t<n_tasks; t++) ccp[t] = c[t] - cp[t]; double regularizer = compute_regularizer(w.matrix, lambda, lambda2, n_vecs, n_feats, n_blocks, options); funcp = func; if (options.loss==LOGISTIC) { func = fun_x + regularizer; } if (options.loss==LEAST_SQUARES) { func = regularizer; for (i=0; i<n_vecs; i++) func += CMath::sq(Aw[i] - y[i]); } //SG_SDEBUG("Obj = %f + %f * %f = %f \n",fun_x, lambda, regularizer, func); if (gradient_break) { SG_SINFO("Gradient norm is less than 1e-20\n"); break; } double norm_wp, norm_wwp; double step; switch (options.termination) { case 0: if (iter>=2) { step = CMath::abs(func-funcp); if (step <= options.tolerance) { SG_SINFO("Objective changes less than tolerance\n"); done = true; } } break; case 1: if (iter>=2) { step = CMath::abs(func-funcp); if (step <= step*options.tolerance) { SG_SINFO("Objective changes relatively less than tolerance\n"); done = true; } } break; case 2: if (func <= options.tolerance) { SG_SINFO("Objective is less than tolerance\n"); done = true; } break; case 3: norm_wwp = CMath::sqrt(SGVector<float64_t>::dot(wwp,wwp,n_feats*n_tasks)); if (norm_wwp <= options.tolerance) done = true; break; case 4: norm_wp = CMath::sqrt(SGVector<float64_t>::dot(wp,wp,n_feats*n_tasks)); norm_wwp = CMath::sqrt(SGVector<float64_t>::dot(wwp,wwp,n_feats*n_tasks)); if (norm_wwp <= options.tolerance*CMath::max(norm_wp,1.0)) done = true; break; default: done = true; } iter++; } SG_SINFO("Finished %d iterations, objective = %f\n", iter, func); cleanup: SG_FREE(ATx); SG_FREE(wp); SG_FREE(wwp); SG_FREE(s); SG_FREE(sc); SG_FREE(cp); SG_FREE(ccp); SG_FREE(g); SG_FREE(v); SG_FREE(Aw); SG_FREE(Awp); SG_FREE(Av); SG_FREE(As); SG_FREE(gc); SG_FREE(z_flsa); SG_FREE(z0_flsa); return slep_result_t(w,c); }; };
/* * Copyright 2020 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/d3d/GrD3DGpu.h" #include "include/gpu/GrBackendSurface.h" #include "include/gpu/d3d/GrD3DBackendContext.h" #include "src/core/SkConvertPixels.h" #include "src/core/SkMipmap.h" #include "src/gpu/GrBackendUtils.h" #include "src/gpu/GrDataUtils.h" #include "src/gpu/GrTexture.h" #include "src/gpu/GrThreadSafePipelineBuilder.h" #include "src/gpu/d3d/GrD3DAMDMemoryAllocator.h" #include "src/gpu/d3d/GrD3DAttachment.h" #include "src/gpu/d3d/GrD3DBuffer.h" #include "src/gpu/d3d/GrD3DCaps.h" #include "src/gpu/d3d/GrD3DOpsRenderPass.h" #include "src/gpu/d3d/GrD3DSemaphore.h" #include "src/gpu/d3d/GrD3DTexture.h" #include "src/gpu/d3d/GrD3DTextureRenderTarget.h" #include "src/gpu/d3d/GrD3DUtil.h" #include "src/sksl/SkSLCompiler.h" #if GR_TEST_UTILS #include <DXProgrammableCapture.h> #endif GrThreadSafePipelineBuilder* GrD3DGpu::pipelineBuilder() { return nullptr; } sk_sp<GrThreadSafePipelineBuilder> GrD3DGpu::refPipelineBuilder() { return nullptr; } sk_sp<GrGpu> GrD3DGpu::Make(const GrD3DBackendContext& backendContext, const GrContextOptions& contextOptions, GrDirectContext* direct) { sk_sp<GrD3DMemoryAllocator> memoryAllocator = backendContext.fMemoryAllocator; if (!memoryAllocator) { // We were not given a memory allocator at creation memoryAllocator = GrD3DAMDMemoryAllocator::Make( backendContext.fAdapter.get(), backendContext.fDevice.get()); } if (!memoryAllocator) { SkDEBUGFAIL("No supplied Direct3D memory allocator and unable to create one internally."); return nullptr; } return sk_sp<GrGpu>(new GrD3DGpu(direct, contextOptions, backendContext, memoryAllocator)); } // This constant determines how many OutstandingCommandLists are allocated together as a block in // the deque. As such it needs to balance allocating too much memory vs. incurring // allocation/deallocation thrashing. It should roughly correspond to the max number of outstanding // command lists we expect to see. static const int kDefaultOutstandingAllocCnt = 8; // constants have to be aligned to 256 constexpr int kConstantAlignment = 256; GrD3DGpu::GrD3DGpu(GrDirectContext* direct, const GrContextOptions& contextOptions, const GrD3DBackendContext& backendContext, sk_sp<GrD3DMemoryAllocator> allocator) : INHERITED(direct) , fDevice(backendContext.fDevice) , fQueue(backendContext.fQueue) , fMemoryAllocator(std::move(allocator)) , fResourceProvider(this) , fStagingBufferManager(this) , fConstantsRingBuffer(this, 128 * 1024, kConstantAlignment, GrGpuBufferType::kVertex) , fOutstandingCommandLists(sizeof(OutstandingCommandList), kDefaultOutstandingAllocCnt) { this->initCapsAndCompiler(sk_make_sp<GrD3DCaps>(contextOptions, backendContext.fAdapter.get(), backendContext.fDevice.get())); fCurrentDirectCommandList = fResourceProvider.findOrCreateDirectCommandList(); SkASSERT(fCurrentDirectCommandList); SkASSERT(fCurrentFenceValue == 0); GR_D3D_CALL_ERRCHECK(fDevice->CreateFence(fCurrentFenceValue, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fFence))); #if GR_TEST_UTILS HRESULT getAnalysis = DXGIGetDebugInterface1(0, IID_PPV_ARGS(&fGraphicsAnalysis)); if (FAILED(getAnalysis)) { fGraphicsAnalysis = nullptr; } #endif } GrD3DGpu::~GrD3DGpu() { this->destroyResources(); } void GrD3DGpu::destroyResources() { if (fCurrentDirectCommandList) { fCurrentDirectCommandList->close(); fCurrentDirectCommandList->reset(); } // We need to make sure everything has finished on the queue. this->waitForQueueCompletion(); SkDEBUGCODE(uint64_t fenceValue = fFence->GetCompletedValue();) // We used a placement new for each object in fOutstandingCommandLists, so we're responsible // for calling the destructor on each of them as well. while (!fOutstandingCommandLists.empty()) { OutstandingCommandList* list = (OutstandingCommandList*)fOutstandingCommandLists.front(); SkASSERT(list->fFenceValue <= fenceValue); // No reason to recycle the command lists since we are destroying all resources anyways. list->~OutstandingCommandList(); fOutstandingCommandLists.pop_front(); } fStagingBufferManager.reset(); fResourceProvider.destroyResources(); } GrOpsRenderPass* GrD3DGpu::onGetOpsRenderPass( GrRenderTarget* rt, bool /*useMSAASurface*/, GrAttachment*, GrSurfaceOrigin origin, const SkIRect& bounds, const GrOpsRenderPass::LoadAndStoreInfo& colorInfo, const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilInfo, const SkTArray<GrSurfaceProxy*, true>& sampledProxies, GrXferBarrierFlags renderPassXferBarriers) { if (!fCachedOpsRenderPass) { fCachedOpsRenderPass.reset(new GrD3DOpsRenderPass(this)); } if (!fCachedOpsRenderPass->set(rt, origin, bounds, colorInfo, stencilInfo, sampledProxies)) { return nullptr; } return fCachedOpsRenderPass.get(); } bool GrD3DGpu::submitDirectCommandList(SyncQueue sync) { SkASSERT(fCurrentDirectCommandList); fResourceProvider.prepForSubmit(); for (int i = 0; i < fMipmapCPUDescriptors.count(); ++i) { fResourceProvider.recycleShaderView(fMipmapCPUDescriptors[i]); } fMipmapCPUDescriptors.reset(); GrD3DDirectCommandList::SubmitResult result = fCurrentDirectCommandList->submit(fQueue.get()); if (result == GrD3DDirectCommandList::SubmitResult::kFailure) { return false; } else if (result == GrD3DDirectCommandList::SubmitResult::kNoWork) { if (sync == SyncQueue::kForce) { this->waitForQueueCompletion(); this->checkForFinishedCommandLists(); } return true; } // We just submitted the command list so make sure all GrD3DPipelineState's mark their cached // uniform data as dirty. fResourceProvider.markPipelineStateUniformsDirty(); GrFence fence = this->insertFence(); new (fOutstandingCommandLists.push_back()) OutstandingCommandList( std::move(fCurrentDirectCommandList), fence); if (sync == SyncQueue::kForce) { this->waitForQueueCompletion(); } fCurrentDirectCommandList = fResourceProvider.findOrCreateDirectCommandList(); // This should be done after we have a new command list in case the freeing of any resources // held by a finished command list causes us send a new command to the gpu (like changing the // resource state. this->checkForFinishedCommandLists(); SkASSERT(fCurrentDirectCommandList); return true; } void GrD3DGpu::checkForFinishedCommandLists() { uint64_t currentFenceValue = fFence->GetCompletedValue(); // Iterate over all the outstanding command lists to see if any have finished. The commands // lists are in order from oldest to newest, so we start at the front to check if their fence // value is less than the last signaled value. If so we pop it off and move onto the next. // Repeat till we find a command list that has not finished yet (and all others afterwards are // also guaranteed to not have finished). OutstandingCommandList* front = (OutstandingCommandList*)fOutstandingCommandLists.front(); while (front && front->fFenceValue <= currentFenceValue) { std::unique_ptr<GrD3DDirectCommandList> currList(std::move(front->fCommandList)); // Since we used placement new we are responsible for calling the destructor manually. front->~OutstandingCommandList(); fOutstandingCommandLists.pop_front(); fResourceProvider.recycleDirectCommandList(std::move(currList)); front = (OutstandingCommandList*)fOutstandingCommandLists.front(); } } void GrD3DGpu::waitForQueueCompletion() { if (fFence->GetCompletedValue() < fCurrentFenceValue) { HANDLE fenceEvent; fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); SkASSERT(fenceEvent); GR_D3D_CALL_ERRCHECK(fFence->SetEventOnCompletion(fCurrentFenceValue, fenceEvent)); WaitForSingleObject(fenceEvent, INFINITE); CloseHandle(fenceEvent); } } void GrD3DGpu::submit(GrOpsRenderPass* renderPass) { SkASSERT(fCachedOpsRenderPass.get() == renderPass); fCachedOpsRenderPass->submit(); fCachedOpsRenderPass.reset(); } void GrD3DGpu::endRenderPass(GrRenderTarget* target, GrSurfaceOrigin origin, const SkIRect& bounds) { this->didWriteToSurface(target, origin, &bounds); } void GrD3DGpu::addFinishedProc(GrGpuFinishedProc finishedProc, GrGpuFinishedContext finishedContext) { SkASSERT(finishedProc); this->addFinishedCallback(GrRefCntedCallback::Make(finishedProc, finishedContext)); } void GrD3DGpu::addFinishedCallback(sk_sp<GrRefCntedCallback> finishedCallback) { SkASSERT(finishedCallback); // Besides the current command list, we also add the finishedCallback to the newest outstanding // command list. Our contract for calling the proc is that all previous submitted command lists // have finished when we call it. However, if our current command list has no work when it is // flushed it will drop its ref to the callback immediately. But the previous work may not have // finished. It is safe to only add the proc to the newest outstanding commandlist cause that // must finish after all previously submitted command lists. OutstandingCommandList* back = (OutstandingCommandList*)fOutstandingCommandLists.back(); if (back) { back->fCommandList->addFinishedCallback(finishedCallback); } fCurrentDirectCommandList->addFinishedCallback(std::move(finishedCallback)); } sk_sp<GrD3DTexture> GrD3DGpu::createD3DTexture(SkISize dimensions, DXGI_FORMAT dxgiFormat, GrRenderable renderable, int renderTargetSampleCnt, SkBudgeted budgeted, GrProtected isProtected, int mipLevelCount, GrMipmapStatus mipmapStatus) { D3D12_RESOURCE_FLAGS usageFlags = D3D12_RESOURCE_FLAG_NONE; if (renderable == GrRenderable::kYes) { usageFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; } // This desc refers to a texture that will be read by the client. Thus even if msaa is // requested, this describes the resolved texture. Therefore we always have samples set // to 1. SkASSERT(mipLevelCount > 0); D3D12_RESOURCE_DESC resourceDesc = {}; resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; // TODO: will use 4MB alignment for MSAA textures and 64KB for everything else // might want to manually set alignment to 4KB for smaller textures resourceDesc.Alignment = 0; resourceDesc.Width = dimensions.fWidth; resourceDesc.Height = dimensions.fHeight; resourceDesc.DepthOrArraySize = 1; resourceDesc.MipLevels = mipLevelCount; resourceDesc.Format = dxgiFormat; resourceDesc.SampleDesc.Count = 1; resourceDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN; resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // use driver-selected swizzle resourceDesc.Flags = usageFlags; if (renderable == GrRenderable::kYes) { return GrD3DTextureRenderTarget::MakeNewTextureRenderTarget( this, budgeted, dimensions, renderTargetSampleCnt, resourceDesc, isProtected, mipmapStatus); } else { return GrD3DTexture::MakeNewTexture(this, budgeted, dimensions, resourceDesc, isProtected, mipmapStatus); } } sk_sp<GrTexture> GrD3DGpu::onCreateTexture(SkISize dimensions, const GrBackendFormat& format, GrRenderable renderable, int renderTargetSampleCnt, SkBudgeted budgeted, GrProtected isProtected, int mipLevelCount, uint32_t levelClearMask) { DXGI_FORMAT dxgiFormat; SkAssertResult(format.asDxgiFormat(&dxgiFormat)); SkASSERT(!GrDxgiFormatIsCompressed(dxgiFormat)); GrMipmapStatus mipmapStatus = mipLevelCount > 1 ? GrMipmapStatus::kDirty : GrMipmapStatus::kNotAllocated; sk_sp<GrD3DTexture> tex = this->createD3DTexture(dimensions, dxgiFormat, renderable, renderTargetSampleCnt, budgeted, isProtected, mipLevelCount, mipmapStatus); if (!tex) { return nullptr; } if (levelClearMask) { // TODO } return std::move(tex); } static void copy_compressed_data(char* mapPtr, DXGI_FORMAT dxgiFormat, D3D12_PLACED_SUBRESOURCE_FOOTPRINT* placedFootprints, UINT* numRows, UINT64* rowSizeInBytes, const void* compressedData, int numMipLevels) { SkASSERT(compressedData && numMipLevels); SkASSERT(GrDxgiFormatIsCompressed(dxgiFormat)); SkASSERT(mapPtr); const char* src = static_cast<const char*>(compressedData); for (int currentMipLevel = 0; currentMipLevel < numMipLevels; currentMipLevel++) { // copy data into the buffer, skipping any trailing bytes char* dst = mapPtr + placedFootprints[currentMipLevel].Offset; SkRectMemcpy(dst, placedFootprints[currentMipLevel].Footprint.RowPitch, src, rowSizeInBytes[currentMipLevel], rowSizeInBytes[currentMipLevel], numRows[currentMipLevel]); src += numRows[currentMipLevel] * rowSizeInBytes[currentMipLevel]; } } sk_sp<GrTexture> GrD3DGpu::onCreateCompressedTexture(SkISize dimensions, const GrBackendFormat& format, SkBudgeted budgeted, GrMipmapped mipMapped, GrProtected isProtected, const void* data, size_t dataSize) { DXGI_FORMAT dxgiFormat; SkAssertResult(format.asDxgiFormat(&dxgiFormat)); SkASSERT(GrDxgiFormatIsCompressed(dxgiFormat)); SkDEBUGCODE(SkImage::CompressionType compression = GrBackendFormatToCompressionType(format)); SkASSERT(dataSize == SkCompressedFormatDataSize(compression, dimensions, mipMapped == GrMipmapped::kYes)); int mipLevelCount = 1; if (mipMapped == GrMipmapped::kYes) { mipLevelCount = SkMipmap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1; } GrMipmapStatus mipmapStatus = mipLevelCount > 1 ? GrMipmapStatus::kValid : GrMipmapStatus::kNotAllocated; sk_sp<GrD3DTexture> d3dTex = this->createD3DTexture(dimensions, dxgiFormat, GrRenderable::kNo, 1, budgeted, isProtected, mipLevelCount, mipmapStatus); if (!d3dTex) { return nullptr; } ID3D12Resource* d3dResource = d3dTex->d3dResource(); SkASSERT(d3dResource); D3D12_RESOURCE_DESC desc = d3dResource->GetDesc(); // Either upload only the first miplevel or all miplevels SkASSERT(1 == mipLevelCount || mipLevelCount == (int)desc.MipLevels); SkAutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount); SkAutoTMalloc<UINT> numRows(mipLevelCount); SkAutoTMalloc<UINT64> rowSizeInBytes(mipLevelCount); UINT64 combinedBufferSize; // We reset the width and height in the description to match our subrectangle size // so we don't end up allocating more space than we need. desc.Width = dimensions.width(); desc.Height = dimensions.height(); fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(), numRows.get(), rowSizeInBytes.get(), &combinedBufferSize); SkASSERT(combinedBufferSize); GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice( combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); if (!slice.fBuffer) { return false; } char* bufferData = (char*)slice.fOffsetMapPtr; copy_compressed_data(bufferData, desc.Format, placedFootprints.get(), numRows.get(), rowSizeInBytes.get(), data, mipLevelCount); // Update the offsets in the footprints to be relative to the slice's offset for (int i = 0; i < mipLevelCount; ++i) { placedFootprints[i].Offset += slice.fOffset; } ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource(); fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer, d3dTex.get(), mipLevelCount, placedFootprints.get(), 0, 0); return std::move(d3dTex); } static int get_surface_sample_cnt(GrSurface* surf) { if (const GrRenderTarget* rt = surf->asRenderTarget()) { return rt->numSamples(); } return 0; } bool GrD3DGpu::onCopySurface(GrSurface* dst, GrSurface* src, const SkIRect& srcRect, const SkIPoint& dstPoint) { if (src->isProtected() && !dst->isProtected()) { SkDebugf("Can't copy from protected memory to non-protected"); return false; } int dstSampleCnt = get_surface_sample_cnt(dst); int srcSampleCnt = get_surface_sample_cnt(src); GrD3DTextureResource* dstTexResource; GrD3DTextureResource* srcTexResource; GrRenderTarget* dstRT = dst->asRenderTarget(); if (dstRT) { GrD3DRenderTarget* d3dRT = static_cast<GrD3DRenderTarget*>(dstRT); dstTexResource = d3dRT->numSamples() > 1 ? d3dRT->msaaTextureResource() : d3dRT; } else { SkASSERT(dst->asTexture()); dstTexResource = static_cast<GrD3DTexture*>(dst->asTexture()); } GrRenderTarget* srcRT = src->asRenderTarget(); if (srcRT) { GrD3DRenderTarget* d3dRT = static_cast<GrD3DRenderTarget*>(srcRT); srcTexResource = d3dRT->numSamples() > 1 ? d3dRT->msaaTextureResource() : d3dRT; } else { SkASSERT(src->asTexture()); srcTexResource = static_cast<GrD3DTexture*>(src->asTexture()); } DXGI_FORMAT dstFormat = dstTexResource->dxgiFormat(); DXGI_FORMAT srcFormat = srcTexResource->dxgiFormat(); if (this->d3dCaps().canCopyAsResolve(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)) { this->copySurfaceAsResolve(dst, src, srcRect, dstPoint); return true; } if (this->d3dCaps().canCopyTexture(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)) { this->copySurfaceAsCopyTexture(dst, src, dstTexResource, srcTexResource, srcRect, dstPoint); return true; } return false; } void GrD3DGpu::copySurfaceAsCopyTexture(GrSurface* dst, GrSurface* src, GrD3DTextureResource* dstResource, GrD3DTextureResource* srcResource, const SkIRect& srcRect, const SkIPoint& dstPoint) { #ifdef SK_DEBUG int dstSampleCnt = get_surface_sample_cnt(dst); int srcSampleCnt = get_surface_sample_cnt(src); DXGI_FORMAT dstFormat = dstResource->dxgiFormat(); DXGI_FORMAT srcFormat; SkAssertResult(dst->backendFormat().asDxgiFormat(&srcFormat)); SkASSERT(this->d3dCaps().canCopyTexture(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)); #endif if (src->isProtected() && !dst->isProtected()) { SkDebugf("Can't copy from protected memory to non-protected"); return; } dstResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); srcResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE); D3D12_TEXTURE_COPY_LOCATION dstLocation = {}; dstLocation.pResource = dstResource->d3dResource(); dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; dstLocation.SubresourceIndex = 0; D3D12_TEXTURE_COPY_LOCATION srcLocation = {}; srcLocation.pResource = srcResource->d3dResource(); srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; srcLocation.SubresourceIndex = 0; D3D12_BOX srcBox = {}; srcBox.left = srcRect.fLeft; srcBox.top = srcRect.fTop; srcBox.right = srcRect.fRight; srcBox.bottom = srcRect.fBottom; srcBox.front = 0; srcBox.back = 1; // TODO: use copyResource if copying full resource and sizes match fCurrentDirectCommandList->copyTextureRegionToTexture(dstResource->resource(), &dstLocation, dstPoint.fX, dstPoint.fY, srcResource->resource(), &srcLocation, &srcBox); SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY, srcRect.width(), srcRect.height()); // The rect is already in device space so we pass in kTopLeft so no flip is done. this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect); } void GrD3DGpu::copySurfaceAsResolve(GrSurface* dst, GrSurface* src, const SkIRect& srcRect, const SkIPoint& dstPoint) { GrD3DRenderTarget* srcRT = static_cast<GrD3DRenderTarget*>(src->asRenderTarget()); SkASSERT(srcRT); this->resolveTexture(dst, dstPoint.fX, dstPoint.fY, srcRT, srcRect); SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY, srcRect.width(), srcRect.height()); // The rect is already in device space so we pass in kTopLeft so no flip is done. this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect); } void GrD3DGpu::resolveTexture(GrSurface* dst, int32_t dstX, int32_t dstY, GrD3DRenderTarget* src, const SkIRect& srcIRect) { SkASSERT(dst); SkASSERT(src && src->numSamples() > 1 && src->msaaTextureResource()); D3D12_RECT srcRect = { srcIRect.fLeft, srcIRect.fTop, srcIRect.fRight, srcIRect.fBottom }; GrD3DTextureResource* dstTextureResource; GrRenderTarget* dstRT = dst->asRenderTarget(); if (dstRT) { dstTextureResource = static_cast<GrD3DRenderTarget*>(dstRT); } else { SkASSERT(dst->asTexture()); dstTextureResource = static_cast<GrD3DTexture*>(dst->asTexture()); } dstTextureResource->setResourceState(this, D3D12_RESOURCE_STATE_RESOLVE_DEST); src->msaaTextureResource()->setResourceState(this, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); fCurrentDirectCommandList->resolveSubresourceRegion(dstTextureResource, dstX, dstY, src->msaaTextureResource(), &srcRect); } void GrD3DGpu::onResolveRenderTarget(GrRenderTarget* target, const SkIRect& resolveRect) { SkASSERT(target->numSamples() > 1); GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(target); SkASSERT(rt->msaaTextureResource() && rt != rt->msaaTextureResource()); this->resolveTexture(target, resolveRect.fLeft, resolveRect.fTop, rt, resolveRect); } bool GrD3DGpu::onReadPixels(GrSurface* surface, SkIRect rect, GrColorType surfaceColorType, GrColorType dstColorType, void* buffer, size_t rowBytes) { SkASSERT(surface); if (surfaceColorType != dstColorType) { return false; } GrD3DTextureResource* texResource = nullptr; GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(surface->asRenderTarget()); if (rt) { texResource = rt; } else { texResource = static_cast<GrD3DTexture*>(surface->asTexture()); } if (!texResource) { return false; } D3D12_RESOURCE_DESC desc = texResource->d3dResource()->GetDesc(); D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint; UINT64 transferTotalBytes; fDevice->GetCopyableFootprints(&desc, 0, 1, 0, &placedFootprint, nullptr, nullptr, &transferTotalBytes); SkASSERT(transferTotalBytes); // TODO: implement some way of reusing buffers instead of making a new one every time. sk_sp<GrGpuBuffer> transferBuffer = this->createBuffer(transferTotalBytes, GrGpuBufferType::kXferGpuToCpu, kDynamic_GrAccessPattern); this->readOrTransferPixels(texResource, rect, transferBuffer, placedFootprint); this->submitDirectCommandList(SyncQueue::kForce); // Copy back to CPU buffer size_t bpp = GrColorTypeBytesPerPixel(dstColorType); if (GrDxgiFormatBytesPerBlock(texResource->dxgiFormat()) != bpp) { return false; } size_t tightRowBytes = bpp * rect.width(); const void* mappedMemory = transferBuffer->map(); SkRectMemcpy(buffer, rowBytes, mappedMemory, placedFootprint.Footprint.RowPitch, tightRowBytes, rect.height()); transferBuffer->unmap(); return true; } void GrD3DGpu::readOrTransferPixels(GrD3DTextureResource* texResource, SkIRect rect, sk_sp<GrGpuBuffer> transferBuffer, const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& placedFootprint) { // Set up src location and box D3D12_TEXTURE_COPY_LOCATION srcLocation = {}; srcLocation.pResource = texResource->d3dResource(); SkASSERT(srcLocation.pResource); srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; srcLocation.SubresourceIndex = 0; D3D12_BOX srcBox = {}; srcBox.left = rect.left(); srcBox.top = rect.top(); srcBox.right = rect.right(); srcBox.bottom = rect.bottom(); srcBox.front = 0; srcBox.back = 1; // Set up dst location D3D12_TEXTURE_COPY_LOCATION dstLocation = {}; dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; dstLocation.PlacedFootprint = placedFootprint; GrD3DBuffer* d3dBuf = static_cast<GrD3DBuffer*>(transferBuffer.get()); dstLocation.pResource = d3dBuf->d3dResource(); // Need to change the resource state to COPY_SOURCE in order to download from it texResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE); fCurrentDirectCommandList->copyTextureRegionToBuffer(transferBuffer, &dstLocation, 0, 0, texResource->resource(), &srcLocation, &srcBox); } bool GrD3DGpu::onWritePixels(GrSurface* surface, SkIRect rect, GrColorType surfaceColorType, GrColorType srcColorType, const GrMipLevel texels[], int mipLevelCount, bool prepForTexSampling) { GrD3DTexture* d3dTex = static_cast<GrD3DTexture*>(surface->asTexture()); if (!d3dTex) { return false; } // Make sure we have at least the base level if (!mipLevelCount || !texels[0].fPixels) { return false; } SkASSERT(!GrDxgiFormatIsCompressed(d3dTex->dxgiFormat())); bool success = false; // Need to change the resource state to COPY_DEST in order to upload to it d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); SkASSERT(mipLevelCount <= d3dTex->maxMipmapLevel() + 1); success = this->uploadToTexture(d3dTex, rect, srcColorType, texels, mipLevelCount); if (prepForTexSampling) { d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); } return success; } bool GrD3DGpu::uploadToTexture(GrD3DTexture* tex, SkIRect rect, GrColorType colorType, const GrMipLevel* texels, int mipLevelCount) { SkASSERT(this->caps()->isFormatTexturable(tex->backendFormat())); // The assumption is either that we have no mipmaps, or that our rect is the entire texture SkASSERT(mipLevelCount == 1 || rect == SkIRect::MakeSize(tex->dimensions())); // We assume that if the texture has mip levels, we either upload to all the levels or just the // first. SkASSERT(mipLevelCount == 1 || mipLevelCount == (tex->maxMipmapLevel() + 1)); if (rect.isEmpty()) { return false; } SkASSERT(this->d3dCaps().surfaceSupportsWritePixels(tex)); SkASSERT(this->d3dCaps().areColorTypeAndFormatCompatible(colorType, tex->backendFormat())); ID3D12Resource* d3dResource = tex->d3dResource(); SkASSERT(d3dResource); D3D12_RESOURCE_DESC desc = d3dResource->GetDesc(); // Either upload only the first miplevel or all miplevels SkASSERT(1 == mipLevelCount || mipLevelCount == (int)desc.MipLevels); if (1 == mipLevelCount && !texels[0].fPixels) { return true; // no data to upload } for (int i = 0; i < mipLevelCount; ++i) { // We do not allow any gaps in the mip data if (!texels[i].fPixels) { return false; } } SkAutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount); UINT64 combinedBufferSize; // We reset the width and height in the description to match our subrectangle size // so we don't end up allocating more space than we need. desc.Width = rect.width(); desc.Height = rect.height(); fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(), nullptr, nullptr, &combinedBufferSize); size_t bpp = GrColorTypeBytesPerPixel(colorType); SkASSERT(combinedBufferSize); GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice( combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); if (!slice.fBuffer) { return false; } char* bufferData = (char*)slice.fOffsetMapPtr; int currentWidth = rect.width(); int currentHeight = rect.height(); int layerHeight = tex->height(); for (int currentMipLevel = 0; currentMipLevel < mipLevelCount; currentMipLevel++) { if (texels[currentMipLevel].fPixels) { SkASSERT(1 == mipLevelCount || currentHeight == layerHeight); const size_t trimRowBytes = currentWidth * bpp; const size_t srcRowBytes = texels[currentMipLevel].fRowBytes; char* dst = bufferData + placedFootprints[currentMipLevel].Offset; // copy data into the buffer, skipping any trailing bytes const char* src = (const char*)texels[currentMipLevel].fPixels; SkRectMemcpy(dst, placedFootprints[currentMipLevel].Footprint.RowPitch, src, srcRowBytes, trimRowBytes, currentHeight); } currentWidth = std::max(1, currentWidth / 2); currentHeight = std::max(1, currentHeight / 2); layerHeight = currentHeight; } // Update the offsets in the footprints to be relative to the slice's offset for (int i = 0; i < mipLevelCount; ++i) { placedFootprints[i].Offset += slice.fOffset; } ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource(); fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer, tex, mipLevelCount, placedFootprints.get(), rect.left(), rect.top()); if (mipLevelCount < (int)desc.MipLevels) { tex->markMipmapsDirty(); } return true; } bool GrD3DGpu::onTransferPixelsTo(GrTexture* texture, SkIRect rect, GrColorType surfaceColorType, GrColorType bufferColorType, sk_sp<GrGpuBuffer> transferBuffer, size_t bufferOffset, size_t rowBytes) { if (!this->currentCommandList()) { return false; } if (!transferBuffer) { return false; } size_t bpp = GrColorTypeBytesPerPixel(bufferColorType); if (GrBackendFormatBytesPerPixel(texture->backendFormat()) != bpp) { return false; } // D3D requires offsets for texture transfers to be aligned to this value if (SkToBool(bufferOffset & (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1))) { return false; } GrD3DTexture* d3dTex = static_cast<GrD3DTexture*>(texture); if (!d3dTex) { return false; } SkDEBUGCODE(DXGI_FORMAT format = d3dTex->dxgiFormat()); // Can't transfer compressed data SkASSERT(!GrDxgiFormatIsCompressed(format)); SkASSERT(GrDxgiFormatBytesPerBlock(format) == GrColorTypeBytesPerPixel(bufferColorType)); SkASSERT(SkIRect::MakeSize(texture->dimensions()).contains(rect)); // Set up copy region D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint = {}; ID3D12Resource* d3dResource = d3dTex->d3dResource(); SkASSERT(d3dResource); D3D12_RESOURCE_DESC desc = d3dResource->GetDesc(); desc.Width = rect.width(); desc.Height = rect.height(); UINT64 totalBytes; fDevice->GetCopyableFootprints(&desc, 0, 1, 0, &placedFootprint, nullptr, nullptr, &totalBytes); placedFootprint.Offset = bufferOffset; // Change state of our target so it can be copied to d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); // Copy the buffer to the image. ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(transferBuffer.get())->d3dResource(); fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer, d3dTex, 1, &placedFootprint, rect.left(), rect.top()); this->currentCommandList()->addGrBuffer(std::move(transferBuffer)); d3dTex->markMipmapsDirty(); return true; } bool GrD3DGpu::onTransferPixelsFrom(GrSurface* surface, SkIRect rect, GrColorType surfaceColorType, GrColorType bufferColorType, sk_sp<GrGpuBuffer> transferBuffer, size_t offset) { if (!this->currentCommandList()) { return false; } SkASSERT(surface); SkASSERT(transferBuffer); // TODO //if (fProtectedContext == GrProtected::kYes) { // return false; //} // D3D requires offsets for texture transfers to be aligned to this value if (SkToBool(offset & (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1))) { return false; } GrD3DTextureResource* texResource = nullptr; GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(surface->asRenderTarget()); if (rt) { texResource = rt; } else { texResource = static_cast<GrD3DTexture*>(surface->asTexture()); } if (!texResource) { return false; } SkDEBUGCODE(DXGI_FORMAT format = texResource->dxgiFormat()); SkASSERT(GrDxgiFormatBytesPerBlock(format) == GrColorTypeBytesPerPixel(bufferColorType)); D3D12_RESOURCE_DESC desc = texResource->d3dResource()->GetDesc(); desc.Width = rect.width(); desc.Height = rect.height(); D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint; UINT64 transferTotalBytes; fDevice->GetCopyableFootprints(&desc, 0, 1, offset, &placedFootprint, nullptr, nullptr, &transferTotalBytes); SkASSERT(transferTotalBytes); this->readOrTransferPixels(texResource, rect, transferBuffer, placedFootprint); // TODO: It's not clear how to ensure the transfer is done before we read from the buffer, // other than maybe doing a resource state transition. return true; } static bool check_resource_info(const GrD3DTextureResourceInfo& info) { if (!info.fResource.get()) { return false; } return true; } static bool check_tex_resource_info(const GrD3DCaps& caps, const GrD3DTextureResourceInfo& info) { if (!caps.isFormatTexturable(info.fFormat)) { return false; } // We don't support sampling from multisampled textures. if (info.fSampleCount != 1) { return false; } return true; } static bool check_rt_resource_info(const GrD3DCaps& caps, const GrD3DTextureResourceInfo& info, int sampleCnt) { if (!caps.isFormatRenderable(info.fFormat, sampleCnt)) { return false; } return true; } sk_sp<GrTexture> GrD3DGpu::onWrapBackendTexture(const GrBackendTexture& tex, GrWrapOwnership, GrWrapCacheable wrapType, GrIOType ioType) { GrD3DTextureResourceInfo textureInfo; if (!tex.getD3DTextureResourceInfo(&textureInfo)) { return nullptr; } if (!check_resource_info(textureInfo)) { return nullptr; } if (!check_tex_resource_info(this->d3dCaps(), textureInfo)) { return nullptr; } // TODO: support protected context if (tex.isProtected()) { return nullptr; } sk_sp<GrD3DResourceState> state = tex.getGrD3DResourceState(); SkASSERT(state); return GrD3DTexture::MakeWrappedTexture(this, tex.dimensions(), wrapType, ioType, textureInfo, std::move(state)); } sk_sp<GrTexture> GrD3DGpu::onWrapCompressedBackendTexture(const GrBackendTexture& tex, GrWrapOwnership ownership, GrWrapCacheable wrapType) { return this->onWrapBackendTexture(tex, ownership, wrapType, kRead_GrIOType); } sk_sp<GrTexture> GrD3DGpu::onWrapRenderableBackendTexture(const GrBackendTexture& tex, int sampleCnt, GrWrapOwnership ownership, GrWrapCacheable cacheable) { GrD3DTextureResourceInfo textureInfo; if (!tex.getD3DTextureResourceInfo(&textureInfo)) { return nullptr; } if (!check_resource_info(textureInfo)) { return nullptr; } if (!check_tex_resource_info(this->d3dCaps(), textureInfo)) { return nullptr; } if (!check_rt_resource_info(this->d3dCaps(), textureInfo, sampleCnt)) { return nullptr; } // TODO: support protected context if (tex.isProtected()) { return nullptr; } sampleCnt = this->d3dCaps().getRenderTargetSampleCount(sampleCnt, textureInfo.fFormat); sk_sp<GrD3DResourceState> state = tex.getGrD3DResourceState(); SkASSERT(state); return GrD3DTextureRenderTarget::MakeWrappedTextureRenderTarget(this, tex.dimensions(), sampleCnt, cacheable, textureInfo, std::move(state)); } sk_sp<GrRenderTarget> GrD3DGpu::onWrapBackendRenderTarget(const GrBackendRenderTarget& rt) { GrD3DTextureResourceInfo info; if (!rt.getD3DTextureResourceInfo(&info)) { return nullptr; } if (!check_resource_info(info)) { return nullptr; } if (!check_rt_resource_info(this->d3dCaps(), info, rt.sampleCnt())) { return nullptr; } // TODO: support protected context if (rt.isProtected()) { return nullptr; } sk_sp<GrD3DResourceState> state = rt.getGrD3DResourceState(); sk_sp<GrD3DRenderTarget> tgt = GrD3DRenderTarget::MakeWrappedRenderTarget( this, rt.dimensions(), rt.sampleCnt(), info, std::move(state)); // We don't allow the client to supply a premade stencil buffer. We always create one if needed. SkASSERT(!rt.stencilBits()); if (tgt) { SkASSERT(tgt->canAttemptStencilAttachment(tgt->numSamples() > 1)); } return std::move(tgt); } static bool is_odd(int x) { return x > 1 && SkToBool(x & 0x1); } bool GrD3DGpu::onRegenerateMipMapLevels(GrTexture * tex) { auto * d3dTex = static_cast<GrD3DTexture*>(tex); SkASSERT(tex->textureType() == GrTextureType::k2D); int width = tex->width(); int height = tex->height(); // determine if we can read from and mipmap this format const GrD3DCaps & caps = this->d3dCaps(); if (!caps.isFormatTexturable(d3dTex->dxgiFormat()) || !caps.mipmapSupport()) { return false; } sk_sp<GrD3DTexture> uavTexture; // if the format is unordered accessible and resource flag is set, use resource for uav if (caps.isFormatUnorderedAccessible(d3dTex->dxgiFormat()) && (d3dTex->d3dResource()->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { uavTexture = sk_ref_sp(d3dTex); } else { // need to make a copy and use that for our uav D3D12_RESOURCE_DESC uavDesc = d3dTex->d3dResource()->GetDesc(); uavDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // if the format is unordered accessible, copy to resource with same format and flag set if (!caps.isFormatUnorderedAccessible(d3dTex->dxgiFormat())) { // TODO: support BGR and sRGB return false; } // TODO: make this a scratch texture GrProtected grProtected = tex->isProtected() ? GrProtected::kYes : GrProtected::kNo; uavTexture = GrD3DTexture::MakeNewTexture(this, SkBudgeted::kNo, tex->dimensions(), uavDesc, grProtected, GrMipmapStatus::kDirty); if (!uavTexture) { return false; } d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE); // copy top miplevel to uavTexture uavTexture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); this->currentCommandList()->copyTextureToTexture(uavTexture.get(), d3dTex, 0); } uint32_t levelCount = d3dTex->mipLevels(); // SkMipmap doesn't include the base level in the level count so we have to add 1 SkASSERT((int)levelCount == SkMipmap::ComputeLevelCount(tex->width(), tex->height()) + 1); sk_sp<GrD3DRootSignature> rootSig = fResourceProvider.findOrCreateRootSignature(1, 1); this->currentCommandList()->setComputeRootSignature(rootSig); // TODO: use linear vs. srgb shader based on texture format sk_sp<GrD3DPipeline> pipeline = this->resourceProvider().findOrCreateMipmapPipeline(); SkASSERT(pipeline); this->currentCommandList()->setPipelineState(std::move(pipeline)); // set sampler GrSamplerState samplerState(SkFilterMode::kLinear, SkMipmapMode::kNearest); std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> samplers(1); samplers[0] = fResourceProvider.findOrCreateCompatibleSampler(samplerState); this->currentCommandList()->addSampledTextureRef(uavTexture.get()); sk_sp<GrD3DDescriptorTable> samplerTable = fResourceProvider.findOrCreateSamplerTable(samplers); this->currentCommandList()->setComputeRootDescriptorTable( static_cast<unsigned int>(GrD3DRootSignature::ParamIndex::kSamplerDescriptorTable), samplerTable->baseGpuDescriptor()); // Transition the top subresource to be readable in the compute shader D3D12_RESOURCE_STATES currentResourceState = uavTexture->currentState(); D3D12_RESOURCE_TRANSITION_BARRIER barrier; barrier.pResource = uavTexture->d3dResource(); barrier.Subresource = 0; barrier.StateBefore = currentResourceState; barrier.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; this->addResourceBarriers(uavTexture->resource(), 1, &barrier); // Generate the miplevels for (unsigned int dstMip = 1; dstMip < levelCount; ++dstMip) { unsigned int srcMip = dstMip - 1; width = std::max(1, width / 2); height = std::max(1, height / 2); unsigned int sampleMode = 0; if (is_odd(width) && is_odd(height)) { sampleMode = 1; } else if (is_odd(width)) { sampleMode = 2; } else if (is_odd(height)) { sampleMode = 3; } // set constants struct { SkSize inverseSize; uint32_t mipLevel; uint32_t sampleMode; } constantData = { {1.f / width, 1.f / height}, srcMip, sampleMode }; D3D12_GPU_VIRTUAL_ADDRESS constantsAddress = fResourceProvider.uploadConstantData(&constantData, sizeof(constantData)); this->currentCommandList()->setComputeRootConstantBufferView( (unsigned int)GrD3DRootSignature::ParamIndex::kConstantBufferView, constantsAddress); std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> shaderViews; // create SRV GrD3DDescriptorHeap::CPUHandle srvHandle = fResourceProvider.createShaderResourceView(uavTexture->d3dResource(), srcMip, 1); shaderViews.push_back(srvHandle.fHandle); fMipmapCPUDescriptors.push_back(srvHandle); // create UAV GrD3DDescriptorHeap::CPUHandle uavHandle = fResourceProvider.createUnorderedAccessView(uavTexture->d3dResource(), dstMip); shaderViews.push_back(uavHandle.fHandle); fMipmapCPUDescriptors.push_back(uavHandle); // set up and bind shaderView descriptor table sk_sp<GrD3DDescriptorTable> srvTable = fResourceProvider.findOrCreateShaderViewTable(shaderViews); this->currentCommandList()->setComputeRootDescriptorTable( (unsigned int)GrD3DRootSignature::ParamIndex::kShaderViewDescriptorTable, srvTable->baseGpuDescriptor()); // Transition resource state of dstMip subresource so we can write to it barrier.Subresource = dstMip; barrier.StateBefore = currentResourceState; barrier.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; this->addResourceBarriers(uavTexture->resource(), 1, &barrier); // Using the form (x+7)/8 ensures that the remainder is covered as well this->currentCommandList()->dispatch((width+7)/8, (height+7)/8); // guarantee UAV writes have completed this->currentCommandList()->uavBarrier(uavTexture->resource(), uavTexture->d3dResource()); // Transition resource state of dstMip subresource so we can read it in the next stage barrier.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; barrier.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; this->addResourceBarriers(uavTexture->resource(), 1, &barrier); } // copy back if necessary if (uavTexture.get() != d3dTex) { d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; barrier.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; barrier.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; // TODO: support BGR and sRGB this->addResourceBarriers(uavTexture->resource(), 1, &barrier); this->currentCommandList()->copyTextureToTexture(d3dTex, uavTexture.get()); } else { // For simplicity our resource state tracking considers all subresources to have the same // state. However, we've changed that state one subresource at a time without going through // the tracking system, so we need to patch up the resource states back to the original. barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; barrier.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; barrier.StateAfter = currentResourceState; this->addResourceBarriers(d3dTex->resource(), 1, &barrier); } return true; } sk_sp<GrGpuBuffer> GrD3DGpu::onCreateBuffer(size_t sizeInBytes, GrGpuBufferType type, GrAccessPattern accessPattern, const void* data) { sk_sp<GrD3DBuffer> buffer = GrD3DBuffer::Make(this, sizeInBytes, type, accessPattern); if (data && buffer) { buffer->updateData(data, sizeInBytes); } return std::move(buffer); } sk_sp<GrAttachment> GrD3DGpu::makeStencilAttachment(const GrBackendFormat& /*colorFormat*/, SkISize dimensions, int numStencilSamples) { DXGI_FORMAT sFmt = this->d3dCaps().preferredStencilFormat(); fStats.incStencilAttachmentCreates(); return GrD3DAttachment::MakeStencil(this, dimensions, numStencilSamples, sFmt); } bool GrD3DGpu::createTextureResourceForBackendSurface(DXGI_FORMAT dxgiFormat, SkISize dimensions, GrTexturable texturable, GrRenderable renderable, GrMipmapped mipMapped, int sampleCnt, GrD3DTextureResourceInfo* info, GrProtected isProtected) { SkASSERT(texturable == GrTexturable::kYes || renderable == GrRenderable::kYes); if (this->protectedContext() != (isProtected == GrProtected::kYes)) { return false; } if (texturable == GrTexturable::kYes && !this->d3dCaps().isFormatTexturable(dxgiFormat)) { return false; } if (renderable == GrRenderable::kYes && !this->d3dCaps().isFormatRenderable(dxgiFormat, 1)) { return false; } int numMipLevels = 1; if (mipMapped == GrMipmapped::kYes) { numMipLevels = SkMipmap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1; } // create the texture D3D12_RESOURCE_FLAGS usageFlags = D3D12_RESOURCE_FLAG_NONE; if (renderable == GrRenderable::kYes) { usageFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; } D3D12_RESOURCE_DESC resourceDesc = {}; resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; resourceDesc.Alignment = 0; // use default alignment resourceDesc.Width = dimensions.fWidth; resourceDesc.Height = dimensions.fHeight; resourceDesc.DepthOrArraySize = 1; resourceDesc.MipLevels = numMipLevels; resourceDesc.Format = dxgiFormat; resourceDesc.SampleDesc.Count = sampleCnt; resourceDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN; resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // use driver-selected swizzle resourceDesc.Flags = usageFlags; D3D12_CLEAR_VALUE* clearValuePtr = nullptr; D3D12_CLEAR_VALUE clearValue = {}; if (renderable == GrRenderable::kYes) { clearValue.Format = dxgiFormat; // Assume transparent black clearValue.Color[0] = 0; clearValue.Color[1] = 0; clearValue.Color[2] = 0; clearValue.Color[3] = 0; clearValuePtr = &clearValue; } D3D12_RESOURCE_STATES initialState = (renderable == GrRenderable::kYes) ? D3D12_RESOURCE_STATE_RENDER_TARGET : D3D12_RESOURCE_STATE_COPY_DEST; if (!GrD3DTextureResource::InitTextureResourceInfo(this, resourceDesc, initialState, isProtected, clearValuePtr, info)) { SkDebugf("Failed to init texture resource info\n"); return false; } return true; } GrBackendTexture GrD3DGpu::onCreateBackendTexture(SkISize dimensions, const GrBackendFormat& format, GrRenderable renderable, GrMipmapped mipMapped, GrProtected isProtected) { const GrD3DCaps& caps = this->d3dCaps(); if (this->protectedContext() != (isProtected == GrProtected::kYes)) { return {}; } DXGI_FORMAT dxgiFormat; if (!format.asDxgiFormat(&dxgiFormat)) { return {}; } // TODO: move the texturability check up to GrGpu::createBackendTexture and just assert here if (!caps.isFormatTexturable(dxgiFormat)) { return {}; } GrD3DTextureResourceInfo info; if (!this->createTextureResourceForBackendSurface(dxgiFormat, dimensions, GrTexturable::kYes, renderable, mipMapped, 1, &info, isProtected)) { return {}; } return GrBackendTexture(dimensions.width(), dimensions.height(), info); } static bool copy_color_data(const GrD3DCaps& caps, char* mapPtr, DXGI_FORMAT dxgiFormat, SkISize dimensions, D3D12_PLACED_SUBRESOURCE_FOOTPRINT* placedFootprints, std::array<float, 4> color) { auto colorType = caps.getFormatColorType(dxgiFormat); if (colorType == GrColorType::kUnknown) { return false; } GrImageInfo ii(colorType, kUnpremul_SkAlphaType, nullptr, dimensions); if (!GrClearImage(ii, mapPtr, placedFootprints[0].Footprint.RowPitch, color)) { return false; } return true; } bool GrD3DGpu::onClearBackendTexture(const GrBackendTexture& backendTexture, sk_sp<GrRefCntedCallback> finishedCallback, std::array<float, 4> color) { GrD3DTextureResourceInfo info; SkAssertResult(backendTexture.getD3DTextureResourceInfo(&info)); SkASSERT(!GrDxgiFormatIsCompressed(info.fFormat)); sk_sp<GrD3DResourceState> state = backendTexture.getGrD3DResourceState(); SkASSERT(state); sk_sp<GrD3DTexture> texture = GrD3DTexture::MakeWrappedTexture(this, backendTexture.dimensions(), GrWrapCacheable::kNo, kRW_GrIOType, info, std::move(state)); if (!texture) { return false; } GrD3DDirectCommandList* cmdList = this->currentCommandList(); if (!cmdList) { return false; } texture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); ID3D12Resource* d3dResource = texture->d3dResource(); SkASSERT(d3dResource); D3D12_RESOURCE_DESC desc = d3dResource->GetDesc(); unsigned int mipLevelCount = 1; if (backendTexture.fMipmapped == GrMipmapped::kYes) { mipLevelCount = SkMipmap::ComputeLevelCount(backendTexture.dimensions()) + 1; } SkASSERT(mipLevelCount == info.fLevelCount); SkAutoSTMalloc<15, D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount); UINT numRows; UINT64 rowSizeInBytes; UINT64 combinedBufferSize; // We reuse the same top-level buffer area for all levels, hence passing 1 for level count. fDevice->GetCopyableFootprints(&desc, /* first resource */ 0, /* mip level count */ 1, /* base offset */ 0, placedFootprints.get(), &numRows, &rowSizeInBytes, &combinedBufferSize); SkASSERT(combinedBufferSize); GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice( combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); if (!slice.fBuffer) { return false; } char* bufferData = (char*)slice.fOffsetMapPtr; SkASSERT(bufferData); if (!copy_color_data(this->d3dCaps(), bufferData, info.fFormat, backendTexture.dimensions(), placedFootprints, color)) { return false; } // Update the offsets in the footprint to be relative to the slice's offset placedFootprints[0].Offset += slice.fOffset; // Since we're sharing data for all the levels, set all the upper level footprints to the base. UINT w = placedFootprints[0].Footprint.Width; UINT h = placedFootprints[0].Footprint.Height; for (unsigned int i = 1; i < mipLevelCount; ++i) { w = std::max(1U, w/2); h = std::max(1U, h/2); placedFootprints[i].Offset = placedFootprints[0].Offset; placedFootprints[i].Footprint.Format = placedFootprints[0].Footprint.Format; placedFootprints[i].Footprint.Width = w; placedFootprints[i].Footprint.Height = h; placedFootprints[i].Footprint.Depth = 1; placedFootprints[i].Footprint.RowPitch = placedFootprints[0].Footprint.RowPitch; } ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource(); cmdList->copyBufferToTexture(d3dBuffer, texture.get(), mipLevelCount, placedFootprints.get(), /*left*/ 0, /*top */ 0); if (finishedCallback) { this->addFinishedCallback(std::move(finishedCallback)); } return true; } GrBackendTexture GrD3DGpu::onCreateCompressedBackendTexture( SkISize dimensions, const GrBackendFormat& format, GrMipmapped mipMapped, GrProtected isProtected) { return this->onCreateBackendTexture(dimensions, format, GrRenderable::kNo, mipMapped, isProtected); } bool GrD3DGpu::onUpdateCompressedBackendTexture(const GrBackendTexture& backendTexture, sk_sp<GrRefCntedCallback> finishedCallback, const void* data, size_t size) { GrD3DTextureResourceInfo info; SkAssertResult(backendTexture.getD3DTextureResourceInfo(&info)); sk_sp<GrD3DResourceState> state = backendTexture.getGrD3DResourceState(); SkASSERT(state); sk_sp<GrD3DTexture> texture = GrD3DTexture::MakeWrappedTexture(this, backendTexture.dimensions(), GrWrapCacheable::kNo, kRW_GrIOType, info, std::move(state)); if (!texture) { return false; } GrD3DDirectCommandList* cmdList = this->currentCommandList(); if (!cmdList) { return false; } texture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); ID3D12Resource* d3dResource = texture->d3dResource(); SkASSERT(d3dResource); D3D12_RESOURCE_DESC desc = d3dResource->GetDesc(); unsigned int mipLevelCount = 1; if (backendTexture.hasMipmaps()) { mipLevelCount = SkMipmap::ComputeLevelCount(backendTexture.dimensions().width(), backendTexture.dimensions().height()) + 1; } SkASSERT(mipLevelCount == info.fLevelCount); SkAutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount); UINT64 combinedBufferSize; SkAutoTMalloc<UINT> numRows(mipLevelCount); SkAutoTMalloc<UINT64> rowSizeInBytes(mipLevelCount); fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(), numRows.get(), rowSizeInBytes.get(), &combinedBufferSize); SkASSERT(combinedBufferSize); SkASSERT(GrDxgiFormatIsCompressed(info.fFormat)); GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice( combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); if (!slice.fBuffer) { return false; } char* bufferData = (char*)slice.fOffsetMapPtr; SkASSERT(bufferData); copy_compressed_data(bufferData, info.fFormat, placedFootprints.get(), numRows.get(), rowSizeInBytes.get(), data, info.fLevelCount); // Update the offsets in the footprints to be relative to the slice's offset for (unsigned int i = 0; i < mipLevelCount; ++i) { placedFootprints[i].Offset += slice.fOffset; } ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource(); cmdList->copyBufferToTexture(d3dBuffer, texture.get(), mipLevelCount, placedFootprints.get(), 0, 0); if (finishedCallback) { this->addFinishedCallback(std::move(finishedCallback)); } return true; } void GrD3DGpu::deleteBackendTexture(const GrBackendTexture& tex) { SkASSERT(GrBackendApi::kDirect3D == tex.fBackend); // Nothing to do here, will get cleaned up when the GrBackendTexture object goes away } bool GrD3DGpu::compile(const GrProgramDesc&, const GrProgramInfo&) { return false; } #if GR_TEST_UTILS bool GrD3DGpu::isTestingOnlyBackendTexture(const GrBackendTexture& tex) const { SkASSERT(GrBackendApi::kDirect3D == tex.backend()); GrD3DTextureResourceInfo info; if (!tex.getD3DTextureResourceInfo(&info)) { return false; } ID3D12Resource* textureResource = info.fResource.get(); if (!textureResource) { return false; } return !(textureResource->GetDesc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); } GrBackendRenderTarget GrD3DGpu::createTestingOnlyBackendRenderTarget(SkISize dimensions, GrColorType colorType, int sampleCnt, GrProtected isProtected) { if (dimensions.width() > this->caps()->maxRenderTargetSize() || dimensions.height() > this->caps()->maxRenderTargetSize()) { return {}; } DXGI_FORMAT dxgiFormat = this->d3dCaps().getFormatFromColorType(colorType); GrD3DTextureResourceInfo info; if (!this->createTextureResourceForBackendSurface(dxgiFormat, dimensions, GrTexturable::kNo, GrRenderable::kYes, GrMipmapped::kNo, sampleCnt, &info, isProtected)) { return {}; } return GrBackendRenderTarget(dimensions.width(), dimensions.height(), info); } void GrD3DGpu::deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget& rt) { SkASSERT(GrBackendApi::kDirect3D == rt.backend()); GrD3DTextureResourceInfo info; if (rt.getD3DTextureResourceInfo(&info)) { this->submitToGpu(true); // Nothing else to do here, will get cleaned up when the GrBackendRenderTarget // is deleted. } } void GrD3DGpu::testingOnly_startCapture() { if (fGraphicsAnalysis) { fGraphicsAnalysis->BeginCapture(); } } void GrD3DGpu::testingOnly_endCapture() { if (fGraphicsAnalysis) { fGraphicsAnalysis->EndCapture(); } } #endif /////////////////////////////////////////////////////////////////////////////// void GrD3DGpu::addResourceBarriers(sk_sp<GrManagedResource> resource, int numBarriers, D3D12_RESOURCE_TRANSITION_BARRIER* barriers) const { SkASSERT(fCurrentDirectCommandList); SkASSERT(resource); fCurrentDirectCommandList->resourceBarrier(std::move(resource), numBarriers, barriers); } void GrD3DGpu::addBufferResourceBarriers(GrD3DBuffer* buffer, int numBarriers, D3D12_RESOURCE_TRANSITION_BARRIER* barriers) const { SkASSERT(fCurrentDirectCommandList); SkASSERT(buffer); fCurrentDirectCommandList->resourceBarrier(nullptr, numBarriers, barriers); fCurrentDirectCommandList->addGrBuffer(sk_ref_sp<const GrBuffer>(buffer)); } void GrD3DGpu::prepareSurfacesForBackendAccessAndStateUpdates( SkSpan<GrSurfaceProxy*> proxies, SkSurface::BackendSurfaceAccess access, const GrBackendSurfaceMutableState* newState) { // prepare proxies by transitioning to PRESENT renderState if (!proxies.empty() && access == SkSurface::BackendSurfaceAccess::kPresent) { GrD3DTextureResource* resource; for (GrSurfaceProxy* proxy : proxies) { SkASSERT(proxy->isInstantiated()); if (GrTexture* tex = proxy->peekTexture()) { resource = static_cast<GrD3DTexture*>(tex); } else { GrRenderTarget* rt = proxy->peekRenderTarget(); SkASSERT(rt); resource = static_cast<GrD3DRenderTarget*>(rt); } resource->prepareForPresent(this); } } } void GrD3DGpu::takeOwnershipOfBuffer(sk_sp<GrGpuBuffer> buffer) { fCurrentDirectCommandList->addGrBuffer(std::move(buffer)); } bool GrD3DGpu::onSubmitToGpu(bool syncCpu) { if (syncCpu) { return this->submitDirectCommandList(SyncQueue::kForce); } else { return this->submitDirectCommandList(SyncQueue::kSkip); } } std::unique_ptr<GrSemaphore> SK_WARN_UNUSED_RESULT GrD3DGpu::makeSemaphore(bool) { return GrD3DSemaphore::Make(this); } std::unique_ptr<GrSemaphore> GrD3DGpu::wrapBackendSemaphore(const GrBackendSemaphore& semaphore, GrSemaphoreWrapType /* wrapType */, GrWrapOwnership /* ownership */) { SkASSERT(this->caps()->semaphoreSupport()); GrD3DFenceInfo fenceInfo; if (!semaphore.getD3DFenceInfo(&fenceInfo)) { return nullptr; } return GrD3DSemaphore::MakeWrapped(fenceInfo); } void GrD3DGpu::insertSemaphore(GrSemaphore* semaphore) { SkASSERT(semaphore); GrD3DSemaphore* d3dSem = static_cast<GrD3DSemaphore*>(semaphore); // TODO: Do we need to track the lifetime of this? How do we know it's done? fQueue->Signal(d3dSem->fence(), d3dSem->value()); } void GrD3DGpu::waitSemaphore(GrSemaphore* semaphore) { SkASSERT(semaphore); GrD3DSemaphore* d3dSem = static_cast<GrD3DSemaphore*>(semaphore); // TODO: Do we need to track the lifetime of this? fQueue->Wait(d3dSem->fence(), d3dSem->value()); } GrFence SK_WARN_UNUSED_RESULT GrD3DGpu::insertFence() { GR_D3D_CALL_ERRCHECK(fQueue->Signal(fFence.get(), ++fCurrentFenceValue)); return fCurrentFenceValue; } bool GrD3DGpu::waitFence(GrFence fence) { return (fFence->GetCompletedValue() >= fence); } void GrD3DGpu::finishOutstandingGpuWork() { this->waitForQueueCompletion(); } Fix compile warning in GrD3DGpu::onCreateCompressedTexture This is an imported pull request from https://github.com/google/skia/pull/82 GitOrigin-RevId: 6e5ca6e5b209b46c11d8d8082c580bd5dd9d0729 Change-Id: I01f95f7ff768453364989372e09c6fd092a74e81 Reviewed-on: https://skia-review.googlesource.com/c/skia/+/424716 Reviewed-by: Greg Daniel <39df0a804564ccb6cf75f18db79653821f37c1c5@google.com> Commit-Queue: Greg Daniel <39df0a804564ccb6cf75f18db79653821f37c1c5@google.com> /* * Copyright 2020 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/d3d/GrD3DGpu.h" #include "include/gpu/GrBackendSurface.h" #include "include/gpu/d3d/GrD3DBackendContext.h" #include "src/core/SkConvertPixels.h" #include "src/core/SkMipmap.h" #include "src/gpu/GrBackendUtils.h" #include "src/gpu/GrDataUtils.h" #include "src/gpu/GrTexture.h" #include "src/gpu/GrThreadSafePipelineBuilder.h" #include "src/gpu/d3d/GrD3DAMDMemoryAllocator.h" #include "src/gpu/d3d/GrD3DAttachment.h" #include "src/gpu/d3d/GrD3DBuffer.h" #include "src/gpu/d3d/GrD3DCaps.h" #include "src/gpu/d3d/GrD3DOpsRenderPass.h" #include "src/gpu/d3d/GrD3DSemaphore.h" #include "src/gpu/d3d/GrD3DTexture.h" #include "src/gpu/d3d/GrD3DTextureRenderTarget.h" #include "src/gpu/d3d/GrD3DUtil.h" #include "src/sksl/SkSLCompiler.h" #if GR_TEST_UTILS #include <DXProgrammableCapture.h> #endif GrThreadSafePipelineBuilder* GrD3DGpu::pipelineBuilder() { return nullptr; } sk_sp<GrThreadSafePipelineBuilder> GrD3DGpu::refPipelineBuilder() { return nullptr; } sk_sp<GrGpu> GrD3DGpu::Make(const GrD3DBackendContext& backendContext, const GrContextOptions& contextOptions, GrDirectContext* direct) { sk_sp<GrD3DMemoryAllocator> memoryAllocator = backendContext.fMemoryAllocator; if (!memoryAllocator) { // We were not given a memory allocator at creation memoryAllocator = GrD3DAMDMemoryAllocator::Make( backendContext.fAdapter.get(), backendContext.fDevice.get()); } if (!memoryAllocator) { SkDEBUGFAIL("No supplied Direct3D memory allocator and unable to create one internally."); return nullptr; } return sk_sp<GrGpu>(new GrD3DGpu(direct, contextOptions, backendContext, memoryAllocator)); } // This constant determines how many OutstandingCommandLists are allocated together as a block in // the deque. As such it needs to balance allocating too much memory vs. incurring // allocation/deallocation thrashing. It should roughly correspond to the max number of outstanding // command lists we expect to see. static const int kDefaultOutstandingAllocCnt = 8; // constants have to be aligned to 256 constexpr int kConstantAlignment = 256; GrD3DGpu::GrD3DGpu(GrDirectContext* direct, const GrContextOptions& contextOptions, const GrD3DBackendContext& backendContext, sk_sp<GrD3DMemoryAllocator> allocator) : INHERITED(direct) , fDevice(backendContext.fDevice) , fQueue(backendContext.fQueue) , fMemoryAllocator(std::move(allocator)) , fResourceProvider(this) , fStagingBufferManager(this) , fConstantsRingBuffer(this, 128 * 1024, kConstantAlignment, GrGpuBufferType::kVertex) , fOutstandingCommandLists(sizeof(OutstandingCommandList), kDefaultOutstandingAllocCnt) { this->initCapsAndCompiler(sk_make_sp<GrD3DCaps>(contextOptions, backendContext.fAdapter.get(), backendContext.fDevice.get())); fCurrentDirectCommandList = fResourceProvider.findOrCreateDirectCommandList(); SkASSERT(fCurrentDirectCommandList); SkASSERT(fCurrentFenceValue == 0); GR_D3D_CALL_ERRCHECK(fDevice->CreateFence(fCurrentFenceValue, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fFence))); #if GR_TEST_UTILS HRESULT getAnalysis = DXGIGetDebugInterface1(0, IID_PPV_ARGS(&fGraphicsAnalysis)); if (FAILED(getAnalysis)) { fGraphicsAnalysis = nullptr; } #endif } GrD3DGpu::~GrD3DGpu() { this->destroyResources(); } void GrD3DGpu::destroyResources() { if (fCurrentDirectCommandList) { fCurrentDirectCommandList->close(); fCurrentDirectCommandList->reset(); } // We need to make sure everything has finished on the queue. this->waitForQueueCompletion(); SkDEBUGCODE(uint64_t fenceValue = fFence->GetCompletedValue();) // We used a placement new for each object in fOutstandingCommandLists, so we're responsible // for calling the destructor on each of them as well. while (!fOutstandingCommandLists.empty()) { OutstandingCommandList* list = (OutstandingCommandList*)fOutstandingCommandLists.front(); SkASSERT(list->fFenceValue <= fenceValue); // No reason to recycle the command lists since we are destroying all resources anyways. list->~OutstandingCommandList(); fOutstandingCommandLists.pop_front(); } fStagingBufferManager.reset(); fResourceProvider.destroyResources(); } GrOpsRenderPass* GrD3DGpu::onGetOpsRenderPass( GrRenderTarget* rt, bool /*useMSAASurface*/, GrAttachment*, GrSurfaceOrigin origin, const SkIRect& bounds, const GrOpsRenderPass::LoadAndStoreInfo& colorInfo, const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilInfo, const SkTArray<GrSurfaceProxy*, true>& sampledProxies, GrXferBarrierFlags renderPassXferBarriers) { if (!fCachedOpsRenderPass) { fCachedOpsRenderPass.reset(new GrD3DOpsRenderPass(this)); } if (!fCachedOpsRenderPass->set(rt, origin, bounds, colorInfo, stencilInfo, sampledProxies)) { return nullptr; } return fCachedOpsRenderPass.get(); } bool GrD3DGpu::submitDirectCommandList(SyncQueue sync) { SkASSERT(fCurrentDirectCommandList); fResourceProvider.prepForSubmit(); for (int i = 0; i < fMipmapCPUDescriptors.count(); ++i) { fResourceProvider.recycleShaderView(fMipmapCPUDescriptors[i]); } fMipmapCPUDescriptors.reset(); GrD3DDirectCommandList::SubmitResult result = fCurrentDirectCommandList->submit(fQueue.get()); if (result == GrD3DDirectCommandList::SubmitResult::kFailure) { return false; } else if (result == GrD3DDirectCommandList::SubmitResult::kNoWork) { if (sync == SyncQueue::kForce) { this->waitForQueueCompletion(); this->checkForFinishedCommandLists(); } return true; } // We just submitted the command list so make sure all GrD3DPipelineState's mark their cached // uniform data as dirty. fResourceProvider.markPipelineStateUniformsDirty(); GrFence fence = this->insertFence(); new (fOutstandingCommandLists.push_back()) OutstandingCommandList( std::move(fCurrentDirectCommandList), fence); if (sync == SyncQueue::kForce) { this->waitForQueueCompletion(); } fCurrentDirectCommandList = fResourceProvider.findOrCreateDirectCommandList(); // This should be done after we have a new command list in case the freeing of any resources // held by a finished command list causes us send a new command to the gpu (like changing the // resource state. this->checkForFinishedCommandLists(); SkASSERT(fCurrentDirectCommandList); return true; } void GrD3DGpu::checkForFinishedCommandLists() { uint64_t currentFenceValue = fFence->GetCompletedValue(); // Iterate over all the outstanding command lists to see if any have finished. The commands // lists are in order from oldest to newest, so we start at the front to check if their fence // value is less than the last signaled value. If so we pop it off and move onto the next. // Repeat till we find a command list that has not finished yet (and all others afterwards are // also guaranteed to not have finished). OutstandingCommandList* front = (OutstandingCommandList*)fOutstandingCommandLists.front(); while (front && front->fFenceValue <= currentFenceValue) { std::unique_ptr<GrD3DDirectCommandList> currList(std::move(front->fCommandList)); // Since we used placement new we are responsible for calling the destructor manually. front->~OutstandingCommandList(); fOutstandingCommandLists.pop_front(); fResourceProvider.recycleDirectCommandList(std::move(currList)); front = (OutstandingCommandList*)fOutstandingCommandLists.front(); } } void GrD3DGpu::waitForQueueCompletion() { if (fFence->GetCompletedValue() < fCurrentFenceValue) { HANDLE fenceEvent; fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); SkASSERT(fenceEvent); GR_D3D_CALL_ERRCHECK(fFence->SetEventOnCompletion(fCurrentFenceValue, fenceEvent)); WaitForSingleObject(fenceEvent, INFINITE); CloseHandle(fenceEvent); } } void GrD3DGpu::submit(GrOpsRenderPass* renderPass) { SkASSERT(fCachedOpsRenderPass.get() == renderPass); fCachedOpsRenderPass->submit(); fCachedOpsRenderPass.reset(); } void GrD3DGpu::endRenderPass(GrRenderTarget* target, GrSurfaceOrigin origin, const SkIRect& bounds) { this->didWriteToSurface(target, origin, &bounds); } void GrD3DGpu::addFinishedProc(GrGpuFinishedProc finishedProc, GrGpuFinishedContext finishedContext) { SkASSERT(finishedProc); this->addFinishedCallback(GrRefCntedCallback::Make(finishedProc, finishedContext)); } void GrD3DGpu::addFinishedCallback(sk_sp<GrRefCntedCallback> finishedCallback) { SkASSERT(finishedCallback); // Besides the current command list, we also add the finishedCallback to the newest outstanding // command list. Our contract for calling the proc is that all previous submitted command lists // have finished when we call it. However, if our current command list has no work when it is // flushed it will drop its ref to the callback immediately. But the previous work may not have // finished. It is safe to only add the proc to the newest outstanding commandlist cause that // must finish after all previously submitted command lists. OutstandingCommandList* back = (OutstandingCommandList*)fOutstandingCommandLists.back(); if (back) { back->fCommandList->addFinishedCallback(finishedCallback); } fCurrentDirectCommandList->addFinishedCallback(std::move(finishedCallback)); } sk_sp<GrD3DTexture> GrD3DGpu::createD3DTexture(SkISize dimensions, DXGI_FORMAT dxgiFormat, GrRenderable renderable, int renderTargetSampleCnt, SkBudgeted budgeted, GrProtected isProtected, int mipLevelCount, GrMipmapStatus mipmapStatus) { D3D12_RESOURCE_FLAGS usageFlags = D3D12_RESOURCE_FLAG_NONE; if (renderable == GrRenderable::kYes) { usageFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; } // This desc refers to a texture that will be read by the client. Thus even if msaa is // requested, this describes the resolved texture. Therefore we always have samples set // to 1. SkASSERT(mipLevelCount > 0); D3D12_RESOURCE_DESC resourceDesc = {}; resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; // TODO: will use 4MB alignment for MSAA textures and 64KB for everything else // might want to manually set alignment to 4KB for smaller textures resourceDesc.Alignment = 0; resourceDesc.Width = dimensions.fWidth; resourceDesc.Height = dimensions.fHeight; resourceDesc.DepthOrArraySize = 1; resourceDesc.MipLevels = mipLevelCount; resourceDesc.Format = dxgiFormat; resourceDesc.SampleDesc.Count = 1; resourceDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN; resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // use driver-selected swizzle resourceDesc.Flags = usageFlags; if (renderable == GrRenderable::kYes) { return GrD3DTextureRenderTarget::MakeNewTextureRenderTarget( this, budgeted, dimensions, renderTargetSampleCnt, resourceDesc, isProtected, mipmapStatus); } else { return GrD3DTexture::MakeNewTexture(this, budgeted, dimensions, resourceDesc, isProtected, mipmapStatus); } } sk_sp<GrTexture> GrD3DGpu::onCreateTexture(SkISize dimensions, const GrBackendFormat& format, GrRenderable renderable, int renderTargetSampleCnt, SkBudgeted budgeted, GrProtected isProtected, int mipLevelCount, uint32_t levelClearMask) { DXGI_FORMAT dxgiFormat; SkAssertResult(format.asDxgiFormat(&dxgiFormat)); SkASSERT(!GrDxgiFormatIsCompressed(dxgiFormat)); GrMipmapStatus mipmapStatus = mipLevelCount > 1 ? GrMipmapStatus::kDirty : GrMipmapStatus::kNotAllocated; sk_sp<GrD3DTexture> tex = this->createD3DTexture(dimensions, dxgiFormat, renderable, renderTargetSampleCnt, budgeted, isProtected, mipLevelCount, mipmapStatus); if (!tex) { return nullptr; } if (levelClearMask) { // TODO } return std::move(tex); } static void copy_compressed_data(char* mapPtr, DXGI_FORMAT dxgiFormat, D3D12_PLACED_SUBRESOURCE_FOOTPRINT* placedFootprints, UINT* numRows, UINT64* rowSizeInBytes, const void* compressedData, int numMipLevels) { SkASSERT(compressedData && numMipLevels); SkASSERT(GrDxgiFormatIsCompressed(dxgiFormat)); SkASSERT(mapPtr); const char* src = static_cast<const char*>(compressedData); for (int currentMipLevel = 0; currentMipLevel < numMipLevels; currentMipLevel++) { // copy data into the buffer, skipping any trailing bytes char* dst = mapPtr + placedFootprints[currentMipLevel].Offset; SkRectMemcpy(dst, placedFootprints[currentMipLevel].Footprint.RowPitch, src, rowSizeInBytes[currentMipLevel], rowSizeInBytes[currentMipLevel], numRows[currentMipLevel]); src += numRows[currentMipLevel] * rowSizeInBytes[currentMipLevel]; } } sk_sp<GrTexture> GrD3DGpu::onCreateCompressedTexture(SkISize dimensions, const GrBackendFormat& format, SkBudgeted budgeted, GrMipmapped mipMapped, GrProtected isProtected, const void* data, size_t dataSize) { DXGI_FORMAT dxgiFormat; SkAssertResult(format.asDxgiFormat(&dxgiFormat)); SkASSERT(GrDxgiFormatIsCompressed(dxgiFormat)); SkDEBUGCODE(SkImage::CompressionType compression = GrBackendFormatToCompressionType(format)); SkASSERT(dataSize == SkCompressedFormatDataSize(compression, dimensions, mipMapped == GrMipmapped::kYes)); int mipLevelCount = 1; if (mipMapped == GrMipmapped::kYes) { mipLevelCount = SkMipmap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1; } GrMipmapStatus mipmapStatus = mipLevelCount > 1 ? GrMipmapStatus::kValid : GrMipmapStatus::kNotAllocated; sk_sp<GrD3DTexture> d3dTex = this->createD3DTexture(dimensions, dxgiFormat, GrRenderable::kNo, 1, budgeted, isProtected, mipLevelCount, mipmapStatus); if (!d3dTex) { return nullptr; } ID3D12Resource* d3dResource = d3dTex->d3dResource(); SkASSERT(d3dResource); D3D12_RESOURCE_DESC desc = d3dResource->GetDesc(); // Either upload only the first miplevel or all miplevels SkASSERT(1 == mipLevelCount || mipLevelCount == (int)desc.MipLevels); SkAutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount); SkAutoTMalloc<UINT> numRows(mipLevelCount); SkAutoTMalloc<UINT64> rowSizeInBytes(mipLevelCount); UINT64 combinedBufferSize; // We reset the width and height in the description to match our subrectangle size // so we don't end up allocating more space than we need. desc.Width = dimensions.width(); desc.Height = dimensions.height(); fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(), numRows.get(), rowSizeInBytes.get(), &combinedBufferSize); SkASSERT(combinedBufferSize); GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice( combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); if (!slice.fBuffer) { return nullptr; } char* bufferData = (char*)slice.fOffsetMapPtr; copy_compressed_data(bufferData, desc.Format, placedFootprints.get(), numRows.get(), rowSizeInBytes.get(), data, mipLevelCount); // Update the offsets in the footprints to be relative to the slice's offset for (int i = 0; i < mipLevelCount; ++i) { placedFootprints[i].Offset += slice.fOffset; } ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource(); fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer, d3dTex.get(), mipLevelCount, placedFootprints.get(), 0, 0); return std::move(d3dTex); } static int get_surface_sample_cnt(GrSurface* surf) { if (const GrRenderTarget* rt = surf->asRenderTarget()) { return rt->numSamples(); } return 0; } bool GrD3DGpu::onCopySurface(GrSurface* dst, GrSurface* src, const SkIRect& srcRect, const SkIPoint& dstPoint) { if (src->isProtected() && !dst->isProtected()) { SkDebugf("Can't copy from protected memory to non-protected"); return false; } int dstSampleCnt = get_surface_sample_cnt(dst); int srcSampleCnt = get_surface_sample_cnt(src); GrD3DTextureResource* dstTexResource; GrD3DTextureResource* srcTexResource; GrRenderTarget* dstRT = dst->asRenderTarget(); if (dstRT) { GrD3DRenderTarget* d3dRT = static_cast<GrD3DRenderTarget*>(dstRT); dstTexResource = d3dRT->numSamples() > 1 ? d3dRT->msaaTextureResource() : d3dRT; } else { SkASSERT(dst->asTexture()); dstTexResource = static_cast<GrD3DTexture*>(dst->asTexture()); } GrRenderTarget* srcRT = src->asRenderTarget(); if (srcRT) { GrD3DRenderTarget* d3dRT = static_cast<GrD3DRenderTarget*>(srcRT); srcTexResource = d3dRT->numSamples() > 1 ? d3dRT->msaaTextureResource() : d3dRT; } else { SkASSERT(src->asTexture()); srcTexResource = static_cast<GrD3DTexture*>(src->asTexture()); } DXGI_FORMAT dstFormat = dstTexResource->dxgiFormat(); DXGI_FORMAT srcFormat = srcTexResource->dxgiFormat(); if (this->d3dCaps().canCopyAsResolve(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)) { this->copySurfaceAsResolve(dst, src, srcRect, dstPoint); return true; } if (this->d3dCaps().canCopyTexture(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)) { this->copySurfaceAsCopyTexture(dst, src, dstTexResource, srcTexResource, srcRect, dstPoint); return true; } return false; } void GrD3DGpu::copySurfaceAsCopyTexture(GrSurface* dst, GrSurface* src, GrD3DTextureResource* dstResource, GrD3DTextureResource* srcResource, const SkIRect& srcRect, const SkIPoint& dstPoint) { #ifdef SK_DEBUG int dstSampleCnt = get_surface_sample_cnt(dst); int srcSampleCnt = get_surface_sample_cnt(src); DXGI_FORMAT dstFormat = dstResource->dxgiFormat(); DXGI_FORMAT srcFormat; SkAssertResult(dst->backendFormat().asDxgiFormat(&srcFormat)); SkASSERT(this->d3dCaps().canCopyTexture(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)); #endif if (src->isProtected() && !dst->isProtected()) { SkDebugf("Can't copy from protected memory to non-protected"); return; } dstResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); srcResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE); D3D12_TEXTURE_COPY_LOCATION dstLocation = {}; dstLocation.pResource = dstResource->d3dResource(); dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; dstLocation.SubresourceIndex = 0; D3D12_TEXTURE_COPY_LOCATION srcLocation = {}; srcLocation.pResource = srcResource->d3dResource(); srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; srcLocation.SubresourceIndex = 0; D3D12_BOX srcBox = {}; srcBox.left = srcRect.fLeft; srcBox.top = srcRect.fTop; srcBox.right = srcRect.fRight; srcBox.bottom = srcRect.fBottom; srcBox.front = 0; srcBox.back = 1; // TODO: use copyResource if copying full resource and sizes match fCurrentDirectCommandList->copyTextureRegionToTexture(dstResource->resource(), &dstLocation, dstPoint.fX, dstPoint.fY, srcResource->resource(), &srcLocation, &srcBox); SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY, srcRect.width(), srcRect.height()); // The rect is already in device space so we pass in kTopLeft so no flip is done. this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect); } void GrD3DGpu::copySurfaceAsResolve(GrSurface* dst, GrSurface* src, const SkIRect& srcRect, const SkIPoint& dstPoint) { GrD3DRenderTarget* srcRT = static_cast<GrD3DRenderTarget*>(src->asRenderTarget()); SkASSERT(srcRT); this->resolveTexture(dst, dstPoint.fX, dstPoint.fY, srcRT, srcRect); SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY, srcRect.width(), srcRect.height()); // The rect is already in device space so we pass in kTopLeft so no flip is done. this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect); } void GrD3DGpu::resolveTexture(GrSurface* dst, int32_t dstX, int32_t dstY, GrD3DRenderTarget* src, const SkIRect& srcIRect) { SkASSERT(dst); SkASSERT(src && src->numSamples() > 1 && src->msaaTextureResource()); D3D12_RECT srcRect = { srcIRect.fLeft, srcIRect.fTop, srcIRect.fRight, srcIRect.fBottom }; GrD3DTextureResource* dstTextureResource; GrRenderTarget* dstRT = dst->asRenderTarget(); if (dstRT) { dstTextureResource = static_cast<GrD3DRenderTarget*>(dstRT); } else { SkASSERT(dst->asTexture()); dstTextureResource = static_cast<GrD3DTexture*>(dst->asTexture()); } dstTextureResource->setResourceState(this, D3D12_RESOURCE_STATE_RESOLVE_DEST); src->msaaTextureResource()->setResourceState(this, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); fCurrentDirectCommandList->resolveSubresourceRegion(dstTextureResource, dstX, dstY, src->msaaTextureResource(), &srcRect); } void GrD3DGpu::onResolveRenderTarget(GrRenderTarget* target, const SkIRect& resolveRect) { SkASSERT(target->numSamples() > 1); GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(target); SkASSERT(rt->msaaTextureResource() && rt != rt->msaaTextureResource()); this->resolveTexture(target, resolveRect.fLeft, resolveRect.fTop, rt, resolveRect); } bool GrD3DGpu::onReadPixels(GrSurface* surface, SkIRect rect, GrColorType surfaceColorType, GrColorType dstColorType, void* buffer, size_t rowBytes) { SkASSERT(surface); if (surfaceColorType != dstColorType) { return false; } GrD3DTextureResource* texResource = nullptr; GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(surface->asRenderTarget()); if (rt) { texResource = rt; } else { texResource = static_cast<GrD3DTexture*>(surface->asTexture()); } if (!texResource) { return false; } D3D12_RESOURCE_DESC desc = texResource->d3dResource()->GetDesc(); D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint; UINT64 transferTotalBytes; fDevice->GetCopyableFootprints(&desc, 0, 1, 0, &placedFootprint, nullptr, nullptr, &transferTotalBytes); SkASSERT(transferTotalBytes); // TODO: implement some way of reusing buffers instead of making a new one every time. sk_sp<GrGpuBuffer> transferBuffer = this->createBuffer(transferTotalBytes, GrGpuBufferType::kXferGpuToCpu, kDynamic_GrAccessPattern); this->readOrTransferPixels(texResource, rect, transferBuffer, placedFootprint); this->submitDirectCommandList(SyncQueue::kForce); // Copy back to CPU buffer size_t bpp = GrColorTypeBytesPerPixel(dstColorType); if (GrDxgiFormatBytesPerBlock(texResource->dxgiFormat()) != bpp) { return false; } size_t tightRowBytes = bpp * rect.width(); const void* mappedMemory = transferBuffer->map(); SkRectMemcpy(buffer, rowBytes, mappedMemory, placedFootprint.Footprint.RowPitch, tightRowBytes, rect.height()); transferBuffer->unmap(); return true; } void GrD3DGpu::readOrTransferPixels(GrD3DTextureResource* texResource, SkIRect rect, sk_sp<GrGpuBuffer> transferBuffer, const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& placedFootprint) { // Set up src location and box D3D12_TEXTURE_COPY_LOCATION srcLocation = {}; srcLocation.pResource = texResource->d3dResource(); SkASSERT(srcLocation.pResource); srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; srcLocation.SubresourceIndex = 0; D3D12_BOX srcBox = {}; srcBox.left = rect.left(); srcBox.top = rect.top(); srcBox.right = rect.right(); srcBox.bottom = rect.bottom(); srcBox.front = 0; srcBox.back = 1; // Set up dst location D3D12_TEXTURE_COPY_LOCATION dstLocation = {}; dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; dstLocation.PlacedFootprint = placedFootprint; GrD3DBuffer* d3dBuf = static_cast<GrD3DBuffer*>(transferBuffer.get()); dstLocation.pResource = d3dBuf->d3dResource(); // Need to change the resource state to COPY_SOURCE in order to download from it texResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE); fCurrentDirectCommandList->copyTextureRegionToBuffer(transferBuffer, &dstLocation, 0, 0, texResource->resource(), &srcLocation, &srcBox); } bool GrD3DGpu::onWritePixels(GrSurface* surface, SkIRect rect, GrColorType surfaceColorType, GrColorType srcColorType, const GrMipLevel texels[], int mipLevelCount, bool prepForTexSampling) { GrD3DTexture* d3dTex = static_cast<GrD3DTexture*>(surface->asTexture()); if (!d3dTex) { return false; } // Make sure we have at least the base level if (!mipLevelCount || !texels[0].fPixels) { return false; } SkASSERT(!GrDxgiFormatIsCompressed(d3dTex->dxgiFormat())); bool success = false; // Need to change the resource state to COPY_DEST in order to upload to it d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); SkASSERT(mipLevelCount <= d3dTex->maxMipmapLevel() + 1); success = this->uploadToTexture(d3dTex, rect, srcColorType, texels, mipLevelCount); if (prepForTexSampling) { d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); } return success; } bool GrD3DGpu::uploadToTexture(GrD3DTexture* tex, SkIRect rect, GrColorType colorType, const GrMipLevel* texels, int mipLevelCount) { SkASSERT(this->caps()->isFormatTexturable(tex->backendFormat())); // The assumption is either that we have no mipmaps, or that our rect is the entire texture SkASSERT(mipLevelCount == 1 || rect == SkIRect::MakeSize(tex->dimensions())); // We assume that if the texture has mip levels, we either upload to all the levels or just the // first. SkASSERT(mipLevelCount == 1 || mipLevelCount == (tex->maxMipmapLevel() + 1)); if (rect.isEmpty()) { return false; } SkASSERT(this->d3dCaps().surfaceSupportsWritePixels(tex)); SkASSERT(this->d3dCaps().areColorTypeAndFormatCompatible(colorType, tex->backendFormat())); ID3D12Resource* d3dResource = tex->d3dResource(); SkASSERT(d3dResource); D3D12_RESOURCE_DESC desc = d3dResource->GetDesc(); // Either upload only the first miplevel or all miplevels SkASSERT(1 == mipLevelCount || mipLevelCount == (int)desc.MipLevels); if (1 == mipLevelCount && !texels[0].fPixels) { return true; // no data to upload } for (int i = 0; i < mipLevelCount; ++i) { // We do not allow any gaps in the mip data if (!texels[i].fPixels) { return false; } } SkAutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount); UINT64 combinedBufferSize; // We reset the width and height in the description to match our subrectangle size // so we don't end up allocating more space than we need. desc.Width = rect.width(); desc.Height = rect.height(); fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(), nullptr, nullptr, &combinedBufferSize); size_t bpp = GrColorTypeBytesPerPixel(colorType); SkASSERT(combinedBufferSize); GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice( combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); if (!slice.fBuffer) { return false; } char* bufferData = (char*)slice.fOffsetMapPtr; int currentWidth = rect.width(); int currentHeight = rect.height(); int layerHeight = tex->height(); for (int currentMipLevel = 0; currentMipLevel < mipLevelCount; currentMipLevel++) { if (texels[currentMipLevel].fPixels) { SkASSERT(1 == mipLevelCount || currentHeight == layerHeight); const size_t trimRowBytes = currentWidth * bpp; const size_t srcRowBytes = texels[currentMipLevel].fRowBytes; char* dst = bufferData + placedFootprints[currentMipLevel].Offset; // copy data into the buffer, skipping any trailing bytes const char* src = (const char*)texels[currentMipLevel].fPixels; SkRectMemcpy(dst, placedFootprints[currentMipLevel].Footprint.RowPitch, src, srcRowBytes, trimRowBytes, currentHeight); } currentWidth = std::max(1, currentWidth / 2); currentHeight = std::max(1, currentHeight / 2); layerHeight = currentHeight; } // Update the offsets in the footprints to be relative to the slice's offset for (int i = 0; i < mipLevelCount; ++i) { placedFootprints[i].Offset += slice.fOffset; } ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource(); fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer, tex, mipLevelCount, placedFootprints.get(), rect.left(), rect.top()); if (mipLevelCount < (int)desc.MipLevels) { tex->markMipmapsDirty(); } return true; } bool GrD3DGpu::onTransferPixelsTo(GrTexture* texture, SkIRect rect, GrColorType surfaceColorType, GrColorType bufferColorType, sk_sp<GrGpuBuffer> transferBuffer, size_t bufferOffset, size_t rowBytes) { if (!this->currentCommandList()) { return false; } if (!transferBuffer) { return false; } size_t bpp = GrColorTypeBytesPerPixel(bufferColorType); if (GrBackendFormatBytesPerPixel(texture->backendFormat()) != bpp) { return false; } // D3D requires offsets for texture transfers to be aligned to this value if (SkToBool(bufferOffset & (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1))) { return false; } GrD3DTexture* d3dTex = static_cast<GrD3DTexture*>(texture); if (!d3dTex) { return false; } SkDEBUGCODE(DXGI_FORMAT format = d3dTex->dxgiFormat()); // Can't transfer compressed data SkASSERT(!GrDxgiFormatIsCompressed(format)); SkASSERT(GrDxgiFormatBytesPerBlock(format) == GrColorTypeBytesPerPixel(bufferColorType)); SkASSERT(SkIRect::MakeSize(texture->dimensions()).contains(rect)); // Set up copy region D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint = {}; ID3D12Resource* d3dResource = d3dTex->d3dResource(); SkASSERT(d3dResource); D3D12_RESOURCE_DESC desc = d3dResource->GetDesc(); desc.Width = rect.width(); desc.Height = rect.height(); UINT64 totalBytes; fDevice->GetCopyableFootprints(&desc, 0, 1, 0, &placedFootprint, nullptr, nullptr, &totalBytes); placedFootprint.Offset = bufferOffset; // Change state of our target so it can be copied to d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); // Copy the buffer to the image. ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(transferBuffer.get())->d3dResource(); fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer, d3dTex, 1, &placedFootprint, rect.left(), rect.top()); this->currentCommandList()->addGrBuffer(std::move(transferBuffer)); d3dTex->markMipmapsDirty(); return true; } bool GrD3DGpu::onTransferPixelsFrom(GrSurface* surface, SkIRect rect, GrColorType surfaceColorType, GrColorType bufferColorType, sk_sp<GrGpuBuffer> transferBuffer, size_t offset) { if (!this->currentCommandList()) { return false; } SkASSERT(surface); SkASSERT(transferBuffer); // TODO //if (fProtectedContext == GrProtected::kYes) { // return false; //} // D3D requires offsets for texture transfers to be aligned to this value if (SkToBool(offset & (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1))) { return false; } GrD3DTextureResource* texResource = nullptr; GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(surface->asRenderTarget()); if (rt) { texResource = rt; } else { texResource = static_cast<GrD3DTexture*>(surface->asTexture()); } if (!texResource) { return false; } SkDEBUGCODE(DXGI_FORMAT format = texResource->dxgiFormat()); SkASSERT(GrDxgiFormatBytesPerBlock(format) == GrColorTypeBytesPerPixel(bufferColorType)); D3D12_RESOURCE_DESC desc = texResource->d3dResource()->GetDesc(); desc.Width = rect.width(); desc.Height = rect.height(); D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint; UINT64 transferTotalBytes; fDevice->GetCopyableFootprints(&desc, 0, 1, offset, &placedFootprint, nullptr, nullptr, &transferTotalBytes); SkASSERT(transferTotalBytes); this->readOrTransferPixels(texResource, rect, transferBuffer, placedFootprint); // TODO: It's not clear how to ensure the transfer is done before we read from the buffer, // other than maybe doing a resource state transition. return true; } static bool check_resource_info(const GrD3DTextureResourceInfo& info) { if (!info.fResource.get()) { return false; } return true; } static bool check_tex_resource_info(const GrD3DCaps& caps, const GrD3DTextureResourceInfo& info) { if (!caps.isFormatTexturable(info.fFormat)) { return false; } // We don't support sampling from multisampled textures. if (info.fSampleCount != 1) { return false; } return true; } static bool check_rt_resource_info(const GrD3DCaps& caps, const GrD3DTextureResourceInfo& info, int sampleCnt) { if (!caps.isFormatRenderable(info.fFormat, sampleCnt)) { return false; } return true; } sk_sp<GrTexture> GrD3DGpu::onWrapBackendTexture(const GrBackendTexture& tex, GrWrapOwnership, GrWrapCacheable wrapType, GrIOType ioType) { GrD3DTextureResourceInfo textureInfo; if (!tex.getD3DTextureResourceInfo(&textureInfo)) { return nullptr; } if (!check_resource_info(textureInfo)) { return nullptr; } if (!check_tex_resource_info(this->d3dCaps(), textureInfo)) { return nullptr; } // TODO: support protected context if (tex.isProtected()) { return nullptr; } sk_sp<GrD3DResourceState> state = tex.getGrD3DResourceState(); SkASSERT(state); return GrD3DTexture::MakeWrappedTexture(this, tex.dimensions(), wrapType, ioType, textureInfo, std::move(state)); } sk_sp<GrTexture> GrD3DGpu::onWrapCompressedBackendTexture(const GrBackendTexture& tex, GrWrapOwnership ownership, GrWrapCacheable wrapType) { return this->onWrapBackendTexture(tex, ownership, wrapType, kRead_GrIOType); } sk_sp<GrTexture> GrD3DGpu::onWrapRenderableBackendTexture(const GrBackendTexture& tex, int sampleCnt, GrWrapOwnership ownership, GrWrapCacheable cacheable) { GrD3DTextureResourceInfo textureInfo; if (!tex.getD3DTextureResourceInfo(&textureInfo)) { return nullptr; } if (!check_resource_info(textureInfo)) { return nullptr; } if (!check_tex_resource_info(this->d3dCaps(), textureInfo)) { return nullptr; } if (!check_rt_resource_info(this->d3dCaps(), textureInfo, sampleCnt)) { return nullptr; } // TODO: support protected context if (tex.isProtected()) { return nullptr; } sampleCnt = this->d3dCaps().getRenderTargetSampleCount(sampleCnt, textureInfo.fFormat); sk_sp<GrD3DResourceState> state = tex.getGrD3DResourceState(); SkASSERT(state); return GrD3DTextureRenderTarget::MakeWrappedTextureRenderTarget(this, tex.dimensions(), sampleCnt, cacheable, textureInfo, std::move(state)); } sk_sp<GrRenderTarget> GrD3DGpu::onWrapBackendRenderTarget(const GrBackendRenderTarget& rt) { GrD3DTextureResourceInfo info; if (!rt.getD3DTextureResourceInfo(&info)) { return nullptr; } if (!check_resource_info(info)) { return nullptr; } if (!check_rt_resource_info(this->d3dCaps(), info, rt.sampleCnt())) { return nullptr; } // TODO: support protected context if (rt.isProtected()) { return nullptr; } sk_sp<GrD3DResourceState> state = rt.getGrD3DResourceState(); sk_sp<GrD3DRenderTarget> tgt = GrD3DRenderTarget::MakeWrappedRenderTarget( this, rt.dimensions(), rt.sampleCnt(), info, std::move(state)); // We don't allow the client to supply a premade stencil buffer. We always create one if needed. SkASSERT(!rt.stencilBits()); if (tgt) { SkASSERT(tgt->canAttemptStencilAttachment(tgt->numSamples() > 1)); } return std::move(tgt); } static bool is_odd(int x) { return x > 1 && SkToBool(x & 0x1); } bool GrD3DGpu::onRegenerateMipMapLevels(GrTexture * tex) { auto * d3dTex = static_cast<GrD3DTexture*>(tex); SkASSERT(tex->textureType() == GrTextureType::k2D); int width = tex->width(); int height = tex->height(); // determine if we can read from and mipmap this format const GrD3DCaps & caps = this->d3dCaps(); if (!caps.isFormatTexturable(d3dTex->dxgiFormat()) || !caps.mipmapSupport()) { return false; } sk_sp<GrD3DTexture> uavTexture; // if the format is unordered accessible and resource flag is set, use resource for uav if (caps.isFormatUnorderedAccessible(d3dTex->dxgiFormat()) && (d3dTex->d3dResource()->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { uavTexture = sk_ref_sp(d3dTex); } else { // need to make a copy and use that for our uav D3D12_RESOURCE_DESC uavDesc = d3dTex->d3dResource()->GetDesc(); uavDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // if the format is unordered accessible, copy to resource with same format and flag set if (!caps.isFormatUnorderedAccessible(d3dTex->dxgiFormat())) { // TODO: support BGR and sRGB return false; } // TODO: make this a scratch texture GrProtected grProtected = tex->isProtected() ? GrProtected::kYes : GrProtected::kNo; uavTexture = GrD3DTexture::MakeNewTexture(this, SkBudgeted::kNo, tex->dimensions(), uavDesc, grProtected, GrMipmapStatus::kDirty); if (!uavTexture) { return false; } d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE); // copy top miplevel to uavTexture uavTexture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); this->currentCommandList()->copyTextureToTexture(uavTexture.get(), d3dTex, 0); } uint32_t levelCount = d3dTex->mipLevels(); // SkMipmap doesn't include the base level in the level count so we have to add 1 SkASSERT((int)levelCount == SkMipmap::ComputeLevelCount(tex->width(), tex->height()) + 1); sk_sp<GrD3DRootSignature> rootSig = fResourceProvider.findOrCreateRootSignature(1, 1); this->currentCommandList()->setComputeRootSignature(rootSig); // TODO: use linear vs. srgb shader based on texture format sk_sp<GrD3DPipeline> pipeline = this->resourceProvider().findOrCreateMipmapPipeline(); SkASSERT(pipeline); this->currentCommandList()->setPipelineState(std::move(pipeline)); // set sampler GrSamplerState samplerState(SkFilterMode::kLinear, SkMipmapMode::kNearest); std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> samplers(1); samplers[0] = fResourceProvider.findOrCreateCompatibleSampler(samplerState); this->currentCommandList()->addSampledTextureRef(uavTexture.get()); sk_sp<GrD3DDescriptorTable> samplerTable = fResourceProvider.findOrCreateSamplerTable(samplers); this->currentCommandList()->setComputeRootDescriptorTable( static_cast<unsigned int>(GrD3DRootSignature::ParamIndex::kSamplerDescriptorTable), samplerTable->baseGpuDescriptor()); // Transition the top subresource to be readable in the compute shader D3D12_RESOURCE_STATES currentResourceState = uavTexture->currentState(); D3D12_RESOURCE_TRANSITION_BARRIER barrier; barrier.pResource = uavTexture->d3dResource(); barrier.Subresource = 0; barrier.StateBefore = currentResourceState; barrier.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; this->addResourceBarriers(uavTexture->resource(), 1, &barrier); // Generate the miplevels for (unsigned int dstMip = 1; dstMip < levelCount; ++dstMip) { unsigned int srcMip = dstMip - 1; width = std::max(1, width / 2); height = std::max(1, height / 2); unsigned int sampleMode = 0; if (is_odd(width) && is_odd(height)) { sampleMode = 1; } else if (is_odd(width)) { sampleMode = 2; } else if (is_odd(height)) { sampleMode = 3; } // set constants struct { SkSize inverseSize; uint32_t mipLevel; uint32_t sampleMode; } constantData = { {1.f / width, 1.f / height}, srcMip, sampleMode }; D3D12_GPU_VIRTUAL_ADDRESS constantsAddress = fResourceProvider.uploadConstantData(&constantData, sizeof(constantData)); this->currentCommandList()->setComputeRootConstantBufferView( (unsigned int)GrD3DRootSignature::ParamIndex::kConstantBufferView, constantsAddress); std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> shaderViews; // create SRV GrD3DDescriptorHeap::CPUHandle srvHandle = fResourceProvider.createShaderResourceView(uavTexture->d3dResource(), srcMip, 1); shaderViews.push_back(srvHandle.fHandle); fMipmapCPUDescriptors.push_back(srvHandle); // create UAV GrD3DDescriptorHeap::CPUHandle uavHandle = fResourceProvider.createUnorderedAccessView(uavTexture->d3dResource(), dstMip); shaderViews.push_back(uavHandle.fHandle); fMipmapCPUDescriptors.push_back(uavHandle); // set up and bind shaderView descriptor table sk_sp<GrD3DDescriptorTable> srvTable = fResourceProvider.findOrCreateShaderViewTable(shaderViews); this->currentCommandList()->setComputeRootDescriptorTable( (unsigned int)GrD3DRootSignature::ParamIndex::kShaderViewDescriptorTable, srvTable->baseGpuDescriptor()); // Transition resource state of dstMip subresource so we can write to it barrier.Subresource = dstMip; barrier.StateBefore = currentResourceState; barrier.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; this->addResourceBarriers(uavTexture->resource(), 1, &barrier); // Using the form (x+7)/8 ensures that the remainder is covered as well this->currentCommandList()->dispatch((width+7)/8, (height+7)/8); // guarantee UAV writes have completed this->currentCommandList()->uavBarrier(uavTexture->resource(), uavTexture->d3dResource()); // Transition resource state of dstMip subresource so we can read it in the next stage barrier.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; barrier.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; this->addResourceBarriers(uavTexture->resource(), 1, &barrier); } // copy back if necessary if (uavTexture.get() != d3dTex) { d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; barrier.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; barrier.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; // TODO: support BGR and sRGB this->addResourceBarriers(uavTexture->resource(), 1, &barrier); this->currentCommandList()->copyTextureToTexture(d3dTex, uavTexture.get()); } else { // For simplicity our resource state tracking considers all subresources to have the same // state. However, we've changed that state one subresource at a time without going through // the tracking system, so we need to patch up the resource states back to the original. barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; barrier.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; barrier.StateAfter = currentResourceState; this->addResourceBarriers(d3dTex->resource(), 1, &barrier); } return true; } sk_sp<GrGpuBuffer> GrD3DGpu::onCreateBuffer(size_t sizeInBytes, GrGpuBufferType type, GrAccessPattern accessPattern, const void* data) { sk_sp<GrD3DBuffer> buffer = GrD3DBuffer::Make(this, sizeInBytes, type, accessPattern); if (data && buffer) { buffer->updateData(data, sizeInBytes); } return std::move(buffer); } sk_sp<GrAttachment> GrD3DGpu::makeStencilAttachment(const GrBackendFormat& /*colorFormat*/, SkISize dimensions, int numStencilSamples) { DXGI_FORMAT sFmt = this->d3dCaps().preferredStencilFormat(); fStats.incStencilAttachmentCreates(); return GrD3DAttachment::MakeStencil(this, dimensions, numStencilSamples, sFmt); } bool GrD3DGpu::createTextureResourceForBackendSurface(DXGI_FORMAT dxgiFormat, SkISize dimensions, GrTexturable texturable, GrRenderable renderable, GrMipmapped mipMapped, int sampleCnt, GrD3DTextureResourceInfo* info, GrProtected isProtected) { SkASSERT(texturable == GrTexturable::kYes || renderable == GrRenderable::kYes); if (this->protectedContext() != (isProtected == GrProtected::kYes)) { return false; } if (texturable == GrTexturable::kYes && !this->d3dCaps().isFormatTexturable(dxgiFormat)) { return false; } if (renderable == GrRenderable::kYes && !this->d3dCaps().isFormatRenderable(dxgiFormat, 1)) { return false; } int numMipLevels = 1; if (mipMapped == GrMipmapped::kYes) { numMipLevels = SkMipmap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1; } // create the texture D3D12_RESOURCE_FLAGS usageFlags = D3D12_RESOURCE_FLAG_NONE; if (renderable == GrRenderable::kYes) { usageFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; } D3D12_RESOURCE_DESC resourceDesc = {}; resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; resourceDesc.Alignment = 0; // use default alignment resourceDesc.Width = dimensions.fWidth; resourceDesc.Height = dimensions.fHeight; resourceDesc.DepthOrArraySize = 1; resourceDesc.MipLevels = numMipLevels; resourceDesc.Format = dxgiFormat; resourceDesc.SampleDesc.Count = sampleCnt; resourceDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN; resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // use driver-selected swizzle resourceDesc.Flags = usageFlags; D3D12_CLEAR_VALUE* clearValuePtr = nullptr; D3D12_CLEAR_VALUE clearValue = {}; if (renderable == GrRenderable::kYes) { clearValue.Format = dxgiFormat; // Assume transparent black clearValue.Color[0] = 0; clearValue.Color[1] = 0; clearValue.Color[2] = 0; clearValue.Color[3] = 0; clearValuePtr = &clearValue; } D3D12_RESOURCE_STATES initialState = (renderable == GrRenderable::kYes) ? D3D12_RESOURCE_STATE_RENDER_TARGET : D3D12_RESOURCE_STATE_COPY_DEST; if (!GrD3DTextureResource::InitTextureResourceInfo(this, resourceDesc, initialState, isProtected, clearValuePtr, info)) { SkDebugf("Failed to init texture resource info\n"); return false; } return true; } GrBackendTexture GrD3DGpu::onCreateBackendTexture(SkISize dimensions, const GrBackendFormat& format, GrRenderable renderable, GrMipmapped mipMapped, GrProtected isProtected) { const GrD3DCaps& caps = this->d3dCaps(); if (this->protectedContext() != (isProtected == GrProtected::kYes)) { return {}; } DXGI_FORMAT dxgiFormat; if (!format.asDxgiFormat(&dxgiFormat)) { return {}; } // TODO: move the texturability check up to GrGpu::createBackendTexture and just assert here if (!caps.isFormatTexturable(dxgiFormat)) { return {}; } GrD3DTextureResourceInfo info; if (!this->createTextureResourceForBackendSurface(dxgiFormat, dimensions, GrTexturable::kYes, renderable, mipMapped, 1, &info, isProtected)) { return {}; } return GrBackendTexture(dimensions.width(), dimensions.height(), info); } static bool copy_color_data(const GrD3DCaps& caps, char* mapPtr, DXGI_FORMAT dxgiFormat, SkISize dimensions, D3D12_PLACED_SUBRESOURCE_FOOTPRINT* placedFootprints, std::array<float, 4> color) { auto colorType = caps.getFormatColorType(dxgiFormat); if (colorType == GrColorType::kUnknown) { return false; } GrImageInfo ii(colorType, kUnpremul_SkAlphaType, nullptr, dimensions); if (!GrClearImage(ii, mapPtr, placedFootprints[0].Footprint.RowPitch, color)) { return false; } return true; } bool GrD3DGpu::onClearBackendTexture(const GrBackendTexture& backendTexture, sk_sp<GrRefCntedCallback> finishedCallback, std::array<float, 4> color) { GrD3DTextureResourceInfo info; SkAssertResult(backendTexture.getD3DTextureResourceInfo(&info)); SkASSERT(!GrDxgiFormatIsCompressed(info.fFormat)); sk_sp<GrD3DResourceState> state = backendTexture.getGrD3DResourceState(); SkASSERT(state); sk_sp<GrD3DTexture> texture = GrD3DTexture::MakeWrappedTexture(this, backendTexture.dimensions(), GrWrapCacheable::kNo, kRW_GrIOType, info, std::move(state)); if (!texture) { return false; } GrD3DDirectCommandList* cmdList = this->currentCommandList(); if (!cmdList) { return false; } texture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); ID3D12Resource* d3dResource = texture->d3dResource(); SkASSERT(d3dResource); D3D12_RESOURCE_DESC desc = d3dResource->GetDesc(); unsigned int mipLevelCount = 1; if (backendTexture.fMipmapped == GrMipmapped::kYes) { mipLevelCount = SkMipmap::ComputeLevelCount(backendTexture.dimensions()) + 1; } SkASSERT(mipLevelCount == info.fLevelCount); SkAutoSTMalloc<15, D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount); UINT numRows; UINT64 rowSizeInBytes; UINT64 combinedBufferSize; // We reuse the same top-level buffer area for all levels, hence passing 1 for level count. fDevice->GetCopyableFootprints(&desc, /* first resource */ 0, /* mip level count */ 1, /* base offset */ 0, placedFootprints.get(), &numRows, &rowSizeInBytes, &combinedBufferSize); SkASSERT(combinedBufferSize); GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice( combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); if (!slice.fBuffer) { return false; } char* bufferData = (char*)slice.fOffsetMapPtr; SkASSERT(bufferData); if (!copy_color_data(this->d3dCaps(), bufferData, info.fFormat, backendTexture.dimensions(), placedFootprints, color)) { return false; } // Update the offsets in the footprint to be relative to the slice's offset placedFootprints[0].Offset += slice.fOffset; // Since we're sharing data for all the levels, set all the upper level footprints to the base. UINT w = placedFootprints[0].Footprint.Width; UINT h = placedFootprints[0].Footprint.Height; for (unsigned int i = 1; i < mipLevelCount; ++i) { w = std::max(1U, w/2); h = std::max(1U, h/2); placedFootprints[i].Offset = placedFootprints[0].Offset; placedFootprints[i].Footprint.Format = placedFootprints[0].Footprint.Format; placedFootprints[i].Footprint.Width = w; placedFootprints[i].Footprint.Height = h; placedFootprints[i].Footprint.Depth = 1; placedFootprints[i].Footprint.RowPitch = placedFootprints[0].Footprint.RowPitch; } ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource(); cmdList->copyBufferToTexture(d3dBuffer, texture.get(), mipLevelCount, placedFootprints.get(), /*left*/ 0, /*top */ 0); if (finishedCallback) { this->addFinishedCallback(std::move(finishedCallback)); } return true; } GrBackendTexture GrD3DGpu::onCreateCompressedBackendTexture( SkISize dimensions, const GrBackendFormat& format, GrMipmapped mipMapped, GrProtected isProtected) { return this->onCreateBackendTexture(dimensions, format, GrRenderable::kNo, mipMapped, isProtected); } bool GrD3DGpu::onUpdateCompressedBackendTexture(const GrBackendTexture& backendTexture, sk_sp<GrRefCntedCallback> finishedCallback, const void* data, size_t size) { GrD3DTextureResourceInfo info; SkAssertResult(backendTexture.getD3DTextureResourceInfo(&info)); sk_sp<GrD3DResourceState> state = backendTexture.getGrD3DResourceState(); SkASSERT(state); sk_sp<GrD3DTexture> texture = GrD3DTexture::MakeWrappedTexture(this, backendTexture.dimensions(), GrWrapCacheable::kNo, kRW_GrIOType, info, std::move(state)); if (!texture) { return false; } GrD3DDirectCommandList* cmdList = this->currentCommandList(); if (!cmdList) { return false; } texture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST); ID3D12Resource* d3dResource = texture->d3dResource(); SkASSERT(d3dResource); D3D12_RESOURCE_DESC desc = d3dResource->GetDesc(); unsigned int mipLevelCount = 1; if (backendTexture.hasMipmaps()) { mipLevelCount = SkMipmap::ComputeLevelCount(backendTexture.dimensions().width(), backendTexture.dimensions().height()) + 1; } SkASSERT(mipLevelCount == info.fLevelCount); SkAutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount); UINT64 combinedBufferSize; SkAutoTMalloc<UINT> numRows(mipLevelCount); SkAutoTMalloc<UINT64> rowSizeInBytes(mipLevelCount); fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(), numRows.get(), rowSizeInBytes.get(), &combinedBufferSize); SkASSERT(combinedBufferSize); SkASSERT(GrDxgiFormatIsCompressed(info.fFormat)); GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice( combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); if (!slice.fBuffer) { return false; } char* bufferData = (char*)slice.fOffsetMapPtr; SkASSERT(bufferData); copy_compressed_data(bufferData, info.fFormat, placedFootprints.get(), numRows.get(), rowSizeInBytes.get(), data, info.fLevelCount); // Update the offsets in the footprints to be relative to the slice's offset for (unsigned int i = 0; i < mipLevelCount; ++i) { placedFootprints[i].Offset += slice.fOffset; } ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource(); cmdList->copyBufferToTexture(d3dBuffer, texture.get(), mipLevelCount, placedFootprints.get(), 0, 0); if (finishedCallback) { this->addFinishedCallback(std::move(finishedCallback)); } return true; } void GrD3DGpu::deleteBackendTexture(const GrBackendTexture& tex) { SkASSERT(GrBackendApi::kDirect3D == tex.fBackend); // Nothing to do here, will get cleaned up when the GrBackendTexture object goes away } bool GrD3DGpu::compile(const GrProgramDesc&, const GrProgramInfo&) { return false; } #if GR_TEST_UTILS bool GrD3DGpu::isTestingOnlyBackendTexture(const GrBackendTexture& tex) const { SkASSERT(GrBackendApi::kDirect3D == tex.backend()); GrD3DTextureResourceInfo info; if (!tex.getD3DTextureResourceInfo(&info)) { return false; } ID3D12Resource* textureResource = info.fResource.get(); if (!textureResource) { return false; } return !(textureResource->GetDesc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); } GrBackendRenderTarget GrD3DGpu::createTestingOnlyBackendRenderTarget(SkISize dimensions, GrColorType colorType, int sampleCnt, GrProtected isProtected) { if (dimensions.width() > this->caps()->maxRenderTargetSize() || dimensions.height() > this->caps()->maxRenderTargetSize()) { return {}; } DXGI_FORMAT dxgiFormat = this->d3dCaps().getFormatFromColorType(colorType); GrD3DTextureResourceInfo info; if (!this->createTextureResourceForBackendSurface(dxgiFormat, dimensions, GrTexturable::kNo, GrRenderable::kYes, GrMipmapped::kNo, sampleCnt, &info, isProtected)) { return {}; } return GrBackendRenderTarget(dimensions.width(), dimensions.height(), info); } void GrD3DGpu::deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget& rt) { SkASSERT(GrBackendApi::kDirect3D == rt.backend()); GrD3DTextureResourceInfo info; if (rt.getD3DTextureResourceInfo(&info)) { this->submitToGpu(true); // Nothing else to do here, will get cleaned up when the GrBackendRenderTarget // is deleted. } } void GrD3DGpu::testingOnly_startCapture() { if (fGraphicsAnalysis) { fGraphicsAnalysis->BeginCapture(); } } void GrD3DGpu::testingOnly_endCapture() { if (fGraphicsAnalysis) { fGraphicsAnalysis->EndCapture(); } } #endif /////////////////////////////////////////////////////////////////////////////// void GrD3DGpu::addResourceBarriers(sk_sp<GrManagedResource> resource, int numBarriers, D3D12_RESOURCE_TRANSITION_BARRIER* barriers) const { SkASSERT(fCurrentDirectCommandList); SkASSERT(resource); fCurrentDirectCommandList->resourceBarrier(std::move(resource), numBarriers, barriers); } void GrD3DGpu::addBufferResourceBarriers(GrD3DBuffer* buffer, int numBarriers, D3D12_RESOURCE_TRANSITION_BARRIER* barriers) const { SkASSERT(fCurrentDirectCommandList); SkASSERT(buffer); fCurrentDirectCommandList->resourceBarrier(nullptr, numBarriers, barriers); fCurrentDirectCommandList->addGrBuffer(sk_ref_sp<const GrBuffer>(buffer)); } void GrD3DGpu::prepareSurfacesForBackendAccessAndStateUpdates( SkSpan<GrSurfaceProxy*> proxies, SkSurface::BackendSurfaceAccess access, const GrBackendSurfaceMutableState* newState) { // prepare proxies by transitioning to PRESENT renderState if (!proxies.empty() && access == SkSurface::BackendSurfaceAccess::kPresent) { GrD3DTextureResource* resource; for (GrSurfaceProxy* proxy : proxies) { SkASSERT(proxy->isInstantiated()); if (GrTexture* tex = proxy->peekTexture()) { resource = static_cast<GrD3DTexture*>(tex); } else { GrRenderTarget* rt = proxy->peekRenderTarget(); SkASSERT(rt); resource = static_cast<GrD3DRenderTarget*>(rt); } resource->prepareForPresent(this); } } } void GrD3DGpu::takeOwnershipOfBuffer(sk_sp<GrGpuBuffer> buffer) { fCurrentDirectCommandList->addGrBuffer(std::move(buffer)); } bool GrD3DGpu::onSubmitToGpu(bool syncCpu) { if (syncCpu) { return this->submitDirectCommandList(SyncQueue::kForce); } else { return this->submitDirectCommandList(SyncQueue::kSkip); } } std::unique_ptr<GrSemaphore> SK_WARN_UNUSED_RESULT GrD3DGpu::makeSemaphore(bool) { return GrD3DSemaphore::Make(this); } std::unique_ptr<GrSemaphore> GrD3DGpu::wrapBackendSemaphore(const GrBackendSemaphore& semaphore, GrSemaphoreWrapType /* wrapType */, GrWrapOwnership /* ownership */) { SkASSERT(this->caps()->semaphoreSupport()); GrD3DFenceInfo fenceInfo; if (!semaphore.getD3DFenceInfo(&fenceInfo)) { return nullptr; } return GrD3DSemaphore::MakeWrapped(fenceInfo); } void GrD3DGpu::insertSemaphore(GrSemaphore* semaphore) { SkASSERT(semaphore); GrD3DSemaphore* d3dSem = static_cast<GrD3DSemaphore*>(semaphore); // TODO: Do we need to track the lifetime of this? How do we know it's done? fQueue->Signal(d3dSem->fence(), d3dSem->value()); } void GrD3DGpu::waitSemaphore(GrSemaphore* semaphore) { SkASSERT(semaphore); GrD3DSemaphore* d3dSem = static_cast<GrD3DSemaphore*>(semaphore); // TODO: Do we need to track the lifetime of this? fQueue->Wait(d3dSem->fence(), d3dSem->value()); } GrFence SK_WARN_UNUSED_RESULT GrD3DGpu::insertFence() { GR_D3D_CALL_ERRCHECK(fQueue->Signal(fFence.get(), ++fCurrentFenceValue)); return fCurrentFenceValue; } bool GrD3DGpu::waitFence(GrFence fence) { return (fFence->GetCompletedValue() >= fence); } void GrD3DGpu::finishOutstandingGpuWork() { this->waitForQueueCompletion(); }
#include "PresetComboBoxes.hpp" #include <cstddef> #include <vector> #include <string> #include <boost/algorithm/string.hpp> #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/textctrl.h> #include <wx/button.h> #include <wx/statbox.h> #include <wx/colordlg.h> #include <wx/wupdlock.h> #include <wx/menu.h> #include "libslic3r/libslic3r.h" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/PresetBundle.hpp" #include "GUI.hpp" #include "GUI_App.hpp" #include "Plater.hpp" #include "MainFrame.hpp" #include "format.hpp" #include "Tab.hpp" #include "ConfigWizard.hpp" #include "../Utils/ASCIIFolding.hpp" #include "../Utils/FixModelByWin10.hpp" #include "../Utils/UndoRedo.hpp" #include "BitmapCache.hpp" #include "PhysicalPrinterDialog.hpp" #include "SavePresetDialog.hpp" using Slic3r::GUI::format_wxstr; namespace Slic3r { namespace GUI { #define BORDER_W 10 // --------------------------------- // *** PresetComboBox *** // --------------------------------- /* For PresetComboBox we use bitmaps that are created from images that are already scaled appropriately for Retina * (Contrary to the intuition, the `scale` argument for Bitmap's constructor doesn't mean * "please scale this to such and such" but rather * "the wxImage is already sized for backing scale such and such". ) * Unfortunately, the constructor changes the size of wxBitmap too. * Thus We need to use unscaled size value for bitmaps that we use * to avoid scaled size of control items. * For this purpose control drawing methods and * control size calculation methods (virtual) are overridden. **/ PresetComboBox::PresetComboBox(wxWindow* parent, Preset::Type preset_type, const wxSize& size) : wxBitmapComboBox(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, size, 0, nullptr, wxCB_READONLY), m_type(preset_type), m_last_selected(wxNOT_FOUND), m_em_unit(em_unit(this)), m_preset_bundle(wxGetApp().preset_bundle) { SetFont(wxGetApp().normal_font()); #ifdef _WIN32 // Workaround for ignoring CBN_EDITCHANGE events, which are processed after the content of the combo box changes, so that // the index of the item inside CBN_EDITCHANGE may no more be valid. EnableTextChangedEvents(false); #endif /* _WIN32 */ switch (m_type) { case Preset::TYPE_PRINT: { m_collection = &m_preset_bundle->prints; m_main_bitmap_name = "cog"; break; } case Preset::TYPE_FILAMENT: { m_collection = &m_preset_bundle->filaments; m_main_bitmap_name = "spool"; break; } case Preset::TYPE_SLA_PRINT: { m_collection = &m_preset_bundle->sla_prints; m_main_bitmap_name = "cog"; break; } case Preset::TYPE_SLA_MATERIAL: { m_collection = &m_preset_bundle->sla_materials; m_main_bitmap_name = "resin"; break; } case Preset::TYPE_PRINTER: { m_collection = &m_preset_bundle->printers; m_main_bitmap_name = "printer"; break; } default: break; } m_bitmapCompatible = ScalableBitmap(this, "flag_green"); m_bitmapIncompatible = ScalableBitmap(this, "flag_red"); // parameters for an icon's drawing fill_width_height(); Bind(wxEVT_COMBOBOX, [this](wxCommandEvent& evt) { // see https://github.com/prusa3d/PrusaSlicer/issues/3889 // Under OSX: in case of use of a same names written in different case (like "ENDER" and "Ender") // m_presets_choice->GetSelection() will return first item, because search in PopupListCtrl is case-insensitive. // So, use GetSelection() from event parameter auto selected_item = evt.GetSelection(); auto marker = reinterpret_cast<Marker>(this->GetClientData(selected_item)); if (marker >= LABEL_ITEM_DISABLED && marker < LABEL_ITEM_MAX) this->SetSelection(this->m_last_selected); else if (on_selection_changed && (m_last_selected != selected_item || m_collection->current_is_dirty())) { m_last_selected = selected_item; on_selection_changed(selected_item); evt.StopPropagation(); } evt.Skip(); }); } PresetComboBox::~PresetComboBox() { } BitmapCache& PresetComboBox::bitmap_cache() { static BitmapCache bmps; return bmps; } void PresetComboBox::set_label_marker(int item, LabelItemType label_item_type) { this->SetClientData(item, (void*)label_item_type); } bool PresetComboBox::set_printer_technology(PrinterTechnology pt) { if (printer_technology != pt) { printer_technology = pt; return true; } return false; } void PresetComboBox::invalidate_selection() { m_last_selected = INT_MAX; // this value means that no one item is selected } void PresetComboBox::validate_selection(bool predicate/*=false*/) { if (predicate || // just in case: mark m_last_selected as a first added element m_last_selected == INT_MAX) m_last_selected = GetCount() - 1; } void PresetComboBox::update_selection() { /* If selected_preset_item is still equal to INT_MAX, it means that * there is no presets added to the list. * So, select last combobox item ("Add/Remove preset") */ validate_selection(); SetSelection(m_last_selected); SetToolTip(GetString(m_last_selected)); } void PresetComboBox::update(std::string select_preset_name) { Freeze(); Clear(); invalidate_selection(); const std::deque<Preset>& presets = m_collection->get_presets(); std::map<wxString, std::pair<wxBitmap*, bool>> nonsys_presets; std::map<wxString, wxBitmap*> incomp_presets; wxString selected = ""; if (!presets.front().is_visible) set_label_marker(Append(separator(L("System presets")), wxNullBitmap)); for (size_t i = presets.front().is_visible ? 0 : m_collection->num_default_presets(); i < presets.size(); ++i) { const Preset& preset = presets[i]; if (!preset.is_visible || !preset.is_compatible) continue; // marker used for disable incompatible printer models for the selected physical printer bool is_enabled = m_type == Preset::TYPE_PRINTER && printer_technology != ptAny ? preset.printer_technology() == printer_technology : true; if (select_preset_name.empty() && is_enabled) select_preset_name = preset.name; std::string bitmap_key = "cb"; if (m_type == Preset::TYPE_PRINTER) { bitmap_key += "_printer"; if (preset.printer_technology() == ptSLA) bitmap_key += "_sla"; } std::string main_icon_name = m_type == Preset::TYPE_PRINTER && preset.printer_technology() == ptSLA ? "sla_printer" : m_main_bitmap_name; wxBitmap* bmp = get_bmp(bitmap_key, main_icon_name, "lock_closed", is_enabled, preset.is_compatible, preset.is_system || preset.is_default); assert(bmp); if (!is_enabled) incomp_presets.emplace(wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), bmp); else if (preset.is_default || preset.is_system) { Append(wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), *bmp); validate_selection(preset.name == select_preset_name); } else { nonsys_presets.emplace(wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), std::pair<wxBitmap*, bool>(bmp, is_enabled)); if (preset.name == select_preset_name || (select_preset_name.empty() && is_enabled)) selected = wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()); } if (i + 1 == m_collection->num_default_presets()) set_label_marker(Append(separator(L("System presets")), wxNullBitmap)); } if (!nonsys_presets.empty()) { set_label_marker(Append(separator(L("User presets")), wxNullBitmap)); for (std::map<wxString, std::pair<wxBitmap*, bool>>::iterator it = nonsys_presets.begin(); it != nonsys_presets.end(); ++it) { int item_id = Append(it->first, *it->second.first); bool is_enabled = it->second.second; if (!is_enabled) set_label_marker(item_id, LABEL_ITEM_DISABLED); validate_selection(it->first == selected); } } if (!incomp_presets.empty()) { set_label_marker(Append(separator(L("Incompatible presets")), wxNullBitmap)); for (std::map<wxString, wxBitmap*>::iterator it = incomp_presets.begin(); it != incomp_presets.end(); ++it) { set_label_marker(Append(it->first, *it->second), LABEL_ITEM_DISABLED); } } update_selection(); Thaw(); } void PresetComboBox::update() { this->update(into_u8(this->GetString(this->GetSelection()))); } void PresetComboBox::msw_rescale() { m_em_unit = em_unit(this); m_bitmapIncompatible.msw_rescale(); m_bitmapCompatible.msw_rescale(); // parameters for an icon's drawing fill_width_height(); // update the control to redraw the icons update(); } void PresetComboBox::fill_width_height() { // To avoid asserts, each added bitmap to wxBitmapCombobox should be the same size, so // set a bitmap's height to m_bitmapCompatible->GetHeight() and norm_icon_width to m_bitmapCompatible->GetWidth() icon_height = m_bitmapCompatible.GetBmpHeight(); norm_icon_width = m_bitmapCompatible.GetBmpWidth(); /* It's supposed that standard size of an icon is 16px*16px for 100% scaled display. * So set sizes for solid_colored icons used for filament preset * and scale them in respect to em_unit value */ const float scale_f = (float)m_em_unit * 0.1f; thin_icon_width = lroundf(8 * scale_f); // analogue to 8px; wide_icon_width = norm_icon_width + thin_icon_width; space_icon_width = lroundf(2 * scale_f); thin_space_icon_width = 2 * space_icon_width; wide_space_icon_width = 3 * space_icon_width; } wxString PresetComboBox::separator(const std::string& label) { return wxString::FromUTF8(separator_head()) + _(label) + wxString::FromUTF8(separator_tail()); } wxBitmap* PresetComboBox::get_bmp( std::string bitmap_key, bool wide_icons, const std::string& main_icon_name, bool is_compatible/* = true*/, bool is_system/* = false*/, bool is_single_bar/* = false*/, std::string filament_rgb/* = ""*/, std::string extruder_rgb/* = ""*/) { // If the filament preset is not compatible and there is a "red flag" icon loaded, show it left // to the filament color image. if (wide_icons) bitmap_key += is_compatible ? ",cmpt" : ",ncmpt"; bitmap_key += is_system ? ",syst" : ",nsyst"; bitmap_key += ",h" + std::to_string(icon_height); wxBitmap* bmp = bitmap_cache().find(bitmap_key); if (bmp == nullptr) { // Create the bitmap with color bars. std::vector<wxBitmap> bmps; if (wide_icons) // Paint a red flag for incompatible presets. bmps.emplace_back(is_compatible ? bitmap_cache().mkclear(norm_icon_width, icon_height) : m_bitmapIncompatible.bmp()); if (m_type == Preset::TYPE_FILAMENT) { unsigned char rgb[3]; // Paint the color bars. bitmap_cache().parse_color(filament_rgb, rgb); bmps.emplace_back(bitmap_cache().mksolid(is_single_bar ? wide_icon_width : norm_icon_width, icon_height, rgb)); if (!is_single_bar) { bitmap_cache().parse_color(extruder_rgb, rgb); bmps.emplace_back(bitmap_cache().mksolid(thin_icon_width, icon_height, rgb)); } // Paint a lock at the system presets. bmps.emplace_back(bitmap_cache().mkclear(space_icon_width, icon_height)); } else { // Paint the color bars. bmps.emplace_back(bitmap_cache().mkclear(thin_space_icon_width, icon_height)); bmps.emplace_back(create_scaled_bitmap(main_icon_name)); // Paint a lock at the system presets. bmps.emplace_back(bitmap_cache().mkclear(wide_space_icon_width, icon_height)); } bmps.emplace_back(is_system ? create_scaled_bitmap("lock_closed") : bitmap_cache().mkclear(norm_icon_width, icon_height)); bmp = bitmap_cache().insert(bitmap_key, bmps); } return bmp; } wxBitmap* PresetComboBox::get_bmp( std::string bitmap_key, const std::string& main_icon_name, const std::string& next_icon_name, bool is_enabled/* = true*/, bool is_compatible/* = true*/, bool is_system/* = false*/) { bitmap_key += !is_enabled ? "_disabled" : ""; bitmap_key += is_compatible ? ",cmpt" : ",ncmpt"; bitmap_key += is_system ? ",syst" : ",nsyst"; bitmap_key += ",h" + std::to_string(icon_height); wxBitmap* bmp = bitmap_cache().find(bitmap_key); if (bmp == nullptr) { // Create the bitmap with color bars. std::vector<wxBitmap> bmps; bmps.emplace_back(m_type == Preset::TYPE_PRINTER ? create_scaled_bitmap(main_icon_name, this, 16, !is_enabled) : is_compatible ? m_bitmapCompatible.bmp() : m_bitmapIncompatible.bmp()); // Paint a lock at the system presets. bmps.emplace_back(is_system ? create_scaled_bitmap(next_icon_name, this, 16, !is_enabled) : bitmap_cache().mkclear(norm_icon_width, icon_height)); bmp = bitmap_cache().insert(bitmap_key, bmps); } return bmp; } bool PresetComboBox::is_selected_physical_printer() { auto selected_item = this->GetSelection(); auto marker = reinterpret_cast<Marker>(this->GetClientData(selected_item)); return marker == LABEL_ITEM_PHYSICAL_PRINTER; } bool PresetComboBox::selection_is_changed_according_to_physical_printers() { if (m_type != Preset::TYPE_PRINTER || !is_selected_physical_printer()) return false; PhysicalPrinterCollection& physical_printers = m_preset_bundle->physical_printers; std::string selected_string = this->GetString(this->GetSelection()).ToUTF8().data(); std::string old_printer_full_name, old_printer_preset; if (physical_printers.has_selection()) { old_printer_full_name = physical_printers.get_selected_full_printer_name(); old_printer_preset = physical_printers.get_selected_printer_preset_name(); } else old_printer_preset = m_collection->get_edited_preset().name; // Select related printer preset on the Printer Settings Tab physical_printers.select_printer(selected_string); std::string preset_name = physical_printers.get_selected_printer_preset_name(); // if new preset wasn't selected, there is no need to call update preset selection if (old_printer_preset == preset_name) { // we need just to update according Plater<->Tab PresetComboBox if (dynamic_cast<PlaterPresetComboBox*>(this)!=nullptr) { wxGetApp().get_tab(m_type)->update_preset_choice(); // Synchronize config.ini with the current selections. m_preset_bundle->export_selections(*wxGetApp().app_config); } else if (dynamic_cast<TabPresetComboBox*>(this)!=nullptr) wxGetApp().sidebar().update_presets(m_type); this->update(); return true; } Tab* tab = wxGetApp().get_tab(Preset::TYPE_PRINTER); if (tab) tab->select_preset(preset_name, false, old_printer_full_name); return true; } #ifdef __APPLE__ bool PresetComboBox::OnAddBitmap(const wxBitmap& bitmap) { if (bitmap.IsOk()) { // we should use scaled! size values of bitmap int width = (int)bitmap.GetScaledWidth(); int height = (int)bitmap.GetScaledHeight(); if (m_usedImgSize.x < 0) { // If size not yet determined, get it from this image. m_usedImgSize.x = width; m_usedImgSize.y = height; // Adjust control size to vertically fit the bitmap wxWindow* ctrl = GetControl(); ctrl->InvalidateBestSize(); wxSize newSz = ctrl->GetBestSize(); wxSize sz = ctrl->GetSize(); if (newSz.y > sz.y) ctrl->SetSize(sz.x, newSz.y); else DetermineIndent(); } wxCHECK_MSG(width == m_usedImgSize.x && height == m_usedImgSize.y, false, "you can only add images of same size"); return true; } return false; } void PresetComboBox::OnDrawItem(wxDC& dc, const wxRect& rect, int item, int flags) const { const wxBitmap& bmp = *(wxBitmap*)m_bitmaps[item]; if (bmp.IsOk()) { // we should use scaled! size values of bitmap wxCoord w = bmp.GetScaledWidth(); wxCoord h = bmp.GetScaledHeight(); const int imgSpacingLeft = 4; // Draw the image centered dc.DrawBitmap(bmp, rect.x + (m_usedImgSize.x - w) / 2 + imgSpacingLeft, rect.y + (rect.height - h) / 2, true); } wxString text = GetString(item); if (!text.empty()) dc.DrawText(text, rect.x + m_imgAreaWidth + 1, rect.y + (rect.height - dc.GetCharHeight()) / 2); } #endif // --------------------------------- // *** PlaterPresetComboBox *** // --------------------------------- PlaterPresetComboBox::PlaterPresetComboBox(wxWindow *parent, Preset::Type preset_type) : PresetComboBox(parent, preset_type, wxSize(15 * wxGetApp().em_unit(), -1)) { Bind(wxEVT_COMBOBOX, [this](wxCommandEvent &evt) { auto selected_item = evt.GetSelection(); auto marker = reinterpret_cast<Marker>(this->GetClientData(selected_item)); if (marker >= LABEL_ITEM_MARKER && marker < LABEL_ITEM_MAX) { this->SetSelection(this->m_last_selected); evt.StopPropagation(); if (marker == LABEL_ITEM_WIZARD_PRINTERS) show_add_menu(); else { ConfigWizard::StartPage sp = ConfigWizard::SP_WELCOME; switch (marker) { case LABEL_ITEM_WIZARD_FILAMENTS: sp = ConfigWizard::SP_FILAMENTS; break; case LABEL_ITEM_WIZARD_MATERIALS: sp = ConfigWizard::SP_MATERIALS; break; default: break; } wxTheApp->CallAfter([sp]() { wxGetApp().run_wizard(ConfigWizard::RR_USER, sp); }); } } else if (marker == LABEL_ITEM_PHYSICAL_PRINTER || this->m_last_selected != selected_item || m_collection->current_is_dirty() ) { this->m_last_selected = selected_item; evt.SetInt(this->m_type); evt.Skip(); } else { evt.StopPropagation(); } }); if (m_type == Preset::TYPE_FILAMENT) { Bind(wxEVT_LEFT_DOWN, [this](wxMouseEvent &event) { const Preset* selected_preset = m_collection->find_preset(m_preset_bundle->filament_presets[m_extruder_idx]); // Wide icons are shown if the currently selected preset is not compatible with the current printer, // and red flag is drown in front of the selected preset. bool wide_icons = selected_preset && !selected_preset->is_compatible; float scale = m_em_unit*0.1f; int shifl_Left = wide_icons ? int(scale * 16 + 0.5) : 0; #if defined(wxBITMAPCOMBOBOX_OWNERDRAWN_BASED) shifl_Left += int(scale * 4 + 0.5f); // IMAGE_SPACING_RIGHT = 4 for wxBitmapComboBox -> Space left of image #endif int icon_right_pos = shifl_Left + int(scale * (24+4) + 0.5); int mouse_pos = event.GetLogicalPosition(wxClientDC(this)).x; if (mouse_pos < shifl_Left || mouse_pos > icon_right_pos ) { // Let the combo box process the mouse click. event.Skip(); return; } // Swallow the mouse click and open the color picker. // get current color DynamicPrintConfig* cfg = wxGetApp().get_tab(Preset::TYPE_PRINTER)->get_config(); auto colors = static_cast<ConfigOptionStrings*>(cfg->option("extruder_colour")->clone()); wxColour clr(colors->values[m_extruder_idx]); if (!clr.IsOk()) clr = wxColour(0,0,0); // Don't set alfa to transparence auto data = new wxColourData(); data->SetChooseFull(1); data->SetColour(clr); wxColourDialog dialog(this, data); dialog.CenterOnParent(); if (dialog.ShowModal() == wxID_OK) { colors->values[m_extruder_idx] = dialog.GetColourData().GetColour().GetAsString(wxC2S_HTML_SYNTAX).ToStdString(); DynamicPrintConfig cfg_new = *cfg; cfg_new.set_key_value("extruder_colour", colors); wxGetApp().get_tab(Preset::TYPE_PRINTER)->load_config(cfg_new); this->update(); wxGetApp().plater()->on_config_change(cfg_new); } }); } edit_btn = new ScalableButton(parent, wxID_ANY, "cog"); edit_btn->SetToolTip(_L("Click to edit preset")); edit_btn->Bind(wxEVT_BUTTON, [this](wxCommandEvent) { // In a case of a physical printer, for its editing open PhysicalPrinterDialog if (m_type == Preset::TYPE_PRINTER/* && this->is_selected_physical_printer()*/) { this->show_edit_menu(); return; } if (!switch_to_tab()) return; /* In a case of a multi-material printing, for editing another Filament Preset * it's needed to select this preset for the "Filament settings" Tab */ if (m_type == Preset::TYPE_FILAMENT && wxGetApp().extruders_edited_cnt() > 1) { const std::string& selected_preset = GetString(GetSelection()).ToUTF8().data(); // Call select_preset() only if there is new preset and not just modified if ( !boost::algorithm::ends_with(selected_preset, Preset::suffix_modified()) ) { const std::string& preset_name = wxGetApp().preset_bundle->filaments.get_preset_name_by_alias(selected_preset); wxGetApp().get_tab(m_type)->select_preset(preset_name); } } }); } PlaterPresetComboBox::~PlaterPresetComboBox() { if (edit_btn) edit_btn->Destroy(); } bool PlaterPresetComboBox::switch_to_tab() { Tab* tab = wxGetApp().get_tab(m_type); if (!tab) return false; int page_id = wxGetApp().tab_panel()->FindPage(tab); if (page_id == wxNOT_FOUND) return false; wxGetApp().tab_panel()->SetSelection(page_id); // Switch to Settings NotePad wxGetApp().mainframe->select_tab(); return true; } void PlaterPresetComboBox::show_add_menu() { wxMenu* menu = new wxMenu(); append_menu_item(menu, wxID_ANY, _L("Add/Remove presets"), "", [this](wxCommandEvent&) { wxTheApp->CallAfter([]() { wxGetApp().run_wizard(ConfigWizard::RR_USER, ConfigWizard::SP_PRINTERS); }); }, "edit_uni", menu, []() { return true; }, wxGetApp().plater()); append_menu_item(menu, wxID_ANY, _L("Add physical printer"), "", [this](wxCommandEvent&) { PhysicalPrinterDialog dlg(wxEmptyString); if (dlg.ShowModal() == wxID_OK) update(); }, "edit_uni", menu, []() { return true; }, wxGetApp().plater()); wxGetApp().plater()->PopupMenu(menu); } void PlaterPresetComboBox::show_edit_menu() { wxMenu* menu = new wxMenu(); append_menu_item(menu, wxID_ANY, _L("Edit preset"), "", [this](wxCommandEvent&) { this->switch_to_tab(); }, "cog", menu, []() { return true; }, wxGetApp().plater()); if (this->is_selected_physical_printer()) { append_menu_item(menu, wxID_ANY, _L("Edit physical printer"), "", [this](wxCommandEvent&) { PhysicalPrinterDialog dlg(this->GetString(this->GetSelection())); if (dlg.ShowModal() == wxID_OK) update(); }, "cog", menu, []() { return true; }, wxGetApp().plater()); append_menu_item(menu, wxID_ANY, _L("Delete physical printer"), "", [this](wxCommandEvent&) { const std::string& printer_name = m_preset_bundle->physical_printers.get_selected_full_printer_name(); if (printer_name.empty()) return; const wxString msg = from_u8((boost::format(_u8L("Are you sure you want to delete \"%1%\" printer?")) % printer_name).str()); if (wxMessageDialog(this, msg, _L("Delete Physical Printer"), wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION).ShowModal() != wxID_YES) return; m_preset_bundle->physical_printers.delete_selected_printer(); wxGetApp().get_tab(m_type)->update_preset_choice(); update(); }, "cross", menu, []() { return true; }, wxGetApp().plater()); } else append_menu_item(menu, wxID_ANY, _L("Add/Remove presets"), "", [this](wxCommandEvent&) { wxTheApp->CallAfter([]() { wxGetApp().run_wizard(ConfigWizard::RR_USER, ConfigWizard::SP_PRINTERS); }); }, "edit_uni", menu, []() { return true; }, wxGetApp().plater()); append_menu_item(menu, wxID_ANY, _L("Add physical printer"), "", [this](wxCommandEvent&) { PhysicalPrinterDialog dlg(wxEmptyString); if (dlg.ShowModal() == wxID_OK) update(); }, "edit_uni", menu, []() { return true; }, wxGetApp().plater()); wxGetApp().plater()->PopupMenu(menu); } // Only the compatible presets are shown. // If an incompatible preset is selected, it is shown as well. void PlaterPresetComboBox::update() { if (m_type == Preset::TYPE_FILAMENT && (m_preset_bundle->printers.get_edited_preset().printer_technology() == ptSLA || m_preset_bundle->filament_presets.size() <= (size_t)m_extruder_idx) ) return; // Otherwise fill in the list from scratch. this->Freeze(); this->Clear(); invalidate_selection(); const Preset* selected_filament_preset; std::string extruder_color; if (m_type == Preset::TYPE_FILAMENT) { unsigned char rgb[3]; extruder_color = m_preset_bundle->printers.get_edited_preset().config.opt_string("extruder_colour", (unsigned int)m_extruder_idx); if (!bitmap_cache().parse_color(extruder_color, rgb)) // Extruder color is not defined. extruder_color.clear(); selected_filament_preset = m_collection->find_preset(m_preset_bundle->filament_presets[m_extruder_idx]); assert(selected_filament_preset); } bool has_selection = m_collection->get_selected_idx() != size_t(-1); const Preset* selected_preset = m_type == Preset::TYPE_FILAMENT ? selected_filament_preset : has_selection ? &m_collection->get_selected_preset() : nullptr; // Show wide icons if the currently selected preset is not compatible with the current printer, // and draw a red flag in front of the selected preset. bool wide_icons = selected_preset && !selected_preset->is_compatible; std::map<wxString, wxBitmap*> nonsys_presets; wxString selected_user_preset = ""; wxString tooltip = ""; const std::deque<Preset>& presets = m_collection->get_presets(); if (!presets.front().is_visible) this->set_label_marker(this->Append(separator(L("System presets")), wxNullBitmap)); for (size_t i = presets.front().is_visible ? 0 : m_collection->num_default_presets(); i < presets.size(); ++i) { const Preset& preset = presets[i]; bool is_selected = m_type == Preset::TYPE_FILAMENT ? m_preset_bundle->filament_presets[m_extruder_idx] == preset.name : // The case, when some physical printer is selected m_type == Preset::TYPE_PRINTER && m_preset_bundle->physical_printers.has_selection() ? false : i == m_collection->get_selected_idx(); if (!preset.is_visible || (!preset.is_compatible && !is_selected)) continue; std::string bitmap_key, filament_rgb, extruder_rgb; std::string bitmap_type_name = bitmap_key = m_type == Preset::TYPE_PRINTER && preset.printer_technology() == ptSLA ? "sla_printer" : m_main_bitmap_name; bool single_bar = false; if (m_type == Preset::TYPE_FILAMENT) { // Assign an extruder color to the selected item if the extruder color is defined. filament_rgb = is_selected ? selected_filament_preset->config.opt_string("filament_colour", 0) : preset.config.opt_string("filament_colour", 0); extruder_rgb = (is_selected && !extruder_color.empty()) ? extruder_color : filament_rgb; single_bar = filament_rgb == extruder_rgb; bitmap_key += single_bar ? filament_rgb : filament_rgb + extruder_rgb; } wxBitmap* bmp = get_bmp(bitmap_key, wide_icons, bitmap_type_name, preset.is_compatible, preset.is_system || preset.is_default, single_bar, filament_rgb, extruder_rgb); assert(bmp); const std::string name = preset.alias.empty() ? preset.name : preset.alias; if (preset.is_default || preset.is_system) { Append(wxString::FromUTF8((name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), *bmp); validate_selection(is_selected); if (is_selected) tooltip = wxString::FromUTF8(preset.name.c_str()); } else { nonsys_presets.emplace(wxString::FromUTF8((name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), bmp); if (is_selected) { selected_user_preset = wxString::FromUTF8((name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()); tooltip = wxString::FromUTF8(preset.name.c_str()); } } if (i + 1 == m_collection->num_default_presets()) set_label_marker(Append(separator(L("System presets")), wxNullBitmap)); } if (!nonsys_presets.empty()) { set_label_marker(Append(separator(L("User presets")), wxNullBitmap)); for (std::map<wxString, wxBitmap*>::iterator it = nonsys_presets.begin(); it != nonsys_presets.end(); ++it) { Append(it->first, *it->second); validate_selection(it->first == selected_user_preset); } } if (m_type == Preset::TYPE_PRINTER) { // add Physical printers, if any exists if (!m_preset_bundle->physical_printers.empty()) { set_label_marker(Append(separator(L("Physical printers")), wxNullBitmap)); const PhysicalPrinterCollection& ph_printers = m_preset_bundle->physical_printers; for (PhysicalPrinterCollection::ConstIterator it = ph_printers.begin(); it != ph_printers.end(); ++it) { for (const std::string preset_name : it->get_preset_names()) { Preset* preset = m_collection->find_preset(preset_name); if (!preset) continue; std::string main_icon_name, bitmap_key = main_icon_name = preset->printer_technology() == ptSLA ? "sla_printer" : m_main_bitmap_name; wxBitmap* bmp = get_bmp(main_icon_name, wide_icons, main_icon_name); assert(bmp); set_label_marker(Append(wxString::FromUTF8((it->get_full_name(preset_name) + (preset->is_dirty ? Preset::suffix_modified() : "")).c_str()), *bmp), LABEL_ITEM_PHYSICAL_PRINTER); validate_selection(ph_printers.is_selected(it, preset_name)); } } } } if (m_type == Preset::TYPE_PRINTER || m_type == Preset::TYPE_SLA_MATERIAL) { wxBitmap* bmp = get_bmp("edit_preset_list", wide_icons, "edit_uni"); assert(bmp); if (m_type == Preset::TYPE_SLA_MATERIAL) set_label_marker(Append(separator(L("Add/Remove materials")), *bmp), LABEL_ITEM_WIZARD_MATERIALS); else set_label_marker(Append(separator(L("Add/Remove printers")), *bmp), LABEL_ITEM_WIZARD_PRINTERS); } update_selection(); Thaw(); if (!tooltip.IsEmpty()) SetToolTip(tooltip); // Update control min size after rescale (changed Display DPI under MSW) if (GetMinWidth() != 20 * m_em_unit) SetMinSize(wxSize(20 * m_em_unit, GetSize().GetHeight())); } void PlaterPresetComboBox::msw_rescale() { PresetComboBox::msw_rescale(); edit_btn->msw_rescale(); } // --------------------------------- // *** TabPresetComboBox *** // --------------------------------- TabPresetComboBox::TabPresetComboBox(wxWindow* parent, Preset::Type preset_type) : PresetComboBox(parent, preset_type, wxSize(35 * wxGetApp().em_unit(), -1)) { Bind(wxEVT_COMBOBOX, [this](wxCommandEvent& evt) { // see https://github.com/prusa3d/PrusaSlicer/issues/3889 // Under OSX: in case of use of a same names written in different case (like "ENDER" and "Ender") // m_presets_choice->GetSelection() will return first item, because search in PopupListCtrl is case-insensitive. // So, use GetSelection() from event parameter auto selected_item = evt.GetSelection(); auto marker = reinterpret_cast<Marker>(this->GetClientData(selected_item)); if (marker >= LABEL_ITEM_DISABLED && marker < LABEL_ITEM_MAX) { this->SetSelection(this->m_last_selected); if (marker == LABEL_ITEM_WIZARD_PRINTERS) wxTheApp->CallAfter([this]() { wxGetApp().run_wizard(ConfigWizard::RR_USER, ConfigWizard::SP_PRINTERS); // update combobox if its parent is a PhysicalPrinterDialog PhysicalPrinterDialog* parent = dynamic_cast<PhysicalPrinterDialog*>(this->GetParent()); if (parent != nullptr) update(); }); } else if (on_selection_changed && (m_last_selected != selected_item || m_collection->current_is_dirty()) ) { m_last_selected = selected_item; on_selection_changed(selected_item); } evt.StopPropagation(); }); } // Update the choice UI from the list of presets. // If show_incompatible, all presets are shown, otherwise only the compatible presets are shown. // If an incompatible preset is selected, it is shown as well. void TabPresetComboBox::update() { Freeze(); Clear(); invalidate_selection(); const std::deque<Preset>& presets = m_collection->get_presets(); std::map<wxString, std::pair<wxBitmap*, bool>> nonsys_presets; wxString selected = ""; if (!presets.front().is_visible) set_label_marker(Append(separator(L("System presets")), wxNullBitmap)); size_t idx_selected = m_collection->get_selected_idx(); if (m_type == Preset::TYPE_PRINTER && m_preset_bundle->physical_printers.has_selection()) { std::string sel_preset_name = m_preset_bundle->physical_printers.get_selected_printer_preset_name(); Preset* preset = m_collection->find_preset(sel_preset_name); if (!preset) m_preset_bundle->physical_printers.unselect_printer(); } for (size_t i = presets.front().is_visible ? 0 : m_collection->num_default_presets(); i < presets.size(); ++i) { const Preset& preset = presets[i]; if (!preset.is_visible || (!show_incompatible && !preset.is_compatible && i != idx_selected)) continue; // marker used for disable incompatible printer models for the selected physical printer bool is_enabled = true; std::string bitmap_key = "tab"; if (m_type == Preset::TYPE_PRINTER) { bitmap_key += "_printer"; if (preset.printer_technology() == ptSLA) bitmap_key += "_sla"; } std::string main_icon_name = m_type == Preset::TYPE_PRINTER && preset.printer_technology() == ptSLA ? "sla_printer" : m_main_bitmap_name; wxBitmap* bmp = get_bmp(bitmap_key, main_icon_name, "lock_closed", is_enabled, preset.is_compatible, preset.is_system || preset.is_default); assert(bmp); if (preset.is_default || preset.is_system) { int item_id = Append(wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), *bmp); if (!is_enabled) set_label_marker(item_id, LABEL_ITEM_DISABLED); validate_selection(i == idx_selected); } else { std::pair<wxBitmap*, bool> pair(bmp, is_enabled); nonsys_presets.emplace(wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), std::pair<wxBitmap*, bool>(bmp, is_enabled)); if (i == idx_selected) selected = wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()); } if (i + 1 == m_collection->num_default_presets()) set_label_marker(Append(separator(L("System presets")), wxNullBitmap)); } if (!nonsys_presets.empty()) { set_label_marker(Append(separator(L("User presets")), wxNullBitmap)); for (std::map<wxString, std::pair<wxBitmap*, bool>>::iterator it = nonsys_presets.begin(); it != nonsys_presets.end(); ++it) { int item_id = Append(it->first, *it->second.first); bool is_enabled = it->second.second; if (!is_enabled) set_label_marker(item_id, LABEL_ITEM_DISABLED); validate_selection(it->first == selected); } } if (m_type == Preset::TYPE_PRINTER) { // add Physical printers, if any exists if (!m_preset_bundle->physical_printers.empty()) { set_label_marker(Append(separator(L("Physical printers")), wxNullBitmap)); const PhysicalPrinterCollection& ph_printers = m_preset_bundle->physical_printers; for (PhysicalPrinterCollection::ConstIterator it = ph_printers.begin(); it != ph_printers.end(); ++it) { for (const std::string preset_name : it->get_preset_names()) { Preset* preset = m_collection->find_preset(preset_name); if (!preset) continue; std::string main_icon_name = preset->printer_technology() == ptSLA ? "sla_printer" : m_main_bitmap_name; wxBitmap* bmp = get_bmp(main_icon_name, main_icon_name, "", true, true, false); assert(bmp); set_label_marker(Append(wxString::FromUTF8((it->get_full_name(preset_name) + (preset->is_dirty ? Preset::suffix_modified() : "")).c_str()), *bmp), LABEL_ITEM_PHYSICAL_PRINTER); validate_selection(ph_printers.is_selected(it, preset_name)); } } } // add "Add/Remove printers" item std::string icon_name = "edit_uni"; wxBitmap* bmp = get_bmp("edit_preset_list, tab,", icon_name, ""); assert(bmp); set_label_marker(Append(separator(L("Add/Remove printers")), *bmp), LABEL_ITEM_WIZARD_PRINTERS); } update_selection(); Thaw(); } void TabPresetComboBox::msw_rescale() { PresetComboBox::msw_rescale(); wxSize sz = wxSize(35 * m_em_unit, -1); SetMinSize(sz); SetSize(sz); } void TabPresetComboBox::update_dirty() { // 1) Update the dirty flag of the current preset. m_collection->update_dirty(); // 2) Update the labels. wxWindowUpdateLocker noUpdates(this); for (unsigned int ui_id = 0; ui_id < GetCount(); ++ui_id) { auto marker = reinterpret_cast<Marker>(this->GetClientData(ui_id)); if (marker >= LABEL_ITEM_MARKER) continue; std::string old_label = GetString(ui_id).utf8_str().data(); std::string preset_name = Preset::remove_suffix_modified(old_label); std::string ph_printer_name; if (marker == LABEL_ITEM_PHYSICAL_PRINTER) { ph_printer_name = PhysicalPrinter::get_short_name(preset_name); preset_name = PhysicalPrinter::get_preset_name(preset_name); } const Preset* preset = m_collection->find_preset(preset_name, false); if (preset) { std::string new_label = preset->is_dirty ? preset->name + Preset::suffix_modified() : preset->name; if (marker == LABEL_ITEM_PHYSICAL_PRINTER) new_label = ph_printer_name + PhysicalPrinter::separator() + new_label; if (old_label != new_label) SetString(ui_id, wxString::FromUTF8(new_label.c_str())); } } #ifdef __APPLE__ // wxWidgets on OSX do not upload the text of the combo box line automatically. // Force it to update by re-selecting. SetSelection(GetSelection()); #endif /* __APPLE __ */ } }} // namespace Slic3r::GUI Fixed #4918 Added missed "Add/Remove filaments" item for the filament preset combobox #include "PresetComboBoxes.hpp" #include <cstddef> #include <vector> #include <string> #include <boost/algorithm/string.hpp> #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/textctrl.h> #include <wx/button.h> #include <wx/statbox.h> #include <wx/colordlg.h> #include <wx/wupdlock.h> #include <wx/menu.h> #include "libslic3r/libslic3r.h" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/PresetBundle.hpp" #include "GUI.hpp" #include "GUI_App.hpp" #include "Plater.hpp" #include "MainFrame.hpp" #include "format.hpp" #include "Tab.hpp" #include "ConfigWizard.hpp" #include "../Utils/ASCIIFolding.hpp" #include "../Utils/FixModelByWin10.hpp" #include "../Utils/UndoRedo.hpp" #include "BitmapCache.hpp" #include "PhysicalPrinterDialog.hpp" #include "SavePresetDialog.hpp" using Slic3r::GUI::format_wxstr; namespace Slic3r { namespace GUI { #define BORDER_W 10 // --------------------------------- // *** PresetComboBox *** // --------------------------------- /* For PresetComboBox we use bitmaps that are created from images that are already scaled appropriately for Retina * (Contrary to the intuition, the `scale` argument for Bitmap's constructor doesn't mean * "please scale this to such and such" but rather * "the wxImage is already sized for backing scale such and such". ) * Unfortunately, the constructor changes the size of wxBitmap too. * Thus We need to use unscaled size value for bitmaps that we use * to avoid scaled size of control items. * For this purpose control drawing methods and * control size calculation methods (virtual) are overridden. **/ PresetComboBox::PresetComboBox(wxWindow* parent, Preset::Type preset_type, const wxSize& size) : wxBitmapComboBox(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, size, 0, nullptr, wxCB_READONLY), m_type(preset_type), m_last_selected(wxNOT_FOUND), m_em_unit(em_unit(this)), m_preset_bundle(wxGetApp().preset_bundle) { SetFont(wxGetApp().normal_font()); #ifdef _WIN32 // Workaround for ignoring CBN_EDITCHANGE events, which are processed after the content of the combo box changes, so that // the index of the item inside CBN_EDITCHANGE may no more be valid. EnableTextChangedEvents(false); #endif /* _WIN32 */ switch (m_type) { case Preset::TYPE_PRINT: { m_collection = &m_preset_bundle->prints; m_main_bitmap_name = "cog"; break; } case Preset::TYPE_FILAMENT: { m_collection = &m_preset_bundle->filaments; m_main_bitmap_name = "spool"; break; } case Preset::TYPE_SLA_PRINT: { m_collection = &m_preset_bundle->sla_prints; m_main_bitmap_name = "cog"; break; } case Preset::TYPE_SLA_MATERIAL: { m_collection = &m_preset_bundle->sla_materials; m_main_bitmap_name = "resin"; break; } case Preset::TYPE_PRINTER: { m_collection = &m_preset_bundle->printers; m_main_bitmap_name = "printer"; break; } default: break; } m_bitmapCompatible = ScalableBitmap(this, "flag_green"); m_bitmapIncompatible = ScalableBitmap(this, "flag_red"); // parameters for an icon's drawing fill_width_height(); Bind(wxEVT_COMBOBOX, [this](wxCommandEvent& evt) { // see https://github.com/prusa3d/PrusaSlicer/issues/3889 // Under OSX: in case of use of a same names written in different case (like "ENDER" and "Ender") // m_presets_choice->GetSelection() will return first item, because search in PopupListCtrl is case-insensitive. // So, use GetSelection() from event parameter auto selected_item = evt.GetSelection(); auto marker = reinterpret_cast<Marker>(this->GetClientData(selected_item)); if (marker >= LABEL_ITEM_DISABLED && marker < LABEL_ITEM_MAX) this->SetSelection(this->m_last_selected); else if (on_selection_changed && (m_last_selected != selected_item || m_collection->current_is_dirty())) { m_last_selected = selected_item; on_selection_changed(selected_item); evt.StopPropagation(); } evt.Skip(); }); } PresetComboBox::~PresetComboBox() { } BitmapCache& PresetComboBox::bitmap_cache() { static BitmapCache bmps; return bmps; } void PresetComboBox::set_label_marker(int item, LabelItemType label_item_type) { this->SetClientData(item, (void*)label_item_type); } bool PresetComboBox::set_printer_technology(PrinterTechnology pt) { if (printer_technology != pt) { printer_technology = pt; return true; } return false; } void PresetComboBox::invalidate_selection() { m_last_selected = INT_MAX; // this value means that no one item is selected } void PresetComboBox::validate_selection(bool predicate/*=false*/) { if (predicate || // just in case: mark m_last_selected as a first added element m_last_selected == INT_MAX) m_last_selected = GetCount() - 1; } void PresetComboBox::update_selection() { /* If selected_preset_item is still equal to INT_MAX, it means that * there is no presets added to the list. * So, select last combobox item ("Add/Remove preset") */ validate_selection(); SetSelection(m_last_selected); SetToolTip(GetString(m_last_selected)); } void PresetComboBox::update(std::string select_preset_name) { Freeze(); Clear(); invalidate_selection(); const std::deque<Preset>& presets = m_collection->get_presets(); std::map<wxString, std::pair<wxBitmap*, bool>> nonsys_presets; std::map<wxString, wxBitmap*> incomp_presets; wxString selected = ""; if (!presets.front().is_visible) set_label_marker(Append(separator(L("System presets")), wxNullBitmap)); for (size_t i = presets.front().is_visible ? 0 : m_collection->num_default_presets(); i < presets.size(); ++i) { const Preset& preset = presets[i]; if (!preset.is_visible || !preset.is_compatible) continue; // marker used for disable incompatible printer models for the selected physical printer bool is_enabled = m_type == Preset::TYPE_PRINTER && printer_technology != ptAny ? preset.printer_technology() == printer_technology : true; if (select_preset_name.empty() && is_enabled) select_preset_name = preset.name; std::string bitmap_key = "cb"; if (m_type == Preset::TYPE_PRINTER) { bitmap_key += "_printer"; if (preset.printer_technology() == ptSLA) bitmap_key += "_sla"; } std::string main_icon_name = m_type == Preset::TYPE_PRINTER && preset.printer_technology() == ptSLA ? "sla_printer" : m_main_bitmap_name; wxBitmap* bmp = get_bmp(bitmap_key, main_icon_name, "lock_closed", is_enabled, preset.is_compatible, preset.is_system || preset.is_default); assert(bmp); if (!is_enabled) incomp_presets.emplace(wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), bmp); else if (preset.is_default || preset.is_system) { Append(wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), *bmp); validate_selection(preset.name == select_preset_name); } else { nonsys_presets.emplace(wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), std::pair<wxBitmap*, bool>(bmp, is_enabled)); if (preset.name == select_preset_name || (select_preset_name.empty() && is_enabled)) selected = wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()); } if (i + 1 == m_collection->num_default_presets()) set_label_marker(Append(separator(L("System presets")), wxNullBitmap)); } if (!nonsys_presets.empty()) { set_label_marker(Append(separator(L("User presets")), wxNullBitmap)); for (std::map<wxString, std::pair<wxBitmap*, bool>>::iterator it = nonsys_presets.begin(); it != nonsys_presets.end(); ++it) { int item_id = Append(it->first, *it->second.first); bool is_enabled = it->second.second; if (!is_enabled) set_label_marker(item_id, LABEL_ITEM_DISABLED); validate_selection(it->first == selected); } } if (!incomp_presets.empty()) { set_label_marker(Append(separator(L("Incompatible presets")), wxNullBitmap)); for (std::map<wxString, wxBitmap*>::iterator it = incomp_presets.begin(); it != incomp_presets.end(); ++it) { set_label_marker(Append(it->first, *it->second), LABEL_ITEM_DISABLED); } } update_selection(); Thaw(); } void PresetComboBox::update() { this->update(into_u8(this->GetString(this->GetSelection()))); } void PresetComboBox::msw_rescale() { m_em_unit = em_unit(this); m_bitmapIncompatible.msw_rescale(); m_bitmapCompatible.msw_rescale(); // parameters for an icon's drawing fill_width_height(); // update the control to redraw the icons update(); } void PresetComboBox::fill_width_height() { // To avoid asserts, each added bitmap to wxBitmapCombobox should be the same size, so // set a bitmap's height to m_bitmapCompatible->GetHeight() and norm_icon_width to m_bitmapCompatible->GetWidth() icon_height = m_bitmapCompatible.GetBmpHeight(); norm_icon_width = m_bitmapCompatible.GetBmpWidth(); /* It's supposed that standard size of an icon is 16px*16px for 100% scaled display. * So set sizes for solid_colored icons used for filament preset * and scale them in respect to em_unit value */ const float scale_f = (float)m_em_unit * 0.1f; thin_icon_width = lroundf(8 * scale_f); // analogue to 8px; wide_icon_width = norm_icon_width + thin_icon_width; space_icon_width = lroundf(2 * scale_f); thin_space_icon_width = 2 * space_icon_width; wide_space_icon_width = 3 * space_icon_width; } wxString PresetComboBox::separator(const std::string& label) { return wxString::FromUTF8(separator_head()) + _(label) + wxString::FromUTF8(separator_tail()); } wxBitmap* PresetComboBox::get_bmp( std::string bitmap_key, bool wide_icons, const std::string& main_icon_name, bool is_compatible/* = true*/, bool is_system/* = false*/, bool is_single_bar/* = false*/, std::string filament_rgb/* = ""*/, std::string extruder_rgb/* = ""*/) { // If the filament preset is not compatible and there is a "red flag" icon loaded, show it left // to the filament color image. if (wide_icons) bitmap_key += is_compatible ? ",cmpt" : ",ncmpt"; bitmap_key += is_system ? ",syst" : ",nsyst"; bitmap_key += ",h" + std::to_string(icon_height); wxBitmap* bmp = bitmap_cache().find(bitmap_key); if (bmp == nullptr) { // Create the bitmap with color bars. std::vector<wxBitmap> bmps; if (wide_icons) // Paint a red flag for incompatible presets. bmps.emplace_back(is_compatible ? bitmap_cache().mkclear(norm_icon_width, icon_height) : m_bitmapIncompatible.bmp()); if (m_type == Preset::TYPE_FILAMENT) { unsigned char rgb[3]; // Paint the color bars. bitmap_cache().parse_color(filament_rgb, rgb); bmps.emplace_back(bitmap_cache().mksolid(is_single_bar ? wide_icon_width : norm_icon_width, icon_height, rgb)); if (!is_single_bar) { bitmap_cache().parse_color(extruder_rgb, rgb); bmps.emplace_back(bitmap_cache().mksolid(thin_icon_width, icon_height, rgb)); } // Paint a lock at the system presets. bmps.emplace_back(bitmap_cache().mkclear(space_icon_width, icon_height)); } else { // Paint the color bars. bmps.emplace_back(bitmap_cache().mkclear(thin_space_icon_width, icon_height)); bmps.emplace_back(create_scaled_bitmap(main_icon_name)); // Paint a lock at the system presets. bmps.emplace_back(bitmap_cache().mkclear(wide_space_icon_width, icon_height)); } bmps.emplace_back(is_system ? create_scaled_bitmap("lock_closed") : bitmap_cache().mkclear(norm_icon_width, icon_height)); bmp = bitmap_cache().insert(bitmap_key, bmps); } return bmp; } wxBitmap* PresetComboBox::get_bmp( std::string bitmap_key, const std::string& main_icon_name, const std::string& next_icon_name, bool is_enabled/* = true*/, bool is_compatible/* = true*/, bool is_system/* = false*/) { bitmap_key += !is_enabled ? "_disabled" : ""; bitmap_key += is_compatible ? ",cmpt" : ",ncmpt"; bitmap_key += is_system ? ",syst" : ",nsyst"; bitmap_key += ",h" + std::to_string(icon_height); wxBitmap* bmp = bitmap_cache().find(bitmap_key); if (bmp == nullptr) { // Create the bitmap with color bars. std::vector<wxBitmap> bmps; bmps.emplace_back(m_type == Preset::TYPE_PRINTER ? create_scaled_bitmap(main_icon_name, this, 16, !is_enabled) : is_compatible ? m_bitmapCompatible.bmp() : m_bitmapIncompatible.bmp()); // Paint a lock at the system presets. bmps.emplace_back(is_system ? create_scaled_bitmap(next_icon_name, this, 16, !is_enabled) : bitmap_cache().mkclear(norm_icon_width, icon_height)); bmp = bitmap_cache().insert(bitmap_key, bmps); } return bmp; } bool PresetComboBox::is_selected_physical_printer() { auto selected_item = this->GetSelection(); auto marker = reinterpret_cast<Marker>(this->GetClientData(selected_item)); return marker == LABEL_ITEM_PHYSICAL_PRINTER; } bool PresetComboBox::selection_is_changed_according_to_physical_printers() { if (m_type != Preset::TYPE_PRINTER || !is_selected_physical_printer()) return false; PhysicalPrinterCollection& physical_printers = m_preset_bundle->physical_printers; std::string selected_string = this->GetString(this->GetSelection()).ToUTF8().data(); std::string old_printer_full_name, old_printer_preset; if (physical_printers.has_selection()) { old_printer_full_name = physical_printers.get_selected_full_printer_name(); old_printer_preset = physical_printers.get_selected_printer_preset_name(); } else old_printer_preset = m_collection->get_edited_preset().name; // Select related printer preset on the Printer Settings Tab physical_printers.select_printer(selected_string); std::string preset_name = physical_printers.get_selected_printer_preset_name(); // if new preset wasn't selected, there is no need to call update preset selection if (old_printer_preset == preset_name) { // we need just to update according Plater<->Tab PresetComboBox if (dynamic_cast<PlaterPresetComboBox*>(this)!=nullptr) { wxGetApp().get_tab(m_type)->update_preset_choice(); // Synchronize config.ini with the current selections. m_preset_bundle->export_selections(*wxGetApp().app_config); } else if (dynamic_cast<TabPresetComboBox*>(this)!=nullptr) wxGetApp().sidebar().update_presets(m_type); this->update(); return true; } Tab* tab = wxGetApp().get_tab(Preset::TYPE_PRINTER); if (tab) tab->select_preset(preset_name, false, old_printer_full_name); return true; } #ifdef __APPLE__ bool PresetComboBox::OnAddBitmap(const wxBitmap& bitmap) { if (bitmap.IsOk()) { // we should use scaled! size values of bitmap int width = (int)bitmap.GetScaledWidth(); int height = (int)bitmap.GetScaledHeight(); if (m_usedImgSize.x < 0) { // If size not yet determined, get it from this image. m_usedImgSize.x = width; m_usedImgSize.y = height; // Adjust control size to vertically fit the bitmap wxWindow* ctrl = GetControl(); ctrl->InvalidateBestSize(); wxSize newSz = ctrl->GetBestSize(); wxSize sz = ctrl->GetSize(); if (newSz.y > sz.y) ctrl->SetSize(sz.x, newSz.y); else DetermineIndent(); } wxCHECK_MSG(width == m_usedImgSize.x && height == m_usedImgSize.y, false, "you can only add images of same size"); return true; } return false; } void PresetComboBox::OnDrawItem(wxDC& dc, const wxRect& rect, int item, int flags) const { const wxBitmap& bmp = *(wxBitmap*)m_bitmaps[item]; if (bmp.IsOk()) { // we should use scaled! size values of bitmap wxCoord w = bmp.GetScaledWidth(); wxCoord h = bmp.GetScaledHeight(); const int imgSpacingLeft = 4; // Draw the image centered dc.DrawBitmap(bmp, rect.x + (m_usedImgSize.x - w) / 2 + imgSpacingLeft, rect.y + (rect.height - h) / 2, true); } wxString text = GetString(item); if (!text.empty()) dc.DrawText(text, rect.x + m_imgAreaWidth + 1, rect.y + (rect.height - dc.GetCharHeight()) / 2); } #endif // --------------------------------- // *** PlaterPresetComboBox *** // --------------------------------- PlaterPresetComboBox::PlaterPresetComboBox(wxWindow *parent, Preset::Type preset_type) : PresetComboBox(parent, preset_type, wxSize(15 * wxGetApp().em_unit(), -1)) { Bind(wxEVT_COMBOBOX, [this](wxCommandEvent &evt) { auto selected_item = evt.GetSelection(); auto marker = reinterpret_cast<Marker>(this->GetClientData(selected_item)); if (marker >= LABEL_ITEM_MARKER && marker < LABEL_ITEM_MAX) { this->SetSelection(this->m_last_selected); evt.StopPropagation(); if (marker == LABEL_ITEM_WIZARD_PRINTERS) show_add_menu(); else { ConfigWizard::StartPage sp = ConfigWizard::SP_WELCOME; switch (marker) { case LABEL_ITEM_WIZARD_FILAMENTS: sp = ConfigWizard::SP_FILAMENTS; break; case LABEL_ITEM_WIZARD_MATERIALS: sp = ConfigWizard::SP_MATERIALS; break; default: break; } wxTheApp->CallAfter([sp]() { wxGetApp().run_wizard(ConfigWizard::RR_USER, sp); }); } } else if (marker == LABEL_ITEM_PHYSICAL_PRINTER || this->m_last_selected != selected_item || m_collection->current_is_dirty() ) { this->m_last_selected = selected_item; evt.SetInt(this->m_type); evt.Skip(); } else { evt.StopPropagation(); } }); if (m_type == Preset::TYPE_FILAMENT) { Bind(wxEVT_LEFT_DOWN, [this](wxMouseEvent &event) { const Preset* selected_preset = m_collection->find_preset(m_preset_bundle->filament_presets[m_extruder_idx]); // Wide icons are shown if the currently selected preset is not compatible with the current printer, // and red flag is drown in front of the selected preset. bool wide_icons = selected_preset && !selected_preset->is_compatible; float scale = m_em_unit*0.1f; int shifl_Left = wide_icons ? int(scale * 16 + 0.5) : 0; #if defined(wxBITMAPCOMBOBOX_OWNERDRAWN_BASED) shifl_Left += int(scale * 4 + 0.5f); // IMAGE_SPACING_RIGHT = 4 for wxBitmapComboBox -> Space left of image #endif int icon_right_pos = shifl_Left + int(scale * (24+4) + 0.5); int mouse_pos = event.GetLogicalPosition(wxClientDC(this)).x; if (mouse_pos < shifl_Left || mouse_pos > icon_right_pos ) { // Let the combo box process the mouse click. event.Skip(); return; } // Swallow the mouse click and open the color picker. // get current color DynamicPrintConfig* cfg = wxGetApp().get_tab(Preset::TYPE_PRINTER)->get_config(); auto colors = static_cast<ConfigOptionStrings*>(cfg->option("extruder_colour")->clone()); wxColour clr(colors->values[m_extruder_idx]); if (!clr.IsOk()) clr = wxColour(0,0,0); // Don't set alfa to transparence auto data = new wxColourData(); data->SetChooseFull(1); data->SetColour(clr); wxColourDialog dialog(this, data); dialog.CenterOnParent(); if (dialog.ShowModal() == wxID_OK) { colors->values[m_extruder_idx] = dialog.GetColourData().GetColour().GetAsString(wxC2S_HTML_SYNTAX).ToStdString(); DynamicPrintConfig cfg_new = *cfg; cfg_new.set_key_value("extruder_colour", colors); wxGetApp().get_tab(Preset::TYPE_PRINTER)->load_config(cfg_new); this->update(); wxGetApp().plater()->on_config_change(cfg_new); } }); } edit_btn = new ScalableButton(parent, wxID_ANY, "cog"); edit_btn->SetToolTip(_L("Click to edit preset")); edit_btn->Bind(wxEVT_BUTTON, [this](wxCommandEvent) { // In a case of a physical printer, for its editing open PhysicalPrinterDialog if (m_type == Preset::TYPE_PRINTER/* && this->is_selected_physical_printer()*/) { this->show_edit_menu(); return; } if (!switch_to_tab()) return; /* In a case of a multi-material printing, for editing another Filament Preset * it's needed to select this preset for the "Filament settings" Tab */ if (m_type == Preset::TYPE_FILAMENT && wxGetApp().extruders_edited_cnt() > 1) { const std::string& selected_preset = GetString(GetSelection()).ToUTF8().data(); // Call select_preset() only if there is new preset and not just modified if ( !boost::algorithm::ends_with(selected_preset, Preset::suffix_modified()) ) { const std::string& preset_name = wxGetApp().preset_bundle->filaments.get_preset_name_by_alias(selected_preset); wxGetApp().get_tab(m_type)->select_preset(preset_name); } } }); } PlaterPresetComboBox::~PlaterPresetComboBox() { if (edit_btn) edit_btn->Destroy(); } bool PlaterPresetComboBox::switch_to_tab() { Tab* tab = wxGetApp().get_tab(m_type); if (!tab) return false; int page_id = wxGetApp().tab_panel()->FindPage(tab); if (page_id == wxNOT_FOUND) return false; wxGetApp().tab_panel()->SetSelection(page_id); // Switch to Settings NotePad wxGetApp().mainframe->select_tab(); return true; } void PlaterPresetComboBox::show_add_menu() { wxMenu* menu = new wxMenu(); append_menu_item(menu, wxID_ANY, _L("Add/Remove presets"), "", [this](wxCommandEvent&) { wxTheApp->CallAfter([]() { wxGetApp().run_wizard(ConfigWizard::RR_USER, ConfigWizard::SP_PRINTERS); }); }, "edit_uni", menu, []() { return true; }, wxGetApp().plater()); append_menu_item(menu, wxID_ANY, _L("Add physical printer"), "", [this](wxCommandEvent&) { PhysicalPrinterDialog dlg(wxEmptyString); if (dlg.ShowModal() == wxID_OK) update(); }, "edit_uni", menu, []() { return true; }, wxGetApp().plater()); wxGetApp().plater()->PopupMenu(menu); } void PlaterPresetComboBox::show_edit_menu() { wxMenu* menu = new wxMenu(); append_menu_item(menu, wxID_ANY, _L("Edit preset"), "", [this](wxCommandEvent&) { this->switch_to_tab(); }, "cog", menu, []() { return true; }, wxGetApp().plater()); if (this->is_selected_physical_printer()) { append_menu_item(menu, wxID_ANY, _L("Edit physical printer"), "", [this](wxCommandEvent&) { PhysicalPrinterDialog dlg(this->GetString(this->GetSelection())); if (dlg.ShowModal() == wxID_OK) update(); }, "cog", menu, []() { return true; }, wxGetApp().plater()); append_menu_item(menu, wxID_ANY, _L("Delete physical printer"), "", [this](wxCommandEvent&) { const std::string& printer_name = m_preset_bundle->physical_printers.get_selected_full_printer_name(); if (printer_name.empty()) return; const wxString msg = from_u8((boost::format(_u8L("Are you sure you want to delete \"%1%\" printer?")) % printer_name).str()); if (wxMessageDialog(this, msg, _L("Delete Physical Printer"), wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION).ShowModal() != wxID_YES) return; m_preset_bundle->physical_printers.delete_selected_printer(); wxGetApp().get_tab(m_type)->update_preset_choice(); update(); }, "cross", menu, []() { return true; }, wxGetApp().plater()); } else append_menu_item(menu, wxID_ANY, _L("Add/Remove presets"), "", [this](wxCommandEvent&) { wxTheApp->CallAfter([]() { wxGetApp().run_wizard(ConfigWizard::RR_USER, ConfigWizard::SP_PRINTERS); }); }, "edit_uni", menu, []() { return true; }, wxGetApp().plater()); append_menu_item(menu, wxID_ANY, _L("Add physical printer"), "", [this](wxCommandEvent&) { PhysicalPrinterDialog dlg(wxEmptyString); if (dlg.ShowModal() == wxID_OK) update(); }, "edit_uni", menu, []() { return true; }, wxGetApp().plater()); wxGetApp().plater()->PopupMenu(menu); } // Only the compatible presets are shown. // If an incompatible preset is selected, it is shown as well. void PlaterPresetComboBox::update() { if (m_type == Preset::TYPE_FILAMENT && (m_preset_bundle->printers.get_edited_preset().printer_technology() == ptSLA || m_preset_bundle->filament_presets.size() <= (size_t)m_extruder_idx) ) return; // Otherwise fill in the list from scratch. this->Freeze(); this->Clear(); invalidate_selection(); const Preset* selected_filament_preset; std::string extruder_color; if (m_type == Preset::TYPE_FILAMENT) { unsigned char rgb[3]; extruder_color = m_preset_bundle->printers.get_edited_preset().config.opt_string("extruder_colour", (unsigned int)m_extruder_idx); if (!bitmap_cache().parse_color(extruder_color, rgb)) // Extruder color is not defined. extruder_color.clear(); selected_filament_preset = m_collection->find_preset(m_preset_bundle->filament_presets[m_extruder_idx]); assert(selected_filament_preset); } bool has_selection = m_collection->get_selected_idx() != size_t(-1); const Preset* selected_preset = m_type == Preset::TYPE_FILAMENT ? selected_filament_preset : has_selection ? &m_collection->get_selected_preset() : nullptr; // Show wide icons if the currently selected preset is not compatible with the current printer, // and draw a red flag in front of the selected preset. bool wide_icons = selected_preset && !selected_preset->is_compatible; std::map<wxString, wxBitmap*> nonsys_presets; wxString selected_user_preset = ""; wxString tooltip = ""; const std::deque<Preset>& presets = m_collection->get_presets(); if (!presets.front().is_visible) this->set_label_marker(this->Append(separator(L("System presets")), wxNullBitmap)); for (size_t i = presets.front().is_visible ? 0 : m_collection->num_default_presets(); i < presets.size(); ++i) { const Preset& preset = presets[i]; bool is_selected = m_type == Preset::TYPE_FILAMENT ? m_preset_bundle->filament_presets[m_extruder_idx] == preset.name : // The case, when some physical printer is selected m_type == Preset::TYPE_PRINTER && m_preset_bundle->physical_printers.has_selection() ? false : i == m_collection->get_selected_idx(); if (!preset.is_visible || (!preset.is_compatible && !is_selected)) continue; std::string bitmap_key, filament_rgb, extruder_rgb; std::string bitmap_type_name = bitmap_key = m_type == Preset::TYPE_PRINTER && preset.printer_technology() == ptSLA ? "sla_printer" : m_main_bitmap_name; bool single_bar = false; if (m_type == Preset::TYPE_FILAMENT) { // Assign an extruder color to the selected item if the extruder color is defined. filament_rgb = is_selected ? selected_filament_preset->config.opt_string("filament_colour", 0) : preset.config.opt_string("filament_colour", 0); extruder_rgb = (is_selected && !extruder_color.empty()) ? extruder_color : filament_rgb; single_bar = filament_rgb == extruder_rgb; bitmap_key += single_bar ? filament_rgb : filament_rgb + extruder_rgb; } wxBitmap* bmp = get_bmp(bitmap_key, wide_icons, bitmap_type_name, preset.is_compatible, preset.is_system || preset.is_default, single_bar, filament_rgb, extruder_rgb); assert(bmp); const std::string name = preset.alias.empty() ? preset.name : preset.alias; if (preset.is_default || preset.is_system) { Append(wxString::FromUTF8((name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), *bmp); validate_selection(is_selected); if (is_selected) tooltip = wxString::FromUTF8(preset.name.c_str()); } else { nonsys_presets.emplace(wxString::FromUTF8((name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), bmp); if (is_selected) { selected_user_preset = wxString::FromUTF8((name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()); tooltip = wxString::FromUTF8(preset.name.c_str()); } } if (i + 1 == m_collection->num_default_presets()) set_label_marker(Append(separator(L("System presets")), wxNullBitmap)); } if (!nonsys_presets.empty()) { set_label_marker(Append(separator(L("User presets")), wxNullBitmap)); for (std::map<wxString, wxBitmap*>::iterator it = nonsys_presets.begin(); it != nonsys_presets.end(); ++it) { Append(it->first, *it->second); validate_selection(it->first == selected_user_preset); } } if (m_type == Preset::TYPE_PRINTER) { // add Physical printers, if any exists if (!m_preset_bundle->physical_printers.empty()) { set_label_marker(Append(separator(L("Physical printers")), wxNullBitmap)); const PhysicalPrinterCollection& ph_printers = m_preset_bundle->physical_printers; for (PhysicalPrinterCollection::ConstIterator it = ph_printers.begin(); it != ph_printers.end(); ++it) { for (const std::string preset_name : it->get_preset_names()) { Preset* preset = m_collection->find_preset(preset_name); if (!preset) continue; std::string main_icon_name, bitmap_key = main_icon_name = preset->printer_technology() == ptSLA ? "sla_printer" : m_main_bitmap_name; wxBitmap* bmp = get_bmp(main_icon_name, wide_icons, main_icon_name); assert(bmp); set_label_marker(Append(wxString::FromUTF8((it->get_full_name(preset_name) + (preset->is_dirty ? Preset::suffix_modified() : "")).c_str()), *bmp), LABEL_ITEM_PHYSICAL_PRINTER); validate_selection(ph_printers.is_selected(it, preset_name)); } } } } if (m_type == Preset::TYPE_PRINTER || m_type == Preset::TYPE_FILAMENT || m_type == Preset::TYPE_SLA_MATERIAL) { wxBitmap* bmp = get_bmp("edit_preset_list", wide_icons, "edit_uni"); assert(bmp); if (m_type == Preset::TYPE_FILAMENT) set_label_marker(Append(separator(L("Add/Remove filaments")), *bmp), LABEL_ITEM_WIZARD_FILAMENTS); else if (m_type == Preset::TYPE_SLA_MATERIAL) set_label_marker(Append(separator(L("Add/Remove materials")), *bmp), LABEL_ITEM_WIZARD_MATERIALS); else set_label_marker(Append(separator(L("Add/Remove printers")), *bmp), LABEL_ITEM_WIZARD_PRINTERS); } update_selection(); Thaw(); if (!tooltip.IsEmpty()) SetToolTip(tooltip); // Update control min size after rescale (changed Display DPI under MSW) if (GetMinWidth() != 20 * m_em_unit) SetMinSize(wxSize(20 * m_em_unit, GetSize().GetHeight())); } void PlaterPresetComboBox::msw_rescale() { PresetComboBox::msw_rescale(); edit_btn->msw_rescale(); } // --------------------------------- // *** TabPresetComboBox *** // --------------------------------- TabPresetComboBox::TabPresetComboBox(wxWindow* parent, Preset::Type preset_type) : PresetComboBox(parent, preset_type, wxSize(35 * wxGetApp().em_unit(), -1)) { Bind(wxEVT_COMBOBOX, [this](wxCommandEvent& evt) { // see https://github.com/prusa3d/PrusaSlicer/issues/3889 // Under OSX: in case of use of a same names written in different case (like "ENDER" and "Ender") // m_presets_choice->GetSelection() will return first item, because search in PopupListCtrl is case-insensitive. // So, use GetSelection() from event parameter auto selected_item = evt.GetSelection(); auto marker = reinterpret_cast<Marker>(this->GetClientData(selected_item)); if (marker >= LABEL_ITEM_DISABLED && marker < LABEL_ITEM_MAX) { this->SetSelection(this->m_last_selected); if (marker == LABEL_ITEM_WIZARD_PRINTERS) wxTheApp->CallAfter([this]() { wxGetApp().run_wizard(ConfigWizard::RR_USER, ConfigWizard::SP_PRINTERS); // update combobox if its parent is a PhysicalPrinterDialog PhysicalPrinterDialog* parent = dynamic_cast<PhysicalPrinterDialog*>(this->GetParent()); if (parent != nullptr) update(); }); } else if (on_selection_changed && (m_last_selected != selected_item || m_collection->current_is_dirty()) ) { m_last_selected = selected_item; on_selection_changed(selected_item); } evt.StopPropagation(); }); } // Update the choice UI from the list of presets. // If show_incompatible, all presets are shown, otherwise only the compatible presets are shown. // If an incompatible preset is selected, it is shown as well. void TabPresetComboBox::update() { Freeze(); Clear(); invalidate_selection(); const std::deque<Preset>& presets = m_collection->get_presets(); std::map<wxString, std::pair<wxBitmap*, bool>> nonsys_presets; wxString selected = ""; if (!presets.front().is_visible) set_label_marker(Append(separator(L("System presets")), wxNullBitmap)); size_t idx_selected = m_collection->get_selected_idx(); if (m_type == Preset::TYPE_PRINTER && m_preset_bundle->physical_printers.has_selection()) { std::string sel_preset_name = m_preset_bundle->physical_printers.get_selected_printer_preset_name(); Preset* preset = m_collection->find_preset(sel_preset_name); if (!preset) m_preset_bundle->physical_printers.unselect_printer(); } for (size_t i = presets.front().is_visible ? 0 : m_collection->num_default_presets(); i < presets.size(); ++i) { const Preset& preset = presets[i]; if (!preset.is_visible || (!show_incompatible && !preset.is_compatible && i != idx_selected)) continue; // marker used for disable incompatible printer models for the selected physical printer bool is_enabled = true; std::string bitmap_key = "tab"; if (m_type == Preset::TYPE_PRINTER) { bitmap_key += "_printer"; if (preset.printer_technology() == ptSLA) bitmap_key += "_sla"; } std::string main_icon_name = m_type == Preset::TYPE_PRINTER && preset.printer_technology() == ptSLA ? "sla_printer" : m_main_bitmap_name; wxBitmap* bmp = get_bmp(bitmap_key, main_icon_name, "lock_closed", is_enabled, preset.is_compatible, preset.is_system || preset.is_default); assert(bmp); if (preset.is_default || preset.is_system) { int item_id = Append(wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), *bmp); if (!is_enabled) set_label_marker(item_id, LABEL_ITEM_DISABLED); validate_selection(i == idx_selected); } else { std::pair<wxBitmap*, bool> pair(bmp, is_enabled); nonsys_presets.emplace(wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()), std::pair<wxBitmap*, bool>(bmp, is_enabled)); if (i == idx_selected) selected = wxString::FromUTF8((preset.name + (preset.is_dirty ? Preset::suffix_modified() : "")).c_str()); } if (i + 1 == m_collection->num_default_presets()) set_label_marker(Append(separator(L("System presets")), wxNullBitmap)); } if (!nonsys_presets.empty()) { set_label_marker(Append(separator(L("User presets")), wxNullBitmap)); for (std::map<wxString, std::pair<wxBitmap*, bool>>::iterator it = nonsys_presets.begin(); it != nonsys_presets.end(); ++it) { int item_id = Append(it->first, *it->second.first); bool is_enabled = it->second.second; if (!is_enabled) set_label_marker(item_id, LABEL_ITEM_DISABLED); validate_selection(it->first == selected); } } if (m_type == Preset::TYPE_PRINTER) { // add Physical printers, if any exists if (!m_preset_bundle->physical_printers.empty()) { set_label_marker(Append(separator(L("Physical printers")), wxNullBitmap)); const PhysicalPrinterCollection& ph_printers = m_preset_bundle->physical_printers; for (PhysicalPrinterCollection::ConstIterator it = ph_printers.begin(); it != ph_printers.end(); ++it) { for (const std::string preset_name : it->get_preset_names()) { Preset* preset = m_collection->find_preset(preset_name); if (!preset) continue; std::string main_icon_name = preset->printer_technology() == ptSLA ? "sla_printer" : m_main_bitmap_name; wxBitmap* bmp = get_bmp(main_icon_name, main_icon_name, "", true, true, false); assert(bmp); set_label_marker(Append(wxString::FromUTF8((it->get_full_name(preset_name) + (preset->is_dirty ? Preset::suffix_modified() : "")).c_str()), *bmp), LABEL_ITEM_PHYSICAL_PRINTER); validate_selection(ph_printers.is_selected(it, preset_name)); } } } // add "Add/Remove printers" item std::string icon_name = "edit_uni"; wxBitmap* bmp = get_bmp("edit_preset_list, tab,", icon_name, ""); assert(bmp); set_label_marker(Append(separator(L("Add/Remove printers")), *bmp), LABEL_ITEM_WIZARD_PRINTERS); } update_selection(); Thaw(); } void TabPresetComboBox::msw_rescale() { PresetComboBox::msw_rescale(); wxSize sz = wxSize(35 * m_em_unit, -1); SetMinSize(sz); SetSize(sz); } void TabPresetComboBox::update_dirty() { // 1) Update the dirty flag of the current preset. m_collection->update_dirty(); // 2) Update the labels. wxWindowUpdateLocker noUpdates(this); for (unsigned int ui_id = 0; ui_id < GetCount(); ++ui_id) { auto marker = reinterpret_cast<Marker>(this->GetClientData(ui_id)); if (marker >= LABEL_ITEM_MARKER) continue; std::string old_label = GetString(ui_id).utf8_str().data(); std::string preset_name = Preset::remove_suffix_modified(old_label); std::string ph_printer_name; if (marker == LABEL_ITEM_PHYSICAL_PRINTER) { ph_printer_name = PhysicalPrinter::get_short_name(preset_name); preset_name = PhysicalPrinter::get_preset_name(preset_name); } const Preset* preset = m_collection->find_preset(preset_name, false); if (preset) { std::string new_label = preset->is_dirty ? preset->name + Preset::suffix_modified() : preset->name; if (marker == LABEL_ITEM_PHYSICAL_PRINTER) new_label = ph_printer_name + PhysicalPrinter::separator() + new_label; if (old_label != new_label) SetString(ui_id, wxString::FromUTF8(new_label.c_str())); } } #ifdef __APPLE__ // wxWidgets on OSX do not upload the text of the combo box line automatically. // Force it to update by re-selecting. SetSelection(GetSelection()); #endif /* __APPLE __ */ } }} // namespace Slic3r::GUI
/* Copyright (c) 2008-2019 the MRtrix3 contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Covered Software is provided under this License on an "as is" * basis, without warranty of any kind, either expressed, implied, or * statutory, including, without limitation, warranties that the * Covered Software is free of defects, merchantable, fit for a * particular purpose or non-infringing. * See the Mozilla Public License v. 2.0 for more details. * * For more details, see http://www.mrtrix.org/. */ #include "gui/color_button.h" #include "gui/lighting_dock.h" #include "file/config.h" #include "math/math.h" namespace MR { namespace GUI { LightingSettings::LightingSettings (QWidget* parent, GL::Lighting& lighting) : QFrame (parent), info (lighting) { QColor C; QVBoxLayout* main_box = new QVBoxLayout; setLayout (main_box); QGridLayout* grid_layout = new QGridLayout; main_box->addLayout (grid_layout); main_box->addStretch (); QSlider* slider; QFont f = font(); f.setPointSize (MR::File::Config::get_int ("MRViewToolFontSize", f.pointSize()-2)); setFont (f); setFrameShadow (QFrame::Sunken); setFrameShape (QFrame::Panel); slider = new QSlider (Qt::Horizontal); slider->setRange (0,1000); slider->setSliderPosition (int (info.ambient * 1000.0)); connect (slider, SIGNAL (valueChanged (int)), this, SLOT (ambient_intensity_slot (int))); grid_layout->addWidget (new QLabel ("Ambient intensity"), 0, 0); grid_layout->addWidget (slider, 0, 1); slider = new QSlider (Qt::Horizontal); slider->setRange (0,1000); slider->setSliderPosition (int (info.diffuse * 1000.0)); connect (slider, SIGNAL (valueChanged (int)), this, SLOT (diffuse_intensity_slot (int))); grid_layout->addWidget (new QLabel ("Diffuse intensity"), 1, 0); grid_layout->addWidget (slider, 1, 1); slider = new QSlider (Qt::Horizontal); slider->setRange (0,1000); slider->setSliderPosition (int (info.specular * 1000.0)); connect (slider, SIGNAL (valueChanged (int)), this, SLOT (specular_intensity_slot (int))); grid_layout->addWidget (new QLabel ("Specular intensity"), 2, 0); grid_layout->addWidget (slider, 2, 1); slider = new QSlider (Qt::Horizontal); slider->setRange (10,10000); slider->setSliderPosition (int (info.shine * 1000.0)); connect (slider, SIGNAL (valueChanged (int)), this, SLOT (shine_slot (int))); grid_layout->addWidget (new QLabel ("Specular exponent"), 3, 0); grid_layout->addWidget (slider, 3, 1); elevation_slider = new QSlider (Qt::Horizontal); elevation_slider->setRange (0,1000); elevation_slider->setSliderPosition (int ( (1000.0/Math::pi) *acos (-info.lightpos[1]/Eigen::Map<Eigen::Matrix<float, 3, 1>>(info.lightpos).norm()))); connect (elevation_slider, SIGNAL (valueChanged (int)), this, SLOT (light_position_slot())); grid_layout->addWidget (new QLabel ("Light elevation"), 4, 0); grid_layout->addWidget (elevation_slider, 4, 1); azimuth_slider = new QSlider (Qt::Horizontal); azimuth_slider->setRange (-1000,1000); azimuth_slider->setSliderPosition (int ( (1000.0/Math::pi) * atan2 (info.lightpos[0], info.lightpos[2]))); connect (azimuth_slider, SIGNAL (valueChanged (int)), this, SLOT (light_position_slot())); grid_layout->addWidget (new QLabel ("Light azimuth"), 5, 0); grid_layout->addWidget (azimuth_slider, 5, 1); grid_layout->setColumnStretch (0,0); grid_layout->setColumnStretch (1,1); grid_layout->setColumnMinimumWidth (1, 100); } void LightingSettings::ambient_intensity_slot (int value) { info.ambient = float (value) /1000.0; info.update(); } void LightingSettings::diffuse_intensity_slot (int value) { info.diffuse = float (value) /1000.0; info.update(); } void LightingSettings::specular_intensity_slot (int value) { info.specular = float (value) /1000.0; info.update(); } void LightingSettings::shine_slot (int value) { info.shine = float (value) /1000.0; info.update(); } void LightingSettings::light_position_slot () { float elevation = elevation_slider->value() * (Math::pi/1000.0); float azimuth = azimuth_slider->value() * (Math::pi/1000.0); info.lightpos[2] = sin (elevation) * cos (azimuth); info.lightpos[0] = sin (elevation) * sin (azimuth); info.lightpos[1] = -cos (elevation); info.update(); } LightingDock::LightingDock (const std::string& title, GL::Lighting& lighting) : QDockWidget (QString (title.c_str())), settings (new LightingSettings (this, lighting)) { setWidget(settings); } } } Fix unused variable compiler warning /* Copyright (c) 2008-2019 the MRtrix3 contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Covered Software is provided under this License on an "as is" * basis, without warranty of any kind, either expressed, implied, or * statutory, including, without limitation, warranties that the * Covered Software is free of defects, merchantable, fit for a * particular purpose or non-infringing. * See the Mozilla Public License v. 2.0 for more details. * * For more details, see http://www.mrtrix.org/. */ #include "gui/color_button.h" #include "gui/lighting_dock.h" #include "file/config.h" #include "math/math.h" namespace MR { namespace GUI { LightingSettings::LightingSettings (QWidget* parent, GL::Lighting& lighting) : QFrame (parent), info (lighting) { QVBoxLayout* main_box = new QVBoxLayout; setLayout (main_box); QGridLayout* grid_layout = new QGridLayout; main_box->addLayout (grid_layout); main_box->addStretch (); QSlider* slider; QFont f = font(); f.setPointSize (MR::File::Config::get_int ("MRViewToolFontSize", f.pointSize()-2)); setFont (f); setFrameShadow (QFrame::Sunken); setFrameShape (QFrame::Panel); slider = new QSlider (Qt::Horizontal); slider->setRange (0,1000); slider->setSliderPosition (int (info.ambient * 1000.0)); connect (slider, SIGNAL (valueChanged (int)), this, SLOT (ambient_intensity_slot (int))); grid_layout->addWidget (new QLabel ("Ambient intensity"), 0, 0); grid_layout->addWidget (slider, 0, 1); slider = new QSlider (Qt::Horizontal); slider->setRange (0,1000); slider->setSliderPosition (int (info.diffuse * 1000.0)); connect (slider, SIGNAL (valueChanged (int)), this, SLOT (diffuse_intensity_slot (int))); grid_layout->addWidget (new QLabel ("Diffuse intensity"), 1, 0); grid_layout->addWidget (slider, 1, 1); slider = new QSlider (Qt::Horizontal); slider->setRange (0,1000); slider->setSliderPosition (int (info.specular * 1000.0)); connect (slider, SIGNAL (valueChanged (int)), this, SLOT (specular_intensity_slot (int))); grid_layout->addWidget (new QLabel ("Specular intensity"), 2, 0); grid_layout->addWidget (slider, 2, 1); slider = new QSlider (Qt::Horizontal); slider->setRange (10,10000); slider->setSliderPosition (int (info.shine * 1000.0)); connect (slider, SIGNAL (valueChanged (int)), this, SLOT (shine_slot (int))); grid_layout->addWidget (new QLabel ("Specular exponent"), 3, 0); grid_layout->addWidget (slider, 3, 1); elevation_slider = new QSlider (Qt::Horizontal); elevation_slider->setRange (0,1000); elevation_slider->setSliderPosition (int ( (1000.0/Math::pi) *acos (-info.lightpos[1]/Eigen::Map<Eigen::Matrix<float, 3, 1>>(info.lightpos).norm()))); connect (elevation_slider, SIGNAL (valueChanged (int)), this, SLOT (light_position_slot())); grid_layout->addWidget (new QLabel ("Light elevation"), 4, 0); grid_layout->addWidget (elevation_slider, 4, 1); azimuth_slider = new QSlider (Qt::Horizontal); azimuth_slider->setRange (-1000,1000); azimuth_slider->setSliderPosition (int ( (1000.0/Math::pi) * atan2 (info.lightpos[0], info.lightpos[2]))); connect (azimuth_slider, SIGNAL (valueChanged (int)), this, SLOT (light_position_slot())); grid_layout->addWidget (new QLabel ("Light azimuth"), 5, 0); grid_layout->addWidget (azimuth_slider, 5, 1); grid_layout->setColumnStretch (0,0); grid_layout->setColumnStretch (1,1); grid_layout->setColumnMinimumWidth (1, 100); } void LightingSettings::ambient_intensity_slot (int value) { info.ambient = float (value) /1000.0; info.update(); } void LightingSettings::diffuse_intensity_slot (int value) { info.diffuse = float (value) /1000.0; info.update(); } void LightingSettings::specular_intensity_slot (int value) { info.specular = float (value) /1000.0; info.update(); } void LightingSettings::shine_slot (int value) { info.shine = float (value) /1000.0; info.update(); } void LightingSettings::light_position_slot () { float elevation = elevation_slider->value() * (Math::pi/1000.0); float azimuth = azimuth_slider->value() * (Math::pi/1000.0); info.lightpos[2] = sin (elevation) * cos (azimuth); info.lightpos[0] = sin (elevation) * sin (azimuth); info.lightpos[1] = -cos (elevation); info.update(); } LightingDock::LightingDock (const std::string& title, GL::Lighting& lighting) : QDockWidget (QString (title.c_str())), settings (new LightingSettings (this, lighting)) { setWidget(settings); } } }
#include <QDir> #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QSettings> #include "functions.h" #include "language-loader.h" #include "main-screen.h" #include "models/image.h" #include "models/profile.h" #include "settings.h" #include "share/share-utils.h" #include "syntax-highlighter-helper.h" int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); app.setApplicationName("Grabber"); app.setApplicationVersion(VERSION); app.setOrganizationName("Bionus"); app.setOrganizationDomain("bionus.fr.cr"); qmlRegisterType<ShareUtils>("Grabber", 1, 0, "ShareUtils"); qmlRegisterType<SyntaxHighlighterHelper>("Grabber", 1, 0, "SyntaxHighlighterHelper"); qRegisterMetaType<QSharedPointer<Image>>("QSharedPointer<Image>"); qRegisterMetaType<Settings*>("Settings*"); // Copy settings files to writable directory const QStringList toCopy { "sites/", "themes/", "webservices/" }; for (const QString &tgt : toCopy) { const QString from = savePath(tgt, true, false); const QString to = savePath(tgt, true, true); if (!QDir(to).exists() && QDir(from).exists()) { copyRecursively(from, to); } } const QUrl url(QStringLiteral("qrc:/main-screen.qml")); QQmlApplicationEngine engine; QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) { QCoreApplication::exit(-1); } }, Qt::QueuedConnection); // Define a few globals engine.rootContext()->setContextProperty("VERSION", QString(VERSION)); #ifdef NIGHTLY engine.rootContext()->setContextProperty("NIGHTLY", true); engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString(NIGHTLY_COMMIT)); #else engine.rootContext()->setContextProperty("NIGHTLY", false); engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString()); #endif Profile profile(savePath()); MainScreen mainScreen(&profile, &engine); engine.setObjectOwnership(&mainScreen, QQmlEngine::CppOwnership); engine.rootContext()->setContextProperty("backend", &mainScreen); Settings settings(profile.getSettings()); engine.rootContext()->setContextProperty("settings", &settings); // Load translations LanguageLoader languageLoader(savePath("languages/", true, false)); languageLoader.install(qApp); languageLoader.setLanguage(profile.getSettings()->value("language", "English").toString()); engine.rootContext()->setContextProperty("languageLoader", &languageLoader); #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) QObject::connect(&languageLoader, &LanguageLoader::languageChanged, &engine, &QQmlEngine::retranslate); #endif engine.load(url); return app.exec(); } Add Android permission check on startup #include <QDir> #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QSettings> #include "functions.h" #include "language-loader.h" #include "main-screen.h" #include "models/image.h" #include "models/profile.h" #include "settings.h" #include "share/share-utils.h" #include "syntax-highlighter-helper.h" #if defined(Q_OS_ANDROID) #include <QtAndroid> #include "logger.h" bool checkPermission(const QString &perm) { auto already = QtAndroid::checkPermission(perm); if (already == QtAndroid::PermissionResult::Denied) { auto results = QtAndroid::requestPermissionsSync(QStringList() << perm); if (results[perm] == QtAndroid::PermissionResult::Denied) { return false; } } return true; } #endif int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); app.setApplicationName("Grabber"); app.setApplicationVersion(VERSION); app.setOrganizationName("Bionus"); app.setOrganizationDomain("bionus.fr.cr"); qmlRegisterType<ShareUtils>("Grabber", 1, 0, "ShareUtils"); qmlRegisterType<SyntaxHighlighterHelper>("Grabber", 1, 0, "SyntaxHighlighterHelper"); qRegisterMetaType<QSharedPointer<Image>>("QSharedPointer<Image>"); qRegisterMetaType<Settings*>("Settings*"); // Copy settings files to writable directory const QStringList toCopy { "sites/", "themes/", "webservices/" }; for (const QString &tgt : toCopy) { const QString from = savePath(tgt, true, false); const QString to = savePath(tgt, true, true); if (!QDir(to).exists() && QDir(from).exists()) { copyRecursively(from, to); } } const QUrl url(QStringLiteral("qrc:/main-screen.qml")); QQmlApplicationEngine engine; QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) { QCoreApplication::exit(-1); } }, Qt::QueuedConnection); // Define a few globals engine.rootContext()->setContextProperty("VERSION", QString(VERSION)); #ifdef NIGHTLY engine.rootContext()->setContextProperty("NIGHTLY", true); engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString(NIGHTLY_COMMIT)); #else engine.rootContext()->setContextProperty("NIGHTLY", false); engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString()); #endif Profile profile(savePath()); MainScreen mainScreen(&profile, &engine); engine.setObjectOwnership(&mainScreen, QQmlEngine::CppOwnership); engine.rootContext()->setContextProperty("backend", &mainScreen); Settings settings(profile.getSettings()); engine.rootContext()->setContextProperty("settings", &settings); // Load translations LanguageLoader languageLoader(savePath("languages/", true, false)); languageLoader.install(qApp); languageLoader.setLanguage(profile.getSettings()->value("language", "English").toString()); engine.rootContext()->setContextProperty("languageLoader", &languageLoader); #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) QObject::connect(&languageLoader, &LanguageLoader::languageChanged, &engine, &QQmlEngine::retranslate); #endif #if defined(Q_OS_ANDROID) if (!checkPermission("android.permission.WRITE_EXTERNAL_STORAGE")) { log(QStringLiteral("Android write permission not granted"), Logger::Error); } #endif engine.load(url); return app.exec(); }
#include "app.h" #include "timer.h" #include "file/config.h" #include "header.h" #include "algo/copy.h" #include "gui/opengl/gl.h" #include "gui/opengl/lighting.h" #include "gui/dialog/file.h" #include "gui/dialog/opengl.h" #include "gui/dialog/progress.h" #include "gui/dialog/image_properties.h" #include "gui/mrview/mode/base.h" #include "gui/mrview/mode/list.h" #include "gui/mrview/tool/base.h" #include "gui/mrview/tool/list.h" namespace MR { namespace GUI { namespace MRView { using namespace App; /* #define MODE(classname, specifier, name, description) #specifier ", " #define MODE_OPTION(classname, specifier, name, description) MODE(classname, specifier, name, description) const OptionGroup Window::options = OptionGroup ("General options") + Option ("mode", "select initial display mode by its short ID. Valid mode IDs are: " #include "gui/mrview/mode/list.h" ) + Argument ("name"); #undef MODE #undef MODE_OPTION */ Window* Window::main = nullptr; namespace { Qt::KeyboardModifiers get_modifier (const char* key, Qt::KeyboardModifiers default_key) { std::string value = lowercase (MR::File::Config::get (key)); if (value.empty()) return default_key; if (value == "shift") return Qt::ShiftModifier; if (value == "alt") return Qt::AltModifier; #ifdef MRTRIX_MACOSX if (value == "ctrl") return Qt::MetaModifier; if (value == "cmd") return Qt::ControlModifier; #else if (value == "ctrl") return Qt::ControlModifier; if (value == "meta" || value == "win") return Qt::MetaModifier; #endif throw Exception ("no such modifier \"" + value + "\" (parsed from config file)"); return Qt::NoModifier; } } std::string get_modifier (Qt::KeyboardModifiers key) { switch (key) { case Qt::ShiftModifier: return "Shift"; case Qt::AltModifier: return "Alt"; #ifdef MRTRIX_MACOSX case Qt::ControlModifier: return "Cmd"; case Qt::MetaModifier: return "Ctrl"; #else case Qt::ControlModifier: return "Ctrl"; case Qt::MetaModifier: return "Win"; #endif default: assert (0); } return "Invalid"; } // GLArea definitions: Window::GLArea::GLArea (Window& parent) : GL::Area (&parent) { setCursor (Cursor::crosshair); setMouseTracking (true); setAcceptDrops (true); setMinimumSize (256, 256); setFocusPolicy (Qt::StrongFocus); grabGesture (Qt::PinchGesture); grabGesture (Qt::SwipeGesture); QFont font_ = font(); font_.setPointSize (MR::File::Config::get_int ("FontSize", 10)); setFont (font_); QSizePolicy policy (QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); policy.setHorizontalStretch (255); policy.setVerticalStretch (255); setSizePolicy (policy); } QSize Window::GLArea::sizeHint () const { std::string init_size_string = lowercase (MR::File::Config::get ("MRViewInitWindowSize")); std::vector<int> init_window_size; if (init_size_string.length()) init_window_size = parse_ints(init_size_string); if (init_window_size.size() == 2) return QSize (init_window_size[0], init_window_size[1]); else return QSize (512, 512); } void Window::GLArea::dragEnterEvent (QDragEnterEvent* event) { event->acceptProposedAction(); } void Window::GLArea::dragMoveEvent (QDragMoveEvent* event) { event->acceptProposedAction(); } void Window::GLArea::dragLeaveEvent (QDragLeaveEvent* event) { event->accept(); } void Window::GLArea::dropEvent (QDropEvent* event) { const QMimeData* mimeData = event->mimeData(); if (mimeData->hasUrls()) { std::vector<std::unique_ptr<MR::Header>> list; QList<QUrl> urlList = mimeData->urls(); for (int i = 0; i < urlList.size() && i < 32; ++i) { try { list.push_back (std::unique_ptr<MR::Header> (new MR::Header (MR::Header::open (urlList.at (i).path().toUtf8().constData())))); } catch (Exception& e) { e.display(); } } if (list.size()) main->add_images (list); } } void Window::GLArea::initializeGL () { main->initGL(); } void Window::GLArea::paintGL () { main->paintGL(); } void Window::GLArea::mousePressEvent (QMouseEvent* event) { main->mousePressEventGL (event); } void Window::GLArea::mouseMoveEvent (QMouseEvent* event) { main->mouseMoveEventGL (event); } void Window::GLArea::mouseReleaseEvent (QMouseEvent* event) { main->mouseReleaseEventGL (event); } void Window::GLArea::wheelEvent (QWheelEvent* event) { main->wheelEventGL (event); } bool Window::GLArea::event (QEvent* event) { if (event->type() == QEvent::Gesture) return main->gestureEventGL (static_cast<QGestureEvent*>(event)); return QWidget::event(event); } //CONF option: MRViewFocusModifierKey //CONF default: meta (cmd on MacOSX) //CONF modifier key to select focus mode in MRView. Valid //CONF choices include shift, alt, ctrl, meta (on MacOSX: shift, alt, //CONF ctrl, cmd). //CONF option: MRViewMoveModifierKey //CONF default: shift //CONF modifier key to select move mode in MRView. Valid //CONF choices include shift, alt, ctrl, meta (on MacOSX: shift, alt, //CONF ctrl, cmd). //CONF option: MRViewRotateModifierKey //CONF default: ctrl //CONF modifier key to select rotate mode in MRView. Valid //CONF choices include shift, alt, ctrl, meta (on MacOSX: shift, alt, //CONF ctrl, cmd). // Main Window class: Window::Window() : glarea (new GLArea (*this)), mode (nullptr), font (glarea->font()), #ifdef MRTRIX_MACOSX FocusModifier (get_modifier ("MRViewFocusModifierKey", Qt::AltModifier)), #else FocusModifier (get_modifier ("MRViewFocusModifierKey", Qt::MetaModifier)), #endif MoveModifier (get_modifier ("MRViewMoveModifierKey", Qt::ShiftModifier)), RotateModifier (get_modifier ("MRViewRotateModifierKey", Qt::ControlModifier)), mouse_action (NoAction), focal_point { NAN, NAN, NAN }, camera_target { NAN, NAN, NAN }, orient (), field_of_view (100.0), anatomical_plane (2), colourbar_position (ColourMap::Position::BottomRight), tools_colourbar_position (ColourMap::Position::TopRight), snap_to_image_axes_and_voxel (true), tool_has_focus (nullptr), best_FPS (NAN), show_FPS (false) { main = this; GUI::App::set_main_window (this); setDockOptions (AllowTabbedDocks | VerticalTabs); setDocumentMode (true); //CONF option: IconSize //CONF default: 24 //CONF The size of the icons in the main MRView toolbar. setWindowTitle (tr ("MRView")); setWindowIcon (QPixmap (":/mrtrix.png")); { int iconsize = MR::File::Config::get_int ("IconSize", 24); setIconSize (QSize (iconsize, iconsize)); } setCentralWidget (glarea); QToolBar* toolbar; QAction* action; QMenu* menu; QToolButton* button; setTabPosition (Qt::AllDockWidgetAreas, QTabWidget::East); // Main toolbar: //CONF option: InitialToolBarPosition //CONF default: top //CONF The starting position of the MRView toolbar. Valid values are: //CONF top, bottom, left, right. Qt::ToolBarArea toolbar_position = Qt::TopToolBarArea; { std::string toolbar_pos_spec = lowercase (MR::File::Config::get ("InitialToolBarPosition")); if (toolbar_pos_spec.size()) { if (toolbar_pos_spec == "bottom") toolbar_position = Qt::BottomToolBarArea; else if (toolbar_pos_spec == "left") toolbar_position = Qt::LeftToolBarArea; else if (toolbar_pos_spec == "right") toolbar_position = Qt::RightToolBarArea; else if (toolbar_pos_spec != "top") WARN ("invalid value for configuration entry \"InitialToolBarPosition\""); } } //CONF option: ToolbarStyle //CONF default: 2 //CONF The style of the main toolbar buttons in MRView. See Qt's //CONF documentation for Qt::ToolButtonStyle. Qt::ToolButtonStyle button_style = static_cast<Qt::ToolButtonStyle> (MR::File::Config::get_int ("ToolbarStyle", 2)); toolbar = new QToolBar ("Main toolbar", this); addToolBar (toolbar_position, toolbar); action = toolbar->toggleViewAction (); action->setShortcut (tr ("Ctrl+M")); addAction (action); // File menu: menu = new QMenu (tr ("File menu"), this); action = menu->addAction (tr ("Open..."), this, SLOT (image_open_slot())); action->setShortcut (tr ("Ctrl+O")); addAction (action); save_action = menu->addAction (tr ("Save..."), this, SLOT (image_save_slot())); save_action->setShortcut (tr ("Ctrl+S")); addAction (save_action); close_action = menu->addAction (tr ("Close"), this, SLOT (image_close_slot())); close_action->setShortcut (tr ("Ctrl+W")); addAction (close_action); menu->addSeparator(); action = menu->addAction (tr ("DICOM import..."), this, SLOT (image_import_DICOM_slot())); action->setShortcut (tr ("Ctrl+D")); addAction (action); menu->addSeparator(); action = menu->addAction (tr ("Quit"), this, SLOT (close())); action->setShortcut (tr ("Ctrl+Q")); addAction (action); button = new QToolButton (this); button->setText ("File"); button->setToolButtonStyle (button_style); button->setToolTip (tr ("File menu")); button->setIcon (QIcon (":/start.svg")); button->setPopupMode (QToolButton::InstantPopup); button->setMenu (menu); toolbar->addWidget (button); // Image menu: image_menu = new QMenu (tr ("Image menu"), this); image_group = new QActionGroup (this); image_group->setExclusive (true); connect (image_group, SIGNAL (triggered (QAction*)), this, SLOT (image_select_slot (QAction*))); properties_action = image_menu->addAction (tr ("Properties..."), this, SLOT (image_properties_slot())); properties_action->setToolTip (tr ("Display the properties of the current image\n\nShortcut: Ctrl+P")); addAction (properties_action); image_menu->addSeparator(); next_slice_action = image_menu->addAction (tr ("Next slice"), this, SLOT (slice_next_slot())); next_slice_action->setShortcut (tr ("Up")); addAction (next_slice_action); prev_slice_action = image_menu->addAction (tr ("Previous slice"), this, SLOT (slice_previous_slot())); prev_slice_action->setShortcut (tr ("Down")); addAction (prev_slice_action); next_image_volume_action = image_menu->addAction (tr ("Next volume"), this, SLOT (image_next_volume_slot())); next_image_volume_action->setShortcut (tr ("Right")); addAction (next_image_volume_action); prev_image_volume_action = image_menu->addAction (tr ("Previous volume"), this, SLOT (image_previous_volume_slot())); prev_image_volume_action->setShortcut (tr ("Left")); addAction (prev_image_volume_action); next_image_volume_group_action = image_menu->addAction (tr ("Next volume group"), this, SLOT (image_next_volume_group_slot())); next_image_volume_group_action->setShortcut (tr ("Shift+Right")); addAction (next_image_volume_group_action); prev_image_volume_group_action = image_menu->addAction (tr("Previous volume group"), this, SLOT (image_previous_volume_group_slot())); prev_image_volume_group_action->setShortcut (tr ("Shift+Left")); addAction (prev_image_volume_group_action); image_menu->addSeparator(); next_image_action = image_menu->addAction (tr ("Next image"), this, SLOT (image_next_slot())); next_image_action->setShortcut (tr ("PgDown")); addAction (next_image_action); prev_image_action = image_menu->addAction (tr ("Previous image"), this, SLOT (image_previous_slot())); prev_image_action->setShortcut (tr ("PgUp")); addAction (prev_image_action); image_list_area = image_menu->addSeparator(); button = new QToolButton (this); button->setText ("Image"); button->setToolButtonStyle (button_style); button->setToolTip (tr ("Image menu")); button->setIcon (QIcon (":/image.svg")); button->setPopupMode (QToolButton::InstantPopup); button->setMenu (image_menu); toolbar->addWidget (button); // Colourmap menu: colourmap_button = new ColourMapButton (this, *this, true, true, false); colourmap_button->setText ("Colourmap"); colourmap_button->setToolButtonStyle (button_style); colourmap_button->setPopupMode (QToolButton::InstantPopup); QMenu* colourmap_menu = colourmap_button->menu(); invert_scale_action = colourmap_menu->addAction (tr ("Invert"), this, SLOT (invert_scaling_slot())); invert_scale_action->setCheckable (true); invert_scale_action->setShortcut (tr("U")); addAction (invert_scale_action); colourmap_menu->addSeparator(); reset_windowing_action = colourmap_menu->addAction (tr ("Reset brightness/contrast"), this, SLOT (image_reset_slot())); reset_windowing_action->setShortcut (tr ("Esc")); addAction (reset_windowing_action); image_interpolate_action = colourmap_menu->addAction (tr ("Interpolate"), this, SLOT (image_interpolate_slot())); image_interpolate_action->setShortcut (tr ("I")); image_interpolate_action->setCheckable (true); image_interpolate_action->setChecked (File::Config::get_bool("ImageInterpolation", true)); addAction (image_interpolate_action); toolbar->addWidget (colourmap_button); // Mode menu: mode_group = new QActionGroup (this); mode_group->setExclusive (true); connect (mode_group, SIGNAL (triggered (QAction*)), this, SLOT (select_mode_slot (QAction*))); menu = new QMenu ("Display mode", this); #define MODE(classname, specifier, name, description) \ menu->addAction (new Mode::Action<Mode::classname> (mode_group, #name, #description, n++)); #define MODE_OPTION(classname, specifier, name, description) MODE(classname, specifier, name, description) { size_t n = 1; #include "gui/mrview/mode/list.h" } #undef MODE #undef MODE_OPTION mode_group->actions()[0]->setChecked (true); for (int n = 0; n < mode_group->actions().size(); ++n) addAction (mode_group->actions()[n]); menu->addSeparator(); plane_group = new QActionGroup (this); plane_group->setExclusive (true); connect (plane_group, SIGNAL (triggered (QAction*)), this, SLOT (select_plane_slot (QAction*))); axial_action = menu->addAction (tr ("Axial")); axial_action->setShortcut (tr ("A")); axial_action->setCheckable (true); plane_group->addAction (axial_action); addAction (axial_action); sagittal_action = menu->addAction (tr ("Sagittal")); sagittal_action->setShortcut (tr ("S")); sagittal_action->setCheckable (true); plane_group->addAction (sagittal_action); addAction (sagittal_action); coronal_action = menu->addAction (tr ("Coronal")); coronal_action->setShortcut (tr ("C")); coronal_action->setCheckable (true); plane_group->addAction (coronal_action); addAction (coronal_action); menu->addSeparator(); action = menu->addAction (tr ("Toggle all annotations"), this, SLOT (toggle_annotations_slot())); action->setShortcut (tr("Space")); addAction (action); show_crosshairs_action = menu->addAction (tr ("Show focus"), glarea, SLOT (update())); show_crosshairs_action->setShortcut (tr("F")); show_crosshairs_action->setCheckable (true); show_crosshairs_action->setChecked (true); addAction (show_crosshairs_action); show_comments_action = menu->addAction (tr ("Show comments"), glarea, SLOT (update())); show_comments_action->setToolTip (tr ("Show/hide image comments\n\nShortcut: H")); show_comments_action->setShortcut (tr("H")); show_comments_action->setCheckable (true); show_comments_action->setChecked (true); addAction (show_comments_action); show_voxel_info_action = menu->addAction (tr ("Show voxel information"), glarea, SLOT (update())); show_voxel_info_action->setShortcut (tr("V")); show_voxel_info_action->setCheckable (true); show_voxel_info_action->setChecked (true); addAction (show_voxel_info_action); show_orientation_labels_action = menu->addAction (tr ("Show orientation labels"), glarea, SLOT (update())); show_orientation_labels_action->setShortcut (tr("O")); show_orientation_labels_action->setCheckable (true); show_orientation_labels_action->setChecked (true); addAction (show_orientation_labels_action); show_colourbar_action = menu->addAction (tr ("Show colour bar"), glarea, SLOT (update())); show_colourbar_action->setShortcut (tr("B")); show_colourbar_action->setCheckable (true); show_colourbar_action->setChecked (true); addAction (show_colourbar_action); menu->addSeparator(); action = menu->addAction (tr ("Background colour..."), this, SLOT (background_colour_slot())); action->setShortcut (tr ("G")); action->setCheckable (false); addAction (action); image_hide_action = menu->addAction (tr ("Hide main image"), this, SLOT (hide_image_slot())); image_hide_action->setShortcut (tr ("M")); image_hide_action->setCheckable (true); image_hide_action->setChecked (false); addAction (image_hide_action); menu->addSeparator(); full_screen_action = menu->addAction (tr ("Full screen"), this, SLOT (full_screen_slot())); full_screen_action->setShortcut (tr ("F11")); full_screen_action->setCheckable (true); full_screen_action->setChecked (false); addAction (full_screen_action); action = menu->addAction (tr ("Reset view"), this, SLOT(reset_view_slot())); action->setShortcut (tr ("R")); addAction (action); button = new QToolButton (this); button->setText ("View"); button->setToolButtonStyle (button_style); button->setToolTip (tr ("Display")); button->setIcon (QIcon (":/mode.svg")); button->setMenu (menu); button->setPopupMode (QToolButton::InstantPopup); toolbar->addWidget (button); // Tool menu: tool_group = new QActionGroup (this); tool_group->setExclusive (false); connect (tool_group, SIGNAL (triggered (QAction*)), this, SLOT (select_tool_slot (QAction*))); menu = new QMenu (tr ("Tools"), this); #undef TOOL #define TOOL(classname, name, description) \ menu->addAction (new Action<Tool::classname> (tool_group, #name, #description, n++)); { using namespace Tool; size_t n = 1; #include "gui/mrview/tool/list.h" } for (int n = 0; n < tool_group->actions().size(); ++n) addAction (tool_group->actions()[n]); button = new QToolButton (this); button->setText ("Tool"); button->setToolButtonStyle (button_style); button->setToolTip (tr ("Select additional tools...")); button->setIcon (QIcon (":/tools.svg")); button->setMenu (menu); button->setPopupMode (QToolButton::InstantPopup); toolbar->addWidget (button); toolbar->addSeparator(); // Mouse mode actions: mode_action_group = new QActionGroup (this); mode_action_group->setExclusive (true); connect (mode_action_group, SIGNAL (triggered (QAction*)), this, SLOT (select_mouse_mode_slot (QAction*))); std::string modifier; action = toolbar->addAction (QIcon (":/select_contrast.svg"), tr ("Change focus / contrast")); action->setToolTip (tr (( "Left-click: set focus\n" "Right-click: change brightness/constrast\n\n" "Shortcut: 1\n\n" "Hold down " + get_modifier (FocusModifier) + " key to use this mode\n" "regardless of currently selected mode").c_str())); action->setShortcut (tr("1")); action->setCheckable (true); action->setChecked (true); mode_action_group->addAction (action); action = toolbar->addAction (QIcon (":/move.svg"), tr ("Move viewport")); action->setToolTip (tr (( "Left-click: move in-plane\n" "Right-click: move through-plane\n\n" "Shortcut: 2\n\n" "Hold down " + get_modifier (MoveModifier) + " key to use this mode\n" "regardless of currently selected mode").c_str())); action->setShortcut (tr("2")); action->setCheckable (true); mode_action_group->addAction (action); action = toolbar->addAction (QIcon (":/rotate.svg"), tr ("Move camera")); action->setToolTip (tr (( "Left-click: move camera in-plane\n" "Right-click: rotate camera about view axis\n\n" "Shortcut: 3\n\n" "Hold down " + get_modifier (RotateModifier) + " key to use this mode\n" "regardless of currently selected mode").c_str())); action->setShortcut (tr("3")); action->setCheckable (true); mode_action_group->addAction (action); for (int n = 0; n < mode_action_group->actions().size(); ++n) addAction (mode_action_group->actions()[n]); toolbar->addSeparator(); snap_to_image_action = toolbar->addAction (QIcon (":/lock.svg"), tr ("Snap to image"), this, SLOT (snap_to_image_slot())); snap_to_image_action->setToolTip (tr ( "Snap focus and view orientation to\n" "image voxel grid and axes respectively\n\n" "Shortcut: L")); snap_to_image_action->setShortcut (tr("L")); snap_to_image_action->setCheckable (true); snap_to_image_action->setChecked (snap_to_image_axes_and_voxel); addAction (snap_to_image_action); toolbar->addSeparator(); // Information menu: menu = new QMenu (tr ("Info"), this); menu->addAction (tr ("About MRView"), this, SLOT (about_slot())); menu->addAction (tr ("About Qt"), this, SLOT (aboutQt_slot())); menu->addAction (tr ("OpenGL information"), this, SLOT (OpenGL_slot())); button = new QToolButton (this); button->setText ("Info"); button->setToolButtonStyle (button_style); button->setToolTip (tr ("Information")); button->setIcon (QIcon (":/help.svg")); button->setPopupMode (QToolButton::InstantPopup); button->setMenu (menu); toolbar->addWidget (button); lighting_ = new GL::Lighting (this); connect (lighting_, SIGNAL (changed()), glarea, SLOT (update())); set_image_menu (); //CONF option: MRViewColourBarPosition //CONF default: bottomright //CONF The position of the colourbar within the main window in MRView. //CONF Valid values are: bottomleft, bottomright, topleft, topright. std::string cbar_pos = lowercase (MR::File::Config::get ("MRViewColourBarPosition", "bottomright")); colourbar_position = parse_colourmap_position_str(cbar_pos); if(!colourbar_position) WARN ("invalid specifier \"" + cbar_pos + "\" for config file entry \"MRViewColourBarPosition\""); //CONF option: MRViewToolsColourBarPosition //CONF default: topright //CONF The position of all visible tool colourbars within the main window in MRView. //CONF Valid values are: bottomleft, bottomright, topleft, topright. cbar_pos = lowercase (MR::File::Config::get ("MRViewToolsColourBarPosition", "topright")); tools_colourbar_position = parse_colourmap_position_str(cbar_pos); if(!tools_colourbar_position) WARN ("invalid specifier \"" + cbar_pos + "\" for config file entry \"MRViewToolsColourBarPosition\""); } ColourMap::Position Window::parse_colourmap_position_str (const std::string& position_str) { ColourMap::Position pos(ColourMap::Position::None); if(position_str == "bottomleft") pos = ColourMap::Position::BottomLeft; else if(position_str == "bottomright") pos = ColourMap::Position::BottomRight; else if(position_str == "topleft") pos = ColourMap::Position::TopLeft; else if(position_str == "topright") pos = ColourMap::Position::TopRight; return pos; } Window::~Window () { glarea->makeCurrent(); QList<QAction*> tools = tool_group->actions(); for (QAction* action : tools) delete action; mode.reset(); QList<QAction*> images = image_group->actions(); for (QAction* action : images) delete action; } void Window::image_open_slot () { std::vector<std::string> image_list = Dialog::File::get_images (this, "Select images to open"); if (image_list.empty()) return; std::vector<std::unique_ptr<MR::Header>> list; for (size_t n = 0; n < image_list.size(); ++n) { try { list.push_back (std::unique_ptr<MR::Header> (new MR::Header (MR::Header::open (image_list[n])))); } catch (Exception& E) { E.display(); } } add_images (list); } void Window::image_import_DICOM_slot () { std::string folder = Dialog::File::get_folder (this, "Select DICOM folder to import"); if (folder.empty()) return; try { std::vector<std::unique_ptr<MR::Header>> list; list.push_back (std::unique_ptr<MR::Header> (new MR::Header (MR::Header::open (folder)))); add_images (list); } catch (Exception& E) { E.display(); } } void Window::add_images (std::vector<std::unique_ptr<MR::Header>>& list) { for (size_t i = 0; i < list.size(); ++i) { const std::string name = list[i]->name(); // Gets move-constructed out QAction* action = new Image (std::move (*list[i])); action->setText (shorten (name, 20, 0).c_str()); action->setParent (Window::main); action->setCheckable (true); action->setToolTip (name.c_str()); action->setStatusTip (name.c_str()); image_group->addAction (action); image_menu->addAction (action); connect (action, SIGNAL(scalingChanged()), this, SLOT(on_scaling_changed())); if (!i) image_select_slot (action); } set_image_menu(); } void Window::image_save_slot () { std::string image_name = Dialog::File::get_save_image_name (this, "Select image destination"); if (image_name.empty()) return; try { auto dest = MR::Image<cfloat>::create (image_name, image()->header()); MR::copy_with_progress (image()->image, dest); } catch (Exception& E) { E.display(); } } void Window::image_close_slot () { Image* imagep = image(); assert (imagep); QList<QAction*> list = image_group->actions(); if (list.size() > 1) { for (int n = 0; n < list.size(); ++n) { if (imagep == list[n]) { image_select_slot (list[ (n+1) %list.size()]); break; } } } image_group->removeAction (imagep); delete imagep; set_image_menu(); } void Window::image_properties_slot () { assert (image()); Dialog::ImageProperties props (this, image()->header()); props.exec(); } void Window::select_mode_slot (QAction* action) { glarea->makeCurrent(); mode.reset (dynamic_cast<GUI::MRView::Mode::__Action__*> (action)->create()); mode->set_visible(! image_hide_action->isChecked()); set_mode_features(); emit modeChanged(); glarea->update(); } void Window::select_mouse_mode_slot (QAction* action) { bool rotate_button_checked = mode_action_group->actions().indexOf (action) == 2; if (rotate_button_checked) set_snap_to_image (false); snap_to_image_action->setEnabled (!rotate_button_checked); set_cursor(); } void Window::select_tool_slot (QAction* action) { Tool::Dock* tool = dynamic_cast<Tool::__Action__*>(action)->dock; if (!tool) { tool = dynamic_cast<Tool::__Action__*>(action)->create(); connect (tool, SIGNAL (visibilityChanged (bool)), action, SLOT (setChecked (bool))); if (MR::File::Config::get_int ("MRViewDockFloating", 0)) return; for (int i = 0; i < tool_group->actions().size(); ++i) { Tool::Dock* other_tool = dynamic_cast<Tool::__Action__*>(tool_group->actions()[i])->dock; if (other_tool && other_tool != tool) { QList<QDockWidget* > list = QMainWindow::tabifiedDockWidgets (other_tool); if (list.size()) QMainWindow::tabifyDockWidget (list.last(), tool); else QMainWindow::tabifyDockWidget (other_tool, tool); tool->setFloating (false); tool->raise(); return; } } //CONF option: MRViewDockFloating //CONF default: 0 (false) //CONF Whether Tools should start docked in the main window, or //CONF floating (detached from the main window). tool->setFloating (MR::File::Config::get_int ("MRViewDockFloating", 0)); tool->show(); } if (action->isChecked()) { if (!tool->isVisible()) tool->show(); tool->raise(); } else { tool->close(); } glarea->update(); } void Window::selected_colourmap (size_t colourmap, const ColourMapButton&) { Image* imagep = image(); if (imagep) { imagep->set_colourmap (colourmap); glarea->update(); } } void Window::selected_custom_colour (const QColor& colour, const ColourMapButton&) { Image* imagep = image(); if (imagep) { std::array<GLubyte, 3> c_colour{{GLubyte(colour.red()), GLubyte(colour.green()), GLubyte(colour.blue())}}; imagep->set_colour(c_colour); glarea->update(); } } void Window::invert_scaling_slot () { if (image()) { image()->set_invert_scale (invert_scale_action->isChecked()); glarea->update(); } } void Window::snap_to_image_slot () { if (image()) { snap_to_image_axes_and_voxel = snap_to_image_action->isChecked(); if (snap_to_image_axes_and_voxel) mode->reset_orientation(); glarea->update(); } } void Window::on_scaling_changed () { emit scalingChanged(); } void Window::updateGL () { glarea->update(); } void Window::image_reset_slot () { Image* imagep = image(); if (imagep) { imagep->reset_windowing(); on_scaling_changed(); glarea->update(); } } void Window::image_interpolate_slot () { Image* imagep = image(); if (imagep) { imagep->set_interpolate (image_interpolate_action->isChecked()); glarea->update(); } } void Window::full_screen_slot () { if (full_screen_action->isChecked()) showFullScreen(); else showNormal(); } void Window::select_plane_slot (QAction* action) { if (action == axial_action) set_plane (2); else if (action == sagittal_action) set_plane (0); else if (action == coronal_action) set_plane (1); else assert (0); glarea->update(); } void Window::reset_view_slot () { if (image()) { mode->reset_event(); QList<QAction*> tools = tool_group->actions(); for (QAction* action : tools) { Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(action)->dock; if (dock) dock->tool->reset_event(); } } } void Window::background_colour_slot () { QColor colour = QColorDialog::getColor(Qt::black, this, "Select background colour", QColorDialog::DontUseNativeDialog); if (colour.isValid()) { background_colour[0] = GLubyte(colour.red()) / 255.0f; background_colour[1] = GLubyte(colour.green()) / 255.0f; background_colour[2] = GLubyte(colour.blue()) / 255.0f; glarea->update(); } } void Window::set_image_visibility (bool flag) { image_hide_action->setChecked(! flag); mode->set_visible(flag); } void Window::hide_image_slot () { bool visible = ! image_hide_action->isChecked(); mode->set_visible(visible); emit imageVisibilityChanged(visible); } void Window::slice_next_slot () { mode->slice_move_event (1); } void Window::slice_previous_slot () { mode->slice_move_event (-1); } void Window::image_next_slot () { QAction* action = image_group->checkedAction(); int N = image_group->actions().size(); int n = image_group->actions().indexOf (action); image_select_slot (image_group->actions()[(n+1)%N]); } void Window::image_previous_slot () { QAction* action = image_group->checkedAction(); int N = image_group->actions().size(); int n = image_group->actions().indexOf (action); image_select_slot (image_group->actions()[(n+N-1)%N]); } void Window::image_next_volume_slot () { size_t vol = image()->image.index(3)+1; set_image_volume (3, vol); emit volumeChanged(vol); } void Window::image_previous_volume_slot () { size_t vol = image()->image.index(3)-1; set_image_volume (3, vol); emit volumeChanged(vol); } void Window::image_next_volume_group_slot () { size_t vol = image()->image.index(4)+1; set_image_volume (4, vol); emit volumeGroupChanged(vol); } void Window::image_previous_volume_group_slot () { size_t vol = image()->image.index(4)-1; set_image_volume (4, vol); emit volumeGroupChanged(vol); } void Window::image_select_slot (QAction* action) { action->setChecked (true); image_interpolate_action->setChecked (image()->interpolate()); size_t cmap_index = image()->colourmap; colourmap_button->colourmap_actions[cmap_index]->setChecked (true); invert_scale_action->setChecked (image()->scale_inverted()); mode->image_changed_event(); setWindowTitle (image()->image.name().c_str()); set_image_navigation_menu(); image()->set_allowed_features ( mode->features & Mode::ShaderThreshold, mode->features & Mode::ShaderTransparency, mode->features & Mode::ShaderLighting); emit imageChanged(); glarea->update(); } void Window::toggle_annotations_slot () { int current_annotations = 0x00000000; if (show_crosshairs()) current_annotations |= 0x00000001; if (show_comments()) current_annotations |= 0x00000002; if (show_voxel_info()) current_annotations |= 0x00000004; if (show_orientation_labels()) current_annotations |= 0x00000008; if (show_colourbar()) current_annotations |= 0x00000010; if (current_annotations) { annotations = current_annotations; show_crosshairs_action->setChecked (false); show_comments_action->setChecked (false); show_voxel_info_action->setChecked (false); show_orientation_labels_action->setChecked (false); show_colourbar_action->setChecked (false); } else { if (!annotations) annotations = 0xFFFFFFFF; show_crosshairs_action->setChecked (annotations & 0x00000001); show_comments_action->setChecked (annotations & 0x00000002); show_voxel_info_action->setChecked (annotations & 0x00000004); show_orientation_labels_action->setChecked (annotations & 0x00000008); show_colourbar_action->setChecked (annotations & 0x00000010); } glarea->update(); } void Window::set_image_menu () { int N = image_group->actions().size(); next_image_action->setEnabled (N>1); prev_image_action->setEnabled (N>1); reset_windowing_action->setEnabled (N>0); colourmap_button->setEnabled (N>0); save_action->setEnabled (N>0); close_action->setEnabled (N>0); properties_action->setEnabled (N>0); set_image_navigation_menu(); glarea->update(); } int Window::get_mouse_mode () { if (mouse_action == NoAction && modifiers_ != Qt::NoModifier) { if (modifiers_ == FocusModifier && ( mode->features & Mode::FocusContrast )) return 1; else if (modifiers_ == MoveModifier && ( mode->features & Mode::MoveTarget )) return 2; else if (modifiers_ == RotateModifier && ( mode->features & Mode::TiltRotate )) return 3; } if (mouse_action == NoAction) return mode_action_group->actions().indexOf (mode_action_group->checkedAction()) + 1; return 0; } void Window::set_cursor () { MouseAction cursor = mouse_action; if (cursor == NoAction) { switch (get_mouse_mode()) { case 1: cursor = SetFocus; break; case 2: cursor = Pan; break; case 3: cursor = Tilt; break; default: assert (0); } } if (tool_has_focus && modifiers_ == Qt::NoModifier) { QCursor* ptr = tool_has_focus->get_cursor(); if (ptr) { glarea->setCursor (*ptr); return; } } switch (cursor) { case SetFocus: glarea->setCursor (Cursor::crosshair); break; case Contrast: glarea->setCursor (Cursor::window); break; case Pan: glarea->setCursor (Cursor::pan_crosshair); break; case PanThrough: glarea->setCursor (Cursor::forward_backward); break; case Tilt: glarea->setCursor (Cursor::throughplane_rotate); break; case Rotate: glarea->setCursor (Cursor::inplane_rotate); break; default: assert (0); } } void Window::set_mode_features () { mode_action_group->actions()[0]->setEnabled (mode->features & Mode::FocusContrast); mode_action_group->actions()[1]->setEnabled (mode->features & Mode::MoveTarget); mode_action_group->actions()[2]->setEnabled (mode->features & Mode::TiltRotate); if (!mode_action_group->checkedAction()->isEnabled()) mode_action_group->actions()[0]->setChecked (true); if (image()) image()->set_allowed_features ( mode->features & Mode::ShaderThreshold, mode->features & Mode::ShaderTransparency, mode->features & Mode::ShaderLighting); } void Window::set_image_navigation_menu () { bool show_next_volume (false), show_prev_volume (false); bool show_next_volume_group (false), show_prev_volume_group (false); Image* imagep = image(); if (imagep) { if (imagep->image.ndim() > 3) { if (imagep->image.index(3) > 0) show_prev_volume = true; if (imagep->image.index(3) < imagep->image.size(3)-1) show_next_volume = true; if (imagep->image.ndim() > 4) { if (imagep->image.index(4) > 0) show_prev_volume_group = true; if (imagep->image.index(4) < imagep->image.size(4)-1) show_next_volume_group = true; } } } prev_image_volume_action->setEnabled (show_prev_volume); next_image_volume_action->setEnabled (show_next_volume); prev_image_volume_group_action->setEnabled (show_prev_volume_group); next_image_volume_group_action->setEnabled (show_next_volume_group); } void Window::OpenGL_slot () { Dialog::OpenGL glinfo (this, glarea->format()); glinfo.exec(); } void Window::about_slot () { std::string message = std::string ("<h1>MRView</h1>The MRtrix viewer, version ") + MR::App::mrtrix_version + "<br>" "<em>" + str (8*sizeof (size_t)) + " bit " #ifdef NDEBUG "release" #else "debug" #endif " version, built " + MR::App::build_date + "</em><p>" "<h4>Authors:</h4>" + MR::join (MR::split (MR::App::AUTHOR, ",;&\n", true), "<br>") + "<p><em>" + MR::App::COPYRIGHT + "</em>"; QMessageBox::about (this, tr ("About MRView"), message.c_str()); } void Window::aboutQt_slot () { QMessageBox::aboutQt (this); } void Window::paintGL () { ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; GL_CHECK_ERROR; gl::ClearColor (background_colour[0], background_colour[1], background_colour[2], 1.0); if (glarea->format().samples() > 1) gl::Enable (gl::MULTISAMPLE); GL_CHECK_ERROR; ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; mode->paintGL(); ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; GL_CHECK_ERROR; if (show_FPS) { render_times.push_back (Timer::current_time()); while (render_times.size() > 10) render_times.erase (render_times.begin()); double FPS = NAN; std::string FPS_string = "-"; std::string FPS_best_string = "-"; if (render_times.back() - best_FPS_time > 3.0) best_FPS = NAN; if (render_times.size() == 10) { FPS = (render_times.size()-1.0) / (render_times.back()-render_times.front()); FPS_string = str (FPS, 4); if (!std::isfinite (best_FPS) || FPS > best_FPS) { best_FPS = FPS; best_FPS_time = render_times.back(); } } else best_FPS = NAN; if (std::isfinite (best_FPS)) FPS_best_string = str (best_FPS, 4); mode->projection.setup_render_text (0.0, 1.0, 0.0); mode->projection.render_text ("max FPS: " + FPS_best_string, RightEdge | TopEdge); mode->projection.render_text ("FPS: " + FPS_string, RightEdge | TopEdge, 1); mode->projection.done_render_text(); } // need to clear alpha channel when using QOpenGLWidget (Qt >= 5.4) // otherwise we get transparent windows... #if QT_VERSION >= 0x050400 gl::ColorMask (false, false, false, true); gl::Clear (gl::COLOR_BUFFER_BIT); glColorMask (true, true, true, true); #endif GL_CHECK_ERROR; ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; } void Window::initGL () { ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; GL::init (); font.initGL(); gl::Enable (gl::DEPTH_TEST); //CONF option: ImageBackgroundColour //CONF default: 0,0,0 (black) // CONF The default image background colour File::Config::get_RGB ("ImageBackgroundColour", background_colour, 0.0f, 0.0f, 0.0f); gl::ClearColor (background_colour[0], background_colour[1], background_colour[2], 1.0); mode.reset (dynamic_cast<Mode::__Action__*> (mode_group->actions()[0])->create()); set_mode_features(); if (MR::App::option.size()) QTimer::singleShot (0, this, SLOT (process_commandline_options())); ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; } template <class Event> void Window::grab_mouse_state (Event* event) { buttons_ = event->buttons(); modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier ); mouse_displacement_ = QPoint (0,0); mouse_position_ = event->pos(); mouse_position_.setY (glarea->height() - mouse_position_.y()); } template <class Event> void Window::update_mouse_state (Event* event) { mouse_displacement_ = mouse_position_; mouse_position_ = event->pos(); mouse_position_.setY (glarea->height() - mouse_position_.y()); mouse_displacement_ = mouse_position_ - mouse_displacement_; } void Window::keyPressEvent (QKeyEvent* event) { modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier ); set_cursor(); } void Window::keyReleaseEvent (QKeyEvent* event) { modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier ); set_cursor(); } void Window::mousePressEventGL (QMouseEvent* event) { assert (mode); grab_mouse_state (event); if (image()) mode->mouse_press_event(); if (tool_has_focus && modifiers_ == Qt::NoModifier) { if (tool_has_focus->mouse_press_event()) { mouse_action = NoAction; event->accept(); return; } } int group = get_mouse_mode(); if (buttons_ == Qt::MidButton) mouse_action = Pan; else if (group == 1) { if (buttons_ == Qt::LeftButton) { mouse_action = SetFocus; if (image()) mode->set_focus_event(); } else if (buttons_ == Qt::RightButton) mouse_action = Contrast; } else if (group == 2) { if (buttons_ == Qt::LeftButton) mouse_action = Pan; else if (buttons_ == Qt::RightButton) mouse_action = PanThrough; } else if (group == 3) { if (buttons_ == Qt::LeftButton) mouse_action = Tilt; else if (buttons_ == Qt::RightButton) mouse_action = Rotate; } set_cursor(); event->accept(); } void Window::mouseMoveEventGL (QMouseEvent* event) { assert (mode); if (!image()) return; update_mouse_state (event); if (mouse_action == NoAction) { if (tool_has_focus) if (tool_has_focus->mouse_move_event()) event->accept(); return; } switch (mouse_action) { case SetFocus: mode->set_focus_event(); break; case Contrast: mode->contrast_event(); break; case Pan: mode->pan_event(); break; case PanThrough: mode->panthrough_event(); break; case Tilt: mode->tilt_event(); break; case Rotate: mode->rotate_event(); break; default: return; } event->accept(); } void Window::mouseReleaseEventGL (QMouseEvent*) { assert (mode); mode->mouse_release_event(); if (tool_has_focus && mouse_action == NoAction) if (tool_has_focus->mouse_release_event()) return; mouse_action = NoAction; set_cursor(); } void Window::wheelEventGL (QWheelEvent* event) { assert (mode); #if QT_VERSION >= 0x050400 QPoint delta = event->pixelDelta(); if (delta.isNull()) delta = event->angleDelta() / 120.0; #else QPoint delta = event->orientation() == Qt::Vertical ? QPoint (0, event->delta() / 120.0) : QPoint (event->delta() / 120.0, 0); #endif if (delta.isNull()) return; if (delta.y()) { if (image()) { grab_mouse_state (event); mode->mouse_press_event(); if (buttons_ == Qt::NoButton) { if (modifiers_ == Qt::ControlModifier) { set_FOV (FOV() * std::exp (-0.1*delta.y())); glarea->update(); event->accept(); return; } float dx = delta.y(); if (modifiers_ == Qt::ShiftModifier) dx *= 10.0; else if (modifiers_ != Qt::NoModifier) return; mode->slice_move_event (dx); event->accept(); return; } } if (buttons_ == Qt::RightButton && modifiers_ == Qt::NoModifier) { if (image_group->actions().size() > 1) { QAction* action = image_group->checkedAction(); int N = image_group->actions().size(); int n = image_group->actions().indexOf (action); image_select_slot (image_group->actions()[(n+N+delta.y())%N]); } } } } bool Window::gestureEventGL (QGestureEvent* event) { assert (mode); if (QGesture *swipe = event->gesture (Qt::SwipeGesture)) { QSwipeGesture* e = static_cast<QSwipeGesture*> (swipe); int dx = e->horizontalDirection() == QSwipeGesture::Left ? -1 : ( e->horizontalDirection() == QSwipeGesture::Right ? 1 : 0); if (dx != 0 && image_group->actions().size() > 1) { QAction* action = image_group->checkedAction(); int N = image_group->actions().size(); int n = image_group->actions().indexOf (action); image_select_slot (image_group->actions()[(n+N+dx)%N]); } } else if (QGesture* pinch = event->gesture(Qt::PinchGesture)) { QPinchGesture* e = static_cast<QPinchGesture*> (pinch); QPinchGesture::ChangeFlags changeFlags = e->changeFlags(); if (changeFlags & QPinchGesture::RotationAngleChanged) { // TODO } if (changeFlags & QPinchGesture::ScaleFactorChanged) { set_FOV (FOV() * e->lastScaleFactor() / e->scaleFactor()); glarea->update(); } } return true; } void Window::closeEvent (QCloseEvent* event) { qApp->quit(); event->accept(); } void Window::process_commandline_options () { #undef TOOL #define TOOL(classname, name, description) \ stub = lowercase (#classname "."); \ if (stub.compare (0, stub.size(), std::string (opt.opt->id), 0, stub.size()) == 0) { \ tool_group->actions()[tool_id]->setChecked (true); \ select_tool_slot (tool_group->actions()[tool_id]); \ if (dynamic_cast<Tool::__Action__*>(tool_group->actions()[tool_id])->dock->tool->process_commandline_option (opt)) \ continue; \ } \ ++tool_id; glarea->update(); qApp->processEvents(); try { for (size_t copt = 0; copt < MR::App::option.size(); ++copt) { if (copt) qApp->processEvents(); const MR::App::ParsedOption& opt (MR::App::option[copt]); // see whether option is claimed by any tools: size_t tool_id = 0; std::string stub; #include "gui/mrview/tool/list.h" // process general options: if (opt.opt->is ("mode")) { int n = int(opt[0]) - 1; if (n < 0 || n >= mode_group->actions().size()) throw Exception ("invalid mode index \"" + str(n) + "\" in batch command"); select_mode_slot (mode_group->actions()[n]); continue; } if (opt.opt->is ("size")) { std::vector<int> glsize = opt[0]; if (glsize.size() != 2) throw Exception ("invalid argument \"" + std::string(opt.args[0]) + "\" to view.size batch command"); QSize oldsize = glarea->size(); QSize winsize = size(); resize (winsize.width() - oldsize.width() + glsize[0], winsize.height() - oldsize.height() + glsize[1]); continue; } if (opt.opt->is ("reset")) { reset_view_slot(); continue; } else if (opt.opt->is ("fov")) { float fov = opt[0]; set_FOV (fov); glarea->update(); continue; } if (opt.opt->is ("focus")) { std::vector<default_type> pos = parse_floats (opt[0]); if (pos.size() != 3) throw Exception ("-focus option expects a comma-separated list of 3 floating-point values"); set_focus (Eigen::Vector3f { float(pos[0]), float(pos[1]), float(pos[2]) }); glarea->update(); continue; } if (opt.opt->is ("voxel")) { if (image()) { std::vector<default_type> pos = parse_floats (opt[0]); if (pos.size() != 3) throw Exception ("-voxel option expects a comma-separated list of 3 floating-point values"); set_focus (image()->transform().voxel2scanner.cast<float>() * Eigen::Vector3f { float(pos[0]), float(pos[1]), float(pos[2]) }); glarea->update(); } continue; } if (opt.opt->is ("fov")) { float fov = opt[0]; set_FOV (fov); glarea->update(); continue; } if (opt.opt->is ("plane")) { int n = opt[0]; set_plane (n); glarea->update(); continue; } if (opt.opt->is ("lock")) { bool n = opt[0]; snap_to_image_action->setChecked (n); snap_to_image_slot(); continue; } if (opt.opt->is ("select_image")) { int n = int(opt[0]) - 1; if (n < 0 || n >= image_group->actions().size()) throw Exception ("invalid image index requested for option -select_image"); image_select_slot (image_group->actions()[n]); continue; } if (opt.opt->is ("load")) { std::vector<std::unique_ptr<MR::Header>> list; try { list.push_back (std::unique_ptr<MR::Header> (new MR::Header (MR::Header::open (opt[0])))); } catch (Exception& e) { e.display(); } add_images (list); continue; } if (opt.opt->is ("autoscale")) { image_reset_slot(); continue; } if (opt.opt->is ("colourmap")) { int n = int(opt[0]) - 1; if (n < 0 || n >= static_cast<int>(colourmap_button->colourmap_actions.size())) throw Exception ("invalid image colourmap index \"" + str(n+1) + "\" requested in batch command"); colourmap_button->set_colourmap_index(n); continue; } if (opt.opt->is ("interpolation_on")) { image_interpolate_action->setChecked(true); image_interpolate_slot(); } if (opt.opt->is ("interpolation_off")) { image_interpolate_action->setChecked(false); image_interpolate_slot(); } if (opt.opt->is ("intensity_range")) { if (image()) { std::vector<default_type> param = parse_floats (opt[0]); if (param.size() != 2) throw Exception ("-intensity_range options expects comma-separated list of two floating-point values"); image()->set_windowing (param[0], param[1]); glarea->update(); } continue; } if (opt.opt->is ("position")) { std::vector<int> pos = opt[0]; if (pos.size() != 2) throw Exception ("invalid argument \"" + std::string(opt[0]) + "\" to -position option"); move (pos[0], pos[1]); continue; } if (opt.opt->is ("fullscreen")) { full_screen_action->setChecked (true); full_screen_slot(); continue; } if (opt.opt->is ("fps")) { show_FPS = true; continue; } if (opt.opt->is ("exit")) { qApp->processEvents(); qApp->quit(); } } } catch (Exception& E) { E.display(); qApp->quit(); } } void Window::add_commandline_options (MR::App::OptionList& options) { options + OptionGroup ("View options") + Option ("mode", "Switch to view mode specified by the integer index. as per the view menu.") + Argument ("index").type_integer() + Option ("load", "Load image specified and make it current.") + Argument ("image").type_image_in() + Option ("reset", "Reset the view according to current image. This resets the FOV, projection, and focus.") + Option ("fov", "Set the field of view, in mm.") + Argument ("value").type_float() + Option ("focus", "Set the position of the crosshairs in scanner coordinates, " "with the new position supplied as a comma-separated list of floating-point values.") + Argument ("x,y,z").type_sequence_float() + Option ("voxel", "Set the position of the crosshairs in voxel coordinates, " "relative the image currently displayed. The new position should be supplied " "as a comma-separated list of floating-point values.") + Argument ("x,y,z").type_sequence_float() + Option ("plane", "Set the viewing plane, according to the mappping 0: sagittal; 1: coronal; 2: axial.") + Argument ("index").type_integer (0,0,3) + Option ("lock", "Set whether view is locked to image axes (0: no, 1: yes).") + Argument ("yesno").type_bool() + Option ("select_image", "Switch to image number specified, with reference to the list of currently loaded images.") + Argument ("index").type_integer (0) + Option ("autoscale", "Reset the image scaling to automatically determined range.") + Option ("interpolation_on", "Enable the image interpolation.") + Option ("interpolation_off", "Disable the image interpolation.") + Option ("colourmap", "Switch the image colourmap to that specified, as per the colourmap menu.") + Argument ("index").type_integer (0) + Option ("intensity_range", "Set the image intensity range to that specified") + Argument ("min,max").type_sequence_int() + OptionGroup ("Window management options") + Option ("size", "Set the size of the view area, in pixel units.") + Argument ("width,height").type_sequence_int() + Option ("position", "Set the position of the main window, in pixel units.") + Argument ("x,y").type_sequence_int() + Option ("fullscreen", "Start fullscreen.") + Option ("exit", "quit MRView") + OptionGroup ("Debugging options") + Option ("fps", "Display frames per second, averaged over the last 10 frames. " "The maximum over the last 3 seconds is also displayed."); } } } } MRView: avoid discretisation of scroll values as discussed in #397 #include "app.h" #include "timer.h" #include "file/config.h" #include "header.h" #include "algo/copy.h" #include "gui/opengl/gl.h" #include "gui/opengl/lighting.h" #include "gui/dialog/file.h" #include "gui/dialog/opengl.h" #include "gui/dialog/progress.h" #include "gui/dialog/image_properties.h" #include "gui/mrview/mode/base.h" #include "gui/mrview/mode/list.h" #include "gui/mrview/tool/base.h" #include "gui/mrview/tool/list.h" namespace MR { namespace GUI { namespace MRView { using namespace App; /* #define MODE(classname, specifier, name, description) #specifier ", " #define MODE_OPTION(classname, specifier, name, description) MODE(classname, specifier, name, description) const OptionGroup Window::options = OptionGroup ("General options") + Option ("mode", "select initial display mode by its short ID. Valid mode IDs are: " #include "gui/mrview/mode/list.h" ) + Argument ("name"); #undef MODE #undef MODE_OPTION */ Window* Window::main = nullptr; namespace { Qt::KeyboardModifiers get_modifier (const char* key, Qt::KeyboardModifiers default_key) { std::string value = lowercase (MR::File::Config::get (key)); if (value.empty()) return default_key; if (value == "shift") return Qt::ShiftModifier; if (value == "alt") return Qt::AltModifier; #ifdef MRTRIX_MACOSX if (value == "ctrl") return Qt::MetaModifier; if (value == "cmd") return Qt::ControlModifier; #else if (value == "ctrl") return Qt::ControlModifier; if (value == "meta" || value == "win") return Qt::MetaModifier; #endif throw Exception ("no such modifier \"" + value + "\" (parsed from config file)"); return Qt::NoModifier; } } std::string get_modifier (Qt::KeyboardModifiers key) { switch (key) { case Qt::ShiftModifier: return "Shift"; case Qt::AltModifier: return "Alt"; #ifdef MRTRIX_MACOSX case Qt::ControlModifier: return "Cmd"; case Qt::MetaModifier: return "Ctrl"; #else case Qt::ControlModifier: return "Ctrl"; case Qt::MetaModifier: return "Win"; #endif default: assert (0); } return "Invalid"; } // GLArea definitions: Window::GLArea::GLArea (Window& parent) : GL::Area (&parent) { setCursor (Cursor::crosshair); setMouseTracking (true); setAcceptDrops (true); setMinimumSize (256, 256); setFocusPolicy (Qt::StrongFocus); grabGesture (Qt::PinchGesture); grabGesture (Qt::SwipeGesture); QFont font_ = font(); font_.setPointSize (MR::File::Config::get_int ("FontSize", 10)); setFont (font_); QSizePolicy policy (QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); policy.setHorizontalStretch (255); policy.setVerticalStretch (255); setSizePolicy (policy); } QSize Window::GLArea::sizeHint () const { std::string init_size_string = lowercase (MR::File::Config::get ("MRViewInitWindowSize")); std::vector<int> init_window_size; if (init_size_string.length()) init_window_size = parse_ints(init_size_string); if (init_window_size.size() == 2) return QSize (init_window_size[0], init_window_size[1]); else return QSize (512, 512); } void Window::GLArea::dragEnterEvent (QDragEnterEvent* event) { event->acceptProposedAction(); } void Window::GLArea::dragMoveEvent (QDragMoveEvent* event) { event->acceptProposedAction(); } void Window::GLArea::dragLeaveEvent (QDragLeaveEvent* event) { event->accept(); } void Window::GLArea::dropEvent (QDropEvent* event) { const QMimeData* mimeData = event->mimeData(); if (mimeData->hasUrls()) { std::vector<std::unique_ptr<MR::Header>> list; QList<QUrl> urlList = mimeData->urls(); for (int i = 0; i < urlList.size() && i < 32; ++i) { try { list.push_back (std::unique_ptr<MR::Header> (new MR::Header (MR::Header::open (urlList.at (i).path().toUtf8().constData())))); } catch (Exception& e) { e.display(); } } if (list.size()) main->add_images (list); } } void Window::GLArea::initializeGL () { main->initGL(); } void Window::GLArea::paintGL () { main->paintGL(); } void Window::GLArea::mousePressEvent (QMouseEvent* event) { main->mousePressEventGL (event); } void Window::GLArea::mouseMoveEvent (QMouseEvent* event) { main->mouseMoveEventGL (event); } void Window::GLArea::mouseReleaseEvent (QMouseEvent* event) { main->mouseReleaseEventGL (event); } void Window::GLArea::wheelEvent (QWheelEvent* event) { main->wheelEventGL (event); } bool Window::GLArea::event (QEvent* event) { if (event->type() == QEvent::Gesture) return main->gestureEventGL (static_cast<QGestureEvent*>(event)); return QWidget::event(event); } //CONF option: MRViewFocusModifierKey //CONF default: meta (cmd on MacOSX) //CONF modifier key to select focus mode in MRView. Valid //CONF choices include shift, alt, ctrl, meta (on MacOSX: shift, alt, //CONF ctrl, cmd). //CONF option: MRViewMoveModifierKey //CONF default: shift //CONF modifier key to select move mode in MRView. Valid //CONF choices include shift, alt, ctrl, meta (on MacOSX: shift, alt, //CONF ctrl, cmd). //CONF option: MRViewRotateModifierKey //CONF default: ctrl //CONF modifier key to select rotate mode in MRView. Valid //CONF choices include shift, alt, ctrl, meta (on MacOSX: shift, alt, //CONF ctrl, cmd). // Main Window class: Window::Window() : glarea (new GLArea (*this)), mode (nullptr), font (glarea->font()), #ifdef MRTRIX_MACOSX FocusModifier (get_modifier ("MRViewFocusModifierKey", Qt::AltModifier)), #else FocusModifier (get_modifier ("MRViewFocusModifierKey", Qt::MetaModifier)), #endif MoveModifier (get_modifier ("MRViewMoveModifierKey", Qt::ShiftModifier)), RotateModifier (get_modifier ("MRViewRotateModifierKey", Qt::ControlModifier)), mouse_action (NoAction), focal_point { NAN, NAN, NAN }, camera_target { NAN, NAN, NAN }, orient (), field_of_view (100.0), anatomical_plane (2), colourbar_position (ColourMap::Position::BottomRight), tools_colourbar_position (ColourMap::Position::TopRight), snap_to_image_axes_and_voxel (true), tool_has_focus (nullptr), best_FPS (NAN), show_FPS (false) { main = this; GUI::App::set_main_window (this); setDockOptions (AllowTabbedDocks | VerticalTabs); setDocumentMode (true); //CONF option: IconSize //CONF default: 24 //CONF The size of the icons in the main MRView toolbar. setWindowTitle (tr ("MRView")); setWindowIcon (QPixmap (":/mrtrix.png")); { int iconsize = MR::File::Config::get_int ("IconSize", 24); setIconSize (QSize (iconsize, iconsize)); } setCentralWidget (glarea); QToolBar* toolbar; QAction* action; QMenu* menu; QToolButton* button; setTabPosition (Qt::AllDockWidgetAreas, QTabWidget::East); // Main toolbar: //CONF option: InitialToolBarPosition //CONF default: top //CONF The starting position of the MRView toolbar. Valid values are: //CONF top, bottom, left, right. Qt::ToolBarArea toolbar_position = Qt::TopToolBarArea; { std::string toolbar_pos_spec = lowercase (MR::File::Config::get ("InitialToolBarPosition")); if (toolbar_pos_spec.size()) { if (toolbar_pos_spec == "bottom") toolbar_position = Qt::BottomToolBarArea; else if (toolbar_pos_spec == "left") toolbar_position = Qt::LeftToolBarArea; else if (toolbar_pos_spec == "right") toolbar_position = Qt::RightToolBarArea; else if (toolbar_pos_spec != "top") WARN ("invalid value for configuration entry \"InitialToolBarPosition\""); } } //CONF option: ToolbarStyle //CONF default: 2 //CONF The style of the main toolbar buttons in MRView. See Qt's //CONF documentation for Qt::ToolButtonStyle. Qt::ToolButtonStyle button_style = static_cast<Qt::ToolButtonStyle> (MR::File::Config::get_int ("ToolbarStyle", 2)); toolbar = new QToolBar ("Main toolbar", this); addToolBar (toolbar_position, toolbar); action = toolbar->toggleViewAction (); action->setShortcut (tr ("Ctrl+M")); addAction (action); // File menu: menu = new QMenu (tr ("File menu"), this); action = menu->addAction (tr ("Open..."), this, SLOT (image_open_slot())); action->setShortcut (tr ("Ctrl+O")); addAction (action); save_action = menu->addAction (tr ("Save..."), this, SLOT (image_save_slot())); save_action->setShortcut (tr ("Ctrl+S")); addAction (save_action); close_action = menu->addAction (tr ("Close"), this, SLOT (image_close_slot())); close_action->setShortcut (tr ("Ctrl+W")); addAction (close_action); menu->addSeparator(); action = menu->addAction (tr ("DICOM import..."), this, SLOT (image_import_DICOM_slot())); action->setShortcut (tr ("Ctrl+D")); addAction (action); menu->addSeparator(); action = menu->addAction (tr ("Quit"), this, SLOT (close())); action->setShortcut (tr ("Ctrl+Q")); addAction (action); button = new QToolButton (this); button->setText ("File"); button->setToolButtonStyle (button_style); button->setToolTip (tr ("File menu")); button->setIcon (QIcon (":/start.svg")); button->setPopupMode (QToolButton::InstantPopup); button->setMenu (menu); toolbar->addWidget (button); // Image menu: image_menu = new QMenu (tr ("Image menu"), this); image_group = new QActionGroup (this); image_group->setExclusive (true); connect (image_group, SIGNAL (triggered (QAction*)), this, SLOT (image_select_slot (QAction*))); properties_action = image_menu->addAction (tr ("Properties..."), this, SLOT (image_properties_slot())); properties_action->setToolTip (tr ("Display the properties of the current image\n\nShortcut: Ctrl+P")); addAction (properties_action); image_menu->addSeparator(); next_slice_action = image_menu->addAction (tr ("Next slice"), this, SLOT (slice_next_slot())); next_slice_action->setShortcut (tr ("Up")); addAction (next_slice_action); prev_slice_action = image_menu->addAction (tr ("Previous slice"), this, SLOT (slice_previous_slot())); prev_slice_action->setShortcut (tr ("Down")); addAction (prev_slice_action); next_image_volume_action = image_menu->addAction (tr ("Next volume"), this, SLOT (image_next_volume_slot())); next_image_volume_action->setShortcut (tr ("Right")); addAction (next_image_volume_action); prev_image_volume_action = image_menu->addAction (tr ("Previous volume"), this, SLOT (image_previous_volume_slot())); prev_image_volume_action->setShortcut (tr ("Left")); addAction (prev_image_volume_action); next_image_volume_group_action = image_menu->addAction (tr ("Next volume group"), this, SLOT (image_next_volume_group_slot())); next_image_volume_group_action->setShortcut (tr ("Shift+Right")); addAction (next_image_volume_group_action); prev_image_volume_group_action = image_menu->addAction (tr("Previous volume group"), this, SLOT (image_previous_volume_group_slot())); prev_image_volume_group_action->setShortcut (tr ("Shift+Left")); addAction (prev_image_volume_group_action); image_menu->addSeparator(); next_image_action = image_menu->addAction (tr ("Next image"), this, SLOT (image_next_slot())); next_image_action->setShortcut (tr ("PgDown")); addAction (next_image_action); prev_image_action = image_menu->addAction (tr ("Previous image"), this, SLOT (image_previous_slot())); prev_image_action->setShortcut (tr ("PgUp")); addAction (prev_image_action); image_list_area = image_menu->addSeparator(); button = new QToolButton (this); button->setText ("Image"); button->setToolButtonStyle (button_style); button->setToolTip (tr ("Image menu")); button->setIcon (QIcon (":/image.svg")); button->setPopupMode (QToolButton::InstantPopup); button->setMenu (image_menu); toolbar->addWidget (button); // Colourmap menu: colourmap_button = new ColourMapButton (this, *this, true, true, false); colourmap_button->setText ("Colourmap"); colourmap_button->setToolButtonStyle (button_style); colourmap_button->setPopupMode (QToolButton::InstantPopup); QMenu* colourmap_menu = colourmap_button->menu(); invert_scale_action = colourmap_menu->addAction (tr ("Invert"), this, SLOT (invert_scaling_slot())); invert_scale_action->setCheckable (true); invert_scale_action->setShortcut (tr("U")); addAction (invert_scale_action); colourmap_menu->addSeparator(); reset_windowing_action = colourmap_menu->addAction (tr ("Reset brightness/contrast"), this, SLOT (image_reset_slot())); reset_windowing_action->setShortcut (tr ("Esc")); addAction (reset_windowing_action); image_interpolate_action = colourmap_menu->addAction (tr ("Interpolate"), this, SLOT (image_interpolate_slot())); image_interpolate_action->setShortcut (tr ("I")); image_interpolate_action->setCheckable (true); image_interpolate_action->setChecked (File::Config::get_bool("ImageInterpolation", true)); addAction (image_interpolate_action); toolbar->addWidget (colourmap_button); // Mode menu: mode_group = new QActionGroup (this); mode_group->setExclusive (true); connect (mode_group, SIGNAL (triggered (QAction*)), this, SLOT (select_mode_slot (QAction*))); menu = new QMenu ("Display mode", this); #define MODE(classname, specifier, name, description) \ menu->addAction (new Mode::Action<Mode::classname> (mode_group, #name, #description, n++)); #define MODE_OPTION(classname, specifier, name, description) MODE(classname, specifier, name, description) { size_t n = 1; #include "gui/mrview/mode/list.h" } #undef MODE #undef MODE_OPTION mode_group->actions()[0]->setChecked (true); for (int n = 0; n < mode_group->actions().size(); ++n) addAction (mode_group->actions()[n]); menu->addSeparator(); plane_group = new QActionGroup (this); plane_group->setExclusive (true); connect (plane_group, SIGNAL (triggered (QAction*)), this, SLOT (select_plane_slot (QAction*))); axial_action = menu->addAction (tr ("Axial")); axial_action->setShortcut (tr ("A")); axial_action->setCheckable (true); plane_group->addAction (axial_action); addAction (axial_action); sagittal_action = menu->addAction (tr ("Sagittal")); sagittal_action->setShortcut (tr ("S")); sagittal_action->setCheckable (true); plane_group->addAction (sagittal_action); addAction (sagittal_action); coronal_action = menu->addAction (tr ("Coronal")); coronal_action->setShortcut (tr ("C")); coronal_action->setCheckable (true); plane_group->addAction (coronal_action); addAction (coronal_action); menu->addSeparator(); action = menu->addAction (tr ("Toggle all annotations"), this, SLOT (toggle_annotations_slot())); action->setShortcut (tr("Space")); addAction (action); show_crosshairs_action = menu->addAction (tr ("Show focus"), glarea, SLOT (update())); show_crosshairs_action->setShortcut (tr("F")); show_crosshairs_action->setCheckable (true); show_crosshairs_action->setChecked (true); addAction (show_crosshairs_action); show_comments_action = menu->addAction (tr ("Show comments"), glarea, SLOT (update())); show_comments_action->setToolTip (tr ("Show/hide image comments\n\nShortcut: H")); show_comments_action->setShortcut (tr("H")); show_comments_action->setCheckable (true); show_comments_action->setChecked (true); addAction (show_comments_action); show_voxel_info_action = menu->addAction (tr ("Show voxel information"), glarea, SLOT (update())); show_voxel_info_action->setShortcut (tr("V")); show_voxel_info_action->setCheckable (true); show_voxel_info_action->setChecked (true); addAction (show_voxel_info_action); show_orientation_labels_action = menu->addAction (tr ("Show orientation labels"), glarea, SLOT (update())); show_orientation_labels_action->setShortcut (tr("O")); show_orientation_labels_action->setCheckable (true); show_orientation_labels_action->setChecked (true); addAction (show_orientation_labels_action); show_colourbar_action = menu->addAction (tr ("Show colour bar"), glarea, SLOT (update())); show_colourbar_action->setShortcut (tr("B")); show_colourbar_action->setCheckable (true); show_colourbar_action->setChecked (true); addAction (show_colourbar_action); menu->addSeparator(); action = menu->addAction (tr ("Background colour..."), this, SLOT (background_colour_slot())); action->setShortcut (tr ("G")); action->setCheckable (false); addAction (action); image_hide_action = menu->addAction (tr ("Hide main image"), this, SLOT (hide_image_slot())); image_hide_action->setShortcut (tr ("M")); image_hide_action->setCheckable (true); image_hide_action->setChecked (false); addAction (image_hide_action); menu->addSeparator(); full_screen_action = menu->addAction (tr ("Full screen"), this, SLOT (full_screen_slot())); full_screen_action->setShortcut (tr ("F11")); full_screen_action->setCheckable (true); full_screen_action->setChecked (false); addAction (full_screen_action); action = menu->addAction (tr ("Reset view"), this, SLOT(reset_view_slot())); action->setShortcut (tr ("R")); addAction (action); button = new QToolButton (this); button->setText ("View"); button->setToolButtonStyle (button_style); button->setToolTip (tr ("Display")); button->setIcon (QIcon (":/mode.svg")); button->setMenu (menu); button->setPopupMode (QToolButton::InstantPopup); toolbar->addWidget (button); // Tool menu: tool_group = new QActionGroup (this); tool_group->setExclusive (false); connect (tool_group, SIGNAL (triggered (QAction*)), this, SLOT (select_tool_slot (QAction*))); menu = new QMenu (tr ("Tools"), this); #undef TOOL #define TOOL(classname, name, description) \ menu->addAction (new Action<Tool::classname> (tool_group, #name, #description, n++)); { using namespace Tool; size_t n = 1; #include "gui/mrview/tool/list.h" } for (int n = 0; n < tool_group->actions().size(); ++n) addAction (tool_group->actions()[n]); button = new QToolButton (this); button->setText ("Tool"); button->setToolButtonStyle (button_style); button->setToolTip (tr ("Select additional tools...")); button->setIcon (QIcon (":/tools.svg")); button->setMenu (menu); button->setPopupMode (QToolButton::InstantPopup); toolbar->addWidget (button); toolbar->addSeparator(); // Mouse mode actions: mode_action_group = new QActionGroup (this); mode_action_group->setExclusive (true); connect (mode_action_group, SIGNAL (triggered (QAction*)), this, SLOT (select_mouse_mode_slot (QAction*))); std::string modifier; action = toolbar->addAction (QIcon (":/select_contrast.svg"), tr ("Change focus / contrast")); action->setToolTip (tr (( "Left-click: set focus\n" "Right-click: change brightness/constrast\n\n" "Shortcut: 1\n\n" "Hold down " + get_modifier (FocusModifier) + " key to use this mode\n" "regardless of currently selected mode").c_str())); action->setShortcut (tr("1")); action->setCheckable (true); action->setChecked (true); mode_action_group->addAction (action); action = toolbar->addAction (QIcon (":/move.svg"), tr ("Move viewport")); action->setToolTip (tr (( "Left-click: move in-plane\n" "Right-click: move through-plane\n\n" "Shortcut: 2\n\n" "Hold down " + get_modifier (MoveModifier) + " key to use this mode\n" "regardless of currently selected mode").c_str())); action->setShortcut (tr("2")); action->setCheckable (true); mode_action_group->addAction (action); action = toolbar->addAction (QIcon (":/rotate.svg"), tr ("Move camera")); action->setToolTip (tr (( "Left-click: move camera in-plane\n" "Right-click: rotate camera about view axis\n\n" "Shortcut: 3\n\n" "Hold down " + get_modifier (RotateModifier) + " key to use this mode\n" "regardless of currently selected mode").c_str())); action->setShortcut (tr("3")); action->setCheckable (true); mode_action_group->addAction (action); for (int n = 0; n < mode_action_group->actions().size(); ++n) addAction (mode_action_group->actions()[n]); toolbar->addSeparator(); snap_to_image_action = toolbar->addAction (QIcon (":/lock.svg"), tr ("Snap to image"), this, SLOT (snap_to_image_slot())); snap_to_image_action->setToolTip (tr ( "Snap focus and view orientation to\n" "image voxel grid and axes respectively\n\n" "Shortcut: L")); snap_to_image_action->setShortcut (tr("L")); snap_to_image_action->setCheckable (true); snap_to_image_action->setChecked (snap_to_image_axes_and_voxel); addAction (snap_to_image_action); toolbar->addSeparator(); // Information menu: menu = new QMenu (tr ("Info"), this); menu->addAction (tr ("About MRView"), this, SLOT (about_slot())); menu->addAction (tr ("About Qt"), this, SLOT (aboutQt_slot())); menu->addAction (tr ("OpenGL information"), this, SLOT (OpenGL_slot())); button = new QToolButton (this); button->setText ("Info"); button->setToolButtonStyle (button_style); button->setToolTip (tr ("Information")); button->setIcon (QIcon (":/help.svg")); button->setPopupMode (QToolButton::InstantPopup); button->setMenu (menu); toolbar->addWidget (button); lighting_ = new GL::Lighting (this); connect (lighting_, SIGNAL (changed()), glarea, SLOT (update())); set_image_menu (); //CONF option: MRViewColourBarPosition //CONF default: bottomright //CONF The position of the colourbar within the main window in MRView. //CONF Valid values are: bottomleft, bottomright, topleft, topright. std::string cbar_pos = lowercase (MR::File::Config::get ("MRViewColourBarPosition", "bottomright")); colourbar_position = parse_colourmap_position_str(cbar_pos); if(!colourbar_position) WARN ("invalid specifier \"" + cbar_pos + "\" for config file entry \"MRViewColourBarPosition\""); //CONF option: MRViewToolsColourBarPosition //CONF default: topright //CONF The position of all visible tool colourbars within the main window in MRView. //CONF Valid values are: bottomleft, bottomright, topleft, topright. cbar_pos = lowercase (MR::File::Config::get ("MRViewToolsColourBarPosition", "topright")); tools_colourbar_position = parse_colourmap_position_str(cbar_pos); if(!tools_colourbar_position) WARN ("invalid specifier \"" + cbar_pos + "\" for config file entry \"MRViewToolsColourBarPosition\""); } ColourMap::Position Window::parse_colourmap_position_str (const std::string& position_str) { ColourMap::Position pos(ColourMap::Position::None); if(position_str == "bottomleft") pos = ColourMap::Position::BottomLeft; else if(position_str == "bottomright") pos = ColourMap::Position::BottomRight; else if(position_str == "topleft") pos = ColourMap::Position::TopLeft; else if(position_str == "topright") pos = ColourMap::Position::TopRight; return pos; } Window::~Window () { glarea->makeCurrent(); QList<QAction*> tools = tool_group->actions(); for (QAction* action : tools) delete action; mode.reset(); QList<QAction*> images = image_group->actions(); for (QAction* action : images) delete action; } void Window::image_open_slot () { std::vector<std::string> image_list = Dialog::File::get_images (this, "Select images to open"); if (image_list.empty()) return; std::vector<std::unique_ptr<MR::Header>> list; for (size_t n = 0; n < image_list.size(); ++n) { try { list.push_back (std::unique_ptr<MR::Header> (new MR::Header (MR::Header::open (image_list[n])))); } catch (Exception& E) { E.display(); } } add_images (list); } void Window::image_import_DICOM_slot () { std::string folder = Dialog::File::get_folder (this, "Select DICOM folder to import"); if (folder.empty()) return; try { std::vector<std::unique_ptr<MR::Header>> list; list.push_back (std::unique_ptr<MR::Header> (new MR::Header (MR::Header::open (folder)))); add_images (list); } catch (Exception& E) { E.display(); } } void Window::add_images (std::vector<std::unique_ptr<MR::Header>>& list) { for (size_t i = 0; i < list.size(); ++i) { const std::string name = list[i]->name(); // Gets move-constructed out QAction* action = new Image (std::move (*list[i])); action->setText (shorten (name, 20, 0).c_str()); action->setParent (Window::main); action->setCheckable (true); action->setToolTip (name.c_str()); action->setStatusTip (name.c_str()); image_group->addAction (action); image_menu->addAction (action); connect (action, SIGNAL(scalingChanged()), this, SLOT(on_scaling_changed())); if (!i) image_select_slot (action); } set_image_menu(); } void Window::image_save_slot () { std::string image_name = Dialog::File::get_save_image_name (this, "Select image destination"); if (image_name.empty()) return; try { auto dest = MR::Image<cfloat>::create (image_name, image()->header()); MR::copy_with_progress (image()->image, dest); } catch (Exception& E) { E.display(); } } void Window::image_close_slot () { Image* imagep = image(); assert (imagep); QList<QAction*> list = image_group->actions(); if (list.size() > 1) { for (int n = 0; n < list.size(); ++n) { if (imagep == list[n]) { image_select_slot (list[ (n+1) %list.size()]); break; } } } image_group->removeAction (imagep); delete imagep; set_image_menu(); } void Window::image_properties_slot () { assert (image()); Dialog::ImageProperties props (this, image()->header()); props.exec(); } void Window::select_mode_slot (QAction* action) { glarea->makeCurrent(); mode.reset (dynamic_cast<GUI::MRView::Mode::__Action__*> (action)->create()); mode->set_visible(! image_hide_action->isChecked()); set_mode_features(); emit modeChanged(); glarea->update(); } void Window::select_mouse_mode_slot (QAction* action) { bool rotate_button_checked = mode_action_group->actions().indexOf (action) == 2; if (rotate_button_checked) set_snap_to_image (false); snap_to_image_action->setEnabled (!rotate_button_checked); set_cursor(); } void Window::select_tool_slot (QAction* action) { Tool::Dock* tool = dynamic_cast<Tool::__Action__*>(action)->dock; if (!tool) { tool = dynamic_cast<Tool::__Action__*>(action)->create(); connect (tool, SIGNAL (visibilityChanged (bool)), action, SLOT (setChecked (bool))); if (MR::File::Config::get_int ("MRViewDockFloating", 0)) return; for (int i = 0; i < tool_group->actions().size(); ++i) { Tool::Dock* other_tool = dynamic_cast<Tool::__Action__*>(tool_group->actions()[i])->dock; if (other_tool && other_tool != tool) { QList<QDockWidget* > list = QMainWindow::tabifiedDockWidgets (other_tool); if (list.size()) QMainWindow::tabifyDockWidget (list.last(), tool); else QMainWindow::tabifyDockWidget (other_tool, tool); tool->setFloating (false); tool->raise(); return; } } //CONF option: MRViewDockFloating //CONF default: 0 (false) //CONF Whether Tools should start docked in the main window, or //CONF floating (detached from the main window). tool->setFloating (MR::File::Config::get_int ("MRViewDockFloating", 0)); tool->show(); } if (action->isChecked()) { if (!tool->isVisible()) tool->show(); tool->raise(); } else { tool->close(); } glarea->update(); } void Window::selected_colourmap (size_t colourmap, const ColourMapButton&) { Image* imagep = image(); if (imagep) { imagep->set_colourmap (colourmap); glarea->update(); } } void Window::selected_custom_colour (const QColor& colour, const ColourMapButton&) { Image* imagep = image(); if (imagep) { std::array<GLubyte, 3> c_colour{{GLubyte(colour.red()), GLubyte(colour.green()), GLubyte(colour.blue())}}; imagep->set_colour(c_colour); glarea->update(); } } void Window::invert_scaling_slot () { if (image()) { image()->set_invert_scale (invert_scale_action->isChecked()); glarea->update(); } } void Window::snap_to_image_slot () { if (image()) { snap_to_image_axes_and_voxel = snap_to_image_action->isChecked(); if (snap_to_image_axes_and_voxel) mode->reset_orientation(); glarea->update(); } } void Window::on_scaling_changed () { emit scalingChanged(); } void Window::updateGL () { glarea->update(); } void Window::image_reset_slot () { Image* imagep = image(); if (imagep) { imagep->reset_windowing(); on_scaling_changed(); glarea->update(); } } void Window::image_interpolate_slot () { Image* imagep = image(); if (imagep) { imagep->set_interpolate (image_interpolate_action->isChecked()); glarea->update(); } } void Window::full_screen_slot () { if (full_screen_action->isChecked()) showFullScreen(); else showNormal(); } void Window::select_plane_slot (QAction* action) { if (action == axial_action) set_plane (2); else if (action == sagittal_action) set_plane (0); else if (action == coronal_action) set_plane (1); else assert (0); glarea->update(); } void Window::reset_view_slot () { if (image()) { mode->reset_event(); QList<QAction*> tools = tool_group->actions(); for (QAction* action : tools) { Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(action)->dock; if (dock) dock->tool->reset_event(); } } } void Window::background_colour_slot () { QColor colour = QColorDialog::getColor(Qt::black, this, "Select background colour", QColorDialog::DontUseNativeDialog); if (colour.isValid()) { background_colour[0] = GLubyte(colour.red()) / 255.0f; background_colour[1] = GLubyte(colour.green()) / 255.0f; background_colour[2] = GLubyte(colour.blue()) / 255.0f; glarea->update(); } } void Window::set_image_visibility (bool flag) { image_hide_action->setChecked(! flag); mode->set_visible(flag); } void Window::hide_image_slot () { bool visible = ! image_hide_action->isChecked(); mode->set_visible(visible); emit imageVisibilityChanged(visible); } void Window::slice_next_slot () { mode->slice_move_event (1); } void Window::slice_previous_slot () { mode->slice_move_event (-1); } void Window::image_next_slot () { QAction* action = image_group->checkedAction(); int N = image_group->actions().size(); int n = image_group->actions().indexOf (action); image_select_slot (image_group->actions()[(n+1)%N]); } void Window::image_previous_slot () { QAction* action = image_group->checkedAction(); int N = image_group->actions().size(); int n = image_group->actions().indexOf (action); image_select_slot (image_group->actions()[(n+N-1)%N]); } void Window::image_next_volume_slot () { size_t vol = image()->image.index(3)+1; set_image_volume (3, vol); emit volumeChanged(vol); } void Window::image_previous_volume_slot () { size_t vol = image()->image.index(3)-1; set_image_volume (3, vol); emit volumeChanged(vol); } void Window::image_next_volume_group_slot () { size_t vol = image()->image.index(4)+1; set_image_volume (4, vol); emit volumeGroupChanged(vol); } void Window::image_previous_volume_group_slot () { size_t vol = image()->image.index(4)-1; set_image_volume (4, vol); emit volumeGroupChanged(vol); } void Window::image_select_slot (QAction* action) { action->setChecked (true); image_interpolate_action->setChecked (image()->interpolate()); size_t cmap_index = image()->colourmap; colourmap_button->colourmap_actions[cmap_index]->setChecked (true); invert_scale_action->setChecked (image()->scale_inverted()); mode->image_changed_event(); setWindowTitle (image()->image.name().c_str()); set_image_navigation_menu(); image()->set_allowed_features ( mode->features & Mode::ShaderThreshold, mode->features & Mode::ShaderTransparency, mode->features & Mode::ShaderLighting); emit imageChanged(); glarea->update(); } void Window::toggle_annotations_slot () { int current_annotations = 0x00000000; if (show_crosshairs()) current_annotations |= 0x00000001; if (show_comments()) current_annotations |= 0x00000002; if (show_voxel_info()) current_annotations |= 0x00000004; if (show_orientation_labels()) current_annotations |= 0x00000008; if (show_colourbar()) current_annotations |= 0x00000010; if (current_annotations) { annotations = current_annotations; show_crosshairs_action->setChecked (false); show_comments_action->setChecked (false); show_voxel_info_action->setChecked (false); show_orientation_labels_action->setChecked (false); show_colourbar_action->setChecked (false); } else { if (!annotations) annotations = 0xFFFFFFFF; show_crosshairs_action->setChecked (annotations & 0x00000001); show_comments_action->setChecked (annotations & 0x00000002); show_voxel_info_action->setChecked (annotations & 0x00000004); show_orientation_labels_action->setChecked (annotations & 0x00000008); show_colourbar_action->setChecked (annotations & 0x00000010); } glarea->update(); } void Window::set_image_menu () { int N = image_group->actions().size(); next_image_action->setEnabled (N>1); prev_image_action->setEnabled (N>1); reset_windowing_action->setEnabled (N>0); colourmap_button->setEnabled (N>0); save_action->setEnabled (N>0); close_action->setEnabled (N>0); properties_action->setEnabled (N>0); set_image_navigation_menu(); glarea->update(); } int Window::get_mouse_mode () { if (mouse_action == NoAction && modifiers_ != Qt::NoModifier) { if (modifiers_ == FocusModifier && ( mode->features & Mode::FocusContrast )) return 1; else if (modifiers_ == MoveModifier && ( mode->features & Mode::MoveTarget )) return 2; else if (modifiers_ == RotateModifier && ( mode->features & Mode::TiltRotate )) return 3; } if (mouse_action == NoAction) return mode_action_group->actions().indexOf (mode_action_group->checkedAction()) + 1; return 0; } void Window::set_cursor () { MouseAction cursor = mouse_action; if (cursor == NoAction) { switch (get_mouse_mode()) { case 1: cursor = SetFocus; break; case 2: cursor = Pan; break; case 3: cursor = Tilt; break; default: assert (0); } } if (tool_has_focus && modifiers_ == Qt::NoModifier) { QCursor* ptr = tool_has_focus->get_cursor(); if (ptr) { glarea->setCursor (*ptr); return; } } switch (cursor) { case SetFocus: glarea->setCursor (Cursor::crosshair); break; case Contrast: glarea->setCursor (Cursor::window); break; case Pan: glarea->setCursor (Cursor::pan_crosshair); break; case PanThrough: glarea->setCursor (Cursor::forward_backward); break; case Tilt: glarea->setCursor (Cursor::throughplane_rotate); break; case Rotate: glarea->setCursor (Cursor::inplane_rotate); break; default: assert (0); } } void Window::set_mode_features () { mode_action_group->actions()[0]->setEnabled (mode->features & Mode::FocusContrast); mode_action_group->actions()[1]->setEnabled (mode->features & Mode::MoveTarget); mode_action_group->actions()[2]->setEnabled (mode->features & Mode::TiltRotate); if (!mode_action_group->checkedAction()->isEnabled()) mode_action_group->actions()[0]->setChecked (true); if (image()) image()->set_allowed_features ( mode->features & Mode::ShaderThreshold, mode->features & Mode::ShaderTransparency, mode->features & Mode::ShaderLighting); } void Window::set_image_navigation_menu () { bool show_next_volume (false), show_prev_volume (false); bool show_next_volume_group (false), show_prev_volume_group (false); Image* imagep = image(); if (imagep) { if (imagep->image.ndim() > 3) { if (imagep->image.index(3) > 0) show_prev_volume = true; if (imagep->image.index(3) < imagep->image.size(3)-1) show_next_volume = true; if (imagep->image.ndim() > 4) { if (imagep->image.index(4) > 0) show_prev_volume_group = true; if (imagep->image.index(4) < imagep->image.size(4)-1) show_next_volume_group = true; } } } prev_image_volume_action->setEnabled (show_prev_volume); next_image_volume_action->setEnabled (show_next_volume); prev_image_volume_group_action->setEnabled (show_prev_volume_group); next_image_volume_group_action->setEnabled (show_next_volume_group); } void Window::OpenGL_slot () { Dialog::OpenGL glinfo (this, glarea->format()); glinfo.exec(); } void Window::about_slot () { std::string message = std::string ("<h1>MRView</h1>The MRtrix viewer, version ") + MR::App::mrtrix_version + "<br>" "<em>" + str (8*sizeof (size_t)) + " bit " #ifdef NDEBUG "release" #else "debug" #endif " version, built " + MR::App::build_date + "</em><p>" "<h4>Authors:</h4>" + MR::join (MR::split (MR::App::AUTHOR, ",;&\n", true), "<br>") + "<p><em>" + MR::App::COPYRIGHT + "</em>"; QMessageBox::about (this, tr ("About MRView"), message.c_str()); } void Window::aboutQt_slot () { QMessageBox::aboutQt (this); } void Window::paintGL () { ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; GL_CHECK_ERROR; gl::ClearColor (background_colour[0], background_colour[1], background_colour[2], 1.0); if (glarea->format().samples() > 1) gl::Enable (gl::MULTISAMPLE); GL_CHECK_ERROR; ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; mode->paintGL(); ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; GL_CHECK_ERROR; if (show_FPS) { render_times.push_back (Timer::current_time()); while (render_times.size() > 10) render_times.erase (render_times.begin()); double FPS = NAN; std::string FPS_string = "-"; std::string FPS_best_string = "-"; if (render_times.back() - best_FPS_time > 3.0) best_FPS = NAN; if (render_times.size() == 10) { FPS = (render_times.size()-1.0) / (render_times.back()-render_times.front()); FPS_string = str (FPS, 4); if (!std::isfinite (best_FPS) || FPS > best_FPS) { best_FPS = FPS; best_FPS_time = render_times.back(); } } else best_FPS = NAN; if (std::isfinite (best_FPS)) FPS_best_string = str (best_FPS, 4); mode->projection.setup_render_text (0.0, 1.0, 0.0); mode->projection.render_text ("max FPS: " + FPS_best_string, RightEdge | TopEdge); mode->projection.render_text ("FPS: " + FPS_string, RightEdge | TopEdge, 1); mode->projection.done_render_text(); } // need to clear alpha channel when using QOpenGLWidget (Qt >= 5.4) // otherwise we get transparent windows... #if QT_VERSION >= 0x050400 gl::ColorMask (false, false, false, true); gl::Clear (gl::COLOR_BUFFER_BIT); glColorMask (true, true, true, true); #endif GL_CHECK_ERROR; ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; } void Window::initGL () { ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; GL::init (); font.initGL(); gl::Enable (gl::DEPTH_TEST); //CONF option: ImageBackgroundColour //CONF default: 0,0,0 (black) // CONF The default image background colour File::Config::get_RGB ("ImageBackgroundColour", background_colour, 0.0f, 0.0f, 0.0f); gl::ClearColor (background_colour[0], background_colour[1], background_colour[2], 1.0); mode.reset (dynamic_cast<Mode::__Action__*> (mode_group->actions()[0])->create()); set_mode_features(); if (MR::App::option.size()) QTimer::singleShot (0, this, SLOT (process_commandline_options())); ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT; } template <class Event> void Window::grab_mouse_state (Event* event) { buttons_ = event->buttons(); modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier ); mouse_displacement_ = QPoint (0,0); mouse_position_ = event->pos(); mouse_position_.setY (glarea->height() - mouse_position_.y()); } template <class Event> void Window::update_mouse_state (Event* event) { mouse_displacement_ = mouse_position_; mouse_position_ = event->pos(); mouse_position_.setY (glarea->height() - mouse_position_.y()); mouse_displacement_ = mouse_position_ - mouse_displacement_; } void Window::keyPressEvent (QKeyEvent* event) { modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier ); set_cursor(); } void Window::keyReleaseEvent (QKeyEvent* event) { modifiers_ = event->modifiers() & ( FocusModifier | MoveModifier | RotateModifier ); set_cursor(); } void Window::mousePressEventGL (QMouseEvent* event) { assert (mode); grab_mouse_state (event); if (image()) mode->mouse_press_event(); if (tool_has_focus && modifiers_ == Qt::NoModifier) { if (tool_has_focus->mouse_press_event()) { mouse_action = NoAction; event->accept(); return; } } int group = get_mouse_mode(); if (buttons_ == Qt::MidButton) mouse_action = Pan; else if (group == 1) { if (buttons_ == Qt::LeftButton) { mouse_action = SetFocus; if (image()) mode->set_focus_event(); } else if (buttons_ == Qt::RightButton) mouse_action = Contrast; } else if (group == 2) { if (buttons_ == Qt::LeftButton) mouse_action = Pan; else if (buttons_ == Qt::RightButton) mouse_action = PanThrough; } else if (group == 3) { if (buttons_ == Qt::LeftButton) mouse_action = Tilt; else if (buttons_ == Qt::RightButton) mouse_action = Rotate; } set_cursor(); event->accept(); } void Window::mouseMoveEventGL (QMouseEvent* event) { assert (mode); if (!image()) return; update_mouse_state (event); if (mouse_action == NoAction) { if (tool_has_focus) if (tool_has_focus->mouse_move_event()) event->accept(); return; } switch (mouse_action) { case SetFocus: mode->set_focus_event(); break; case Contrast: mode->contrast_event(); break; case Pan: mode->pan_event(); break; case PanThrough: mode->panthrough_event(); break; case Tilt: mode->tilt_event(); break; case Rotate: mode->rotate_event(); break; default: return; } event->accept(); } void Window::mouseReleaseEventGL (QMouseEvent*) { assert (mode); mode->mouse_release_event(); if (tool_has_focus && mouse_action == NoAction) if (tool_has_focus->mouse_release_event()) return; mouse_action = NoAction; set_cursor(); } void Window::wheelEventGL (QWheelEvent* event) { assert (mode); #if QT_VERSION >= 0x050400 QPoint delta = event->pixelDelta(); if (delta.isNull()) delta = event->angleDelta(); #else QPoint delta = event->orientation() == Qt::Vertical ? QPoint (0, event->delta()) : QPoint (event->delta(), 0); #endif if (delta.isNull()) return; if (delta.y()) { if (image()) { grab_mouse_state (event); mode->mouse_press_event(); if (buttons_ == Qt::NoButton) { if (modifiers_ == Qt::ControlModifier) { set_FOV (FOV() * std::exp (-delta.y()/1200.0)); glarea->update(); event->accept(); return; } float dx = delta.y()/120.0; if (modifiers_ == Qt::ShiftModifier) dx *= 10.0; else if (modifiers_ != Qt::NoModifier) return; mode->slice_move_event (dx); event->accept(); return; } } if (buttons_ == Qt::RightButton && modifiers_ == Qt::NoModifier) { if (image_group->actions().size() > 1) { QAction* action = image_group->checkedAction(); int N = image_group->actions().size(); int n = image_group->actions().indexOf (action); image_select_slot (image_group->actions()[(n+N+int(std::round(delta.y()/120.0)))%N]); } } } } bool Window::gestureEventGL (QGestureEvent* event) { assert (mode); if (QGesture *swipe = event->gesture (Qt::SwipeGesture)) { QSwipeGesture* e = static_cast<QSwipeGesture*> (swipe); int dx = e->horizontalDirection() == QSwipeGesture::Left ? -1 : ( e->horizontalDirection() == QSwipeGesture::Right ? 1 : 0); if (dx != 0 && image_group->actions().size() > 1) { QAction* action = image_group->checkedAction(); int N = image_group->actions().size(); int n = image_group->actions().indexOf (action); image_select_slot (image_group->actions()[(n+N+dx)%N]); } } else if (QGesture* pinch = event->gesture(Qt::PinchGesture)) { QPinchGesture* e = static_cast<QPinchGesture*> (pinch); QPinchGesture::ChangeFlags changeFlags = e->changeFlags(); if (changeFlags & QPinchGesture::RotationAngleChanged) { // TODO } if (changeFlags & QPinchGesture::ScaleFactorChanged) { set_FOV (FOV() * e->lastScaleFactor() / e->scaleFactor()); glarea->update(); } } return true; } void Window::closeEvent (QCloseEvent* event) { qApp->quit(); event->accept(); } void Window::process_commandline_options () { #undef TOOL #define TOOL(classname, name, description) \ stub = lowercase (#classname "."); \ if (stub.compare (0, stub.size(), std::string (opt.opt->id), 0, stub.size()) == 0) { \ tool_group->actions()[tool_id]->setChecked (true); \ select_tool_slot (tool_group->actions()[tool_id]); \ if (dynamic_cast<Tool::__Action__*>(tool_group->actions()[tool_id])->dock->tool->process_commandline_option (opt)) \ continue; \ } \ ++tool_id; glarea->update(); qApp->processEvents(); try { for (size_t copt = 0; copt < MR::App::option.size(); ++copt) { if (copt) qApp->processEvents(); const MR::App::ParsedOption& opt (MR::App::option[copt]); // see whether option is claimed by any tools: size_t tool_id = 0; std::string stub; #include "gui/mrview/tool/list.h" // process general options: if (opt.opt->is ("mode")) { int n = int(opt[0]) - 1; if (n < 0 || n >= mode_group->actions().size()) throw Exception ("invalid mode index \"" + str(n) + "\" in batch command"); select_mode_slot (mode_group->actions()[n]); continue; } if (opt.opt->is ("size")) { std::vector<int> glsize = opt[0]; if (glsize.size() != 2) throw Exception ("invalid argument \"" + std::string(opt.args[0]) + "\" to view.size batch command"); QSize oldsize = glarea->size(); QSize winsize = size(); resize (winsize.width() - oldsize.width() + glsize[0], winsize.height() - oldsize.height() + glsize[1]); continue; } if (opt.opt->is ("reset")) { reset_view_slot(); continue; } else if (opt.opt->is ("fov")) { float fov = opt[0]; set_FOV (fov); glarea->update(); continue; } if (opt.opt->is ("focus")) { std::vector<default_type> pos = parse_floats (opt[0]); if (pos.size() != 3) throw Exception ("-focus option expects a comma-separated list of 3 floating-point values"); set_focus (Eigen::Vector3f { float(pos[0]), float(pos[1]), float(pos[2]) }); glarea->update(); continue; } if (opt.opt->is ("voxel")) { if (image()) { std::vector<default_type> pos = parse_floats (opt[0]); if (pos.size() != 3) throw Exception ("-voxel option expects a comma-separated list of 3 floating-point values"); set_focus (image()->transform().voxel2scanner.cast<float>() * Eigen::Vector3f { float(pos[0]), float(pos[1]), float(pos[2]) }); glarea->update(); } continue; } if (opt.opt->is ("fov")) { float fov = opt[0]; set_FOV (fov); glarea->update(); continue; } if (opt.opt->is ("plane")) { int n = opt[0]; set_plane (n); glarea->update(); continue; } if (opt.opt->is ("lock")) { bool n = opt[0]; snap_to_image_action->setChecked (n); snap_to_image_slot(); continue; } if (opt.opt->is ("select_image")) { int n = int(opt[0]) - 1; if (n < 0 || n >= image_group->actions().size()) throw Exception ("invalid image index requested for option -select_image"); image_select_slot (image_group->actions()[n]); continue; } if (opt.opt->is ("load")) { std::vector<std::unique_ptr<MR::Header>> list; try { list.push_back (std::unique_ptr<MR::Header> (new MR::Header (MR::Header::open (opt[0])))); } catch (Exception& e) { e.display(); } add_images (list); continue; } if (opt.opt->is ("autoscale")) { image_reset_slot(); continue; } if (opt.opt->is ("colourmap")) { int n = int(opt[0]) - 1; if (n < 0 || n >= static_cast<int>(colourmap_button->colourmap_actions.size())) throw Exception ("invalid image colourmap index \"" + str(n+1) + "\" requested in batch command"); colourmap_button->set_colourmap_index(n); continue; } if (opt.opt->is ("interpolation_on")) { image_interpolate_action->setChecked(true); image_interpolate_slot(); } if (opt.opt->is ("interpolation_off")) { image_interpolate_action->setChecked(false); image_interpolate_slot(); } if (opt.opt->is ("intensity_range")) { if (image()) { std::vector<default_type> param = parse_floats (opt[0]); if (param.size() != 2) throw Exception ("-intensity_range options expects comma-separated list of two floating-point values"); image()->set_windowing (param[0], param[1]); glarea->update(); } continue; } if (opt.opt->is ("position")) { std::vector<int> pos = opt[0]; if (pos.size() != 2) throw Exception ("invalid argument \"" + std::string(opt[0]) + "\" to -position option"); move (pos[0], pos[1]); continue; } if (opt.opt->is ("fullscreen")) { full_screen_action->setChecked (true); full_screen_slot(); continue; } if (opt.opt->is ("fps")) { show_FPS = true; continue; } if (opt.opt->is ("exit")) { qApp->processEvents(); qApp->quit(); } } } catch (Exception& E) { E.display(); qApp->quit(); } } void Window::add_commandline_options (MR::App::OptionList& options) { options + OptionGroup ("View options") + Option ("mode", "Switch to view mode specified by the integer index. as per the view menu.") + Argument ("index").type_integer() + Option ("load", "Load image specified and make it current.") + Argument ("image").type_image_in() + Option ("reset", "Reset the view according to current image. This resets the FOV, projection, and focus.") + Option ("fov", "Set the field of view, in mm.") + Argument ("value").type_float() + Option ("focus", "Set the position of the crosshairs in scanner coordinates, " "with the new position supplied as a comma-separated list of floating-point values.") + Argument ("x,y,z").type_sequence_float() + Option ("voxel", "Set the position of the crosshairs in voxel coordinates, " "relative the image currently displayed. The new position should be supplied " "as a comma-separated list of floating-point values.") + Argument ("x,y,z").type_sequence_float() + Option ("plane", "Set the viewing plane, according to the mappping 0: sagittal; 1: coronal; 2: axial.") + Argument ("index").type_integer (0,0,3) + Option ("lock", "Set whether view is locked to image axes (0: no, 1: yes).") + Argument ("yesno").type_bool() + Option ("select_image", "Switch to image number specified, with reference to the list of currently loaded images.") + Argument ("index").type_integer (0) + Option ("autoscale", "Reset the image scaling to automatically determined range.") + Option ("interpolation_on", "Enable the image interpolation.") + Option ("interpolation_off", "Disable the image interpolation.") + Option ("colourmap", "Switch the image colourmap to that specified, as per the colourmap menu.") + Argument ("index").type_integer (0) + Option ("intensity_range", "Set the image intensity range to that specified") + Argument ("min,max").type_sequence_int() + OptionGroup ("Window management options") + Option ("size", "Set the size of the view area, in pixel units.") + Argument ("width,height").type_sequence_int() + Option ("position", "Set the position of the main window, in pixel units.") + Argument ("x,y").type_sequence_int() + Option ("fullscreen", "Start fullscreen.") + Option ("exit", "quit MRView") + OptionGroup ("Debugging options") + Option ("fps", "Display frames per second, averaged over the last 10 frames. " "The maximum over the last 3 seconds is also displayed."); } } } }
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qdebug.h> #include <QtGui/private/qt_x11_p.h> #include <QtGui/qx11info_x11.h> #include <QtGui/private/qpixmapdata_p.h> #include <QtGui/private/qpixmap_x11_p.h> #include <QtGui/private/qimagepixmapcleanuphooks_p.h> #include <QtGui/qpaintdevice.h> #include <QtGui/qpixmap.h> #include <QtGui/qwidget.h> #include <QtGui/qcolormap.h> #include "QtGui/private/qegl_p.h" #include "QtGui/private/qeglcontext_p.h" QT_BEGIN_NAMESPACE EGLNativeDisplayType QEgl::nativeDisplay() { Display *xdpy = QX11Info::display(); if (!xdpy) { qWarning("QEglContext::getDisplay(): X11 display is not open"); return EGLNativeDisplayType(EGL_DEFAULT_DISPLAY); } return EGLNativeDisplayType(xdpy); } EGLNativeWindowType QEgl::nativeWindow(QWidget* widget) { return (EGLNativeWindowType)(widget->winId()); } EGLNativePixmapType QEgl::nativePixmap(QPixmap* pixmap) { return (EGLNativePixmapType)(pixmap->handle()); } static int countBits(unsigned long mask) { int count = 0; while (mask != 0) { if (mask & 1) ++count; mask >>= 1; } return count; } // Set the pixel format parameters from the visual in "xinfo". void QEglProperties::setVisualFormat(const QX11Info *xinfo) { if (!xinfo) return; Visual *visual = (Visual*)xinfo->visual(); if (!visual) return; if (visual->c_class != TrueColor && visual->c_class != DirectColor) return; setValue(EGL_RED_SIZE, countBits(visual->red_mask)); setValue(EGL_GREEN_SIZE, countBits(visual->green_mask)); setValue(EGL_BLUE_SIZE, countBits(visual->blue_mask)); EGLint alphaBits = 0; #if !defined(QT_NO_XRENDER) XRenderPictFormat *format; format = XRenderFindVisualFormat(xinfo->display(), visual); if (format && (format->type == PictTypeDirect) && format->direct.alphaMask) { alphaBits = countBits(format->direct.alphaMask); qDebug("QEglProperties::setVisualFormat() - visual's alphaMask is %d", alphaBits); } #endif setValue(EGL_ALPHA_SIZE, alphaBits); } extern const QX11Info *qt_x11Info(const QPaintDevice *pd); // Set pixel format and other properties based on a paint device. void QEglProperties::setPaintDeviceFormat(QPaintDevice *dev) { if (!dev) return; if (dev->devType() == QInternal::Image) setPixelFormat(static_cast<QImage *>(dev)->format()); else setVisualFormat(qt_x11Info(dev)); } //#define QT_DEBUG_X11_VISUAL_SELECTION 1 VisualID QEgl::getCompatibleVisualId(EGLConfig config) { VisualID visualId = 0; EGLint eglValue = 0; EGLint configRedSize = 0; eglGetConfigAttrib(display(), config, EGL_RED_SIZE, &configRedSize); EGLint configGreenSize = 0; eglGetConfigAttrib(display(), config, EGL_GREEN_SIZE, &configGreenSize); EGLint configBlueSize = 0; eglGetConfigAttrib(display(), config, EGL_BLUE_SIZE, &configBlueSize); EGLint configAlphaSize = 0; eglGetConfigAttrib(display(), config, EGL_ALPHA_SIZE, &configAlphaSize); eglGetConfigAttrib(display(), config, EGL_CONFIG_ID, &eglValue); int configId = eglValue; // See if EGL provided a valid VisualID: eglGetConfigAttrib(display(), config, EGL_NATIVE_VISUAL_ID, &eglValue); visualId = (VisualID)eglValue; if (visualId) { // EGL has suggested a visual id, so get the rest of the visual info for that id: XVisualInfo visualInfoTemplate; memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); visualInfoTemplate.visualid = visualId; XVisualInfo *chosenVisualInfo; int matchingCount = 0; chosenVisualInfo = XGetVisualInfo(X11->display, VisualIDMask, &visualInfoTemplate, &matchingCount); if (chosenVisualInfo) { int visualRedSize = countBits(chosenVisualInfo->red_mask); int visualGreenSize = countBits(chosenVisualInfo->green_mask); int visualBlueSize = countBits(chosenVisualInfo->blue_mask); int visualAlphaSize = -1; // Need XRender to tell us the alpha channel size #if !defined(QT_NO_XRENDER) if (X11->use_xrender) { // If we have XRender, actually check the visual supplied by EGL is ARGB XRenderPictFormat *format; format = XRenderFindVisualFormat(X11->display, chosenVisualInfo->visual); if (format && (format->type == PictTypeDirect)) visualAlphaSize = countBits(format->direct.alphaMask); } #endif bool visualMatchesConfig = false; if ( visualRedSize == configRedSize && visualGreenSize == configGreenSize && visualBlueSize == configBlueSize ) { // We need XRender to check the alpha channel size of the visual. If we don't have // the alpha size, we don't check it against the EGL config's alpha size. if (visualAlphaSize >= 0) visualMatchesConfig = visualAlphaSize == configAlphaSize; else visualMatchesConfig = true; } if (!visualMatchesConfig) { if (visualAlphaSize >= 0) { qWarning("Warning: EGL suggested using X Visual ID %d (ARGB%d%d%d%d) for EGL config %d (ARGB%d%d%d%d), but this is incompatable", (int)visualId, visualAlphaSize, visualRedSize, visualGreenSize, visualBlueSize, configId, configAlphaSize, configRedSize, configGreenSize, configBlueSize); } else { qWarning("Warning: EGL suggested using X Visual ID %d (RGB%d%d%d) for EGL config %d (RGB%d%d%d), but this is incompatable", (int)visualId, visualRedSize, visualGreenSize, visualBlueSize, configId, configRedSize, configGreenSize, configBlueSize); } visualId = 0; } } else { qWarning("Warning: EGL suggested using X Visual ID %d for EGL config %d, but that isn't a valid ID", (int)visualId, configId); visualId = 0; } XFree(chosenVisualInfo); } if (visualId) { #ifdef QT_DEBUG_X11_VISUAL_SELECTION if (configAlphaSize > 0) qDebug("Using ARGB Visual ID %d provided by EGL for config %d", (int)visualId, configId); else qDebug("Using Opaque Visual ID %d provided by EGL for config %d", (int)visualId, configId); #endif return visualId; } // If EGL didn't give us a valid visual ID, try XRender #if !defined(QT_NO_XRENDER) if (!visualId && X11->use_xrender) { XVisualInfo visualInfoTemplate; memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); visualInfoTemplate.c_class = TrueColor; XVisualInfo *matchingVisuals; int matchingCount = 0; matchingVisuals = XGetVisualInfo(X11->display, VisualClassMask, &visualInfoTemplate, &matchingCount); for (int i = 0; i < matchingCount; ++i) { XRenderPictFormat *format; format = XRenderFindVisualFormat(X11->display, matchingVisuals[i].visual); // Check the format for the visual matches the EGL config if ( (countBits(format->direct.redMask) == configRedSize) && (countBits(format->direct.greenMask) == configGreenSize) && (countBits(format->direct.blueMask) == configBlueSize) && (countBits(format->direct.alphaMask) == configAlphaSize) ) { visualId = matchingVisuals[i].visualid; break; } } if (matchingVisuals) XFree(matchingVisuals); } if (visualId) { # ifdef QT_DEBUG_X11_VISUAL_SELECTION if (configAlphaSize > 0) qDebug("Using ARGB Visual ID %d provided by XRender for EGL config %d", (int)visualId, configId); else qDebug("Using Opaque Visual ID %d provided by XRender for EGL config %d", (int)visualId, configId); # endif // QT_DEBUG_X11_VISUAL_SELECTION return visualId; } #endif //!defined(QT_NO_XRENDER) // Finally, if XRender also failed to find a visual (or isn't present), try to // use XGetVisualInfo and only use the bit depths to match on: if (!visualId) { XVisualInfo visualInfoTemplate; memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); XVisualInfo *matchingVisuals; int matchingCount = 0; visualInfoTemplate.depth = configRedSize + configGreenSize + configBlueSize + configAlphaSize; matchingVisuals = XGetVisualInfo(X11->display, VisualDepthMask, &visualInfoTemplate, &matchingCount); if (!matchingVisuals) { // Try again without taking the alpha channel into account: visualInfoTemplate.depth = configRedSize + configGreenSize + configBlueSize; matchingVisuals = XGetVisualInfo(X11->display, VisualDepthMask, &visualInfoTemplate, &matchingCount); } if (matchingVisuals) { visualId = matchingVisuals[0].visualid; XFree(matchingVisuals); } } if (visualId) { #ifdef QT_DEBUG_X11_VISUAL_SELECTION qDebug("Using Visual ID %d provided by XGetVisualInfo for EGL config %d", (int)visualId, configId); #endif return visualId; } qWarning("Unable to find an X11 visual which matches EGL config %d", configId); return (VisualID)0; } void qt_set_winid_on_widget(QWidget* w, Qt::HANDLE id) { w->create(id); } // NOTE: The X11 version of createSurface will re-create the native drawable if it's visual doesn't // match the one for the passed in EGLConfig EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig config, const QEglProperties *unusedProperties) { Q_UNUSED(unusedProperties); int devType = device->devType(); if (devType == QInternal::Pbuffer) { // TODO return EGL_NO_SURFACE; } QX11PixmapData *x11PixmapData = 0; if (devType == QInternal::Pixmap) { QPixmapData *pmd = static_cast<QPixmap*>(device)->data_ptr().data(); if (pmd->classId() == QPixmapData::X11Class) x11PixmapData = static_cast<QX11PixmapData*>(pmd); else { // TODO: Replace the pixmap's data with a new QX11PixmapData qWarning("WARNING: Creating an EGL surface on a QPixmap is only supported for QX11PixmapData"); return EGL_NO_SURFACE; } } else if ((devType != QInternal::Widget) && (devType != QInternal::Pbuffer)) { qWarning("WARNING: Creating an EGLSurface for device type %d isn't supported", devType); return EGL_NO_SURFACE; } VisualID visualId = QEgl::getCompatibleVisualId(config); EGLint alphaSize; eglGetConfigAttrib(QEgl::display(), config, EGL_ALPHA_SIZE, &alphaSize); if (devType == QInternal::Widget) { QWidget *widget = static_cast<QWidget*>(device); VisualID currentVisualId = 0; if (widget->testAttribute(Qt::WA_WState_Created)) currentVisualId = XVisualIDFromVisual((Visual*)widget->x11Info().visual()); if (currentVisualId != visualId) { // The window is either not created or has the wrong visual. Either way, we need // to create a window with the correct visual and call create() on the widget: bool visible = widget->isVisible(); if (visible) widget->hide(); XVisualInfo visualInfo; visualInfo.visualid = visualId; { XVisualInfo *visualInfoPtr; int matchingCount = 0; visualInfoPtr = XGetVisualInfo(widget->x11Info().display(), VisualIDMask, &visualInfo, &matchingCount); Q_ASSERT(visualInfoPtr); // visualId really should be valid! visualInfo = *visualInfoPtr; XFree(visualInfoPtr); } Window parentWindow = RootWindow(widget->x11Info().display(), widget->x11Info().screen()); if (widget->parentWidget()) parentWindow = widget->parentWidget()->winId(); XSetWindowAttributes windowAttribs; QColormap colmap = QColormap::instance(widget->x11Info().screen()); windowAttribs.background_pixel = colmap.pixel(widget->palette().color(widget->backgroundRole())); windowAttribs.border_pixel = colmap.pixel(Qt::black); unsigned int valueMask = CWBackPixel|CWBorderPixel; if (alphaSize > 0) { windowAttribs.colormap = XCreateColormap(widget->x11Info().display(), parentWindow, visualInfo.visual, AllocNone); valueMask |= CWColormap; } Window window = XCreateWindow(widget->x11Info().display(), parentWindow, widget->x(), widget->y(), widget->width(), widget->height(), 0, visualInfo.depth, InputOutput, visualInfo.visual, valueMask, &windowAttribs); // This is a nasty hack to get round the fact that we can't be a friend of QWidget: qt_set_winid_on_widget(widget, window); if (visible) widget->show(); } // At this point, the widget's window should be created and have the correct visual. Now we // just need to create the EGL surface for it: return eglCreateWindowSurface(QEgl::display(), config, (EGLNativeWindowType)widget->winId(), 0); } if (x11PixmapData) { // X11 Pixmaps are only created with a depth, so that's all we need to check EGLint configDepth; eglGetConfigAttrib(QEgl::display(), config, EGL_BUFFER_SIZE , &configDepth); if (x11PixmapData->depth() != configDepth) { // The bit depths are wrong which means the EGLConfig isn't compatable with // this pixmap. So we need to replace the pixmap's existing data with a new // one which is created with the correct depth: #ifndef QT_NO_XRENDER if (configDepth == 32) { qWarning("Warning: EGLConfig's depth (32) != pixmap's depth (%d), converting to ARGB32", x11PixmapData->depth()); x11PixmapData->convertToARGB32(true); } else #endif { qWarning("Warning: EGLConfig's depth (%d) != pixmap's depth (%d)", configDepth, x11PixmapData->depth()); } } QEglProperties surfaceAttribs; // If the pixmap can't be bound to a texture, it's pretty useless surfaceAttribs.setValue(EGL_TEXTURE_TARGET, EGL_TEXTURE_2D); if (alphaSize > 0) surfaceAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA); else surfaceAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGB); EGLSurface surf = eglCreatePixmapSurface(QEgl::display(), config, (EGLNativePixmapType) x11PixmapData->handle(), surfaceAttribs.properties()); x11PixmapData->gl_surface = (void*)surf; QImagePixmapCleanupHooks::enableCleanupHooks(x11PixmapData); return surf; } return EGL_NO_SURFACE; } QT_END_NAMESPACE Print more information when debugging X11 Visual selection Reviewed-By: TrustMe /**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qdebug.h> #include <QtGui/private/qt_x11_p.h> #include <QtGui/qx11info_x11.h> #include <QtGui/private/qpixmapdata_p.h> #include <QtGui/private/qpixmap_x11_p.h> #include <QtGui/private/qimagepixmapcleanuphooks_p.h> #include <QtGui/qpaintdevice.h> #include <QtGui/qpixmap.h> #include <QtGui/qwidget.h> #include <QtGui/qcolormap.h> #include "QtGui/private/qegl_p.h" #include "QtGui/private/qeglcontext_p.h" QT_BEGIN_NAMESPACE EGLNativeDisplayType QEgl::nativeDisplay() { Display *xdpy = QX11Info::display(); if (!xdpy) { qWarning("QEglContext::getDisplay(): X11 display is not open"); return EGLNativeDisplayType(EGL_DEFAULT_DISPLAY); } return EGLNativeDisplayType(xdpy); } EGLNativeWindowType QEgl::nativeWindow(QWidget* widget) { return (EGLNativeWindowType)(widget->winId()); } EGLNativePixmapType QEgl::nativePixmap(QPixmap* pixmap) { return (EGLNativePixmapType)(pixmap->handle()); } static int countBits(unsigned long mask) { int count = 0; while (mask != 0) { if (mask & 1) ++count; mask >>= 1; } return count; } // Set the pixel format parameters from the visual in "xinfo". void QEglProperties::setVisualFormat(const QX11Info *xinfo) { if (!xinfo) return; Visual *visual = (Visual*)xinfo->visual(); if (!visual) return; if (visual->c_class != TrueColor && visual->c_class != DirectColor) return; setValue(EGL_RED_SIZE, countBits(visual->red_mask)); setValue(EGL_GREEN_SIZE, countBits(visual->green_mask)); setValue(EGL_BLUE_SIZE, countBits(visual->blue_mask)); EGLint alphaBits = 0; #if !defined(QT_NO_XRENDER) XRenderPictFormat *format; format = XRenderFindVisualFormat(xinfo->display(), visual); if (format && (format->type == PictTypeDirect) && format->direct.alphaMask) { alphaBits = countBits(format->direct.alphaMask); qDebug("QEglProperties::setVisualFormat() - visual's alphaMask is %d", alphaBits); } #endif setValue(EGL_ALPHA_SIZE, alphaBits); } extern const QX11Info *qt_x11Info(const QPaintDevice *pd); // Set pixel format and other properties based on a paint device. void QEglProperties::setPaintDeviceFormat(QPaintDevice *dev) { if (!dev) return; if (dev->devType() == QInternal::Image) setPixelFormat(static_cast<QImage *>(dev)->format()); else setVisualFormat(qt_x11Info(dev)); } //#define QT_DEBUG_X11_VISUAL_SELECTION 1 VisualID QEgl::getCompatibleVisualId(EGLConfig config) { VisualID visualId = 0; EGLint eglValue = 0; EGLint configRedSize = 0; eglGetConfigAttrib(display(), config, EGL_RED_SIZE, &configRedSize); EGLint configGreenSize = 0; eglGetConfigAttrib(display(), config, EGL_GREEN_SIZE, &configGreenSize); EGLint configBlueSize = 0; eglGetConfigAttrib(display(), config, EGL_BLUE_SIZE, &configBlueSize); EGLint configAlphaSize = 0; eglGetConfigAttrib(display(), config, EGL_ALPHA_SIZE, &configAlphaSize); eglGetConfigAttrib(display(), config, EGL_CONFIG_ID, &eglValue); int configId = eglValue; // See if EGL provided a valid VisualID: eglGetConfigAttrib(display(), config, EGL_NATIVE_VISUAL_ID, &eglValue); visualId = (VisualID)eglValue; if (visualId) { // EGL has suggested a visual id, so get the rest of the visual info for that id: XVisualInfo visualInfoTemplate; memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); visualInfoTemplate.visualid = visualId; XVisualInfo *chosenVisualInfo; int matchingCount = 0; chosenVisualInfo = XGetVisualInfo(X11->display, VisualIDMask, &visualInfoTemplate, &matchingCount); if (chosenVisualInfo) { int visualRedSize = countBits(chosenVisualInfo->red_mask); int visualGreenSize = countBits(chosenVisualInfo->green_mask); int visualBlueSize = countBits(chosenVisualInfo->blue_mask); int visualAlphaSize = -1; // Need XRender to tell us the alpha channel size #if !defined(QT_NO_XRENDER) if (X11->use_xrender) { // If we have XRender, actually check the visual supplied by EGL is ARGB XRenderPictFormat *format; format = XRenderFindVisualFormat(X11->display, chosenVisualInfo->visual); if (format && (format->type == PictTypeDirect)) visualAlphaSize = countBits(format->direct.alphaMask); } #endif bool visualMatchesConfig = false; if ( visualRedSize == configRedSize && visualGreenSize == configGreenSize && visualBlueSize == configBlueSize ) { // We need XRender to check the alpha channel size of the visual. If we don't have // the alpha size, we don't check it against the EGL config's alpha size. if (visualAlphaSize >= 0) visualMatchesConfig = visualAlphaSize == configAlphaSize; else visualMatchesConfig = true; } if (!visualMatchesConfig) { if (visualAlphaSize >= 0) { qWarning("Warning: EGL suggested using X Visual ID %d (ARGB%d%d%d%d) for EGL config %d (ARGB%d%d%d%d), but this is incompatable", (int)visualId, visualAlphaSize, visualRedSize, visualGreenSize, visualBlueSize, configId, configAlphaSize, configRedSize, configGreenSize, configBlueSize); } else { qWarning("Warning: EGL suggested using X Visual ID %d (RGB%d%d%d) for EGL config %d (RGB%d%d%d), but this is incompatable", (int)visualId, visualRedSize, visualGreenSize, visualBlueSize, configId, configRedSize, configGreenSize, configBlueSize); } visualId = 0; } } else { qWarning("Warning: EGL suggested using X Visual ID %d for EGL config %d, but that isn't a valid ID", (int)visualId, configId); visualId = 0; } XFree(chosenVisualInfo); } #ifdef QT_DEBUG_X11_VISUAL_SELECTION else qDebug("EGL did not suggest a VisualID (EGL_NATIVE_VISUAL_ID was zero) for EGLConfig %d", configId); #endif if (visualId) { #ifdef QT_DEBUG_X11_VISUAL_SELECTION if (configAlphaSize > 0) qDebug("Using ARGB Visual ID %d provided by EGL for config %d", (int)visualId, configId); else qDebug("Using Opaque Visual ID %d provided by EGL for config %d", (int)visualId, configId); #endif return visualId; } // If EGL didn't give us a valid visual ID, try XRender #if !defined(QT_NO_XRENDER) if (!visualId && X11->use_xrender) { XVisualInfo visualInfoTemplate; memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); visualInfoTemplate.c_class = TrueColor; XVisualInfo *matchingVisuals; int matchingCount = 0; matchingVisuals = XGetVisualInfo(X11->display, VisualClassMask, &visualInfoTemplate, &matchingCount); for (int i = 0; i < matchingCount; ++i) { XRenderPictFormat *format; format = XRenderFindVisualFormat(X11->display, matchingVisuals[i].visual); // Check the format for the visual matches the EGL config if ( (countBits(format->direct.redMask) == configRedSize) && (countBits(format->direct.greenMask) == configGreenSize) && (countBits(format->direct.blueMask) == configBlueSize) && (countBits(format->direct.alphaMask) == configAlphaSize) ) { visualId = matchingVisuals[i].visualid; break; } } if (matchingVisuals) XFree(matchingVisuals); } if (visualId) { # ifdef QT_DEBUG_X11_VISUAL_SELECTION if (configAlphaSize > 0) qDebug("Using ARGB Visual ID %d provided by XRender for EGL config %d", (int)visualId, configId); else qDebug("Using Opaque Visual ID %d provided by XRender for EGL config %d", (int)visualId, configId); # endif // QT_DEBUG_X11_VISUAL_SELECTION return visualId; } # ifdef QT_DEBUG_X11_VISUAL_SELECTION else qDebug("Failed to find an XVisual which matches EGL config %d using XRender", configId); # endif // QT_DEBUG_X11_VISUAL_SELECTION #endif //!defined(QT_NO_XRENDER) // Finally, if XRender also failed to find a visual (or isn't present), try to // use XGetVisualInfo and only use the bit depths to match on: if (!visualId) { XVisualInfo visualInfoTemplate; memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); XVisualInfo *matchingVisuals; int matchingCount = 0; visualInfoTemplate.depth = configRedSize + configGreenSize + configBlueSize + configAlphaSize; matchingVisuals = XGetVisualInfo(X11->display, VisualDepthMask, &visualInfoTemplate, &matchingCount); if (!matchingVisuals) { // Try again without taking the alpha channel into account: visualInfoTemplate.depth = configRedSize + configGreenSize + configBlueSize; matchingVisuals = XGetVisualInfo(X11->display, VisualDepthMask, &visualInfoTemplate, &matchingCount); } if (matchingVisuals) { visualId = matchingVisuals[0].visualid; XFree(matchingVisuals); } } if (visualId) { #ifdef QT_DEBUG_X11_VISUAL_SELECTION qDebug("Using Visual ID %d provided by XGetVisualInfo for EGL config %d", (int)visualId, configId); #endif return visualId; } qWarning("Unable to find an X11 visual which matches EGL config %d", configId); return (VisualID)0; } void qt_set_winid_on_widget(QWidget* w, Qt::HANDLE id) { w->create(id); } // NOTE: The X11 version of createSurface will re-create the native drawable if it's visual doesn't // match the one for the passed in EGLConfig EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig config, const QEglProperties *unusedProperties) { Q_UNUSED(unusedProperties); int devType = device->devType(); if (devType == QInternal::Pbuffer) { // TODO return EGL_NO_SURFACE; } QX11PixmapData *x11PixmapData = 0; if (devType == QInternal::Pixmap) { QPixmapData *pmd = static_cast<QPixmap*>(device)->data_ptr().data(); if (pmd->classId() == QPixmapData::X11Class) x11PixmapData = static_cast<QX11PixmapData*>(pmd); else { // TODO: Replace the pixmap's data with a new QX11PixmapData qWarning("WARNING: Creating an EGL surface on a QPixmap is only supported for QX11PixmapData"); return EGL_NO_SURFACE; } } else if ((devType != QInternal::Widget) && (devType != QInternal::Pbuffer)) { qWarning("WARNING: Creating an EGLSurface for device type %d isn't supported", devType); return EGL_NO_SURFACE; } VisualID visualId = QEgl::getCompatibleVisualId(config); EGLint alphaSize; eglGetConfigAttrib(QEgl::display(), config, EGL_ALPHA_SIZE, &alphaSize); if (devType == QInternal::Widget) { QWidget *widget = static_cast<QWidget*>(device); VisualID currentVisualId = 0; if (widget->testAttribute(Qt::WA_WState_Created)) currentVisualId = XVisualIDFromVisual((Visual*)widget->x11Info().visual()); if (currentVisualId != visualId) { // The window is either not created or has the wrong visual. Either way, we need // to create a window with the correct visual and call create() on the widget: bool visible = widget->isVisible(); if (visible) widget->hide(); XVisualInfo visualInfo; visualInfo.visualid = visualId; { XVisualInfo *visualInfoPtr; int matchingCount = 0; visualInfoPtr = XGetVisualInfo(widget->x11Info().display(), VisualIDMask, &visualInfo, &matchingCount); Q_ASSERT(visualInfoPtr); // visualId really should be valid! visualInfo = *visualInfoPtr; XFree(visualInfoPtr); } Window parentWindow = RootWindow(widget->x11Info().display(), widget->x11Info().screen()); if (widget->parentWidget()) parentWindow = widget->parentWidget()->winId(); XSetWindowAttributes windowAttribs; QColormap colmap = QColormap::instance(widget->x11Info().screen()); windowAttribs.background_pixel = colmap.pixel(widget->palette().color(widget->backgroundRole())); windowAttribs.border_pixel = colmap.pixel(Qt::black); unsigned int valueMask = CWBackPixel|CWBorderPixel; if (alphaSize > 0) { windowAttribs.colormap = XCreateColormap(widget->x11Info().display(), parentWindow, visualInfo.visual, AllocNone); valueMask |= CWColormap; } Window window = XCreateWindow(widget->x11Info().display(), parentWindow, widget->x(), widget->y(), widget->width(), widget->height(), 0, visualInfo.depth, InputOutput, visualInfo.visual, valueMask, &windowAttribs); // This is a nasty hack to get round the fact that we can't be a friend of QWidget: qt_set_winid_on_widget(widget, window); if (visible) widget->show(); } // At this point, the widget's window should be created and have the correct visual. Now we // just need to create the EGL surface for it: return eglCreateWindowSurface(QEgl::display(), config, (EGLNativeWindowType)widget->winId(), 0); } if (x11PixmapData) { // X11 Pixmaps are only created with a depth, so that's all we need to check EGLint configDepth; eglGetConfigAttrib(QEgl::display(), config, EGL_BUFFER_SIZE , &configDepth); if (x11PixmapData->depth() != configDepth) { // The bit depths are wrong which means the EGLConfig isn't compatable with // this pixmap. So we need to replace the pixmap's existing data with a new // one which is created with the correct depth: #ifndef QT_NO_XRENDER if (configDepth == 32) { qWarning("Warning: EGLConfig's depth (32) != pixmap's depth (%d), converting to ARGB32", x11PixmapData->depth()); x11PixmapData->convertToARGB32(true); } else #endif { qWarning("Warning: EGLConfig's depth (%d) != pixmap's depth (%d)", configDepth, x11PixmapData->depth()); } } QEglProperties surfaceAttribs; // If the pixmap can't be bound to a texture, it's pretty useless surfaceAttribs.setValue(EGL_TEXTURE_TARGET, EGL_TEXTURE_2D); if (alphaSize > 0) surfaceAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA); else surfaceAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGB); EGLSurface surf = eglCreatePixmapSurface(QEgl::display(), config, (EGLNativePixmapType) x11PixmapData->handle(), surfaceAttribs.properties()); x11PixmapData->gl_surface = (void*)surf; QImagePixmapCleanupHooks::enableCleanupHooks(x11PixmapData); return surf; } return EGL_NO_SURFACE; } QT_END_NAMESPACE
#ifndef __STAN__MATH__SPECIAL_FUNCTIONS_HPP__ #define __STAN__MATH__SPECIAL_FUNCTIONS_HPP__ #include <stdexcept> #include <boost/math/special_functions/gamma.hpp> #include <boost/math/special_functions/beta.hpp> #include <boost/math/tools/promotion.hpp> #include <boost/throw_exception.hpp> #include <stan/math/constants.hpp> namespace stan { namespace math { // C99 /** * Return the exponent base 2 of the specified argument (C99). * * The exponent base 2 function is defined by * * <code>exp2(y) = pow(2.0,y)</code>. * * @param y Value. * @return Exponent base 2 of value. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type exp2(T y) { using std::pow; return pow(2.0,y); } /** * The positive difference function (C99). * * The function is defined by * * <code>fdim(a,b) = (a > b) ? (a - b) : 0.0</code>. * * @param a First value. * @param b Second value. * @return Returns min(a - b, 0.0). */ template <typename T1, typename T2> inline typename boost::math::tools::promote_args<T1, T2>::type fdim(T1 a, T2 b) { return (a > b) ? (a - b) : 0.0; } /** * The fused multiply-add operation (C99). * * The function is defined by * * <code>fma(a,b,c) = (a * b) + c</code>. * * @param a First value. * @param b Second value. * @param c Third value. * @return Product of the first two values plust the third. */ template <typename T1, typename T2, typename T3> inline typename boost::math::tools::promote_args<T1,T2,T3>::type fma(T1 a, T2 b, T3 c) { return a * b + c; } /** * Returns the base 2 logarithm of the argument (C99). * * The function is defined by: * * <code>log2(a) = log(a) / std::log(2.0)</code>. * * @param a Value. * @return Base 2 logarithm of the value. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type log2(T a) { using std::log; const static double LOG2 = std::log(2.0); return log(a) / LOG2; } // OTHER BASIC FUNCTIONS /** * The integer step, or Heaviside, function. * * @param y Value to test. * @return 1 if value is greater than 0 and 0 otherwise * @tparam T Scalar argument type. */ template <typename T> unsigned int int_step(T y) { return y > 0; } /** * The step, or Heaviside, function. * * The function is defined by * * <code>step(y) = (y < 0.0) ? 0 : 1</code>. * * @param y Scalar argument. * * @return 1 if the specified argument is greater than or equal to * 0.0, and 0 otherwise. */ template <typename T> inline int step(T y) { return y < 0.0 ? 0 : 1; } // PROBABILITY-RELATED FUNCTIONS /** * Return the log of the beta function applied to the specified * arguments. * * The beta function is defined for \f$a > 0\f$ and \f$b > 0\f$ by * * \f$\mbox{B}(a,b) = \frac{\Gamma(a) \Gamma(b)}{\Gamma(a+b)}\f$. * * This function returns its log, * * \f$\log \mbox{B}(a,b) = \log \Gamma(a) + \log \Gamma(b) - \log \Gamma(a+b)\f$. * * See boost::math::lgamma() for the double-based and stan::agrad for the * variable-based log Gamma function. * * @param a First value * @param b Second value * @return Log of the beta function applied to the two values. * @tparam T1 Type of first value. * @tparam T2 Type of second value. */ template <typename T1, typename T2> inline typename boost::math::tools::promote_args<T1,T2>::type lbeta(T1 a, T2 b) { return lgamma(a) + lgamma(b) - lgamma(a + b); } /** * Return the log of the binomial coefficient for the specified * arguments. * * The binomial coefficient, \f${N \choose n}\f$, read "N choose n", is * defined for \f$0 \leq n \leq N\f$ by * * \f${N \choose n} = \frac{N!}{n! (N-n)!}\f$. * * This function uses Gamma functions to define the log * and generalize the arguments to continuous N and n. * * \f$ \log {N \choose n} = \log \ \Gamma(N+1) - \log \Gamma(n+1) - \log \Gamma(N-n+1)\f$. * * @param N total number of objects. * @param n number of objects chosen. * @return log (N choose n). */ template <typename T_N, typename T_n> inline typename boost::math::tools::promote_args<T_N, T_n>::type binomial_coefficient_log(T_N N, T_n n) { return lgamma(N + 1.0) - lgamma(n + 1.0) - lgamma(N - n + 1.0); } /** * Returns the inverse logit function applied to the argument. * * The inverse logit function is defined by * * \f$\mbox{logit}^{-1}(x) = \frac{1}{1 + \exp(-x)}\f$. * * This function can be used to implement the inverse link function * for logistic regression. * * The inverse to this function is <code>stan::math::logit</code>. * * @param a Argument. * @return Inverse logit of argument. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type inv_logit(T a) { using std::exp; return 1.0 / (1.0 + exp(-a)); } /** * Returns the logit function applied to the * argument. * * The logit function is defined as for \f$x \in [0,1]\f$ by * returning the log odds of \f$x\f$ treated as a probability, * * \f$\mbox{logit}(x) = \log \left( \frac{x}{1 - x} \right)\f$. * * The inverse to this function is <code>stan::math::inv_logit</code>. * * @param a Argument. * @return Logit of the argument. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type logit(T a) { using std::log; return log(a / (1.0 - a)); } /** * The unit normal cumulative distribution function. * * The return value for a specified input is the probability that * a random unit normal variate is less than or equal to the * specified value, defined by * * \f$\Phi(x) = \int_{-\infty}^x \mbox{\sf Norm}(x|0,1) \ dx\f$ * * This function can be used to implement the inverse link function * for probit regression. * * @param x Argument. * @return Probability random sample is less than or equal to argument. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type Phi(T x) { static const double INV_SQRT_TWO = 1.0 / std::sqrt(2.0); return 0.5 * (1.0 + boost::math::erf(INV_SQRT_TWO * x)); } /** * The inverse complementary log-log function. * * The function is defined by * * <code>inv_cloglog(x) = -exp(-exp(x))</code>. * * This function can be used to implement the inverse link * function for complenentary-log-log regression. * * @param x Argument. * @return Inverse complementary log-log of the argument. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type inv_cloglog(T x) { using std::exp; return exp(-exp(x)); } /** * Returns the log loss function for binary classification * with specified reference and response values. * * The log loss function for prediction \f$\hat{y} \in [0, 1]\f$ * given outcome \f$y \in \{ 0, 1 \}\f$ is * * \f$\mbox{logloss}(1,\hat{y}) = -\log \hat{y} \f$, and * * \f$\mbox{logloss}(0,\hat{y}) = -\log (1 - \hat{y}) \f$. * * @param y Reference value in { 0 , 1 }. * @param y_hat Response value in [0,1]. * @return Log loss for response given reference value. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type binary_log_loss(int y, T y_hat) { using std::log; return -log(y ? y_hat : (1.0 - y_hat)); } // hide helper for now; could use Eigen here namespace { template <typename Vector, typename Scalar> Scalar maximum(const Vector& x) { if(x.size() == 0) BOOST_THROW_EXCEPTION(std::invalid_argument ("x must have at least one element")); Scalar max_x(x[0]); for (typename Vector::size_type i = 1; i < x.size(); ++i) if (x[i] < max_x) max_x = x[i]; return max_x; } } /** * Write the values of the softmax transformed first argument * into the second argument. Values in the first argument * are unbounded and values in the output form a simplex. * * The softmax transformed generalizes the inverse logistic * function by transforming a vector \f$x\f$ of length \f$K\f$ as * * \f$\mbox{softmax}(x)[i] = \frac{\exp(x[i])}{\sum_{k=1}^{K} \exp(x[k])}\f$. * * By construction, the result is a simplex, which means the values * are all non-negative and sum to 1.0, * * \f$ \sum_{k=1}^{K} \mbox{softmax}(x)[k] = 1\f$. * * The type <code>Vector</code> is for a vector with values of * type <code>Scalar</code>. Vectors <code>x</code> must support * <code>x.size()</code> and return assignable references of type * <code>Scalar</code> through <code>x[int]</code>. Variables * <code>a</code> of type <code>Scalar</code> need to support * division (in context <code>x[i] /= a</code>) and exponentiation * (<code>exp(a)</code>). Conforming examples include * * <code>Vector = std::vector&lt;double&gt;</code> and * <code>Scalar = double</code>, * * <code>Vector = std::vector&lt;stan::agrad::var&gt;</code> and * <code>Scalar = stan::agrad::var</code>, * * <code>Vector = Eigen::Matrix<double,Eigen::Dynamic,1>&lt;double&gt;</code> and * <code>Scalar = double</code>, * * and so on. * * The function <code>stan::math::inverse_softmax</code> provides an * inverse of this operation up to an additive constant. Specifically, * if <code>x</code> is a simplex argument, then * * <code>softmax(inv_softmax(x)) = x</code>. * * If <code>y</code> is an arbitrary vector, then we only have * identification up to an additive constant <code>c</code>, as in * * <code>inv_softmax(softmax(y)) = y + c * I</code>. * * @param x Input vector of unbounded parameters. * @param simplex Output vector of simplex values. * @throw std::invalid_argument if size of the input and output vectors differ. */ template <typename Vector, typename Scalar> void softmax(const Vector& x, Vector& simplex) { using std::exp; if(x.size() != simplex.size()) BOOST_THROW_EXCEPTION(std::invalid_argument ("x.size() != simplex.size()")); Scalar sum(0.0); Scalar max_x = maximum<Vector,Scalar>(x); for (typename Vector::size_type i = 0; i < x.size(); ++i) sum += (simplex[i] = exp(x[i]-max_x)); for (typename Vector::size_type i = 0; i < x.size(); ++i) simplex[i] /= sum; } /** * Writes the inverse softmax of the simplex argument into the second * argument. See <code>stan::math::softmax</code> for the inverse * function and a definition of the relation. * * The inverse softmax function is defined by * * \f$\mbox{inverse\_softmax}(x)[i] = \log x[i]\f$. * * This function defines the inverse of <code>stan::math::softmax</code> * up to a scaling factor. * * Because of the definition, values of 0.0 in the simplex * are converted to negative infinity, and values of 1.0 * are converted to 0.0. * * There is no check that the input vector is a valid simplex vector. * * @param simplex Simplex vector input. * @param y Vector into which the inverse softmax is written. * @throw std::invalid_argument if size of the input and output vectors differ. */ template <typename Vector> void inverse_softmax(const Vector& simplex, Vector& y) { using std::log; if(simplex.size() != y.size()) BOOST_THROW_EXCEPTION(std::invalid_argument ("simplex.size() != y.size()")); for (size_t i = 0; i < simplex.size(); ++i) y[i] = log(simplex[i]); } /** * Return the natural logarithm of one plus the specified value. * * The main use of this function is to cut down on intermediate * values during algorithmic differentiation. * * @param x Specified value. * @return Natural log of one plus <code>x</code>. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type log1p(T x) { using std::log; if (x < -1.0) BOOST_THROW_EXCEPTION(std::domain_error ("x can not be less than -1")); if (x > 1e-9 || x < -1e-9) return log(1.0 + x); // direct, if distant from 1 else if (x > 1e-16 || x < -1e-16) return x - 0.5 * x * x; // 2nd order Taylor, if close to 1 else return x; // 1st order Taylor, if very close to 1 } /** * Return the natural logarithm of one minus the specified value. * * The main use of this function is to cut down on intermediate * values during algorithmic differentiation. * * @param x Specified value. * @return Natural log of one minus <code>x</code>. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type log1m(T x) { return log1p(-x); } namespace { const double LOG_PI_OVER_FOUR = std::log(boost::math::constants::pi<double>()) / 4.0; } /** * Return the natural logarithm of the multivariate gamma function * with the speciifed dimensions and argument. * * <p>The multivariate gamma function \f$\Gamma_k(x)\f$ for * dimensionality \f$k\f$ and argument \f$x\f$ is defined by * * <p>\f$\Gamma_k(x) = \pi^{k(k-1)/4} \, \prod_{j=1}^k \Gamma(x + (1 - j)/2)\f$, * * where \f$\Gamma()\f$ is the gamma function. * * @param k Number of dimensions. * @param x Function argument. * @return Natural log of the multivariate gamma function. * @tparam T Type of scalar. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type lmgamma(unsigned int k, T x) { typename boost::math::tools::promote_args<T>::type result = k * (k - 1) * LOG_PI_OVER_FOUR; for (unsigned int j = 1; j <= k; ++j) result += lgamma(x + (1.0 - j) / 2.0); return result; } /** * Return the second argument if the first argument is true * and otherwise return the second argument. * * <p>This is just a convenience method to provide a function * with the same behavior as the built-in ternary operator. * In general, this function behaves as if defined by * * <p><code>if_else(c,y1,y0) = c ? y1 : y0</code>. * * @param c Boolean condition value. * @param y_true Value to return if condition is true. * @param y_false Value to return if condition is false. */ inline double if_else(bool c, double y_true, double y_false) { return c ? y_true : y_false; } /** * Return the square of the specified argument. * * <p>\f$\mbox{square}(x) = x^2\f$. * * <p>The implementation of <code>square(x)</code> is just * <code>x * x</code>. Given this, this method is mainly useful * in cases where <code>x</code> is not a simple primitive type, * particularly when it is an auto-dif type. * * @param x Input to square. * @return Square of input. * @tparam T Type of scalar. */ template <typename T> inline T square(T x) { return x * x; } template <typename T_a, typename T_b> inline typename boost::math::tools::promote_args<T_a,T_b>::type multiply_log(T_a a, T_b b) { using std::log; if (b == 0.0 && a == 0.0) return 0.0; return a * log(b); } /** * Calculates the log of 1 plus the exponential of the specified * value without overflow. * * This function is related to other special functions by: * * <code>log_1p_exp(x) </code> * * <code> = log1p(exp(a))</code> * * <code> = log(1 + exp(x))</code> * <code> = log_sum_exp(0,x)</code>. */ inline double log1p_exp(const double& a) { using std::exp; // like log_sum_exp below with b=0.0 if (a > 0.0) return a + log1p(exp(-a)); return log1p(exp(a)); } /** * Calculates the log sum of exponetials without overflow. * * \f$\log (\exp(a) + \exp(b)) = m + \log(\exp(a-m) + \exp(b-m))\f$, * * where \f$m = max(a,b)\f$. * * @param a the first variable * @param b the second variable */ inline double log_sum_exp(const double& a, const double& b) { using std::exp; if (a > b) return a + log1p(exp(b - a)); return b + log1p(exp(a - b)); } /** * The normalized incomplete beta function of a, b, and x. * * Used to compute the cumulative density function for the beta * distribution. * * @param a Shape parameter. * @param b Shape parameter. * @param x Random variate. * * @return The normalized incomplete beta function. */ inline double ibeta(const double& a, const double& b, const double& x) { return boost::math::ibeta(a, b, x); } /** * Return the log of the sum of the exponentiated values of the specified * sequence of values. * * The function is defined as follows to prevent overflow in exponential * calculations. * * \f$\log \sum_{n=1}^N \exp(x_n) = \max(x) + \log \sum_{n=1}^N \exp(x_n - \max(x))\f$. * * @param x array of specified values */ static double log_sum_exp(const std::vector<double>& x) { using std::numeric_limits; using std::log; using std::exp; double max = -numeric_limits<double>::infinity(); for (size_t ii = 0; ii < x.size(); ii++) if (x[ii] > max) max = x[ii]; double sum = 0.0; for (size_t ii = 0; ii < x.size(); ii++) if (x[ii] != -numeric_limits<double>::infinity()) sum += exp(x[ii] - max); return max + log(sum); } // CONSTANTS /** * Return the value of pi. * * @return Pi. */ inline double pi() { return boost::math::constants::pi<double>(); } /** * Return the base of the natural logarithm. * * @return Base of natural logarithm. */ inline double e() { return E; } /** * Return the square root of two. * * @return Square root of two. */ inline double sqrt2() { return SQRT_2; } /** * Return natural logarithm of two. * * @return Natural logarithm of two. */ inline double log2() { return LOG_2; } /** * Return natural logarithm of ten. * * @return Natural logarithm of ten. */ inline double log10() { return LOG_10; } /** * Return positive infinity. * * @return Positive infinity. */ inline double infinity() { return INFTY; } /** * Return negative infinity. * * @return Negative infinity. */ inline double negative_infinity() { return NEGATIVE_INFTY; } /** * Return (quiet) not-a-number. * * @return Quiet not-a-number. */ inline double nan() { return NOT_A_NUMBER; } /** * Return minimum positive number representable. * * @return Minimum positive number. */ inline double epsilon() { return EPSILON; } /** * Return maximum negative number (i.e., negative * number with smallest absolute value). * * @return Maximum negative number. */ inline double negative_epsilon() { return NEGATIVE_EPSILON; } } } #endif math/special_functions: added Policy placeholder for exp2 #ifndef __STAN__MATH__SPECIAL_FUNCTIONS_HPP__ #define __STAN__MATH__SPECIAL_FUNCTIONS_HPP__ #include <stdexcept> #include <boost/math/special_functions/gamma.hpp> #include <boost/math/special_functions/beta.hpp> #include <boost/math/tools/promotion.hpp> #include <boost/throw_exception.hpp> #include <stan/math/constants.hpp> #include <stan/math/error_handling.hpp> namespace stan { namespace math { // C99 /** * Return the exponent base 2 of the specified argument (C99). * * The exponent base 2 function is defined by * * <code>exp2(y) = pow(2.0,y)</code>. * * @param y Value. * @return Exponent base 2 of value. */ template <typename T, class Policy> inline typename boost::math::tools::promote_args<T>::type exp2(T y, const Policy&) { using std::pow; return pow(2.0,y); } template <typename T> inline typename boost::math::tools::promote_args<T>::type exp2(T y) { return exp2(y, stan::math::default_policy()); } /** * The positive difference function (C99). * * The function is defined by * * <code>fdim(a,b) = (a > b) ? (a - b) : 0.0</code>. * * @param a First value. * @param b Second value. * @return Returns min(a - b, 0.0). */ template <typename T1, typename T2> inline typename boost::math::tools::promote_args<T1, T2>::type fdim(T1 a, T2 b) { return (a > b) ? (a - b) : 0.0; } /** * The fused multiply-add operation (C99). * * The function is defined by * * <code>fma(a,b,c) = (a * b) + c</code>. * * @param a First value. * @param b Second value. * @param c Third value. * @return Product of the first two values plust the third. */ template <typename T1, typename T2, typename T3> inline typename boost::math::tools::promote_args<T1,T2,T3>::type fma(T1 a, T2 b, T3 c) { return a * b + c; } /** * Returns the base 2 logarithm of the argument (C99). * * The function is defined by: * * <code>log2(a) = log(a) / std::log(2.0)</code>. * * @param a Value. * @return Base 2 logarithm of the value. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type log2(T a) { using std::log; const static double LOG2 = std::log(2.0); return log(a) / LOG2; } // OTHER BASIC FUNCTIONS /** * The integer step, or Heaviside, function. * * @param y Value to test. * @return 1 if value is greater than 0 and 0 otherwise * @tparam T Scalar argument type. */ template <typename T> unsigned int int_step(T y) { return y > 0; } /** * The step, or Heaviside, function. * * The function is defined by * * <code>step(y) = (y < 0.0) ? 0 : 1</code>. * * @param y Scalar argument. * * @return 1 if the specified argument is greater than or equal to * 0.0, and 0 otherwise. */ template <typename T> inline int step(T y) { return y < 0.0 ? 0 : 1; } // PROBABILITY-RELATED FUNCTIONS /** * Return the log of the beta function applied to the specified * arguments. * * The beta function is defined for \f$a > 0\f$ and \f$b > 0\f$ by * * \f$\mbox{B}(a,b) = \frac{\Gamma(a) \Gamma(b)}{\Gamma(a+b)}\f$. * * This function returns its log, * * \f$\log \mbox{B}(a,b) = \log \Gamma(a) + \log \Gamma(b) - \log \Gamma(a+b)\f$. * * See boost::math::lgamma() for the double-based and stan::agrad for the * variable-based log Gamma function. * * @param a First value * @param b Second value * @return Log of the beta function applied to the two values. * @tparam T1 Type of first value. * @tparam T2 Type of second value. */ template <typename T1, typename T2> inline typename boost::math::tools::promote_args<T1,T2>::type lbeta(T1 a, T2 b) { return lgamma(a) + lgamma(b) - lgamma(a + b); } /** * Return the log of the binomial coefficient for the specified * arguments. * * The binomial coefficient, \f${N \choose n}\f$, read "N choose n", is * defined for \f$0 \leq n \leq N\f$ by * * \f${N \choose n} = \frac{N!}{n! (N-n)!}\f$. * * This function uses Gamma functions to define the log * and generalize the arguments to continuous N and n. * * \f$ \log {N \choose n} = \log \ \Gamma(N+1) - \log \Gamma(n+1) - \log \Gamma(N-n+1)\f$. * * @param N total number of objects. * @param n number of objects chosen. * @return log (N choose n). */ template <typename T_N, typename T_n> inline typename boost::math::tools::promote_args<T_N, T_n>::type binomial_coefficient_log(T_N N, T_n n) { return lgamma(N + 1.0) - lgamma(n + 1.0) - lgamma(N - n + 1.0); } /** * Returns the inverse logit function applied to the argument. * * The inverse logit function is defined by * * \f$\mbox{logit}^{-1}(x) = \frac{1}{1 + \exp(-x)}\f$. * * This function can be used to implement the inverse link function * for logistic regression. * * The inverse to this function is <code>stan::math::logit</code>. * * @param a Argument. * @return Inverse logit of argument. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type inv_logit(T a) { using std::exp; return 1.0 / (1.0 + exp(-a)); } /** * Returns the logit function applied to the * argument. * * The logit function is defined as for \f$x \in [0,1]\f$ by * returning the log odds of \f$x\f$ treated as a probability, * * \f$\mbox{logit}(x) = \log \left( \frac{x}{1 - x} \right)\f$. * * The inverse to this function is <code>stan::math::inv_logit</code>. * * @param a Argument. * @return Logit of the argument. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type logit(T a) { using std::log; return log(a / (1.0 - a)); } /** * The unit normal cumulative distribution function. * * The return value for a specified input is the probability that * a random unit normal variate is less than or equal to the * specified value, defined by * * \f$\Phi(x) = \int_{-\infty}^x \mbox{\sf Norm}(x|0,1) \ dx\f$ * * This function can be used to implement the inverse link function * for probit regression. * * @param x Argument. * @return Probability random sample is less than or equal to argument. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type Phi(T x) { static const double INV_SQRT_TWO = 1.0 / std::sqrt(2.0); return 0.5 * (1.0 + boost::math::erf(INV_SQRT_TWO * x)); } /** * The inverse complementary log-log function. * * The function is defined by * * <code>inv_cloglog(x) = -exp(-exp(x))</code>. * * This function can be used to implement the inverse link * function for complenentary-log-log regression. * * @param x Argument. * @return Inverse complementary log-log of the argument. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type inv_cloglog(T x) { using std::exp; return exp(-exp(x)); } /** * Returns the log loss function for binary classification * with specified reference and response values. * * The log loss function for prediction \f$\hat{y} \in [0, 1]\f$ * given outcome \f$y \in \{ 0, 1 \}\f$ is * * \f$\mbox{logloss}(1,\hat{y}) = -\log \hat{y} \f$, and * * \f$\mbox{logloss}(0,\hat{y}) = -\log (1 - \hat{y}) \f$. * * @param y Reference value in { 0 , 1 }. * @param y_hat Response value in [0,1]. * @return Log loss for response given reference value. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type binary_log_loss(int y, T y_hat) { using std::log; return -log(y ? y_hat : (1.0 - y_hat)); } // hide helper for now; could use Eigen here namespace { template <typename Vector, typename Scalar> Scalar maximum(const Vector& x) { if(x.size() == 0) BOOST_THROW_EXCEPTION(std::invalid_argument ("x must have at least one element")); Scalar max_x(x[0]); for (typename Vector::size_type i = 1; i < x.size(); ++i) if (x[i] < max_x) max_x = x[i]; return max_x; } } /** * Write the values of the softmax transformed first argument * into the second argument. Values in the first argument * are unbounded and values in the output form a simplex. * * The softmax transformed generalizes the inverse logistic * function by transforming a vector \f$x\f$ of length \f$K\f$ as * * \f$\mbox{softmax}(x)[i] = \frac{\exp(x[i])}{\sum_{k=1}^{K} \exp(x[k])}\f$. * * By construction, the result is a simplex, which means the values * are all non-negative and sum to 1.0, * * \f$ \sum_{k=1}^{K} \mbox{softmax}(x)[k] = 1\f$. * * The type <code>Vector</code> is for a vector with values of * type <code>Scalar</code>. Vectors <code>x</code> must support * <code>x.size()</code> and return assignable references of type * <code>Scalar</code> through <code>x[int]</code>. Variables * <code>a</code> of type <code>Scalar</code> need to support * division (in context <code>x[i] /= a</code>) and exponentiation * (<code>exp(a)</code>). Conforming examples include * * <code>Vector = std::vector&lt;double&gt;</code> and * <code>Scalar = double</code>, * * <code>Vector = std::vector&lt;stan::agrad::var&gt;</code> and * <code>Scalar = stan::agrad::var</code>, * * <code>Vector = Eigen::Matrix<double,Eigen::Dynamic,1>&lt;double&gt;</code> and * <code>Scalar = double</code>, * * and so on. * * The function <code>stan::math::inverse_softmax</code> provides an * inverse of this operation up to an additive constant. Specifically, * if <code>x</code> is a simplex argument, then * * <code>softmax(inv_softmax(x)) = x</code>. * * If <code>y</code> is an arbitrary vector, then we only have * identification up to an additive constant <code>c</code>, as in * * <code>inv_softmax(softmax(y)) = y + c * I</code>. * * @param x Input vector of unbounded parameters. * @param simplex Output vector of simplex values. * @throw std::invalid_argument if size of the input and output vectors differ. */ template <typename Vector, typename Scalar> void softmax(const Vector& x, Vector& simplex) { using std::exp; if(x.size() != simplex.size()) BOOST_THROW_EXCEPTION(std::invalid_argument ("x.size() != simplex.size()")); Scalar sum(0.0); Scalar max_x = maximum<Vector,Scalar>(x); for (typename Vector::size_type i = 0; i < x.size(); ++i) sum += (simplex[i] = exp(x[i]-max_x)); for (typename Vector::size_type i = 0; i < x.size(); ++i) simplex[i] /= sum; } /** * Writes the inverse softmax of the simplex argument into the second * argument. See <code>stan::math::softmax</code> for the inverse * function and a definition of the relation. * * The inverse softmax function is defined by * * \f$\mbox{inverse\_softmax}(x)[i] = \log x[i]\f$. * * This function defines the inverse of <code>stan::math::softmax</code> * up to a scaling factor. * * Because of the definition, values of 0.0 in the simplex * are converted to negative infinity, and values of 1.0 * are converted to 0.0. * * There is no check that the input vector is a valid simplex vector. * * @param simplex Simplex vector input. * @param y Vector into which the inverse softmax is written. * @throw std::invalid_argument if size of the input and output vectors differ. */ template <typename Vector> void inverse_softmax(const Vector& simplex, Vector& y) { using std::log; if(simplex.size() != y.size()) BOOST_THROW_EXCEPTION(std::invalid_argument ("simplex.size() != y.size()")); for (size_t i = 0; i < simplex.size(); ++i) y[i] = log(simplex[i]); } /** * Return the natural logarithm of one plus the specified value. * * The main use of this function is to cut down on intermediate * values during algorithmic differentiation. * * @param x Specified value. * @return Natural log of one plus <code>x</code>. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type log1p(T x) { using std::log; if (x < -1.0) BOOST_THROW_EXCEPTION(std::domain_error ("x can not be less than -1")); if (x > 1e-9 || x < -1e-9) return log(1.0 + x); // direct, if distant from 1 else if (x > 1e-16 || x < -1e-16) return x - 0.5 * x * x; // 2nd order Taylor, if close to 1 else return x; // 1st order Taylor, if very close to 1 } /** * Return the natural logarithm of one minus the specified value. * * The main use of this function is to cut down on intermediate * values during algorithmic differentiation. * * @param x Specified value. * @return Natural log of one minus <code>x</code>. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type log1m(T x) { return log1p(-x); } namespace { const double LOG_PI_OVER_FOUR = std::log(boost::math::constants::pi<double>()) / 4.0; } /** * Return the natural logarithm of the multivariate gamma function * with the speciifed dimensions and argument. * * <p>The multivariate gamma function \f$\Gamma_k(x)\f$ for * dimensionality \f$k\f$ and argument \f$x\f$ is defined by * * <p>\f$\Gamma_k(x) = \pi^{k(k-1)/4} \, \prod_{j=1}^k \Gamma(x + (1 - j)/2)\f$, * * where \f$\Gamma()\f$ is the gamma function. * * @param k Number of dimensions. * @param x Function argument. * @return Natural log of the multivariate gamma function. * @tparam T Type of scalar. */ template <typename T> inline typename boost::math::tools::promote_args<T>::type lmgamma(unsigned int k, T x) { typename boost::math::tools::promote_args<T>::type result = k * (k - 1) * LOG_PI_OVER_FOUR; for (unsigned int j = 1; j <= k; ++j) result += lgamma(x + (1.0 - j) / 2.0); return result; } /** * Return the second argument if the first argument is true * and otherwise return the second argument. * * <p>This is just a convenience method to provide a function * with the same behavior as the built-in ternary operator. * In general, this function behaves as if defined by * * <p><code>if_else(c,y1,y0) = c ? y1 : y0</code>. * * @param c Boolean condition value. * @param y_true Value to return if condition is true. * @param y_false Value to return if condition is false. */ inline double if_else(bool c, double y_true, double y_false) { return c ? y_true : y_false; } /** * Return the square of the specified argument. * * <p>\f$\mbox{square}(x) = x^2\f$. * * <p>The implementation of <code>square(x)</code> is just * <code>x * x</code>. Given this, this method is mainly useful * in cases where <code>x</code> is not a simple primitive type, * particularly when it is an auto-dif type. * * @param x Input to square. * @return Square of input. * @tparam T Type of scalar. */ template <typename T> inline T square(T x) { return x * x; } template <typename T_a, typename T_b> inline typename boost::math::tools::promote_args<T_a,T_b>::type multiply_log(T_a a, T_b b) { using std::log; if (b == 0.0 && a == 0.0) return 0.0; return a * log(b); } /** * Calculates the log of 1 plus the exponential of the specified * value without overflow. * * This function is related to other special functions by: * * <code>log_1p_exp(x) </code> * * <code> = log1p(exp(a))</code> * * <code> = log(1 + exp(x))</code> * <code> = log_sum_exp(0,x)</code>. */ inline double log1p_exp(const double& a) { using std::exp; // like log_sum_exp below with b=0.0 if (a > 0.0) return a + log1p(exp(-a)); return log1p(exp(a)); } /** * Calculates the log sum of exponetials without overflow. * * \f$\log (\exp(a) + \exp(b)) = m + \log(\exp(a-m) + \exp(b-m))\f$, * * where \f$m = max(a,b)\f$. * * @param a the first variable * @param b the second variable */ inline double log_sum_exp(const double& a, const double& b) { using std::exp; if (a > b) return a + log1p(exp(b - a)); return b + log1p(exp(a - b)); } /** * The normalized incomplete beta function of a, b, and x. * * Used to compute the cumulative density function for the beta * distribution. * * @param a Shape parameter. * @param b Shape parameter. * @param x Random variate. * * @return The normalized incomplete beta function. */ inline double ibeta(const double& a, const double& b, const double& x) { return boost::math::ibeta(a, b, x); } /** * Return the log of the sum of the exponentiated values of the specified * sequence of values. * * The function is defined as follows to prevent overflow in exponential * calculations. * * \f$\log \sum_{n=1}^N \exp(x_n) = \max(x) + \log \sum_{n=1}^N \exp(x_n - \max(x))\f$. * * @param x array of specified values */ static double log_sum_exp(const std::vector<double>& x) { using std::numeric_limits; using std::log; using std::exp; double max = -numeric_limits<double>::infinity(); for (size_t ii = 0; ii < x.size(); ii++) if (x[ii] > max) max = x[ii]; double sum = 0.0; for (size_t ii = 0; ii < x.size(); ii++) if (x[ii] != -numeric_limits<double>::infinity()) sum += exp(x[ii] - max); return max + log(sum); } // CONSTANTS /** * Return the value of pi. * * @return Pi. */ inline double pi() { return boost::math::constants::pi<double>(); } /** * Return the base of the natural logarithm. * * @return Base of natural logarithm. */ inline double e() { return E; } /** * Return the square root of two. * * @return Square root of two. */ inline double sqrt2() { return SQRT_2; } /** * Return natural logarithm of two. * * @return Natural logarithm of two. */ inline double log2() { return LOG_2; } /** * Return natural logarithm of ten. * * @return Natural logarithm of ten. */ inline double log10() { return LOG_10; } /** * Return positive infinity. * * @return Positive infinity. */ inline double infinity() { return INFTY; } /** * Return negative infinity. * * @return Negative infinity. */ inline double negative_infinity() { return NEGATIVE_INFTY; } /** * Return (quiet) not-a-number. * * @return Quiet not-a-number. */ inline double nan() { return NOT_A_NUMBER; } /** * Return minimum positive number representable. * * @return Minimum positive number. */ inline double epsilon() { return EPSILON; } /** * Return maximum negative number (i.e., negative * number with smallest absolute value). * * @return Maximum negative number. */ inline double negative_epsilon() { return NEGATIVE_EPSILON; } } } #endif